Skip to content

[Encoding] Add interfaces for encoding propagation - #20567

Merged
pashu123 merged 10 commits into
iree-org:mainfrom
pashu123:encodinginter
Apr 30, 2025
Merged

pashu123 merged 10 commits into
iree-org:mainfrom
pashu123:encodinginter

Conversation

@pashu123

@pashu123 pashu123 commented Apr 17, 2025 •

Copy link
Copy Markdown
Contributor

Adds attribute and op interface for encoding propagation. The attribute interface generates new encoding attributes for the operand and result of the operation whereas the op interface is responsible for propagation of the encoding i.e., create new set_encoding ops and update operations.
Design doc by @hanhanW https://hackmd.io/@hwPnnvLBTB-JGVMeh-bCEA/SkKbbnXiJl
This commit moves from rewrite pattern to interfaces, and the tests here https://github.com/iree-org/iree/blob/main/compiler/src/iree/compiler/DispatchCreation/test/propagate_encodings.mlir are verified.

@pashu123
pashu123 force-pushed the encodinginter branch 4 times, most recently from 54b2b40 to 1f68d8c Compare April 17, 2025 04:09
@hanhanW
hanhanW requested review from Max191 and removed request for IanWood1, benvanik and bjacob April 17, 2025 04:48

@hanhanW hanhanW left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks, Prashant. Please add the reason about no new tests to the PR description. I think it is NFC in terms of the propagation pass. (I don't mark it NFC because we are doing something not trivial in the PR.)

if (auto collapseOp = target.getDefiningOp<tensor::CollapseShapeOp>()) {
ArrayRef<int32_t> kDims = encoding.getKDims().asArrayRef();

// Bail out if it is not propagable.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I think this comment is copied from the other file, and we should delete it. Given that the function name is isPropagable, it is very clear that "return false" means it is not propagable.

The reason of having the comment in the other file is that it's matchAndRewrite function.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

IMO, we can delete the assertion from new interfaces because it is very safe to always return false/failure by default.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I think it's for early exit during compile time.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

RE assertion: I don't see how it relates to early exit during compile time. Generally, assertion is a sanity check for buggy code. And we don't see the assertion in release build, because they are dropped by compiler.

@pashu123
pashu123 force-pushed the encodinginter branch 4 times, most recently from e4a8690 to f2c99a3 Compare April 27, 2025 08:03
@pashu123
pashu123 requested a review from hanhanW April 27, 2025 08:03
@pashu123
pashu123 force-pushed the encodinginter branch 2 times, most recently from 678cebb to 0aef3bf Compare April 28, 2025 21:21

@hanhanW hanhanW left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Please try to avoid force pushing. I can't view the diff between the last review and the current code. There are some comments got addressed in the first commit during the force pushing. And there are few comments not yet addressed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

RE assertion: I don't see how it relates to early exit during compile time. Generally, assertion is a sanity check for buggy code. And we don't see the assertion in release build, because they are dropped by compiler.

// clang-format off: must be included after all LLVM/MLIR headers
#include "iree/compiler/Dialect/Encoding/IR/EncodingDialect.h.inc" // IWYU pragma: keep
// clang-format on

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is not addressed, and I can't bump on the original comment because of the force pushing.

#20567 (comment)

(This is another data point to try avoiding force pushing during review.)

Comment on lines +279 to +303
let methods = [InterfaceMethod<
/*desc=*/[{
Returns true if the encodings can be propagated across the operation.
}],
/*retTy=*/"bool",
/*methodName=*/"isPropagable",
/*args=*/(ins "::mlir::Value":$target),
/*methodBody=*/"",
/*defaultImplementation=*/[{
return false;
}]>,
InterfaceMethod<
/*desc=*/[{
Returns the new encodings for operand and result types
for the given operation.
}],
/*retTy=*/
"llvm::FailureOr<::mlir::iree_compiler::IREE::Encoding::"
"PropagationEncoding>",
/*methodName=*/"generateEncodings",
/*args=*/(ins "::mlir::Value":$target),
/*methodBody=*/"",
/*defaultImplementation=*/[{
return failure();
}]>];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can you format it like the style we have in the file? E.g.,

  let methods = [
    InterfaceMethod<
      [{
        Returns the tensor type with the encoding.
      }],
      /*retTy=*/"::mlir::Type",
      /*methodName=*/"getEncodingType",
      /*args=*/(ins)
    >,
    InterfaceMethod<
      [{
        Returns the same type but with the updated encoding.
      }],
      /*retTy=*/"::mlir::Type",
      /*methodName=*/"updateEncoding",
      /*args=*/(ins
        "::mlir::Attribute":$encoding)
    >,

(This is another data point. I think I did not see this kind of formatting in the previous review.)

Comment on lines +20 to +40
struct PropagationEncoding {
SmallVector<Attribute> operandEncodings;
SmallVector<Attribute> resultEncodings;
};

struct PropagationResult {
// A list of operations that are created by the propagation. They are returned
// to the caller for further transformation.
SmallVector<Operation *> encodedOps;

// A list of new set_encoding/unset_encoding ops that are generated by
// the propagation.
SmallVector<Operation *> generatedEncodingOps;

// The new corresponding result that is created by the propagation. It is
// returned to the caller for further transformation or replacement.
Value replacement;
}; //

} // namespace mlir::iree_compiler::IREE::Encoding

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

To avoid this chunk being larger in the future, can we use forward declaration? Also, please add a comment about why we need to declare it before the includes. I think it is because we use the structs in interface methods.

E.g., we declare the struct here, but describe details after includes.

namespace mlir::iree_compiler::IREE::Encoding {
struct PropagationEncoding;
struct PropagationResult;
}

...

namespace mlir::iree_compiler::IREE::Encoding {
static constexpr char kEncodingResolverAttrName[] = "iree.encoding.resolver";

struct PropagationEncoding {
  SmallVector<Attribute> operandEncodings;
  SmallVector<Attribute> resultEncodings;
};

struct PropagationResult {
  // A list of operations that are created by the propagation. They are returned
  // to the caller for further transformation.
  SmallVector<Operation *> encodedOps;

  // A list of new set_encoding/unset_encoding ops that are generated by
  // the propagation.
  SmallVector<Operation *> generatedEncodingOps;

  // The new corresponding result that is created by the propagation. It is
  // returned to the caller for further transformation or replacement.
  Value replacement;
};

...

(Please remove the double slash at the end of the PropagationResult struct.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

A forward declaration tells the compiler that a type exists, but not what it contains. You can't use it to declare variables or access members - only pointers or references are allowed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for giving it a try. I took a deeper look, and then I realized that it is not possible in the CRTP (i.e., curiously recurring template pattern) setup. Because they always generate implementation in the .h.inc file. Initially, I thought that the implementation is located in .cpp.inc, so it should work. Apparently, I was wrong.

Getting back to my original concern, we want to avoid mixed actual code and includes. Looking at an example in IREE, we are able to have a clean way even we have c++ struct in the interfaces. The example returns ValueAccess, which is defined in UtilTypes.h, and the includes for generated files locate at the end of the file. This is what we are looking for.

However, we are not able to do the same thing in this PR. The root issue is that we have few methods are defined in the file and they need to know some details of Encoding attributes and operations. This is bad, and I've been wanting to do such refactoring for a while.

So the solution can be moving those methods to Encoding/Utils/Utils.[h|cpp] that depend on encoding dialect. Below are the functions that I found in my deeper look, and I think we can move them to Utils.[h|cpp]. This way we can avoid interleaving the code and includes, and we have a clearer line for EncodingTypes.

getSerializableEncodingAttrInterface
getEncodingAttr
hasPackedStorageAttr
getEncodingContractionDims
getPo2MatmulNarrowDim
isNarrowNResult

The getEncodingContractionDims is used by the EncodingAttr.cpp, which will introduce a circular dependency. To address the issue, it is valid to dup the code in the EncodingAttr.cpp because the snippet is very small.

We can go with the current implementation for this PR, but please promise me that you will have the follow-up for this. Otherwise, you should do the refactoring first, and then rebase this PR. Let me know what you think, thanks!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I'll do that in the follow-up PR.

Comment on lines +28 to +29
.Case<tensor::CollapseShapeOp>([&](auto op) {
auto collapseOp = cast<tensor::CollapseShapeOp>(op);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

You don't need the cast. We can use op directly.

Comment on lines +77 to +81
collapseOp.getOperation());

ArrayRef<int32_t> kDims = encoding.getKDims().asArrayRef();
llvm::SetVector<int32_t> kDimsSet(kDims.begin(), kDims.end());

// Bail out if it is not propagable.
// TODO: Relax the check to allow transforming innermost reduction dimensions.
// We need to revisit the matmul_k encoding semantic.
SmallVector<ReassociationIndices, 4> reassociationMaps =
collapseOp.getReassociationIndices();
for (int32_t k : kDims) {
if (reassociationMaps[k].size() != 1) {
return rewriter.notifyMatchFailure(
encodingOp,
"expected collaps_shape ops to not transform k dimensions");
}
if (!propagationResult) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

style nit: remove the blank line

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Please replace return failure()s with error messages as many as you can - we used to have the error messages, and now they are removed in the PR. It is also very convenient when you debug code and triage issues.

Comment on lines +64 to +68
auto resultEncodingAttr =
IREE::Encoding::MatmulKAttr::get(ctx, newKDims);

IREE::Encoding::PropagationEncoding propEncoding;
propEncoding.operandEncodings.push_back(resultEncodingAttr);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Shouldn't we just name it as operandEncodingAttr?

Comment on lines +93 to +94
.Case<tensor::CollapseShapeOp>([&](auto op) {
auto collapseShapeOp = cast<tensor::CollapseShapeOp>(op);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ditto, we don't need the cast.

FailureOr<IREE::Encoding::PropagationResult>
propagateEncoding(Operation *op, RewriterBase &builder,
IREE::Encoding::PropagationEncoding encodings,
OpResult opResult) const {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Same issue for the implementation. Please don't use blank lines when you don't have to. We don't put a blank line between every statement.

https://google.github.io/styleguide/cppguide.html#Vertical_Whitespace

This is more a principle than a rule: don't use blank lines when you don't have to. In particular, don't put more than one or two blank lines between functions, resist starting functions with a blank line, don't end functions with a blank line, and be sparing with your use of blank lines. A blank line within a block of code serves like a paragraph break in prose: visually separating two thoughts.

@hanhanW hanhanW left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM % few nits. I also have a question about replacement in the review comment, please take a look.

Comment on lines +323 to +324
Transforms the op with given encodings. If succeeded, it replaces
the uses of the op except the opResult.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

If succeeded, it replaces the uses of the op except the opResult.

Is this statement correct? I don't see the code that reflects it, can you point it out or update the description?

Comment on lines +331 to +332
"::mlir::iree_compiler::IREE::Encoding::"
"PropagationEncoding":$encodings,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This should be collapsed into a single line?

Comment on lines +296 to +297
Returns the new encodings for operand and result types
for the given operation.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

We don't have lint for td file, but I'd generally format this kind of description within 80 chars per line when possible. Maybe we can format it a bit in the first place.

Suggested change
Returns the new encodings for operand and result types
for the given operation.
Returns the new encodings for operand and result types for the given
operation.

Comment on lines +23 to +27
Operation *attachedToOperation = target.getDefiningOp();
if (!attachedToOperation) {
return false;
}
return TypeSwitch<Operation *, bool>(attachedToOperation)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I think we don't need the attachedToOperation and the check, because they are covered by this TypeSwitch default case. Can you give it a try?

Suggested change
Operation *attachedToOperation = target.getDefiningOp();
if (!attachedToOperation) {
return false;
}
return TypeSwitch<Operation *, bool>(attachedToOperation)
return TypeSwitch<Operation *, bool>(target.getDefiningOp())

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

It can be a nullptr.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This just crashes.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I see, thanks for giving a try. I just checked the documentation and realized that the implementation does not use dyn_cast_or_null, and it surprises me. Then please ignore this comment, sorry about that.

/// This class implements a switch-like dispatch statement for a value of 'T'
/// using dyn_cast functionality. Each `Case<T>` takes a callable to be invoked
/// if the root value isa<T>, the callable is invoked with the result of
/// dyn_cast<T>() as a parameter.
///
/// Example:
///  Operation *op = ...;
///  LogicalResult result = TypeSwitch<Operation *, LogicalResult>(op)
///    .Case<ConstantOp>([](ConstantOp op) { ... })
///    .Default([](Operation *op) { ... });
///
template <typename T, typename ResultT = void>
class TypeSwitch : public detail::TypeSwitchBase<TypeSwitch<T, ResultT>, T> {

Comment on lines +20 to +40
struct PropagationEncoding {
SmallVector<Attribute> operandEncodings;
SmallVector<Attribute> resultEncodings;
};

struct PropagationResult {
// A list of operations that are created by the propagation. They are returned
// to the caller for further transformation.
SmallVector<Operation *> encodedOps;

// A list of new set_encoding/unset_encoding ops that are generated by
// the propagation.
SmallVector<Operation *> generatedEncodingOps;

// The new corresponding result that is created by the propagation. It is
// returned to the caller for further transformation or replacement.
Value replacement;
}; //

} // namespace mlir::iree_compiler::IREE::Encoding

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for giving it a try. I took a deeper look, and then I realized that it is not possible in the CRTP (i.e., curiously recurring template pattern) setup. Because they always generate implementation in the .h.inc file. Initially, I thought that the implementation is located in .cpp.inc, so it should work. Apparently, I was wrong.

Getting back to my original concern, we want to avoid mixed actual code and includes. Looking at an example in IREE, we are able to have a clean way even we have c++ struct in the interfaces. The example returns ValueAccess, which is defined in UtilTypes.h, and the includes for generated files locate at the end of the file. This is what we are looking for.

However, we are not able to do the same thing in this PR. The root issue is that we have few methods are defined in the file and they need to know some details of Encoding attributes and operations. This is bad, and I've been wanting to do such refactoring for a while.

So the solution can be moving those methods to Encoding/Utils/Utils.[h|cpp] that depend on encoding dialect. Below are the functions that I found in my deeper look, and I think we can move them to Utils.[h|cpp]. This way we can avoid interleaving the code and includes, and we have a clearer line for EncodingTypes.

getSerializableEncodingAttrInterface
getEncodingAttr
hasPackedStorageAttr
getEncodingContractionDims
getPo2MatmulNarrowDim
isNarrowNResult

The getEncodingContractionDims is used by the EncodingAttr.cpp, which will introduce a circular dependency. To address the issue, it is valid to dup the code in the EncodingAttr.cpp because the snippet is very small.

We can go with the current implementation for this PR, but please promise me that you will have the follow-up for this. Otherwise, you should do the refactoring first, and then rebase this PR. Let me know what you think, thanks!

Adds attribute and op interface for encoding propagation. The attribute
interface generates new encoding attributes for the operand and result
of the operation whereas the op interface is responsible for propagation
of the encoding i.e., create new set_encoding ops and update operations.
@pashu123
pashu123 merged commit 127397e into iree-org:main Apr 30, 2025
KyleHerndon pushed a commit to KyleHerndon/iree that referenced this pull request May 7, 2025
Adds attribute and op interface for encoding propagation. The attribute
interface generates new encoding attributes for the operand and result
of the operation whereas the op interface is responsible for propagation
of the encoding i.e., create new set_encoding ops and update operations.
Design doc by @hanhanW
https://hackmd.io/@hwPnnvLBTB-JGVMeh-bCEA/SkKbbnXiJl
This commit moves from rewrite pattern to interfaces, and the tests here
https://github.com/iree-org/iree/blob/main/compiler/src/iree/compiler/DispatchCreation/test/propagate_encodings.mlir
are verified.
AWoloszyn pushed a commit that referenced this pull request Dec 1, 2025
Adds attribute and op interface for encoding propagation. The attribute
interface generates new encoding attributes for the operand and result
of the operation whereas the op interface is responsible for propagation
of the encoding i.e., create new set_encoding ops and update operations.
Design doc by @hanhanW
https://hackmd.io/@hwPnnvLBTB-JGVMeh-bCEA/SkKbbnXiJl
This commit moves from rewrite pattern to interfaces, and the tests here
https://github.com/iree-org/iree/blob/main/compiler/src/iree/compiler/DispatchCreation/test/propagate_encodings.mlir
are verified.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants