Skip to content

Commit

Permalink
[Torch] support aten.column_stack (#3867)
Browse files Browse the repository at this point in the history
  • Loading branch information
yyp0 authored and qingyunqu committed Nov 18, 2024
1 parent 5d3bd54 commit 715b72c
Show file tree
Hide file tree
Showing 8 changed files with 257 additions and 0 deletions.
23 changes: 23 additions & 0 deletions include/torch-mlir/Dialect/Torch/IR/GeneratedTorchOps.td
Original file line number Diff line number Diff line change
Expand Up @@ -14460,6 +14460,29 @@ def Torch_AtenHstackOp : Torch_Op<"aten.hstack", [
}];
}

def Torch_AtenColumnStackOp : Torch_Op<"aten.column_stack", [
AllowsTypeRefinement,
HasValueSemantics,
ReadOnly
]> {
let summary = "Generated op for `aten::column_stack : (Tensor[]) -> (Tensor)`";
let arguments = (ins
AnyTorchListOfTensorType:$tensors
);
let results = (outs
AnyTorchOptionalTensorType:$result
);
let hasCustomAssemblyFormat = 1;
let extraClassDefinition = [{
ParseResult AtenColumnStackOp::parse(OpAsmParser &parser, OperationState &result) {
return parseDefaultTorchOp(parser, result, 1, 1);
}
void AtenColumnStackOp::print(OpAsmPrinter &printer) {
printDefaultTorchOp(printer, *this, 1, 1);
}
}];
}

def Torch_AtenAppendTOp : Torch_Op<"aten.append.t", [
AllowsTypeRefinement
]> {
Expand Down
58 changes: 58 additions & 0 deletions lib/Dialect/Torch/Transforms/AbstractInterpLibrary.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10633,6 +10633,37 @@ StringRef mlir::torch::Torch::getAbstractInterpLibrary() {
" }\n"
" return %5 : !torch.list<int>\n"
" }\n"
" func.func @\"__torch_mlir_shape_fn.aten.column_stack\"(%arg0: !torch.list<list<int>>) -> !torch.list<int> {\n"
" %true = torch.constant.bool true\n"
" %int0 = torch.constant.int 0\n"
" %int1 = torch.constant.int 1\n"
" %0 = torch.prim.ListConstruct : () -> !torch.list<list<int>>\n"
" %1 = torch.aten.len.t %arg0 : !torch.list<list<int>> -> !torch.int\n"
" torch.prim.Loop %1, %true, init() {\n"
" ^bb0(%arg1: !torch.int):\n"
" %3 = torch.aten.__getitem__.t %arg0, %arg1 : !torch.list<list<int>>, !torch.int -> !torch.list<int>\n"
" %4 = torch.aten.len.t %3 : !torch.list<int> -> !torch.int\n"
" %5 = torch.aten.eq.int %4, %int0 : !torch.int, !torch.int -> !torch.bool\n"
" %6 = torch.prim.If %5 -> (!torch.list<int>) {\n"
" %8 = torch.prim.ListConstruct %int1, %int1 : (!torch.int, !torch.int) -> !torch.list<int>\n"
" torch.prim.If.yield %8 : !torch.list<int>\n"
" } else {\n"
" %8 = torch.aten.len.t %3 : !torch.list<int> -> !torch.int\n"
" %9 = torch.aten.eq.int %8, %int1 : !torch.int, !torch.int -> !torch.bool\n"
" torch.prim.If %9 -> () {\n"
" %10 = torch.aten.append.t %3, %int1 : !torch.list<int>, !torch.int -> !torch.list<int>\n"
" torch.prim.If.yield\n"
" } else {\n"
" torch.prim.If.yield\n"
" }\n"
" torch.prim.If.yield %3 : !torch.list<int>\n"
" }\n"
" %7 = torch.aten.append.t %0, %6 : !torch.list<list<int>>, !torch.list<int> -> !torch.list<list<int>>\n"
" torch.prim.Loop.condition %true, iter()\n"
" } : (!torch.int, !torch.bool) -> ()\n"
" %2 = call @__torch__.torch.jit._shape_functions.cat(%0, %int1) : (!torch.list<list<int>>, !torch.int) -> !torch.list<int>\n"
" return %2 : !torch.list<int>\n"
" }\n"
" func.func @\"__torch_mlir_shape_fn.aten.fft_fft\"(%arg0: !torch.list<int>, %arg1: !torch.optional<int>, %arg2: !torch.int, %arg3: !torch.optional<str>) -> !torch.list<int> {\n"
" return %arg0 : !torch.list<int>\n"
" }\n"
Expand Down Expand Up @@ -15284,6 +15315,33 @@ StringRef mlir::torch::Torch::getAbstractInterpLibrary() {
" %5 = call @__torch__.torch_mlir.jit_ir_importer.build_tools.library_generator.promote_dtypes(%0, %1) : (!torch.list<optional<int>>, !torch.list<int>) -> !torch.int\n"
" return %5 : !torch.int\n"
" }\n"
" func.func @\"__torch_mlir_dtype_fn.aten.column_stack\"(%arg0: !torch.list<tuple<int, int>>) -> !torch.int {\n"
" %true = torch.constant.bool true\n"
" %none = torch.constant.none\n"
" %str = torch.constant.str \"AssertionError: \"\n"
" %int0 = torch.constant.int 0\n"
" %0 = torch.prim.ListConstruct : () -> !torch.list<optional<int>>\n"
" %1 = torch.prim.ListConstruct : () -> !torch.list<int>\n"
" %2 = torch.aten.len.t %arg0 : !torch.list<tuple<int, int>> -> !torch.int\n"
" %3 = torch.aten.ne.int %2, %int0 : !torch.int, !torch.int -> !torch.bool\n"
" torch.prim.If %3 -> () {\n"
" torch.prim.If.yield\n"
" } else {\n"
" torch.prim.RaiseException %str, %none : !torch.str, !torch.none\n"
" torch.prim.If.yield\n"
" }\n"
" %4 = torch.aten.len.t %arg0 : !torch.list<tuple<int, int>> -> !torch.int\n"
" torch.prim.Loop %4, %true, init() {\n"
" ^bb0(%arg1: !torch.int):\n"
" %6 = torch.aten.__getitem__.t %arg0, %arg1 : !torch.list<tuple<int, int>>, !torch.int -> !torch.tuple<int, int>\n"
" %7:2 = torch.prim.TupleUnpack %6 : !torch.tuple<int, int> -> !torch.int, !torch.int\n"
" %8 = torch.aten.append.t %0, %7#0 : !torch.list<optional<int>>, !torch.int -> !torch.list<optional<int>>\n"
" %9 = torch.aten.append.t %1, %7#1 : !torch.list<int>, !torch.int -> !torch.list<int>\n"
" torch.prim.Loop.condition %true, iter()\n"
" } : (!torch.int, !torch.bool) -> ()\n"
" %5 = call @__torch__.torch_mlir.jit_ir_importer.build_tools.library_generator.promote_dtypes(%0, %1) : (!torch.list<optional<int>>, !torch.list<int>) -> !torch.int\n"
" return %5 : !torch.int\n"
" }\n"
" func.func @\"__torch_mlir_dtype_fn.aten.einsum\"(%arg0: !torch.str, %arg1: !torch.list<tuple<int, int>>, %arg2: !torch.optional<list<int>>) -> !torch.int {\n"
" %true = torch.constant.bool true\n"
" %none = torch.constant.none\n"
Expand Down
63 changes: 63 additions & 0 deletions lib/Dialect/Torch/Transforms/DecomposeComplexOps.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3831,6 +3831,68 @@ class DecomposeAtenHstackOp : public OpRewritePattern<AtenHstackOp> {
};
} // namespace

// Decompose `aten.column_stack` into `aten.reshape` and `aten.cat`.
// https://github.com/pytorch/pytorch/blob/207564bab1c4fe42750931765734ee604032fb69/torch/_refs/__init__.py#L2822
namespace {
class DecomposeAtenColumnStackOp : public OpRewritePattern<AtenColumnStackOp> {
public:
using OpRewritePattern::OpRewritePattern;
LogicalResult matchAndRewrite(AtenColumnStackOp op,
PatternRewriter &rewriter) const override {
Location loc = op.getLoc();

SmallVector<Value> tensors;
if (!getListConstructElements(op.getTensors(), tensors))
return rewriter.notifyMatchFailure(
op, "unimplemented: the tensor list is not from list construct");

for (auto tensor : tensors) {
auto tTy = dyn_cast<BaseTensorType>(tensor.getType());
if (!tTy || !tTy.hasSizes())
return rewriter.notifyMatchFailure(
op, "unimplemented: one tensor does not have known sizes");
}

SmallVector<Value> tensors2d;
for (auto tensor : tensors) {
auto tTy = dyn_cast<BaseTensorType>(tensor.getType());
SmallVector<int64_t> tSizes(tTy.getSizes());
if (tSizes.size() <= 1) {
if (tSizes.size() == 0) {
tSizes.push_back(1);
}
tSizes.push_back(1);
auto newTy = tTy.getWithSizesAndDtype(tSizes, tTy.getDtype());
SmallVector<Value> newShapeList;
for (auto tSize : tSizes) {
newShapeList.push_back(rewriter.create<ConstantIntOp>(
loc, rewriter.getI64IntegerAttr(tSize)));
}
auto newShape = rewriter.create<PrimListConstructOp>(
loc, Torch::ListType::get(rewriter.getType<IntType>()),
newShapeList);
Value tensor2d =
rewriter.create<AtenReshapeOp>(loc, newTy, tensor, newShape);
tensors2d.push_back(tensor2d);
} else {
tensors2d.push_back(tensor);
}
}

auto elemType = cast<BaseTensorType>(tensors2d[0].getType())
.getWithSizesAndDtype(std::nullopt, nullptr);
Value newTensors = rewriter.create<PrimListConstructOp>(
loc, Torch::ListType::get(elemType), tensors2d);

rewriter.replaceOpWithNewOp<AtenCatOp>(
op, op.getType(), newTensors,
rewriter.create<ConstantIntOp>(loc, rewriter.getI64IntegerAttr(1)));

return success();
}
};
} // namespace

// Decompose aten.roll into aten.slice and aten.cat ops.
// https://pytorch.org/docs/stable/generated/torch.roll.html
namespace {
Expand Down Expand Up @@ -10077,6 +10139,7 @@ class DecomposeComplexOpsPass
DecomposeConstantTensorAllocLikeOp<AtenZerosLikeOp, 0>>(patterns);
addPatternIfTargetOpIsIllegal<DecomposeAtenStackOp>(patterns);
addPatternIfTargetOpIsIllegal<DecomposeAtenHstackOp>(patterns);
addPatternIfTargetOpIsIllegal<DecomposeAtenColumnStackOp>(patterns);
addPatternIfTargetOpIsIllegal<DecomposeAtenRollOp>(patterns);
addPatternIfTargetOpIsIllegal<DecomposeAtenRepeatOp>(patterns);
addPatternIfTargetOpIsIllegal<DecomposeAtenRepeatInterleaveSelfIntOp>(
Expand Down
1 change: 1 addition & 0 deletions lib/Dialect/Torch/Transforms/LowerToBackendContract.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,7 @@ static void markDecomposedOpsAsIllegal(MLIRContext *context,
target.addIllegalOp<AtenZerosLikeOp>();
target.addIllegalOp<AtenStackOp>();
target.addIllegalOp<AtenHstackOp>();
target.addIllegalOp<AtenColumnStackOp>();
target.addIllegalOp<AtenRollOp>();
target.addIllegalOp<AtenRepeatOp>();
target.addIllegalOp<AtenRepeatInterleaveSelfIntOp>();
Expand Down
3 changes: 3 additions & 0 deletions projects/pt1/e2e_testing/xfail_sets.py
Original file line number Diff line number Diff line change
Expand Up @@ -2494,6 +2494,9 @@
"CollapsePartialDynamicModule_basic",
"CollapseRank1DynamicModule_basic",
"CollapseStaticModule_basic",
"ColumnStackBasicIntModule_basic",
"ColumnStack1dModule_basic",
"ColumnStack0dModule_basic",
"ConstantBoolParameterModule_basic",
"ContainsIntList_False",
"ContainsIntList_True",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2175,6 +2175,20 @@ def aten〇hstack〡shape(tensors: List[List[int]]) -> List[int]:

return upstream_shape_functions.cat(tensors_atleast1d, dim=1)

@check_shape_function([
Invocation([LongTensorOfShape(2, 4, 3), LongTensorOfShape(2, 5, 3)]), # Basic case.
])
def aten〇column_stack〡shape(tensors: List[List[int]]) -> List[int]:
tensors2d: List[List[int]] = []
for tensor in tensors:
if len(tensor) == 0:
tensor = [1, 1]
elif len(tensor) == 1:
tensor.append(1)
tensors2d.append(tensor)

return upstream_shape_functions.cat(tensors2d, dim=1)

def aten〇fft_fft〡shape(self: List[int], n: Optional[int] = None, dim: int = -1, norm: Optional[str] = None) -> List[int]:
return self

Expand Down Expand Up @@ -5414,6 +5428,23 @@ def aten〇hstack〡dtype(tensors_rank_dtype: List[Tuple[int, int]]) -> int:

return promote_dtypes(ranks, dtypes)

@check_dtype_function(
[Invocation([NonZeroDTensorWithDtype(torch.bool), NonZeroDTensorWithDtype(torch.int32), NonZeroDTensorWithDtype(torch.int64)]),
Invocation([NonZeroDTensorWithDtype(torch.float32), NonZeroDTensorWithDtype(torch.int32)]),
Invocation([NonZeroDTensorWithDtype(torch.float16), NonZeroDTensorWithDtype(torch.float64)]),
Invocation([NonZeroDTensorWithDtype(torch.float32), NonZeroDTensorWithDtype(torch.int32),
NonZeroDTensorWithDtype(torch.complex64)])])
def aten〇column_stack〡dtype(tensors_rank_dtype: List[Tuple[int, int]]) -> int:
ranks: List[Optional[int]] = []
dtypes: List[int] = []
assert len(tensors_rank_dtype) != 0
for tensor_rank_dtype in tensors_rank_dtype:
tensor_rank, tensor_dtype = tensor_rank_dtype
ranks.append(tensor_rank)
dtypes.append(tensor_dtype)

return promote_dtypes(ranks, dtypes)

@check_dtype_function(
[Invocation("i,j->ij", [TensorOfShape(1, dtype=torch.float32),
TensorOfShape(1, dtype=torch.int32)]),])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1036,6 +1036,7 @@ def emit_with_mutating_variants(key, **kwargs):
)
emit("aten::stack : (Tensor[], int) -> (Tensor)")
emit("aten::hstack : (Tensor[]) -> (Tensor)")
emit("aten::column_stack : (Tensor[]) -> (Tensor)")
emit("aten::append.t : (t[], t) -> (t[])")
emit("aten::add.t : (t[], t[]) -> (t[])", has_canonicalizer=True)
emit("aten::eq.int_list : (int[], int[]) -> (bool)", has_folder=True)
Expand Down
77 changes: 77 additions & 0 deletions projects/pt1/python/torch_mlir_e2e_test/test_suite/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1409,6 +1409,83 @@ def HstackBasicComplexModule_basic(module, tu: TestUtils):
# ==============================================================================


class ColumnStackBasicIntModule(torch.nn.Module):
def __init__(self):
super().__init__()

@export
@annotate_args(
[
None,
([2, 3, 4], torch.bool, True),
([2, 3, 4], torch.int32, True),
([2, 3, 4], torch.int64, True),
]
)
def forward(self, x, y, z):
return torch.ops.aten.column_stack([x, y, z])


@register_test_case(module_factory=lambda: ColumnStackBasicIntModule())
def ColumnStackBasicIntModule_basic(module, tu: TestUtils):
module.forward(
tu.randint(2, 3, 4, low=0, high=2).bool(),
tu.randint(2, 3, 4, low=0, high=100).int(),
tu.randint(2, 3, 4, low=0, high=100).long(),
)


# ==============================================================================


class ColumnStack1dModule(torch.nn.Module):
def __init__(self):
super().__init__()

@export
@annotate_args(
[
None,
([4], torch.float32, True),
([4], torch.float32, True),
]
)
def forward(self, x, y):
return torch.ops.aten.column_stack([x, y])


@register_test_case(module_factory=lambda: ColumnStack1dModule())
def ColumnStack1dModule_basic(module, tu: TestUtils):
module.forward(tu.rand(4), tu.rand(4))


# ==============================================================================


class ColumnStack0dModule(torch.nn.Module):
def __init__(self):
super().__init__()

@export
@annotate_args(
[
None,
([], torch.float32, True),
([], torch.float32, True),
]
)
def forward(self, x, y):
return torch.ops.aten.column_stack([x, y])


@register_test_case(module_factory=lambda: ColumnStack0dModule())
def ColumnStack0dModule_basic(module, tu: TestUtils):
module.forward(torch.tensor(4.0), torch.tensor(1.0))


# ==============================================================================


class GatherModule(torch.nn.Module):
def __init__(self):
super().__init__()
Expand Down

0 comments on commit 715b72c

Please sign in to comment.