Skip to content

[mlir][mesh] Add endomorphism simplification for all-reduce #73150

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Dec 12, 2023
Merged
110 changes: 110 additions & 0 deletions mlir/include/mlir/Dialect/Mesh/Transforms/Simplifications.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
//===- Simplifications.h - Mesh Simplifications -----------------*- C++ -*-===//
//
// 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
//
//===----------------------------------------------------------------------===//

#ifndef MLIR_DIALECT_MESH_TRANSFORMS_SIMPLIFICATIONS_H
#define MLIR_DIALECT_MESH_TRANSFORMS_SIMPLIFICATIONS_H

#include "mlir/Dialect/Mesh/IR/MeshOps.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/Transforms/EndomorphismSimplification.h"
#include "llvm/Support/Casting.h"
#include <algorithm>
#include <iterator>
#include <memory>
#include <utility>

namespace mlir {
namespace mesh {

// If we have an algebraic op like "+" and a summing all-reduce,
// `all_reduce_sum(x) + all_reduce_sum(y)` will be transformed to
// `all_reduce_sum(x + y)`.
//
// Another example with `min`.
// `min(all_reduce_min(x), all_reduce_min(y))` will be transformed to
// `all_reduce_min(min(x, y))`.
//
// Works only with algebraic ops that have all their operands relevant
// to the all-reduce endomorphism.
// Will not work with some op `f(x, y, z)` where only `x` and `y` form
// the algebraic structure.
template <typename AlgebraicOp>
void populateAllReduceEndomorphismSimplificationPatterns(
RewritePatternSet &patterns, Partial reduction) {
auto getEndomorphismOpOperand = [](Operation *op) {
auto allReduceOp = llvm::cast<AllReduceOp>(op);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems all_gather could also benefit from this. I suggest we could mark it as a TODO here.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added a comment in populateSimplificationPatterns.

return &allReduceOp.getInputMutable();
};
auto getEndomorphismOpResult = [](Operation *op) {
auto allReduceOp = llvm::cast<AllReduceOp>(op);
return allReduceOp->getResult(0);
};
auto getAlgebraicOpOperands = [](Operation *op,
SmallVector<OpOperand *> &operands) {
auto algebraicOp = llvm::cast<AlgebraicOp>(op);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if AlgebraicOp is a destination style op? I think the logic should be different, but we can add a TODO here first.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you mean a scenario like this?
h is the endomorphism and a is the algebraic structure op.
Then

a(h(x), h(y), z) = h(a(x, y, z))

does not actually hold.

If that is the case you may be able to do homomorphism simplification where the target algebraic structure op b is different. And we have

a(h(x), h(y), z) = h(b(x, y, z))

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, what I meant is ops in linalg dialect which have the DestinationStyleOpInterface. For a linalg.matmul op

%matmul = linalg.matmul ins(%0, %1 : tensor<1x1xi8>, tensor<1x?xi8>) outs(%2 : tensor<1x?xi32>) -> tensor<1x?xi32>

Here the %2 operand is different from %0 and %1

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I expanded the documentation of the function.

std::transform(algebraicOp->getOpOperands().begin(),
algebraicOp->getOpOperands().end(),
std::back_inserter(operands),
[](OpOperand &operand) { return &operand; });
};
auto getAlgebraicOpResult = [](Operation *op) {
auto algebraicOp = llvm::cast<AlgebraicOp>(op);
return algebraicOp->getResult(0);
};
auto isEndomorphismOp = [reduction](Operation *op,
std::optional<Operation *> referenceOp) {
auto allReduceOp = llvm::dyn_cast<AllReduceOp>(op);
if (!allReduceOp ||
allReduceOp.getInput().getType().getElementType() !=
allReduceOp.getResult().getType().getElementType() ||
allReduceOp.getReduction() != reduction) {
return false;
}

// Dont't use simplify if the all-reduce is used other than by the
// algebraic op.
// TODO: maybe handle this by an additional pass that later reverses the
// simplification if there are other uses left other optimizations have
// been done.
if (!allReduceOp->hasOneUse()) {
return false;
}

if (!referenceOp) {
return true;
}

auto refAllReduceOp = llvm::dyn_cast<AllReduceOp>(referenceOp.value());
return refAllReduceOp->getAttrs() == allReduceOp->getAttrs() &&
allReduceOp.getInput().getType().getElementType() ==
refAllReduceOp.getInput().getType().getElementType();
};
auto isAlgebraicOp = [](Operation *op) {
return static_cast<bool>(llvm::dyn_cast<AlgebraicOp>(op));
};

using ConcreteEndomorphismSimplification = EndomorphismSimplification<
std::decay_t<decltype(getEndomorphismOpOperand)>,
std::decay_t<decltype(getEndomorphismOpResult)>,
std::decay_t<decltype(getAlgebraicOpOperands)>,
std::decay_t<decltype(getAlgebraicOpResult)>,
std::decay_t<decltype(isEndomorphismOp)>,
std::decay_t<decltype(isAlgebraicOp)>>;
patterns.add(std::make_unique<ConcreteEndomorphismSimplification>(
std::move(getEndomorphismOpOperand), std::move(getEndomorphismOpResult),
std::move(getAlgebraicOpOperands), std::move(getAlgebraicOpResult),
std::move(isEndomorphismOp), std::move(isAlgebraicOp),
AlgebraicOp::getOperationName(), 1, patterns.getContext()));
}

void populateSimplificationPatterns(RewritePatternSet &patterns);

} // namespace mesh
} // namespace mlir

#endif // MLIR_DIALECT_MESH_TRANSFORMS_SIMPLIFICATIONS_H
93 changes: 93 additions & 0 deletions mlir/include/mlir/Transforms/EndomorphismSimplification.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
//===- EndomorphismSimplification.h -----------------------------*- C++ -*-===//
//
// 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
//
//===----------------------------------------------------------------------===//

#ifndef MLIR_TRANSFORMS_SIMPLIFY_ENDOMORPHISM_H_
#define MLIR_TRANSFORMS_SIMPLIFY_ENDOMORPHISM_H_

#include "mlir/Transforms/HomomorphismSimplification.h"

namespace mlir {

namespace detail {
struct CreateAlgebraicOpForEndomorphismSimplification {
Operation *operator()(Operation *op, IRMapping &operandsRemapping,
PatternRewriter &rewriter) const {
return rewriter.clone(*op, operandsRemapping);
}
};
} // namespace detail

// If `f` is an endomorphism with respect to the algebraic structure induced by
// function `g`, transforms `g(f(x1), f(x2) ..., f(xn))` into
// `f(g(x1, x2, ..., xn))`.
// `g` is the algebraic operation and `f` is the endomorphism.
//
// Functors:
// ---------
// `GetEndomorphismOpOperandFn`: `(Operation*) -> OpOperand*`
// Returns the operand relevant to the endomorphism.
// There may be other operands that are not relevant.
//
// `GetEndomorphismOpResultFn`: `(Operation*) -> OpResult`
// Returns the result relevant to the endomorphism.
//
// `GetAlgebraicOpOperandsFn`: `(Operation*, SmallVector<OpOperand*>&) -> void`
// Populates into the vector the operands relevant to the endomorphism.
//
// `GetAlgebraicOpResultFn`: `(Operation*) -> OpResult`
// Return the result relevant to the endomorphism.
//
// `IsEndomorphismOpFn`: `(Operation*, std::optional<Operation*>) -> bool`
// Check if the operation is an endomorphism of the required type.
// Additionally if the optional is present checks if the operations are
// compatible endomorphisms.
//
// `IsAlgebraicOpFn`: `(Operation*) -> bool`
// Check if the operation is an operation of the algebraic structure.
template <typename GetEndomorphismOpOperandFn,
typename GetEndomorphismOpResultFn, typename GetAlgebraicOpOperandsFn,
typename GetAlgebraicOpResultFn, typename IsEndomorphismOpFn,
typename IsAlgebraicOpFn>
struct EndomorphismSimplification
: HomomorphismSimplification<
GetEndomorphismOpOperandFn, GetEndomorphismOpResultFn,
GetAlgebraicOpOperandsFn, GetAlgebraicOpResultFn,
GetAlgebraicOpResultFn, IsEndomorphismOpFn, IsAlgebraicOpFn,
detail::CreateAlgebraicOpForEndomorphismSimplification> {
template <typename GetEndomorphismOpOperandFnArg,
typename GetEndomorphismOpResultFnArg,
typename GetAlgebraicOpOperandsFnArg,
typename GetAlgebraicOpResultFnArg, typename IsEndomorphismOpFnArg,
typename IsAlgebraicOpFnArg, typename... RewritePatternArgs>
EndomorphismSimplification(
GetEndomorphismOpOperandFnArg &&getEndomorphismOpOperand,
GetEndomorphismOpResultFnArg &&getEndomorphismOpResult,
GetAlgebraicOpOperandsFnArg &&getAlgebraicOpOperands,
GetAlgebraicOpResultFnArg &&getAlgebraicOpResult,
IsEndomorphismOpFnArg &&isEndomorphismOp,
IsAlgebraicOpFnArg &&isAlgebraicOp, RewritePatternArgs &&...args)
: HomomorphismSimplification<
GetEndomorphismOpOperandFn, GetEndomorphismOpResultFn,
GetAlgebraicOpOperandsFn, GetAlgebraicOpResultFn,
GetAlgebraicOpResultFn, IsEndomorphismOpFn, IsAlgebraicOpFn,
detail::CreateAlgebraicOpForEndomorphismSimplification>(
std::forward<GetEndomorphismOpOperandFnArg>(
getEndomorphismOpOperand),
std::forward<GetEndomorphismOpResultFnArg>(getEndomorphismOpResult),
std::forward<GetAlgebraicOpOperandsFnArg>(getAlgebraicOpOperands),
std::forward<GetAlgebraicOpResultFnArg>(getAlgebraicOpResult),
std::forward<GetAlgebraicOpResultFnArg>(getAlgebraicOpResult),
std::forward<IsEndomorphismOpFnArg>(isEndomorphismOp),
std::forward<IsAlgebraicOpFnArg>(isAlgebraicOp),
detail::CreateAlgebraicOpForEndomorphismSimplification(),
std::forward<RewritePatternArgs>(args)...) {}
};

} // namespace mlir

