2022-03-11 01:54:13 +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/TorchToLinalg/TorchToLinalg.h"
|
|
|
|
|
|
|
|
#include "PopulatePatterns.h"
|
2022-10-05 21:28:06 +08:00
|
|
|
#include "mlir/Dialect/Arith/IR/Arith.h"
|
2022-03-11 01:54:13 +08:00
|
|
|
#include "mlir/Dialect/Linalg/IR/Linalg.h"
|
|
|
|
#include "mlir/IR/Matchers.h"
|
2023-12-02 08:38:21 +08:00
|
|
|
#include "torch-mlir/Conversion/TorchToLinalg/Utils.h"
|
2022-03-11 01:54:13 +08:00
|
|
|
#include "torch-mlir/Conversion/Utils/Utils.h"
|
|
|
|
#include "torch-mlir/Dialect/Torch/IR/TorchOps.h"
|
|
|
|
#include "torch-mlir/Dialect/Torch/Utils/TorchUpstream.h"
|
|
|
|
#include "torch-mlir/Dialect/TorchConversion/IR/TorchConversionOps.h"
|
|
|
|
|
|
|
|
using namespace mlir;
|
|
|
|
using namespace mlir::torch;
|
|
|
|
using namespace mlir::torch::Torch;
|
|
|
|
|
|
|
|
namespace {
|
|
|
|
// TODO: Dropout should probably be handled in DecomposeComplexOps instead of
|
|
|
|
// here.
|
|
|
|
class ConvertAtenDropoutOp : public OpConversionPattern<AtenDropoutOp> {
|
|
|
|
public:
|
|
|
|
using OpConversionPattern::OpConversionPattern;
|
|
|
|
LogicalResult
|
|
|
|
matchAndRewrite(AtenDropoutOp op, OpAdaptor adaptor,
|
|
|
|
ConversionPatternRewriter &rewriter) const override {
|
|
|
|
if (failed(verifyLinalgCompatibleTypes(op, rewriter)))
|
|
|
|
return failure();
|
|
|
|
|
|
|
|
bool train;
|
2022-12-08 04:20:41 +08:00
|
|
|
if (!matchPattern(op.getTrain(), m_TorchConstantBool(&train)))
|
2022-03-11 01:54:13 +08:00
|
|
|
return rewriter.notifyMatchFailure(op,
|
|
|
|
"Expected train to be constant bool.");
|
|
|
|
|
|
|
|
if (train)
|
|
|
|
return failure();
|
2024-05-31 14:45:13 +08:00
|
|
|
auto resultType = cast<RankedTensorType>(
|
|
|
|
getTypeConverter()->convertType(op->getResult(0).getType()));
|
2022-03-11 01:54:13 +08:00
|
|
|
rewriter.replaceOpWithNewOp<tensor::CastOp>(op, resultType,
|
2022-12-08 04:20:41 +08:00
|
|
|
adaptor.getInput());
|
2022-03-11 01:54:13 +08:00
|
|
|
return success();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
} // namespace
|
|
|
|
|
2022-12-02 00:30:10 +08:00
|
|
|
static Value toLinearIndex(OpBuilder &b, Location loc,
|
|
|
|
ArrayRef<Value> indicesIntValues,
|
|
|
|
ArrayRef<Value> shapeIntValues) {
|
|
|
|
assert(indicesIntValues.size() == shapeIntValues.size() &&
|
|
|
|
"Expected `indices` and `shape` to have the same size");
|
|
|
|
Value result =
|
|
|
|
b.create<arith::ConstantOp>(loc, b.getZeroAttr(b.getI64Type()));
|
|
|
|
for (auto [index, stride] : llvm::zip(indicesIntValues, shapeIntValues)) {
|
2024-05-31 14:45:13 +08:00
|
|
|
assert(isa<mlir::IntegerType>(index.getType()) &&
|
|
|
|
isa<mlir::IntegerType>(stride.getType()) &&
|
2022-12-02 00:30:10 +08:00
|
|
|
"Input arrays to `toLinearIndex` must only contain values of type "
|
|
|
|
"`mlir::IntegerType`");
|
|
|
|
Value mul = b.create<arith::MulIOp>(loc, result, stride);
|
|
|
|
result = b.create<arith::AddIOp>(loc, mul, index);
|
|
|
|
}
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Squares64 Algorithm for generating 64-bit random numbers.
|
|
|
|
// See: https://arxiv.org/abs/2004.06278
|
|
|
|
static Value randomUniformUInt(OpBuilder &b, Location loc, Value ctr,
|
|
|
|
Value key) {
|
|
|
|
auto mul = [&](Value lhs, Value rhs) -> Value {
|
|
|
|
return b.create<arith::MulIOp>(loc, lhs, rhs);
|
|
|
|
};
|
|
|
|
auto add = [&](Value lhs, Value rhs) -> Value {
|
|
|
|
return b.create<arith::AddIOp>(loc, lhs, rhs);
|
|
|
|
};
|
|
|
|
Value cst32 = b.create<arith::ConstantOp>(loc, b.getI64IntegerAttr(32));
|
|
|
|
auto shiftRight32 = [&](Value val) -> Value {
|
|
|
|
return b.create<arith::ShRUIOp>(loc, val, cst32);
|
|
|
|
};
|
|
|
|
auto swapLoHi = [&](Value val) -> Value {
|
|
|
|
Value leftShift = b.create<arith::ShLIOp>(loc, val, cst32);
|
|
|
|
Value rightShift = shiftRight32(val);
|
|
|
|
return b.create<arith::OrIOp>(loc, leftShift, rightShift);
|
|
|
|
};
|
|
|
|
auto bitwiseXOr = [&](Value lhs, Value rhs) -> Value {
|
|
|
|
return b.create<arith::XOrIOp>(loc, lhs, rhs);
|
|
|
|
};
|
|
|
|
|
|
|
|
Value t, x, y, z;
|
|
|
|
x = mul(ctr, key);
|
|
|
|
y = x;
|
|
|
|
z = add(y, key);
|
|
|
|
x = add(mul(x, x), y);
|
|
|
|
x = swapLoHi(x);
|
|
|
|
x = add(mul(x, x), z);
|
|
|
|
x = swapLoHi(x);
|
|
|
|
x = add(mul(x, x), y);
|
|
|
|
x = swapLoHi(x);
|
|
|
|
t = x = add(mul(x, x), z);
|
|
|
|
x = swapLoHi(x);
|
|
|
|
return bitwiseXOr(t, shiftRight32(add(mul(x, x), y)));
|
|
|
|
}
|
2022-03-11 01:54:13 +08:00
|
|
|
|
|
|
|
namespace {
|
2022-10-28 23:06:11 +08:00
|
|
|
class ConvertAtenUniformOp : public OpConversionPattern<AtenUniformOp> {
|
2022-03-11 01:54:13 +08:00
|
|
|
public:
|
|
|
|
using OpConversionPattern::OpConversionPattern;
|
|
|
|
LogicalResult
|
2022-10-28 23:06:11 +08:00
|
|
|
matchAndRewrite(AtenUniformOp op, OpAdaptor adaptor,
|
2022-03-11 01:54:13 +08:00
|
|
|
ConversionPatternRewriter &rewriter) const override {
|
|
|
|
if (failed(verifyLinalgCompatibleTypes(op, rewriter)))
|
|
|
|
return failure();
|
|
|
|
Location loc = op.getLoc();
|
2022-12-08 04:20:41 +08:00
|
|
|
Value self = adaptor.getSelf();
|
|
|
|
Value from = adaptor.getFrom();
|
|
|
|
Value to = adaptor.getTo();
|
|
|
|
Value generator = adaptor.getGenerator();
|
2024-04-28 05:00:56 +08:00
|
|
|
RankedTensorType resultType = cast<RankedTensorType>(self.getType());
|
2022-03-11 01:54:13 +08:00
|
|
|
Type elemTy = resultType.getElementType();
|
2024-04-24 14:58:08 +08:00
|
|
|
Type f64Ty = rewriter.getF64Type();
|
2022-03-11 01:54:13 +08:00
|
|
|
|
2024-04-11 21:47:35 +08:00
|
|
|
if (!isa<mlir::FloatType>(elemTy))
|
2022-03-11 01:54:13 +08:00
|
|
|
return rewriter.notifyMatchFailure(op, "This op only support float type");
|
|
|
|
|
2024-05-31 14:45:13 +08:00
|
|
|
if (!isa<Torch::NoneType>(generator.getType()))
|
2022-03-11 01:54:13 +08:00
|
|
|
return rewriter.notifyMatchFailure(
|
2022-11-14 15:08:13 +08:00
|
|
|
op, "The generator has to be None because only global default "
|
2022-03-11 01:54:13 +08:00
|
|
|
"generator is supported");
|
2022-12-02 00:30:10 +08:00
|
|
|
// Get key, min and max used by `linalg.generic` compute payload.
|
|
|
|
Value key = rewriter.create<TorchConversion::GetNextSeedOp>(loc);
|
2024-04-24 14:58:08 +08:00
|
|
|
Value min = convertScalarToDtype(rewriter, loc, from, f64Ty);
|
|
|
|
Value max = convertScalarToDtype(rewriter, loc, to, f64Ty);
|
2022-03-11 01:54:13 +08:00
|
|
|
|
|
|
|
// Construct the `linalg.generic` op.
|
|
|
|
auto resultRank = resultType.getRank();
|
|
|
|
SmallVector<AffineMap, 1> indexingMaps(
|
|
|
|
1, rewriter.getMultiDimIdentityMap(resultRank));
|
2022-11-17 06:40:36 +08:00
|
|
|
SmallVector<utils::IteratorType> iteratorTypes(
|
|
|
|
resultRank, utils::IteratorType::parallel);
|
2022-03-11 01:54:13 +08:00
|
|
|
SmallVector<Value> sizes = getTensorSizes(rewriter, loc, self);
|
2022-12-02 00:30:10 +08:00
|
|
|
SmallVector<Value> sizesIntValues =
|
|
|
|
castIndexVectorToInt64Vector(rewriter, loc, sizes);
|
2022-03-11 01:54:13 +08:00
|
|
|
Value initTensor =
|
2022-10-18 12:22:53 +08:00
|
|
|
rewriter.create<tensor::EmptyOp>(loc, getAsOpFoldResult(sizes), elemTy);
|
2022-03-11 01:54:13 +08:00
|
|
|
Value uniformRes =
|
|
|
|
rewriter
|
|
|
|
.create<linalg::GenericOp>(
|
|
|
|
loc, initTensor.getType(), /*inputs=*/ValueRange{},
|
|
|
|
/*outputs=*/initTensor, indexingMaps, iteratorTypes,
|
|
|
|
[&](OpBuilder &b, Location loc, ValueRange args) {
|
2022-12-02 00:30:10 +08:00
|
|
|
SmallVector<Value> indicesIntValues;
|
2022-03-11 01:54:13 +08:00
|
|
|
for (int i = 0; i < resultRank; i++) {
|
2022-12-02 00:30:10 +08:00
|
|
|
indicesIntValues.push_back(castIndexToInt64(
|
|
|
|
b, loc, b.create<linalg::IndexOp>(loc, i)));
|
2022-03-11 01:54:13 +08:00
|
|
|
}
|
2022-12-02 00:30:10 +08:00
|
|
|
|
|
|
|
Value linearIndex =
|
|
|
|
toLinearIndex(b, loc, indicesIntValues, sizesIntValues);
|
|
|
|
Value randomVal = randomUniformUInt(b, loc, linearIndex, key);
|
|
|
|
|
2022-03-11 01:54:13 +08:00
|
|
|
// scale = (max - min) * const(F64, 5.4210108E-20)
|
|
|
|
// which is derived from rand(min,max) =
|
|
|
|
// rand()/(RAND_MAX/(max-min)) where RAND_MAX = 2^64 - 1
|
|
|
|
Value epsilon = b.create<arith::ConstantOp>(
|
|
|
|
loc, b.getFloatAttr(min.getType(), 5.4210108E-20));
|
|
|
|
Value range = b.create<arith::SubFOp>(loc, max, min);
|
|
|
|
Value scale = b.create<arith::MulFOp>(loc, range, epsilon);
|
|
|
|
|
|
|
|
// res = cast(F64, tempN) * scale + min
|
|
|
|
Value updateFloat =
|
2024-04-24 14:58:08 +08:00
|
|
|
b.create<arith::UIToFPOp>(loc, f64Ty, randomVal);
|
2022-03-11 01:54:13 +08:00
|
|
|
Value updateScaled =
|
|
|
|
b.create<arith::MulFOp>(loc, updateFloat, scale);
|
|
|
|
Value res = b.create<arith::AddFOp>(loc, updateScaled, min);
|
2024-04-24 14:58:08 +08:00
|
|
|
Value truncRes = res;
|
2024-05-31 14:45:13 +08:00
|
|
|
if (isa<Float16Type, Float32Type>(elemTy))
|
2024-04-24 14:58:08 +08:00
|
|
|
truncRes = b.create<arith::TruncFOp>(loc, elemTy, res);
|
|
|
|
b.create<linalg::YieldOp>(loc, truncRes);
|
2022-03-11 01:54:13 +08:00
|
|
|
})
|
|
|
|
.getResult(0);
|
|
|
|
|
|
|
|
Type newResultType = getTypeConverter()->convertType(op.getType());
|
|
|
|
rewriter.replaceOpWithNewOp<tensor::CastOp>(op, newResultType, uniformRes);
|
|
|
|
return success();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
} // namespace
|
|
|
|
|
|
|
|
void mlir::torch::torch_to_linalg::populateRandomPatternsAndLegality(
|
|
|
|
TypeConverter &typeConverter, RewritePatternSet &patterns,
|
|
|
|
ConversionTarget &target) {
|
|
|
|
MLIRContext *context = patterns.getContext();
|
|
|
|
target.addIllegalOp<AtenDropoutOp>();
|
|
|
|
patterns.add<ConvertAtenDropoutOp>(typeConverter, context);
|
2022-10-28 23:06:11 +08:00
|
|
|
target.addIllegalOp<AtenUniformOp>();
|
|
|
|
patterns.add<ConvertAtenUniformOp>(typeConverter, context);
|
2022-03-11 01:54:13 +08:00
|
|
|
}
|