Repository navigation
[Encoding] Add interfaces for encoding propagation - #20567
Conversation
54b2b40 to
1f68d8c
Compare
hanhanW
left a comment
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
IMO, we can delete the assertion from new interfaces because it is very safe to always return false/failure by default.
There was a problem hiding this comment.
I think it's for early exit during compile time.
There was a problem hiding this comment.
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.
e4a8690 to
f2c99a3
Compare
678cebb to
0aef3bf
Compare
hanhanW
left a comment
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 | ||
|
|
There was a problem hiding this comment.
This is not addressed, and I can't bump on the original comment because of the force pushing.
(This is another data point to try avoiding force pushing during review.)
| 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(); | ||
| }]>]; |
There was a problem hiding this comment.
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.)
| 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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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!
There was a problem hiding this comment.
I'll do that in the follow-up PR.
| .Case<tensor::CollapseShapeOp>([&](auto op) { | ||
| auto collapseOp = cast<tensor::CollapseShapeOp>(op); |
There was a problem hiding this comment.
You don't need the cast. We can use op directly.
| 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) { |
There was a problem hiding this comment.
style nit: remove the blank line
There was a problem hiding this comment.
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.
| auto resultEncodingAttr = | ||
| IREE::Encoding::MatmulKAttr::get(ctx, newKDims); | ||
|
|
||
| IREE::Encoding::PropagationEncoding propEncoding; | ||
| propEncoding.operandEncodings.push_back(resultEncodingAttr); |
There was a problem hiding this comment.
Shouldn't we just name it as operandEncodingAttr?
| .Case<tensor::CollapseShapeOp>([&](auto op) { | ||
| auto collapseShapeOp = cast<tensor::CollapseShapeOp>(op); |
There was a problem hiding this comment.
ditto, we don't need the cast.
| FailureOr<IREE::Encoding::PropagationResult> | ||
| propagateEncoding(Operation *op, RewriterBase &builder, | ||
| IREE::Encoding::PropagationEncoding encodings, | ||
| OpResult opResult) const { |
There was a problem hiding this comment.
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.
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
left a comment
There was a problem hiding this comment.
LGTM % few nits. I also have a question about replacement in the review comment, please take a look.
| Transforms the op with given encodings. If succeeded, it replaces | ||
| the uses of the op except the opResult. |
There was a problem hiding this comment.
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?
| "::mlir::iree_compiler::IREE::Encoding::" | ||
| "PropagationEncoding":$encodings, |
There was a problem hiding this comment.
This should be collapsed into a single line?
| Returns the new encodings for operand and result types | ||
| for the given operation. |
There was a problem hiding this comment.
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.
| 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. |
| Operation *attachedToOperation = target.getDefiningOp(); | ||
| if (!attachedToOperation) { | ||
| return false; | ||
| } | ||
| return TypeSwitch<Operation *, bool>(attachedToOperation) |
There was a problem hiding this comment.
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?
| Operation *attachedToOperation = target.getDefiningOp(); | |
| if (!attachedToOperation) { | |
| return false; | |
| } | |
| return TypeSwitch<Operation *, bool>(attachedToOperation) | |
| return TypeSwitch<Operation *, bool>(target.getDefiningOp()) |
There was a problem hiding this comment.
It can be a nullptr.
There was a problem hiding this comment.
This just crashes.
There was a problem hiding this comment.
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> {| 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 |
There was a problem hiding this comment.
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.
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.
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.
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.