2021-10-08 10:07:03 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
2024-05-31 14:45:13 +08:00
|
|
|
////
|
2021-10-08 10:07:03 +08:00
|
|
|
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
|
|
|
|
// See https://llvm.org/LICENSE.txt for license information.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
|
|
|
// Also available under a BSD-style license. See LICENSE.
|
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
#include "torch-mlir/Conversion/TorchToTosa/TorchToTosa.h"
|
|
|
|
#include "../PassDetail.h"
|
2022-10-05 21:28:06 +08:00
|
|
|
#include "mlir/Dialect/Arith/IR/Arith.h"
|
2021-12-16 03:01:01 +08:00
|
|
|
#include "mlir/Dialect/Tensor/IR/Tensor.h"
|
2021-10-08 10:07:03 +08:00
|
|
|
#include "mlir/Dialect/Tosa/IR/TosaOps.h"
|
|
|
|
#include "mlir/IR/Matchers.h"
|
|
|
|
#include "mlir/Transforms/DialectConversion.h"
|
2024-02-28 05:40:55 +08:00
|
|
|
#include "torch-mlir/Conversion/TorchToTosa/TosaLegalizeCommon.h"
|
|
|
|
#include "torch-mlir/Conversion/TorchToTosa/TosaLegalizeUtils.h"
|
|
|
|
#include "torch-mlir/Conversion/Utils/Utils.h"
|
2023-07-25 16:11:40 +08:00
|
|
|
#include "torch-mlir/Dialect/Torch/IR/TorchDialect.h"
|
2021-10-08 10:07:03 +08:00
|
|
|
#include "torch-mlir/Dialect/Torch/IR/TorchOps.h"
|
2022-11-29 20:33:31 +08:00
|
|
|
#include "torch-mlir/Dialect/Torch/IR/TorchTypes.h"
|
2022-02-01 05:34:09 +08:00
|
|
|
#include "torch-mlir/Dialect/Torch/Utils/Utils.h"
|
2021-10-08 10:07:03 +08:00
|
|
|
#include "torch-mlir/Dialect/TorchConversion/Transforms/BackendTypeConversion.h"
|
2024-09-06 02:27:29 +08:00
|
|
|
#include "llvm/ADT/TypeSwitch.h"
|
2024-06-27 00:10:14 +08:00
|
|
|
#include <numeric>
|
2024-02-28 05:40:55 +08:00
|
|
|
#include <optional>
|
2021-10-08 10:07:03 +08:00
|
|
|
|
|
|
|
using namespace mlir;
|
|
|
|
using namespace mlir::torch;
|
|
|
|
using namespace mlir::torch::Torch;
|
|
|
|
|
|
|
|
namespace {
|
2021-11-12 08:15:58 +08:00
|
|
|
|
|
|
|
// These legalizations are for unary ops with only for floating point datatypes.
|
2021-11-11 11:03:36 +08:00
|
|
|
// There is no supported quantized integer mode for these.
|
2021-11-12 08:15:58 +08:00
|
|
|
template <typename AtenOpT, typename TosaOpT>
|
|
|
|
class ConvertAtenUnaryFPOnlyOp : public OpConversionPattern<AtenOpT> {
|
|
|
|
public:
|
|
|
|
using OpConversionPattern<AtenOpT>::OpConversionPattern;
|
2021-11-16 07:00:53 +08:00
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
2021-11-12 08:15:58 +08:00
|
|
|
LogicalResult
|
2021-11-16 07:00:53 +08:00
|
|
|
matchAndRewrite(AtenOpT op, OpAdaptor adaptor,
|
2021-11-12 08:15:58 +08:00
|
|
|
ConversionPatternRewriter &rewriter) const override {
|
2022-12-08 04:20:41 +08:00
|
|
|
Value self = adaptor.getSelf();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfTy = cast<TensorType>(self.getType());
|
2021-11-12 08:15:58 +08:00
|
|
|
|
|
|
|
if (!selfTy)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Only Tensor types supported in TOSA");
|
2021-11-12 08:15:58 +08:00
|
|
|
|
2024-05-31 14:45:13 +08:00
|
|
|
if (isa<mlir::FloatType>(selfTy.getElementType())) {
|
2021-11-12 08:15:58 +08:00
|
|
|
rewriter.replaceOpWithNewOp<TosaOpT>(
|
|
|
|
op,
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
op.getType()),
|
|
|
|
self);
|
|
|
|
return success();
|
|
|
|
} else {
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only floating-point datatype legalization supported");
|
2021-11-12 08:15:58 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
// These unary op legalizations are identical for floating-point
|
|
|
|
// or quantized types
|
|
|
|
template <typename AtenOpT, typename TosaOpT>
|
|
|
|
class ConvertAtenUnaryOp : public OpConversionPattern<AtenOpT> {
|
|
|
|
public:
|
|
|
|
using OpConversionPattern<AtenOpT>::OpConversionPattern;
|
2021-11-16 07:00:53 +08:00
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
2021-11-12 08:15:58 +08:00
|
|
|
LogicalResult
|
2021-11-16 07:00:53 +08:00
|
|
|
matchAndRewrite(AtenOpT op, OpAdaptor adaptor,
|
2021-11-12 08:15:58 +08:00
|
|
|
ConversionPatternRewriter &rewriter) const override {
|
|
|
|
rewriter.replaceOpWithNewOp<TosaOpT>(
|
|
|
|
op,
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
op.getType()),
|
2022-12-08 04:20:41 +08:00
|
|
|
adaptor.getSelf());
|
2021-11-12 08:15:58 +08:00
|
|
|
return success();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2021-12-16 03:19:25 +08:00
|
|
|
// These binary op legalizations are identical for floating-point
|
|
|
|
// or quantized types
|
|
|
|
template <typename AtenOpT, typename TosaOpT>
|
|
|
|
class ConvertAtenBinaryOp : public OpConversionPattern<AtenOpT> {
|
|
|
|
public:
|
|
|
|
using OpConversionPattern<AtenOpT>::OpConversionPattern;
|
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
|
|
|
LogicalResult
|
|
|
|
matchAndRewrite(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const override {
|
2022-12-08 04:20:41 +08:00
|
|
|
Value lhs = adaptor.getSelf();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto lhsTy = cast<TensorType>(lhs.getType());
|
2022-12-08 04:20:41 +08:00
|
|
|
Value rhs = adaptor.getOther();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto rhsTy = cast<TensorType>(rhs.getType());
|
2021-12-16 03:19:25 +08:00
|
|
|
|
|
|
|
if (!lhsTy || !rhsTy)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Only Tensor types supported in TOSA");
|
2021-12-16 03:19:25 +08:00
|
|
|
|
2024-05-31 14:45:13 +08:00
|
|
|
auto outTy = cast<TensorType>(
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
op.getType()));
|
2021-12-16 03:19:25 +08:00
|
|
|
|
2024-09-21 05:33:55 +08:00
|
|
|
Value binaryOp;
|
|
|
|
|
|
|
|
// TOSA ArithmeticRightShiftOp has a round parameter.
|
|
|
|
if constexpr (std::is_same<AtenOpT, AtenBitwiseRightShiftTensorOp>()) {
|
|
|
|
binaryOp = rewriter.create<TosaOpT>(op->getLoc(), outTy, lhs, rhs,
|
|
|
|
/*round=*/false);
|
|
|
|
} else {
|
|
|
|
binaryOp =
|
|
|
|
tosa::createBinaryOpAndCast<TosaOpT>(rewriter, op, outTy, lhs, rhs);
|
|
|
|
}
|
|
|
|
|
|
|
|
rewriter.replaceOp(op, binaryOp);
|
2021-12-16 03:19:25 +08:00
|
|
|
return success();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2022-02-12 04:30:02 +08:00
|
|
|
template <typename T>
|
|
|
|
static bool isInValidRange(bool isFloat, const double &doubleValue, bool isInt,
|
|
|
|
const int64_t &intValue) {
|
|
|
|
if (isFloat) {
|
2022-02-15 04:45:19 +08:00
|
|
|
// Do a round-trip check here instead of numeric limits due to
|
|
|
|
// compiler warnings around double <-> int conversion.
|
|
|
|
return (doubleValue == static_cast<double>(static_cast<T>(doubleValue)));
|
2022-02-12 04:30:02 +08:00
|
|
|
} else {
|
|
|
|
assert(isInt);
|
2023-09-21 01:48:40 +08:00
|
|
|
return (intValue >= static_cast<int64_t>(std::numeric_limits<T>::min())) &&
|
|
|
|
(intValue <= static_cast<int64_t>(std::numeric_limits<T>::max()));
|
2022-02-12 04:30:02 +08:00
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2022-01-21 02:58:30 +08:00
|
|
|
// FIXME: This will eventually go into a Tosa*Utils file.
|
|
|
|
LogicalResult torchScalarToTosaTensor(ConversionPatternRewriter &rewriter,
|
|
|
|
Operation *op, Value torchScalarValue,
|
2022-02-12 04:30:02 +08:00
|
|
|
Value &tosaTensor, Type dtype,
|
|
|
|
llvm::ArrayRef<int64_t> dshape) {
|
|
|
|
// Retrieve a const float or int value but create the out Tensor with dtype.
|
|
|
|
double doubleValue;
|
|
|
|
auto isFloat =
|
|
|
|
matchPattern(torchScalarValue, m_TorchConstantFloat(&doubleValue));
|
2022-01-21 02:58:30 +08:00
|
|
|
|
2022-02-12 04:30:02 +08:00
|
|
|
int64_t intValue;
|
|
|
|
auto isInt = matchPattern(torchScalarValue, m_TorchConstantInt(&intValue));
|
2022-01-21 02:58:30 +08:00
|
|
|
|
2022-02-12 04:30:02 +08:00
|
|
|
if (!isFloat && !isInt)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Unable to extract the scalar constant");
|
2022-01-21 02:58:30 +08:00
|
|
|
|
2024-04-11 21:47:35 +08:00
|
|
|
if (isa<mlir::FloatType>(dtype)) {
|
2023-09-21 01:48:40 +08:00
|
|
|
tosaTensor = tosa::getConstTensor<float>(rewriter, op,
|
|
|
|
(isFloat ? doubleValue : intValue),
|
|
|
|
dshape, dtype)
|
2022-08-09 11:17:35 +08:00
|
|
|
.value();
|
2024-04-11 21:47:35 +08:00
|
|
|
} else if (auto intType = dyn_cast<mlir::IntegerType>(dtype)) {
|
2022-01-21 02:58:30 +08:00
|
|
|
auto w = intType.getWidth();
|
2023-07-17 15:49:04 +08:00
|
|
|
if (w != 1 && w != 32 && w != 64)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, [&](Diagnostic &diag) {
|
|
|
|
diag << "Unsupported integer type: " << intType;
|
|
|
|
});
|
2022-01-21 02:58:30 +08:00
|
|
|
|
2023-07-17 15:49:04 +08:00
|
|
|
if (w == 1) {
|
|
|
|
if (!isInValidRange<bool>(isFloat, doubleValue, isInt, intValue)) {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Supplied value of scalar constant exceeds limits "
|
|
|
|
"of destination type");
|
|
|
|
}
|
|
|
|
bool d = isFloat ? static_cast<bool>(doubleValue)
|
2023-09-21 01:48:40 +08:00
|
|
|
: static_cast<bool>(intValue);
|
2023-07-17 15:49:04 +08:00
|
|
|
tosaTensor =
|
|
|
|
tosa::getConstTensor<bool>(rewriter, op, {d}, dshape).value();
|
|
|
|
} else if (w == 32) {
|
2022-02-12 04:30:02 +08:00
|
|
|
if (!isInValidRange<int32_t>(isFloat, doubleValue, isInt, intValue)) {
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Supplied value of scalar constant exceeds limits "
|
|
|
|
"of destination type");
|
2022-02-12 04:30:02 +08:00
|
|
|
}
|
|
|
|
int32_t d = isFloat ? static_cast<int32_t>(doubleValue)
|
|
|
|
: static_cast<int32_t>(intValue);
|
|
|
|
tosaTensor =
|
2022-08-09 11:17:35 +08:00
|
|
|
tosa::getConstTensor<int32_t>(rewriter, op, {d}, dshape).value();
|
2022-01-21 02:58:30 +08:00
|
|
|
} else if (w == 64) {
|
2022-02-12 04:30:02 +08:00
|
|
|
if (!isInValidRange<int64_t>(isFloat, doubleValue, isInt, intValue)) {
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Supplied value of scalar constant exceeds limits "
|
|
|
|
"of destination type");
|
2022-02-12 04:30:02 +08:00
|
|
|
}
|
|
|
|
int64_t d = (isFloat ? static_cast<int64_t>(doubleValue) : intValue);
|
2022-01-21 02:58:30 +08:00
|
|
|
tosaTensor =
|
2022-08-09 11:17:35 +08:00
|
|
|
tosa::getConstTensor<int64_t>(rewriter, op, {d}, dshape).value();
|
2022-01-21 02:58:30 +08:00
|
|
|
}
|
2022-07-18 09:39:54 +08:00
|
|
|
} else {
|
|
|
|
return rewriter.notifyMatchFailure(op, "Usupported element type");
|
|
|
|
}
|
2022-01-21 02:58:30 +08:00
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
|
|
|
LogicalResult torchAlphaToTosaTensor(ConversionPatternRewriter &rewriter,
|
|
|
|
Operation *op, Value alphaScalar,
|
|
|
|
Value &alphaTensor, Type dtype,
|
|
|
|
bool checkForUnity) {
|
|
|
|
if (succeeded(torchScalarToTosaTensor(rewriter, op, alphaScalar, alphaTensor,
|
2022-02-12 04:30:02 +08:00
|
|
|
dtype, {})))
|
2022-01-21 02:58:30 +08:00
|
|
|
return success();
|
|
|
|
|
|
|
|
// `alpha` has not been specified.
|
|
|
|
int64_t alphaValue;
|
|
|
|
if (!matchPattern(alphaScalar, m_TorchConstantInt(&alphaValue)))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Currently only scalar constants are supported for "
|
|
|
|
"alpha in TOSA operation");
|
2022-01-21 02:58:30 +08:00
|
|
|
// When no alpha has been specified, this must be 1.
|
|
|
|
if (checkForUnity && alphaValue != 1)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Unsupported integer value for alpha");
|
2022-01-21 02:58:30 +08:00
|
|
|
|
2023-06-16 15:51:24 +08:00
|
|
|
alphaTensor = tosa::getConstTensor<float>(
|
|
|
|
rewriter, op, {static_cast<float>(alphaValue)}, {}, dtype)
|
|
|
|
.value();
|
2022-01-21 02:58:30 +08:00
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2021-11-12 08:15:58 +08:00
|
|
|
// These binary op legalizations are specific to add/sub which have an
|
|
|
|
// alpha multiplier.
|
|
|
|
template <typename AtenOpT, typename TosaOpT>
|
|
|
|
class ConvertAtenAddSubOp : public OpConversionPattern<AtenOpT> {
|
|
|
|
public:
|
|
|
|
using OpConversionPattern<AtenOpT>::OpConversionPattern;
|
2021-11-16 07:00:53 +08:00
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
2022-01-08 02:57:54 +08:00
|
|
|
LogicalResult
|
|
|
|
matchAndRewrite(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const override {
|
2022-12-13 04:13:07 +08:00
|
|
|
// left : tensor: tensor<i32/i64/f32>
|
|
|
|
// right : scalar: i32/i64/f32
|
|
|
|
// tensor: tensor<i32/i64/f32>
|
|
|
|
// alpha : scalar: i32/i64/f32
|
|
|
|
// output: tensor: tensor<i32/i64/f32>
|
2022-12-08 04:20:41 +08:00
|
|
|
Value lhs = adaptor.getSelf();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto lhsType = dyn_cast<TensorType>(lhs.getType());
|
2022-12-08 04:20:41 +08:00
|
|
|
Value rhs = adaptor.getOther();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto rhsType = dyn_cast<TensorType>(rhs.getType());
|
2021-11-12 08:15:58 +08:00
|
|
|
|
2022-02-12 04:30:02 +08:00
|
|
|
if (!lhsType)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Only Tensor types supported in TOSA");
|
2021-11-12 08:15:58 +08:00
|
|
|
|
2024-04-28 05:00:56 +08:00
|
|
|
if (auto lhsElemTy = dyn_cast<IntegerType>(lhsType.getElementType())) {
|
2022-12-13 04:13:07 +08:00
|
|
|
if (lhsElemTy.getWidth() > 64)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
2022-12-13 04:13:07 +08:00
|
|
|
op, "Integers with widths greater than 64 are not supported");
|
2022-02-12 04:30:02 +08:00
|
|
|
}
|
|
|
|
|
2022-12-13 04:13:07 +08:00
|
|
|
// Get output type: tensor<i32/i64/f32>
|
2024-05-31 14:45:13 +08:00
|
|
|
auto outType = cast<TensorType>(
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
op.getType()));
|
2022-02-12 04:30:02 +08:00
|
|
|
|
|
|
|
Type outElemTy = outType.getElementType();
|
|
|
|
if (!outElemTy.isIntOrFloat()) {
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only floating-point or integer datatype legalization supported");
|
2022-02-12 04:30:02 +08:00
|
|
|
}
|
2022-01-21 02:58:30 +08:00
|
|
|
|
2022-12-13 04:13:07 +08:00
|
|
|
Type rhsAlphaMulElemType;
|
2024-04-11 21:47:35 +08:00
|
|
|
if (isa<mlir::FloatType>(outElemTy)) {
|
2022-12-13 04:13:07 +08:00
|
|
|
rhsAlphaMulElemType = outElemTy;
|
|
|
|
} else {
|
|
|
|
// if output type is 64, input type should also be 32
|
|
|
|
rhsAlphaMulElemType = rewriter.getIntegerType(32);
|
|
|
|
}
|
|
|
|
|
|
|
|
// if right is scalar, rhgType==None, which need to be manually cast to
|
|
|
|
// TensorType else right is tensor, rhsType==tensor<i32/i64/f32>
|
2022-01-21 02:58:30 +08:00
|
|
|
Value rhsAsTensor;
|
2022-02-12 04:30:02 +08:00
|
|
|
if (!rhsType) {
|
2022-12-13 04:13:07 +08:00
|
|
|
if (failed(torchScalarToTosaTensor(rewriter, op, op.getOther(),
|
|
|
|
rhsAsTensor, rhsAlphaMulElemType, {})))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Currently only scalar constants are supported for "
|
|
|
|
"conversion in TOSA operation");
|
2022-12-13 04:13:07 +08:00
|
|
|
} else if (rhsType.getElementType() != rhsAlphaMulElemType) {
|
|
|
|
// right is tensor, rhsType == tensor<i32/i64/f32>
|
|
|
|
// right must be cast to same type as the alpha, so MulOp success
|
|
|
|
rhs = rewriter.create<tosa::CastOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
RankedTensorType::get(rhsType.getShape(), rhsAlphaMulElemType), rhs);
|
|
|
|
// reinitialize right value type to tensor<i32/f32>
|
2024-04-28 05:00:56 +08:00
|
|
|
rhsType = dyn_cast<TensorType>(rhs.getType());
|
2022-01-21 02:58:30 +08:00
|
|
|
}
|
2022-02-12 04:30:02 +08:00
|
|
|
auto rhsTensor = rhsType ? rhs : rhsAsTensor;
|
2021-11-12 08:15:58 +08:00
|
|
|
|
2022-12-13 04:13:07 +08:00
|
|
|
// Handle scalar value alpha.
|
|
|
|
// It should be either f32/i32
|
2022-01-21 02:58:30 +08:00
|
|
|
Value alphaTensor;
|
2022-12-13 04:13:07 +08:00
|
|
|
if (failed(torchAlphaToTosaTensor(rewriter, op.getOperation(),
|
|
|
|
op.getAlpha(), alphaTensor,
|
|
|
|
rhsAlphaMulElemType,
|
2022-02-12 04:30:02 +08:00
|
|
|
/*checkForUnity=*/false))) {
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Currently only scalar constants are supported for "
|
|
|
|
"alpha in conversion to TOSA operation");
|
2022-02-12 04:30:02 +08:00
|
|
|
}
|
2021-11-12 08:15:58 +08:00
|
|
|
|
2023-05-19 08:12:18 +08:00
|
|
|
auto mulAlphaOp = tosa::createMulOpAndCast(
|
|
|
|
rewriter, op,
|
2022-12-13 04:13:07 +08:00
|
|
|
rhsType ? rhsType : RankedTensorType::get({}, rhsAlphaMulElemType),
|
2022-02-12 04:30:02 +08:00
|
|
|
rhsTensor, alphaTensor, /*shift=*/0);
|
|
|
|
|
2023-05-19 08:12:18 +08:00
|
|
|
if (outElemTy.isInteger(64)) {
|
|
|
|
// Tosa doesn't support 64-bit elementwise addition and subtraction.
|
2022-12-13 04:13:07 +08:00
|
|
|
// if outElemTy tensor<i64>, mulTensor must be tensor<i32>,
|
|
|
|
// left value could be tensor<f32/i32/i64> type, cast left value to
|
|
|
|
// tensor<i32> type
|
2023-05-19 08:12:18 +08:00
|
|
|
auto addOrSubi64Op = tosa::createBinaryOpAndCast<TosaOpT>(
|
|
|
|
rewriter, op,
|
2022-12-13 04:13:07 +08:00
|
|
|
RankedTensorType::get(outType.getShape(), rhsAlphaMulElemType), lhs,
|
2023-05-19 08:12:18 +08:00
|
|
|
mulAlphaOp);
|
2022-12-13 04:13:07 +08:00
|
|
|
|
2023-05-19 08:12:18 +08:00
|
|
|
// cast tensor<i32> back to tensor<i64>
|
|
|
|
rewriter.replaceOpWithNewOp<tosa::CastOp>(op, outType, addOrSubi64Op);
|
2021-11-12 08:15:58 +08:00
|
|
|
return success();
|
|
|
|
}
|
2023-05-19 08:12:18 +08:00
|
|
|
|
|
|
|
auto binaryOp = tosa::createBinaryOpAndCast<TosaOpT>(rewriter, op, outType,
|
|
|
|
lhs, mulAlphaOp);
|
|
|
|
rewriter.replaceOp(op, binaryOp.getResult());
|
|
|
|
return success();
|
2021-11-12 08:15:58 +08:00
|
|
|
}
|
2022-01-21 02:58:30 +08:00
|
|
|
}; // namespace
|
|
|
|
|
|
|
|
// Binary op legalizations for comparator ops.
|
|
|
|
template <typename AtenOpT, typename TosaOpT>
|
|
|
|
class ConvertAtenCompareOp : public OpConversionPattern<AtenOpT> {
|
|
|
|
public:
|
|
|
|
using OpConversionPattern<AtenOpT>::OpConversionPattern;
|
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
|
|
|
LogicalResult
|
|
|
|
matchAndRewrite(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const override {
|
2022-12-08 04:20:41 +08:00
|
|
|
Value lhs = adaptor.getSelf();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto lhsTy = dyn_cast<TensorType>(lhs.getType());
|
2022-12-08 04:20:41 +08:00
|
|
|
Value rhs = adaptor.getOther();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto rhsTy = dyn_cast<TensorType>(rhs.getType());
|
2022-01-21 02:58:30 +08:00
|
|
|
|
|
|
|
if (!lhsTy)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Only Tensor types supported in TOSA");
|
2022-01-21 02:58:30 +08:00
|
|
|
|
|
|
|
auto lhsElemTy = lhsTy.getElementType();
|
|
|
|
if (!lhsElemTy.isIntOrFloat())
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only floating-point or integer datatype legalization supported");
|
2022-01-21 02:58:30 +08:00
|
|
|
|
2022-02-12 04:30:02 +08:00
|
|
|
// For bitwise operators, only integer datatype legalization is supported
|
2023-01-12 06:40:03 +08:00
|
|
|
constexpr bool isBitwiseOp =
|
|
|
|
std::is_same<AtenOpT, AtenBitwiseAndTensorOp>() ||
|
2024-09-21 05:33:55 +08:00
|
|
|
std::is_same<AtenOpT, AtenBitwiseAndScalarOp>() ||
|
2023-01-12 06:40:03 +08:00
|
|
|
std::is_same<AtenOpT, AtenBitwiseOrTensorOp>() ||
|
|
|
|
std::is_same<AtenOpT, AtenBitwiseXorTensorOp>();
|
2024-04-11 21:47:35 +08:00
|
|
|
if (isa<mlir::FloatType>(lhsElemTy) && isBitwiseOp) {
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"For bitwise operators, only integer "
|
|
|
|
"datatype legalization is supported");
|
2022-02-12 04:30:02 +08:00
|
|
|
}
|
|
|
|
|
2022-01-21 02:58:30 +08:00
|
|
|
Value rhsAsTensor;
|
|
|
|
if (!rhsTy) {
|
2023-01-11 13:42:07 +08:00
|
|
|
if (failed(torchScalarToTosaTensor(rewriter, op, op.getOther(),
|
|
|
|
rhsAsTensor, lhsElemTy, {})))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Currently only scalar constants are supported for "
|
|
|
|
"conversion in TOSA operation");
|
2022-01-21 02:58:30 +08:00
|
|
|
}
|
|
|
|
auto rhsTensor = rhsTy ? rhs : rhsAsTensor;
|
2022-02-12 04:30:02 +08:00
|
|
|
// There is no Lesser operator in TOSA.
|
2024-05-10 17:07:37 +08:00
|
|
|
constexpr auto swapLhsRhs = (std::is_same<AtenOpT, AtenLtTensorOp>() ||
|
2024-09-21 05:33:55 +08:00
|
|
|
std::is_same<AtenOpT, AtenLtScalarOp>() ||
|
|
|
|
std::is_same<AtenOpT, AtenLeTensorOp>() ||
|
|
|
|
std::is_same<AtenOpT, AtenLeScalarOp>());
|
2022-01-21 02:58:30 +08:00
|
|
|
|
2023-01-12 06:40:03 +08:00
|
|
|
// Promote lhs and rhs dtypes for bitwise operators.
|
2024-05-31 14:45:13 +08:00
|
|
|
TensorType resultTy = cast<TensorType>(
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
op.getType()));
|
2023-01-12 06:40:03 +08:00
|
|
|
if (isBitwiseOp) {
|
|
|
|
lhs = tosa::promoteType(rewriter, lhs, resultTy);
|
|
|
|
rhsTensor = tosa::promoteType(rewriter, rhsTensor, resultTy);
|
|
|
|
}
|
|
|
|
|
|
|
|
auto resultOp = rewriter.create<TosaOpT>(op.getLoc(), resultTy,
|
|
|
|
(swapLhsRhs ? rhsTensor : lhs),
|
|
|
|
(swapLhsRhs ? lhs : rhsTensor));
|
2022-02-12 04:30:02 +08:00
|
|
|
|
|
|
|
// There is no NE operator in TOSA.
|
2024-05-10 17:07:37 +08:00
|
|
|
if constexpr (std::is_same<AtenOpT, AtenNeTensorOp>() ||
|
|
|
|
std::is_same<AtenOpT, AtenNeScalarOp>()) {
|
2023-01-12 06:40:03 +08:00
|
|
|
rewriter.replaceOpWithNewOp<tosa::LogicalNotOp>(op, resultTy,
|
|
|
|
resultOp.getResult());
|
2024-05-10 17:07:37 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
else {
|
2022-02-12 04:30:02 +08:00
|
|
|
rewriter.replaceOp(op, resultOp.getResult());
|
2024-05-10 17:07:37 +08:00
|
|
|
}
|
2022-02-12 04:30:02 +08:00
|
|
|
|
2022-01-21 02:58:30 +08:00
|
|
|
return success();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
// Binary op legalizations for Mul variants.
|
|
|
|
template <typename AtenOpT>
|
|
|
|
class ConvertAtenMulOp : public OpConversionPattern<AtenOpT> {
|
|
|
|
public:
|
|
|
|
using OpConversionPattern<AtenOpT>::OpConversionPattern;
|
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
|
|
|
LogicalResult
|
|
|
|
matchAndRewrite(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const override {
|
2022-12-08 04:20:41 +08:00
|
|
|
Value lhs = adaptor.getSelf();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto lhsType = dyn_cast<TensorType>(lhs.getType());
|
2022-01-21 02:58:30 +08:00
|
|
|
|
2022-02-12 04:30:02 +08:00
|
|
|
if (!lhsType)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Only Tensor types supported in TOSA");
|
2022-01-21 02:58:30 +08:00
|
|
|
|
2024-05-31 14:45:13 +08:00
|
|
|
auto outType = cast<TensorType>(
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
op.getType()));
|
2022-02-12 04:30:02 +08:00
|
|
|
|
|
|
|
Type outElemTy = outType.getElementType();
|
|
|
|
if (!outElemTy.isIntOrFloat())
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only floating-point or integer datatype legalization supported");
|
2022-01-21 02:58:30 +08:00
|
|
|
|
2022-02-12 04:30:02 +08:00
|
|
|
Value rhsTensor;
|
2024-05-10 17:07:37 +08:00
|
|
|
if constexpr (std::is_same<AtenOpT, AtenSquareOp>()) {
|
2022-02-12 04:30:02 +08:00
|
|
|
rhsTensor = lhs;
|
|
|
|
} else {
|
|
|
|
Value rhsAsTensor;
|
2022-12-08 04:20:41 +08:00
|
|
|
Value rhs = adaptor.getOther();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto rhsType = dyn_cast<TensorType>(rhs.getType());
|
2022-02-12 04:30:02 +08:00
|
|
|
if (!rhsType) {
|
2022-12-08 04:20:41 +08:00
|
|
|
if (failed(torchScalarToTosaTensor(rewriter, op, op.getOther(),
|
2022-07-18 09:39:54 +08:00
|
|
|
rhsAsTensor, outElemTy, {}))) {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Currently only scalar constants are supported for "
|
|
|
|
"conversion in TOSA operation");
|
|
|
|
}
|
2022-02-12 04:30:02 +08:00
|
|
|
}
|
|
|
|
rhsTensor = rhsType ? rhs : rhsAsTensor;
|
2022-01-21 02:58:30 +08:00
|
|
|
}
|
|
|
|
|
2024-04-11 21:47:35 +08:00
|
|
|
if (isa<mlir::FloatType>(outElemTy) || isa<mlir::IntegerType>(outElemTy)) {
|
2024-05-31 14:45:13 +08:00
|
|
|
auto outType = cast<TensorType>(
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
op.getType()));
|
2022-02-12 04:30:02 +08:00
|
|
|
|
2023-05-19 08:12:18 +08:00
|
|
|
auto mulOp = tosa::createMulOpAndCast(rewriter, op, outType, lhs,
|
|
|
|
rhsTensor, /*shift=*/0);
|
|
|
|
rewriter.replaceOp(op, mulOp.getResult());
|
2022-01-21 02:58:30 +08:00
|
|
|
return success();
|
|
|
|
}
|
2022-07-18 09:39:54 +08:00
|
|
|
|
|
|
|
// Quantized multiplication may need to rescale inputs.
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only floating-point or integer datatype "
|
|
|
|
"legalization currently supported");
|
2022-01-21 02:58:30 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-09-21 04:34:09 +08:00
|
|
|
// Function to perform division with trunc rounding mode (rounding result
|
|
|
|
// towards zero) for float type inputs.
|
|
|
|
// This function takes in the division result between lhs and rhs rather
|
|
|
|
// than takes in the original lhs and rhs tensors as parameters.
|
|
|
|
Value truncFloatDivWithDivResult(PatternRewriter &rewriter, Operation *op,
|
|
|
|
TensorType outType, Value divResult) {
|
|
|
|
// To implement trunc mode for float inputs, multiply the floored abs
|
|
|
|
// of the tensor with the elementwise signedness of the tensor.
|
|
|
|
// div_result = lhs / rhs
|
|
|
|
// trunc_val = floor(abs(div_result)) * sign(div_result)
|
|
|
|
auto zero =
|
|
|
|
tosa::getConstTensor<float>(rewriter, op, 0, {}, outType.getElementType())
|
|
|
|
.value();
|
|
|
|
|
|
|
|
auto one =
|
|
|
|
tosa::getConstTensor<float>(rewriter, op, 1, {}, outType.getElementType())
|
|
|
|
.value();
|
|
|
|
|
|
|
|
auto minusOne = tosa::getConstTensor<float>(rewriter, op, -1, {},
|
|
|
|
outType.getElementType())
|
|
|
|
.value();
|
|
|
|
|
|
|
|
auto cond = rewriter.create<tosa::GreaterEqualOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
RankedTensorType::get(outType.getShape(), rewriter.getIntegerType(1)),
|
|
|
|
divResult, zero);
|
|
|
|
|
|
|
|
auto selectOp = rewriter.create<tosa::SelectOp>(op->getLoc(), outType, cond,
|
|
|
|
one, minusOne);
|
|
|
|
|
|
|
|
auto absDivResult =
|
|
|
|
rewriter.create<tosa::AbsOp>(op->getLoc(), outType, divResult);
|
|
|
|
|
|
|
|
auto flooredAbsDivResult =
|
|
|
|
rewriter.create<tosa::FloorOp>(op->getLoc(), outType, absDivResult);
|
|
|
|
|
|
|
|
Value result =
|
|
|
|
tosa::createMulOpAndCast(rewriter, op, outType, flooredAbsDivResult,
|
|
|
|
selectOp, /*shift=*/0)
|
|
|
|
.getResult();
|
|
|
|
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Function to perform division with trunc rounding mode (rounding result
|
|
|
|
// towards zero) for float type inputs
|
|
|
|
Value truncFloatDiv(PatternRewriter &rewriter, Operation *op,
|
|
|
|
TensorType outType, Value lhs, Value rhs) {
|
|
|
|
rhs = tosa::promoteType(rewriter, rhs, outType);
|
|
|
|
|
|
|
|
auto rhsRcp =
|
|
|
|
rewriter.create<tosa::ReciprocalOp>(op->getLoc(), rhs.getType(), rhs);
|
|
|
|
|
|
|
|
auto divResult = tosa::createMulOpAndCast(rewriter, op, outType, lhs, rhsRcp,
|
|
|
|
/*shift=*/0);
|
|
|
|
|
|
|
|
return truncFloatDivWithDivResult(rewriter, op, outType, divResult);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Function to perform division with floor rounding mode (rounding result
|
|
|
|
// down) for integer type inputs.
|
|
|
|
Value floorIntDiv(PatternRewriter &rewriter, Operation *op, TensorType outType,
|
|
|
|
Value lhs, Value rhs) {
|
|
|
|
// To implement floor mode int input, utilize tosa::IntDivOp (trunc div
|
|
|
|
// result) with the following formula elementwise:
|
|
|
|
// floor_val = trunc_val - ((trunc_val * rhs != lhs)
|
|
|
|
// && (sign(lhs) != sign(rhs)))
|
|
|
|
|
|
|
|
// TOSA IntDiv requires inputs to be i32
|
|
|
|
auto i32Type =
|
|
|
|
RankedTensorType::get(outType.getShape(), rewriter.getIntegerType(32));
|
|
|
|
lhs = tosa::promoteType(rewriter, lhs, i32Type);
|
|
|
|
rhs = tosa::promoteType(rewriter, rhs, i32Type);
|
|
|
|
|
|
|
|
auto intDivOp =
|
|
|
|
rewriter.create<tosa::IntDivOp>(op->getLoc(), i32Type, lhs, rhs);
|
|
|
|
|
|
|
|
auto zero = tosa::getConstTensor<int32_t>(rewriter, op, 0, {}).value();
|
|
|
|
|
|
|
|
auto one = tosa::getConstTensor<int32_t>(rewriter, op, 1, {}).value();
|
|
|
|
|
|
|
|
auto boolType =
|
|
|
|
RankedTensorType::get(outType.getShape(), rewriter.getIntegerType(1));
|
|
|
|
|
|
|
|
auto lhsMulRhs = rewriter.create<tosa::MulOp>(op->getLoc(), i32Type, lhs, rhs,
|
|
|
|
/*shift=*/0);
|
|
|
|
|
|
|
|
auto lhsRhsDifferentSign =
|
|
|
|
rewriter.create<tosa::GreaterOp>(op->getLoc(), boolType, zero, lhsMulRhs);
|
|
|
|
|
|
|
|
auto truncMulRhs = rewriter.create<tosa::MulOp>(op->getLoc(), i32Type,
|
|
|
|
intDivOp, rhs, /*shift=*/0);
|
|
|
|
|
|
|
|
auto truncMulRhsEqualLhs =
|
|
|
|
rewriter.create<tosa::EqualOp>(op->getLoc(), boolType, truncMulRhs, lhs);
|
|
|
|
|
|
|
|
auto truncMulRhsNotEqualLhs = rewriter.create<tosa::LogicalNotOp>(
|
|
|
|
op->getLoc(), boolType, truncMulRhsEqualLhs);
|
|
|
|
|
|
|
|
auto truncMinusOne =
|
|
|
|
rewriter.create<tosa::SubOp>(op->getLoc(), i32Type, intDivOp, one);
|
|
|
|
|
|
|
|
auto cond = rewriter.create<tosa::LogicalAndOp>(
|
|
|
|
op->getLoc(), boolType, lhsRhsDifferentSign, truncMulRhsNotEqualLhs);
|
|
|
|
|
|
|
|
auto selectOp = rewriter.create<tosa::SelectOp>(op->getLoc(), i32Type, cond,
|
|
|
|
truncMinusOne, intDivOp);
|
|
|
|
|
|
|
|
Value result = tosa::promoteType(rewriter, selectOp, outType);
|
|
|
|
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2022-01-21 02:58:30 +08:00
|
|
|
template <typename AtenOpT>
|
|
|
|
class ConvertAtenDivOp : public OpConversionPattern<AtenOpT> {
|
|
|
|
public:
|
|
|
|
using OpConversionPattern<AtenOpT>::OpConversionPattern;
|
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
|
|
|
LogicalResult
|
|
|
|
matchAndRewrite(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const override {
|
2022-12-08 04:20:41 +08:00
|
|
|
Value lhs = adaptor.getSelf();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto lhsTy = dyn_cast<TensorType>(lhs.getType());
|
2022-12-08 04:20:41 +08:00
|
|
|
Value rhs = adaptor.getOther();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto rhsTy = dyn_cast<TensorType>(rhs.getType());
|
2022-01-21 02:58:30 +08:00
|
|
|
|
|
|
|
if (!lhsTy)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Only Tensor types supported in TOSA");
|
2022-01-21 02:58:30 +08:00
|
|
|
|
|
|
|
auto lhsElemTy = lhsTy.getElementType();
|
|
|
|
if (!lhsElemTy.isIntOrFloat())
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only floating-point or integer datatype legalization supported");
|
2022-01-21 02:58:30 +08:00
|
|
|
|
|
|
|
Value rhsAsTensor;
|
|
|
|
if (!rhsTy) {
|
2023-01-11 13:42:07 +08:00
|
|
|
if (failed(torchScalarToTosaTensor(rewriter, op, op.getOther(),
|
|
|
|
rhsAsTensor, lhsElemTy, {})))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Currently only scalar constants are supported for "
|
|
|
|
"conversion in TOSA operation");
|
2022-01-21 02:58:30 +08:00
|
|
|
}
|
|
|
|
auto rhsTensor = rhsTy ? rhs : rhsAsTensor;
|
2024-05-31 14:45:13 +08:00
|
|
|
auto outType = cast<TensorType>(
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
op.getType()));
|
2022-01-21 02:58:30 +08:00
|
|
|
|
2024-09-21 04:34:09 +08:00
|
|
|
// Get rounding mode for aten.div.Tensor_mode
|
|
|
|
std::string roundMode;
|
|
|
|
if constexpr (std::is_same<AtenOpT, AtenDivTensorModeOp>() ||
|
|
|
|
std::is_same<AtenOpT, AtenDivScalarModeOp>()) {
|
|
|
|
if (!matchPattern(op.getRoundingMode(), m_TorchConstantStr(roundMode)))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Non-const rounding mode parameter unsupported");
|
|
|
|
}
|
|
|
|
|
2023-05-19 08:12:18 +08:00
|
|
|
Value result;
|
2024-04-28 05:00:56 +08:00
|
|
|
if (isa<mlir::FloatType>(outType.getElementType())) {
|
2024-09-21 04:34:09 +08:00
|
|
|
// The input to the reciprocal is an integer sometimes, and we may need
|
|
|
|
// to promote it to a floating point. Per TOSA specification, the input
|
|
|
|
// types can only be floating point for tosa::ReciprocalOp.
|
|
|
|
rhsTensor = tosa::promoteType(rewriter, rhsTensor, outType);
|
|
|
|
auto rhsRcp = rewriter.create<tosa::ReciprocalOp>(
|
|
|
|
op->getLoc(), rhsTensor.getType(), rhsTensor);
|
|
|
|
|
|
|
|
auto divResult = tosa::createMulOpAndCast(rewriter, op, outType, lhs,
|
|
|
|
rhsRcp, /*shift=*/0);
|
|
|
|
|
|
|
|
// Round result based on rounding mode
|
|
|
|
if (roundMode.compare("floor") == 0) {
|
|
|
|
// "floor": rounds the results of the division down. Equivalent to
|
|
|
|
// floor division in Python (the // operator).
|
|
|
|
auto floorOp =
|
|
|
|
rewriter.create<tosa::FloorOp>(op->getLoc(), outType, divResult);
|
|
|
|
|
|
|
|
result = floorOp.getResult();
|
|
|
|
} else if (roundMode.compare("trunc") == 0) {
|
|
|
|
// "trunc": rounds the results of the division towards zero. Equivalent
|
|
|
|
// to C-style integer division.
|
|
|
|
result = truncFloatDivWithDivResult(rewriter, op, outType, divResult);
|
|
|
|
} else {
|
|
|
|
// None: No rounding mode
|
|
|
|
result = divResult.getResult();
|
|
|
|
}
|
2022-01-21 02:58:30 +08:00
|
|
|
} else {
|
2024-09-21 04:34:09 +08:00
|
|
|
if (roundMode.compare("floor") == 0) {
|
|
|
|
// "floor": rounds the results of the division down. Equivalent to floor
|
|
|
|
// division in Python (the // operator).
|
|
|
|
result = floorIntDiv(rewriter, op, outType, lhs, rhsTensor);
|
|
|
|
} else {
|
|
|
|
// "trunc": rounds the results of the division towards zero. Equivalent
|
|
|
|
// to C-style integer division.
|
|
|
|
// None: no rounding mode.
|
|
|
|
|
|
|
|
// TOSA IntDiv requires inputs to be i32
|
|
|
|
auto i32Type = RankedTensorType::get(outType.getShape(),
|
|
|
|
rewriter.getIntegerType(32));
|
|
|
|
lhs = tosa::promoteType(rewriter, lhs, i32Type);
|
|
|
|
rhsTensor = tosa::promoteType(rewriter, rhsTensor, i32Type);
|
|
|
|
|
|
|
|
auto intDivOp = rewriter.create<tosa::IntDivOp>(op->getLoc(), i32Type,
|
|
|
|
lhs, rhsTensor);
|
|
|
|
|
|
|
|
result = tosa::promoteType(rewriter, intDivOp, outType);
|
|
|
|
}
|
2022-01-21 02:58:30 +08:00
|
|
|
}
|
2023-05-19 08:12:18 +08:00
|
|
|
|
|
|
|
rewriter.replaceOp(op, {result});
|
2022-01-21 02:58:30 +08:00
|
|
|
return success();
|
|
|
|
}
|
2021-11-12 08:15:58 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
// This defines a template to construct ops whose legalizations are
|
|
|
|
// specialized.
|
|
|
|
template <typename AtenOpT>
|
|
|
|
class ConvertAtenOp : public OpConversionPattern<AtenOpT> {
|
|
|
|
public:
|
|
|
|
using OpConversionPattern<AtenOpT>::OpConversionPattern;
|
2021-11-16 07:00:53 +08:00
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
2021-11-12 08:15:58 +08:00
|
|
|
LogicalResult
|
2021-11-16 07:00:53 +08:00
|
|
|
matchAndRewrite(AtenOpT op, OpAdaptor adaptor,
|
2021-11-12 08:15:58 +08:00
|
|
|
ConversionPatternRewriter &rewriter) const override;
|
|
|
|
};
|
|
|
|
|
2024-09-21 05:33:55 +08:00
|
|
|
template <typename AtenOpT, typename TosaOpT>
|
|
|
|
class ConvertAtenActivationFunctionOp : public OpConversionPattern<AtenOpT> {
|
|
|
|
public:
|
|
|
|
using OpConversionPattern<AtenOpT>::OpConversionPattern;
|
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
|
|
|
LogicalResult
|
|
|
|
matchAndRewrite(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const override {
|
|
|
|
Value self = adaptor.getSelf();
|
|
|
|
auto selfTy = cast<TensorType>(self.getType());
|
|
|
|
|
|
|
|
if (!selfTy)
|
|
|
|
return rewriter.notifyMatchFailure(op, "Only Tensor types supported");
|
|
|
|
|
|
|
|
if (!isa<mlir::FloatType>(selfTy.getElementType()))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only floating-point datatype legalization currently supported");
|
|
|
|
|
|
|
|
rewriter.replaceOpWithNewOp<TosaOpT>(
|
|
|
|
op, this->getTypeConverter()->convertType(op.getType()), self);
|
2021-10-29 01:09:12 +08:00
|
|
|
|
2021-11-11 11:03:36 +08:00
|
|
|
return success();
|
|
|
|
}
|
2024-09-21 05:33:55 +08:00
|
|
|
};
|
2021-11-11 11:03:36 +08:00
|
|
|
|
2021-11-12 08:15:58 +08:00
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenReluOp>::matchAndRewrite(
|
2021-11-16 07:00:53 +08:00
|
|
|
AtenReluOp op, OpAdaptor adaptor,
|
2021-11-12 08:15:58 +08:00
|
|
|
ConversionPatternRewriter &rewriter) const {
|
2022-12-08 04:20:41 +08:00
|
|
|
Value self = adaptor.getSelf();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfTy = cast<TensorType>(self.getType());
|
2021-11-11 11:03:36 +08:00
|
|
|
|
|
|
|
// Maps to tosa.clamp which has both int and fp limits.
|
|
|
|
int64_t clampMin = 0;
|
|
|
|
Value clampIn = self;
|
2022-07-18 09:39:54 +08:00
|
|
|
if (!selfTy) {
|
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Only Tensor types supported in TOSA");
|
2021-11-11 11:03:36 +08:00
|
|
|
}
|
2022-07-18 09:39:54 +08:00
|
|
|
|
|
|
|
// Rescale the clampIn for quantized types. TBD
|
2024-05-31 14:45:13 +08:00
|
|
|
if (!isa<mlir::FloatType>(selfTy.getElementType())) {
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only floating-point datatype legalization currently supported");
|
|
|
|
}
|
|
|
|
rewriter.replaceOpWithNewOp<tosa::ClampOp>(
|
|
|
|
op, getTypeConverter()->convertType(op.getType()), clampIn,
|
|
|
|
rewriter.getI64IntegerAttr(clampMin),
|
|
|
|
rewriter.getI64IntegerAttr(std::numeric_limits<int32_t>::max()),
|
|
|
|
rewriter.getF32FloatAttr(0.0f),
|
|
|
|
rewriter.getF32FloatAttr(std::numeric_limits<float>::max()));
|
|
|
|
return success();
|
2021-10-29 01:09:12 +08:00
|
|
|
}
|
|
|
|
|
2023-01-11 13:42:07 +08:00
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenLeakyReluOp>::matchAndRewrite(
|
|
|
|
AtenLeakyReluOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
|
|
|
Value self = adaptor.getSelf();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfTy = cast<TensorType>(self.getType());
|
2024-05-31 14:45:13 +08:00
|
|
|
if (!isa<mlir::FloatType>(selfTy.getElementType())) {
|
2023-01-11 13:42:07 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only floating-point datatype legalization currently supported");
|
|
|
|
}
|
|
|
|
|
|
|
|
Value alphaScalar = op.getNegativeSlope();
|
|
|
|
Value alphaTensor;
|
|
|
|
if (failed(torchScalarToTosaTensor(rewriter, op.getOperation(), alphaScalar,
|
|
|
|
alphaTensor, selfTy.getElementType(), {})))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Negative slope needs to be a scalar constant for conversion to "
|
|
|
|
"TOSA LeakyReLU operation");
|
|
|
|
|
2023-09-21 01:48:40 +08:00
|
|
|
auto zero =
|
|
|
|
tosa::getConstTensor<float>(rewriter, op, 0, {}, selfTy.getElementType())
|
|
|
|
.value();
|
2023-01-11 13:42:07 +08:00
|
|
|
auto cond = rewriter.create<tosa::GreaterEqualOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
RankedTensorType::get(selfTy.getShape(), rewriter.getIntegerType(1)),
|
|
|
|
self, zero);
|
|
|
|
auto mulTensor = rewriter.create<tosa::MulOp>(
|
|
|
|
op->getLoc(), getTypeConverter()->convertType(op.getType()), self,
|
|
|
|
alphaTensor, /*shift=*/0);
|
|
|
|
|
|
|
|
rewriter.replaceOpWithNewOp<tosa::SelectOp>(
|
|
|
|
op, getTypeConverter()->convertType(op.getType()), cond, self, mulTensor);
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2022-12-20 18:17:27 +08:00
|
|
|
using ReductionConvFunc = std::optional<Value> (*)(PatternRewriter &,
|
|
|
|
Operation *,
|
|
|
|
RankedTensorType, Value,
|
|
|
|
ElementsAttr, bool);
|
2021-12-03 08:52:01 +08:00
|
|
|
|
|
|
|
// They all constitute a common form invoking the appropriate
|
|
|
|
// converion function in TosaLegalizeCommon.cpp
|
|
|
|
template <typename AtenOpT, ReductionConvFunc ConversionFuncT>
|
|
|
|
class ConvertAtenReductionOp : public OpConversionPattern<AtenOpT> {
|
|
|
|
public:
|
|
|
|
using OpConversionPattern<AtenOpT>::OpConversionPattern;
|
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
|
|
|
|
|
|
|
// Each variant must implement corresponding parameter parsing options
|
|
|
|
virtual LogicalResult readReduceDimsAndKeepDims(
|
|
|
|
AtenOpT op, OpAdaptor adaptor, ConversionPatternRewriter &rewriter,
|
|
|
|
ElementsAttr &reduceDimsAttr, bool &keepDims) const {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Unimplemented reduce_dims and keep_dims parsing function");
|
|
|
|
}
|
|
|
|
|
|
|
|
// Common rewriter for all reduction ops, calls the specific implementation of
|
|
|
|
// readReduceDimsAndKeepDims() needed for the op variant.
|
2022-01-08 02:57:54 +08:00
|
|
|
LogicalResult
|
|
|
|
matchAndRewrite(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const override {
|
2022-12-08 04:20:41 +08:00
|
|
|
Value self = adaptor.getSelf();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfTy = cast<TensorType>(self.getType());
|
2021-12-03 08:52:01 +08:00
|
|
|
|
|
|
|
if (!selfTy)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Only Tensor types supported in TOSA");
|
2021-12-03 08:52:01 +08:00
|
|
|
|
2024-05-31 14:45:13 +08:00
|
|
|
auto outputTy = cast<RankedTensorType>(
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
op.getType()));
|
2021-12-03 08:52:01 +08:00
|
|
|
if (!outputTy)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only ranked tensor type outputs permitted for reduce_mean");
|
2021-12-03 08:52:01 +08:00
|
|
|
|
2024-09-17 03:40:24 +08:00
|
|
|
auto selfElemTy = selfTy.getElementType();
|
|
|
|
if (!selfElemTy.isIntOrFloat())
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only floating-point or integer datatype legalization supported");
|
|
|
|
|
|
|
|
// TOSA ReduceAll and ReduceAny ops only accept bool input
|
|
|
|
if constexpr (std::is_same<AtenOpT, AtenAllDimOp>() ||
|
|
|
|
std::is_same<AtenOpT, AtenAnyDimOp>() ||
|
|
|
|
std::is_same<AtenOpT, AtenAllOp>() ||
|
|
|
|
std::is_same<AtenOpT, AtenAnyOp>()) {
|
|
|
|
self = tosa::promoteType(
|
|
|
|
rewriter, self,
|
|
|
|
RankedTensorType::get(selfTy.getShape(), rewriter.getIntegerType(1)));
|
|
|
|
}
|
|
|
|
|
|
|
|
// Handle dtype output and bool elem type for ReduceSum and ReduceProd ops
|
|
|
|
if constexpr (std::is_same<AtenOpT, AtenSumDimIntListOp>() ||
|
|
|
|
std::is_same<AtenOpT, AtenSumOp>() ||
|
|
|
|
std::is_same<AtenOpT, AtenProdDimIntOp>() ||
|
|
|
|
std::is_same<AtenOpT, AtenProdOp>()) {
|
|
|
|
auto dtype = op.getDtype();
|
|
|
|
int64_t dtypeInt;
|
|
|
|
if (!isa<Torch::NoneType>(dtype.getType())) {
|
|
|
|
if (!matchPattern(dtype, m_TorchConstantInt(&dtypeInt)))
|
|
|
|
return rewriter.notifyMatchFailure(op, "dtype is not a constant int");
|
|
|
|
|
|
|
|
FailureOr<Type> maybeDtypeType = getTypeForScalarType(
|
|
|
|
op.getContext(), (torch_upstream::ScalarType)dtypeInt);
|
|
|
|
if (failed(maybeDtypeType)) {
|
|
|
|
return rewriter.notifyMatchFailure(op, "dtype is undefined");
|
|
|
|
} else {
|
|
|
|
Type dtypeType = maybeDtypeType.value();
|
|
|
|
|
|
|
|
if (isa<mlir::IntegerType>(dtypeType))
|
|
|
|
dtypeType =
|
|
|
|
rewriter.getIntegerType(dtypeType.getIntOrFloatBitWidth());
|
|
|
|
|
|
|
|
self = tosa::promoteType(
|
|
|
|
rewriter, self,
|
|
|
|
RankedTensorType::get(selfTy.getShape(), dtypeType));
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if (selfElemTy.isInteger(1))
|
|
|
|
self = tosa::promoteType(rewriter, self, outputTy);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-03 08:52:01 +08:00
|
|
|
ElementsAttr reduceDimsAttr;
|
|
|
|
bool keepDims;
|
|
|
|
|
|
|
|
if (failed(readReduceDimsAndKeepDims(op, adaptor, rewriter, reduceDimsAttr,
|
|
|
|
keepDims)))
|
|
|
|
return failure();
|
|
|
|
|
2022-12-20 18:17:27 +08:00
|
|
|
std::optional<Value> result =
|
2021-12-03 08:52:01 +08:00
|
|
|
ConversionFuncT(rewriter, op, outputTy, self, reduceDimsAttr, keepDims);
|
|
|
|
|
|
|
|
if (!result)
|
|
|
|
return failure();
|
|
|
|
|
2022-08-09 11:17:35 +08:00
|
|
|
rewriter.replaceOp(op, {result.value()});
|
2021-12-03 08:52:01 +08:00
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
// This reduction op legalization template handles op variants that have
|
|
|
|
// explicit reduce_dims dimensions (provided as a list) and keep_dims
|
|
|
|
// parameters.
|
|
|
|
template <typename AtenOpT, ReductionConvFunc ConversionFuncT>
|
|
|
|
class ConvertAtenMultipleDimsReductionOp
|
|
|
|
: public ConvertAtenReductionOp<AtenOpT, ConversionFuncT> {
|
|
|
|
using ConvertAtenReductionOp<AtenOpT,
|
|
|
|
ConversionFuncT>::ConvertAtenReductionOp;
|
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
|
|
|
LogicalResult readReduceDimsAndKeepDims(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter,
|
|
|
|
ElementsAttr &reduceDimsAttr,
|
2022-01-08 02:57:54 +08:00
|
|
|
bool &keepDims) const override {
|
2021-12-03 08:52:01 +08:00
|
|
|
SmallVector<int64_t, 4> reduceDims;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getDim(), m_TorchListOfConstantInts(reduceDims)))
|
2021-12-03 08:52:01 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"non-const dim parameter unsupported");
|
|
|
|
int64_t N = reduceDims.size();
|
2023-05-10 23:25:58 +08:00
|
|
|
int64_t inputRank =
|
2024-04-28 05:00:56 +08:00
|
|
|
cast<RankedTensorType>(adaptor.getSelf().getType()).getRank();
|
2023-05-10 23:25:58 +08:00
|
|
|
for (unsigned i = 0; i < N; i++) {
|
2023-04-07 19:49:35 +08:00
|
|
|
reduceDims[i] = toPositiveDim(reduceDims[i], inputRank);
|
|
|
|
if (!isValidDim(reduceDims[i], inputRank))
|
2023-05-10 23:25:58 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"reduce dim is statically invalid");
|
2023-04-07 19:49:35 +08:00
|
|
|
}
|
2021-12-03 08:52:01 +08:00
|
|
|
auto reduceDimsType = RankedTensorType::get({N}, rewriter.getI64Type());
|
2023-01-25 09:29:42 +08:00
|
|
|
reduceDimsAttr =
|
|
|
|
DenseIntElementsAttr::get(reduceDimsType, llvm::ArrayRef(reduceDims));
|
2021-12-03 08:52:01 +08:00
|
|
|
|
|
|
|
keepDims = false;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getKeepdim(), m_TorchConstantBool(&keepDims)))
|
2021-12-03 08:52:01 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "non-const keepdim parameter unsupported");
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
// This reduction op legalization template handles op variants that reduce in
|
|
|
|
// only one explicit dim which is provided as a number (rather than a list), and
|
|
|
|
// a keep_dims parameter.
|
|
|
|
template <typename AtenOpT, ReductionConvFunc ConversionFuncT>
|
|
|
|
class ConvertAtenOneDimReductionOp
|
|
|
|
: public ConvertAtenReductionOp<AtenOpT, ConversionFuncT> {
|
|
|
|
using ConvertAtenReductionOp<AtenOpT,
|
|
|
|
ConversionFuncT>::ConvertAtenReductionOp;
|
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
|
|
|
LogicalResult readReduceDimsAndKeepDims(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter,
|
|
|
|
ElementsAttr &reduceDimsAttr,
|
2022-01-08 02:57:54 +08:00
|
|
|
bool &keepDims) const override {
|
2021-12-03 08:52:01 +08:00
|
|
|
int64_t reduceDim;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getDim(), m_TorchConstantInt(&reduceDim)))
|
2021-12-03 08:52:01 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"non-const dim parameter unsupported");
|
2023-05-10 23:25:58 +08:00
|
|
|
int64_t inputRank =
|
2024-04-28 05:00:56 +08:00
|
|
|
cast<RankedTensorType>(adaptor.getSelf().getType()).getRank();
|
2023-04-07 19:49:35 +08:00
|
|
|
reduceDim = toPositiveDim(reduceDim, inputRank);
|
|
|
|
if (!isValidDim(reduceDim, inputRank))
|
|
|
|
return rewriter.notifyMatchFailure(op, "dim is statically invalid");
|
2021-12-03 08:52:01 +08:00
|
|
|
auto reduceDimsType = RankedTensorType::get({1}, rewriter.getI64Type());
|
2023-01-25 09:29:42 +08:00
|
|
|
reduceDimsAttr =
|
|
|
|
DenseIntElementsAttr::get(reduceDimsType, llvm::ArrayRef({reduceDim}));
|
2021-12-03 08:52:01 +08:00
|
|
|
|
|
|
|
keepDims = false;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getKeepdim(), m_TorchConstantBool(&keepDims)))
|
2021-12-03 08:52:01 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "non-const keepdim parameter unsupported");
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
// This reduction op legalization template handles op variants that reduce all
|
|
|
|
// dims does not keep dims.
|
|
|
|
template <typename AtenOpT, ReductionConvFunc ConversionFuncT>
|
|
|
|
class ConvertAtenAllDimsReductionOp
|
|
|
|
: public ConvertAtenReductionOp<AtenOpT, ConversionFuncT> {
|
|
|
|
public:
|
|
|
|
using ConvertAtenReductionOp<AtenOpT,
|
|
|
|
ConversionFuncT>::ConvertAtenReductionOp;
|
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
|
|
|
LogicalResult readReduceDimsAndKeepDims(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter,
|
|
|
|
ElementsAttr &reduceDimsAttr,
|
2022-01-08 02:57:54 +08:00
|
|
|
bool &keepDims) const override {
|
2022-12-08 04:20:41 +08:00
|
|
|
auto self = adaptor.getSelf();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfTy = cast<RankedTensorType>(self.getType());
|
2021-12-03 08:52:01 +08:00
|
|
|
|
|
|
|
// Select all dims to reduce
|
|
|
|
SmallVector<int64_t, 4> reduceDims;
|
|
|
|
for (int64_t i = 0; i < selfTy.getRank(); i++)
|
|
|
|
reduceDims.push_back(i);
|
|
|
|
int64_t N = selfTy.getRank();
|
|
|
|
auto reduceDimsType = RankedTensorType::get({N}, rewriter.getI64Type());
|
2023-01-25 09:29:42 +08:00
|
|
|
reduceDimsAttr =
|
|
|
|
DenseIntElementsAttr::get(reduceDimsType, llvm::ArrayRef(reduceDims));
|
2021-12-03 08:52:01 +08:00
|
|
|
keepDims = false;
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2021-12-16 03:01:01 +08:00
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenArgmaxOp>::matchAndRewrite(
|
|
|
|
AtenArgmaxOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
2022-12-08 04:20:41 +08:00
|
|
|
Value self = adaptor.getSelf();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfTy = cast<RankedTensorType>(self.getType());
|
2021-12-16 03:01:01 +08:00
|
|
|
|
|
|
|
if (!selfTy)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only ranked tensor types supported in TOSA argmax");
|
2021-12-16 03:01:01 +08:00
|
|
|
|
|
|
|
int64_t reduceDim;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getDim(), m_TorchConstantInt(&reduceDim))) {
|
2021-12-16 03:01:01 +08:00
|
|
|
// NoneType indicates reduce on all dims
|
|
|
|
reduceDim = -1;
|
2023-04-07 19:49:35 +08:00
|
|
|
} else {
|
|
|
|
int64_t inputRank = selfTy.getRank();
|
|
|
|
reduceDim = toPositiveDim(reduceDim, inputRank);
|
|
|
|
if (!isValidDim(reduceDim, inputRank))
|
2023-05-10 23:25:58 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"reduce dim is statically invalid");
|
2021-12-16 03:01:01 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
bool keepDim = false;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getKeepdim(), m_TorchConstantBool(&keepDim)))
|
2021-12-16 03:01:01 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "non-const keepdim parameter unsupported");
|
|
|
|
|
2024-05-31 14:45:13 +08:00
|
|
|
auto resultTy = cast<RankedTensorType>(
|
|
|
|
getTypeConverter()->convertType(op.getResult().getType()));
|
2021-12-16 03:01:01 +08:00
|
|
|
auto outputETy = resultTy.getElementType();
|
|
|
|
|
|
|
|
// Create a single instance of tosa.argmax.
|
|
|
|
// Multiple dims require chained construct.
|
|
|
|
auto buildArgmax = [&](int64_t reduceDim, Value input) -> Value {
|
2024-04-28 05:00:56 +08:00
|
|
|
auto inputTy = cast<RankedTensorType>(input.getType());
|
2022-11-29 20:33:31 +08:00
|
|
|
auto inputShape = makeShapeTorchCompatible(inputTy.getShape());
|
2021-12-16 03:01:01 +08:00
|
|
|
SmallVector<int64_t> outputShapeArr = {};
|
|
|
|
int32_t i = 0;
|
|
|
|
|
|
|
|
for (auto &dim : inputShape) {
|
|
|
|
if (i++ != reduceDim) {
|
|
|
|
outputShapeArr.push_back(dim);
|
|
|
|
} else {
|
|
|
|
if (keepDim)
|
|
|
|
outputShapeArr.push_back(1);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Tosa argmax output is i32, while Torch backend mandates i64.
|
|
|
|
auto outputReduceTy = RankedTensorType::get(
|
2022-11-29 20:33:31 +08:00
|
|
|
makeShapeLLVMCompatible(ArrayRef<int64_t>(outputShapeArr)),
|
|
|
|
rewriter.getI32Type());
|
2021-12-16 03:01:01 +08:00
|
|
|
auto reduceDimAttr =
|
|
|
|
rewriter.getIntegerAttr(rewriter.getI64Type(), reduceDim);
|
|
|
|
return rewriter
|
|
|
|
.create<tosa::ArgMaxOp>(op->getLoc(),
|
|
|
|
getTypeConverter()->convertType(outputReduceTy),
|
|
|
|
input, reduceDimAttr)
|
|
|
|
.getResult();
|
|
|
|
};
|
|
|
|
|
|
|
|
// Convert the final index to i64 for backend finalization, However, i64
|
|
|
|
// is not a defined type for tosa.cast, so using arith.extsi instead.
|
|
|
|
auto castToInt64 = [&](Value result) -> LogicalResult {
|
2024-04-28 05:00:56 +08:00
|
|
|
auto resTy = cast<ShapedType>(result.getType());
|
2021-12-16 03:01:01 +08:00
|
|
|
if (!resTy)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Argmax: Result is not a shaped type");
|
2021-12-16 03:01:01 +08:00
|
|
|
|
2022-11-29 20:33:31 +08:00
|
|
|
auto resShape = makeShapeTorchCompatible(resTy.getShape());
|
|
|
|
auto outTy =
|
|
|
|
RankedTensorType::get(makeShapeLLVMCompatible(resShape), outputETy);
|
2021-12-16 03:01:01 +08:00
|
|
|
|
|
|
|
rewriter.replaceOpWithNewOp<arith::ExtSIOp>(
|
|
|
|
op, getTypeConverter()->convertType(outTy), result);
|
|
|
|
|
|
|
|
return success();
|
|
|
|
};
|
|
|
|
|
|
|
|
if (reduceDim == -1) { // reducing on all dims
|
|
|
|
Value input = self;
|
|
|
|
for (int dim = 0; dim < selfTy.getRank(); dim++) {
|
|
|
|
// progressively reduce each 0-th dim
|
|
|
|
input = buildArgmax(0, input);
|
|
|
|
}
|
|
|
|
return castToInt64(input);
|
|
|
|
} else {
|
|
|
|
return castToInt64(buildArgmax(reduceDim, self));
|
|
|
|
}
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2022-01-07 00:31:29 +08:00
|
|
|
template <typename AtenOpT>
|
|
|
|
class ConvertAtenSqueezeOp : public OpConversionPattern<AtenOpT> {
|
|
|
|
public:
|
|
|
|
using OpConversionPattern<AtenOpT>::OpConversionPattern;
|
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
2021-12-16 13:40:29 +08:00
|
|
|
|
2022-01-07 00:31:29 +08:00
|
|
|
// Each variant must implement corresponding parameter parsing options
|
|
|
|
virtual LogicalResult
|
|
|
|
generateSqueezedShape(AtenOpT op, RankedTensorType selfTy,
|
|
|
|
ConversionPatternRewriter &rewriter,
|
|
|
|
SmallVector<int64_t> &squeezedShape) const {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Unimplemented dim/dim-list parsing function");
|
|
|
|
}
|
2021-12-16 13:40:29 +08:00
|
|
|
|
2022-01-07 00:31:29 +08:00
|
|
|
// Common rewriter for all squeeze ops, calls the specific implementation of
|
|
|
|
// generateSqueezedShape() needed for the op variant.
|
2022-01-08 02:57:54 +08:00
|
|
|
LogicalResult
|
|
|
|
matchAndRewrite(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const override {
|
2022-12-08 04:20:41 +08:00
|
|
|
Value self = adaptor.getSelf();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfTy = cast<RankedTensorType>(self.getType());
|
2022-01-07 00:31:29 +08:00
|
|
|
|
|
|
|
if (!selfTy)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only ranked tensor types supported in TOSA argmax");
|
2022-01-07 00:31:29 +08:00
|
|
|
|
|
|
|
SmallVector<int64_t> newOutputShape;
|
|
|
|
if (failed(generateSqueezedShape(op, selfTy, rewriter, newOutputShape)))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Squeeze could not compute new shape");
|
2022-01-07 00:31:29 +08:00
|
|
|
|
2024-05-31 14:45:13 +08:00
|
|
|
auto resultTy = cast<RankedTensorType>(
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
op.getResult().getType()));
|
2022-01-07 00:31:29 +08:00
|
|
|
auto resultElemTy = resultTy.getElementType();
|
2021-12-16 13:40:29 +08:00
|
|
|
|
2022-11-29 20:33:31 +08:00
|
|
|
auto newOutputTy = RankedTensorType::get(
|
|
|
|
makeShapeLLVMCompatible(newOutputShape), resultElemTy);
|
2021-12-16 13:40:29 +08:00
|
|
|
|
2022-01-07 00:31:29 +08:00
|
|
|
auto reshapeOp = rewriter.create<tosa::ReshapeOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
newOutputTy),
|
2023-01-11 07:07:19 +08:00
|
|
|
self, rewriter.getDenseI64ArrayAttr(newOutputShape));
|
2022-01-07 00:31:29 +08:00
|
|
|
rewriter.replaceOpWithNewOp<tensor::CastOp>(
|
|
|
|
op,
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
newOutputTy),
|
|
|
|
reshapeOp);
|
|
|
|
|
|
|
|
return success();
|
2021-12-16 13:40:29 +08:00
|
|
|
}
|
2022-01-07 00:31:29 +08:00
|
|
|
};
|
2021-12-16 13:40:29 +08:00
|
|
|
|
2022-01-07 00:31:29 +08:00
|
|
|
template <typename AtenOpT>
|
|
|
|
class ConvertAtenSqueezeOneDimOp : public ConvertAtenSqueezeOp<AtenOpT> {
|
|
|
|
using ConvertAtenSqueezeOp<AtenOpT>::ConvertAtenSqueezeOp;
|
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
|
|
|
|
|
|
|
LogicalResult
|
|
|
|
generateSqueezedShape(AtenOpT op, RankedTensorType selfTy,
|
|
|
|
ConversionPatternRewriter &rewriter,
|
2022-01-08 02:57:54 +08:00
|
|
|
SmallVector<int64_t> &squeezedShape) const override {
|
2022-01-07 00:31:29 +08:00
|
|
|
int64_t squeezeDim;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getDim(), m_TorchConstantInt(&squeezeDim)))
|
2022-01-07 00:31:29 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"non-const dim parameter unsupported");
|
2021-12-16 13:40:29 +08:00
|
|
|
|
2022-01-07 00:31:29 +08:00
|
|
|
// Handle negative dim
|
|
|
|
if (squeezeDim < 0)
|
|
|
|
squeezeDim = squeezeDim + selfTy.getRank();
|
2021-12-16 13:40:29 +08:00
|
|
|
|
2022-11-29 20:33:31 +08:00
|
|
|
auto selfShape = makeShapeTorchCompatible(selfTy.getShape());
|
2021-12-16 13:40:29 +08:00
|
|
|
|
2022-01-07 00:31:29 +08:00
|
|
|
// Only dims statically known to have size=1 are reduced.
|
|
|
|
// Dynamic dims are treated as unknowns and will not be squeezed
|
|
|
|
// even if dim parameter says it should be.
|
|
|
|
uint32_t dimNum = 0;
|
|
|
|
for (auto &dim : selfShape) {
|
|
|
|
if (dim != 1 || squeezeDim != dimNum)
|
|
|
|
squeezedShape.push_back(dim);
|
|
|
|
dimNum++;
|
|
|
|
}
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
template <typename AtenOpT>
|
|
|
|
class ConvertAtenSqueezeAllDimsOp : public ConvertAtenSqueezeOp<AtenOpT> {
|
|
|
|
using ConvertAtenSqueezeOp<AtenOpT>::ConvertAtenSqueezeOp;
|
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
|
|
|
|
|
|
|
LogicalResult
|
|
|
|
generateSqueezedShape(AtenOpT op, RankedTensorType selfTy,
|
|
|
|
ConversionPatternRewriter &rewriter,
|
2022-01-08 02:57:54 +08:00
|
|
|
SmallVector<int64_t> &squeezedShape) const override {
|
2022-11-29 20:33:31 +08:00
|
|
|
auto selfShape = makeShapeTorchCompatible(selfTy.getShape());
|
2022-01-07 00:31:29 +08:00
|
|
|
|
|
|
|
// Dims that may dynamically resolve to 1 are not reduced here. Only
|
|
|
|
// compile-time resolvable dims are handled here.
|
|
|
|
for (auto &dim : selfShape) {
|
|
|
|
if (dim != 1)
|
|
|
|
squeezedShape.push_back(dim);
|
|
|
|
}
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
};
|
2021-12-16 13:40:29 +08:00
|
|
|
|
2024-09-21 05:33:55 +08:00
|
|
|
template <typename AtenOpT>
|
|
|
|
class ConvertAtenPowOp : public OpConversionPattern<AtenOpT> {
|
|
|
|
public:
|
|
|
|
using OpConversionPattern<AtenOpT>::OpConversionPattern;
|
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
|
|
|
LogicalResult
|
|
|
|
matchAndRewrite(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const override {
|
2022-01-12 04:49:17 +08:00
|
|
|
|
2024-09-21 05:33:55 +08:00
|
|
|
auto outType =
|
|
|
|
cast<TensorType>(this->getTypeConverter()->convertType(op.getType()));
|
2022-01-12 04:49:17 +08:00
|
|
|
|
2024-09-21 05:33:55 +08:00
|
|
|
Value selfTensor;
|
|
|
|
if constexpr (std::is_same<AtenOpT, AtenPowScalarOp>()) {
|
|
|
|
Value selfScalar = op.getSelf();
|
|
|
|
if (failed(torchScalarToTosaTensor(rewriter, op, selfScalar, selfTensor,
|
|
|
|
outType.getElementType(), {})))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Currently only scalar constants are supported for "
|
|
|
|
"conversion in TOSA PowScalar operation");
|
|
|
|
} else {
|
|
|
|
selfTensor = adaptor.getSelf();
|
|
|
|
auto selfTy = cast<RankedTensorType>(selfTensor.getType());
|
2022-01-12 04:49:17 +08:00
|
|
|
|
2024-09-21 05:33:55 +08:00
|
|
|
if (!selfTy)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only ranked tensor types supported in TOSA Pow");
|
2022-01-12 04:49:17 +08:00
|
|
|
|
2024-09-21 05:33:55 +08:00
|
|
|
if (!isa<mlir::FloatType>(selfTy.getElementType()))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only floating-point datatype legalization supported");
|
|
|
|
}
|
2023-06-16 15:51:24 +08:00
|
|
|
|
2024-09-21 05:33:55 +08:00
|
|
|
Value expTensor;
|
|
|
|
if constexpr (std::is_same<AtenOpT, AtenPowTensorScalarOp>()) {
|
|
|
|
Value expScalar = op.getExponent();
|
|
|
|
if (failed(torchScalarToTosaTensor(rewriter, op, expScalar, expTensor,
|
|
|
|
outType.getElementType(), {})))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Currently only scalar constants are supported for "
|
|
|
|
"conversion in TOSA Pow operation");
|
|
|
|
} else {
|
|
|
|
expTensor = adaptor.getExponent();
|
|
|
|
auto expTy = cast<RankedTensorType>(expTensor.getType());
|
|
|
|
|
|
|
|
if (!expTy)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only ranked tensor types supported in TOSA Pow");
|
|
|
|
}
|
2022-01-12 04:49:17 +08:00
|
|
|
|
2024-09-21 05:33:55 +08:00
|
|
|
auto powOp = tosa::createBinaryOpAndCast<tosa::PowOp>(
|
|
|
|
rewriter, op, outType, selfTensor, expTensor);
|
|
|
|
rewriter.replaceOp(op, powOp.getResult());
|
2022-01-12 04:49:17 +08:00
|
|
|
|
2024-09-21 05:33:55 +08:00
|
|
|
return success();
|
|
|
|
}
|
|
|
|
};
|
2022-01-19 05:37:32 +08:00
|
|
|
|
2022-01-26 00:48:58 +08:00
|
|
|
// Perform the basic n-dim matmul operation encompassing the handling of
|
|
|
|
// broadcasting and dynamic shape propagation.
|
|
|
|
// All PyTorch ops that leverage matrix multiplication will derive this and
|
|
|
|
// implement their specialized input processing (e.g transpose), and output
|
|
|
|
// processing, e.g. GEMM or fully connected bias handling.
|
2022-01-19 05:37:32 +08:00
|
|
|
template <typename AtenOpT>
|
2022-01-26 00:48:58 +08:00
|
|
|
class ConvertAtenMatmulBaseOp : public OpConversionPattern<AtenOpT> {
|
2022-01-19 05:37:32 +08:00
|
|
|
public:
|
|
|
|
using OpConversionPattern<AtenOpT>::OpConversionPattern;
|
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
2022-01-26 00:48:58 +08:00
|
|
|
// Each variant must implement corresponding parameter parsing options.
|
|
|
|
// Maintain separate input read functions for each variant because it is not
|
|
|
|
// necessarily true with all variants that the first two operands are the lhs
|
|
|
|
// and rhs.
|
|
|
|
virtual LogicalResult readMatMulInputs(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter,
|
|
|
|
Value &lhs, Value &rhs) const {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op,
|
|
|
|
"Unimplemented matrix multiplication variant input parsing function");
|
|
|
|
}
|
|
|
|
LogicalResult performMatmul(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter, Value &lhs,
|
|
|
|
Value &rhs, Value &output) const {
|
2022-01-19 05:37:32 +08:00
|
|
|
|
2024-04-28 05:00:56 +08:00
|
|
|
auto lhsTy = cast<RankedTensorType>(lhs.getType());
|
|
|
|
auto rhsTy = cast<RankedTensorType>(rhs.getType());
|
2022-01-19 05:37:32 +08:00
|
|
|
|
|
|
|
auto lhsRank = lhsTy.getRank();
|
|
|
|
auto rhsRank = rhsTy.getRank();
|
|
|
|
|
2022-11-29 20:33:31 +08:00
|
|
|
auto lhsShape = makeShapeTorchCompatible(lhsTy.getShape());
|
|
|
|
auto rhsShape = makeShapeTorchCompatible(rhsTy.getShape());
|
2022-01-19 05:37:32 +08:00
|
|
|
|
|
|
|
auto lhsElemTy = lhsTy.getElementType();
|
|
|
|
auto rhsElemTy = rhsTy.getElementType();
|
|
|
|
|
|
|
|
if (lhsElemTy != rhsElemTy)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Matmul: input datatypes mismatched");
|
2022-01-19 05:37:32 +08:00
|
|
|
|
|
|
|
// Legalization constructs may offer input shapes but expect output shapes
|
|
|
|
// to be inferred, e.g.
|
|
|
|
// func @forward(%arg0: !torch.vtensor<[14,19],f32>,
|
|
|
|
// %arg1: !torch.vtensor<[19,28],f32>) ->
|
|
|
|
// !torch.vtensor<[?,?],f32>
|
|
|
|
// This is tricky with matmul, since TOSA matmul is on 3D inputs.
|
|
|
|
// This means the need to reshape potentially both inputs and outputs,
|
|
|
|
// and reshape to unknown shape is undefined.
|
|
|
|
|
|
|
|
auto maxInputRank = lhsRank > rhsRank ? lhsRank : rhsRank;
|
|
|
|
// If performing dot product on vectors, the RHS is synthetically transposed
|
|
|
|
if (maxInputRank == 1)
|
|
|
|
maxInputRank++;
|
|
|
|
|
|
|
|
// Obtaining the rank broadcasted shapes of tensors makes it easier to
|
|
|
|
// construct the input and output reshaping logic.
|
|
|
|
auto getRankBroadcastedShape = [&](Value tensor,
|
|
|
|
bool isRHS) -> SmallVector<int64_t> {
|
2024-04-28 05:00:56 +08:00
|
|
|
auto tensorTy = cast<TensorType>(tensor.getType());
|
2022-11-29 20:33:31 +08:00
|
|
|
auto tensorShape = makeShapeTorchCompatible(tensorTy.getShape());
|
2022-01-19 05:37:32 +08:00
|
|
|
auto tensorRank = tensorTy.getRank();
|
|
|
|
|
|
|
|
SmallVector<int64_t> bcastedShape;
|
|
|
|
|
|
|
|
auto bcastDims = maxInputRank - tensorRank;
|
|
|
|
|
|
|
|
if (isRHS && (tensorRank == 1) && bcastDims) {
|
|
|
|
// RHS with rank1 is special. It be synthetically transposed to dim[:-2]
|
|
|
|
for (int32_t i = 0; i < bcastDims - 1; i++)
|
|
|
|
bcastedShape.push_back(1);
|
|
|
|
bcastedShape.push_back(tensorShape[0]);
|
|
|
|
bcastedShape.push_back(1);
|
|
|
|
} else {
|
|
|
|
if (bcastDims > 0) { // rank broadcast
|
|
|
|
for (uint32_t i = 0; i < bcastDims; i++)
|
|
|
|
bcastedShape.push_back(1);
|
|
|
|
}
|
|
|
|
for (auto &dim : tensorShape)
|
|
|
|
bcastedShape.push_back(dim);
|
|
|
|
}
|
|
|
|
return bcastedShape;
|
|
|
|
};
|
|
|
|
|
|
|
|
// Step: Rank broadcast the two inputs.
|
|
|
|
auto lhsBroadcastedShape = getRankBroadcastedShape(lhs, false);
|
2022-11-29 20:33:31 +08:00
|
|
|
auto lhsBroadcastedTy = RankedTensorType::get(
|
|
|
|
makeShapeLLVMCompatible(lhsBroadcastedShape), lhsElemTy);
|
2022-01-19 05:37:32 +08:00
|
|
|
auto rhsBroadcastedShape = getRankBroadcastedShape(rhs, true);
|
2022-11-29 20:33:31 +08:00
|
|
|
auto rhsBroadcastedTy = RankedTensorType::get(
|
|
|
|
makeShapeLLVMCompatible(rhsBroadcastedShape), rhsElemTy);
|
2022-01-19 05:37:32 +08:00
|
|
|
|
|
|
|
auto rankBroadcastedLhs =
|
|
|
|
lhsRank == maxInputRank
|
|
|
|
? lhs
|
|
|
|
: rewriter.create<tosa::ReshapeOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
lhsBroadcastedTy),
|
2023-01-11 07:07:19 +08:00
|
|
|
lhs, rewriter.getDenseI64ArrayAttr(lhsBroadcastedShape));
|
2022-01-19 05:37:32 +08:00
|
|
|
|
|
|
|
auto rankBroadcastedRhs =
|
|
|
|
rhsRank == maxInputRank
|
|
|
|
? rhs
|
|
|
|
: rewriter.create<tosa::ReshapeOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
rhsBroadcastedTy),
|
2023-01-11 07:07:19 +08:00
|
|
|
rhs, rewriter.getDenseI64ArrayAttr(rhsBroadcastedShape));
|
2022-01-19 05:37:32 +08:00
|
|
|
|
|
|
|
// TOSA matmul is performed on two 3D inputs and generates a 3D output.
|
|
|
|
// Lower ranked tensors are dim-1 reshaped up to 3D
|
|
|
|
auto reshapeUpTo3DTensor = [&](Value tensor) -> Value {
|
2024-04-28 05:00:56 +08:00
|
|
|
auto tensorTy = cast<TensorType>(tensor.getType());
|
2022-01-19 05:37:32 +08:00
|
|
|
auto rank = tensorTy.getRank();
|
|
|
|
|
|
|
|
assert(rank <= 3 && "reshapeUpTo3D tensor must receive rank <= 3");
|
|
|
|
if (rank == 3)
|
|
|
|
return tensor;
|
|
|
|
|
2022-11-29 20:33:31 +08:00
|
|
|
auto shape = makeShapeTorchCompatible(tensorTy.getShape());
|
2022-01-19 05:37:32 +08:00
|
|
|
SmallVector<int64_t> newShape({1, 1, 1});
|
|
|
|
|
|
|
|
if (rank == 2) { // batchsize = 1
|
|
|
|
newShape[1] = shape[0];
|
|
|
|
newShape[2] = shape[1];
|
|
|
|
} else { // rank 1
|
|
|
|
newShape[2] = shape[0];
|
|
|
|
}
|
2022-11-29 20:33:31 +08:00
|
|
|
auto newType = RankedTensorType::get(makeShapeLLVMCompatible(newShape),
|
|
|
|
tensorTy.getElementType());
|
2022-01-19 05:37:32 +08:00
|
|
|
|
|
|
|
return rewriter.create<tosa::ReshapeOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
newType),
|
2023-01-11 07:07:19 +08:00
|
|
|
tensor, rewriter.getDenseI64ArrayAttr(newShape));
|
2022-01-19 05:37:32 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
// Where broadcasting is required in one or more batch dims, the following
|
|
|
|
// is done.
|
|
|
|
// Where all batch dims are involved in broadcasting:
|
|
|
|
// Given A: 3x1x5x6 and B: 1x4x6x7
|
|
|
|
// 1. Reshape A to 1x15x6 (squeeze all batchdims into dim1)
|
|
|
|
// 2. Transpose B to 6x1x4x7, Reshape to 1x6x28
|
|
|
|
// 3. tosa.Matmul 1x15x6 1x6x28 = 1x15x28
|
|
|
|
// 4. Reshape out to 3x5x4x7, Transpose to 3x4x5x7
|
|
|
|
// Where there are batch dimensions that are broadcast and not, the
|
|
|
|
// treatment is to have dim0 correspond to product of all non-broadcast
|
|
|
|
// dimsizes:
|
|
|
|
// Given A: 4x8x16x32 B: 8x32x17
|
|
|
|
// 1. Reshape A to 8x64x32 (squeeze all unbroadcasted dims into dim0,
|
|
|
|
// broadcasted dims into dim1)
|
|
|
|
// 2. No transpose or reshape of B as its batchdims are not broadcast to.
|
|
|
|
// 3. tosa.Matmul 8x64x32 8x32x17 = 8x64x17
|
|
|
|
// 4. Reshape to 8x4x16x17, Transpose to 4x8x16x17
|
|
|
|
|
|
|
|
// Check if we need to perform the broadcast on batch dim
|
|
|
|
// Not needed if max rank < 3, or if maxrank == 3 and dim[0] matches
|
|
|
|
auto needsBatchDimBroadcast = [&]() -> bool {
|
|
|
|
if (maxInputRank < 3) {
|
|
|
|
return false;
|
|
|
|
} else {
|
|
|
|
if (maxInputRank == 3 &&
|
|
|
|
lhsBroadcastedShape[0] == rhsBroadcastedShape[0]) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
auto performBatchDimBroadcast = needsBatchDimBroadcast();
|
|
|
|
|
|
|
|
// Inputs to the tosa.matmul
|
|
|
|
Value matmulLhs, matmulRhs;
|
|
|
|
|
|
|
|
using TensorShape_t = struct {
|
|
|
|
int64_t dim;
|
|
|
|
int64_t shape;
|
|
|
|
};
|
|
|
|
|
|
|
|
// Transpose needs to done if transposeDims are not non-monotonically
|
|
|
|
// increasing. E.g. [0, 1, 2, 3]: No transpose [1, 0, 2, 3]: Transpose dim0
|
|
|
|
// and dim1 The order need not be sequential, since one or more dims may
|
|
|
|
// have been removed due to broadcasting.
|
|
|
|
auto isTransposeRequired = [](SmallVector<int32_t> transposedDims) -> bool {
|
|
|
|
int32_t lastDim = -1;
|
|
|
|
for (auto &dim : transposedDims) {
|
|
|
|
if (lastDim > dim)
|
|
|
|
return true;
|
|
|
|
lastDim = dim;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
};
|
|
|
|
|
2024-02-29 01:46:58 +08:00
|
|
|
SmallVector<TensorShape_t> batchElems, lhsSqueezedElems, rhsSqueezedElems;
|
2022-01-19 05:37:32 +08:00
|
|
|
|
|
|
|
if (!performBatchDimBroadcast) {
|
|
|
|
// Simple with no broadcasting artifacts. Just reshape up to 3D
|
|
|
|
matmulLhs = reshapeUpTo3DTensor(rankBroadcastedLhs);
|
|
|
|
matmulRhs = reshapeUpTo3DTensor(rankBroadcastedRhs);
|
|
|
|
|
|
|
|
} else {
|
|
|
|
// In this case, either or both input matrices involve broadcasting on
|
|
|
|
// their batch dimensions. For example:
|
|
|
|
// 4x5x6, 1x6x7 -> 4x5x7
|
|
|
|
// 4x1x5x6, 1x3x6x7 -> 4x3x5x7
|
|
|
|
// Though maxInputRank is necessarily >=3 here, individual matrices may be
|
|
|
|
// lower rank.
|
|
|
|
// E.g. 3x4x5x6, 6 -> 3x4x5
|
|
|
|
|
|
|
|
// These are the accumulated products of the shape of each dim:
|
|
|
|
// 1. common dimensions: upper dimensions (dims other than two rightmost)
|
|
|
|
// whose shapes are the same for both LHS and RHS.
|
|
|
|
// 2. LHS squeezed dimensions: all dimensions of LHS that involve
|
|
|
|
// broadcasting in either direction, plus the LHS[-2] shape
|
|
|
|
// 3. RHS squeezed dimensions: all dimensions of RHS that involve
|
|
|
|
// broadcasting in either direction, plus the RHS[-1] shape
|
|
|
|
int64_t commonValue = 1, lhsSqueezedValue = 1, rhsSqueezedValue = 1;
|
|
|
|
|
|
|
|
// For both LHS and RHS, the dimensions are separated into the common,
|
|
|
|
// squeezed and remaining dim. E.g. given
|
|
|
|
// LHS = 3x4x5x6
|
|
|
|
// RHS = 1x4x6x7
|
|
|
|
// common = {{dim=1, shape=4}}
|
|
|
|
// lhs squeezed = {{dim=0, shape=3},
|
|
|
|
// {dim=2, shape=5}}
|
|
|
|
// rhs squeezed = {{dim=0, shape=1},
|
|
|
|
// {dim=2, shape=7}}
|
|
|
|
// The matmul dim is LHS[-1] and RHS[-2], i.e. 6.
|
|
|
|
// Once this is obtained, LHS and RHS are expressed as:
|
|
|
|
// LHS = {common, lhs_squeezed, matmul_dim}
|
|
|
|
// RHS = {common, matmul_dim, rhs_squeezed}
|
|
|
|
// The matmul is then performed to obtain output:
|
|
|
|
// matmul_out = {common, lhs_squeezed, rhs_squeezed}
|
|
|
|
// Finally, we reshape to 'unsqueeze' the LHS and RHS parts and transpose
|
|
|
|
// them back to their correct positions.
|
|
|
|
|
|
|
|
SmallVector<int64_t> transposedLhsShape;
|
|
|
|
SmallVector<int32_t> transposedLhsDims;
|
|
|
|
|
|
|
|
// Step: generate the common dim/shape information
|
2022-06-16 23:45:10 +08:00
|
|
|
bool hasDynamicDims = false;
|
2022-01-19 05:37:32 +08:00
|
|
|
for (uint32_t dim = 0; dim < maxInputRank - 2; dim++) {
|
2022-01-27 11:16:13 +08:00
|
|
|
bool isDynamicDim = ShapedType::isDynamic(lhsBroadcastedShape[dim]);
|
2022-06-16 23:45:10 +08:00
|
|
|
hasDynamicDims |= isDynamicDim;
|
2022-01-19 05:37:32 +08:00
|
|
|
if (isDynamicDim ||
|
|
|
|
lhsBroadcastedShape[dim] == rhsBroadcastedShape[dim]) {
|
|
|
|
commonValue *= lhsBroadcastedShape[dim];
|
2024-02-29 01:46:58 +08:00
|
|
|
batchElems.push_back({dim, lhsBroadcastedShape[dim]});
|
2022-01-19 05:37:32 +08:00
|
|
|
}
|
|
|
|
}
|
2023-01-11 13:42:07 +08:00
|
|
|
commonValue = commonValue < 0 ? kUnknownSize : commonValue;
|
2022-01-19 05:37:32 +08:00
|
|
|
|
2022-06-16 23:45:10 +08:00
|
|
|
// TODO: Handle the case when there are dynamic batch dimensions.
|
|
|
|
if (hasDynamicDims)
|
2022-11-29 20:33:31 +08:00
|
|
|
commonValue = kUnknownSize;
|
2022-06-16 23:45:10 +08:00
|
|
|
|
2022-01-19 05:37:32 +08:00
|
|
|
// Step: generate the LHS squeezed dim/shape information.
|
|
|
|
for (uint32_t dim = 0; dim < maxInputRank - 2; dim++) {
|
2022-01-27 11:16:13 +08:00
|
|
|
bool isDynamicDim = ShapedType::isDynamic(lhsBroadcastedShape[dim]);
|
2022-01-19 05:37:32 +08:00
|
|
|
if (!isDynamicDim &&
|
|
|
|
lhsBroadcastedShape[dim] != rhsBroadcastedShape[dim]) {
|
|
|
|
lhsSqueezedValue *= lhsBroadcastedShape[dim];
|
|
|
|
lhsSqueezedElems.push_back({dim, lhsBroadcastedShape[dim]});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// including LHS[-2]
|
|
|
|
lhsSqueezedElems.push_back(
|
|
|
|
{maxInputRank - 2, lhsBroadcastedShape[maxInputRank - 2]});
|
|
|
|
lhsSqueezedValue *= lhsBroadcastedShape[maxInputRank - 2];
|
2022-11-29 20:33:31 +08:00
|
|
|
lhsSqueezedValue = lhsSqueezedValue < 0 ? kUnknownSize : lhsSqueezedValue;
|
2022-01-19 05:37:32 +08:00
|
|
|
|
|
|
|
// Step: Create the tosa.transpose array. If this array has a
|
|
|
|
// non-monotonic series of dims, perform transpose.
|
|
|
|
// First the common_elems
|
2024-02-29 01:46:58 +08:00
|
|
|
for (uint32_t i = 0; i < batchElems.size(); i++) {
|
|
|
|
transposedLhsShape.push_back(batchElems[i].shape);
|
|
|
|
transposedLhsDims.push_back(batchElems[i].dim);
|
2022-01-19 05:37:32 +08:00
|
|
|
}
|
|
|
|
// then the lhs_squeezed elems
|
|
|
|
for (uint32_t i = 0; i < lhsSqueezedElems.size(); i++) {
|
|
|
|
transposedLhsShape.push_back(lhsSqueezedElems[i].shape);
|
|
|
|
transposedLhsDims.push_back(lhsSqueezedElems[i].dim);
|
|
|
|
}
|
|
|
|
// then the final dim
|
|
|
|
transposedLhsDims.push_back(maxInputRank - 1);
|
|
|
|
transposedLhsShape.push_back(lhsBroadcastedShape[maxInputRank - 1]);
|
|
|
|
|
|
|
|
bool lhsNeedsTranspose = isTransposeRequired(transposedLhsDims);
|
|
|
|
|
|
|
|
auto lhsReshapeInput = rankBroadcastedLhs;
|
|
|
|
|
|
|
|
if (lhsNeedsTranspose) {
|
2022-11-29 20:33:31 +08:00
|
|
|
auto transposedLhsType = RankedTensorType::get(
|
|
|
|
makeShapeLLVMCompatible(transposedLhsShape), rhsElemTy);
|
2022-01-19 05:37:32 +08:00
|
|
|
|
2022-12-20 18:17:27 +08:00
|
|
|
std::optional<Value> transposedLhsDimsConst =
|
2022-01-19 05:37:32 +08:00
|
|
|
tosa::getConstTensor<int32_t>(
|
|
|
|
rewriter, op,
|
|
|
|
/*vec=*/transposedLhsDims,
|
|
|
|
/*shape=*/{static_cast<int32_t>(transposedLhsDims.size())});
|
|
|
|
|
|
|
|
lhsReshapeInput =
|
|
|
|
rewriter
|
|
|
|
.create<tosa::TransposeOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()
|
|
|
|
->convertType(transposedLhsType),
|
2022-08-09 11:17:35 +08:00
|
|
|
rankBroadcastedLhs, transposedLhsDimsConst.value())
|
2022-01-19 05:37:32 +08:00
|
|
|
.getResult();
|
|
|
|
}
|
|
|
|
|
|
|
|
// LHS = {common, lhs_squeezed, matmul_dim}
|
|
|
|
SmallVector<int64_t> newLhsShape(
|
|
|
|
{1, 1, lhsBroadcastedShape[maxInputRank - 1]});
|
|
|
|
newLhsShape[0] = commonValue;
|
2022-11-29 20:33:31 +08:00
|
|
|
newLhsShape[1] = hasDynamicDims ? kUnknownSize : lhsSqueezedValue;
|
2022-01-19 05:37:32 +08:00
|
|
|
|
2022-11-29 20:33:31 +08:00
|
|
|
auto newLhsType = RankedTensorType::get(
|
|
|
|
makeShapeLLVMCompatible(newLhsShape), lhsElemTy);
|
2022-01-19 05:37:32 +08:00
|
|
|
|
|
|
|
matmulLhs = rewriter.create<tosa::ReshapeOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
newLhsType),
|
2023-01-11 07:07:19 +08:00
|
|
|
lhsReshapeInput, rewriter.getDenseI64ArrayAttr(newLhsShape));
|
2022-01-19 05:37:32 +08:00
|
|
|
|
|
|
|
SmallVector<int64_t> transposedRhsShape;
|
|
|
|
SmallVector<int32_t> transposedRhsDims;
|
|
|
|
|
|
|
|
// Step: Create the RHS transpose sequence
|
|
|
|
// RHS = {common, matmul_dim, rhs_squeezed}
|
|
|
|
// first the common_dims
|
2024-02-29 01:46:58 +08:00
|
|
|
for (uint32_t i = 0; i < batchElems.size(); i++) {
|
|
|
|
transposedRhsShape.push_back(batchElems[i].shape);
|
|
|
|
transposedRhsDims.push_back(batchElems[i].dim);
|
2022-01-19 05:37:32 +08:00
|
|
|
}
|
|
|
|
// The matmul_dim of RHS
|
|
|
|
transposedRhsDims.push_back(maxInputRank - 2);
|
|
|
|
transposedRhsShape.push_back(rhsBroadcastedShape[maxInputRank - 2]);
|
|
|
|
// finally all the rhs_squeeze dims
|
|
|
|
hasDynamicDims = false;
|
|
|
|
for (uint32_t dim = 0; dim < maxInputRank - 2; dim++) {
|
2022-01-27 11:16:13 +08:00
|
|
|
bool isDynamicDim = ShapedType::isDynamic(rhsBroadcastedShape[dim]);
|
2022-01-19 05:37:32 +08:00
|
|
|
hasDynamicDims |= isDynamicDim;
|
|
|
|
if (!isDynamicDim &&
|
|
|
|
rhsBroadcastedShape[dim] != lhsBroadcastedShape[dim]) {
|
|
|
|
rhsSqueezedElems.push_back({dim, rhsBroadcastedShape[dim]});
|
|
|
|
rhsSqueezedValue *= rhsBroadcastedShape[dim];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
rhsSqueezedElems.push_back(
|
|
|
|
{maxInputRank - 1, rhsBroadcastedShape[maxInputRank - 1]});
|
|
|
|
rhsSqueezedValue *= rhsBroadcastedShape[maxInputRank - 1];
|
|
|
|
for (uint32_t i = 0; i < rhsSqueezedElems.size(); i++) {
|
|
|
|
transposedRhsShape.push_back(rhsSqueezedElems[i].shape);
|
|
|
|
transposedRhsDims.push_back(rhsSqueezedElems[i].dim);
|
|
|
|
}
|
|
|
|
|
2022-11-29 20:33:31 +08:00
|
|
|
auto transposedRhsType = RankedTensorType::get(
|
|
|
|
makeShapeLLVMCompatible(transposedRhsShape), rhsElemTy);
|
2022-01-19 05:37:32 +08:00
|
|
|
|
|
|
|
if (hasDynamicDims)
|
2022-11-29 20:33:31 +08:00
|
|
|
rhsSqueezedValue = kUnknownSize;
|
2022-01-19 05:37:32 +08:00
|
|
|
|
2022-11-29 20:33:31 +08:00
|
|
|
SmallVector<int64_t> newRhsShape(
|
|
|
|
{commonValue < 0 ? kUnknownSize : commonValue,
|
|
|
|
rhsBroadcastedShape[maxInputRank - 2], rhsSqueezedValue});
|
|
|
|
auto newRhsType = RankedTensorType::get(
|
|
|
|
makeShapeLLVMCompatible(newRhsShape), rhsElemTy);
|
2022-01-19 05:37:32 +08:00
|
|
|
|
|
|
|
bool rhsNeedsTranspose = isTransposeRequired(transposedRhsDims);
|
|
|
|
|
|
|
|
auto transposedRhsValue = rankBroadcastedRhs;
|
|
|
|
|
|
|
|
if (rhsNeedsTranspose) {
|
2022-12-20 18:17:27 +08:00
|
|
|
std::optional<Value> transposedRhsDimsConst =
|
2022-01-19 05:37:32 +08:00
|
|
|
tosa::getConstTensor<int32_t>(
|
|
|
|
rewriter, op,
|
|
|
|
/*vec=*/transposedRhsDims,
|
|
|
|
/*shape=*/{static_cast<int32_t>(transposedRhsDims.size())});
|
|
|
|
|
|
|
|
transposedRhsValue =
|
|
|
|
rewriter
|
|
|
|
.create<tosa::TransposeOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()
|
|
|
|
->convertType(transposedRhsType),
|
2022-08-09 11:17:35 +08:00
|
|
|
rankBroadcastedRhs, transposedRhsDimsConst.value())
|
2022-01-19 05:37:32 +08:00
|
|
|
.getResult();
|
|
|
|
}
|
|
|
|
|
|
|
|
// reshape
|
|
|
|
matmulRhs = rewriter.create<tosa::ReshapeOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
newRhsType),
|
2023-01-11 07:07:19 +08:00
|
|
|
transposedRhsValue, rewriter.getDenseI64ArrayAttr(newRhsShape));
|
2022-01-19 05:37:32 +08:00
|
|
|
}
|
|
|
|
|
2022-11-29 20:33:31 +08:00
|
|
|
auto matmulLhsShape = makeShapeTorchCompatible(
|
2024-04-28 05:00:56 +08:00
|
|
|
cast<RankedTensorType>(matmulLhs.getType()).getShape());
|
2022-11-29 20:33:31 +08:00
|
|
|
auto matmulRhsShape = makeShapeTorchCompatible(
|
2024-04-28 05:00:56 +08:00
|
|
|
cast<RankedTensorType>(matmulRhs.getType()).getShape());
|
2022-01-19 05:37:32 +08:00
|
|
|
|
|
|
|
// The reshape/transpose should ensure the tosa.matmul always has same
|
|
|
|
// batch size for either matrix. If if shapes are dynamic, they'll be
|
|
|
|
// appropriately handled.
|
|
|
|
assert(matmulLhsShape[0] == matmulRhsShape[0] &&
|
|
|
|
"tosa.matmul needs same batchsize on LHS and RHS");
|
|
|
|
|
|
|
|
SmallVector<int64_t> matmulOutputShape(
|
|
|
|
{matmulLhsShape[0], matmulLhsShape[1], matmulRhsShape[2]});
|
|
|
|
Type outputElemTy;
|
2024-04-11 21:47:35 +08:00
|
|
|
if (isa<mlir::FloatType>(lhsElemTy)) {
|
2022-01-19 05:37:32 +08:00
|
|
|
outputElemTy = lhsElemTy;
|
|
|
|
} else { // qint8 emits i32 matmul output
|
|
|
|
outputElemTy = rewriter.getIntegerType(32);
|
|
|
|
}
|
|
|
|
|
2022-11-29 20:33:31 +08:00
|
|
|
auto mmOutputTy = RankedTensorType::get(
|
|
|
|
makeShapeLLVMCompatible(matmulOutputShape), outputElemTy);
|
2022-01-19 05:37:32 +08:00
|
|
|
auto mmOpResult =
|
|
|
|
rewriter
|
|
|
|
.create<tosa::MatMulOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
mmOutputTy),
|
|
|
|
matmulLhs, matmulRhs)
|
|
|
|
.getResult();
|
|
|
|
|
2022-07-07 08:24:16 +08:00
|
|
|
// Perform the reshape to output shape. This is always required unless max
|
2022-07-14 01:10:18 +08:00
|
|
|
// input rank=3 and there was no broadcasting, in which case the tosa.matmul
|
|
|
|
// output itself is correctly shaped.
|
|
|
|
bool performOpReshape = !(maxInputRank == 3 && !performBatchDimBroadcast);
|
2022-01-19 05:37:32 +08:00
|
|
|
|
|
|
|
if (performOpReshape) {
|
|
|
|
// Since the output shape may be unknown, we construct it
|
|
|
|
// independently and reshape. Otherwise reshape may be expressed for
|
|
|
|
// an unknown to-be-inferred output shape. The final tensor.cast
|
|
|
|
// reshapes the known shape to the desired output shape.
|
|
|
|
auto computeOpShape = [&](SmallVector<int64_t> &reshapedOpShape,
|
|
|
|
SmallVector<int32_t> &transposedOpDims,
|
|
|
|
SmallVector<int64_t> &transposedOpShapes) {
|
|
|
|
if (maxInputRank == 1)
|
|
|
|
return;
|
|
|
|
|
|
|
|
if (maxInputRank == 2) {
|
|
|
|
if (lhsRank == 2)
|
|
|
|
reshapedOpShape.push_back(lhsShape[0]);
|
|
|
|
if (rhsRank == 2)
|
|
|
|
reshapedOpShape.push_back(rhsShape[1]);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Step: Construct the output transpose/reshape information
|
|
|
|
// First the common_dims
|
2024-02-29 01:46:58 +08:00
|
|
|
for (uint32_t i = 0; i < batchElems.size(); i++) {
|
|
|
|
reshapedOpShape.push_back(batchElems[i].shape);
|
|
|
|
transposedOpDims.push_back(batchElems[i].dim);
|
2022-01-19 05:37:32 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Then the LHS squeezed dims
|
|
|
|
for (uint32_t i = 0; i < lhsSqueezedElems.size() - 1; i++) {
|
|
|
|
// Only dims that don't broadcast - broadcasting ones come from the
|
|
|
|
// other input.
|
|
|
|
if (lhsSqueezedElems[i].shape != 1) {
|
|
|
|
reshapedOpShape.push_back(lhsSqueezedElems[i].shape);
|
|
|
|
transposedOpDims.push_back(lhsSqueezedElems[i].dim);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// The last squeezed dim is lhs[-2] which needs to be
|
|
|
|
// checked separately for broadcasting
|
|
|
|
if (lhsRank > 1) {
|
|
|
|
reshapedOpShape.push_back(lhsBroadcastedShape[maxInputRank - 2]);
|
|
|
|
transposedOpDims.push_back(maxInputRank - 2);
|
|
|
|
}
|
|
|
|
|
|
|
|
// then the RHS squeezed dims except rhs[-1] which is handled like
|
|
|
|
// lhs[-2]
|
|
|
|
for (uint32_t i = 0; i < rhsSqueezedElems.size() - 1; i++) {
|
|
|
|
if (rhsSqueezedElems[i].shape != 1) {
|
|
|
|
reshapedOpShape.push_back(rhsSqueezedElems[i].shape);
|
|
|
|
transposedOpDims.push_back(rhsSqueezedElems[i].dim);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// rhs[-1]
|
|
|
|
if (rhsRank > 1) {
|
|
|
|
reshapedOpShape.push_back(rhsBroadcastedShape[maxInputRank - 1]);
|
|
|
|
transposedOpDims.push_back(maxInputRank - 1);
|
|
|
|
}
|
|
|
|
|
2024-02-29 01:46:58 +08:00
|
|
|
// The transposition order is the inverse of what we actually want,
|
|
|
|
// inversing should fix this:
|
|
|
|
llvm::SmallVector<int> inverseTransposeDims(transposedOpDims.size());
|
|
|
|
for (int i = 0, s = transposedOpDims.size(); i < s; ++i)
|
|
|
|
inverseTransposeDims[transposedOpDims[i]] = i;
|
|
|
|
|
|
|
|
transposedOpDims = inverseTransposeDims;
|
|
|
|
|
2022-01-19 05:37:32 +08:00
|
|
|
// Final transposed output shape construction
|
|
|
|
for (uint32_t i = 0; i < maxInputRank - 2; i++) {
|
|
|
|
if (lhsBroadcastedTy.isDynamicDim(i)) {
|
2022-11-29 20:33:31 +08:00
|
|
|
transposedOpShapes.push_back(kUnknownSize);
|
2022-01-19 05:37:32 +08:00
|
|
|
} else {
|
|
|
|
if (lhsBroadcastedShape[i] == rhsBroadcastedShape[i]) {
|
|
|
|
transposedOpShapes.push_back(lhsBroadcastedShape[i]);
|
|
|
|
} else {
|
|
|
|
transposedOpShapes.push_back(lhsBroadcastedShape[i] == 1
|
|
|
|
? rhsBroadcastedShape[i]
|
|
|
|
: lhsBroadcastedShape[i]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (lhsRank > 1)
|
|
|
|
transposedOpShapes.push_back(lhsBroadcastedShape[maxInputRank - 2]);
|
|
|
|
if (rhsRank > 1)
|
|
|
|
transposedOpShapes.push_back(rhsBroadcastedShape[maxInputRank - 1]);
|
|
|
|
|
|
|
|
return;
|
|
|
|
};
|
|
|
|
|
|
|
|
SmallVector<int64_t> reshapedOpShape, transposedOpShape;
|
|
|
|
SmallVector<int32_t> transposedOpDims;
|
|
|
|
|
|
|
|
computeOpShape(reshapedOpShape, transposedOpDims, transposedOpShape);
|
|
|
|
|
|
|
|
bool opNeedsTranspose = isTransposeRequired(transposedOpDims);
|
|
|
|
|
|
|
|
// Perform reshape
|
2022-11-29 20:33:31 +08:00
|
|
|
auto reshapedOpType = RankedTensorType::get(
|
|
|
|
makeShapeLLVMCompatible(reshapedOpShape), outputElemTy);
|
2022-01-19 05:37:32 +08:00
|
|
|
auto reshapedOp = rewriter.create<tosa::ReshapeOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
reshapedOpType),
|
2023-01-11 07:07:19 +08:00
|
|
|
mmOpResult, rewriter.getDenseI64ArrayAttr(reshapedOpShape));
|
2022-01-19 05:37:32 +08:00
|
|
|
|
|
|
|
if (opNeedsTranspose) {
|
|
|
|
|
2022-12-20 18:17:27 +08:00
|
|
|
std::optional<Value> transposedOpShapeConst =
|
2022-01-19 05:37:32 +08:00
|
|
|
tosa::getConstTensor<int32_t>(
|
|
|
|
rewriter, op,
|
|
|
|
/*vec=*/transposedOpDims,
|
|
|
|
/*shape=*/{static_cast<int32_t>(transposedOpDims.size())});
|
|
|
|
|
2022-11-29 20:33:31 +08:00
|
|
|
auto transposedOpType = RankedTensorType::get(
|
|
|
|
makeShapeLLVMCompatible(transposedOpShape), outputElemTy);
|
2022-08-09 11:17:35 +08:00
|
|
|
output = rewriter
|
|
|
|
.create<tosa::TransposeOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()
|
|
|
|
->convertType(transposedOpType),
|
|
|
|
reshapedOp.getResult(), transposedOpShapeConst.value())
|
|
|
|
.getResult();
|
2022-01-19 05:37:32 +08:00
|
|
|
|
|
|
|
} else {
|
2022-01-26 00:48:58 +08:00
|
|
|
output = reshapedOp.getResult();
|
2022-01-19 05:37:32 +08:00
|
|
|
}
|
|
|
|
} else {
|
2022-01-26 00:48:58 +08:00
|
|
|
output = mmOpResult;
|
2022-01-19 05:37:32 +08:00
|
|
|
}
|
|
|
|
|
2022-01-26 00:48:58 +08:00
|
|
|
return success();
|
|
|
|
}
|
|
|
|
// The default version just reads two inputs, computes output and returns it.
|
|
|
|
// Other versions may add a bias, apply GEMM-style alpha/beta scaling etc.
|
|
|
|
virtual LogicalResult
|
|
|
|
matchAndRewrite(AtenOpT op, OpAdaptor adaptor,
|
2022-01-27 11:16:13 +08:00
|
|
|
ConversionPatternRewriter &rewriter) const override {
|
2022-01-26 00:48:58 +08:00
|
|
|
|
|
|
|
Value lhs, rhs;
|
|
|
|
|
|
|
|
if (failed(readMatMulInputs(op, adaptor, rewriter, lhs, rhs)))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "Failed to read matmul inputs");
|
2022-01-26 00:48:58 +08:00
|
|
|
|
|
|
|
Value output;
|
|
|
|
|
|
|
|
if (failed(performMatmul(op, adaptor, rewriter, lhs, rhs, output)))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Failed to perform matmul operation");
|
2022-01-26 00:48:58 +08:00
|
|
|
|
|
|
|
rewriter.replaceOpWithNewOp<tensor::CastOp>(
|
|
|
|
op,
|
2024-05-31 14:45:13 +08:00
|
|
|
cast<RankedTensorType>(
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
op.getType())),
|
2022-01-26 00:48:58 +08:00
|
|
|
output);
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
// Legalizes the torch.matmul op for general n-dim matmul.
|
|
|
|
template <typename AtenOpT>
|
|
|
|
class ConvertAtenMatMulOp : public ConvertAtenMatmulBaseOp<AtenOpT> {
|
|
|
|
public:
|
|
|
|
using ConvertAtenMatmulBaseOp<AtenOpT>::ConvertAtenMatmulBaseOp;
|
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
|
|
|
LogicalResult readMatMulInputs(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter,
|
|
|
|
Value &lhs, Value &rhs) const override {
|
2022-12-08 04:20:41 +08:00
|
|
|
lhs = adaptor.getSelf();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto lhsTy = cast<RankedTensorType>(lhs.getType());
|
2022-01-26 00:48:58 +08:00
|
|
|
|
2022-12-08 04:20:41 +08:00
|
|
|
rhs = adaptor.getOther();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto rhsTy = cast<RankedTensorType>(rhs.getType());
|
2022-01-26 00:48:58 +08:00
|
|
|
|
|
|
|
if (!lhsTy || !rhsTy)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only ranked tensor types supported in TOSA matmul");
|
2022-01-26 00:48:58 +08:00
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
// Implements handling of aten.mm and aten.bmm ops.
|
|
|
|
template <typename AtenOpT>
|
|
|
|
class ConvertAtenMmOp : public ConvertAtenMatmulBaseOp<AtenOpT> {
|
|
|
|
public:
|
|
|
|
using ConvertAtenMatmulBaseOp<AtenOpT>::ConvertAtenMatmulBaseOp;
|
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
|
|
|
LogicalResult readMatMulInputs(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter,
|
|
|
|
Value &lhs, Value &rhs) const override {
|
|
|
|
|
2022-12-08 04:20:41 +08:00
|
|
|
lhs = adaptor.getSelf();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto lhsTy = cast<RankedTensorType>(lhs.getType());
|
2022-01-26 00:48:58 +08:00
|
|
|
|
2022-12-08 04:20:41 +08:00
|
|
|
rhs = adaptor.getMat2();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto rhsTy = cast<RankedTensorType>(rhs.getType());
|
2022-01-26 00:48:58 +08:00
|
|
|
|
|
|
|
if (!lhsTy || !rhsTy)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only ranked tensor types supported in TOSA matmul");
|
2022-01-26 00:48:58 +08:00
|
|
|
|
|
|
|
auto lhsRank = lhsTy.getRank();
|
|
|
|
auto rhsRank = rhsTy.getRank();
|
|
|
|
|
|
|
|
if (isa<AtenMmOp>(op)) {
|
|
|
|
// Mm takes two 2D tensors.
|
|
|
|
if (lhsRank != 2 || rhsRank != 2)
|
|
|
|
return op.emitError("aten.mm called but matrix rank != 2");
|
|
|
|
} else if (isa<AtenBmmOp>(op)) {
|
|
|
|
// Bmm takes two 3D tensors.
|
|
|
|
if (lhsRank != 3 || rhsRank != 3)
|
|
|
|
return op.emitError("aten.bmm called but matrix rank != 3");
|
|
|
|
}
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
// Implements handling of aten.linear op.
|
|
|
|
template <typename AtenOpT>
|
|
|
|
class ConvertAtenLinearOp : public ConvertAtenMatmulBaseOp<AtenOpT> {
|
|
|
|
public:
|
|
|
|
using ConvertAtenMatmulBaseOp<AtenOpT>::ConvertAtenMatmulBaseOp;
|
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
|
|
|
LogicalResult readMatMulInputs(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter,
|
|
|
|
Value &lhs, Value &rhs) const override {
|
|
|
|
|
2022-12-08 04:20:41 +08:00
|
|
|
lhs = adaptor.getInput();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto lhsTy = cast<RankedTensorType>(lhs.getType());
|
2022-01-26 00:48:58 +08:00
|
|
|
|
2022-12-08 04:20:41 +08:00
|
|
|
rhs = adaptor.getWeight();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto rhsTy = cast<RankedTensorType>(rhs.getType());
|
2022-01-26 00:48:58 +08:00
|
|
|
|
|
|
|
if (!lhsTy || !rhsTy)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only ranked tensor types supported in TOSA matmul");
|
2022-01-26 00:48:58 +08:00
|
|
|
|
|
|
|
auto lhsRank = lhsTy.getRank();
|
|
|
|
auto rhsRank = rhsTy.getRank();
|
|
|
|
|
|
|
|
if (lhsRank != 2 && lhsRank != 3)
|
|
|
|
return op.emitError("aten.Linear called but input rank not 2 or 3");
|
|
|
|
if (rhsRank != 2 && rhsRank != 3)
|
|
|
|
return op.emitError("aten.Linear called but weight rank not 2 or 3");
|
|
|
|
|
|
|
|
// Protection against crash due to unguarded code in TOSA->LinAlg.
|
2022-07-18 09:39:54 +08:00
|
|
|
// TODO: This should be handled in TOSA->LinAlg instead.
|
2022-01-26 00:48:58 +08:00
|
|
|
if (!lhsTy.hasStaticShape() || !rhsTy.hasStaticShape())
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "aten.Linear needs statically shaped input");
|
2022-01-26 00:48:58 +08:00
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
// Override the default rewriter to perform RHS transpose and bias addition as
|
|
|
|
// well.
|
|
|
|
LogicalResult
|
|
|
|
matchAndRewrite(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const override {
|
|
|
|
|
|
|
|
Value lhs, rhs;
|
|
|
|
|
|
|
|
if (failed(readMatMulInputs(op, adaptor, rewriter, lhs, rhs)))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "Failed to read matmul inputs");
|
2022-01-26 00:48:58 +08:00
|
|
|
|
|
|
|
// The aten.Linear op has a bias tensor that is added to the matmul output.
|
2022-12-08 04:20:41 +08:00
|
|
|
auto bias = adaptor.getBias();
|
2022-01-26 00:48:58 +08:00
|
|
|
auto biasTy = bias.getType();
|
|
|
|
|
|
|
|
// TOSA does not mandate that elementwise op tensors need to be ranked.
|
2024-04-28 05:00:56 +08:00
|
|
|
if (!isa<Torch::NoneType>(biasTy) && !isa<TensorType>(biasTy))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only tensor types supported in GEMM to TOSA for bias tensor");
|
2022-01-26 00:48:58 +08:00
|
|
|
|
|
|
|
// RHS must have its last two dims transposed prior to matrix
|
|
|
|
// multiplication.
|
2024-04-28 05:00:56 +08:00
|
|
|
auto rhsTy = cast<RankedTensorType>(rhs.getType());
|
2022-01-26 00:48:58 +08:00
|
|
|
auto rhsRank = rhsTy.getRank();
|
2022-11-29 20:33:31 +08:00
|
|
|
auto rhsShape = makeShapeTorchCompatible(rhsTy.getShape());
|
2022-01-26 00:48:58 +08:00
|
|
|
auto rhsElemTy = rhsTy.getElementType();
|
|
|
|
|
|
|
|
// Create a non-const shape array to transpose dims.
|
|
|
|
SmallVector<int64_t> transposedRhsShape;
|
|
|
|
for (auto &shape : rhsShape)
|
|
|
|
transposedRhsShape.push_back(shape);
|
|
|
|
SmallVector<int32_t> transposedRhsDims;
|
|
|
|
for (int32_t i = 0; i < rhsRank; i++)
|
|
|
|
transposedRhsDims.push_back(i);
|
|
|
|
|
|
|
|
// Swap the last two dims.
|
|
|
|
std::swap(transposedRhsShape[rhsRank - 1], transposedRhsShape[rhsRank - 2]);
|
|
|
|
std::swap(transposedRhsDims[rhsRank - 1], transposedRhsDims[rhsRank - 2]);
|
|
|
|
|
2022-12-20 18:17:27 +08:00
|
|
|
std::optional<Value> transposedRhsShapeConst =
|
2022-01-26 00:48:58 +08:00
|
|
|
tosa::getConstTensor<int32_t>(
|
|
|
|
rewriter, op,
|
|
|
|
/*vec=*/transposedRhsDims,
|
|
|
|
/*shape=*/{static_cast<int32_t>(transposedRhsDims.size())});
|
|
|
|
|
2022-11-29 20:33:31 +08:00
|
|
|
auto transposedRhsType = RankedTensorType::get(
|
|
|
|
makeShapeLLVMCompatible(transposedRhsShape), rhsElemTy);
|
2022-01-26 00:48:58 +08:00
|
|
|
rhs = rewriter.create<tosa::TransposeOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
transposedRhsType),
|
2022-08-09 11:17:35 +08:00
|
|
|
rhs, transposedRhsShapeConst.value());
|
2022-01-26 00:48:58 +08:00
|
|
|
|
|
|
|
Value matmulOutput;
|
|
|
|
if (failed(
|
|
|
|
this->performMatmul(op, adaptor, rewriter, lhs, rhs, matmulOutput)))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Failed to perform matmul operation");
|
2022-01-26 00:48:58 +08:00
|
|
|
|
|
|
|
Value matmulPlusBias = matmulOutput;
|
2024-04-28 05:00:56 +08:00
|
|
|
if (!isa<Torch::NoneType>(biasTy)) {
|
2022-01-26 00:48:58 +08:00
|
|
|
// Bias addition broadcasts to the matmul output shape.
|
|
|
|
matmulPlusBias =
|
|
|
|
rewriter
|
|
|
|
.create<tosa::AddOp>(op->getLoc(), matmulOutput.getType(),
|
|
|
|
matmulOutput, bias)
|
|
|
|
.getResult();
|
|
|
|
}
|
|
|
|
|
|
|
|
rewriter.replaceOpWithNewOp<tensor::CastOp>(
|
|
|
|
op,
|
2024-05-31 14:45:13 +08:00
|
|
|
cast<RankedTensorType>(
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
op.getType())),
|
2022-01-26 00:48:58 +08:00
|
|
|
matmulPlusBias);
|
|
|
|
|
2022-01-19 05:37:32 +08:00
|
|
|
return success();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2022-01-21 02:58:30 +08:00
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenRsubScalarOp>::matchAndRewrite(
|
|
|
|
AtenRsubScalarOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
2022-12-08 04:20:41 +08:00
|
|
|
auto self = adaptor.getSelf();
|
|
|
|
auto otherScalar = op.getOther();
|
|
|
|
auto alphaScalar = op.getAlpha();
|
2022-01-21 02:58:30 +08:00
|
|
|
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfTy = cast<RankedTensorType>(self.getType());
|
2022-01-21 02:58:30 +08:00
|
|
|
if (!selfTy)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only ranked tensor types supported in TOSA Rsub");
|
2022-01-21 02:58:30 +08:00
|
|
|
|
|
|
|
Value otherTensor, alphaTensor;
|
|
|
|
|
2022-02-12 04:30:02 +08:00
|
|
|
if (failed(torchScalarToTosaTensor(rewriter, op, otherScalar, otherTensor,
|
|
|
|
selfTy.getElementType(), {})))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Currently only scalar constants are supported for "
|
|
|
|
"conversion in TOSA Rsub operation");
|
2022-01-21 02:58:30 +08:00
|
|
|
|
|
|
|
if (failed(torchAlphaToTosaTensor(rewriter, op.getOperation(), alphaScalar,
|
|
|
|
alphaTensor, selfTy.getElementType(),
|
2022-02-12 04:30:02 +08:00
|
|
|
/*checkForUnity=*/true)))
|
2022-01-21 02:58:30 +08:00
|
|
|
return failure();
|
|
|
|
|
|
|
|
auto multTensor = rewriter.create<tosa::MulOp>(
|
|
|
|
op->getLoc(), getTypeConverter()->convertType(op.getType()), self,
|
2022-02-12 04:30:02 +08:00
|
|
|
alphaTensor, /*shift=*/0);
|
2022-01-21 02:58:30 +08:00
|
|
|
|
|
|
|
rewriter.replaceOpWithNewOp<tosa::SubOp>(
|
|
|
|
op, getTypeConverter()->convertType(op.getType()), otherTensor,
|
|
|
|
multTensor);
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2022-01-27 11:16:13 +08:00
|
|
|
template <>
|
2022-04-08 12:47:57 +08:00
|
|
|
LogicalResult ConvertAtenOp<AtenConvolutionOp>::matchAndRewrite(
|
|
|
|
AtenConvolutionOp op, OpAdaptor adaptor,
|
2022-01-27 11:16:13 +08:00
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
Do not try to legalize transposed convolution (#2721)
Currently transposed convolution is not handled correctly by
`TorchToTosa`. This PR allows transposed convolutions to pass through
the conversion so that they can be handled by other conversion passes
later in a pipeline.
An example input which produces a compilation error is:
```
func.func @forward(%input: !torch.vtensor<[1,64,1,100],f32>) -> !torch.vtensor<[1,64,2,200],f32> {
%true = torch.constant.bool true
%int1 = torch.constant.int 1
%int2 = torch.constant.int 2
%weight = torch.vtensor.literal(dense<0.0> : tensor<64x64x3x3xf32>) : !torch.vtensor<[64,64,3,3],f32>
%bias = torch.vtensor.literal(dense<0.0> : tensor<64xf32>) : !torch.vtensor<[64],f32>
%stride = torch.prim.ListConstruct %int2, %int2 : (!torch.int, !torch.int) -> !torch.list<int>
%int1x1 = torch.prim.ListConstruct %int1, %int1 : (!torch.int, !torch.int) -> !torch.list<int>
%output = torch.aten.convolution %input, %weight, %bias, %stride, %int1x1, %int1x1, %true, %int1x1, %int1 : !torch.vtensor<[1,64,1,100],f32>, !torch.vtensor<[64,64,3,3],f32>, !torch.vtensor<[64],f32>, !torch.list<int>, !torch.list<int>, !torch.list<int>, !torch.bool, !torch.list<int>, !torch.int -> !torch.vtensor<[1,64,2,200],f32>
return %output : !torch.vtensor<[1,64,2,200],f32>
}
```
This MLIR produces an error about a cast operation with a size mismatch
when passed through `torch-to-tosa`:
```
error: 'tensor.cast' op operand type 'tensor<1x64x1x50xf32>' and result type 'tensor<1x64x2x200xf32>' are cast incompatible
```
---------
Co-authored-by: Srinath Avadhanula <srinath.avadhanula@getcruise.com>
2024-01-23 02:57:56 +08:00
|
|
|
bool transposed;
|
|
|
|
if (!matchPattern(op.getTransposed(), m_TorchConstantBool(&transposed)))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Unimplemented: non-constant value for transposed not supported");
|
|
|
|
if (transposed)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Unimplemented: transposed convolution not supported");
|
|
|
|
|
2022-12-08 04:20:41 +08:00
|
|
|
auto input = adaptor.getInput();
|
|
|
|
auto weight = adaptor.getWeight();
|
2022-01-27 11:16:13 +08:00
|
|
|
|
2024-04-28 05:00:56 +08:00
|
|
|
auto inputTy = cast<RankedTensorType>(input.getType());
|
|
|
|
auto weightTy = cast<RankedTensorType>(weight.getType());
|
2024-05-31 14:45:13 +08:00
|
|
|
auto outputTy =
|
|
|
|
cast<RankedTensorType>(getTypeConverter()->convertType(op.getType()));
|
2022-01-27 11:16:13 +08:00
|
|
|
|
|
|
|
if (!inputTy || !weightTy || !outputTy)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Input, weight and output to Convolution must be ranked tensors");
|
2022-01-27 11:16:13 +08:00
|
|
|
|
|
|
|
auto inputElemTy = inputTy.getElementType();
|
|
|
|
auto weightElemTy = weightTy.getElementType();
|
2022-11-29 20:33:31 +08:00
|
|
|
auto inputShape = makeShapeTorchCompatible(inputTy.getShape());
|
|
|
|
auto weightShape = makeShapeTorchCompatible(weightTy.getShape());
|
2022-01-27 11:16:13 +08:00
|
|
|
|
2022-04-08 12:47:57 +08:00
|
|
|
if (inputTy.getRank() != 4)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Unimplemented: only 2D convolutions supported");
|
2022-04-08 12:47:57 +08:00
|
|
|
|
|
|
|
if (!weightTy.hasStaticShape())
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Unimplemented: TOSA only supports static weight");
|
2022-04-08 12:47:57 +08:00
|
|
|
|
2022-01-27 11:16:13 +08:00
|
|
|
// Bias is optional. TOSA mandates a zero tensor here, so construct one if
|
|
|
|
// required.
|
2022-12-08 04:20:41 +08:00
|
|
|
auto bias = adaptor.getBias();
|
2024-04-28 05:00:56 +08:00
|
|
|
if (isa<Torch::NoneType>(adaptor.getBias().getType())) {
|
2022-01-27 11:16:13 +08:00
|
|
|
// TBD: This is only valid for quantized 8-bit. For 16-bit, the bias (and
|
|
|
|
// accumulator) are 48-bit and not 32-bit, and requires the use of APInt to
|
|
|
|
// define a 48-bit int.
|
2024-04-11 21:47:35 +08:00
|
|
|
if (isa<quant::QuantizedType>(inputElemTy)) {
|
2022-01-27 11:16:13 +08:00
|
|
|
SmallVector<int32_t> zeroVec(weightShape[0], 0);
|
|
|
|
bias = tosa::getConstTensor<int32_t>(
|
|
|
|
rewriter, op, zeroVec, {static_cast<int32_t>(weightShape[0])})
|
2022-08-09 11:17:35 +08:00
|
|
|
.value();
|
2022-01-27 11:16:13 +08:00
|
|
|
} else {
|
|
|
|
SmallVector<float> zeroVec(weightShape[0], 0);
|
|
|
|
bias = tosa::getConstTensor<float>(rewriter, op, zeroVec,
|
|
|
|
{static_cast<int32_t>(weightShape[0])})
|
2022-08-09 11:17:35 +08:00
|
|
|
.value();
|
2022-01-27 11:16:13 +08:00
|
|
|
}
|
|
|
|
} else {
|
2024-04-28 05:00:56 +08:00
|
|
|
if (!cast<RankedTensorType>(bias.getType()))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Bias provided but not a ranked tensor");
|
2022-01-27 11:16:13 +08:00
|
|
|
}
|
2023-01-11 13:42:07 +08:00
|
|
|
auto biasElemTy =
|
2024-04-11 21:47:35 +08:00
|
|
|
isa<mlir::FloatType>(inputElemTy) ? inputElemTy : rewriter.getI32Type();
|
2022-01-27 11:16:13 +08:00
|
|
|
|
2023-08-18 23:15:54 +08:00
|
|
|
int64_t groups;
|
|
|
|
if (!matchPattern(op.getGroups(), m_TorchConstantInt(&groups))) {
|
|
|
|
return rewriter.notifyMatchFailure(op, "non-const group size unsupported");
|
|
|
|
} else if (groups != 1 && weightShape[1] != 1) {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "group size must be 1 (convolution) or weight.dim(1) must be 1 "
|
|
|
|
"(depthwise convolution)");
|
|
|
|
}
|
|
|
|
|
2022-01-27 11:16:13 +08:00
|
|
|
SmallVector<int64_t, 2> stride;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(adaptor.getStride(), m_TorchListOfConstantInts(stride)))
|
2022-01-27 11:16:13 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "non-const stride list unsupported");
|
|
|
|
|
|
|
|
SmallVector<int64_t, 2> padding_2d;
|
2023-01-11 13:42:07 +08:00
|
|
|
if (!matchPattern(adaptor.getPadding(),
|
|
|
|
m_TorchListOfConstantInts(padding_2d)))
|
2022-01-27 11:16:13 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"non-const padding list unsupported");
|
|
|
|
// TOSA uses 4D padding {t, b, l, r} while Torch defines 2D padding {t, l}.
|
|
|
|
// The Torch OFM computation uses 2*pad in each spatial direction, implying
|
|
|
|
// the same t=b and l=r values for TOSA.
|
|
|
|
SmallVector<int64_t> padding(
|
|
|
|
{padding_2d[0], padding_2d[0], padding_2d[1], padding_2d[1]});
|
|
|
|
|
|
|
|
SmallVector<int64_t, 2> dilation;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(adaptor.getDilation(), m_TorchListOfConstantInts(dilation)))
|
2022-01-27 11:16:13 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"non-const dilation list unsupported");
|
|
|
|
|
2023-08-18 23:15:54 +08:00
|
|
|
// TOSA works in NHWC and takes OHWI (conv) / HWIM (depthwise conv) weights.
|
|
|
|
// Perform the necessary transformations.
|
2022-12-20 18:17:27 +08:00
|
|
|
std::optional<Value> nchwToNhwcTransposeConst =
|
2022-01-27 11:16:13 +08:00
|
|
|
tosa::getConstTensor<int32_t>(rewriter, op,
|
|
|
|
/*vec=*/{0, 2, 3, 1},
|
|
|
|
/*shape=*/{static_cast<int32_t>(4)});
|
|
|
|
SmallVector<int64_t> transposedInputShape(
|
|
|
|
{inputShape[0], inputShape[2], inputShape[3], inputShape[1]});
|
2022-11-29 20:33:31 +08:00
|
|
|
auto transposedInputType = RankedTensorType::get(
|
|
|
|
makeShapeLLVMCompatible(transposedInputShape), inputElemTy);
|
2022-01-27 11:16:13 +08:00
|
|
|
auto transposedInput =
|
|
|
|
rewriter
|
|
|
|
.create<tosa::TransposeOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
getTypeConverter()->convertType(transposedInputType), input,
|
2022-08-09 11:17:35 +08:00
|
|
|
nchwToNhwcTransposeConst.value())
|
2022-01-27 11:16:13 +08:00
|
|
|
.getResult();
|
|
|
|
|
2023-08-18 23:15:54 +08:00
|
|
|
SmallVector<int64_t> transformedWeightShape;
|
|
|
|
RankedTensorType transformedWeightType;
|
|
|
|
Value transformedWeight;
|
|
|
|
int64_t outputCDim;
|
|
|
|
if (groups == 1) {
|
|
|
|
// full convolution: O(I/G)HW-> OHWI
|
|
|
|
transformedWeightShape = {weightShape[0], weightShape[2], weightShape[3],
|
|
|
|
weightShape[1]};
|
|
|
|
transformedWeightType = RankedTensorType::get(
|
|
|
|
makeShapeLLVMCompatible(transformedWeightShape), weightElemTy);
|
|
|
|
transformedWeight =
|
|
|
|
rewriter
|
|
|
|
.create<tosa::TransposeOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
getTypeConverter()->convertType(transformedWeightType), weight,
|
|
|
|
nchwToNhwcTransposeConst.value())
|
|
|
|
.getResult();
|
|
|
|
outputCDim = transformedWeightShape[0];
|
|
|
|
} else if (weightShape[1] == 1) {
|
|
|
|
// depthwise convolution: O(I/G)HW-> HWIM)
|
|
|
|
// transpose: O(I/G)HW -> HWO(I/G)
|
|
|
|
std::optional<Value> transposeConst =
|
|
|
|
tosa::getConstTensor<int32_t>(rewriter, op,
|
|
|
|
/*vec=*/{2, 3, 0, 1},
|
|
|
|
/*shape=*/{static_cast<int32_t>(4)});
|
|
|
|
SmallVector<int64_t> transposedWeightShape = {
|
|
|
|
weightShape[2], weightShape[3], weightShape[0], weightShape[1]};
|
|
|
|
auto transposedWeightType = RankedTensorType::get(
|
|
|
|
makeShapeLLVMCompatible(transposedWeightShape), weightElemTy);
|
|
|
|
auto transposedWeight =
|
|
|
|
rewriter
|
|
|
|
.create<tosa::TransposeOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
getTypeConverter()->convertType(transposedWeightType), weight,
|
|
|
|
transposeConst.value())
|
|
|
|
.getResult();
|
|
|
|
|
|
|
|
// reshape: HWO(I/G) -> HWIM
|
|
|
|
outputCDim = makeShapeTorchCompatible(outputTy.getShape())[1];
|
|
|
|
if (outputCDim == kUnknownSize) {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "number of output channels must be statically known for "
|
|
|
|
"depthwise convolutions");
|
|
|
|
}
|
|
|
|
transformedWeightShape = {
|
|
|
|
transposedWeightShape[0],
|
|
|
|
transposedWeightShape[1],
|
|
|
|
groups,
|
|
|
|
outputCDim / groups,
|
|
|
|
};
|
|
|
|
transformedWeightType = RankedTensorType::get(
|
|
|
|
makeShapeLLVMCompatible(transformedWeightShape), weightElemTy);
|
|
|
|
transformedWeight =
|
|
|
|
rewriter
|
|
|
|
.create<tosa::ReshapeOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
getTypeConverter()->convertType(transformedWeightType),
|
|
|
|
transposedWeight,
|
|
|
|
rewriter.getDenseI64ArrayAttr(transformedWeightShape))
|
|
|
|
.getResult();
|
|
|
|
} else {
|
|
|
|
llvm_unreachable("Unhandled convolution type");
|
|
|
|
}
|
2022-01-27 11:16:13 +08:00
|
|
|
|
|
|
|
int64_t outputHDim, outputWDim;
|
|
|
|
if (inputTy.hasStaticShape()) {
|
2023-08-18 23:15:54 +08:00
|
|
|
int64_t inputHDim = inputShape[2];
|
|
|
|
int64_t inputWDim = inputShape[3];
|
|
|
|
int64_t weightHDim = weightShape[2];
|
|
|
|
int64_t weightWDim = weightShape[3];
|
|
|
|
outputHDim = (inputHDim + padding[0] + padding[1] -
|
|
|
|
dilation[0] * (weightHDim - 1) - 1) /
|
2022-01-27 11:16:13 +08:00
|
|
|
stride[0] +
|
|
|
|
1;
|
2023-08-18 23:15:54 +08:00
|
|
|
outputWDim = (inputWDim + padding[2] + padding[3] -
|
|
|
|
dilation[1] * (weightWDim - 1) - 1) /
|
2022-01-27 11:16:13 +08:00
|
|
|
stride[1] +
|
|
|
|
1;
|
|
|
|
} else {
|
2022-11-29 20:33:31 +08:00
|
|
|
outputHDim = kUnknownSize;
|
|
|
|
outputWDim = kUnknownSize;
|
2022-01-27 11:16:13 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Output shape is NHWC, to be transposed back to NCHW. Output elemTy for
|
|
|
|
// quantized input is i32, which gets rescaled down to quantized output range.
|
|
|
|
SmallVector<int64_t> outputShape = {transposedInputShape[0], outputHDim,
|
2023-08-18 23:15:54 +08:00
|
|
|
outputWDim, outputCDim};
|
2022-11-29 20:33:31 +08:00
|
|
|
auto convOpTy =
|
|
|
|
RankedTensorType::get(makeShapeLLVMCompatible(outputShape), biasElemTy);
|
2022-01-27 11:16:13 +08:00
|
|
|
|
2023-08-18 23:15:54 +08:00
|
|
|
Value convOpResult;
|
|
|
|
if (groups == 1) {
|
|
|
|
// full convolution
|
|
|
|
convOpResult =
|
|
|
|
rewriter
|
|
|
|
.create<tosa::Conv2DOp>(op->getLoc(),
|
|
|
|
getTypeConverter()->convertType(convOpTy),
|
|
|
|
transposedInput, transformedWeight, bias,
|
|
|
|
rewriter.getDenseI64ArrayAttr(padding),
|
|
|
|
rewriter.getDenseI64ArrayAttr(stride),
|
|
|
|
rewriter.getDenseI64ArrayAttr(dilation))
|
|
|
|
.getResult();
|
|
|
|
} else if (weightShape[1] == 1) {
|
|
|
|
// depthwise convolution
|
|
|
|
convOpResult =
|
|
|
|
rewriter
|
|
|
|
.create<tosa::DepthwiseConv2DOp>(
|
|
|
|
op->getLoc(), getTypeConverter()->convertType(convOpTy),
|
|
|
|
transposedInput, transformedWeight, bias,
|
|
|
|
rewriter.getDenseI64ArrayAttr(padding),
|
|
|
|
rewriter.getDenseI64ArrayAttr(stride),
|
|
|
|
rewriter.getDenseI64ArrayAttr(dilation))
|
|
|
|
.getResult();
|
|
|
|
} else {
|
|
|
|
llvm_unreachable("Unhandled convolution type");
|
|
|
|
}
|
2022-01-27 11:16:13 +08:00
|
|
|
|
2022-12-20 18:17:27 +08:00
|
|
|
std::optional<Value> nhwcToNchwTransposeConst =
|
2022-01-27 11:16:13 +08:00
|
|
|
tosa::getConstTensor<int32_t>(rewriter, op,
|
|
|
|
/*vec=*/{0, 3, 1, 2},
|
|
|
|
/*shape=*/{static_cast<int32_t>(4)});
|
|
|
|
SmallVector<int64_t> transposedOutputShape(
|
|
|
|
{outputShape[0], outputShape[3], outputShape[1], outputShape[2]});
|
2022-11-29 20:33:31 +08:00
|
|
|
auto transposedOutputType = RankedTensorType::get(
|
|
|
|
makeShapeLLVMCompatible(transposedOutputShape), biasElemTy);
|
2022-01-27 11:16:13 +08:00
|
|
|
auto transposedOutput =
|
|
|
|
rewriter
|
|
|
|
.create<tosa::TransposeOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
getTypeConverter()->convertType(transposedOutputType),
|
2022-08-09 11:17:35 +08:00
|
|
|
convOpResult, nhwcToNchwTransposeConst.value())
|
2022-01-27 11:16:13 +08:00
|
|
|
.getResult();
|
|
|
|
|
|
|
|
Value rescaledResult = transposedOutput;
|
2024-04-11 21:47:35 +08:00
|
|
|
if (isa<quant::QuantizedType>(inputElemTy)) {
|
2022-01-27 11:16:13 +08:00
|
|
|
rescaledResult = tosa::buildRescaleOpConvOutput(
|
|
|
|
rewriter, op, transposedOutput, inputTy, weightTy, outputTy);
|
|
|
|
}
|
|
|
|
|
|
|
|
rewriter.replaceOpWithNewOp<tensor::CastOp>(
|
|
|
|
op, getTypeConverter()->convertType(op.getType()), rescaledResult);
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2022-01-28 06:38:59 +08:00
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenReshapeOp>::matchAndRewrite(
|
|
|
|
AtenReshapeOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
2022-12-08 04:20:41 +08:00
|
|
|
auto self = adaptor.getSelf();
|
2022-01-28 06:38:59 +08:00
|
|
|
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfTy = cast<RankedTensorType>(self.getType());
|
2022-01-28 06:38:59 +08:00
|
|
|
if (!selfTy)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only ranked tensor types supported in TOSA Reshape");
|
2022-01-28 06:38:59 +08:00
|
|
|
|
|
|
|
// Check that at most one dimension is -1
|
|
|
|
SmallVector<int64_t> newShape;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getShape(), m_TorchListOfConstantInts(newShape)))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only constant shape supported in TOSA Reshape");
|
2022-01-28 06:38:59 +08:00
|
|
|
|
|
|
|
int auto_sz = 0;
|
2022-11-24 21:02:59 +08:00
|
|
|
for (auto s : newShape)
|
|
|
|
auto_sz += (s == -1 ? 1 : 0);
|
2022-01-28 06:38:59 +08:00
|
|
|
if (auto_sz > 1)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "At most one dimension may be specified as -1 to "
|
|
|
|
"automatically calculate its size");
|
2022-01-28 06:38:59 +08:00
|
|
|
|
2022-11-29 20:33:31 +08:00
|
|
|
auto newType = RankedTensorType::get(makeShapeLLVMCompatible(newShape),
|
|
|
|
selfTy.getElementType());
|
2022-01-28 06:38:59 +08:00
|
|
|
|
|
|
|
rewriter.replaceOpWithNewOp<tosa::ReshapeOp>(
|
|
|
|
op, getTypeConverter()->convertType(newType), self,
|
2023-01-11 07:07:19 +08:00
|
|
|
rewriter.getDenseI64ArrayAttr(newShape));
|
2022-01-28 06:38:59 +08:00
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2022-02-04 06:08:19 +08:00
|
|
|
Value computeBatchNorm(Operation *op, ConversionPatternRewriter &rewriter,
|
|
|
|
Type outType, Value input, Value variance, Value eps,
|
|
|
|
Value mean, Value weight, Value bias) {
|
2022-01-28 06:38:59 +08:00
|
|
|
// For PyTorch:
|
|
|
|
// scale = gamma = weight
|
|
|
|
// offset = beta = bias
|
|
|
|
// Lowering:
|
|
|
|
// fused batchnorm = (input-mean) * scale * rsqrt(var+epsilon)) + offset
|
|
|
|
//
|
|
|
|
// shape_0 = ones(input.rank)
|
|
|
|
// shape_0[input.rank-1] = input.shape[input.rank-1]
|
|
|
|
// shape_1 = ones(1)
|
|
|
|
//
|
|
|
|
// bmean = reshape(mean, shape_0)
|
|
|
|
// bscale = reshape(scale, shape_0)
|
|
|
|
// boffset= reshape(offset, shape_0)
|
|
|
|
// beps = reshape(epsilon, shape_1)
|
|
|
|
//
|
|
|
|
// op1 = sub(input, bmean)
|
|
|
|
// op2 = add(var, beps)
|
|
|
|
// op3 = rsqrt(op2)
|
|
|
|
// bvar = reshape(op3, shape_0)
|
|
|
|
// op4 = mul(op1, bvar)
|
|
|
|
// op5 = mul(op4, bscale)
|
|
|
|
// op6 = add(op5, boffset)
|
|
|
|
|
2022-02-04 06:08:19 +08:00
|
|
|
auto op1SubInputMean =
|
|
|
|
rewriter.create<tosa::SubOp>(op->getLoc(), outType, input, mean);
|
|
|
|
|
|
|
|
auto op2AddVarEpsilon = rewriter.create<tosa::AddOp>(
|
|
|
|
op->getLoc(), variance.getType(), variance, eps);
|
|
|
|
|
|
|
|
auto op3RsqrtOp2 = rewriter.create<tosa::RsqrtOp>(
|
|
|
|
op->getLoc(), variance.getType(), op2AddVarEpsilon.getResult());
|
|
|
|
|
|
|
|
auto op4MulOp1Op3 = rewriter.create<tosa::MulOp>(op->getLoc(), outType,
|
|
|
|
op1SubInputMean.getResult(),
|
|
|
|
op3RsqrtOp2.getResult(), 0);
|
|
|
|
|
|
|
|
auto op5MulOp4Scale = rewriter.create<tosa::MulOp>(
|
|
|
|
op->getLoc(), outType, op4MulOp1Op3.getResult(), weight, 0);
|
|
|
|
|
|
|
|
return rewriter
|
|
|
|
.create<tosa::AddOp>(op->getLoc(), outType, op5MulOp4Scale.getResult(),
|
|
|
|
bias)
|
|
|
|
.getResult();
|
|
|
|
}
|
|
|
|
|
|
|
|
// This lowering is based on the TensorFlow to TOSA lowering.
|
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenBatchNormOp>::matchAndRewrite(
|
|
|
|
AtenBatchNormOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
|
|
|
// Not a ranked tensor output
|
2024-04-28 05:00:56 +08:00
|
|
|
if (!dyn_cast<RankedTensorType>(adaptor.getInput().getType()))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only ranked tensor types are supported");
|
2022-02-04 06:08:19 +08:00
|
|
|
|
|
|
|
auto outType = getTypeConverter()->convertType(op.getType());
|
|
|
|
|
|
|
|
// Note: cudnn_enabled is not handled.
|
|
|
|
|
|
|
|
// FIXME: Handle training and momentum.
|
2024-05-31 14:45:13 +08:00
|
|
|
if (isa<Torch::NoneType>(op.getMomentum().getType()))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "Unsupported None for momentum");
|
2022-02-04 06:08:19 +08:00
|
|
|
|
2024-04-28 05:00:56 +08:00
|
|
|
auto meanType = dyn_cast<TensorType>(adaptor.getRunningMean().getType());
|
|
|
|
auto varianceType = dyn_cast<TensorType>(adaptor.getRunningVar().getType());
|
2022-01-28 06:38:59 +08:00
|
|
|
if (!varianceType || !meanType)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only ranked tensor types are supported");
|
2022-01-28 06:38:59 +08:00
|
|
|
|
2022-02-04 06:08:19 +08:00
|
|
|
// Normalization ops perform elementwise ops of a single mean/stdev value
|
|
|
|
// against the feature map and because input is NCHW, the rank-1 value must be
|
|
|
|
// reshaped so it sits on the same dim as 'C'.
|
|
|
|
auto reshapeToNormInputDim = [&](Operation *op,
|
|
|
|
ConversionPatternRewriter &rewriter,
|
2023-08-16 00:53:28 +08:00
|
|
|
const TypeConverter *converter, Type outType,
|
2022-02-04 06:08:19 +08:00
|
|
|
const Value toBcast, Value &result) {
|
|
|
|
RankedTensorType toBcastType =
|
2024-04-28 05:00:56 +08:00
|
|
|
dyn_cast<RankedTensorType>(toBcast.getType());
|
2022-02-04 06:08:19 +08:00
|
|
|
if (toBcastType.getRank() > 1)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "Rank cannot be more than 1");
|
2022-02-04 06:08:19 +08:00
|
|
|
|
2024-04-11 21:47:35 +08:00
|
|
|
RankedTensorType outTensorType = cast<RankedTensorType>(outType);
|
2022-11-29 20:33:31 +08:00
|
|
|
SmallVector<int64_t> newShape = {
|
|
|
|
makeShapeTorchCompatible(toBcastType.getShape())[0]};
|
2022-02-04 06:08:19 +08:00
|
|
|
for (auto i = 2; i < outTensorType.getRank(); ++i)
|
|
|
|
newShape.push_back(1);
|
2022-11-29 20:33:31 +08:00
|
|
|
auto newType = RankedTensorType::get(makeShapeLLVMCompatible(newShape),
|
|
|
|
outTensorType.getElementType());
|
2022-02-04 06:08:19 +08:00
|
|
|
|
|
|
|
result = rewriter.create<tosa::ReshapeOp>(
|
2023-01-11 07:07:19 +08:00
|
|
|
op->getLoc(), newType, toBcast,
|
|
|
|
rewriter.getDenseI64ArrayAttr(newShape));
|
2022-02-04 06:08:19 +08:00
|
|
|
|
|
|
|
return success();
|
|
|
|
};
|
|
|
|
|
2022-01-28 06:38:59 +08:00
|
|
|
Value meanVal, varianceVal, weightVal, biasVal;
|
|
|
|
assert(meanType.getNumElements() != 0 && varianceType.getNumElements() != 0);
|
|
|
|
if (failed(reshapeToNormInputDim(op.getOperation(), rewriter,
|
|
|
|
getTypeConverter(), outType,
|
2022-12-08 04:20:41 +08:00
|
|
|
adaptor.getRunningMean(), meanVal)))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "Failed to reshape running mean");
|
2022-01-28 06:38:59 +08:00
|
|
|
|
|
|
|
if (failed(reshapeToNormInputDim(op.getOperation(), rewriter,
|
|
|
|
getTypeConverter(), outType,
|
2022-12-08 04:20:41 +08:00
|
|
|
adaptor.getRunningVar(), varianceVal)))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Failed to reshape running variance");
|
2022-01-28 06:38:59 +08:00
|
|
|
|
|
|
|
if (failed(reshapeToNormInputDim(op.getOperation(), rewriter,
|
|
|
|
getTypeConverter(), outType,
|
2022-12-08 04:20:41 +08:00
|
|
|
adaptor.getWeight(), weightVal)))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "Failed to reshape weight");
|
2022-01-28 06:38:59 +08:00
|
|
|
|
|
|
|
if (failed(reshapeToNormInputDim(op.getOperation(), rewriter,
|
2023-01-11 13:42:07 +08:00
|
|
|
getTypeConverter(), outType,
|
|
|
|
adaptor.getBias(), biasVal)))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "Failed to reshape bias");
|
2022-01-28 06:38:59 +08:00
|
|
|
|
|
|
|
double eps;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getEps(), m_TorchConstantFloat(&eps)))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "eps must be a scalar constant");
|
2022-01-28 06:38:59 +08:00
|
|
|
|
2023-09-21 01:48:40 +08:00
|
|
|
auto epsilonConst = tosa::getConstTensor<float>(rewriter, op.getOperation(),
|
|
|
|
{static_cast<float>(eps)}, {},
|
|
|
|
meanType.getElementType())
|
|
|
|
.value();
|
2022-01-28 06:38:59 +08:00
|
|
|
|
2022-02-04 06:08:19 +08:00
|
|
|
auto batchNorm =
|
2022-12-08 04:20:41 +08:00
|
|
|
computeBatchNorm(op, rewriter, outType, adaptor.getInput(), varianceVal,
|
2022-02-04 06:08:19 +08:00
|
|
|
epsilonConst, meanVal, weightVal, biasVal);
|
2022-01-28 06:38:59 +08:00
|
|
|
|
2022-02-04 06:08:19 +08:00
|
|
|
rewriter.replaceOp(op, {batchNorm});
|
2022-01-28 06:38:59 +08:00
|
|
|
|
2022-02-04 06:08:19 +08:00
|
|
|
return success();
|
|
|
|
}
|
2022-01-28 06:38:59 +08:00
|
|
|
|
2022-02-04 06:08:19 +08:00
|
|
|
// This lowering is loosely based on Torch to LinAlg lowering.
|
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenNativeLayerNormOp>::matchAndRewrite(
|
|
|
|
AtenNativeLayerNormOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
2022-01-28 06:38:59 +08:00
|
|
|
|
2022-02-04 06:08:19 +08:00
|
|
|
// The key difference from BatchNorm is that a specified set of dims
|
|
|
|
// (normalized_shape) are chosen to compute the mean and variance from input.
|
|
|
|
// Where as in BatchNorm the mean and variance are operands. tosa::ReduceSumOp
|
|
|
|
// is used to sum up the these dims for mean and for variance. The results
|
|
|
|
// eventually being reshaped for broadcasting.
|
|
|
|
|
|
|
|
// Not a ranked tensor output
|
2024-04-28 05:00:56 +08:00
|
|
|
if (!dyn_cast<RankedTensorType>(adaptor.getInput().getType()))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only ranked tensor types are supported");
|
2022-01-28 06:38:59 +08:00
|
|
|
|
2024-04-28 05:00:56 +08:00
|
|
|
auto inputType = cast<RankedTensorType>(adaptor.getInput().getType());
|
2022-02-04 06:08:19 +08:00
|
|
|
if (inputType.getRank() > 4)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Only up to 4D tensors are supported");
|
2022-02-04 06:08:19 +08:00
|
|
|
|
|
|
|
auto outType = getTypeConverter()->convertType(op.getType(0));
|
|
|
|
|
|
|
|
// Note: cudnn_enabled is not handled.
|
|
|
|
|
|
|
|
// FIXME: Handle the None cases for the optional parameters.
|
2024-05-31 14:45:13 +08:00
|
|
|
if (isa<Torch::NoneType>(adaptor.getWeight().getType()))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "Unsupported None for weight");
|
2024-05-31 14:45:13 +08:00
|
|
|
if (isa<Torch::NoneType>(adaptor.getBias().getType()))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "Unsupported None for bias");
|
2022-02-04 06:08:19 +08:00
|
|
|
|
2024-04-28 05:00:56 +08:00
|
|
|
auto weightType = cast<RankedTensorType>(adaptor.getWeight().getType());
|
|
|
|
auto biasType = cast<RankedTensorType>(adaptor.getBias().getType());
|
2022-02-04 06:08:19 +08:00
|
|
|
int64_t inputRank = inputType.getRank();
|
|
|
|
Type elemTy = inputType.getElementType();
|
2022-11-29 20:33:31 +08:00
|
|
|
SmallVector<int64_t> inputTypeShape(
|
|
|
|
makeShapeTorchCompatible(inputType.getShape()));
|
2022-02-04 06:08:19 +08:00
|
|
|
|
|
|
|
// Check if all the arguments meet the requirements.
|
|
|
|
SmallVector<int64_t> normalizedShapeSizesInt;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getNormalizedShape(),
|
2022-11-17 04:33:12 +08:00
|
|
|
m_TorchListOfConstantInts(normalizedShapeSizesInt))) {
|
2022-02-04 06:08:19 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "Unimplemented normalized_shape not"
|
|
|
|
"constructed from ListConstruct");
|
|
|
|
}
|
|
|
|
int64_t normalizedShapeRank = normalizedShapeSizesInt.size();
|
|
|
|
if (weightType.getRank() != normalizedShapeRank ||
|
|
|
|
biasType.getRank() != normalizedShapeRank ||
|
|
|
|
inputRank < normalizedShapeRank || normalizedShapeRank < 1)
|
|
|
|
return rewriter.notifyMatchFailure(op, "Input or weight or bias shape or"
|
|
|
|
"normalized shape not compatible");
|
|
|
|
|
|
|
|
// Check all the dimensions match the normalized_shape, only static shapes as
|
|
|
|
// of now
|
|
|
|
int64_t meanAndVarShapeRank = inputRank - normalizedShapeSizesInt.size();
|
|
|
|
for (auto en : llvm::enumerate((normalizedShapeSizesInt))) {
|
|
|
|
int64_t index = en.index();
|
|
|
|
int64_t value = en.value();
|
2022-11-29 20:33:31 +08:00
|
|
|
if (inputTypeShape[index + meanAndVarShapeRank] != value ||
|
|
|
|
makeShapeTorchCompatible(weightType.getShape())[index] != value ||
|
|
|
|
makeShapeTorchCompatible(biasType.getShape())[index] != value)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"mismatching contracting dimension");
|
2022-02-04 06:08:19 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Helper for computing mean and variance.
|
|
|
|
auto computeSumAndReshape = [&](Value toReduce, RankedTensorType toReduceType,
|
|
|
|
Type outType, SmallVector<int64_t> outShape) {
|
|
|
|
Value sumDiv = toReduce;
|
2022-11-29 20:33:31 +08:00
|
|
|
SmallVector<int64_t> toReduceShape(
|
|
|
|
makeShapeTorchCompatible(toReduceType.getShape()));
|
2022-10-18 12:22:53 +08:00
|
|
|
for (int64_t i = toReduceShape.size() - 1; i >= meanAndVarShapeRank; i--) {
|
|
|
|
toReduceShape[i] = 1;
|
2022-02-04 06:08:19 +08:00
|
|
|
sumDiv = rewriter.create<tosa::ReduceSumOp>(
|
|
|
|
op.getLoc(),
|
2022-11-29 20:33:31 +08:00
|
|
|
RankedTensorType::get(makeShapeLLVMCompatible(toReduceShape),
|
|
|
|
inputType.getElementType()),
|
2023-09-13 06:09:57 +08:00
|
|
|
sumDiv, rewriter.getI32IntegerAttr(i));
|
2022-02-04 06:08:19 +08:00
|
|
|
}
|
|
|
|
|
2023-01-11 07:07:19 +08:00
|
|
|
return rewriter.create<tosa::ReshapeOp>(
|
|
|
|
op.getLoc(), outType, sumDiv, rewriter.getDenseI64ArrayAttr(outShape));
|
2022-02-04 06:08:19 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
// TOSA has integer Div so, compute reciprocal of element count to be used in
|
|
|
|
// mul.
|
|
|
|
int64_t elemCnt = 1;
|
|
|
|
for (auto i : normalizedShapeSizesInt)
|
|
|
|
elemCnt *= i;
|
|
|
|
|
|
|
|
auto elemCntConst =
|
|
|
|
tosa::getConstTensor<float>(rewriter, op.getOperation(),
|
2023-06-16 15:51:24 +08:00
|
|
|
{static_cast<float>(elemCnt)}, {1}, elemTy)
|
2022-08-09 11:17:35 +08:00
|
|
|
.value();
|
2022-02-04 06:08:19 +08:00
|
|
|
Value elemCntRcp = rewriter.create<tosa::ReciprocalOp>(
|
|
|
|
op.getLoc(), elemCntConst.getType(), elemCntConst);
|
|
|
|
|
|
|
|
// Broadcast type and shape for various intermediate values.
|
|
|
|
SmallVector<int64_t> bcastOutShape;
|
2022-11-29 20:33:31 +08:00
|
|
|
for (auto en : llvm::enumerate(inputTypeShape)) {
|
2022-02-04 06:08:19 +08:00
|
|
|
bcastOutShape.push_back(
|
|
|
|
static_cast<int64_t>(en.index()) >= meanAndVarShapeRank ? 1
|
|
|
|
: en.value());
|
|
|
|
}
|
2022-11-29 20:33:31 +08:00
|
|
|
auto bcastOutType =
|
|
|
|
RankedTensorType::get(makeShapeLLVMCompatible(bcastOutShape), elemTy);
|
2022-02-04 06:08:19 +08:00
|
|
|
|
|
|
|
// Compute mean.
|
2022-12-08 04:20:41 +08:00
|
|
|
Value sum = computeSumAndReshape(adaptor.getInput(), inputType, bcastOutType,
|
2022-02-04 06:08:19 +08:00
|
|
|
bcastOutShape);
|
|
|
|
Value meanVal = rewriter.create<tosa::MulOp>(op.getLoc(), bcastOutType, sum,
|
|
|
|
elemCntRcp, /*shift=*/0);
|
|
|
|
|
|
|
|
// Compute variance.
|
2023-01-11 13:42:07 +08:00
|
|
|
Value squareSumSub = rewriter.create<tosa::SubOp>(
|
|
|
|
op.getLoc(), inputType, adaptor.getInput(), meanVal);
|
2022-02-04 06:08:19 +08:00
|
|
|
Value squareSum = rewriter.create<tosa::MulOp>(op.getLoc(), inputType,
|
|
|
|
squareSumSub, squareSumSub, 0);
|
|
|
|
|
|
|
|
Value squareSumReduced =
|
|
|
|
computeSumAndReshape(squareSum, inputType, bcastOutType, bcastOutShape);
|
|
|
|
Value varianceVal = rewriter.create<tosa::MulOp>(
|
|
|
|
op.getLoc(), bcastOutType, squareSumReduced, elemCntRcp, /*shift=*/0);
|
|
|
|
|
|
|
|
// Reshape weight and bias.
|
|
|
|
SmallVector<int64_t> weightAndBiasBcastShape;
|
2022-11-29 20:33:31 +08:00
|
|
|
for (auto en :
|
|
|
|
llvm::enumerate(makeShapeTorchCompatible(inputType.getShape()))) {
|
2022-02-04 06:08:19 +08:00
|
|
|
weightAndBiasBcastShape.push_back(
|
|
|
|
static_cast<int64_t>(en.index()) < meanAndVarShapeRank ? 1
|
|
|
|
: en.value());
|
|
|
|
}
|
2022-11-29 20:33:31 +08:00
|
|
|
auto weightAndMeanBcastType = RankedTensorType::get(
|
|
|
|
makeShapeLLVMCompatible(weightAndBiasBcastShape), elemTy);
|
2022-01-28 06:38:59 +08:00
|
|
|
|
2022-02-04 06:08:19 +08:00
|
|
|
Value weightVal = rewriter.create<tosa::ReshapeOp>(
|
2022-12-08 04:20:41 +08:00
|
|
|
op.getLoc(), weightAndMeanBcastType, adaptor.getWeight(),
|
2023-01-11 07:07:19 +08:00
|
|
|
rewriter.getDenseI64ArrayAttr(weightAndBiasBcastShape));
|
2022-02-04 06:08:19 +08:00
|
|
|
|
|
|
|
Value biasVal = rewriter.create<tosa::ReshapeOp>(
|
2022-12-08 04:20:41 +08:00
|
|
|
op.getLoc(), weightAndMeanBcastType, adaptor.getBias(),
|
2023-01-11 07:07:19 +08:00
|
|
|
rewriter.getDenseI64ArrayAttr(weightAndBiasBcastShape));
|
2022-02-04 06:08:19 +08:00
|
|
|
|
|
|
|
double eps;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getEps(), m_TorchConstantFloat(&eps)))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "eps must be a scalar constant");
|
2022-02-04 06:08:19 +08:00
|
|
|
auto epsilonConst =
|
2023-06-16 15:51:24 +08:00
|
|
|
tosa::getConstTensor<float>(rewriter, op.getOperation(),
|
|
|
|
{static_cast<float>(eps)}, {}, elemTy)
|
|
|
|
.value();
|
2022-02-04 06:08:19 +08:00
|
|
|
|
|
|
|
// Compute layer norm.
|
|
|
|
auto layerNorm =
|
2022-12-08 04:20:41 +08:00
|
|
|
computeBatchNorm(op, rewriter, outType, adaptor.getInput(), varianceVal,
|
2022-02-04 06:08:19 +08:00
|
|
|
epsilonConst, meanVal, weightVal, biasVal);
|
|
|
|
|
|
|
|
rewriter.replaceOp(op, {layerNorm, meanVal, varianceVal});
|
2022-01-28 06:38:59 +08:00
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2022-01-27 11:16:13 +08:00
|
|
|
// Torch constants are converted to tosa.const .
|
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<ValueTensorLiteralOp>::matchAndRewrite(
|
|
|
|
ValueTensorLiteralOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
2022-09-27 07:54:27 +08:00
|
|
|
|
2024-05-31 14:45:13 +08:00
|
|
|
auto outputTy =
|
|
|
|
cast<RankedTensorType>(getTypeConverter()->convertType(op.getType()));
|
2022-01-27 11:16:13 +08:00
|
|
|
|
2022-09-27 07:54:27 +08:00
|
|
|
// Tensors with integer types need to be converted to signless integer
|
|
|
|
// element type. All tensors with element types other than integer can reuse
|
|
|
|
// existing elements attribute.
|
|
|
|
// TODO: what about unsigned integer?
|
2024-04-28 05:00:56 +08:00
|
|
|
if (auto elements = dyn_cast<DenseIntElementsAttr>(op.getValueAttr())) {
|
2022-09-29 15:47:22 +08:00
|
|
|
if (elements.getElementType().isSignedInteger()) {
|
|
|
|
Type builtinTensorElemTy = outputTy.getElementType();
|
|
|
|
unsigned bitWidth = builtinTensorElemTy.getIntOrFloatBitWidth();
|
2022-09-27 07:54:27 +08:00
|
|
|
DenseElementsAttr valueAttr =
|
|
|
|
elements.mapValues(builtinTensorElemTy, [&](const APInt &v) {
|
|
|
|
return APInt(bitWidth, v.getSExtValue());
|
|
|
|
});
|
|
|
|
rewriter.replaceOpWithNewOp<tosa::ConstOp>(op, outputTy, valueAttr);
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
}
|
2022-12-08 04:20:41 +08:00
|
|
|
rewriter.replaceOpWithNewOp<tosa::ConstOp>(op, outputTy, adaptor.getValue());
|
2022-01-27 11:16:13 +08:00
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2022-01-29 13:38:56 +08:00
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenFlattenUsingIntsOp>::matchAndRewrite(
|
|
|
|
AtenFlattenUsingIntsOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
|
|
|
// Not a ranked tensor type
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfType = dyn_cast<RankedTensorType>(adaptor.getSelf().getType());
|
2024-03-20 06:19:29 +08:00
|
|
|
if (!selfType)
|
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Only ranked tensor types supported");
|
2022-01-29 13:38:56 +08:00
|
|
|
|
|
|
|
int64_t selfRank = selfType.getRank();
|
|
|
|
|
|
|
|
int64_t start_dim, end_dim;
|
|
|
|
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getStartDim(), m_TorchConstantInt(&start_dim)))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"start_dim must be a Scalar constant");
|
2022-01-29 13:38:56 +08:00
|
|
|
start_dim = toPositiveDim(start_dim, selfRank);
|
|
|
|
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getEndDim(), m_TorchConstantInt(&end_dim)))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "end_dim must be a Scalar constant");
|
2022-01-29 13:38:56 +08:00
|
|
|
end_dim = toPositiveDim(end_dim, selfRank);
|
|
|
|
|
|
|
|
if (selfRank > 0 && !isValidDim(start_dim, selfRank))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "start_dim is statically invalid");
|
2022-01-29 13:38:56 +08:00
|
|
|
if (selfRank > 0 && !isValidDim(end_dim, selfRank))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "end_dim is statically invalid");
|
2022-01-29 13:38:56 +08:00
|
|
|
if (end_dim < start_dim)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"end_dim must be larger than start_dim");
|
2022-01-29 13:38:56 +08:00
|
|
|
|
|
|
|
SmallVector<int64_t> newShape;
|
2022-11-29 20:33:31 +08:00
|
|
|
for (auto s :
|
|
|
|
llvm::enumerate(makeShapeTorchCompatible(selfType.getShape()))) {
|
2022-01-29 13:38:56 +08:00
|
|
|
int64_t idx = s.index();
|
|
|
|
if (idx < start_dim || idx > end_dim) {
|
|
|
|
newShape.push_back(s.value());
|
|
|
|
} else {
|
|
|
|
if (idx == start_dim)
|
|
|
|
newShape.push_back(s.value());
|
2024-03-20 06:19:29 +08:00
|
|
|
// Only updating when the shapes are static
|
|
|
|
else if (s.value() != kUnknownSize && newShape.back() != kUnknownSize)
|
2022-01-29 13:38:56 +08:00
|
|
|
newShape.back() *= s.value();
|
2024-03-20 06:19:29 +08:00
|
|
|
else
|
|
|
|
newShape.back() = kUnknownSize;
|
2022-01-29 13:38:56 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Handle the Scalar case
|
|
|
|
if (newShape.size() == 0)
|
|
|
|
newShape.push_back(1);
|
|
|
|
|
2022-11-29 20:33:31 +08:00
|
|
|
auto newType = RankedTensorType::get(makeShapeLLVMCompatible(newShape),
|
|
|
|
selfType.getElementType());
|
2023-01-11 07:07:19 +08:00
|
|
|
auto reshapeOp =
|
|
|
|
rewriter.create<tosa::ReshapeOp>(op.getLoc(), newType, adaptor.getSelf(),
|
|
|
|
rewriter.getDenseI64ArrayAttr(newShape));
|
2022-01-29 13:38:56 +08:00
|
|
|
|
|
|
|
rewriter.replaceOpWithNewOp<tensor::CastOp>(
|
|
|
|
op, getTypeConverter()->convertType(op.getType()), reshapeOp);
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2023-10-14 09:39:41 +08:00
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenUnflattenIntOp>::matchAndRewrite(
|
|
|
|
AtenUnflattenIntOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
|
|
|
// Not a ranked tensor type
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfType = dyn_cast<RankedTensorType>(adaptor.getSelf().getType());
|
2023-10-14 09:39:41 +08:00
|
|
|
if (!selfType || !selfType.hasStaticShape())
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op,
|
|
|
|
"Only ranked tensor types with static shapes are currently supported");
|
|
|
|
|
|
|
|
int64_t selfRank = selfType.getRank();
|
|
|
|
int64_t dim;
|
|
|
|
|
|
|
|
if (!matchPattern(op.getDim(), m_TorchConstantInt(&dim)))
|
|
|
|
return rewriter.notifyMatchFailure(op, "dim must be a Scalar constant");
|
|
|
|
|
|
|
|
SmallVector<int64_t> sizes;
|
|
|
|
if (!matchPattern(op.getSizes(), m_TorchListOfConstantInts(sizes)))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only constant sizes are currently supported");
|
|
|
|
|
|
|
|
if (selfRank > 0 && !isValidDim(dim, selfRank))
|
|
|
|
return rewriter.notifyMatchFailure(op, "dim is statically invalid");
|
|
|
|
|
|
|
|
SmallVector<int64_t> newShape;
|
|
|
|
for (auto s :
|
|
|
|
llvm::enumerate(makeShapeTorchCompatible(selfType.getShape()))) {
|
|
|
|
int64_t idx = s.index();
|
|
|
|
if (idx < dim || idx > dim) {
|
|
|
|
newShape.push_back(s.value());
|
|
|
|
} else {
|
|
|
|
auto sum = 1;
|
|
|
|
for (auto newDims : sizes) {
|
|
|
|
newShape.push_back(newDims);
|
|
|
|
sum *= newDims;
|
|
|
|
}
|
|
|
|
if (sum != s.value())
|
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"sizes mismatch with original dim");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
auto newType = RankedTensorType::get(makeShapeLLVMCompatible(newShape),
|
|
|
|
selfType.getElementType());
|
|
|
|
|
|
|
|
rewriter.replaceOpWithNewOp<tosa::ReshapeOp>(
|
|
|
|
op, getTypeConverter()->convertType(newType), adaptor.getSelf(),
|
|
|
|
rewriter.getDenseI64ArrayAttr(newShape));
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2022-02-04 06:08:19 +08:00
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenPermuteOp>::matchAndRewrite(
|
|
|
|
AtenPermuteOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
|
|
|
// Not a ranked tensor type
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfType = dyn_cast<RankedTensorType>(adaptor.getSelf().getType());
|
2022-02-04 06:08:19 +08:00
|
|
|
if (!selfType)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op,
|
2022-02-04 06:08:19 +08:00
|
|
|
"Only ranked tensor types with static shapes are currently supported");
|
|
|
|
|
|
|
|
SmallVector<int64_t> dimListInt;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(adaptor.getDims(), m_TorchListOfConstantInts(dimListInt)))
|
2022-02-04 06:08:19 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only constant dimensions are currently supported");
|
|
|
|
|
|
|
|
int64_t selfRank = selfType.getRank();
|
2022-07-18 09:39:54 +08:00
|
|
|
// TODO: If this is already verified on the op then we can drop checking here.
|
2022-02-04 06:08:19 +08:00
|
|
|
for (auto &d : dimListInt) {
|
|
|
|
d = toPositiveDim(d, selfRank);
|
|
|
|
if (!isValidDim(d, selfRank))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "Not all dims are valid");
|
2022-02-04 06:08:19 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
auto transposeDimsConst = mlir::tosa::getConstTensor<int64_t>(
|
|
|
|
rewriter, op.getOperation(), dimListInt, {selfRank});
|
|
|
|
|
|
|
|
rewriter.replaceOpWithNewOp<tosa::TransposeOp>(
|
2022-12-08 04:20:41 +08:00
|
|
|
op, getTypeConverter()->convertType(op.getType()), adaptor.getSelf(),
|
2022-08-09 11:17:35 +08:00
|
|
|
transposeDimsConst.value());
|
2022-02-04 06:08:19 +08:00
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2022-02-12 04:30:02 +08:00
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenLog2Op>::matchAndRewrite(
|
|
|
|
AtenLog2Op op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
|
|
|
// Not a tensor type.
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfType = dyn_cast<TensorType>(adaptor.getSelf().getType());
|
2022-02-12 04:30:02 +08:00
|
|
|
if (!selfType)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only tensor types are currently supported");
|
2022-02-12 04:30:02 +08:00
|
|
|
|
|
|
|
// Constant value of ln2.
|
|
|
|
SmallVector<int64_t> ln2Shape(selfType.getRank(), 1);
|
2023-09-21 01:48:40 +08:00
|
|
|
auto ln2Op = tosa::getConstTensor<float>(rewriter, op, {0.69314718056f},
|
2023-06-16 15:51:24 +08:00
|
|
|
ln2Shape, selfType.getElementType())
|
|
|
|
.value();
|
2022-02-12 04:30:02 +08:00
|
|
|
auto rcpOp =
|
|
|
|
rewriter.create<tosa::ReciprocalOp>(op.getLoc(), ln2Op.getType(), ln2Op);
|
|
|
|
|
|
|
|
auto outType = getTypeConverter()->convertType(op.getType());
|
|
|
|
auto logOp =
|
2022-12-08 04:20:41 +08:00
|
|
|
rewriter.create<tosa::LogOp>(op.getLoc(), outType, adaptor.getSelf());
|
2022-02-12 04:30:02 +08:00
|
|
|
rewriter.replaceOpWithNewOp<tosa::MulOp>(op, outType, logOp, rcpOp,
|
|
|
|
/*shift=*/0);
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenThresholdOp>::matchAndRewrite(
|
|
|
|
AtenThresholdOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
|
|
|
// Not a tensor type.
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfType = dyn_cast<TensorType>(adaptor.getSelf().getType());
|
2022-02-12 04:30:02 +08:00
|
|
|
if (!selfType)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only tensor types are currently supported");
|
2022-02-12 04:30:02 +08:00
|
|
|
|
|
|
|
auto selfElemTy = selfType.getElementType();
|
|
|
|
if (!selfElemTy.isIntOrFloat())
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only floating-point or integer datatype legalization supported");
|
2022-02-12 04:30:02 +08:00
|
|
|
|
|
|
|
// Integer types with width > 32 are not supported
|
2024-04-11 21:47:35 +08:00
|
|
|
auto selfIntType = dyn_cast<IntegerType>(selfElemTy);
|
2022-02-12 04:30:02 +08:00
|
|
|
if (selfIntType && selfIntType.getWidth() > 32) {
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Integer types with width greater than 32 are not supported");
|
2022-02-12 04:30:02 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
SmallVector<int64_t> constTypeShape(selfType.getRank(), 1);
|
|
|
|
Value threshold, value;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (failed(torchScalarToTosaTensor(rewriter, op, op.getThreshold(), threshold,
|
2022-02-12 04:30:02 +08:00
|
|
|
selfElemTy, constTypeShape)))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only scalar constant is supported for threshold");
|
2022-02-12 04:30:02 +08:00
|
|
|
|
2022-12-08 04:20:41 +08:00
|
|
|
if (failed(torchScalarToTosaTensor(rewriter, op, op.getValue(), value,
|
2022-02-12 04:30:02 +08:00
|
|
|
selfElemTy, constTypeShape)))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only scalar constant is supported for value");
|
2022-02-12 04:30:02 +08:00
|
|
|
|
|
|
|
// Threshold only clamps the upper values. tosa::ClampOp has the same
|
|
|
|
// value for both threshold and clamped value so cannot be used.
|
|
|
|
auto outType = getTypeConverter()->convertType(op.getType());
|
|
|
|
|
|
|
|
auto cmpOp = rewriter.create<tosa::GreaterOp>(
|
|
|
|
op.getLoc(),
|
|
|
|
RankedTensorType::get(selfType.getShape(), rewriter.getIntegerType(1)),
|
2022-12-08 04:20:41 +08:00
|
|
|
adaptor.getSelf(), threshold);
|
2022-02-12 04:30:02 +08:00
|
|
|
|
|
|
|
rewriter.replaceOpWithNewOp<tosa::SelectOp>(op, outType, cmpOp,
|
2022-12-08 04:20:41 +08:00
|
|
|
adaptor.getSelf(), value);
|
2022-02-12 04:30:02 +08:00
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2022-03-26 05:15:07 +08:00
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenUnsqueezeOp>::matchAndRewrite(
|
|
|
|
AtenUnsqueezeOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
|
|
|
// Not a tensor type.
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfType = dyn_cast<TensorType>(adaptor.getSelf().getType());
|
2022-03-26 05:15:07 +08:00
|
|
|
if (!selfType) {
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only tensor types are currently supported");
|
2022-03-26 05:15:07 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
auto selfRank = selfType.getRank();
|
|
|
|
auto selfElemTy = selfType.getElementType();
|
|
|
|
if (!selfElemTy.isIntOrFloat()) {
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only floating-point or integer datatype legalization supported");
|
2022-03-26 05:15:07 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
int64_t dim;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getDim(), m_TorchConstantInt(&dim)))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "dim must be a Scalar constant");
|
2022-03-26 05:15:07 +08:00
|
|
|
|
2023-01-11 03:09:58 +08:00
|
|
|
// toPositiveDim converts negative dims to the range [0, inputRank). So, -1
|
|
|
|
// will be converted to inputRank-1. For `torch.unsqueeze` op, -1 has to be
|
|
|
|
// converted to inputRank, and the valid dim range is [0, inputRank + 1).
|
|
|
|
dim = toPositiveDim(dim, selfRank + 1);
|
2022-11-15 01:09:15 +08:00
|
|
|
if (!isValidDim(dim, selfRank + 1))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "dim is statically invalid");
|
2022-03-26 05:15:07 +08:00
|
|
|
|
|
|
|
SmallVector<int64_t> outShape;
|
2022-11-29 20:33:31 +08:00
|
|
|
for (auto en :
|
|
|
|
llvm::enumerate(makeShapeTorchCompatible(selfType.getShape()))) {
|
2022-03-26 05:15:07 +08:00
|
|
|
if (static_cast<int64_t>(en.index()) == dim)
|
|
|
|
outShape.push_back(1);
|
|
|
|
|
|
|
|
outShape.push_back(en.value());
|
|
|
|
}
|
2023-01-11 03:09:58 +08:00
|
|
|
if (dim == selfRank)
|
|
|
|
outShape.push_back(1);
|
2022-03-26 05:15:07 +08:00
|
|
|
|
|
|
|
rewriter.replaceOpWithNewOp<tosa::ReshapeOp>(
|
2022-12-08 04:20:41 +08:00
|
|
|
op, getTypeConverter()->convertType(op.getType()), adaptor.getSelf(),
|
2023-01-11 07:07:19 +08:00
|
|
|
rewriter.getDenseI64ArrayAttr(outShape));
|
2022-03-26 05:15:07 +08:00
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenContiguousOp>::matchAndRewrite(
|
|
|
|
AtenContiguousOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
|
|
|
// Not a tensor type.
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfType = dyn_cast<TensorType>(adaptor.getSelf().getType());
|
2022-03-26 05:15:07 +08:00
|
|
|
if (!selfType)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only tensor types are currently supported");
|
2022-03-26 05:15:07 +08:00
|
|
|
|
|
|
|
// FIXME: memory_format is not handled.
|
|
|
|
|
2022-12-08 04:20:41 +08:00
|
|
|
rewriter.replaceOp(op, adaptor.getSelf());
|
2022-03-26 05:15:07 +08:00
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenDropoutOp>::matchAndRewrite(
|
|
|
|
AtenDropoutOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
|
|
|
// Not a tensor type.
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfType = dyn_cast<TensorType>(adaptor.getInput().getType());
|
2022-03-26 05:15:07 +08:00
|
|
|
if (!selfType)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only tensor types are currently supported");
|
2022-03-26 05:15:07 +08:00
|
|
|
|
|
|
|
// FIXME: train and p are not handled.
|
|
|
|
|
|
|
|
bool train;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getTrain(), m_TorchConstantBool(&train)))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "train must be a Scalar constant");
|
2022-03-26 05:15:07 +08:00
|
|
|
|
|
|
|
if (train)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "train must be false");
|
2022-03-26 05:15:07 +08:00
|
|
|
|
|
|
|
rewriter.replaceOpWithNewOp<tosa::CastOp>(
|
2022-12-08 04:20:41 +08:00
|
|
|
op, getTypeConverter()->convertType(op.getType()), adaptor.getInput());
|
2022-03-26 05:15:07 +08:00
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenViewOp>::matchAndRewrite(
|
|
|
|
AtenViewOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
|
|
|
// Not a tensor type.
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfType = dyn_cast<TensorType>(adaptor.getSelf().getType());
|
2022-03-26 05:15:07 +08:00
|
|
|
if (!selfType)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only tensor types are currently supported");
|
2022-03-26 05:15:07 +08:00
|
|
|
|
|
|
|
auto selfElemTy = selfType.getElementType();
|
|
|
|
if (!selfElemTy.isIntOrFloat()) {
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only floating-point or integer datatype legalization supported");
|
2022-03-26 05:15:07 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
SmallVector<int64_t> outShape;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getSize(), m_TorchListOfConstantInts(outShape)))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"size must consist of Scalar constants");
|
2022-03-26 05:15:07 +08:00
|
|
|
|
2023-01-21 03:56:26 +08:00
|
|
|
// the shape -1 is inferred from other dimensions
|
|
|
|
size_t countNegativeShape{0};
|
|
|
|
// Check at most one -1 shape
|
|
|
|
for (size_t i = 0; i < outShape.size(); i++) {
|
|
|
|
if (outShape[i] < 0) {
|
|
|
|
countNegativeShape++;
|
|
|
|
if (countNegativeShape > 1)
|
|
|
|
return rewriter.notifyMatchFailure(op, "At most one -1 shape");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
auto inputShape = selfType.getShape();
|
|
|
|
size_t totalSize = 1;
|
|
|
|
for (size_t i = 0; i < inputShape.size(); i++) {
|
|
|
|
totalSize *= inputShape[i];
|
|
|
|
}
|
|
|
|
|
|
|
|
size_t otherSize = 1;
|
|
|
|
for (size_t i = 0; i < outShape.size(); i++) {
|
|
|
|
if (outShape[i] > 0) {
|
|
|
|
otherSize *= outShape[i];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for (size_t i = 0; i < outShape.size(); i++) {
|
|
|
|
if (outShape[i] < 0) {
|
|
|
|
outShape[i] = totalSize / otherSize;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-26 05:15:07 +08:00
|
|
|
rewriter.replaceOpWithNewOp<tosa::ReshapeOp>(
|
2022-12-08 04:20:41 +08:00
|
|
|
op, getTypeConverter()->convertType(op.getType()), adaptor.getSelf(),
|
2023-01-11 07:07:19 +08:00
|
|
|
rewriter.getDenseI64ArrayAttr(outShape));
|
2022-03-26 05:15:07 +08:00
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2022-03-31 08:00:55 +08:00
|
|
|
static Value approximateErfOp(ConversionPatternRewriter &rewriter,
|
2023-06-16 15:51:24 +08:00
|
|
|
Operation *op, Value x, Type dtype) {
|
2022-03-31 08:00:55 +08:00
|
|
|
// Using:
|
|
|
|
// https://en.wikipedia.org/wiki/Error_function#Numerical_approximations with
|
|
|
|
// maximum error as 5 x 10^-4 where a1 = 0.278393, a2 = 0.230389, a3 =
|
|
|
|
// 0.000972, a4 = 0.078108.
|
|
|
|
//
|
|
|
|
// Erf = 1 - 1 / (1 + a1X + a2X + a3X + a4X)^4
|
|
|
|
|
2024-04-28 05:00:56 +08:00
|
|
|
auto outType = cast<TensorType>(x.getType());
|
2022-03-31 08:00:55 +08:00
|
|
|
auto loc = op->getLoc();
|
|
|
|
auto absX = rewriter.create<tosa::AbsOp>(loc, outType, x);
|
2023-06-16 15:51:24 +08:00
|
|
|
auto zero = tosa::getConstTensor<float>(rewriter, op, 0, {}, dtype).value();
|
|
|
|
auto one = tosa::getConstTensor<float>(rewriter, op, 1, {}, dtype).value();
|
2022-03-31 08:00:55 +08:00
|
|
|
|
2023-09-21 01:48:40 +08:00
|
|
|
auto a1 =
|
|
|
|
tosa::getConstTensor<float>(rewriter, op, 0.278393f, {}, dtype).value();
|
2022-03-31 08:00:55 +08:00
|
|
|
auto a1X = rewriter.create<tosa::MulOp>(loc, outType, a1, absX, /*shift=*/0);
|
|
|
|
auto sum = rewriter.create<tosa::AddOp>(loc, outType, a1X, one);
|
|
|
|
|
2023-09-21 01:48:40 +08:00
|
|
|
auto a2 =
|
|
|
|
tosa::getConstTensor<float>(rewriter, op, 0.230389f, {}, dtype).value();
|
2022-03-31 08:00:55 +08:00
|
|
|
auto x2 = rewriter.create<tosa::MulOp>(loc, outType, absX, absX, /*shift=*/0);
|
|
|
|
auto a2X = rewriter.create<tosa::MulOp>(loc, outType, a2, x2, /*shift=*/0);
|
|
|
|
sum = rewriter.create<tosa::AddOp>(loc, outType, sum, a2X);
|
|
|
|
|
2023-09-21 01:48:40 +08:00
|
|
|
auto a3 =
|
|
|
|
tosa::getConstTensor<float>(rewriter, op, 0.000972f, {}, dtype).value();
|
2022-03-31 08:00:55 +08:00
|
|
|
auto x3 = rewriter.create<tosa::MulOp>(loc, outType, x2, absX, /*shift=*/0);
|
|
|
|
auto a3X = rewriter.create<tosa::MulOp>(loc, outType, a3, x3, /*shift=*/0);
|
|
|
|
sum = rewriter.create<tosa::AddOp>(loc, outType, sum, a3X);
|
|
|
|
|
2023-09-21 01:48:40 +08:00
|
|
|
auto a4 =
|
|
|
|
tosa::getConstTensor<float>(rewriter, op, 0.078108f, {}, dtype).value();
|
2022-03-31 08:00:55 +08:00
|
|
|
auto x4 = rewriter.create<tosa::MulOp>(loc, outType, x3, absX, /*shift=*/0);
|
|
|
|
auto a4X = rewriter.create<tosa::MulOp>(loc, outType, a4, x4, /*shift=*/0);
|
|
|
|
sum = rewriter.create<tosa::AddOp>(loc, outType, sum, a4X);
|
|
|
|
|
|
|
|
auto rcprl = rewriter.create<tosa::ReciprocalOp>(loc, outType, sum);
|
|
|
|
auto rcprl2 =
|
|
|
|
rewriter.create<tosa::MulOp>(loc, outType, rcprl, rcprl, /*shift=*/0);
|
|
|
|
auto rcprl4 =
|
|
|
|
rewriter.create<tosa::MulOp>(loc, outType, rcprl2, rcprl2, /*shift=*/0);
|
|
|
|
auto erf = rewriter.create<tosa::SubOp>(loc, outType, one, rcprl4);
|
|
|
|
|
|
|
|
// Deal with negative x.
|
|
|
|
auto cond = rewriter.create<tosa::GreaterEqualOp>(
|
|
|
|
loc,
|
2023-01-11 13:42:07 +08:00
|
|
|
RankedTensorType::get(outType.getShape(), rewriter.getIntegerType(1)), x,
|
|
|
|
zero);
|
2022-03-31 08:00:55 +08:00
|
|
|
auto negateErf = rewriter.create<tosa::NegateOp>(loc, outType, erf);
|
|
|
|
|
|
|
|
return rewriter.create<tosa::SelectOp>(loc, outType, cond, erf, negateErf);
|
|
|
|
}
|
|
|
|
|
|
|
|
static Value buildUnitNormalCdf(ConversionPatternRewriter &rewriter,
|
2023-06-16 15:51:24 +08:00
|
|
|
Operation *op, Value x, Type dtype) {
|
|
|
|
auto zero = tosa::getConstTensor<float>(rewriter, op, 0, {}, dtype).value();
|
|
|
|
auto one = tosa::getConstTensor<float>(rewriter, op, 1, {}, dtype).value();
|
|
|
|
|
2022-03-31 08:00:55 +08:00
|
|
|
auto loc = op->getLoc();
|
|
|
|
|
|
|
|
// buildNormalCdf, mean = zero, sigma = one
|
|
|
|
auto outType = x.getType();
|
|
|
|
auto mean = zero;
|
|
|
|
Value xMinusMean = rewriter.create<tosa::SubOp>(loc, outType, x, mean);
|
|
|
|
// rsqrt of 2
|
2022-05-19 20:35:59 +08:00
|
|
|
Value rsqrt2 =
|
2023-09-21 01:48:40 +08:00
|
|
|
tosa::getConstTensor<float>(rewriter, op, 0.70710678f, {}, dtype).value();
|
2023-06-16 15:51:24 +08:00
|
|
|
|
2022-03-31 08:00:55 +08:00
|
|
|
Value erfArg = rewriter.create<tosa::MulOp>(loc, outType, xMinusMean, rsqrt2,
|
|
|
|
/*shift=*/0);
|
2023-06-16 15:51:24 +08:00
|
|
|
Value erf = approximateErfOp(rewriter, op, erfArg, dtype);
|
2022-03-31 08:00:55 +08:00
|
|
|
Value erfPlus1 = rewriter.create<tosa::AddOp>(loc, outType, one, erf);
|
2023-09-21 01:48:40 +08:00
|
|
|
Value oneHalf =
|
|
|
|
tosa::getConstTensor<float>(rewriter, op, 0.5, {}, dtype).value();
|
2023-06-16 15:51:24 +08:00
|
|
|
|
2022-03-31 08:00:55 +08:00
|
|
|
Value normalCdf = rewriter.create<tosa::MulOp>(loc, outType, oneHalf,
|
|
|
|
erfPlus1, /*shift=*/0);
|
|
|
|
return normalCdf;
|
|
|
|
}
|
|
|
|
|
|
|
|
// This lowering is based on Torch to LinAlg lowering.
|
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenGeluOp>::matchAndRewrite(
|
|
|
|
AtenGeluOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
|
|
|
// Not a tensor type.
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfType = dyn_cast<TensorType>(adaptor.getSelf().getType());
|
2022-03-31 08:00:55 +08:00
|
|
|
if (!selfType)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only tensor types are currently supported");
|
2022-03-31 08:00:55 +08:00
|
|
|
|
|
|
|
auto selfElemTy = selfType.getElementType();
|
2024-04-11 21:47:35 +08:00
|
|
|
if (!isa<mlir::FloatType>(selfElemTy)) {
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only floating-point datatype legalization supported");
|
2022-03-31 08:00:55 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: Handle approximate.
|
|
|
|
std::string approximate;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getApproximate(), m_TorchConstantStr(approximate)) ||
|
2022-03-31 08:00:55 +08:00
|
|
|
approximate != "none") {
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "Unsupported value of approximate");
|
2022-03-31 08:00:55 +08:00
|
|
|
}
|
|
|
|
|
2023-06-16 15:51:24 +08:00
|
|
|
Value cdf = buildUnitNormalCdf(rewriter, op, adaptor.getSelf(), selfElemTy);
|
|
|
|
cdf = rewriter.createOrFold<tosa::CastOp>(
|
2023-09-21 01:48:40 +08:00
|
|
|
op->getLoc(),
|
|
|
|
cast<RankedTensorType>(cdf.getType()).cloneWith({}, selfElemTy), cdf);
|
2023-06-16 15:51:24 +08:00
|
|
|
|
2022-03-31 08:00:55 +08:00
|
|
|
rewriter.replaceOpWithNewOp<tosa::MulOp>(
|
2022-12-08 04:20:41 +08:00
|
|
|
op, getTypeConverter()->convertType(op.getType()), adaptor.getSelf(), cdf,
|
2022-03-31 08:00:55 +08:00
|
|
|
/*shift=*/0);
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
|
|
|
// This lowering is based on Torch to LinAlg lowering.
|
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenGeluBackwardOp>::matchAndRewrite(
|
|
|
|
AtenGeluBackwardOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
|
|
|
// Not a tensor type.
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfType = dyn_cast<TensorType>(adaptor.getSelf().getType());
|
2022-03-31 08:00:55 +08:00
|
|
|
if (!selfType)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only tensor types are currently supported");
|
2022-03-31 08:00:55 +08:00
|
|
|
|
|
|
|
auto selfElemTy = selfType.getElementType();
|
2024-04-11 21:47:35 +08:00
|
|
|
if (!isa<mlir::FloatType>(selfElemTy)) {
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only floating-point datatype legalization supported");
|
2022-03-31 08:00:55 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: Handle approximate.
|
|
|
|
std::string approximate;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getApproximate(), m_TorchConstantStr(approximate)) ||
|
2022-03-31 08:00:55 +08:00
|
|
|
approximate != "none") {
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "Unsupported value of approximate");
|
2022-03-31 08:00:55 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
auto loc = op->getLoc();
|
|
|
|
|
2023-09-21 01:48:40 +08:00
|
|
|
const float cstAlpha0 = 1.12837916709551257390f;
|
|
|
|
const float cstAlpha1 = 0.70710678118654752440f;
|
|
|
|
const float oneHalf = 0.5f;
|
|
|
|
const float kAlpha = cstAlpha0 * cstAlpha1;
|
2022-03-31 08:00:55 +08:00
|
|
|
|
2023-09-21 01:48:40 +08:00
|
|
|
Value kAlphaHalf = tosa::getConstTensor<float>(rewriter, op, kAlpha * oneHalf,
|
|
|
|
{}, selfElemTy)
|
|
|
|
.value();
|
2022-03-31 08:00:55 +08:00
|
|
|
Value negOneHalf =
|
2023-09-21 01:48:40 +08:00
|
|
|
tosa::getConstTensor<float>(rewriter, op, -0.5f, {}, selfElemTy).value();
|
2022-03-31 08:00:55 +08:00
|
|
|
Value inputSquared = rewriter.create<tosa::MulOp>(
|
2022-12-08 04:20:41 +08:00
|
|
|
loc, selfType, adaptor.getSelf(), adaptor.getSelf(), /*shift=*/0);
|
2022-03-31 08:00:55 +08:00
|
|
|
Value negHalfInputSquared = rewriter.create<tosa::MulOp>(
|
|
|
|
loc, selfType, inputSquared, negOneHalf, /*shift=*/0);
|
|
|
|
Value dinput =
|
|
|
|
rewriter.create<tosa::ExpOp>(loc, selfType, negHalfInputSquared);
|
2023-06-16 15:51:24 +08:00
|
|
|
Value cdf = buildUnitNormalCdf(rewriter, op, adaptor.getSelf(), selfElemTy);
|
2023-01-11 13:42:07 +08:00
|
|
|
Value dinputInput = rewriter.create<tosa::MulOp>(
|
|
|
|
loc, selfType, dinput, adaptor.getSelf(), /*shift=*/0);
|
2022-03-31 08:00:55 +08:00
|
|
|
Value dinputInputAlpha = rewriter.create<tosa::MulOp>(
|
|
|
|
loc, selfType, dinputInput, kAlphaHalf, /*shift=*/0);
|
|
|
|
Value cdfExt =
|
|
|
|
rewriter.create<tosa::AddOp>(loc, selfType, dinputInputAlpha, cdf);
|
|
|
|
rewriter.replaceOpWithNewOp<tosa::MulOp>(
|
2023-01-11 13:42:07 +08:00
|
|
|
op, getTypeConverter()->convertType(op.getType()),
|
|
|
|
adaptor.getGradOutput(), cdfExt,
|
2022-03-31 08:00:55 +08:00
|
|
|
/*shift=*/0);
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2023-03-07 02:16:37 +08:00
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenHardtanhBackwardOp>::matchAndRewrite(
|
|
|
|
AtenHardtanhBackwardOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
|
|
|
// Not a tensor type.
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfType = dyn_cast<TensorType>(adaptor.getSelf().getType());
|
2023-03-07 02:16:37 +08:00
|
|
|
if (!selfType) {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only tensor types are currently supported");
|
|
|
|
}
|
|
|
|
|
|
|
|
auto selfElemTy = selfType.getElementType();
|
|
|
|
if (!selfElemTy.isIntOrFloat()) {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only floating-point or integer datatype legalization supported");
|
|
|
|
}
|
|
|
|
|
|
|
|
// Integer types with width > 32 are not supported
|
2024-04-11 21:47:35 +08:00
|
|
|
auto selfIntType = dyn_cast<IntegerType>(selfElemTy);
|
2023-03-07 02:16:37 +08:00
|
|
|
if (selfIntType && selfIntType.getWidth() > 32) {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Integer types with width greater than 32 are not supported");
|
|
|
|
}
|
|
|
|
|
|
|
|
Value gradOutput = adaptor.getGradOutput();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto gradOutputType = dyn_cast<TensorType>(adaptor.getSelf().getType());
|
2023-03-07 02:16:37 +08:00
|
|
|
|
|
|
|
Type gradOutputElemType = gradOutputType.getElementType();
|
|
|
|
|
|
|
|
if (selfElemTy != gradOutputElemType) {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op,
|
|
|
|
"Input element type should be same as the grad_output element type.");
|
|
|
|
}
|
|
|
|
|
|
|
|
SmallVector<int64_t> constTypeShape(selfType.getRank(), 1);
|
|
|
|
Value maxVal, minVal;
|
|
|
|
|
|
|
|
if (failed(torchScalarToTosaTensor(rewriter, op, op.getMinVal(), minVal,
|
|
|
|
selfElemTy, constTypeShape))) {
|
|
|
|
return rewriter.notifyMatchFailure(op, "Only scalar constant is supported");
|
|
|
|
}
|
|
|
|
|
|
|
|
if (failed(torchScalarToTosaTensor(rewriter, op, op.getMaxVal(), maxVal,
|
|
|
|
selfElemTy, constTypeShape))) {
|
|
|
|
return rewriter.notifyMatchFailure(op, "Only scalar constant is supported");
|
|
|
|
}
|
|
|
|
|
2023-09-21 01:48:40 +08:00
|
|
|
Value replace =
|
|
|
|
tosa::getConstTensor<float>(rewriter, op, 0, {}, selfElemTy).value();
|
2023-03-07 02:16:37 +08:00
|
|
|
Type outType = getTypeConverter()->convertType(op.getType());
|
|
|
|
|
|
|
|
Value lesser = rewriter.create<tosa::GreaterOp>(
|
|
|
|
op.getLoc(),
|
|
|
|
RankedTensorType::get(selfType.getShape(), rewriter.getIntegerType(1)),
|
|
|
|
minVal, adaptor.getSelf());
|
|
|
|
|
|
|
|
Value greater = rewriter.create<tosa::GreaterOp>(
|
|
|
|
op.getLoc(),
|
|
|
|
RankedTensorType::get(selfType.getShape(), rewriter.getIntegerType(1)),
|
|
|
|
adaptor.getSelf(), maxVal);
|
|
|
|
|
|
|
|
Value cmp = rewriter.create<tosa::LogicalOrOp>(
|
|
|
|
op.getLoc(),
|
|
|
|
RankedTensorType::get(selfType.getShape(), rewriter.getIntegerType(1)),
|
|
|
|
lesser, greater);
|
|
|
|
|
|
|
|
rewriter.replaceOpWithNewOp<tosa::SelectOp>(op, outType, cmp, replace,
|
|
|
|
gradOutput);
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2022-07-01 04:13:52 +08:00
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenEmbeddingOp>::matchAndRewrite(
|
|
|
|
AtenEmbeddingOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
2022-12-08 04:20:41 +08:00
|
|
|
Value weight = adaptor.getWeight();
|
|
|
|
Value indices = adaptor.getIndices();
|
2022-07-01 04:13:52 +08:00
|
|
|
RankedTensorType outType =
|
2024-04-28 05:00:56 +08:00
|
|
|
cast<RankedTensorType>(typeConverter->convertType(op.getType()));
|
2022-07-01 04:13:52 +08:00
|
|
|
|
2024-04-28 05:00:56 +08:00
|
|
|
auto indicesType = dyn_cast<RankedTensorType>(indices.getType());
|
2024-05-31 14:45:13 +08:00
|
|
|
if (!indicesType || !isa<IntegerType>(indicesType.getElementType()))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Indices must be of integer tensor type");
|
2022-07-01 04:13:52 +08:00
|
|
|
|
2024-04-28 05:00:56 +08:00
|
|
|
auto weightType = cast<RankedTensorType>(weight.getType());
|
2022-07-01 04:13:52 +08:00
|
|
|
if (weightType.getRank() != 2)
|
|
|
|
return op.emitError("weight must be of rank 2");
|
|
|
|
|
|
|
|
// FIXME: padding_idx, scale_grad_by_freq and sparse are not handled yet.
|
|
|
|
int64_t paddingIdx;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getPaddingIdx(), m_TorchConstantInt(&paddingIdx)))
|
2022-07-01 04:13:52 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "only supports constant int padding_idx for embedding op");
|
|
|
|
|
|
|
|
bool scaleGradByFreq;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getScaleGradByFreq(),
|
2022-07-01 04:13:52 +08:00
|
|
|
m_TorchConstantBool(&scaleGradByFreq)))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "only supports constant bool scale_grad_by_freq for embedding op");
|
|
|
|
if (scaleGradByFreq)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op,
|
|
|
|
"only supports scale_grad_by_freq equals to False for embedding op");
|
|
|
|
|
|
|
|
bool isSparse;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getSparse(), m_TorchConstantBool(&isSparse)))
|
2022-07-01 04:13:52 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "only supports constant bool sparse for embedding op");
|
|
|
|
if (isSparse)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "only support sparse equals to False for embedding op");
|
|
|
|
|
|
|
|
// For inference:
|
|
|
|
// Weights [num_embeddings, embedding_dim], Indices [X, Y]
|
|
|
|
// Output [X, Y, embedding_dim] = Weights[Indices[x, y]] forall x in X, y
|
|
|
|
// in Y
|
|
|
|
//
|
|
|
|
// Condition: num_embeddings > Indices [x, y] forall x in X, y in Y
|
|
|
|
|
|
|
|
// Reshape the weight, since tosa.gather expects a 3D tensor
|
2022-11-29 20:33:31 +08:00
|
|
|
auto indicesShape = makeShapeTorchCompatible(indicesType.getShape());
|
|
|
|
auto weightShape = makeShapeTorchCompatible(weightType.getShape());
|
2022-07-01 04:13:52 +08:00
|
|
|
|
|
|
|
SmallVector<int64_t> newWeightShape = {1};
|
|
|
|
for (auto s : weightShape)
|
|
|
|
newWeightShape.push_back(s);
|
|
|
|
|
|
|
|
auto reshapedWeight = rewriter.create<tosa::ReshapeOp>(
|
|
|
|
op->getLoc(),
|
2022-11-29 20:33:31 +08:00
|
|
|
RankedTensorType::get(makeShapeLLVMCompatible(newWeightShape),
|
|
|
|
weightType.getElementType()),
|
2023-01-11 07:07:19 +08:00
|
|
|
weight, rewriter.getDenseI64ArrayAttr(newWeightShape));
|
2022-07-01 04:13:52 +08:00
|
|
|
|
|
|
|
int64_t numIndices = 1;
|
|
|
|
if (indicesType.hasStaticShape()) {
|
|
|
|
for (auto s : indicesShape)
|
|
|
|
numIndices *= s;
|
|
|
|
} else {
|
2022-11-29 20:33:31 +08:00
|
|
|
numIndices = kUnknownSize;
|
2022-07-01 04:13:52 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
SmallVector<int64_t> newIndicesShape = {1, numIndices};
|
|
|
|
auto reshapedIndices = rewriter.create<tosa::ReshapeOp>(
|
|
|
|
op->getLoc(),
|
2022-11-29 20:33:31 +08:00
|
|
|
RankedTensorType::get(makeShapeLLVMCompatible(newIndicesShape),
|
|
|
|
indicesType.getElementType()),
|
2023-01-11 07:07:19 +08:00
|
|
|
indices, rewriter.getDenseI64ArrayAttr(newIndicesShape));
|
2022-07-01 04:13:52 +08:00
|
|
|
|
|
|
|
auto castIndices = rewriter.create<tosa::CastOp>(
|
|
|
|
op->getLoc(),
|
2022-11-29 20:33:31 +08:00
|
|
|
RankedTensorType::get(makeShapeLLVMCompatible(newIndicesShape),
|
|
|
|
rewriter.getIntegerType(32)),
|
2022-07-01 04:13:52 +08:00
|
|
|
reshapedIndices);
|
|
|
|
|
|
|
|
SmallVector<int64_t> intermediateOutShape = {1, numIndices, weightShape[1]};
|
|
|
|
auto gatherOp = rewriter.create<tosa::GatherOp>(
|
|
|
|
op->getLoc(),
|
2022-11-29 20:33:31 +08:00
|
|
|
RankedTensorType::get(makeShapeLLVMCompatible(intermediateOutShape),
|
|
|
|
weightType.getElementType()),
|
2022-07-01 04:13:52 +08:00
|
|
|
reshapedWeight, castIndices);
|
|
|
|
|
|
|
|
rewriter.replaceOpWithNewOp<tosa::ReshapeOp>(
|
2022-11-29 20:33:31 +08:00
|
|
|
op, outType, gatherOp,
|
2023-01-11 07:07:19 +08:00
|
|
|
rewriter.getDenseI64ArrayAttr(
|
|
|
|
makeShapeTorchCompatible(outType.getShape())));
|
2022-07-01 04:13:52 +08:00
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2022-07-08 04:05:33 +08:00
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenTransposeIntOp>::matchAndRewrite(
|
|
|
|
AtenTransposeIntOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfType = dyn_cast<TensorType>(adaptor.getSelf().getType());
|
2022-07-08 04:05:33 +08:00
|
|
|
if (!selfType)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "Only tensor types are supported");
|
2022-07-08 04:05:33 +08:00
|
|
|
|
|
|
|
// Only statically resolvable values are currently supported
|
|
|
|
int64_t dim0, dim1;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getDim0(), m_TorchConstantInt(&dim0)))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "dim0 must be a Scalar constant");
|
2022-07-08 04:05:33 +08:00
|
|
|
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getDim1(), m_TorchConstantInt(&dim1)))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "dim1 must be a Scalar constant");
|
2022-07-08 04:05:33 +08:00
|
|
|
|
|
|
|
dim0 = toPositiveDim(dim0, selfType.getRank());
|
|
|
|
dim1 = toPositiveDim(dim1, selfType.getRank());
|
|
|
|
|
|
|
|
auto selfRank = selfType.getRank();
|
|
|
|
if (!isValidDim(dim0, selfRank) || !isValidDim(dim1, selfRank))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "dim0 and dim1 must be less than tensor rank");
|
2022-07-08 04:05:33 +08:00
|
|
|
|
|
|
|
SmallVector<int32_t> transposeDims;
|
|
|
|
for (auto i = 0; i < selfType.getRank(); ++i)
|
|
|
|
transposeDims.push_back(i);
|
|
|
|
|
|
|
|
transposeDims[dim0] = dim1;
|
|
|
|
transposeDims[dim1] = dim0;
|
|
|
|
|
|
|
|
auto transposeDimsConst = mlir::tosa::getConstTensor<int32_t>(
|
|
|
|
rewriter, op.getOperation(), transposeDims, {selfType.getRank()});
|
|
|
|
|
|
|
|
rewriter.replaceOpWithNewOp<tosa::TransposeOp>(
|
2022-12-08 04:20:41 +08:00
|
|
|
op, getTypeConverter()->convertType(op.getType()), adaptor.getSelf(),
|
2022-08-09 11:17:35 +08:00
|
|
|
transposeDimsConst.value());
|
2022-07-08 04:05:33 +08:00
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2024-09-17 03:40:24 +08:00
|
|
|
template <typename AtenOpT, typename TosaOpT>
|
|
|
|
class ConvertAtenMinMaxDimOp : public OpConversionPattern<AtenOpT> {
|
|
|
|
public:
|
|
|
|
using OpConversionPattern<AtenOpT>::OpConversionPattern;
|
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
|
|
|
LogicalResult
|
|
|
|
matchAndRewrite(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const override {
|
2022-07-14 01:10:18 +08:00
|
|
|
|
2024-09-17 03:40:24 +08:00
|
|
|
auto self = adaptor.getSelf();
|
|
|
|
auto selfType = dyn_cast<TensorType>(self.getType());
|
|
|
|
if (!selfType)
|
|
|
|
return rewriter.notifyMatchFailure(op, "Only tensor types are supported");
|
2022-07-14 01:10:18 +08:00
|
|
|
|
2024-09-17 03:40:24 +08:00
|
|
|
const TypeConverter *typeConverter = this->getTypeConverter();
|
|
|
|
auto indicesType =
|
|
|
|
dyn_cast<TensorType>(typeConverter->convertType(op.getType(1)));
|
|
|
|
if (!indicesType)
|
|
|
|
return rewriter.notifyMatchFailure(op, "Only tensor types are supported");
|
2022-07-14 01:10:18 +08:00
|
|
|
|
2024-09-17 03:40:24 +08:00
|
|
|
auto selfElemType = selfType.getElementType();
|
|
|
|
auto indicesElemType = indicesType.getElementType();
|
2022-07-14 01:10:18 +08:00
|
|
|
|
2024-09-17 03:40:24 +08:00
|
|
|
// Only statically deducible values are currently supported
|
|
|
|
int64_t dim;
|
|
|
|
if (!matchPattern(op.getDim(), m_TorchConstantInt(&dim)))
|
|
|
|
return rewriter.notifyMatchFailure(op, "dim must be a Scalar constant");
|
2022-07-14 01:10:18 +08:00
|
|
|
|
2024-09-17 03:40:24 +08:00
|
|
|
dim = toPositiveDim(dim, selfType.getRank());
|
2022-07-14 01:10:18 +08:00
|
|
|
|
2024-09-17 03:40:24 +08:00
|
|
|
if (!isValidDim(dim, selfType.getRank()))
|
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"dim must be less than tensor rank");
|
2022-07-14 01:10:18 +08:00
|
|
|
|
2024-09-17 03:40:24 +08:00
|
|
|
bool keepDim;
|
|
|
|
if (!matchPattern(op.getKeepdim(), m_TorchConstantBool(&keepDim)))
|
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"keepdim must be a Scalar constant");
|
|
|
|
|
|
|
|
SmallVector<int64_t> reducedShape, prunedShape;
|
|
|
|
for (auto en :
|
|
|
|
llvm::enumerate(makeShapeTorchCompatible(selfType.getShape()))) {
|
|
|
|
if (static_cast<int64_t>(en.index()) == dim) {
|
|
|
|
reducedShape.push_back(1);
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
reducedShape.push_back(en.value());
|
|
|
|
prunedShape.push_back(en.value());
|
2022-07-14 01:10:18 +08:00
|
|
|
}
|
|
|
|
|
2024-09-17 03:40:24 +08:00
|
|
|
auto dimAttr = rewriter.getIntegerAttr(rewriter.getI32Type(), dim);
|
|
|
|
auto prunedShapeAttr = rewriter.getDenseI64ArrayAttr(prunedShape);
|
2022-07-14 01:10:18 +08:00
|
|
|
|
2024-09-17 03:40:24 +08:00
|
|
|
Value reduceOp = rewriter.create<TosaOpT>(
|
2022-11-29 20:33:31 +08:00
|
|
|
op->getLoc(),
|
2024-09-17 03:40:24 +08:00
|
|
|
RankedTensorType::get(makeShapeLLVMCompatible(reducedShape),
|
2023-01-11 13:42:07 +08:00
|
|
|
selfElemType),
|
2024-09-17 03:40:24 +08:00
|
|
|
self, dimAttr);
|
2022-07-14 01:10:18 +08:00
|
|
|
|
2024-09-17 03:40:24 +08:00
|
|
|
// To handle ReduceMinDim indices, we apply ArgMaxOp on the negate
|
|
|
|
// of the input tensor, which will return indices of input's min values
|
|
|
|
Value argMaxOp;
|
|
|
|
if constexpr (std::is_same<AtenOpT, AtenMinDimOp>()) {
|
|
|
|
Value negateOp =
|
|
|
|
rewriter.create<tosa::NegateOp>(op->getLoc(), selfType, self);
|
2022-07-14 01:10:18 +08:00
|
|
|
|
2024-09-17 03:40:24 +08:00
|
|
|
argMaxOp = rewriter.create<tosa::ArgMaxOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
RankedTensorType::get(makeShapeLLVMCompatible(prunedShape),
|
|
|
|
indicesElemType),
|
|
|
|
negateOp, dimAttr);
|
|
|
|
} else {
|
|
|
|
argMaxOp = rewriter.create<tosa::ArgMaxOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
RankedTensorType::get(makeShapeLLVMCompatible(prunedShape),
|
|
|
|
indicesElemType),
|
|
|
|
self, dimAttr);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (argMaxOp.getType() != indicesType) {
|
|
|
|
argMaxOp = rewriter.create<tosa::ReshapeOp>(
|
|
|
|
op->getLoc(), indicesType, argMaxOp,
|
|
|
|
rewriter.getDenseI64ArrayAttr(reducedShape));
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!keepDim) {
|
|
|
|
reduceOp = rewriter.create<tosa::ReshapeOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
RankedTensorType::get(makeShapeLLVMCompatible(prunedShape),
|
|
|
|
selfElemType),
|
|
|
|
reduceOp, prunedShapeAttr);
|
|
|
|
}
|
|
|
|
|
|
|
|
rewriter.replaceOp(op, {reduceOp, argMaxOp});
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
};
|
2022-07-14 01:10:18 +08:00
|
|
|
|
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenSliceTensorOp>::matchAndRewrite(
|
|
|
|
AtenSliceTensorOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfType = dyn_cast<TensorType>(adaptor.getSelf().getType());
|
2022-07-14 01:10:18 +08:00
|
|
|
if (!selfType || !selfType.hasStaticShape())
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only tensor types with static shape are supported");
|
2022-07-14 01:10:18 +08:00
|
|
|
|
|
|
|
// Only statically deducible values are currently supported
|
|
|
|
int64_t dim;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getDim(), m_TorchConstantInt(&dim)))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "dim must be a Scalar constant");
|
2022-07-14 01:10:18 +08:00
|
|
|
|
|
|
|
dim = toPositiveDim(dim, selfType.getRank());
|
|
|
|
|
|
|
|
if (!isValidDim(dim, selfType.getRank()))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "dim must less than tensor rank");
|
2022-07-14 01:10:18 +08:00
|
|
|
|
|
|
|
int64_t start;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getStart(), m_TorchConstantInt(&start)))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "start must be a Scalar constant");
|
2022-07-14 01:10:18 +08:00
|
|
|
|
2024-01-12 02:36:48 +08:00
|
|
|
if (start < 0) {
|
|
|
|
start = toPositiveDim(start, selfType.getShape()[dim]);
|
|
|
|
if (!isValidDim(start, selfType.getShape()[dim]))
|
|
|
|
return rewriter.notifyMatchFailure(op, "start is not a valid index");
|
|
|
|
}
|
2023-07-20 15:53:54 +08:00
|
|
|
start = std::min(selfType.getShape()[dim], start);
|
|
|
|
|
2022-07-14 01:10:18 +08:00
|
|
|
int64_t end;
|
2023-07-20 15:53:54 +08:00
|
|
|
if (!matchPattern(op.getEnd(), m_TorchConstantInt(&end))) {
|
|
|
|
if (isa<ConstantNoneOp>(op.getEnd().getDefiningOp()))
|
|
|
|
end = selfType.getShape()[dim];
|
|
|
|
else
|
|
|
|
return rewriter.notifyMatchFailure(op, "end must be a Scalar constant");
|
|
|
|
}
|
2023-04-07 07:19:00 +08:00
|
|
|
// support for end < 0
|
|
|
|
end = toPositiveDim(end, selfType.getShape()[dim]);
|
2023-06-07 01:38:04 +08:00
|
|
|
// support for end out of upper bound
|
|
|
|
end = (end > selfType.getShape()[dim] ? selfType.getShape()[dim] : end);
|
2022-07-14 01:10:18 +08:00
|
|
|
|
2023-04-07 07:19:00 +08:00
|
|
|
// FIXME: add support for start < 0 and end < start
|
2022-07-14 01:10:18 +08:00
|
|
|
if (end < start)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Currently unsupported: end < start");
|
2022-07-14 01:10:18 +08:00
|
|
|
|
|
|
|
int64_t step;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getStep(), m_TorchConstantInt(&step)))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "step must be a Scalar constant");
|
2022-07-14 01:10:18 +08:00
|
|
|
|
|
|
|
if (step != 1)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "step value other than 1 is currently unsupported");
|
2022-07-14 01:10:18 +08:00
|
|
|
|
|
|
|
SmallVector<int64_t> startSlice(selfType.getRank(), 0);
|
2022-11-29 20:33:31 +08:00
|
|
|
SmallVector<int64_t> sizeSlice =
|
|
|
|
llvm::to_vector(makeShapeTorchCompatible(selfType.getShape()));
|
2022-07-14 01:10:18 +08:00
|
|
|
|
|
|
|
startSlice[dim] = start;
|
|
|
|
sizeSlice[dim] = end - start;
|
|
|
|
|
|
|
|
rewriter.replaceOpWithNewOp<tosa::SliceOp>(
|
2022-12-08 04:20:41 +08:00
|
|
|
op, getTypeConverter()->convertType(op.getType()), adaptor.getSelf(),
|
2023-01-11 07:07:19 +08:00
|
|
|
rewriter.getDenseI64ArrayAttr(startSlice),
|
|
|
|
rewriter.getDenseI64ArrayAttr(sizeSlice));
|
2022-07-14 01:10:18 +08:00
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2022-09-21 01:04:51 +08:00
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenBroadcastToOp>::matchAndRewrite(
|
|
|
|
AtenBroadcastToOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
|
|
|
// Not a tensor type.
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfType = dyn_cast<TensorType>(adaptor.getSelf().getType());
|
2022-09-21 01:04:51 +08:00
|
|
|
if (!selfType || !selfType.hasStaticShape())
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only tensor types with static shape are supported");
|
|
|
|
|
|
|
|
auto selfElemTy = selfType.getElementType();
|
|
|
|
if (!selfElemTy.isIntOrFloat()) {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only floating-point or integer datatype legalization supported");
|
|
|
|
}
|
|
|
|
|
2023-02-10 01:15:14 +08:00
|
|
|
SmallVector<int64_t> resultShape;
|
|
|
|
if (!matchPattern(op.getSize(), m_TorchListOfConstantInts(resultShape)))
|
2022-09-21 01:04:51 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"size must consist of Scalar constants");
|
2023-02-10 01:15:14 +08:00
|
|
|
// Get the result type
|
|
|
|
auto resultType = getTypeConverter()->convertType(op.getType());
|
2022-09-21 01:04:51 +08:00
|
|
|
|
2022-11-29 20:33:31 +08:00
|
|
|
SmallVector<int64_t> inputShape(
|
|
|
|
makeShapeTorchCompatible(selfType.getShape()));
|
2023-06-12 17:17:25 +08:00
|
|
|
// Result dimension -1 means not changing the size of that dimension.
|
|
|
|
// Adjust it by assigning its inputShape.
|
|
|
|
for (auto shape : llvm::enumerate(makeShapeTorchCompatible(inputShape))) {
|
|
|
|
auto index = shape.index();
|
|
|
|
if (resultShape[index] == -1)
|
|
|
|
resultShape[index] = shape.value();
|
|
|
|
}
|
2023-02-10 01:15:14 +08:00
|
|
|
// Check for identity case i.e, for ex: [a, b, c] -> [a, b, c]. If this is
|
|
|
|
// true then we can replace the op result with the input operand directly.
|
|
|
|
if (llvm::equal(inputShape, resultShape)) {
|
|
|
|
// If we reach here, then it means that the broadcasting is not required
|
|
|
|
// since the input and result are of same shape.
|
|
|
|
op.replaceAllUsesWith(op.getSelf());
|
|
|
|
rewriter.eraseOp(op);
|
|
|
|
return success();
|
|
|
|
} else if (selfType.hasRank() &&
|
|
|
|
(selfType.getRank() == (int64_t)resultShape.size() ||
|
|
|
|
selfType.getRank() == 0)) {
|
|
|
|
// Right now to support limited cases where input and result shape are not
|
|
|
|
// equal, we can put a constraint that either the input should be of rank
|
|
|
|
// 0 or the rank of input tensor and result should be equal. And then we
|
|
|
|
// can check for broadcasting compatibility for the latter case. For
|
|
|
|
// broadcasting compatibility, either the shape of input and result should
|
|
|
|
// be equal at each dimenion or one of them should be 1.
|
|
|
|
if (selfType.getRank() != 0) {
|
|
|
|
for (unsigned i = 0; i < inputShape.size(); i++) {
|
|
|
|
if (inputShape[i] != resultShape[i] && inputShape[i] != 1 &&
|
|
|
|
resultShape[i] != 1) {
|
2022-09-30 00:40:56 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
2023-02-10 01:15:14 +08:00
|
|
|
op, "unimplemented: either the shape of input and result should "
|
|
|
|
"be equal at each dimenion or one of them should be 1.");
|
2022-09-30 00:40:56 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-02-10 01:15:14 +08:00
|
|
|
|
|
|
|
// If the above condition hold true then we can directly create a const
|
|
|
|
// zero tensor of shape same as the result shape.
|
|
|
|
SmallVector<int64_t> zeroTensorShape{resultShape};
|
|
|
|
|
|
|
|
// create the 0 constant tensor
|
|
|
|
int64_t totalNumElements = 1;
|
|
|
|
for (auto dimSize : zeroTensorShape) {
|
|
|
|
totalNumElements = dimSize * totalNumElements;
|
|
|
|
}
|
|
|
|
// There is some danger here. For edge cases in floating point, x + 0 != x.
|
|
|
|
// The cases are denormalized values, which may get flushed, and -0 + 0 =
|
|
|
|
// +0. (sign bit flips). These are probably acceptable in the short term,
|
|
|
|
// but we should put a comment acknowledging the danger, as there isn't an
|
|
|
|
// op that avoids the denorm flushing.
|
2023-05-19 08:12:18 +08:00
|
|
|
Value zeroTensor =
|
|
|
|
tosa::getZerosLikeTensor(rewriter, op, resultType).value();
|
2023-02-10 01:15:14 +08:00
|
|
|
|
|
|
|
// Use add broadcast
|
|
|
|
rewriter.replaceOpWithNewOp<tosa::AddOp>(op, resultType, adaptor.getSelf(),
|
|
|
|
zeroTensor);
|
2022-09-30 00:40:56 +08:00
|
|
|
return success();
|
|
|
|
}
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op,
|
|
|
|
"unimplemented: broadcasts other than same rank or zero ranked tensor.");
|
2022-09-21 01:04:51 +08:00
|
|
|
}
|
|
|
|
|
2022-12-22 03:04:07 +08:00
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenGatherOp>::matchAndRewrite(
|
|
|
|
AtenGatherOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
// For easy understanding of this algorithm, I will comment the code with an
|
|
|
|
// exact example: torch.aten.gather (!torch.vtensor<[1,4,3],f32>,
|
|
|
|
// !torch.int-1, !torch.vtensor<[1,4,2],si64>)
|
|
|
|
// -> !torch.vtensor<[1,4,2],f32>
|
|
|
|
// https://gist.github.com/AmosLewis/2f18434397025211da4491735bcc6db6
|
|
|
|
|
|
|
|
// Not a tensor type.
|
|
|
|
auto input = adaptor.getSelf();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto inputType = dyn_cast<RankedTensorType>(adaptor.getSelf().getType());
|
2022-12-22 03:04:07 +08:00
|
|
|
if (!inputType)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only RankedTensorType input are currently supported");
|
|
|
|
|
|
|
|
auto index = adaptor.getIndex();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto indexType = dyn_cast<RankedTensorType>(adaptor.getIndex().getType());
|
2022-12-22 03:04:07 +08:00
|
|
|
auto inputShape = inputType.getShape();
|
|
|
|
int paramsRank = inputShape.size();
|
|
|
|
|
|
|
|
if (!indexType)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only RankedTensorType index are currently supported");
|
|
|
|
|
|
|
|
// Check `index` and `input` param should have the same rank
|
|
|
|
if (indexType.getRank() != inputType.getRank())
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "`index` and `input` param should have the same rank");
|
|
|
|
|
|
|
|
// Dynamic shape check
|
|
|
|
if (!inputType.hasStaticShape() || !indexType.hasStaticShape())
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "AtenGatherOp: support for dynamic input "
|
|
|
|
"shape not implemented");
|
|
|
|
|
|
|
|
// index i64 to i32 for tosa compatitable
|
|
|
|
if (indexType.getElementType() != rewriter.getIntegerType(32)) {
|
|
|
|
index = rewriter.create<tosa::CastOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
RankedTensorType::get(indexType.getShape(),
|
|
|
|
rewriter.getIntegerType(32)),
|
|
|
|
index);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get positive dim
|
|
|
|
int64_t dim{0};
|
|
|
|
if (!matchPattern(op.getDim(), m_TorchConstantInt(&dim)))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "unimplemented: value `dim` should be a torch constant int");
|
|
|
|
dim = toPositiveDim(dim, paramsRank);
|
|
|
|
if (!isValidDim(dim, paramsRank))
|
|
|
|
return rewriter.notifyMatchFailure(op, "Not dim are invalid");
|
|
|
|
|
|
|
|
// check sparseGrad is bool type
|
|
|
|
bool sparseGrad = false;
|
|
|
|
if (!matchPattern(op.getSparseGrad(), m_TorchConstantBool(&sparseGrad)))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "only constant boolean `sparse_grad` param supported");
|
|
|
|
if (sparseGrad)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "only constant boolean `sparse_grad` == false supported");
|
|
|
|
|
|
|
|
// Get the output type
|
|
|
|
auto outType = getTypeConverter()->convertType(op.getType());
|
|
|
|
|
|
|
|
// convert torch style index and dim into tf style indices
|
|
|
|
// tensor<[1,4,2],si64> -> tensor<[1,4,2,3],si64>
|
|
|
|
auto indicesTf =
|
|
|
|
tosa::convertTorchIndexToTfIndices(rewriter, op, input, index, dim);
|
|
|
|
if (!indicesTf) {
|
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Convert TorchIndex To TfIndices fail.");
|
|
|
|
}
|
|
|
|
|
|
|
|
// do the tf gathernp algorithm with tf style indices as input.
|
|
|
|
auto result =
|
|
|
|
tosa::convertGatherNdOp(rewriter, op, outType, input, indicesTf.value());
|
|
|
|
|
|
|
|
if (!result) {
|
|
|
|
return rewriter.notifyMatchFailure(op, "Convert GatherNdOp fail.");
|
|
|
|
}
|
|
|
|
rewriter.replaceOp(op, {result.value()});
|
|
|
|
return success();
|
|
|
|
}
|
2022-10-19 00:39:39 +08:00
|
|
|
|
2023-07-18 00:51:24 +08:00
|
|
|
template <>
|
2024-05-08 22:44:57 +08:00
|
|
|
LogicalResult ConvertAtenOp<AtenIndexPutHackedTwinOp>::matchAndRewrite(
|
|
|
|
AtenIndexPutHackedTwinOp op, OpAdaptor adaptor,
|
2023-07-18 00:51:24 +08:00
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
// a = torch.tensor([[0, 1, 2, 3]])
|
|
|
|
// a[..., 1:] = torch.tensor([4, 5, 6])
|
|
|
|
// = a[..., 1:4] = torch.tensor([4, 5, 6])
|
|
|
|
// = a[[0, 0, 0], [1, 2, 3]] = torch.tensor([4, 5, 6]) # tensor([[0, 4, 5,
|
|
|
|
// 6]]) = torch.ops.aten.index_put(torch.tensor([[0, 1, 2, 3]]), # input
|
|
|
|
// (torch.tensor([0, 0, 0]), torch.tensor([1, 2,
|
|
|
|
// 3])), # indicies torch.tensor([4, 5, 6])) #
|
|
|
|
// value
|
|
|
|
// = torch.ops.aten.index_put(torch.tensor([[0, 1, 2, 3]]), # input
|
|
|
|
// (None, torch.tensor([1, 2, 3]),),# indicies
|
|
|
|
// torch.tensor([4, 5, 6])) # value
|
|
|
|
|
|
|
|
// Not a tensor type.
|
|
|
|
auto input = adaptor.getSelf();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfType = dyn_cast<TensorType>(adaptor.getSelf().getType());
|
2023-07-18 00:51:24 +08:00
|
|
|
if (!selfType)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only tensor types input are currently supported");
|
|
|
|
|
|
|
|
auto fillValues = adaptor.getValues();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto valuesType = dyn_cast<TensorType>(adaptor.getValues().getType());
|
2023-07-18 00:51:24 +08:00
|
|
|
if (!valuesType)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only tensor types input are currently supported");
|
|
|
|
|
|
|
|
// Deal with torch.prim.ListConstruct of non const value to get the index
|
|
|
|
auto tensorList = op.getIndices();
|
|
|
|
SmallVector<Value> tensorsTorchType;
|
|
|
|
if (!getListConstructElements(tensorList, tensorsTorchType))
|
|
|
|
return op.emitError(
|
|
|
|
"unimplemented: the tensor list is not from list construct");
|
|
|
|
auto indexTensors = getTypeConvertedValues(
|
|
|
|
rewriter, op->getLoc(), getTypeConverter(), tensorsTorchType);
|
|
|
|
|
|
|
|
auto outType = getTypeConverter()->convertType(op.getType());
|
|
|
|
|
|
|
|
// convert list of indices with none into indices tensor without none
|
|
|
|
// indexTensors (none,[1,2,3]) -> ([0,0,0],[1,2,3])
|
|
|
|
// ([[0],[0],[0]],[[1],[2],[3]])-> [[0,1],[0,2], [0,3]]
|
|
|
|
if (indexTensors.size() <= 1) {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only support indexput with multiple index.");
|
|
|
|
}
|
|
|
|
SmallVector<Value> indicesTfConcatTensors;
|
|
|
|
SmallVector<int64_t> indexesRank;
|
|
|
|
SmallVector<SmallVector<int64_t>> indexesShape;
|
|
|
|
|
|
|
|
// concat index tensor into to indices tensor for concat
|
|
|
|
for (size_t i = 0; i < indexTensors.size(); i++) {
|
|
|
|
auto index = indexTensors[i];
|
|
|
|
auto indexTorch = tensorsTorchType[i];
|
|
|
|
// TODO add support for none index other than i==0, like (index0, None)
|
|
|
|
// (None, index1)
|
2024-05-31 14:45:13 +08:00
|
|
|
if (i == 0 && isa<Torch::NoneType>(indexTorch.getType())) {
|
2023-07-18 00:51:24 +08:00
|
|
|
// convert None to [0,0,0]
|
|
|
|
auto indexNext = indexTensors[i + 1];
|
|
|
|
auto indexNextTorch = tensorsTorchType[i + 1];
|
2024-05-31 14:45:13 +08:00
|
|
|
if (isa<Torch::NoneType>(indexNextTorch.getType())) {
|
2023-07-18 00:51:24 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Multiple None index is not support for now.");
|
|
|
|
}
|
2024-04-28 05:00:56 +08:00
|
|
|
auto indexNextType = dyn_cast<RankedTensorType>(indexNext.getType());
|
2023-07-18 00:51:24 +08:00
|
|
|
auto indexNextShape = indexNextType.getShape();
|
|
|
|
|
|
|
|
int64_t size = 1;
|
|
|
|
for (auto s : indexNextShape)
|
|
|
|
size *= s;
|
|
|
|
SmallVector<int32_t> values(size, i);
|
|
|
|
index =
|
|
|
|
tosa::getConstTensor<int32_t>(rewriter, op, values, indexNextShape)
|
|
|
|
.value();
|
|
|
|
}
|
|
|
|
|
2024-04-28 05:00:56 +08:00
|
|
|
auto indexType = dyn_cast<RankedTensorType>(index.getType());
|
2023-07-18 00:51:24 +08:00
|
|
|
auto indexShape = indexType.getShape();
|
|
|
|
indexesShape.push_back(makeShapeTorchCompatible(indexShape));
|
|
|
|
indexesRank.push_back(indexType.getRank());
|
|
|
|
|
|
|
|
// index i64 to i32 for tosa compatible
|
|
|
|
if (indexType.getElementType() != rewriter.getIntegerType(32)) {
|
|
|
|
index = rewriter.create<tosa::CastOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
RankedTensorType::get(indexShape, rewriter.getIntegerType(32)),
|
|
|
|
index);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Expand last dim of index to tf indices [3] -> [3,1]
|
|
|
|
// convert [0,0,0] to [[0],[0],[0]]
|
|
|
|
SmallVector<int64_t> indiceShapeOneDim;
|
|
|
|
for (auto shape : indexShape) {
|
|
|
|
indiceShapeOneDim.push_back(shape);
|
|
|
|
}
|
|
|
|
indiceShapeOneDim.push_back(1);
|
|
|
|
auto indicesTfOneDim = tosa::CreateOpAndInfer<tosa::ReshapeOp>(
|
|
|
|
rewriter, op->getLoc(),
|
|
|
|
RankedTensorType::get(indiceShapeOneDim, rewriter.getIntegerType(32)),
|
|
|
|
index, rewriter.getDenseI64ArrayAttr(indiceShapeOneDim));
|
|
|
|
|
|
|
|
// create concat tensor for indicesTf
|
|
|
|
// ([[0],[0],[0]], [[1],[2],[3]])
|
|
|
|
indicesTfConcatTensors.push_back(indicesTfOneDim.getResult());
|
|
|
|
}
|
|
|
|
|
|
|
|
// Right now only support multiple indexes with same shape
|
|
|
|
// TODO for different shape multiple indexes, add broadcast_to for small
|
|
|
|
// shape
|
|
|
|
for (auto indexShapeOneDim : indexesShape) {
|
|
|
|
if (!llvm::equal(indexesShape[0], indexShapeOneDim)) {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "unimplemented: Only support multi indexes with same shape");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// concat each indices into indicesTf: shape ([3,1],[3,1]) -> [3,2]
|
|
|
|
// ([0,0,0],[1,2,3]) -> [[0,1],[0,2], [0,3]]
|
|
|
|
auto indicesShapeConcat = indexesShape[0];
|
|
|
|
uint64_t lastDim = indexesRank[0];
|
|
|
|
indicesShapeConcat.push_back(indicesTfConcatTensors.size());
|
|
|
|
auto indicesTf = tosa::CreateOpAndInfer<tosa::ConcatOp>(
|
|
|
|
rewriter, op->getLoc(),
|
|
|
|
GetTypeFromTensorShape(indicesShapeConcat, rewriter.getIntegerType(32)),
|
|
|
|
indicesTfConcatTensors, lastDim);
|
|
|
|
|
|
|
|
if (!indicesTf) {
|
2023-09-21 01:48:40 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Convert TorchIndex To TfIndices fail.");
|
2023-07-18 00:51:24 +08:00
|
|
|
}
|
2023-09-21 01:48:40 +08:00
|
|
|
// do the tf scatterNd algorithm with tf style indices as input, algorithm
|
|
|
|
// mostly take from convertGatherNdOp.
|
2023-07-18 00:51:24 +08:00
|
|
|
auto result = tosa::convertScatterNdOp(rewriter, op, outType, input,
|
2023-09-21 01:48:40 +08:00
|
|
|
indicesTf.getResult(), fillValues);
|
2023-07-18 00:51:24 +08:00
|
|
|
|
|
|
|
if (!result) {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Convert ScatterNdOp fail for index tensor.");
|
|
|
|
}
|
|
|
|
rewriter.replaceOp(op, {result.value()});
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2023-01-20 13:19:00 +08:00
|
|
|
template <>
|
2023-08-15 19:36:08 +08:00
|
|
|
LogicalResult ConvertAtenOp<AtenIndexTensorHackedTwinOp>::matchAndRewrite(
|
|
|
|
AtenIndexTensorHackedTwinOp op, OpAdaptor adaptor,
|
2023-01-20 13:19:00 +08:00
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
// t = tf.constant([[1, 2, 3, 4, 5],[6,7,8,9,10],
|
|
|
|
// [11,12,13,14,15],[16,17,18,19,20]]) # 4*5
|
|
|
|
// i = tf.constant([[1,2,3], [3,2,1]]) # 2*3
|
|
|
|
// i_expand = tf.expand_dims(i,axis=2) # 2*3*1
|
|
|
|
// IndexTensorOutput = tf.gather_nd(t,tf.i_expand)
|
|
|
|
// = torch.ops.aten.index(t, (i, )) = t[i] # 2*3*5
|
|
|
|
// [[[ 6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]],
|
|
|
|
// [[16, 17, 18, 19, 20], [11, 12, 13, 14, 15], [ 6, 7, 8, 9, 10]]]
|
|
|
|
auto input = adaptor.getSelf();
|
|
|
|
auto inputTensorType =
|
2024-04-28 05:00:56 +08:00
|
|
|
dyn_cast<RankedTensorType>(adaptor.getSelf().getType());
|
2023-01-20 13:19:00 +08:00
|
|
|
// Check input is a tensor type.
|
|
|
|
if (!inputTensorType)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only tensor types input are currently supported");
|
|
|
|
|
|
|
|
// Deal with torch.prim.ListConstruct of non const value to get the index
|
|
|
|
auto tensorList = op.getIndices();
|
|
|
|
SmallVector<Value> tensorsTorchType;
|
|
|
|
if (!getListConstructElements(tensorList, tensorsTorchType))
|
|
|
|
return op.emitError(
|
|
|
|
"unimplemented: the tensor list is not from list construct");
|
2023-02-14 15:07:15 +08:00
|
|
|
auto indexTensors = getTypeConvertedValues(
|
|
|
|
rewriter, op->getLoc(), getTypeConverter(), tensorsTorchType);
|
2023-01-20 13:19:00 +08:00
|
|
|
|
2023-02-14 15:07:15 +08:00
|
|
|
auto outType = getTypeConverter()->convertType(op.getType());
|
|
|
|
|
|
|
|
// Support for multiple indexes
|
|
|
|
if (indexTensors.size() > 1) {
|
|
|
|
// t[i, i]
|
|
|
|
// = torch.ops.aten.index(t,(i,i))
|
|
|
|
// = tensor([[ t[1,1], t[2,2], t[3,3]],
|
|
|
|
// [ t[3,3], t[2,2], t[1,1]]])
|
|
|
|
// = tensor([[ 7, 13, 19], [19, 13, 7]])
|
|
|
|
// = tf.gather_nd(t,tf.ii_expand)
|
|
|
|
// ii_expand
|
|
|
|
// = tf.concat((i_expand,i_expand), dim=2)
|
|
|
|
// = tf.constant([[[1,1],[2,2],[3,3]],
|
|
|
|
// [[3,3],[2,2],[1,1]]]) # 2*3*2
|
|
|
|
SmallVector<Value> indicesTfConcatTensors;
|
|
|
|
SmallVector<int64_t> indexesRank;
|
|
|
|
SmallVector<SmallVector<int64_t>> indexesShape;
|
|
|
|
|
|
|
|
// concat index tensor into to indices tensor for concat
|
|
|
|
for (size_t i = 0; i < indexTensors.size(); i++) {
|
|
|
|
auto index = indexTensors[i];
|
|
|
|
|
2024-04-28 05:00:56 +08:00
|
|
|
auto indexType = dyn_cast<RankedTensorType>(index.getType());
|
2023-02-14 15:07:15 +08:00
|
|
|
auto indexShape = indexType.getShape();
|
|
|
|
indexesShape.push_back(makeShapeTorchCompatible(indexShape));
|
|
|
|
indexesRank.push_back(indexType.getRank());
|
|
|
|
|
2023-07-18 00:51:24 +08:00
|
|
|
// Make type of index tosa compatible, i64 to i32.
|
2023-02-14 15:07:15 +08:00
|
|
|
if (indexType.getElementType() != rewriter.getIntegerType(32)) {
|
|
|
|
index = rewriter.create<tosa::CastOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
RankedTensorType::get(indexShape, rewriter.getIntegerType(32)),
|
|
|
|
index);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Expand last dim of index to tf indices [2,3] -> [2,3,1]
|
|
|
|
SmallVector<int64_t> indiceShapeOneDim;
|
|
|
|
for (auto shape : indexShape) {
|
|
|
|
indiceShapeOneDim.push_back(shape);
|
|
|
|
}
|
|
|
|
indiceShapeOneDim.push_back(1);
|
|
|
|
auto indicesTfOneDim = tosa::CreateOpAndInfer<tosa::ReshapeOp>(
|
|
|
|
rewriter, op->getLoc(),
|
|
|
|
RankedTensorType::get(indiceShapeOneDim, rewriter.getIntegerType(32)),
|
|
|
|
index, rewriter.getDenseI64ArrayAttr(indiceShapeOneDim));
|
|
|
|
|
|
|
|
// create concat tensor for indicesTf
|
|
|
|
indicesTfConcatTensors.push_back(indicesTfOneDim.getResult());
|
|
|
|
}
|
|
|
|
|
2024-07-31 05:32:05 +08:00
|
|
|
auto getRankExtendedShape =
|
|
|
|
[](SmallVector<int64_t> inputShape,
|
|
|
|
SmallVector<int64_t> maxRank1DimShape) -> SmallVector<int64_t> {
|
|
|
|
SmallVector<int64_t> rankExtendedShape(maxRank1DimShape);
|
|
|
|
auto inputRank = inputShape.size();
|
|
|
|
auto maxRank = maxRank1DimShape.size();
|
|
|
|
auto startIdx = maxRank - inputRank;
|
|
|
|
for (size_t i = startIdx; i < maxRank; i++) {
|
|
|
|
rankExtendedShape[i] = inputShape[i - startIdx];
|
|
|
|
}
|
|
|
|
return rankExtendedShape;
|
|
|
|
};
|
|
|
|
|
|
|
|
bool hasDiffShapedIndexes = false;
|
2023-02-14 15:07:15 +08:00
|
|
|
for (auto indexShapeOneDim : indexesShape) {
|
|
|
|
if (!llvm::equal(indexesShape[0], indexShapeOneDim)) {
|
2024-07-31 05:32:05 +08:00
|
|
|
hasDiffShapedIndexes = true;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (hasDiffShapedIndexes) {
|
|
|
|
int64_t maxRank = 1;
|
|
|
|
for (auto idxRank : indexesRank) {
|
|
|
|
if (idxRank > maxRank)
|
|
|
|
maxRank = idxRank;
|
|
|
|
}
|
|
|
|
// Tensor shape of max rank, each dim being 1
|
|
|
|
SmallVector<int64_t> maxRank1DimShape;
|
|
|
|
for (int i = 0; i < maxRank; i++)
|
|
|
|
maxRank1DimShape.push_back(1);
|
|
|
|
// Tensor shape of max rank, each dim being the max dim.
|
|
|
|
SmallVector<int64_t> maxRankMaxDimShape(maxRank1DimShape);
|
|
|
|
|
|
|
|
auto updateMaxRankMaxDimShape =
|
|
|
|
[&](SmallVector<int64_t> broadcastedShape) -> LogicalResult {
|
|
|
|
for (size_t i = 0; i < maxRankMaxDimShape.size(); i++) {
|
|
|
|
// check for malformed index tensors
|
|
|
|
if (broadcastedShape[i] != 1 && maxRankMaxDimShape[i] != 1 &&
|
|
|
|
maxRankMaxDimShape[i] != broadcastedShape[i]) {
|
|
|
|
return failure();
|
|
|
|
}
|
|
|
|
if (broadcastedShape[i] > maxRankMaxDimShape[i])
|
|
|
|
maxRankMaxDimShape[i] = broadcastedShape[i];
|
|
|
|
}
|
|
|
|
return success();
|
|
|
|
};
|
|
|
|
|
|
|
|
for (size_t i = 0; i < indexesRank.size(); i++) {
|
|
|
|
// Reshape all index tensors to same maxRank
|
|
|
|
auto idxRank = indexesRank[i];
|
|
|
|
auto unreshapedIdxTensor = indicesTfConcatTensors[i];
|
|
|
|
SmallVector<int64_t> broadcastedShape =
|
|
|
|
getRankExtendedShape(indexesShape[i], maxRank1DimShape);
|
|
|
|
|
|
|
|
if (idxRank < maxRank) {
|
|
|
|
auto idxType =
|
|
|
|
dyn_cast<RankedTensorType>(indicesTfConcatTensors[i].getType());
|
|
|
|
// indicesTfConcatTensors has a trailing [1] dim for the final concat.
|
|
|
|
auto broadcastedShapeTf(broadcastedShape);
|
|
|
|
broadcastedShapeTf.push_back(1);
|
|
|
|
auto reshapeOutputTy = RankedTensorType::get(
|
|
|
|
broadcastedShapeTf, idxType.getElementType());
|
|
|
|
// Update the tensor array with the max rank-extended form
|
|
|
|
indicesTfConcatTensors[i] = rewriter.create<tosa::ReshapeOp>(
|
|
|
|
op->getLoc(), reshapeOutputTy, unreshapedIdxTensor,
|
|
|
|
rewriter.getDenseI64ArrayAttr(broadcastedShapeTf));
|
|
|
|
}
|
|
|
|
|
|
|
|
// Construct the max rank broadcasted form of all index tensors with
|
|
|
|
// each index tensor.
|
|
|
|
if (updateMaxRankMaxDimShape(broadcastedShape).failed()) {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Malformed index tensors that have mismatched dim shapes");
|
|
|
|
}
|
|
|
|
|
|
|
|
// Every index now has the same rank but not yet same shape until
|
|
|
|
// tosa.tile below.
|
|
|
|
indexesShape[i] = broadcastedShape;
|
|
|
|
indexesRank[i] = maxRank;
|
|
|
|
}
|
|
|
|
|
|
|
|
auto getTileOpShape = [&](SmallVector<int64_t> indexShape,
|
|
|
|
SmallVector<int64_t> &tileOpShape) -> bool {
|
|
|
|
bool needsTiling = false;
|
|
|
|
for (size_t i = 0; i < indexShape.size(); i++) {
|
|
|
|
if (1 == indexShape[i]) {
|
|
|
|
tileOpShape.push_back(maxRankMaxDimShape[i]);
|
|
|
|
needsTiling = true;
|
|
|
|
} else {
|
|
|
|
tileOpShape.push_back(1);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return needsTiling;
|
|
|
|
};
|
|
|
|
|
|
|
|
// Use tosa.tile to broadcast in multiple dims so all index tensors have
|
|
|
|
// the same shape. This materializes new tensors.
|
|
|
|
for (size_t i = 0; i < indexesRank.size(); i++) {
|
|
|
|
SmallVector<int64_t> tileOpShape;
|
|
|
|
bool needsTiling = getTileOpShape(indexesShape[i], tileOpShape);
|
|
|
|
|
|
|
|
if (needsTiling) {
|
|
|
|
auto idxType =
|
|
|
|
dyn_cast<RankedTensorType>(indicesTfConcatTensors[i].getType());
|
|
|
|
// indicesTfConcatTensors has a trailing [1] dim for the final concat.
|
|
|
|
auto maxRankMaxDimShapeTf(maxRankMaxDimShape);
|
|
|
|
maxRankMaxDimShapeTf.push_back(1);
|
|
|
|
auto tileOpShapeTf(tileOpShape);
|
|
|
|
tileOpShapeTf.push_back(1);
|
|
|
|
auto tileOutputTy = RankedTensorType::get(maxRankMaxDimShapeTf,
|
|
|
|
idxType.getElementType());
|
|
|
|
auto reshapedIdxTensor = indicesTfConcatTensors[i];
|
|
|
|
indicesTfConcatTensors[i] = rewriter.create<tosa::TileOp>(
|
|
|
|
op->getLoc(), tileOutputTy, reshapedIdxTensor,
|
|
|
|
rewriter.getDenseI64ArrayAttr(tileOpShapeTf));
|
|
|
|
}
|
|
|
|
|
|
|
|
// Every index tensor now has the same rank and shape
|
|
|
|
indexesShape[i] = maxRankMaxDimShape;
|
2023-02-14 15:07:15 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// concat each indices into indicesTf: shape [2,3,1],[2,3,1] -> [2,3,2]
|
|
|
|
auto indicesShapeConcat = indexesShape[0];
|
|
|
|
uint64_t lastDim = indexesRank[0];
|
|
|
|
indicesShapeConcat.push_back(indicesTfConcatTensors.size());
|
|
|
|
auto indicesTf = tosa::CreateOpAndInfer<tosa::ConcatOp>(
|
|
|
|
rewriter, op->getLoc(),
|
|
|
|
GetTypeFromTensorShape(indicesShapeConcat, rewriter.getIntegerType(32)),
|
|
|
|
indicesTfConcatTensors, lastDim);
|
|
|
|
|
|
|
|
if (!indicesTf) {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Convert TorchIndex To TfIndices fail.");
|
|
|
|
}
|
|
|
|
// do the tf gathernp algorithm with tf style indices as input.
|
|
|
|
auto result = tosa::convertGatherNdOp(rewriter, op, outType, input,
|
|
|
|
indicesTf.getResult());
|
|
|
|
|
|
|
|
if (!result) {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Convert GatherNdOp fail for index tensor.");
|
|
|
|
}
|
|
|
|
rewriter.replaceOp(op, {result.value()});
|
|
|
|
|
|
|
|
return success();
|
2023-01-20 13:19:00 +08:00
|
|
|
}
|
2023-02-14 15:07:15 +08:00
|
|
|
|
|
|
|
// Support for multiple index
|
|
|
|
auto index = indexTensors[0];
|
2024-04-28 05:00:56 +08:00
|
|
|
auto indexType = dyn_cast<RankedTensorType>(index.getType());
|
2023-01-20 13:19:00 +08:00
|
|
|
auto indexShape = indexType.getShape();
|
|
|
|
// index i64 to i32 for tosa compatible
|
|
|
|
if (indexType.getElementType() != rewriter.getIntegerType(32)) {
|
|
|
|
index = rewriter.create<tosa::CastOp>(
|
|
|
|
op->getLoc(),
|
|
|
|
RankedTensorType::get(indexShape, rewriter.getIntegerType(32)), index);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Expand last dim of index to tf indices [2,3] -> [2,3,1]
|
|
|
|
SmallVector<int64_t> indicesShape;
|
|
|
|
for (auto shape : indexShape) {
|
|
|
|
indicesShape.push_back(shape);
|
|
|
|
}
|
|
|
|
indicesShape.push_back(1);
|
|
|
|
auto indicesTf = tosa::CreateOpAndInfer<tosa::ReshapeOp>(
|
|
|
|
rewriter, op->getLoc(),
|
|
|
|
RankedTensorType::get(indicesShape, rewriter.getIntegerType(32)), index,
|
|
|
|
rewriter.getDenseI64ArrayAttr(indicesShape));
|
|
|
|
|
|
|
|
if (!indicesTf) {
|
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Convert TorchIndex To TfIndices fail.");
|
|
|
|
}
|
|
|
|
// do the tf gathernp algorithm with tf style indices as input.
|
|
|
|
auto result = tosa::convertGatherNdOp(rewriter, op, outType, input,
|
|
|
|
indicesTf.getResult());
|
|
|
|
|
|
|
|
if (!result) {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Convert GatherNdOp fail for index tensor.");
|
|
|
|
}
|
|
|
|
rewriter.replaceOp(op, {result.value()});
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2023-04-14 23:43:39 +08:00
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenAbsOp>::matchAndRewrite(
|
|
|
|
AtenAbsOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
// Not a tensor type.
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfType = dyn_cast<TensorType>(adaptor.getSelf().getType());
|
2023-04-14 23:43:39 +08:00
|
|
|
if (!selfType)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only tensor types input are currently supported");
|
|
|
|
|
|
|
|
auto outType = getTypeConverter()->convertType(op.getType());
|
|
|
|
rewriter.replaceOpWithNewOp<tosa::AbsOp>(op, outType, adaptor.getSelf());
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2022-10-19 00:39:39 +08:00
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenWhereSelfOp>::matchAndRewrite(
|
|
|
|
AtenWhereSelfOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
|
|
|
// Not a tensor type.
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfType = dyn_cast<TensorType>(adaptor.getSelf().getType());
|
2022-10-19 00:39:39 +08:00
|
|
|
if (!selfType)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only tensor types input are currently supported");
|
2024-04-28 05:00:56 +08:00
|
|
|
auto condType = dyn_cast<TensorType>(adaptor.getCondition().getType());
|
2022-10-19 00:39:39 +08:00
|
|
|
if (!condType)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only tensor types condition are currently supported");
|
|
|
|
|
|
|
|
auto outType = getTypeConverter()->convertType(op.getType());
|
2023-01-11 13:42:07 +08:00
|
|
|
rewriter.replaceOpWithNewOp<tosa::SelectOp>(
|
|
|
|
op, outType, adaptor.getCondition(), adaptor.getSelf(),
|
|
|
|
adaptor.getOther());
|
2022-10-19 00:39:39 +08:00
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2023-10-17 00:44:53 +08:00
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenIscloseOp>::matchAndRewrite(
|
|
|
|
AtenIscloseOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
// check args
|
|
|
|
double rtol, atol;
|
|
|
|
bool equalNan;
|
|
|
|
if (!matchPattern(op.getRtol(), m_TorchConstantFloat(&rtol)))
|
|
|
|
return rewriter.notifyMatchFailure(op, "rtol must be a scalar constant");
|
|
|
|
if (!matchPattern(op.getAtol(), m_TorchConstantFloat(&atol)))
|
|
|
|
return rewriter.notifyMatchFailure(op, "atol must be a scalar constant");
|
|
|
|
if (!matchPattern(op.getEqualNan(), m_TorchConstantBool(&equalNan)))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "unimplemented: equal_nan is expected to be false");
|
|
|
|
|
|
|
|
// check tensor type.
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfType = dyn_cast<TensorType>(adaptor.getSelf().getType());
|
|
|
|
auto otherType = dyn_cast<TensorType>(adaptor.getOther().getType());
|
2023-10-17 00:44:53 +08:00
|
|
|
if (!selfType || !otherType)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only tensor types input are currently supported");
|
|
|
|
if (!selfType.hasStaticShape() || !otherType.hasStaticShape())
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only tensor types with static shape are supported");
|
2024-05-31 14:45:13 +08:00
|
|
|
if (!isa<mlir::FloatType>(selfType.getElementType()) ||
|
|
|
|
!isa<mlir::FloatType>(otherType.getElementType())) {
|
2023-10-17 00:44:53 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "unimplemented: only FP element type is supported");
|
|
|
|
}
|
|
|
|
|
|
|
|
auto rhsSubOp = rewriter.create<tosa::SubOp>(
|
|
|
|
op->getLoc(), selfType, adaptor.getSelf(), adaptor.getOther());
|
|
|
|
auto rhsAbsOp =
|
|
|
|
rewriter.create<tosa::AbsOp>(op->getLoc(), selfType, rhsSubOp);
|
|
|
|
|
|
|
|
auto lhsAbsOp =
|
|
|
|
rewriter.create<tosa::AbsOp>(op->getLoc(), otherType, adaptor.getOther());
|
|
|
|
auto rtolConstOp =
|
|
|
|
tosa::getTosaConstTensorSingleF32(rewriter, op, static_cast<float>(rtol));
|
|
|
|
auto mulOp = rewriter.create<tosa::MulOp>(op->getLoc(), otherType,
|
|
|
|
rtolConstOp, lhsAbsOp, /*shift=*/0);
|
|
|
|
auto atolConstOp =
|
|
|
|
tosa::getTosaConstTensorSingleF32(rewriter, op, static_cast<float>(atol));
|
|
|
|
auto addOp =
|
|
|
|
rewriter.create<tosa::AddOp>(op->getLoc(), otherType, atolConstOp, mulOp);
|
|
|
|
|
|
|
|
auto outType = getTypeConverter()->convertType(op.getType());
|
|
|
|
rewriter.replaceOpWithNewOp<tosa::GreaterEqualOp>(op, outType, addOp,
|
|
|
|
rhsAbsOp);
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2022-11-19 05:32:13 +08:00
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenClampOp>::matchAndRewrite(
|
|
|
|
AtenClampOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
|
|
|
// Not a tensor type.
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfType = dyn_cast<TensorType>(adaptor.getSelf().getType());
|
2022-11-19 05:32:13 +08:00
|
|
|
if (!selfType)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "only tensor types input are currently supported");
|
|
|
|
|
2024-01-12 02:36:48 +08:00
|
|
|
IntegerAttr min_int =
|
|
|
|
rewriter.getI64IntegerAttr(std::numeric_limits<int64_t>::min());
|
|
|
|
IntegerAttr max_int =
|
|
|
|
rewriter.getI64IntegerAttr(std::numeric_limits<int64_t>::max());
|
|
|
|
FloatAttr min_fp =
|
|
|
|
rewriter.getF32FloatAttr(std::numeric_limits<float>::lowest());
|
|
|
|
FloatAttr max_fp =
|
|
|
|
rewriter.getF32FloatAttr(std::numeric_limits<float>::max());
|
|
|
|
|
|
|
|
auto getValAttr = [&](Value operand, IntegerAttr &intAttr,
|
|
|
|
FloatAttr &fpAttr) -> LogicalResult {
|
|
|
|
double valFloat;
|
|
|
|
int64_t valInt;
|
|
|
|
if (matchPattern(operand, m_TorchConstantFloat(&valFloat))) {
|
|
|
|
intAttr = rewriter.getI64IntegerAttr(static_cast<int64_t>(valFloat));
|
|
|
|
fpAttr = rewriter.getF32FloatAttr(static_cast<float>(valFloat));
|
|
|
|
} else if (matchPattern(operand, m_TorchConstantInt(&valInt))) {
|
|
|
|
intAttr = rewriter.getI64IntegerAttr(valInt);
|
|
|
|
fpAttr = rewriter.getF32FloatAttr(static_cast<float>(valInt));
|
|
|
|
} else {
|
|
|
|
return failure();
|
|
|
|
}
|
|
|
|
return success();
|
|
|
|
};
|
2023-10-18 05:49:47 +08:00
|
|
|
|
2024-01-12 02:36:48 +08:00
|
|
|
LogicalResult minAttrResult = getValAttr(op.getMin(), min_int, min_fp);
|
|
|
|
LogicalResult maxAttrResult = getValAttr(op.getMax(), max_int, max_fp);
|
|
|
|
if (failed(minAttrResult) && failed(maxAttrResult)) {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "either `min` or `max` should be a torch constant");
|
|
|
|
}
|
|
|
|
if (failed(minAttrResult) &&
|
|
|
|
succeeded(checkNotNone(rewriter, op, op.getMin()))) {
|
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"min attr should be a torch constant");
|
|
|
|
}
|
|
|
|
if (failed(maxAttrResult) &&
|
|
|
|
succeeded(checkNotNone(rewriter, op, op.getMax()))) {
|
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"max attr should be a torch constant");
|
2023-10-18 05:49:47 +08:00
|
|
|
}
|
2022-11-19 05:32:13 +08:00
|
|
|
|
|
|
|
auto outType = getTypeConverter()->convertType(op.getType());
|
2023-01-11 13:42:07 +08:00
|
|
|
rewriter.replaceOpWithNewOp<tosa::ClampOp>(op, outType, adaptor.getSelf(),
|
|
|
|
min_int, max_int, min_fp, max_fp);
|
2022-11-19 05:32:13 +08:00
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
2022-10-19 00:39:39 +08:00
|
|
|
|
2022-09-30 22:33:41 +08:00
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenArangeStartStepOp>::matchAndRewrite(
|
|
|
|
AtenArangeStartStepOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
2023-08-16 00:53:28 +08:00
|
|
|
const TypeConverter *typeConverter = this->getTypeConverter();
|
2024-05-31 14:45:13 +08:00
|
|
|
RankedTensorType resultType = cast<RankedTensorType>(
|
|
|
|
typeConverter->convertType(op->getResult(0).getType()));
|
2022-09-30 22:33:41 +08:00
|
|
|
|
|
|
|
// At this point all tensors should have value semantics, and hence the
|
|
|
|
// `layout` check can be ignored.
|
|
|
|
|
|
|
|
// TODO: Add support for pin_memory features.
|
|
|
|
// The pin_memory should be either `False` or `none`.
|
|
|
|
bool pinMemory;
|
2024-05-31 14:45:13 +08:00
|
|
|
if (!isa<Torch::NoneType>(op.getPinMemory().getType()) &&
|
2022-12-08 04:20:41 +08:00
|
|
|
(!matchPattern(op.getPinMemory(), m_TorchConstantBool(&pinMemory)) ||
|
2022-09-30 22:33:41 +08:00
|
|
|
pinMemory)) {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "unimplemented: pin_memory must be either None or false");
|
|
|
|
}
|
|
|
|
|
2024-02-28 05:40:55 +08:00
|
|
|
// Stores a range value (a start, end, or step value) and whether or not it
|
|
|
|
// was initiated with a constant integer, an constant float or neither.
|
|
|
|
class ConstRangeValue {
|
|
|
|
public:
|
|
|
|
explicit ConstRangeValue(double v)
|
|
|
|
: vDouble(v), fromDouble(true), vInt(static_cast<int64_t>(v)),
|
|
|
|
fromInt(false) {}
|
|
|
|
|
|
|
|
explicit ConstRangeValue(int64_t v)
|
|
|
|
: vDouble(static_cast<double>(v)), fromDouble(false), vInt(v),
|
|
|
|
fromInt(true) {}
|
|
|
|
|
|
|
|
// Constructor for the case where there is no constant value to use.
|
|
|
|
ConstRangeValue()
|
|
|
|
: vDouble(0), fromDouble(false), vInt(0), fromInt(false) {}
|
|
|
|
|
|
|
|
static ConstRangeValue fromValue(Value v) {
|
|
|
|
int64_t intVal{0};
|
|
|
|
double floatVal{0.0};
|
|
|
|
if (matchPattern(v, m_TorchConstantFloat(&floatVal))) {
|
|
|
|
return ConstRangeValue(floatVal);
|
|
|
|
} else if (matchPattern(v, m_TorchConstantInt(&intVal))) {
|
|
|
|
return ConstRangeValue(intVal);
|
|
|
|
}
|
|
|
|
return ConstRangeValue();
|
|
|
|
}
|
|
|
|
|
|
|
|
bool hasConstInt() const { return fromInt; }
|
|
|
|
bool hasConstDouble() const { return fromDouble; }
|
|
|
|
bool hasConst() const { return fromInt || fromDouble; }
|
|
|
|
double getDouble() const { return vDouble; }
|
|
|
|
int64_t getInt() const { return vInt; }
|
|
|
|
|
|
|
|
private:
|
|
|
|
double vDouble;
|
|
|
|
bool fromDouble;
|
|
|
|
int64_t vInt;
|
|
|
|
bool fromInt;
|
|
|
|
};
|
|
|
|
|
|
|
|
auto start = ConstRangeValue::fromValue(op.getStart());
|
|
|
|
if (!start.hasConst()) {
|
2022-09-30 22:33:41 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
2024-02-28 05:40:55 +08:00
|
|
|
op, "unimplemented: case where `start` is not a constant int or float");
|
|
|
|
}
|
2022-09-30 22:33:41 +08:00
|
|
|
|
2024-02-28 05:40:55 +08:00
|
|
|
auto end = ConstRangeValue::fromValue(op.getEnd());
|
|
|
|
if (!end.hasConst()) {
|
2022-09-30 22:33:41 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
2024-02-28 05:40:55 +08:00
|
|
|
op,
|
|
|
|
"unimplemented: case where value `end` is not a constant int or float");
|
|
|
|
}
|
2022-09-30 22:33:41 +08:00
|
|
|
|
2024-02-28 05:40:55 +08:00
|
|
|
auto step = ConstRangeValue::fromValue(op.getStep());
|
|
|
|
if (!step.hasConst()) {
|
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"unimplemented: case where value `step` "
|
|
|
|
"is not a constant int or float");
|
|
|
|
}
|
|
|
|
|
|
|
|
auto getRange = [](auto start, auto end, auto step) {
|
|
|
|
// Initialize a small vector of the same type as start:
|
|
|
|
using T = decltype(start);
|
|
|
|
SmallVector<T> values;
|
|
|
|
|
|
|
|
uint64_t counter{0};
|
|
|
|
if (start == end) {
|
|
|
|
return values;
|
|
|
|
}
|
|
|
|
assert(step != T(0));
|
|
|
|
values.reserve(
|
|
|
|
1 + static_cast<size_t>(std::abs((end - start) / std::abs(step))));
|
|
|
|
if (step > 0) {
|
|
|
|
while (start + T(counter) * step < end) {
|
|
|
|
values.push_back(start + counter * step);
|
|
|
|
counter++;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
while (start + T(counter) * step > end) {
|
|
|
|
values.push_back(start + counter * step);
|
|
|
|
counter++;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return values;
|
|
|
|
};
|
|
|
|
|
|
|
|
const auto isIntType =
|
2024-05-31 14:45:13 +08:00
|
|
|
dyn_cast_or_null<mlir::IntegerType>(resultType.getElementType());
|
2024-02-28 05:40:55 +08:00
|
|
|
|
|
|
|
const auto isDoubleType =
|
2024-05-31 14:45:13 +08:00
|
|
|
dyn_cast_or_null<mlir::FloatType>(resultType.getElementType());
|
2024-02-28 05:40:55 +08:00
|
|
|
|
|
|
|
auto maybeResult = [&]() -> std::optional<Value> {
|
|
|
|
// Integer output type, and start / end / range are all integers.
|
|
|
|
if (isIntType && start.hasConstInt() && end.hasConstInt() &&
|
|
|
|
step.hasConstInt()) {
|
|
|
|
auto values = getRange(start.getInt(), end.getInt(), step.getInt());
|
|
|
|
return tosa::getConstTensor<int64_t>(rewriter, op, values, values.size());
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get a double range.
|
|
|
|
auto values =
|
|
|
|
getRange(start.getDouble(), end.getDouble(), step.getDouble());
|
|
|
|
if (isIntType) {
|
|
|
|
SmallVector<int64_t> values_i64;
|
|
|
|
values_i64.reserve(values.size());
|
|
|
|
for (auto v : values) {
|
|
|
|
values_i64.push_back(static_cast<int64_t>(v));
|
|
|
|
}
|
|
|
|
return tosa::getConstTensor<int64_t>(rewriter, op, values_i64,
|
|
|
|
values.size());
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!isDoubleType) {
|
|
|
|
return {};
|
|
|
|
}
|
|
|
|
|
|
|
|
SmallVector<float> values_f32;
|
|
|
|
values_f32.reserve(values.size());
|
|
|
|
for (auto v : values) {
|
|
|
|
values_f32.push_back(static_cast<float>(v));
|
|
|
|
}
|
|
|
|
auto vs = tosa::getConstTensor<float>(rewriter, op, values_f32,
|
|
|
|
values_f32.size());
|
|
|
|
return vs;
|
|
|
|
}();
|
|
|
|
|
|
|
|
if (!maybeResult.has_value()) {
|
2022-09-30 22:33:41 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
2024-02-28 05:40:55 +08:00
|
|
|
op, "failed to generate constant tensor for arange");
|
|
|
|
}
|
|
|
|
auto result = maybeResult.value();
|
2022-09-30 22:33:41 +08:00
|
|
|
|
|
|
|
rewriter.replaceOpWithNewOp<tosa::CastOp>(op, resultType, result);
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2022-10-04 22:00:16 +08:00
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<PrimNumToTensorScalarOp>::matchAndRewrite(
|
|
|
|
PrimNumToTensorScalarOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
2023-08-16 00:53:28 +08:00
|
|
|
const TypeConverter *typeConverter = this->getTypeConverter();
|
2024-05-31 14:45:13 +08:00
|
|
|
RankedTensorType resultType = cast<RankedTensorType>(
|
|
|
|
typeConverter->convertType(op->getResult(0).getType()));
|
2022-10-04 22:00:16 +08:00
|
|
|
|
|
|
|
// Only supports integer operand type, because for the floating point operand
|
|
|
|
// type result tensor has to be of type `f64` which is not supported in the
|
|
|
|
// tosa.
|
2023-04-19 04:36:57 +08:00
|
|
|
double doubleValue;
|
|
|
|
auto isDouble = matchPattern(op.getA(), m_TorchConstantFloat(&doubleValue));
|
|
|
|
int64_t intValue;
|
|
|
|
auto isInt = matchPattern(op.getA(), m_TorchConstantInt(&intValue));
|
|
|
|
if (!isDouble && !isInt)
|
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Unable to extract the scalar constant");
|
|
|
|
|
|
|
|
auto outElemTy = resultType.getElementType();
|
2024-04-11 21:47:35 +08:00
|
|
|
if (isa<mlir::IntegerType>(outElemTy)) {
|
2023-05-10 23:25:58 +08:00
|
|
|
rewriter.replaceOpWithNewOp<tosa::ConstOp>(
|
|
|
|
op, resultType, DenseElementsAttr::get(resultType, {intValue}));
|
2023-04-19 04:36:57 +08:00
|
|
|
} else if (outElemTy.isF64()) {
|
2023-05-10 23:25:58 +08:00
|
|
|
rewriter.replaceOpWithNewOp<tosa::ConstOp>(
|
|
|
|
op, resultType, DenseElementsAttr::get(resultType, {doubleValue}));
|
2023-04-19 04:36:57 +08:00
|
|
|
}
|
2022-10-04 22:00:16 +08:00
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2022-10-04 21:05:59 +08:00
|
|
|
template <>
|
2022-10-28 23:06:11 +08:00
|
|
|
LogicalResult ConvertAtenOp<AtenCopyOp>::matchAndRewrite(
|
|
|
|
AtenCopyOp op, OpAdaptor adaptor,
|
2022-10-04 21:05:59 +08:00
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
|
|
|
// Not a tensor type.
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfType = dyn_cast<TensorType>(adaptor.getSelf().getType());
|
|
|
|
auto srcType = dyn_cast<TensorType>(adaptor.getSrc().getType());
|
2022-10-04 21:05:59 +08:00
|
|
|
if (!selfType || !selfType.hasStaticShape())
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only tensor types with static shape are supported");
|
|
|
|
|
|
|
|
if (!srcType || !srcType.hasStaticShape())
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only tensor types with static shape are supported");
|
|
|
|
|
|
|
|
// The non_blocking should be a constant `False`.
|
|
|
|
bool nonBlocking;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getNonBlocking(), m_TorchConstantBool(&nonBlocking))) {
|
2022-10-04 21:05:59 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "unimplemented: non_blocking must be a constant");
|
|
|
|
} else if (nonBlocking) {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "unimplemented: non_blocking is expected to be false");
|
|
|
|
}
|
|
|
|
|
2022-11-29 20:33:31 +08:00
|
|
|
SmallVector<int64_t> selfShape(makeShapeTorchCompatible(selfType.getShape()));
|
|
|
|
SmallVector<int64_t> srcShape(makeShapeTorchCompatible(srcType.getShape()));
|
2022-10-04 21:05:59 +08:00
|
|
|
|
|
|
|
if (llvm::equal(selfShape, srcShape) || selfShape.size() == 0) {
|
|
|
|
// If we reach here, then it means the given case is handled by implicit
|
|
|
|
// broadcasting done by tosa.
|
|
|
|
Value result;
|
|
|
|
if (failed(tosa::tosaCastTensorToType(
|
2022-12-08 04:20:41 +08:00
|
|
|
rewriter, op, adaptor.getSrc(),
|
2022-10-04 21:05:59 +08:00
|
|
|
getTypeConverter()->convertType(op.getType()), result)))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "unimplemented: cast to result type not supported");
|
|
|
|
rewriter.replaceOp(op, result);
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "unimplemented: valsem.aten.copy op not supported for this case.");
|
|
|
|
}
|
|
|
|
|
|
|
|
// Legalizes the torch.aten.to.dtype op
|
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenToDtypeOp>::matchAndRewrite(
|
|
|
|
AtenToDtypeOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
|
|
|
// Not a tensor type.
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfType = dyn_cast<TensorType>(adaptor.getSelf().getType());
|
2022-10-04 21:05:59 +08:00
|
|
|
if (!selfType || !selfType.hasStaticShape())
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only tensor types with static shape are supported");
|
|
|
|
|
|
|
|
// The non_blocking arg should be a constant `False`.
|
|
|
|
bool nonBlocking;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getNonBlocking(), m_TorchConstantBool(&nonBlocking))) {
|
2022-10-04 21:05:59 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "unimplemented: non_blocking arg must be a constant");
|
|
|
|
} else if (nonBlocking) {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "unimplemented: non_blocking arg is expected to be false");
|
|
|
|
}
|
|
|
|
|
|
|
|
// The copy arg should be a constant `False`.
|
|
|
|
bool copy;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getCopy(), m_TorchConstantBool(©))) {
|
2022-10-04 21:05:59 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "unimplemented: copy arg must be a constant");
|
|
|
|
} else if (copy) {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "unimplemented: copy arg is expected to be false");
|
|
|
|
}
|
|
|
|
|
|
|
|
// Only `none`, `contiguous` and `preserve` memory_format is supported.
|
2024-05-31 14:45:13 +08:00
|
|
|
if (!isa<Torch::NoneType>(op.getMemoryFormat().getType())) {
|
2022-10-04 21:05:59 +08:00
|
|
|
int64_t memoryFormat;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getMemoryFormat(), m_TorchConstantInt(&memoryFormat)))
|
2022-10-04 21:05:59 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "unimplemented: the memory format should be specified in "
|
|
|
|
"an integer constant");
|
|
|
|
if (memoryFormat != torch_upstream::MemoryFormat::Contiguous &&
|
|
|
|
memoryFormat != torch_upstream::MemoryFormat::Preserve)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "unimplemented: only none, contiguous and preserve "
|
|
|
|
"memory_format is supported");
|
|
|
|
}
|
|
|
|
|
2024-05-31 14:45:13 +08:00
|
|
|
auto resultTy = cast<RankedTensorType>(
|
|
|
|
getTypeConverter()->convertType(op.getResult().getType()));
|
2022-10-04 21:05:59 +08:00
|
|
|
|
|
|
|
Value result;
|
2023-01-11 13:42:07 +08:00
|
|
|
if (failed(tosa::tosaCastTensorToType(rewriter, op, adaptor.getSelf(),
|
|
|
|
resultTy, result)))
|
2022-10-04 21:05:59 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "conversion to result type failed");
|
|
|
|
|
|
|
|
rewriter.replaceOp(op, result);
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2024-09-21 04:34:09 +08:00
|
|
|
template <typename AtenOpT>
|
|
|
|
class ConvertAtenRemainderFmodOp : public OpConversionPattern<AtenOpT> {
|
|
|
|
public:
|
|
|
|
using OpConversionPattern<AtenOpT>::OpConversionPattern;
|
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
|
|
|
LogicalResult
|
|
|
|
matchAndRewrite(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const override {
|
2023-03-24 08:55:58 +08:00
|
|
|
|
2024-09-21 04:34:09 +08:00
|
|
|
Value self = adaptor.getSelf();
|
|
|
|
auto selfTy = cast<RankedTensorType>(self.getType());
|
2023-03-24 08:55:58 +08:00
|
|
|
|
2024-09-21 04:34:09 +08:00
|
|
|
if (!selfTy)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only ranked tensor types supported in TOSA Remainder/Fmod");
|
2023-03-24 08:55:58 +08:00
|
|
|
|
2024-09-21 04:34:09 +08:00
|
|
|
auto outType =
|
|
|
|
cast<TensorType>(this->getTypeConverter()->convertType(op.getType()));
|
2023-03-24 08:55:58 +08:00
|
|
|
|
2024-09-21 04:34:09 +08:00
|
|
|
Type outElemTy = outType.getElementType();
|
|
|
|
if (!outElemTy.isIntOrFloat())
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only floating-point or integer datatype legalization supported");
|
2023-03-24 08:55:58 +08:00
|
|
|
|
2024-09-21 04:34:09 +08:00
|
|
|
Value otherTensor;
|
|
|
|
if constexpr (std::is_same<AtenOpT, AtenRemainderScalarOp>()) {
|
|
|
|
Value other = op.getOther();
|
|
|
|
if (failed(torchScalarToTosaTensor(rewriter, op, other, otherTensor,
|
|
|
|
outElemTy, {})))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Currently only scalar constants are supported for "
|
|
|
|
"conversion in TOSA Remainder/Fmod operation");
|
|
|
|
} else {
|
|
|
|
otherTensor = adaptor.getOther();
|
|
|
|
auto otherTy = cast<RankedTensorType>(otherTensor.getType());
|
2023-03-24 08:55:58 +08:00
|
|
|
|
2024-09-21 04:34:09 +08:00
|
|
|
if (!otherTy)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only ranked tensor types supported in TOSA Remainder/Fmod");
|
|
|
|
}
|
2023-03-24 08:55:58 +08:00
|
|
|
|
2024-09-21 04:34:09 +08:00
|
|
|
constexpr bool isRemainderOp =
|
|
|
|
std::is_same<AtenOpT, AtenRemainderScalarOp>() ||
|
|
|
|
std::is_same<AtenOpT, AtenRemainderTensorOp>() ||
|
|
|
|
std::is_same<AtenOpT, AtenRemainderIntOp>();
|
|
|
|
|
|
|
|
if (selfTy.getElementType() != outElemTy)
|
|
|
|
self = rewriter.create<tosa::CastOp>(op.getLoc(), outType, self);
|
|
|
|
|
|
|
|
Value divTensor;
|
|
|
|
if (isRemainderOp) {
|
|
|
|
// torch.remainder(a, b) == a - a.div(b, rounding_mode="floor") * b
|
|
|
|
if (isa<mlir::FloatType>(outElemTy)) {
|
|
|
|
auto otherTensorReciprocal = rewriter.create<tosa::ReciprocalOp>(
|
|
|
|
op.getLoc(), otherTensor.getType(), otherTensor);
|
|
|
|
divTensor = rewriter.create<tosa::MulOp>(
|
|
|
|
op.getLoc(), outType, self, otherTensorReciprocal, /*shift=*/0);
|
|
|
|
divTensor =
|
|
|
|
rewriter.create<tosa::FloorOp>(op.getLoc(), outType, divTensor);
|
|
|
|
} else {
|
|
|
|
divTensor = floorIntDiv(rewriter, op, outType, self, otherTensor);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// torch.fmod(a, b) == a - a.div(b, rounding_mode="trunc") * b
|
|
|
|
if (isa<mlir::FloatType>(outElemTy)) {
|
|
|
|
divTensor = truncFloatDiv(rewriter, op, outType, self, otherTensor);
|
|
|
|
} else {
|
|
|
|
// TOSA IntDiv requires inputs to be i32
|
|
|
|
auto i32Type = RankedTensorType::get(outType.getShape(),
|
|
|
|
rewriter.getIntegerType(32));
|
|
|
|
self = tosa::promoteType(rewriter, self, i32Type);
|
|
|
|
otherTensor = tosa::promoteType(rewriter, otherTensor, i32Type);
|
|
|
|
|
|
|
|
auto intDivTensor = rewriter.create<tosa::IntDivOp>(
|
|
|
|
op->getLoc(), i32Type, self, otherTensor);
|
|
|
|
|
|
|
|
divTensor = tosa::promoteType(rewriter, intDivTensor, outType);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
auto mulTensor = rewriter.create<tosa::MulOp>(op.getLoc(), outType,
|
|
|
|
otherTensor, divTensor,
|
|
|
|
/*shift=*/0);
|
|
|
|
rewriter.replaceOpWithNewOp<tosa::SubOp>(op, outType, self, mulTensor);
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
};
|
2023-03-24 08:55:58 +08:00
|
|
|
|
2022-02-01 05:34:09 +08:00
|
|
|
template <typename AtenOpT, typename TosaOpT>
|
|
|
|
class ConvertAtenPoolingBaseOp : public OpConversionPattern<AtenOpT> {
|
|
|
|
public:
|
|
|
|
using OpConversionPattern<AtenOpT>::OpConversionPattern;
|
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
|
|
|
|
|
|
|
// Different pooling variants need to process inputs differently, e.g.
|
|
|
|
// adaptive pooling generates the kernel size rather than receive it. This
|
|
|
|
// function also transposes inputs.
|
|
|
|
virtual LogicalResult processInputs(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter,
|
2023-01-11 07:07:19 +08:00
|
|
|
Value &input, DenseI64ArrayAttr &kernel,
|
|
|
|
DenseI64ArrayAttr &stride,
|
|
|
|
DenseI64ArrayAttr &pad,
|
2022-02-01 05:34:09 +08:00
|
|
|
Type &outputTy) const {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Unimplemented pooling input parsing function");
|
|
|
|
}
|
|
|
|
|
2022-05-19 20:35:59 +08:00
|
|
|
static int64_t getOutputDim(int64_t inputDim, int64_t kernelDim,
|
|
|
|
int64_t stride, int64_t padBefore,
|
2023-03-22 01:17:39 +08:00
|
|
|
int64_t padAfter, int64_t dilation,
|
|
|
|
bool ceilMode = false) {
|
2022-11-29 20:33:31 +08:00
|
|
|
if (inputDim == kUnknownSize) {
|
|
|
|
return kUnknownSize;
|
2022-02-01 05:34:09 +08:00
|
|
|
} else {
|
2023-03-24 08:55:58 +08:00
|
|
|
int64_t dimSize =
|
|
|
|
inputDim + padBefore + padAfter - dilation * (kernelDim - 1) - 1;
|
2023-03-22 01:17:39 +08:00
|
|
|
if (ceilMode && (dimSize % stride != 0))
|
|
|
|
return dimSize / stride + 2;
|
|
|
|
return dimSize / stride + 1;
|
2022-02-01 05:34:09 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Apply the transposeDims vector on input to generate a transposed form.
|
|
|
|
Value transposeTensor(AtenOpT op, ConversionPatternRewriter &rewriter,
|
|
|
|
Value input, ArrayRef<int32_t> transposeDims) const {
|
2024-04-28 05:00:56 +08:00
|
|
|
auto inputTy = cast<RankedTensorType>(input.getType());
|
2022-02-01 05:34:09 +08:00
|
|
|
auto inputElemTy = inputTy.getElementType();
|
2022-11-29 20:33:31 +08:00
|
|
|
auto inputShape = makeShapeTorchCompatible(inputTy.getShape());
|
2022-02-01 05:34:09 +08:00
|
|
|
auto inputRank = inputTy.getRank();
|
|
|
|
|
2022-12-20 18:17:27 +08:00
|
|
|
std::optional<Value> transposeDimsConst = tosa::getConstTensor<int32_t>(
|
2022-02-01 05:34:09 +08:00
|
|
|
rewriter, op,
|
|
|
|
/*vec=*/transposeDims,
|
|
|
|
/*shape=*/{static_cast<int32_t>(inputRank)});
|
|
|
|
|
|
|
|
SmallVector<int64_t> transposedInputShape;
|
|
|
|
for (auto &dim : transposeDims)
|
|
|
|
transposedInputShape.push_back(inputShape[dim]);
|
2022-11-29 20:33:31 +08:00
|
|
|
auto transposedInputType = RankedTensorType::get(
|
|
|
|
makeShapeLLVMCompatible(transposedInputShape), inputElemTy);
|
2022-02-01 05:34:09 +08:00
|
|
|
return rewriter
|
|
|
|
.create<tosa::TransposeOp>(op->getLoc(), transposedInputType, input,
|
2022-08-09 11:17:35 +08:00
|
|
|
transposeDimsConst.value())
|
2022-02-01 05:34:09 +08:00
|
|
|
.getResult();
|
|
|
|
}
|
|
|
|
|
|
|
|
Value transposePoolingInputToHwc(AtenOpT op,
|
|
|
|
ConversionPatternRewriter &rewriter,
|
|
|
|
Value input) const {
|
2024-04-28 05:00:56 +08:00
|
|
|
auto inputRank = cast<RankedTensorType>(input.getType()).getRank();
|
2022-02-01 05:34:09 +08:00
|
|
|
|
|
|
|
SmallVector<int32_t> nchwToNhwc4DTransposeDims({0, 2, 3, 1});
|
|
|
|
SmallVector<int32_t> chwToHwc3DTransposeDims({1, 2, 0});
|
|
|
|
|
|
|
|
return transposeTensor(op, rewriter, input,
|
|
|
|
inputRank == 3 ? chwToHwc3DTransposeDims
|
|
|
|
: nchwToNhwc4DTransposeDims);
|
|
|
|
}
|
|
|
|
|
|
|
|
Value transposePoolingOutputToChw(AtenOpT op,
|
|
|
|
ConversionPatternRewriter &rewriter,
|
|
|
|
Value input) const {
|
2024-04-28 05:00:56 +08:00
|
|
|
auto inputTy = cast<RankedTensorType>(input.getType());
|
2022-02-01 05:34:09 +08:00
|
|
|
auto inputRank = inputTy.getRank();
|
|
|
|
|
|
|
|
SmallVector<int32_t> nhwcToNchw4DTransposeDims({0, 3, 1, 2});
|
|
|
|
SmallVector<int32_t> hwcToChw3DTransposeDims({2, 0, 1});
|
|
|
|
|
|
|
|
return transposeTensor(op, rewriter, input,
|
|
|
|
inputRank == 3 ? hwcToChw3DTransposeDims
|
|
|
|
: nhwcToNchw4DTransposeDims);
|
|
|
|
}
|
|
|
|
|
|
|
|
LogicalResult
|
|
|
|
matchAndRewrite(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const override {
|
|
|
|
Value input;
|
2023-01-11 07:07:19 +08:00
|
|
|
DenseI64ArrayAttr kernel, stride, pad;
|
2022-02-01 05:34:09 +08:00
|
|
|
Type outputTy;
|
|
|
|
|
|
|
|
// Attempts to read input and kernel parameters, or synthesize them in the
|
|
|
|
// case of adaptive pooling. Also performs input CHW->HWC transpose.
|
|
|
|
if (failed(processInputs(op, adaptor, rewriter, input, kernel, stride, pad,
|
|
|
|
outputTy)))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Failed to process inputs for pooling");
|
2022-02-01 05:34:09 +08:00
|
|
|
|
2023-06-13 22:17:23 +08:00
|
|
|
Value pooledOutput;
|
|
|
|
static_assert(std::is_same<TosaOpT, tosa::MaxPool2dOp>::value ||
|
|
|
|
std::is_same<TosaOpT, tosa::AvgPool2dOp>::value,
|
|
|
|
"Expected either tosa::MaxPool2dOp or tosa::AvgPool2dOp");
|
|
|
|
if constexpr (std::is_same<TosaOpT, tosa::MaxPool2dOp>::value) {
|
|
|
|
pooledOutput = rewriter
|
|
|
|
.create<TosaOpT>(op->getLoc(), outputTy, input, kernel,
|
|
|
|
stride, pad)
|
|
|
|
.getResult();
|
|
|
|
} else if constexpr (std::is_same<TosaOpT, tosa::AvgPool2dOp>::value) {
|
|
|
|
TypeAttr accType;
|
|
|
|
if (failed(tosa::getAvgPool2dAccType(rewriter, input, accType)))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Failed to get accumulator type for pooling");
|
|
|
|
pooledOutput = rewriter
|
|
|
|
.create<TosaOpT>(op->getLoc(), outputTy, input, kernel,
|
|
|
|
stride, pad, accType)
|
|
|
|
.getResult();
|
|
|
|
}
|
2022-02-01 05:34:09 +08:00
|
|
|
|
|
|
|
auto transposedOutput =
|
|
|
|
ConvertAtenPoolingBaseOp<AtenOpT, TosaOpT>::transposePoolingOutputToChw(
|
|
|
|
op, rewriter, pooledOutput);
|
|
|
|
|
|
|
|
rewriter.replaceOpWithNewOp<tensor::CastOp>(
|
|
|
|
op,
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
op.getType()),
|
|
|
|
transposedOutput);
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
template <typename AtenOpT, typename TosaOpT>
|
|
|
|
class ConvertAtenAdaptivePoolingOp
|
|
|
|
: public ConvertAtenPoolingBaseOp<AtenOpT, TosaOpT> {
|
|
|
|
public:
|
|
|
|
using ConvertAtenPoolingBaseOp<AtenOpT, TosaOpT>::ConvertAtenPoolingBaseOp;
|
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
|
|
|
LogicalResult processInputs(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter, Value &input,
|
2023-01-11 07:07:19 +08:00
|
|
|
DenseI64ArrayAttr &kernel,
|
|
|
|
DenseI64ArrayAttr &stride, DenseI64ArrayAttr &pad,
|
|
|
|
Type &outputTy) const override {
|
2022-12-08 04:20:41 +08:00
|
|
|
auto inputXchw = adaptor.getSelf();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto inputTy = cast<RankedTensorType>(inputXchw.getType());
|
2022-02-01 05:34:09 +08:00
|
|
|
if (!inputTy)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Adaptive avgpool requires ranked tensor input");
|
2022-02-01 05:34:09 +08:00
|
|
|
|
2022-11-29 20:33:31 +08:00
|
|
|
auto inputShape = makeShapeTorchCompatible(inputTy.getShape());
|
2022-02-01 05:34:09 +08:00
|
|
|
auto inputRank = inputTy.getRank();
|
|
|
|
auto inputElemTy = inputTy.getElementType();
|
|
|
|
|
|
|
|
// Rank sanity check.
|
|
|
|
if (inputTy.getRank() != 4 && inputRank != 3)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "NCHW->NHWC transpose requires 3D or 4D tensor");
|
2022-02-01 05:34:09 +08:00
|
|
|
|
|
|
|
int64_t inputHDim = inputShape[inputRank - 2];
|
|
|
|
int64_t inputWDim = inputShape[inputRank - 1];
|
|
|
|
|
|
|
|
SmallVector<int64_t> outputSize;
|
2023-01-11 13:42:07 +08:00
|
|
|
if (!matchPattern(op.getOutputSize(),
|
|
|
|
m_TorchListOfConstantInts(outputSize)))
|
2022-02-01 05:34:09 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Non-const output_size for adaptive pooling unsupported.");
|
|
|
|
|
|
|
|
SmallVector<int64_t> kernelDims;
|
|
|
|
int64_t outputHDim, outputWDim;
|
|
|
|
if (outputSize.size() == 1) {
|
|
|
|
outputHDim = outputWDim = outputSize[0];
|
|
|
|
} else {
|
|
|
|
if (outputSize.size() != 2)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Adaptive avgpool output_size not 1 or 2 elements.");
|
2022-02-01 05:34:09 +08:00
|
|
|
|
|
|
|
// Assumes 'None' (e.g. output_size=(None, 5) ) is expressed as <=0.
|
|
|
|
outputHDim =
|
|
|
|
(outputSize[0] <= 0) ? inputShape[inputRank - 2] : outputSize[0];
|
|
|
|
outputWDim =
|
|
|
|
(outputSize[1] <= 0) ? inputShape[inputRank - 1] : outputSize[1];
|
|
|
|
}
|
|
|
|
|
|
|
|
// In adaptive pooling,
|
|
|
|
// stride = inputDim // outputDim
|
|
|
|
// kernel = inputDim - (outputDim-1)* stride
|
|
|
|
// pad = 0, dilation = 1
|
|
|
|
|
|
|
|
int64_t strideH = inputShape[inputRank - 2] / outputHDim;
|
|
|
|
int64_t strideW = inputShape[inputRank - 1] / outputWDim;
|
|
|
|
|
|
|
|
kernelDims.push_back(inputHDim - (outputHDim - 1) * strideH);
|
|
|
|
kernelDims.push_back(inputWDim - (outputWDim - 1) * strideW);
|
|
|
|
|
|
|
|
SmallVector<int64_t> outputShape;
|
|
|
|
if (inputRank > 3)
|
|
|
|
outputShape.push_back(inputShape[0]);
|
|
|
|
outputShape.push_back(outputHDim);
|
|
|
|
outputShape.push_back(outputWDim);
|
|
|
|
outputShape.push_back(inputShape[inputRank - 3]);
|
|
|
|
|
|
|
|
// Transpose to xHWC
|
|
|
|
input =
|
|
|
|
ConvertAtenPoolingBaseOp<AtenOpT, TosaOpT>::transposePoolingInputToHwc(
|
|
|
|
op, rewriter, inputXchw);
|
2023-01-11 07:07:19 +08:00
|
|
|
kernel = rewriter.getDenseI64ArrayAttr(kernelDims);
|
|
|
|
stride = rewriter.getDenseI64ArrayAttr({strideH, strideW});
|
2022-02-01 05:34:09 +08:00
|
|
|
// Adaptive pooling does unit dilation and zero pad.
|
2023-01-11 07:07:19 +08:00
|
|
|
pad = rewriter.getDenseI64ArrayAttr({0, 0, 0, 0});
|
|
|
|
outputTy = RankedTensorType::get(makeShapeLLVMCompatible(outputShape),
|
|
|
|
inputElemTy);
|
2022-02-01 05:34:09 +08:00
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2022-05-19 20:35:59 +08:00
|
|
|
template <typename AtenOpT, typename tosaOp>
|
|
|
|
static Type getOutputTypeForNonAdaptivePoolingOp(
|
|
|
|
RankedTensorType inputTy, SmallVectorImpl<int64_t> &kernelSize,
|
|
|
|
SmallVectorImpl<int64_t> &strideArray, SmallVectorImpl<int64_t> &padArray,
|
2023-03-22 01:17:39 +08:00
|
|
|
SmallVectorImpl<int64_t> &dilationArray, bool ceilMode = false) {
|
2022-11-29 20:33:31 +08:00
|
|
|
auto inputShape = makeShapeTorchCompatible(inputTy.getShape());
|
2022-05-19 20:35:59 +08:00
|
|
|
auto inputRank = inputTy.getRank();
|
|
|
|
auto inputElemTy = inputTy.getElementType();
|
2022-02-01 05:34:09 +08:00
|
|
|
|
2022-05-19 20:35:59 +08:00
|
|
|
int64_t outputHDim = ConvertAtenPoolingBaseOp<AtenOpT, tosaOp>::getOutputDim(
|
|
|
|
inputShape[inputRank - 2], kernelSize[0], strideArray[0], padArray[0],
|
2023-03-22 01:17:39 +08:00
|
|
|
padArray[0], dilationArray[0], ceilMode);
|
2022-05-19 20:35:59 +08:00
|
|
|
int64_t outputWDim = ConvertAtenPoolingBaseOp<AtenOpT, tosaOp>::getOutputDim(
|
|
|
|
inputShape[inputRank - 1], kernelSize[1], strideArray[1], padArray[1],
|
2023-03-22 01:17:39 +08:00
|
|
|
padArray[1], dilationArray[1], ceilMode);
|
|
|
|
padArray[0] = (outputHDim - 1) * strideArray[0] +
|
|
|
|
dilationArray[0] * kernelSize[0] - dilationArray[0] + 1 -
|
|
|
|
padArray[0] * 2 - inputShape[inputRank - 2];
|
|
|
|
padArray[1] = (outputWDim - 1) * strideArray[1] +
|
|
|
|
dilationArray[0] * kernelSize[1] - dilationArray[0] + 1 -
|
|
|
|
padArray[1] * 2 - inputShape[inputRank - 1];
|
2022-05-19 20:35:59 +08:00
|
|
|
SmallVector<int64_t> outputShape;
|
|
|
|
if (inputRank > 3)
|
|
|
|
outputShape.push_back(inputShape[0]);
|
|
|
|
outputShape.push_back(outputHDim);
|
|
|
|
outputShape.push_back(outputWDim);
|
|
|
|
outputShape.push_back(inputShape[inputRank - 3]);
|
2023-01-11 13:42:07 +08:00
|
|
|
return RankedTensorType::get(makeShapeLLVMCompatible(outputShape),
|
|
|
|
inputElemTy);
|
2022-05-19 20:35:59 +08:00
|
|
|
}
|
2022-02-01 05:34:09 +08:00
|
|
|
|
2022-05-19 20:35:59 +08:00
|
|
|
// Checks the validity of pooling parameters and stores them in the respective
|
|
|
|
// vector. Also, gets the output type for the pooling op.
|
|
|
|
template <typename AtenOpT, typename tosaOp>
|
|
|
|
static LogicalResult getOutputTypeAndPoolingParameters(
|
|
|
|
AtenOpT op, ConversionPatternRewriter &rewriter, Value inputXchw,
|
2023-01-11 07:07:19 +08:00
|
|
|
SmallVectorImpl<int64_t> &dilationArray, Type &outputTy,
|
|
|
|
DenseI64ArrayAttr &kernel, DenseI64ArrayAttr &stride,
|
|
|
|
DenseI64ArrayAttr &pad) {
|
2022-05-19 20:35:59 +08:00
|
|
|
|
2024-04-28 05:00:56 +08:00
|
|
|
RankedTensorType inputTy = cast<RankedTensorType>(inputXchw.getType());
|
2022-05-19 20:35:59 +08:00
|
|
|
if (!inputTy)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Pooling op requires ranked tensor input");
|
2022-05-19 20:35:59 +08:00
|
|
|
|
|
|
|
auto inputRank = inputTy.getRank();
|
|
|
|
// Rank sanity check.
|
|
|
|
if (inputTy.getRank() != 4 && inputRank != 3)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "NCHW->NHWC transpose requires 3D or 4D tensor");
|
2022-05-19 20:35:59 +08:00
|
|
|
|
|
|
|
SmallVector<int64_t, 2> kernelSizeInts, strideInts, paddingInts;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getKernelSize(),
|
2022-11-17 04:33:12 +08:00
|
|
|
m_TorchListOfConstantInts(kernelSizeInts)))
|
2022-05-19 20:35:59 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Non-const kernel_size for pooling op unsupported");
|
2023-04-27 23:31:36 +08:00
|
|
|
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getStride(), m_TorchListOfConstantInts(strideInts)))
|
2022-05-19 20:35:59 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Non-const stride for pooling op unsupported");
|
2023-04-27 23:31:36 +08:00
|
|
|
// If `stride` is not specified by the user, it is assigned the value of empty
|
|
|
|
// list during import. For such a case, the stride value is the kernel size.
|
|
|
|
// See:
|
|
|
|
// https://pytorch.org/docs/stable/generated/torch.nn.MaxPool2d.html#torch.nn.MaxPool2d
|
|
|
|
if (strideInts.empty())
|
|
|
|
strideInts.assign(kernelSizeInts);
|
|
|
|
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getPadding(), m_TorchListOfConstantInts(paddingInts)))
|
2022-05-19 20:35:59 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Non-const padding factor for pooling op unsupported");
|
2022-02-01 05:34:09 +08:00
|
|
|
|
2023-03-22 01:17:39 +08:00
|
|
|
SmallVector<int64_t, 4> padArr = {paddingInts[0], paddingInts[0],
|
|
|
|
paddingInts[1], paddingInts[1]};
|
2023-01-11 07:07:19 +08:00
|
|
|
kernel = rewriter.getDenseI64ArrayAttr(kernelSizeInts);
|
|
|
|
stride = rewriter.getDenseI64ArrayAttr(strideInts);
|
2022-02-01 05:34:09 +08:00
|
|
|
|
2022-05-19 20:35:59 +08:00
|
|
|
bool ceilMode;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getCeilMode(), m_TorchConstantBool(&ceilMode)))
|
2022-05-19 20:35:59 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "only support constant bool ceil_mode for pooling op");
|
2022-02-01 05:34:09 +08:00
|
|
|
|
2022-05-19 20:35:59 +08:00
|
|
|
outputTy = getOutputTypeForNonAdaptivePoolingOp<AtenOpT, tosaOp>(
|
2023-03-22 01:17:39 +08:00
|
|
|
inputTy, kernelSizeInts, strideInts, paddingInts, dilationArray,
|
|
|
|
ceilMode);
|
|
|
|
padArr[1] = padArr[1] + paddingInts[0];
|
|
|
|
padArr[3] = padArr[3] + paddingInts[1];
|
|
|
|
pad = rewriter.getDenseI64ArrayAttr(
|
|
|
|
{padArr[0], padArr[1], padArr[2], padArr[3]});
|
2022-05-19 20:35:59 +08:00
|
|
|
return success();
|
|
|
|
}
|
2022-02-01 05:34:09 +08:00
|
|
|
|
2022-05-19 20:35:59 +08:00
|
|
|
class ConvertAtenMaxPool2dOp
|
|
|
|
: public ConvertAtenPoolingBaseOp<AtenMaxPool2dOp, tosa::MaxPool2dOp> {
|
|
|
|
public:
|
|
|
|
using ConvertAtenPoolingBaseOp<AtenMaxPool2dOp,
|
|
|
|
tosa::MaxPool2dOp>::ConvertAtenPoolingBaseOp;
|
|
|
|
LogicalResult processInputs(AtenMaxPool2dOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter, Value &input,
|
2023-01-11 07:07:19 +08:00
|
|
|
DenseI64ArrayAttr &kernel,
|
|
|
|
DenseI64ArrayAttr &stride, DenseI64ArrayAttr &pad,
|
|
|
|
Type &outputTy) const override {
|
2022-05-19 20:35:59 +08:00
|
|
|
SmallVector<int64_t, 2> dilationArray;
|
2023-01-11 07:07:19 +08:00
|
|
|
if (!matchPattern(op.getDilation(),
|
|
|
|
m_TorchListOfConstantInts(dilationArray)))
|
2022-02-01 05:34:09 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
2022-05-19 20:35:59 +08:00
|
|
|
op, "Non-const dilation for pooling op unsupported.");
|
2022-02-01 05:34:09 +08:00
|
|
|
// TOSA pooling only supports unit dilation.
|
|
|
|
if (dilationArray[0] > 1 || dilationArray[1] > 1)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Cannot process non-unit pooling dilation.");
|
2022-02-01 05:34:09 +08:00
|
|
|
|
2022-05-19 20:35:59 +08:00
|
|
|
if (failed(getOutputTypeAndPoolingParameters<AtenMaxPool2dOp,
|
|
|
|
tosa::MaxPool2dOp>(
|
2022-12-08 04:20:41 +08:00
|
|
|
op, rewriter, adaptor.getSelf(), dilationArray, outputTy, kernel,
|
2022-05-19 20:35:59 +08:00
|
|
|
stride, pad)))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "invalid pooling parameters or input type");
|
2022-02-01 05:34:09 +08:00
|
|
|
|
2022-05-19 20:35:59 +08:00
|
|
|
// Transpose to xHWC
|
|
|
|
input = ConvertAtenPoolingBaseOp<AtenMaxPool2dOp, tosa::MaxPool2dOp>::
|
2022-12-08 04:20:41 +08:00
|
|
|
transposePoolingInputToHwc(op, rewriter, adaptor.getSelf());
|
2022-05-19 20:35:59 +08:00
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
class ConvertAtenAvgPool2dOp
|
|
|
|
: public ConvertAtenPoolingBaseOp<AtenAvgPool2dOp, tosa::AvgPool2dOp> {
|
|
|
|
public:
|
|
|
|
using ConvertAtenPoolingBaseOp<AtenAvgPool2dOp,
|
|
|
|
tosa::AvgPool2dOp>::ConvertAtenPoolingBaseOp;
|
|
|
|
LogicalResult processInputs(AtenAvgPool2dOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter, Value &input,
|
2023-01-11 07:07:19 +08:00
|
|
|
DenseI64ArrayAttr &kernel,
|
|
|
|
DenseI64ArrayAttr &stride, DenseI64ArrayAttr &pad,
|
|
|
|
Type &outputTy) const override {
|
2022-05-19 20:35:59 +08:00
|
|
|
SmallVector<int64_t, 2> dilationArray{1, 1};
|
|
|
|
if (failed(getOutputTypeAndPoolingParameters<AtenAvgPool2dOp,
|
|
|
|
tosa::AvgPool2dOp>(
|
2022-12-08 04:20:41 +08:00
|
|
|
op, rewriter, adaptor.getSelf(), dilationArray, outputTy, kernel,
|
2022-05-19 20:35:59 +08:00
|
|
|
stride, pad)))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "invalid pooling parameters or input type");
|
|
|
|
|
|
|
|
// Transpose to xHWC
|
|
|
|
input = ConvertAtenPoolingBaseOp<AtenAvgPool2dOp, tosa::AvgPool2dOp>::
|
2022-12-08 04:20:41 +08:00
|
|
|
transposePoolingInputToHwc(op, rewriter, adaptor.getSelf());
|
2022-02-01 05:34:09 +08:00
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2022-02-17 01:53:51 +08:00
|
|
|
// Ref: Error checking based on the Torch to LinAlg lowering
|
|
|
|
template <typename AtenOpT, int fillVal>
|
|
|
|
class ConvertAtenConstPatternOp : public OpConversionPattern<AtenOpT> {
|
|
|
|
public:
|
|
|
|
using OpConversionPattern<AtenOpT>::OpConversionPattern;
|
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
|
|
|
LogicalResult
|
|
|
|
matchAndRewrite(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const override {
|
|
|
|
|
2024-05-31 14:45:13 +08:00
|
|
|
auto outType = dyn_cast<TensorType>(
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
op.getType()));
|
2022-02-17 01:53:51 +08:00
|
|
|
|
|
|
|
if (!outType)
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Only Tensor types supported in TOSA");
|
2022-02-17 01:53:51 +08:00
|
|
|
|
|
|
|
Type outElemTy = outType.getElementType();
|
|
|
|
if (!outElemTy.isIntOrFloat())
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only floating-point or integer datatype legalization supported");
|
2022-02-17 01:53:51 +08:00
|
|
|
|
|
|
|
// FIXME: Handle layout, device and pin_memory. Assume dtype has been
|
|
|
|
// processed to set output type correctly?
|
2023-03-30 22:08:20 +08:00
|
|
|
// The layout arg should be either `none` or `0` i.e. strided.
|
2024-04-28 05:00:56 +08:00
|
|
|
if (!isa<Torch::NoneType>(op.getLayout().getType())) {
|
2023-03-30 22:08:20 +08:00
|
|
|
int64_t tensorLayout;
|
|
|
|
if (!matchPattern(op.getLayout(), m_TorchConstantInt(&tensorLayout)))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "The layout arg should be either `none` or `0` i.e. strided.");
|
|
|
|
else if (tensorLayout != torch_upstream::Layout::Strided)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "The layout arg should be either `none` or `0` i.e. strided.");
|
|
|
|
}
|
2022-02-17 01:53:51 +08:00
|
|
|
|
|
|
|
bool pinMemory;
|
2024-04-28 05:00:56 +08:00
|
|
|
if (!isa<Torch::NoneType>(op.getPinMemory().getType()) &&
|
2022-12-08 04:20:41 +08:00
|
|
|
(!matchPattern(op.getPinMemory(), m_TorchConstantBool(&pinMemory)) ||
|
2022-02-17 01:53:51 +08:00
|
|
|
pinMemory)) {
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Unsupported pin_memory, should be either None or false");
|
2022-02-17 01:53:51 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
SmallVector<int64_t> shape;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getSize(), m_TorchListOfConstantInts(shape))) {
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Shape must be a list of Scalar constants");
|
2022-02-17 01:53:51 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
int64_t size = 1;
|
|
|
|
for (auto s : shape)
|
|
|
|
size *= s;
|
|
|
|
|
|
|
|
SmallVector<int32_t> values(size, fillVal);
|
|
|
|
auto constOp =
|
2022-08-09 11:17:35 +08:00
|
|
|
tosa::getConstTensor<int32_t>(rewriter, op, values, shape).value();
|
2022-02-17 01:53:51 +08:00
|
|
|
|
|
|
|
rewriter.replaceOpWithNewOp<tosa::CastOp>(op, outType, constOp);
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
template <typename AtenOpT>
|
|
|
|
class ConvertAtenFillScalarOp : public OpConversionPattern<AtenOpT> {
|
|
|
|
public:
|
|
|
|
using OpConversionPattern<AtenOpT>::OpConversionPattern;
|
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
|
|
|
LogicalResult
|
|
|
|
matchAndRewrite(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const override {
|
2024-05-31 14:45:13 +08:00
|
|
|
auto outType = dyn_cast<TensorType>(
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
op.getType()));
|
2022-02-17 01:53:51 +08:00
|
|
|
|
|
|
|
if (!outType || !outType.hasStaticShape())
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only Tensor types with static shapes are currently supported");
|
2022-02-17 01:53:51 +08:00
|
|
|
|
|
|
|
Type outElemTy = outType.getElementType();
|
|
|
|
if (!outElemTy.isIntOrFloat()) {
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only floating-point or integer datatype legalization supported");
|
2022-02-17 01:53:51 +08:00
|
|
|
}
|
|
|
|
Value constOp;
|
2022-11-29 20:33:31 +08:00
|
|
|
if (failed(torchScalarToTosaTensor(
|
2022-12-08 04:20:41 +08:00
|
|
|
rewriter, op, op.getValue(), constOp, outElemTy,
|
2022-11-29 20:33:31 +08:00
|
|
|
makeShapeTorchCompatible(outType.getShape()))))
|
2022-07-18 09:39:54 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Supplied value must be a Scalar constant");
|
2022-02-17 01:53:51 +08:00
|
|
|
|
|
|
|
rewriter.replaceOpWithNewOp<tosa::CastOp>(op, outType, constOp);
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2022-12-22 00:56:07 +08:00
|
|
|
template <typename AtenOpT>
|
|
|
|
class ConvertAtenMaskedFillOp : public OpConversionPattern<AtenOpT> {
|
|
|
|
public:
|
|
|
|
using OpConversionPattern<AtenOpT>::OpConversionPattern;
|
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
|
|
|
LogicalResult
|
|
|
|
matchAndRewrite(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const override {
|
2024-05-31 14:45:13 +08:00
|
|
|
auto outType = dyn_cast<TensorType>(
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
op.getType()));
|
2022-12-22 00:56:07 +08:00
|
|
|
|
|
|
|
if (!outType || !outType.hasStaticShape())
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only Tensor types with static shapes are currently supported");
|
|
|
|
|
|
|
|
Type outElemTy = outType.getElementType();
|
|
|
|
if (!outElemTy.isIntOrFloat()) {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only floating-point or integer datatype legalization supported");
|
|
|
|
}
|
|
|
|
|
|
|
|
// Not a tensor type.
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfType = dyn_cast<TensorType>(adaptor.getSelf().getType());
|
2022-12-22 00:56:07 +08:00
|
|
|
if (!selfType || !outType.hasStaticShape())
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op,
|
|
|
|
"Only tensor types with static shapes input are currently supported");
|
|
|
|
|
2024-04-28 05:00:56 +08:00
|
|
|
auto maskType = dyn_cast<TensorType>(adaptor.getMask().getType());
|
2022-12-22 00:56:07 +08:00
|
|
|
if (!maskType)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only tensor types mask are currently supported");
|
|
|
|
|
|
|
|
Value rhs = adaptor.getValue();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto rhsType = dyn_cast<TensorType>(rhs.getType());
|
2022-12-22 00:56:07 +08:00
|
|
|
Value rhsAsTensor;
|
|
|
|
if (!rhsType) { // scalar
|
|
|
|
if (failed(torchScalarToTosaTensor(rewriter, op, op.getValue(),
|
|
|
|
rhsAsTensor, rhs.getType(), {})))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Currently only scalar constants are supported for "
|
|
|
|
"conversion in TOSA operation");
|
|
|
|
} else { // tensor
|
2024-04-28 05:00:56 +08:00
|
|
|
rhsType = dyn_cast<TensorType>(rhs.getType());
|
2022-12-22 00:56:07 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
auto rhsTensor = rhsType ? rhs : rhsAsTensor;
|
2024-04-28 05:00:56 +08:00
|
|
|
auto rhsTensorType = dyn_cast<TensorType>(rhsTensor.getType());
|
2022-12-22 00:56:07 +08:00
|
|
|
if (rhsTensorType.getElementType() != outElemTy)
|
|
|
|
rhsTensor = rewriter.create<tosa::CastOp>(
|
|
|
|
op.getLoc(),
|
|
|
|
RankedTensorType::get(rhsTensorType.getShape(), outElemTy),
|
|
|
|
rhsTensor);
|
|
|
|
|
|
|
|
rewriter.replaceOpWithNewOp<tosa::SelectOp>(op, outType, adaptor.getMask(),
|
|
|
|
rhsTensor, adaptor.getSelf());
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2022-09-21 06:07:46 +08:00
|
|
|
// Legalizes the torch.clone op.
|
|
|
|
template <typename AtenOpT>
|
|
|
|
class ConvertAtenCloneOp : public OpConversionPattern<AtenOpT> {
|
|
|
|
public:
|
|
|
|
using OpConversionPattern<AtenOpT>::OpConversionPattern;
|
|
|
|
using OpAdaptor = typename AtenOpT::Adaptor;
|
|
|
|
LogicalResult
|
|
|
|
matchAndRewrite(AtenOpT op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const override {
|
|
|
|
int64_t memoryFormat;
|
2024-04-28 05:00:56 +08:00
|
|
|
if (!isa<Torch::NoneType>(op.getMemoryFormat().getType()) &&
|
2023-01-11 13:42:07 +08:00
|
|
|
(!matchPattern(op.getMemoryFormat(),
|
|
|
|
m_TorchConstantInt(&memoryFormat)) ||
|
2023-02-01 19:13:59 +08:00
|
|
|
(memoryFormat != torch_upstream::MemoryFormat::Contiguous &&
|
|
|
|
memoryFormat != torch_upstream::MemoryFormat::ChannelsLast))) {
|
2022-09-21 06:07:46 +08:00
|
|
|
return op.emitError(
|
2023-02-01 19:13:59 +08:00
|
|
|
"unimplemented: only contiguous and channels last memory "
|
|
|
|
"format is supported");
|
2022-09-21 06:07:46 +08:00
|
|
|
}
|
2024-05-31 14:45:13 +08:00
|
|
|
auto outType = dyn_cast<TensorType>(
|
|
|
|
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
|
|
|
|
op.getType()));
|
2022-12-08 04:20:41 +08:00
|
|
|
rewriter.replaceOpWithNewOp<tosa::CastOp>(op, outType, adaptor.getSelf());
|
2022-09-21 06:07:46 +08:00
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2023-03-15 23:42:15 +08:00
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenConstantPadNdOp>::matchAndRewrite(
|
|
|
|
AtenConstantPadNdOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
Location loc = op.getLoc();
|
|
|
|
Value self = adaptor.getSelf();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfTy = cast<RankedTensorType>(self.getType());
|
2023-03-15 23:42:15 +08:00
|
|
|
auto selfElemTy = selfTy.getElementType();
|
|
|
|
int64_t rank = selfTy.getRank();
|
|
|
|
|
2023-03-24 08:55:58 +08:00
|
|
|
// START the code snippet from
|
|
|
|
// lib/Conversion/TorchToLinalg/TensorConstructors.cpp (see:
|
|
|
|
// ConvertAtenConstantPadNdOp) Pattern match against the op's original
|
|
|
|
// operands, because otherwise we will get the lowered version of the operands
|
|
|
|
// which is harder to pattern match.
|
2023-03-15 23:42:15 +08:00
|
|
|
SmallVector<int64_t> padInts;
|
|
|
|
if (!matchPattern(op.getPad(), m_TorchListOfConstantInts(padInts)))
|
2023-03-24 08:55:58 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"only support constant int pad ranges");
|
2023-03-15 23:42:15 +08:00
|
|
|
uint64_t padRank = padInts.size() / 2;
|
|
|
|
if (padRank * 2 != padInts.size())
|
|
|
|
return rewriter.notifyMatchFailure(op, "pad range size is not even");
|
|
|
|
if (rank < 0 || padRank > (uint64_t)rank)
|
|
|
|
return rewriter.notifyMatchFailure(op, "padding exceeds tensor rank");
|
|
|
|
|
|
|
|
// Initialize low/high paddings with 0 for all the dims.
|
|
|
|
SmallVector<int64_t> lowPadding(/*Size=*/rank, /*Value=*/0);
|
|
|
|
SmallVector<int64_t> highPadding(/*Size=*/rank, /*Value=*/0);
|
|
|
|
// Add the requested padding - note op.pad() is highest dim first ordered
|
|
|
|
// pairs of low,high.
|
|
|
|
for (uint64_t i = 0; i < padRank; ++i) {
|
2023-03-24 08:55:58 +08:00
|
|
|
lowPadding[rank - i - 1] = padInts[i * 2];
|
|
|
|
highPadding[rank - i - 1] = padInts[i * 2 + 1];
|
2023-03-15 23:42:15 +08:00
|
|
|
}
|
2023-03-24 08:55:58 +08:00
|
|
|
// END the code snippet from
|
|
|
|
// lib/Conversion/TorchToLinalg/TensorConstructors.cpp (see:
|
|
|
|
// ConvertAtenConstantPadNdOp)
|
2023-03-15 23:42:15 +08:00
|
|
|
|
|
|
|
llvm::SmallVector<int64_t> translatePadsList;
|
|
|
|
|
|
|
|
for (unsigned int i = 0; i < rank; i++) {
|
|
|
|
translatePadsList.push_back(lowPadding[i]);
|
|
|
|
translatePadsList.push_back(highPadding[i]);
|
|
|
|
}
|
|
|
|
|
|
|
|
DenseElementsAttr paddingAttr = DenseIntElementsAttr::get(
|
|
|
|
RankedTensorType::get({rank, 2}, rewriter.getI64Type()),
|
|
|
|
translatePadsList);
|
|
|
|
|
|
|
|
Value padsList1 = rewriter.create<mlir::tosa::ConstOp>(
|
|
|
|
loc, paddingAttr.getType(), paddingAttr);
|
|
|
|
|
|
|
|
Value padValue = adaptor.getValue();
|
|
|
|
Operation *padOp = padValue.getDefiningOp();
|
|
|
|
padValue = padOp->getOperand(0);
|
|
|
|
|
|
|
|
Value padTensor;
|
|
|
|
if (failed(torchScalarToTosaTensor(rewriter, op.getOperation(), padValue,
|
2023-03-24 08:55:58 +08:00
|
|
|
padTensor, selfElemTy, {})))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Pad value needs to be a scalar constant for conversion to "
|
|
|
|
"TOSA pad operation");
|
|
|
|
|
2023-03-15 23:42:15 +08:00
|
|
|
rewriter.replaceOpWithNewOp<mlir::tosa::PadOp>(
|
2023-03-24 08:55:58 +08:00
|
|
|
op, getTypeConverter()->convertType(op.getType()), self, padsList1,
|
|
|
|
padTensor);
|
2023-03-15 23:42:15 +08:00
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2023-05-10 23:25:58 +08:00
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenCatOp>::matchAndRewrite(
|
|
|
|
AtenCatOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
2023-08-16 00:53:28 +08:00
|
|
|
const TypeConverter *typeConverter = this->getTypeConverter();
|
2023-05-10 23:25:58 +08:00
|
|
|
auto outType =
|
2024-04-28 05:00:56 +08:00
|
|
|
cast<RankedTensorType>(typeConverter->convertType(op.getType()));
|
2023-05-10 23:25:58 +08:00
|
|
|
int64_t rank = outType.getRank();
|
|
|
|
int64_t dim;
|
|
|
|
|
|
|
|
if (!outType || !outType.hasStaticShape()) {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only Tensor types with static shapes are currently supported");
|
|
|
|
}
|
|
|
|
|
|
|
|
Location loc = op.getLoc();
|
|
|
|
if (!matchPattern(op.getDim(), m_TorchConstantInt(&dim))) {
|
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"unimplemented: dim is not constant");
|
|
|
|
}
|
|
|
|
dim = toPositiveDim(dim, rank);
|
|
|
|
if (!isValidDim(dim, rank)) {
|
|
|
|
return rewriter.notifyMatchFailure(op, "dim is statically invalid");
|
|
|
|
}
|
|
|
|
auto tensorList = op.getTensors();
|
|
|
|
SmallVector<Value> tensorsTorchType;
|
|
|
|
|
|
|
|
if (!getListConstructElements(tensorList, tensorsTorchType)) {
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "unimplemented: the tensor list is not from list construct");
|
|
|
|
}
|
|
|
|
auto builtinTensors =
|
|
|
|
getTypeConvertedValues(rewriter, loc, typeConverter, tensorsTorchType);
|
|
|
|
|
|
|
|
auto result = tosa::CreateOpAndInfer<tosa::ConcatOp>(
|
2023-09-13 06:09:57 +08:00
|
|
|
rewriter, loc, outType, builtinTensors, rewriter.getI32IntegerAttr(dim));
|
2023-05-10 23:25:58 +08:00
|
|
|
rewriter.replaceOp(op, result.getResult());
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2023-07-14 14:23:10 +08:00
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenSqrtOp>::matchAndRewrite(
|
|
|
|
AtenSqrtOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
|
|
|
|
// Converts AtenSqrtOp into pow(x, 0.5)
|
|
|
|
auto self = adaptor.getSelf();
|
2024-04-28 05:00:56 +08:00
|
|
|
auto selfTy = dyn_cast<TensorType>(self.getType());
|
2023-07-14 14:23:10 +08:00
|
|
|
if (!selfTy)
|
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Only Tensor types supported in TOSA");
|
|
|
|
|
2024-05-31 14:45:13 +08:00
|
|
|
auto resultType =
|
|
|
|
cast<RankedTensorType>(typeConverter->convertType(op.getType()));
|
2023-07-14 14:23:10 +08:00
|
|
|
auto elementType = resultType.getElementType();
|
|
|
|
|
|
|
|
if (isa<mlir::IntegerType>(selfTy.getElementType())) {
|
|
|
|
self = rewriter.createOrFold<tosa::CastOp>(
|
|
|
|
op->getLoc(), RankedTensorType::get(resultType.getShape(), elementType),
|
|
|
|
self);
|
|
|
|
}
|
|
|
|
|
|
|
|
auto oneHalf =
|
|
|
|
tosa::getConstTensor<float>(rewriter, op, 0.5, {}, elementType).value();
|
|
|
|
|
|
|
|
rewriter.replaceOpWithNewOp<tosa::PowOp>(op, resultType, self, oneHalf);
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2024-06-27 00:10:14 +08:00
|
|
|
template <>
|
|
|
|
LogicalResult
|
|
|
|
ConvertAtenOp<Aten__InterpolateSizeListScaleListOp>::matchAndRewrite(
|
|
|
|
Aten__InterpolateSizeListScaleListOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
// Converts torch.aten.__interpolate.size_list_scale_list to tosa.resize
|
|
|
|
auto input = adaptor.getInput();
|
|
|
|
auto inputTy = dyn_cast<RankedTensorType>(input.getType());
|
|
|
|
if (!inputTy)
|
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Only Tensor types supported in TOSA");
|
|
|
|
auto inputRank = inputTy.getRank();
|
|
|
|
if (inputRank != 4)
|
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"TOSA resize() takes rank==4 tensors.");
|
|
|
|
|
|
|
|
auto inputShape = inputTy.getShape();
|
|
|
|
auto inputElemTy = inputTy.getElementType();
|
|
|
|
// TOSA works in NHWC. Perform the necessary transformations.
|
|
|
|
std::optional<Value> nchwToNhwcTransposeConst =
|
|
|
|
tosa::getConstTensor<int32_t>(rewriter, op,
|
|
|
|
/*vec=*/{0, 2, 3, 1},
|
|
|
|
/*shape=*/{static_cast<int32_t>(4)});
|
|
|
|
SmallVector<int64_t> transposedInputShape(
|
|
|
|
{inputShape[0], inputShape[2], inputShape[3], inputShape[1]});
|
|
|
|
auto transposedInputTy = RankedTensorType::get(
|
|
|
|
makeShapeLLVMCompatible(transposedInputShape), inputElemTy);
|
|
|
|
auto transposedInput =
|
|
|
|
rewriter
|
|
|
|
.create<tosa::TransposeOp>(
|
|
|
|
op->getLoc(), getTypeConverter()->convertType(transposedInputTy),
|
|
|
|
input, nchwToNhwcTransposeConst.value())
|
|
|
|
.getResult();
|
|
|
|
|
|
|
|
auto inputHeight = transposedInputShape[1];
|
|
|
|
auto inputWidth = transposedInputShape[2];
|
|
|
|
|
|
|
|
int outputHeight, outputWidth;
|
|
|
|
if (!isa<Torch::NoneType>(op.getScaleFactor().getType())) {
|
|
|
|
SmallVector<double, 2> scaleFactor;
|
|
|
|
if (!matchPattern(op.getScaleFactor(),
|
|
|
|
m_TorchListOfConstantFloats(scaleFactor)))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "non-const scale_factor parameter unsupported");
|
|
|
|
|
|
|
|
outputHeight = inputHeight * scaleFactor[0];
|
|
|
|
outputWidth = inputWidth * scaleFactor[1];
|
|
|
|
|
|
|
|
} else {
|
|
|
|
if (!isa<Torch::NoneType>(op.getSize().getType()))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Scale factor and size are both absent!");
|
|
|
|
|
|
|
|
SmallVector<int64_t, 4> size;
|
|
|
|
if (!matchPattern(op.getSize(), m_TorchListOfConstantInts(size)))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "non-const size parameter unsupported");
|
|
|
|
outputHeight = size[0];
|
|
|
|
outputWidth = size[1];
|
|
|
|
}
|
|
|
|
|
|
|
|
std::string pyMode;
|
|
|
|
if (!matchPattern(op.getMode(), m_TorchConstantStr(pyMode)))
|
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"non-const mode parameter unsupported");
|
|
|
|
|
|
|
|
// All torch modes listed in
|
|
|
|
// https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html
|
|
|
|
if (pyMode != "bilinear" && pyMode != "nearest")
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only nearest and bilinear interpolation modes supported");
|
|
|
|
|
|
|
|
std::string mode;
|
|
|
|
if (pyMode == "bilinear") {
|
|
|
|
mode = "BILINEAR";
|
|
|
|
} else {
|
|
|
|
mode = "NEAREST_NEIGHBOR";
|
|
|
|
}
|
|
|
|
|
|
|
|
bool alignCorners;
|
|
|
|
if (!matchPattern(op.getAlignCorners(), m_TorchConstantBool(&alignCorners)))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "non-const align_corners parameter unsupported");
|
|
|
|
|
|
|
|
bool recomputeScaleFactor;
|
|
|
|
if (isa<Torch::NoneType>(op.getRecomputeScaleFactor().getType()))
|
|
|
|
recomputeScaleFactor = false;
|
|
|
|
else if (!matchPattern(op.getRecomputeScaleFactor(),
|
|
|
|
m_TorchConstantBool(&recomputeScaleFactor)))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "non-const recompute_scale_factor parameter unsupported");
|
|
|
|
if (recomputeScaleFactor)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Application of recompute_scale_factor not yet supported");
|
|
|
|
|
|
|
|
bool antialias;
|
|
|
|
if (!matchPattern(op.getAntialias(), m_TorchConstantBool(&antialias)))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "non-const antialias parameter unsupported");
|
|
|
|
if (antialias)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Application of antialias not yet supported");
|
|
|
|
|
|
|
|
SmallVector<int64_t> transposedResizedOpShape(
|
|
|
|
{inputShape[0], outputHeight, outputWidth, inputShape[1]});
|
|
|
|
auto transposedResizedOpTy = RankedTensorType::get(
|
|
|
|
makeShapeLLVMCompatible(transposedResizedOpShape), inputElemTy);
|
|
|
|
|
|
|
|
// Formatting snake_case to match TOSA spec names for readability
|
|
|
|
int scale_y_n, scale_y_d, offset_y, border_y;
|
|
|
|
int scale_x_n, scale_x_d, offset_x, border_x;
|
|
|
|
|
|
|
|
// Align corners sets the scaling ratio to (OH - 1)/(IH - 1)
|
|
|
|
// rather than OH / IH. Similarly for width.
|
|
|
|
auto normalize = [&](int input, int output, int &n, int &d, int &offset,
|
|
|
|
int &border) {
|
|
|
|
// Dimension is length 1, we are just sampling from one value.
|
|
|
|
if (input == 1) {
|
|
|
|
n = output;
|
|
|
|
d = 1;
|
|
|
|
offset = 0;
|
|
|
|
border = output - 1;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Apply if aligned and capable to be aligned.
|
|
|
|
bool apply_aligned = alignCorners && (output > 1);
|
|
|
|
n = apply_aligned ? (output - 1) : output;
|
|
|
|
d = apply_aligned ? (input - 1) : input;
|
|
|
|
|
|
|
|
// Simplify the scalers, make sure they are even values.
|
|
|
|
int gcd = std::gcd(n, d);
|
|
|
|
n = 2 * n / gcd;
|
|
|
|
d = 2 * d / gcd;
|
|
|
|
|
|
|
|
offset = 0;
|
|
|
|
|
|
|
|
// If nearest neighbours we need to guarantee we round up.
|
|
|
|
if (mode == "NEAREST_NEIGHBOR" && alignCorners) {
|
|
|
|
offset += n / 2;
|
|
|
|
}
|
|
|
|
|
|
|
|
// TBD: impact of antialias parameter here ?
|
|
|
|
|
|
|
|
// We can compute this directly based on previous values.
|
|
|
|
border = d * (output - 1) - n * (input - 1) + offset;
|
|
|
|
};
|
|
|
|
|
|
|
|
normalize(inputHeight, outputHeight, scale_y_n, scale_y_d, offset_y,
|
|
|
|
border_y);
|
|
|
|
normalize(inputWidth, outputWidth, scale_x_n, scale_x_d, offset_x, border_x);
|
|
|
|
|
|
|
|
DenseI64ArrayAttr scale = rewriter.getDenseI64ArrayAttr(
|
|
|
|
{scale_y_n, scale_y_d, scale_x_n, scale_x_d});
|
|
|
|
DenseI64ArrayAttr offset =
|
|
|
|
rewriter.getDenseI64ArrayAttr({offset_y, offset_x});
|
|
|
|
DenseI64ArrayAttr border =
|
|
|
|
rewriter.getDenseI64ArrayAttr({border_y, border_x});
|
|
|
|
StringAttr modeAttr = rewriter.getStringAttr(mode);
|
|
|
|
|
|
|
|
auto resizeOpResult =
|
|
|
|
rewriter
|
|
|
|
.create<tosa::ResizeOp>(op->getLoc(), transposedResizedOpTy,
|
|
|
|
transposedInput, scale, offset, border,
|
|
|
|
modeAttr)
|
|
|
|
.getResult();
|
|
|
|
|
|
|
|
auto resultType =
|
|
|
|
cast<RankedTensorType>(typeConverter->convertType(op.getType()));
|
|
|
|
std::optional<Value> nhwcToNchwTransposeConst =
|
|
|
|
tosa::getConstTensor<int32_t>(rewriter, op,
|
|
|
|
/*vec=*/{0, 3, 1, 2},
|
|
|
|
/*shape=*/{static_cast<int32_t>(4)});
|
|
|
|
// SmallVector<int64_t> transposedOutputShape(
|
|
|
|
// {transposedResizedOpShape[0], transposedResizedOpShape[3],
|
|
|
|
// transposedResizedOpShape[1], transposedResizedOpShape[2]});
|
|
|
|
// auto transposedOutputType = RankedTensorType::get(
|
|
|
|
// makeShapeLLVMCompatible(transposedOutputShape), inputElemTy);
|
|
|
|
rewriter
|
|
|
|
.replaceOpWithNewOp<tosa::TransposeOp>(
|
|
|
|
op, getTypeConverter()->convertType(resultType), resizeOpResult,
|
|
|
|
nhwcToNchwTransposeConst.value())
|
|
|
|
.getResult();
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2024-09-30 23:24:31 +08:00
|
|
|
// Template to create supporting tril mask tensor for aten.tril
|
2024-09-06 02:27:29 +08:00
|
|
|
template <typename T>
|
|
|
|
Value createTrilMask(PatternRewriter &rewriter, Operation *op,
|
|
|
|
ArrayRef<int64_t> shape, int64_t h, int64_t w,
|
|
|
|
int64_t diagonal) {
|
|
|
|
SmallVector<T> vec;
|
|
|
|
|
|
|
|
for (int64_t i = 0; i < h; i++) {
|
|
|
|
for (int64_t j = 0; j < w; j++) {
|
|
|
|
// Positive diagonal value includes as many diagonals above the main
|
|
|
|
// diagonal, while negative diagonal value excludes as many diagonals
|
|
|
|
// below the main diagonal.
|
|
|
|
if (i >= j - diagonal) {
|
|
|
|
vec.push_back(static_cast<T>(1));
|
|
|
|
} else {
|
|
|
|
vec.push_back(static_cast<T>(0));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return tosa::getConstTensor<T>(rewriter, op, vec, shape).value();
|
|
|
|
}
|
|
|
|
|
|
|
|
// Legalization for aten.tril
|
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenTrilOp>::matchAndRewrite(
|
|
|
|
AtenTrilOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
auto self = adaptor.getSelf();
|
|
|
|
|
|
|
|
// Not a ranked tensor type
|
|
|
|
auto selfType = dyn_cast<RankedTensorType>(self.getType());
|
|
|
|
if (!selfType)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only ranked tensor types are supported");
|
|
|
|
|
|
|
|
// Rank below 2 not accepted
|
|
|
|
auto selfRank = selfType.getRank();
|
|
|
|
if (selfRank <= 1)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Rank 0 and 1 are not accepted as they cause underflow");
|
|
|
|
|
|
|
|
if (!selfType.hasStaticShape())
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Currently only static shapes are supported");
|
|
|
|
|
|
|
|
const TypeConverter *typeConverter = this->getTypeConverter();
|
|
|
|
RankedTensorType resultType = cast<RankedTensorType>(
|
|
|
|
typeConverter->convertType(op->getResult(0).getType()));
|
|
|
|
if (!resultType)
|
|
|
|
return rewriter.notifyMatchFailure(op, "Result type cannot be empty");
|
|
|
|
|
|
|
|
// Get height, width of input tensor, and diagonal arg to create
|
|
|
|
// a const mask tensor to multiply with input.
|
|
|
|
// This mask tensor has the same height and width of input tensor
|
|
|
|
// and consists of 1's for the lower triangle part and 0's for the rest.
|
|
|
|
// For example, with h=4, w=6, diagonal=1:
|
|
|
|
// tensor([[1, 1, 0, 0, 0, 0],
|
|
|
|
// [1, 1, 1, 0, 0, 0],
|
|
|
|
// [1, 1, 1, 1, 0, 0],
|
|
|
|
// [1, 1, 1, 1, 1, 0]])
|
|
|
|
auto selfShape = selfType.getShape();
|
|
|
|
int64_t h = selfShape[selfRank - 2];
|
|
|
|
int64_t w = selfShape[selfRank - 1];
|
|
|
|
int64_t diagonal;
|
|
|
|
|
|
|
|
if (!matchPattern(op.getDiagonal(), m_TorchConstantInt(&diagonal)))
|
|
|
|
return rewriter.notifyMatchFailure(op, "Diagonal value is not an integer");
|
|
|
|
|
|
|
|
// Define shape for mask tensor based on rank
|
2024-09-30 23:24:31 +08:00
|
|
|
SmallVector<int64_t> maskShape;
|
2024-09-06 02:27:29 +08:00
|
|
|
for (auto i = 0; i < selfRank - 2; i++)
|
2024-09-30 23:24:31 +08:00
|
|
|
maskShape.push_back(1);
|
|
|
|
maskShape.push_back(h);
|
|
|
|
maskShape.push_back(w);
|
|
|
|
|
|
|
|
Value trilMask = TypeSwitch<Type, Value>(resultType.getElementType())
|
|
|
|
.Case<mlir::FloatType>([&](auto) {
|
|
|
|
return createTrilMask<float>(rewriter, op, maskShape,
|
|
|
|
h, w, diagonal);
|
|
|
|
})
|
|
|
|
.Case<mlir::IntegerType>([&](auto intType) {
|
|
|
|
switch (intType.getWidth()) {
|
|
|
|
case 1:
|
|
|
|
return createTrilMask<bool>(rewriter, op, maskShape,
|
|
|
|
h, w, diagonal);
|
|
|
|
case 32:
|
|
|
|
return createTrilMask<int32_t>(
|
|
|
|
rewriter, op, maskShape, h, w, diagonal);
|
|
|
|
case 64:
|
|
|
|
return createTrilMask<int64_t>(
|
|
|
|
rewriter, op, maskShape, h, w, diagonal);
|
|
|
|
}
|
|
|
|
llvm_unreachable("Invalid integer width");
|
|
|
|
});
|
2024-09-06 02:27:29 +08:00
|
|
|
|
|
|
|
rewriter.replaceOpWithNewOp<tosa::MulOp>(op, resultType, self, trilMask,
|
|
|
|
/*shift=*/0);
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
|
2024-09-30 23:24:31 +08:00
|
|
|
// Template to create supporting diagonal mask tensor for aten.diagonal
|
|
|
|
template <typename T>
|
|
|
|
Value createDiagonalMask(PatternRewriter &rewriter, Operation *op,
|
|
|
|
ArrayRef<int64_t> shape, int64_t h, int64_t w,
|
|
|
|
int64_t offset) {
|
|
|
|
SmallVector<T> vec;
|
|
|
|
|
|
|
|
for (int64_t i = 0; i < h; i++) {
|
|
|
|
for (int64_t j = 0; j < w; j++) {
|
|
|
|
// Positive offset value moves above the main diagonal, while negative
|
|
|
|
// diagonal value moves below the main diagonal.
|
|
|
|
if (i + offset == j) {
|
|
|
|
vec.push_back(static_cast<T>(1));
|
|
|
|
} else {
|
|
|
|
vec.push_back(static_cast<T>(0));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return tosa::getConstTensor<T>(rewriter, op, vec, shape).value();
|
|
|
|
}
|
|
|
|
|
|
|
|
// Legalization for aten.diagonal
|
|
|
|
template <>
|
|
|
|
LogicalResult ConvertAtenOp<AtenDiagonalOp>::matchAndRewrite(
|
|
|
|
AtenDiagonalOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const {
|
|
|
|
auto self = adaptor.getSelf();
|
|
|
|
|
|
|
|
// Not a ranked tensor type
|
|
|
|
auto selfType = dyn_cast<RankedTensorType>(self.getType());
|
|
|
|
if (!selfType)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Only ranked tensor types are supported");
|
|
|
|
|
|
|
|
// Rank below 2 not accepted
|
|
|
|
auto selfRank = selfType.getRank();
|
|
|
|
if (selfRank <= 1)
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Rank 0 and 1 are not accepted as they cause underflow");
|
|
|
|
|
|
|
|
if (!selfType.hasStaticShape())
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Currently only static shapes are supported");
|
|
|
|
|
|
|
|
const TypeConverter *typeConverter = this->getTypeConverter();
|
|
|
|
RankedTensorType resultType = cast<RankedTensorType>(
|
|
|
|
typeConverter->convertType(op->getResult(0).getType()));
|
|
|
|
if (!resultType)
|
|
|
|
return rewriter.notifyMatchFailure(op, "Result type cannot be empty");
|
|
|
|
|
|
|
|
auto selfElemTy = selfType.getElementType();
|
|
|
|
auto resultElemTy = resultType.getElementType();
|
|
|
|
|
|
|
|
int64_t offset, dim1, dim2;
|
|
|
|
if (!matchPattern(op.getOffset(), m_TorchConstantInt(&offset)))
|
|
|
|
offset = 0;
|
|
|
|
|
|
|
|
if (!matchPattern(op.getDim1(), m_TorchConstantInt(&dim1))) {
|
|
|
|
dim1 = 0;
|
|
|
|
} else {
|
|
|
|
dim1 = toPositiveDim(dim1, selfRank);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!matchPattern(op.getDim2(), m_TorchConstantInt(&dim2))) {
|
|
|
|
dim2 = 1;
|
|
|
|
} else {
|
|
|
|
dim2 = toPositiveDim(dim2, selfRank);
|
|
|
|
}
|
|
|
|
|
|
|
|
auto selfShape = makeShapeTorchCompatible(selfType.getShape());
|
|
|
|
int64_t h = selfShape[dim1];
|
|
|
|
int64_t w = selfShape[dim2];
|
|
|
|
|
|
|
|
// Overflowing offset not supported
|
|
|
|
if ((offset < 0 && std::abs(offset) >= h) || (offset >= 0 && offset >= w))
|
|
|
|
return rewriter.notifyMatchFailure(
|
|
|
|
op, "Offset greater or equal than shape not supported");
|
|
|
|
|
|
|
|
int64_t targetDim1 = selfRank - 2;
|
|
|
|
int64_t targetDim2 = selfRank - 1;
|
|
|
|
|
|
|
|
Value selfTransposed = self;
|
|
|
|
SmallVector<int64_t> transposedInputShape = selfShape;
|
|
|
|
RankedTensorType transposedInputType = selfType;
|
|
|
|
|
|
|
|
// If (dim1, dim2) != (rank - 2, rank - 1), transpose the input tensor
|
|
|
|
// so that dim1 and dim2 become rank - 2 and rank - 1. We do this so that
|
|
|
|
// we can consistently create the diagonal mask tensor.
|
|
|
|
if (!(dim1 == targetDim1 && dim2 == targetDim2)) {
|
|
|
|
SmallVector<int32_t> transposedDims;
|
|
|
|
transposedInputShape.clear();
|
|
|
|
|
|
|
|
for (int64_t i = 0; i < selfRank; ++i) {
|
|
|
|
if (i == dim1 || i == dim2)
|
|
|
|
continue;
|
|
|
|
transposedDims.push_back(i);
|
|
|
|
}
|
|
|
|
transposedDims.push_back(dim1);
|
|
|
|
transposedDims.push_back(dim2);
|
|
|
|
|
|
|
|
auto transposedDimsConst = tosa::getConstTensor<int32_t>(
|
|
|
|
rewriter, op,
|
|
|
|
/*vec=*/transposedDims,
|
|
|
|
/*shape=*/{static_cast<int32_t>(selfRank)});
|
|
|
|
|
|
|
|
for (auto &dim : transposedDims)
|
|
|
|
transposedInputShape.push_back(selfShape[dim]);
|
|
|
|
|
|
|
|
transposedInputType = RankedTensorType::get(
|
|
|
|
makeShapeLLVMCompatible(transposedInputShape), selfElemTy);
|
|
|
|
|
|
|
|
selfTransposed = rewriter.create<tosa::TransposeOp>(
|
|
|
|
op->getLoc(), transposedInputType, self, transposedDimsConst.value());
|
|
|
|
}
|
|
|
|
|
|
|
|
// Define shape for mask tensor based on rank
|
|
|
|
SmallVector<int64_t> maskShape;
|
|
|
|
for (auto i = 0; i < selfRank - 2; i++)
|
|
|
|
maskShape.push_back(1);
|
|
|
|
maskShape.push_back(h);
|
|
|
|
maskShape.push_back(w);
|
|
|
|
|
|
|
|
Value diagonalMask =
|
|
|
|
TypeSwitch<Type, Value>(resultElemTy)
|
|
|
|
.Case<mlir::FloatType>([&](auto) {
|
|
|
|
return createDiagonalMask<float>(rewriter, op, maskShape, h, w,
|
|
|
|
offset);
|
|
|
|
})
|
|
|
|
.Case<mlir::IntegerType>([&](auto intType) {
|
|
|
|
switch (intType.getWidth()) {
|
|
|
|
case 1:
|
|
|
|
return createDiagonalMask<bool>(rewriter, op, maskShape, h, w,
|
|
|
|
offset);
|
|
|
|
case 32:
|
|
|
|
return createDiagonalMask<int32_t>(rewriter, op, maskShape, h, w,
|
|
|
|
offset);
|
|
|
|
case 64:
|
|
|
|
return createDiagonalMask<int64_t>(rewriter, op, maskShape, h, w,
|
|
|
|
offset);
|
|
|
|
}
|
|
|
|
llvm_unreachable("Invalid integer width");
|
|
|
|
});
|
|
|
|
|
|
|
|
Value diagonalTensor = rewriter.create<tosa::MulOp>(
|
|
|
|
op->getLoc(), transposedInputType, selfTransposed, diagonalMask,
|
|
|
|
/*shift=*/0);
|
|
|
|
|
|
|
|
auto resultShape = makeShapeTorchCompatible(resultType.getShape());
|
|
|
|
auto targetReduceDim = resultShape[resultType.getRank() - 1];
|
|
|
|
|
|
|
|
// If transposedInputShape[targetDim1] (or h) is greater than the innermost
|
|
|
|
// dim of the result, we won't get the correct shape when we reduce sum along
|
|
|
|
// the innermost dim to get the result. Therefore, we have to slice the
|
|
|
|
// transposed tensor so that transposedInputShape[targetDim1] ==
|
|
|
|
// targetReduceDim.
|
|
|
|
if (h > targetReduceDim) {
|
|
|
|
transposedInputShape[targetDim1] = targetReduceDim;
|
|
|
|
transposedInputType = RankedTensorType::get(
|
|
|
|
makeShapeLLVMCompatible(transposedInputShape), selfElemTy);
|
|
|
|
SmallVector<int64_t> startSlice(selfRank, 0);
|
|
|
|
SmallVector<int64_t> sizeSlice =
|
|
|
|
llvm::to_vector(makeShapeTorchCompatible(transposedInputShape));
|
|
|
|
if (offset < 0)
|
|
|
|
startSlice[targetDim1] = std::abs(offset);
|
|
|
|
diagonalTensor = rewriter.create<tosa::SliceOp>(
|
|
|
|
op->getLoc(), transposedInputType, diagonalTensor,
|
|
|
|
rewriter.getDenseI64ArrayAttr(startSlice),
|
|
|
|
rewriter.getDenseI64ArrayAttr(sizeSlice));
|
|
|
|
}
|
|
|
|
|
|
|
|
// Apply Reduce Sum to get the result
|
|
|
|
auto reduceDimType = RankedTensorType::get({1}, rewriter.getI64Type());
|
|
|
|
auto reduceDimAttr =
|
|
|
|
DenseIntElementsAttr::get(reduceDimType, llvm::ArrayRef({targetDim2}));
|
|
|
|
auto result =
|
|
|
|
mlir::tosa::convertReduceSumOp(rewriter, op, resultType, diagonalTensor,
|
|
|
|
reduceDimAttr, /*keep_dims=*/false);
|
|
|
|
|
|
|
|
rewriter.replaceOp(op, result.value());
|
|
|
|
|
|
|
|
return success();
|
|
|
|
}
|
2021-10-08 10:07:03 +08:00
|
|
|
} // namespace
|
|
|
|
|
|
|
|
// -----------------------------------------------------------------------------
|
2021-10-29 01:09:12 +08:00
|
|
|
// TorchToTosa Pass
|
2021-10-08 10:07:03 +08:00
|
|
|
// -----------------------------------------------------------------------------
|
|
|
|
|
|
|
|
namespace {
|
2021-11-11 11:03:36 +08:00
|
|
|
class ConvertTorchToTosa : public ConvertTorchToTosaBase<ConvertTorchToTosa> {
|
2021-10-08 10:07:03 +08:00
|
|
|
public:
|
|
|
|
void getDependentDialects(DialectRegistry ®istry) const override {
|
|
|
|
registry.insert<tosa::TosaDialect>();
|
2021-12-16 03:01:01 +08:00
|
|
|
registry.insert<tensor::TensorDialect>();
|
2022-10-05 21:28:06 +08:00
|
|
|
registry.insert<arith::ArithDialect>();
|
2021-10-08 10:07:03 +08:00
|
|
|
TorchConversion::getBackendTypeConversionDependentDialects(registry);
|
|
|
|
}
|
|
|
|
|
|
|
|
void runOnOperation() override {
|
|
|
|
MLIRContext *context = &getContext();
|
|
|
|
ConversionTarget target(*context);
|
2021-12-16 03:01:01 +08:00
|
|
|
target.addLegalDialect<tosa::TosaDialect, tensor::TensorDialect,
|
2022-10-05 21:28:06 +08:00
|
|
|
arith::ArithDialect>();
|
2021-10-08 10:07:03 +08:00
|
|
|
|
|
|
|
TypeConverter typeConverter;
|
|
|
|
typeConverter.addConversion([](Type type) { return type; });
|
|
|
|
TorchConversion::setupBackendTypeConversion(target, typeConverter);
|
|
|
|
|
2023-07-25 16:11:40 +08:00
|
|
|
// The following ops are never the primary reason why lowering fails.
|
|
|
|
// The backend contract only allows functions to return tensors thus there
|
|
|
|
// is always another op using them.
|
|
|
|
// When we have a chain of torch.constant.int followed by a unsupported
|
|
|
|
// torch op, we want the pass to mention the unsupported torch op
|
|
|
|
// in the error message.
|
|
|
|
target.addLegalOp<ConstantNoneOp>();
|
|
|
|
target.addLegalOp<ConstantBoolOp>();
|
|
|
|
target.addLegalOp<ConstantIntOp>();
|
|
|
|
target.addLegalOp<ConstantFloatOp>();
|
|
|
|
target.addLegalOp<ConstantStrOp>();
|
|
|
|
target.addLegalOp<ConstantDeviceOp>();
|
|
|
|
target.addLegalOp<PrimListConstructOp>();
|
|
|
|
target.addLegalOp<PrimTupleConstructOp>();
|
|
|
|
target.addIllegalDialect<Torch::TorchDialect>();
|
|
|
|
|
2021-10-08 10:07:03 +08:00
|
|
|
RewritePatternSet patterns(context);
|
2021-10-29 01:09:12 +08:00
|
|
|
|
2021-11-12 08:15:58 +08:00
|
|
|
#define INSERT_UNARY_FPONLY_PATTERN(AtenOp, TosaOp) \
|
|
|
|
target.addIllegalOp<AtenOp>(); \
|
|
|
|
patterns.add<ConvertAtenUnaryFPOnlyOp<AtenOp, TosaOp>>(typeConverter, \
|
|
|
|
context);
|
|
|
|
INSERT_UNARY_FPONLY_PATTERN(AtenLogOp, tosa::LogOp)
|
|
|
|
INSERT_UNARY_FPONLY_PATTERN(AtenExpOp, tosa::ExpOp)
|
|
|
|
#undef INSERT_UNARY_FPONLY_PATTERN
|
|
|
|
|
|
|
|
#define INSERT_UNARY_PATTERN(AtenOp, TosaOp) \
|
|
|
|
target.addIllegalOp<AtenOp>(); \
|
|
|
|
patterns.add<ConvertAtenUnaryOp<AtenOp, TosaOp>>(typeConverter, context);
|
|
|
|
INSERT_UNARY_PATTERN(AtenNegOp, tosa::NegateOp)
|
|
|
|
INSERT_UNARY_PATTERN(AtenFloorOp, tosa::FloorOp)
|
2021-12-15 02:03:58 +08:00
|
|
|
INSERT_UNARY_PATTERN(AtenRsqrtOp, tosa::RsqrtOp)
|
2021-11-12 08:15:58 +08:00
|
|
|
INSERT_UNARY_PATTERN(AtenBitwiseNotOp, tosa::BitwiseNotOp)
|
2022-01-21 02:58:30 +08:00
|
|
|
INSERT_UNARY_PATTERN(AtenCeilOp, tosa::CeilOp)
|
|
|
|
INSERT_UNARY_PATTERN(AtenReciprocalOp, tosa::ReciprocalOp)
|
2024-09-21 05:33:55 +08:00
|
|
|
INSERT_UNARY_PATTERN(AtenCosOp, tosa::CosOp)
|
|
|
|
INSERT_UNARY_PATTERN(AtenSinOp, tosa::SinOp)
|
|
|
|
INSERT_UNARY_PATTERN(AtenLogicalNotOp, tosa::LogicalNotOp)
|
2021-11-12 08:15:58 +08:00
|
|
|
#undef INSERT_UNARY_PATTERN
|
|
|
|
|
2022-01-07 00:31:29 +08:00
|
|
|
#define INSERT_BINARY_PATTERN(AtenOp, TosaOp) \
|
|
|
|
target.addIllegalOp<AtenOp>(); \
|
2021-12-16 03:19:25 +08:00
|
|
|
patterns.add<ConvertAtenBinaryOp<AtenOp, TosaOp>>(typeConverter, context);
|
|
|
|
INSERT_BINARY_PATTERN(AtenMaximumOp, tosa::MaximumOp)
|
|
|
|
INSERT_BINARY_PATTERN(AtenMinimumOp, tosa::MinimumOp)
|
2024-01-12 02:36:48 +08:00
|
|
|
INSERT_BINARY_PATTERN(AtenLogicalOrOp, tosa::LogicalOrOp)
|
2024-09-21 05:33:55 +08:00
|
|
|
INSERT_BINARY_PATTERN(AtenLogicalXorOp, tosa::LogicalXorOp)
|
|
|
|
INSERT_BINARY_PATTERN(AtenBitwiseLeftShiftTensorOp,
|
|
|
|
tosa::LogicalLeftShiftOp)
|
|
|
|
INSERT_BINARY_PATTERN(AtenBitwiseRightShiftTensorOp,
|
|
|
|
tosa::ArithmeticRightShiftOp)
|
2021-12-16 03:19:25 +08:00
|
|
|
#undef INSERT_BINARY_PATTERN
|
|
|
|
|
2021-11-12 08:15:58 +08:00
|
|
|
#define INSERT_BINARY_ADDSUB_PATTERN(AtenOp, TosaOp) \
|
|
|
|
target.addIllegalOp<AtenOp>(); \
|
|
|
|
patterns.add<ConvertAtenAddSubOp<AtenOp, TosaOp>>(typeConverter, context);
|
|
|
|
INSERT_BINARY_ADDSUB_PATTERN(AtenAddTensorOp, tosa::AddOp)
|
2022-01-21 02:58:30 +08:00
|
|
|
INSERT_BINARY_ADDSUB_PATTERN(AtenAddScalarOp, tosa::AddOp)
|
2021-11-12 08:15:58 +08:00
|
|
|
INSERT_BINARY_ADDSUB_PATTERN(AtenSubTensorOp, tosa::SubOp)
|
2022-01-21 02:58:30 +08:00
|
|
|
INSERT_BINARY_ADDSUB_PATTERN(AtenSubScalarOp, tosa::SubOp)
|
2021-11-12 08:15:58 +08:00
|
|
|
#undef INSERT_BINARY_ADDSUB_PATTERN
|
|
|
|
|
2022-01-21 02:58:30 +08:00
|
|
|
#define INSERT_BINARY_COMPARE_PATTERN(AtenOp, TosaOp) \
|
|
|
|
target.addIllegalOp<AtenOp>(); \
|
|
|
|
patterns.add<ConvertAtenCompareOp<AtenOp, TosaOp>>(typeConverter, context);
|
|
|
|
INSERT_BINARY_COMPARE_PATTERN(AtenGtTensorOp, tosa::GreaterOp)
|
2023-06-11 02:45:35 +08:00
|
|
|
INSERT_BINARY_COMPARE_PATTERN(AtenGeScalarOp, tosa::GreaterEqualOp)
|
2024-09-21 04:34:09 +08:00
|
|
|
INSERT_BINARY_COMPARE_PATTERN(AtenGeTensorOp, tosa::GreaterEqualOp)
|
2022-01-21 02:58:30 +08:00
|
|
|
INSERT_BINARY_COMPARE_PATTERN(AtenGtScalarOp, tosa::GreaterOp)
|
|
|
|
INSERT_BINARY_COMPARE_PATTERN(AtenLtTensorOp, tosa::GreaterOp)
|
|
|
|
INSERT_BINARY_COMPARE_PATTERN(AtenLtScalarOp, tosa::GreaterOp)
|
2024-09-21 05:33:55 +08:00
|
|
|
INSERT_BINARY_COMPARE_PATTERN(AtenLeTensorOp, tosa::GreaterEqualOp)
|
|
|
|
INSERT_BINARY_COMPARE_PATTERN(AtenLeScalarOp, tosa::GreaterEqualOp)
|
2022-01-21 02:58:30 +08:00
|
|
|
INSERT_BINARY_COMPARE_PATTERN(AtenEqTensorOp, tosa::EqualOp)
|
|
|
|
INSERT_BINARY_COMPARE_PATTERN(AtenEqScalarOp, tosa::EqualOp)
|
2022-02-12 04:30:02 +08:00
|
|
|
INSERT_BINARY_COMPARE_PATTERN(AtenNeTensorOp, tosa::EqualOp)
|
|
|
|
INSERT_BINARY_COMPARE_PATTERN(AtenNeScalarOp, tosa::EqualOp)
|
|
|
|
INSERT_BINARY_COMPARE_PATTERN(AtenBitwiseAndTensorOp, tosa::BitwiseAndOp)
|
2024-09-21 05:33:55 +08:00
|
|
|
INSERT_BINARY_COMPARE_PATTERN(AtenBitwiseAndScalarOp, tosa::BitwiseAndOp)
|
2023-01-12 06:40:03 +08:00
|
|
|
INSERT_BINARY_COMPARE_PATTERN(AtenBitwiseOrTensorOp, tosa::BitwiseOrOp)
|
|
|
|
INSERT_BINARY_COMPARE_PATTERN(AtenBitwiseXorTensorOp, tosa::BitwiseXorOp)
|
2022-01-21 02:58:30 +08:00
|
|
|
#undef INSERT_BINARY_COMPARE_PATTERN
|
|
|
|
|
|
|
|
#define INSERT_BINARY_MUL_PATTERN(AtenOp) \
|
|
|
|
target.addIllegalOp<AtenOp>(); \
|
|
|
|
patterns.add<ConvertAtenMulOp<AtenOp>>(typeConverter, context);
|
|
|
|
INSERT_BINARY_MUL_PATTERN(AtenMulTensorOp);
|
|
|
|
INSERT_BINARY_MUL_PATTERN(AtenMulScalarOp);
|
|
|
|
#undef INSERT_BINARY_MUL_PATTERN
|
|
|
|
|
|
|
|
#define INSERT_BINARY_DIV_PATTERN(AtenOp) \
|
|
|
|
target.addIllegalOp<AtenOp>(); \
|
|
|
|
patterns.add<ConvertAtenDivOp<AtenOp>>(typeConverter, context);
|
|
|
|
INSERT_BINARY_DIV_PATTERN(AtenDivTensorOp);
|
|
|
|
INSERT_BINARY_DIV_PATTERN(AtenDivScalarOp);
|
2024-09-21 04:34:09 +08:00
|
|
|
INSERT_BINARY_DIV_PATTERN(AtenDivTensorModeOp);
|
|
|
|
INSERT_BINARY_DIV_PATTERN(AtenDivScalarModeOp);
|
2022-01-21 02:58:30 +08:00
|
|
|
#undef INSERT_BINARY_DIV_PATTERN
|
|
|
|
|
2024-09-21 04:34:09 +08:00
|
|
|
#define INSERT_REMAINDER_FMOD_OP_PATTERN(AtenOp) \
|
|
|
|
target.addIllegalOp<AtenOp>(); \
|
|
|
|
patterns.add<ConvertAtenRemainderFmodOp<AtenOp>>(typeConverter, context);
|
|
|
|
INSERT_REMAINDER_FMOD_OP_PATTERN(AtenRemainderScalarOp);
|
|
|
|
INSERT_REMAINDER_FMOD_OP_PATTERN(AtenRemainderTensorOp);
|
|
|
|
INSERT_REMAINDER_FMOD_OP_PATTERN(AtenFmodScalarOp);
|
|
|
|
INSERT_REMAINDER_FMOD_OP_PATTERN(AtenFmodTensorOp);
|
|
|
|
#undef INSERT_REMAINDER_FMOD_OP_PATTERN
|
|
|
|
|
2021-12-03 08:52:01 +08:00
|
|
|
#define INSERT_NDIMS_REDUCTION_OP_PATTERN(AtenOp, ConversionFunc) \
|
|
|
|
target.addIllegalOp<AtenOp>(); \
|
|
|
|
patterns.add<ConvertAtenMultipleDimsReductionOp<AtenOp, ConversionFunc>>( \
|
|
|
|
typeConverter, context);
|
|
|
|
INSERT_NDIMS_REDUCTION_OP_PATTERN(AtenMeanDimOp,
|
|
|
|
mlir::tosa::convertReduceMeanOp)
|
|
|
|
INSERT_NDIMS_REDUCTION_OP_PATTERN(AtenSumDimIntListOp,
|
|
|
|
mlir::tosa::convertReduceSumOp)
|
2024-01-19 04:32:23 +08:00
|
|
|
INSERT_NDIMS_REDUCTION_OP_PATTERN(AtenLinalgVectorNormOp,
|
|
|
|
mlir::tosa::convertLinalgVectorNormOp)
|
2021-12-03 08:52:01 +08:00
|
|
|
#undef INSERT_NDIMS_REDUCTION_OP_PATTERN
|
|
|
|
|
|
|
|
#define INSERT_ONEDIM_REDUCTION_OP_PATTERN(AtenOp, ConversionFunc) \
|
|
|
|
target.addIllegalOp<AtenOp>(); \
|
|
|
|
patterns.add<ConvertAtenOneDimReductionOp<AtenOp, ConversionFunc>>( \
|
|
|
|
typeConverter, context);
|
|
|
|
INSERT_ONEDIM_REDUCTION_OP_PATTERN(AtenAnyDimOp,
|
|
|
|
mlir::tosa::convertReduceAnyOp)
|
2024-09-17 03:40:24 +08:00
|
|
|
INSERT_ONEDIM_REDUCTION_OP_PATTERN(AtenAllDimOp,
|
|
|
|
mlir::tosa::convertReduceAllOp)
|
|
|
|
INSERT_ONEDIM_REDUCTION_OP_PATTERN(AtenProdDimIntOp,
|
|
|
|
mlir::tosa::convertReduceProdOp)
|
2021-12-03 08:52:01 +08:00
|
|
|
#undef INSERT_ONEDIM_REDUCTION_OP_PATTERN
|
|
|
|
|
|
|
|
#define INSERT_ALLDIMS_REDUCTION_OP_PATTERN(AtenOp, ConversionFunc) \
|
|
|
|
target.addIllegalOp<AtenOp>(); \
|
|
|
|
patterns.add<ConvertAtenAllDimsReductionOp<AtenOp, ConversionFunc>>( \
|
|
|
|
typeConverter, context);
|
|
|
|
INSERT_ALLDIMS_REDUCTION_OP_PATTERN(AtenAllOp,
|
|
|
|
mlir::tosa::convertReduceAllOp)
|
|
|
|
INSERT_ALLDIMS_REDUCTION_OP_PATTERN(AtenAnyOp,
|
|
|
|
mlir::tosa::convertReduceAnyOp)
|
|
|
|
INSERT_ALLDIMS_REDUCTION_OP_PATTERN(AtenSumOp,
|
|
|
|
mlir::tosa::convertReduceSumOp)
|
2024-09-17 03:40:24 +08:00
|
|
|
INSERT_ALLDIMS_REDUCTION_OP_PATTERN(AtenMaxOp,
|
|
|
|
mlir::tosa::convertReduceMaxOp)
|
|
|
|
INSERT_ALLDIMS_REDUCTION_OP_PATTERN(AtenMinOp,
|
|
|
|
mlir::tosa::convertReduceMinOp)
|
|
|
|
INSERT_ALLDIMS_REDUCTION_OP_PATTERN(AtenProdOp,
|
|
|
|
mlir::tosa::convertReduceProdOp)
|
2021-12-03 08:52:01 +08:00
|
|
|
#undef INSERT_ALLDIMS_REDUCTION_OP_PATTERN
|
|
|
|
|
2024-09-17 03:40:24 +08:00
|
|
|
#define INSERT_INDICES_REDUCTION_OP_PATTERN(AtenOp, TosaOp) \
|
|
|
|
target.addIllegalOp<AtenOp>(); \
|
|
|
|
patterns.add<ConvertAtenMinMaxDimOp<AtenOp, TosaOp>>(typeConverter, context);
|
|
|
|
INSERT_INDICES_REDUCTION_OP_PATTERN(AtenMaxDimOp, tosa::ReduceMaxOp);
|
|
|
|
INSERT_INDICES_REDUCTION_OP_PATTERN(AtenMinDimOp, tosa::ReduceMinOp);
|
|
|
|
#undef INSERT_INDICES_REDUCTION_OP_PATTERN
|
|
|
|
|
2022-01-07 00:31:29 +08:00
|
|
|
#define INSERT_SQUEEZE_OP_PATTERN(AtenOp, TemplateForm) \
|
|
|
|
target.addIllegalOp<AtenOp>(); \
|
|
|
|
patterns.add<TemplateForm<AtenOp>>(typeConverter, context);
|
|
|
|
INSERT_SQUEEZE_OP_PATTERN(AtenSqueezeOp, ConvertAtenSqueezeAllDimsOp)
|
|
|
|
INSERT_SQUEEZE_OP_PATTERN(AtenSqueezeDimOp, ConvertAtenSqueezeOneDimOp)
|
|
|
|
#undef INSERT_SQUEEZE_OP_PATTERN
|
|
|
|
|
2022-01-19 05:37:32 +08:00
|
|
|
#define INSERT_MATMUL_ATENOP_PATTERN(AtenOp) \
|
|
|
|
target.addIllegalOp<AtenOp>(); \
|
|
|
|
patterns.add<ConvertAtenMatMulOp<AtenOp>>(typeConverter, context);
|
|
|
|
INSERT_MATMUL_ATENOP_PATTERN(AtenMatmulOp);
|
|
|
|
#undef INSERT_MATMUL_ATEMOP_PATTERN
|
|
|
|
|
2022-01-26 00:48:58 +08:00
|
|
|
#define INSERT_MM_ATENOP_PATTERN(AtenOp) \
|
|
|
|
target.addIllegalOp<AtenOp>(); \
|
|
|
|
patterns.add<ConvertAtenMmOp<AtenOp>>(typeConverter, context);
|
|
|
|
INSERT_MM_ATENOP_PATTERN(AtenMmOp);
|
|
|
|
INSERT_MM_ATENOP_PATTERN(AtenBmmOp);
|
|
|
|
#undef INSERT_MM_ATEMOP_PATTERN
|
|
|
|
|
|
|
|
#define INSERT_LINEAR_ATENOP_PATTERN(AtenOp) \
|
|
|
|
target.addIllegalOp<AtenOp>(); \
|
|
|
|
patterns.add<ConvertAtenLinearOp<AtenOp>>(typeConverter, context);
|
|
|
|
INSERT_LINEAR_ATENOP_PATTERN(AtenLinearOp);
|
|
|
|
#undef INSERT_LINEAR_ATEMOP_PATTERN
|
|
|
|
|
2022-02-01 05:34:09 +08:00
|
|
|
#define INSERT_ADAPTIVE_POOLING_ATENOP_PATTERN(AtenOp, TosaOpT) \
|
|
|
|
target.addIllegalOp<AtenOp>(); \
|
|
|
|
patterns.add<ConvertAtenAdaptivePoolingOp<AtenOp, TosaOpT>>(typeConverter, \
|
|
|
|
context);
|
|
|
|
INSERT_ADAPTIVE_POOLING_ATENOP_PATTERN(AtenAdaptiveAvgPool2dOp,
|
|
|
|
tosa::AvgPool2dOp);
|
|
|
|
#undef INSERT_ADAPTIVE_POOLING_ATEMOP_PATTERN
|
|
|
|
|
2022-07-01 04:13:52 +08:00
|
|
|
target.addIllegalOp<AtenMaxPool2dOp>();
|
|
|
|
patterns.add<ConvertAtenMaxPool2dOp>(typeConverter, context);
|
2022-05-19 20:35:59 +08:00
|
|
|
|
2022-07-01 04:13:52 +08:00
|
|
|
target.addIllegalOp<AtenAvgPool2dOp>();
|
|
|
|
patterns.add<ConvertAtenAvgPool2dOp>(typeConverter, context);
|
2022-05-19 20:35:59 +08:00
|
|
|
|
2022-02-17 01:53:51 +08:00
|
|
|
#define INSERT_CONSTANT_FILL_PATTERN(AtenOp, fillVal) \
|
|
|
|
target.addIllegalOp<AtenOp>(); \
|
|
|
|
patterns.add<ConvertAtenConstPatternOp<AtenOp, fillVal>>(typeConverter, \
|
|
|
|
context);
|
|
|
|
INSERT_CONSTANT_FILL_PATTERN(AtenOnesOp, 1);
|
|
|
|
INSERT_CONSTANT_FILL_PATTERN(AtenZerosOp, 0);
|
|
|
|
#undef INSERT_CONSTANT_FILL_PATTERN
|
|
|
|
|
|
|
|
#define INSERT_FILL_SCALAR_PATTERN(AtenOp) \
|
|
|
|
target.addIllegalOp<AtenOp>(); \
|
|
|
|
patterns.add<ConvertAtenFillScalarOp<AtenOp>>(typeConverter, context);
|
|
|
|
INSERT_FILL_SCALAR_PATTERN(AtenFill_ScalarOp);
|
|
|
|
#undef INSERT_FILL_SCALAR_PATTERN
|
|
|
|
|
2022-12-22 00:56:07 +08:00
|
|
|
#define INSERT_MASKED_FILL_PATTERN(AtenOp) \
|
|
|
|
target.addIllegalOp<AtenOp>(); \
|
|
|
|
patterns.add<ConvertAtenMaskedFillOp<AtenOp>>(typeConverter, context);
|
|
|
|
INSERT_MASKED_FILL_PATTERN(AtenMaskedFillScalarOp);
|
|
|
|
INSERT_MASKED_FILL_PATTERN(AtenMaskedFillTensorOp);
|
|
|
|
#undef INSERT_MASKED_FILL_PATTERN
|
|
|
|
|
2024-09-21 05:33:55 +08:00
|
|
|
#define INSERT_POW_OP_PATTERN(AtenOp) \
|
|
|
|
target.addIllegalOp<AtenOp>(); \
|
|
|
|
patterns.add<ConvertAtenPowOp<AtenOp>>(typeConverter, context);
|
|
|
|
INSERT_POW_OP_PATTERN(AtenPowTensorScalarOp);
|
|
|
|
INSERT_POW_OP_PATTERN(AtenPowTensorTensorOp);
|
|
|
|
INSERT_POW_OP_PATTERN(AtenPowScalarOp);
|
|
|
|
#undef INSERT_POW_OP_PATTERN
|
|
|
|
|
|
|
|
#define INSERT_ACTIVATION_FUNCTION_OP_PATTERN(AtenOp, TosaOp) \
|
|
|
|
target.addIllegalOp<AtenOp>(); \
|
|
|
|
patterns.add<ConvertAtenActivationFunctionOp<AtenOp, TosaOp>>(typeConverter, \
|
|
|
|
context);
|
|
|
|
INSERT_ACTIVATION_FUNCTION_OP_PATTERN(AtenTanhOp, tosa::TanhOp);
|
|
|
|
INSERT_ACTIVATION_FUNCTION_OP_PATTERN(AtenSigmoidOp, tosa::SigmoidOp);
|
|
|
|
INSERT_ACTIVATION_FUNCTION_OP_PATTERN(AtenErfOp, tosa::ErfOp);
|
|
|
|
#undef INSERT_ACTIVATION_FUNCITON_OP_PATTERN
|
|
|
|
|
2021-11-12 08:15:58 +08:00
|
|
|
#define INSERT_ATENOP_PATTERN(AtenOp) \
|
|
|
|
target.addIllegalOp<AtenOp>(); \
|
|
|
|
patterns.add<ConvertAtenOp<AtenOp>>(typeConverter, context);
|
2023-03-07 02:16:37 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenHardtanhBackwardOp);
|
2021-11-12 08:15:58 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenReluOp);
|
2023-01-11 13:42:07 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenLeakyReluOp);
|
2021-12-16 03:01:01 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenArgmaxOp);
|
2022-01-21 02:58:30 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenRsubScalarOp);
|
2022-04-08 12:47:57 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenConvolutionOp);
|
2022-01-27 11:16:13 +08:00
|
|
|
INSERT_ATENOP_PATTERN(ValueTensorLiteralOp);
|
2022-01-28 06:38:59 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenReshapeOp);
|
|
|
|
INSERT_ATENOP_PATTERN(AtenBatchNormOp);
|
2022-02-04 06:08:19 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenNativeLayerNormOp);
|
2022-01-29 13:38:56 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenFlattenUsingIntsOp);
|
2023-10-14 09:39:41 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenUnflattenIntOp);
|
2022-02-04 06:08:19 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenPermuteOp);
|
2022-02-12 04:30:02 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenLog2Op);
|
|
|
|
INSERT_ATENOP_PATTERN(AtenThresholdOp);
|
2022-03-26 05:15:07 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenUnsqueezeOp);
|
|
|
|
INSERT_ATENOP_PATTERN(AtenContiguousOp);
|
|
|
|
INSERT_ATENOP_PATTERN(AtenDropoutOp);
|
|
|
|
INSERT_ATENOP_PATTERN(AtenViewOp);
|
2022-03-31 08:00:55 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenGeluOp);
|
|
|
|
INSERT_ATENOP_PATTERN(AtenGeluBackwardOp);
|
2022-07-01 04:13:52 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenEmbeddingOp);
|
2022-07-08 04:05:33 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenTransposeIntOp);
|
2022-07-14 01:10:18 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenSliceTensorOp);
|
2022-09-21 01:04:51 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenBroadcastToOp);
|
2022-12-22 03:04:07 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenGatherOp);
|
2024-05-08 22:44:57 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenIndexPutHackedTwinOp);
|
2023-08-15 19:36:08 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenIndexTensorHackedTwinOp);
|
2023-04-14 23:43:39 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenAbsOp);
|
2022-10-19 00:39:39 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenWhereSelfOp);
|
2022-11-19 05:32:13 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenClampOp);
|
2022-09-30 22:33:41 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenArangeStartStepOp);
|
2022-10-04 22:00:16 +08:00
|
|
|
INSERT_ATENOP_PATTERN(PrimNumToTensorScalarOp);
|
2022-10-28 23:06:11 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenCopyOp);
|
2022-10-04 21:05:59 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenToDtypeOp);
|
2023-03-15 23:42:15 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenConstantPadNdOp);
|
2023-05-10 23:25:58 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenCatOp);
|
2023-07-14 14:23:10 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenSqrtOp);
|
2023-10-17 00:44:53 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenIscloseOp);
|
2024-06-27 00:10:14 +08:00
|
|
|
INSERT_ATENOP_PATTERN(Aten__InterpolateSizeListScaleListOp);
|
2024-09-06 02:27:29 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenTrilOp);
|
2024-09-30 23:24:31 +08:00
|
|
|
INSERT_ATENOP_PATTERN(AtenDiagonalOp);
|
2021-11-12 08:15:58 +08:00
|
|
|
#undef INSERT_ATENOP_PATTERN
|
2021-10-08 10:07:03 +08:00
|
|
|
|
2022-09-21 06:07:46 +08:00
|
|
|
#define INSERT_CLONE_ATENOP_PATTERN(AtenOp) \
|
|
|
|
target.addIllegalOp<AtenOp>(); \
|
|
|
|
patterns.add<ConvertAtenCloneOp<AtenOp>>(typeConverter, context);
|
|
|
|
INSERT_CLONE_ATENOP_PATTERN(AtenCloneOp);
|
|
|
|
#undef INSERT_CLONE_ATENOP_PATTERN
|
|
|
|
|
2021-10-08 10:07:03 +08:00
|
|
|
if (failed(applyPartialConversion(getOperation(), target,
|
|
|
|
std::move(patterns))))
|
|
|
|
return signalPassFailure();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
} // namespace
|
|
|
|
|
2022-04-27 03:27:51 +08:00
|
|
|
std::unique_ptr<OperationPass<func::FuncOp>>
|
2021-10-08 10:07:03 +08:00
|
|
|
mlir::torch::createConvertTorchToTosaPass() {
|
|
|
|
return std::make_unique<ConvertTorchToTosa>();
|
|
|
|
}
|