#endif // MLIR_TRANSFORMS_SIMPLIFY_ENDOMORPHISM_H_
188 changes: 188 additions & 0 deletions mlir/include/mlir/Transforms/HomomorphismSimplification.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
//===- HomomorphismSimplification.h -----------------------------*- C++ -*-===//
//
// 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
//
//===----------------------------------------------------------------------===//

#ifndef MLIR_TRANSFORMS_SIMPLIFY_HOMOMORPHISM_H_
#define MLIR_TRANSFORMS_SIMPLIFY_HOMOMORPHISM_H_

#include "mlir/IR/IRMapping.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/IR/Value.h"
#include "mlir/Support/LLVM.h"
#include "mlir/Support/LogicalResult.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Casting.h"
#include <iterator>
#include <optional>
#include <type_traits>
#include <utility>

namespace mlir {

// If `h` is an homomorphism with respect to the source algebraic structure
// induced by function `s` and the target algebraic structure induced by
// function `t`, transforms `s(h(x1), h(x2) ..., h(xn))` into
// `h(t(x1, x2, ..., xn))`.
//
// Functors:
// ---------
// `GetHomomorphismOpOperandFn`: `(Operation*) -> OpOperand*`
// Returns the operand relevant to the homomorphism.
// There may be other operands that are not relevant.
//
// `GetHomomorphismOpResultFn`: `(Operation*) -> OpResult`
// Returns the result relevant to the homomorphism.
//
// `GetSourceAlgebraicOpOperandsFn`: `(Operation*, SmallVector<OpOperand*>&) ->
// void` Populates into the vector the operands relevant to the homomorphism.
//
// `GetSourceAlgebraicOpResultFn`: `(Operation*) -> OpResult`
// Return the result of the source algebraic operation relevant to the
// homomorphism.
//
// `GetTargetAlgebraicOpResultFn`: `(Operation*) -> OpResult`
// Return the result of the target algebraic operation relevant to the
// homomorphism.
//
// `IsHomomorphismOpFn`: `(Operation*, std::optional<Operation*>) -> bool`
// Check if the operation is an homomorphism of the required type.
// Additionally if the optional is present checks if the operations are
// compatible homomorphisms.
//
// `IsSourceAlgebraicOpFn`: `(Operation*) -> bool`
// Check if the operation is an operation of the algebraic structure.
//
// `CreateTargetAlgebraicOpFn`: `(Operation*, IRMapping& operandsRemapping,
// PatternRewriter &rewriter) -> Operation*`
template <typename GetHomomorphismOpOperandFn,
typename GetHomomorphismOpResultFn,
typename GetSourceAlgebraicOpOperandsFn,
typename GetSourceAlgebraicOpResultFn,
typename GetTargetAlgebraicOpResultFn, typename IsHomomorphismOpFn,
typename IsSourceAlgebraicOpFn, typename CreateTargetAlgebraicOpFn>
struct HomomorphismSimplification : public RewritePattern {
template <typename GetHomomorphismOpOperandFnArg,
typename GetHomomorphismOpResultFnArg,
typename GetSourceAlgebraicOpOperandsFnArg,
typename GetSourceAlgebraicOpResultFnArg,
typename GetTargetAlgebraicOpResultFnArg,
typename IsHomomorphismOpFnArg, typename IsSourceAlgebraicOpFnArg,
typename CreateTargetAlgebraicOpFnArg,
typename... RewritePatternArgs>
HomomorphismSimplification(
GetHomomorphismOpOperandFnArg &&getHomomorphismOpOperand,
GetHomomorphismOpResultFnArg &&getHomomorphismOpResult,
GetSourceAlgebraicOpOperandsFnArg &&getSourceAlgebraicOpOperands,
GetSourceAlgebraicOpResultFnArg &&getSourceAlgebraicOpResult,
GetTargetAlgebraicOpResultFnArg &&getTargetAlgebraicOpResult,
IsHomomorphismOpFnArg &&isHomomorphismOp,
IsSourceAlgebraicOpFnArg &&isSourceAlgebraicOp,
CreateTargetAlgebraicOpFnArg &&createTargetAlgebraicOpFn,
RewritePatternArgs &&...args)
: RewritePattern(std::forward<RewritePatternArgs>(args)...),
getHomomorphismOpOperand(std::forward<GetHomomorphismOpOperandFnArg>(
getHomomorphismOpOperand)),
getHomomorphismOpResult(std::forward<GetHomomorphismOpResultFnArg>(
getHomomorphismOpResult)),
getSourceAlgebraicOpOperands(
std::forward<GetSourceAlgebraicOpOperandsFnArg>(
getSourceAlgebraicOpOperands)),
getSourceAlgebraicOpResult(
std::forward<GetSourceAlgebraicOpResultFnArg>(
getSourceAlgebraicOpResult)),
getTargetAlgebraicOpResult(
std::forward<GetTargetAlgebraicOpResultFnArg>(
getTargetAlgebraicOpResult)),
isHomomorphismOp(std::forward<IsHomomorphismOpFnArg>(isHomomorphismOp)),
isSourceAlgebraicOp(
std::forward<IsSourceAlgebraicOpFnArg>(isSourceAlgebraicOp)),
createTargetAlgebraicOpFn(std::forward<CreateTargetAlgebraicOpFnArg>(
createTargetAlgebraicOpFn)) {}

LogicalResult matchAndRewrite(Operation *op,
PatternRewriter &rewriter) const override {
SmallVector<OpOperand *> algebraicOpOperands;
if (failed(matchOp(op, algebraicOpOperands))) {
return failure();
}
return rewriteOp(op, algebraicOpOperands, rewriter);
}

private:
LogicalResult
matchOp(Operation *sourceAlgebraicOp,
SmallVector<OpOperand *> &sourceAlgebraicOpOperands) const {
if (!isSourceAlgebraicOp(sourceAlgebraicOp)) {
return failure();
}
sourceAlgebraicOpOperands.clear();
getSourceAlgebraicOpOperands(sourceAlgebraicOp, sourceAlgebraicOpOperands);
if (sourceAlgebraicOpOperands.empty()) {
return failure();
}

Operation *firstHomomorphismOp =
sourceAlgebraicOpOperands.front()->get().getDefiningOp();
if (!firstHomomorphismOp ||
!isHomomorphismOp(firstHomomorphismOp, std::nullopt)) {
return failure();
}
OpResult firstHomomorphismOpResult =
getHomomorphismOpResult(firstHomomorphismOp);
if (firstHomomorphismOpResult != sourceAlgebraicOpOperands.front()->get()) {
return failure();
}

for (auto operand : sourceAlgebraicOpOperands) {
Operation *homomorphismOp = operand->get().getDefiningOp();
if (!homomorphismOp ||
!isHomomorphismOp(homomorphismOp, firstHomomorphismOp)) {
return failure();
}
}
return success();
}

LogicalResult
rewriteOp(Operation *sourceAlgebraicOp,
const SmallVector<OpOperand *> &sourceAlgebraicOpOperands,
PatternRewriter &rewriter) const {
IRMapping irMapping;
for (auto operand : sourceAlgebraicOpOperands) {
Operation *homomorphismOp = operand->get().getDefiningOp();
irMapping.map(operand->get(),
getHomomorphismOpOperand(homomorphismOp)->get());
}
Operation *targetAlgebraicOp =
createTargetAlgebraicOpFn(sourceAlgebraicOp, irMapping, rewriter);

irMapping.clear();
assert(!sourceAlgebraicOpOperands.empty());
Operation *firstHomomorphismOp =
sourceAlgebraicOpOperands[0]->get().getDefiningOp();
irMapping.map(getHomomorphismOpOperand(firstHomomorphismOp)->get(),
getTargetAlgebraicOpResult(targetAlgebraicOp));
Operation *newHomomorphismOp =
rewriter.clone(*firstHomomorphismOp, irMapping);
rewriter.replaceAllUsesWith(getSourceAlgebraicOpResult(sourceAlgebraicOp),
getHomomorphismOpResult(newHomomorphismOp));
return success();
}

GetHomomorphismOpOperandFn getHomomorphismOpOperand;
GetHomomorphismOpResultFn getHomomorphismOpResult;
GetSourceAlgebraicOpOperandsFn getSourceAlgebraicOpOperands;
GetSourceAlgebraicOpResultFn getSourceAlgebraicOpResult;
GetTargetAlgebraicOpResultFn getTargetAlgebraicOpResult;
IsHomomorphismOpFn isHomomorphismOp;
IsSourceAlgebraicOpFn isSourceAlgebraicOp;
CreateTargetAlgebraicOpFn createTargetAlgebraicOpFn;
};

} // namespace mlir

#endif // MLIR_TRANSFORMS_SIMPLIFY_HOMOMORPHISM_H_
Loading