Skip to content

Add transform dialect building blocks for dispatch region formation - #9985

Merged
matthias-springer merged 1 commit into
iree-org:mainfrom
matthias-springer:clone_into_dispatch_region
Aug 15, 2022
Merged

matthias-springer merged 1 commit into
iree-org:mainfrom
matthias-springer:clone_into_dispatch_region

Conversation

@matthias-springer

@matthias-springer matthias-springer commented Aug 2, 2022 •

Copy link
Copy Markdown
Contributor

This commit adds two new transform dialect ops:

  • WrapInDispatchRegionOp: Warp an arbitrary op in a new
    dispatch.region op.
  • PullPrecedingOpIntoDispatchRegionOp: Move a preceding op into an
    existing dispatch.region op.

These ops will be used to build heuristics for dispatch region
formation.

The implementation of both ops is purpusely inside of static functions,
such the rewrite logic could be called from C++ without using the
transform dialect, if necessary.

@MaheshRavishankar MaheshRavishankar left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Overall this is looking good! Have a few questions about details, and Ill do a more detailed review in a bit.

}

// Case 4: Query ShapeAwareOpInterface.
auto shapeAwareOp = dyn_cast<IREE::Util::ShapeAwareOpInterface>(op);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Maybe better to move this to case 3 cause this would mot require any new operations.

@matthias-springer matthias-springer Aug 4, 2022 •

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.

Do you mean moving this before Step 3? I just gave it a try and it doesn't break anything, but I think the current approach could be a bit more efficient.

The way the two new ops are used is as follows: Create a dispatch region with just one op with WrapInDispatchRegionOp. Then use MoveIntoDispatchRegionOp iteratively to pull in (clone) more and more ops into the region. The problem is what if we are trying to pull in an op that is also used in a tensor.dim that is used as resultDims operand for the dispatch.region op. In that case, the pulled-in op will not fold away outside of the region because it still has a use. And we have to rely on other patterns to canonicalize the tensor.dim ops.

Example:

%0 = "some_op"(%arg0) : tensor<?xf32>
%1 = tensor.dim %0, %c0
%r = dispatch.region -> (tensor<?xf32>{%1}) {...}

Now we are cloning %0 into the region. But the original %0 won't DCE away because of %1. (It will eventually DCE away after the tensor.dim is canonicalized to dim(arg0).) We can avoid this by walking up the tied OpResult-OpOperand chain as much as possible when calculating the dynamic dims.

DominanceInfo domInfo;

// Case 1: `target` dominates `regionOp`.
if (domInfo.properlyDominates(target, regionOp)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I am not sure I follow why the consumers of the target are moved into the dispatch region.

@matthias-springer matthias-springer Aug 4, 2022 •

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.

The consumers variable contains all consumers of target that are in the dispatch region. In "Case 1" no consumers are moved into the dispatch region. Only in "Case 2", a consumer (of the dispatch region, not of target) is moved into the dispatch region.

The semantics of the op is: Given an existing dispatch region, move the target op into the dispatch region. If the target in front of (dominating) the dispatch region, it is a producer (or nothing; in case there is no use of the target in the dispatch region). If the target is after (post-dominating) the dispatch region, it is a consumer (or nothing; in case the target does not use the result of a dispatch region). This op is currently asymmetric in a sense that:

  • "dominating but not a producer" --> IR will not be modified
  • "post-dominating but not a consumer" --> target will be moved in to the dispatch region,

(Note, Case 1 and Case 2 could be split into two separate ops, but it may be easier to use if the user does not have to think about whether the target is a producer or a consumer.)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

If this is required by transform dialect, then thats a separate approach. I am not sure building this iteratively this way works very well for a whole program with thousands of statements. The current implementation does this in two steps and makes a distinction between compute ops and clonable ops. Compute ops are not duplicated.

  1. So first make a pass through the graph in post-order (use before def). Find the compute ops that become the root operations and then pull in other compute ops that need to be fused with it. I'd expect the same logic to work well for flow.dispatch.region op formation. Once you pull something in, it will not even stay outside the graph which means it wont get replicated. Root op determination is simple
  • Start with the gemms/convolution, etc. as being the roots. If a gemm is to be fused with its consumer elementwise operation, treat the consumer as the root. (Always easier to pull things into a region from above than to pull things into the region from below).
  1. After you form a skeleton of what goes into dispatch region look at values used from outside within the region. For each of these values, walk the use-def chain in reverse recording all operations that can be cloned. Since there are multiple values, you effectively have a DAG of operations. Do a topological sort of them to find order in which they should be cloned and clone them into the region. Now the values used in region defined outside become the actual arguments for the dispatch.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Going to what is implemented here. Why "Case 2"? If it is post-dominating, but not a consumer, why is it moved into the dispatch?

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 dropped "case 2". I still think it's useful to have, but let's leave that for a separate commit to keep this change a bit smaller.

I added an attribute to the op to distinguish between "moving" and "cloning" semantics. Alternatively, I could also make this two separate ops.

At the moment, this op is limited to one target op at a time. I'd like to extend this to multiple targets (and the topological sorting) in a separate commit if that's OK.

@matthias-springer
matthias-springer force-pushed the clone_into_dispatch_region branch 2 times, most recently from f120369 to 70de46b Compare August 4, 2022 09:26
@matthias-springer

Copy link
Copy Markdown
Contributor Author

I expanded the docs a bit and added some examples. Also removed a bit of code duplication around WrapInDispatchRegionOp.

@matthias-springer
matthias-springer force-pushed the clone_into_dispatch_region branch from 70de46b to fa45bf3 Compare August 4, 2022 12:30
DominanceInfo domInfo;

// Case 1: `target` dominates `regionOp`.
if (domInfo.properlyDominates(target, regionOp)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

If this is required by transform dialect, then thats a separate approach. I am not sure building this iteratively this way works very well for a whole program with thousands of statements. The current implementation does this in two steps and makes a distinction between compute ops and clonable ops. Compute ops are not duplicated.

  1. So first make a pass through the graph in post-order (use before def). Find the compute ops that become the root operations and then pull in other compute ops that need to be fused with it. I'd expect the same logic to work well for flow.dispatch.region op formation. Once you pull something in, it will not even stay outside the graph which means it wont get replicated. Root op determination is simple
  • Start with the gemms/convolution, etc. as being the roots. If a gemm is to be fused with its consumer elementwise operation, treat the consumer as the root. (Always easier to pull things into a region from above than to pull things into the region from below).
  1. After you form a skeleton of what goes into dispatch region look at values used from outside within the region. For each of these values, walk the use-def chain in reverse recording all operations that can be cloned. Since there are multiple values, you effectively have a DAG of operations. Do a topological sort of them to find order in which they should be cloned and clone them into the region. Now the values used in region defined outside become the actual arguments for the dispatch.

DominanceInfo domInfo;

// Case 1: `target` dominates `regionOp`.
if (domInfo.properlyDominates(target, regionOp)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Going to what is implemented here. Why "Case 2"? If it is post-dominating, but not a consumer, why is it moved into the dispatch?

// not be modified and this function would fail.
if (domInfo.properlyDominates(target, regionOp)) {
SmallVector<OpOperand *> consumers;
for (OpOperand &use : target->getUses())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I dont think you need this. If you are cloning the operation, then you are necessarily duplicating it within all regions that use it. So target dominating the region is all that should be needed.

Another point to consider properlyDominates can be potentially expensive. Everytime you insert/modify an operation into a basic block, it invalidates the precomputed order that dominator information relies on. If you query dominance again, it will recompute the block order which requires traversal of the entire block. It is not unusual to have the entire program in the block. So this could be potentially O(n^2).

//
// Note: If there is no use of %r#0, the dispatch region can canonicalize to
// an op with only one result.
if (!domInfo.properlyDominates(regionOp, target)) return failure();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Do you really need dominator information here. You can just use the SSA producer-consumer relationship....
Also not convinced this is needed. It is better/easier to create the region with the consumer in this case...

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.

Dropped the DominatorInfo usage. It is not needed.

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 is still used in an assert for easier debbuging

@matthias-springer

Copy link
Copy Markdown
Contributor Author

I've been thinking about how to extend this to support cloning/moving multiple ops in one go. The current approach with the move flag does not work well, because I cannot specify for every single op if it should be cloned or moved. But the more I think about this, I think this is actually irrelevant. We can just always clone. If there are no longer uses outside of the dispatch region, the original op will fold away.

The only variation point that we still have is whether we want to append results to the dispatch region and replace all uses of the original op that appear after the dispatch region. (This only makes sense if all remaining uses of the original op appear after the dispatch region.)

// Gather all uses of `target`.
SmallVector<OpOperand *> usesInsideOfRegion, usesOutsideOfRegion;
bool hasUsesBeforeRegion = false;
for (OpOperand &use : target->getUses()) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I am still not clear why you are looking into uses of the target.... I know I said dont use dominator, but this is actually using the same methods that the dominator uses. Look at the implementation of isBeforeInBlock here . The recomputeOpOrder is what is the problem. So this still has the same issue.

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.

Note the isBeforeInBlock is only used in the assert. It's just there to catch incorrect usage API usage, which can result in dominance errors. These can be difficult to debug. Dominance errors may surface later (sometimes it's not clear which transform caused them) and sometimes they are accidentally fixed up by canonicalizers, CSE, etc. Meaning that the dominance error may not surface at all during our tests and when we run another model/benchmark it may suddenly generate incorrect IR.

@matthias-springer matthias-springer Aug 9, 2022 •

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'm checking the uses so that I know all places that must be updated after cloning. This should be cheap. Of course not as cheap as just moving.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Ok fair enough.

@MaheshRavishankar

Copy link
Copy Markdown
Collaborator

I've been thinking about how to extend this to support cloning/moving multiple ops in one go. The current approach with the move flag does not work well, because I cannot specify for every single op if it should be cloned or moved. But the more I think about this, I think this is actually irrelevant. We can just always clone. If there are no longer uses outside of the dispatch region, the original op will fold away.

The only variation point that we still have is whether we want to append results to the dispatch region and replace all uses of the original op that appear after the dispatch region. (This only makes sense if all remaining uses of the original op appear after the dispatch region.)

Yeah that is true, but you want to make sure that the operation that are actual compute are not unnecessarily duplicated. That just increases the compute in the model. So thats the difference between operations that you want to always clone (they are not really compute for the most part) and those that are compute.

@matthias-springer

Copy link
Copy Markdown
Contributor Author

Yeah that is true, but you want to make sure that the operation that are actual compute are not unnecessarily duplicated. That just increases the compute in the model. So thats the difference between operations that you want to always clone (they are not really compute for the most part) and those that are compute.

If the original compute has no other uses (outside of the compute region), it will fold away. (I even remove it explicitly.) This is identical to moving.

If there are additional uses outside of the compute region, it is not possible to just move the compute op into the dispatch region. I think the code in DispatchLinalgOnTensors.cpp would generate IR with a dominance error. So really the only thing you can do is "clone" or abort compilation. Assuming that the heuristic is well-designed, I would conclude that the heuristic actually wants us to duplicate the compute op in that case. (If not, there's a bug in the heuristic and it's garbage in garbage out.)

you want to make sure that the operation that are actual compute are not unnecessarily duplicated

Sounds like what we need is an assertion to guard against bugs in the heuristic. (Because right now we don't crash with a dominance error like DispatchLinalgOnTensors.cpp, but "silently" clone the compute op and continue compilation. But maybe that's what the designer of the heuristic wanted?)

The reason why I gave the op this "cloning" semantics is to make it a bit more general. Not just capturing the bare minimum semantics that I need to replicate the current heuristic, but also allowing us to experiment with different heuristics in the future. (And potentially upstreaming some of these ops.) Also trying to limit the number of "building blocks" that I'm adding. I.e., having one expressive transform that can handle both cloning and moving semantics instead of two separate ones.

@matthias-springer
matthias-springer force-pushed the clone_into_dispatch_region branch from d6a5842 to 0591a1e Compare August 9, 2022 09:49
@matthias-springer

Copy link
Copy Markdown
Contributor Author

I added an additional function movePrecedingOpIntoDispatchRegion that provides a strong guarantee that the target op will not be duplicated. This one can be used in DispatchLinalgOnTensors.cpp.

ClonePrecedingOpIntoDispatchRegionOp can still be used when experimenting with new heuristics with the transform dialect.

This commit adds two new transform dialect ops:
* WrapInDispatchRegionOp: Warp an arbitrary op in a new
  `dispatch.region` op.
* ClonePrecedingOpIntoDispatchRegionOp: Clone a preceding op into an
  existing `dispatch.region` op.

These ops will be used to build heuristics for dispatch region
formation.

The implementation of both ops is purpusely inside of static functions,
such the rewrite logic could be called from C++ without using the
transform dialect, if necessary.
@matthias-springer
matthias-springer force-pushed the clone_into_dispatch_region branch from 0591a1e to ef1f2df Compare August 9, 2022 12:20
@MaheshRavishankar

Copy link
Copy Markdown
Collaborator

Yeah that is true, but you want to make sure that the operation that are actual compute are not unnecessarily duplicated. That just increases the compute in the model. So thats the difference between operations that you want to always clone (they are not really compute for the most part) and those that are compute.

If the original compute has no other uses (outside of the compute region), it will fold away. (I even remove it explicitly.) This is identical to moving.

If there are additional uses outside of the compute region, it is not possible to just move the compute op into the dispatch region. I think the code in DispatchLinalgOnTensors.cpp would generate IR with a dominance error. So really the only thing you can do is "clone" or abort compilation. Assuming that the heuristic is well-designed, I would conclude that the heuristic actually wants us to duplicate the compute op in that case. (If not, there's a bug in the heuristic and it's garbage in garbage out.)

Do you have an example of where the current pass creates an SSA use-def error ? AFAIK, this pass works across all the models that are tested on IREE and I dont see any case where the SSA use-def error is thrown. This used to happen a lot, and the current iteration of DispatchLinalgOnTensors avoids all of it.

you want to make sure that the operation that are actual compute are not unnecessarily duplicated

Sounds like what we need is an assertion to guard against bugs in the heuristic. (Because right now we don't crash with a dominance error like DispatchLinalgOnTensors.cpp, but "silently" clone the compute op and continue compilation. But maybe that's what the designer of the heuristic wanted?)

The reason why I gave the op this "cloning" semantics is to make it a bit more general. Not just capturing the bare minimum semantics that I need to replicate the current heuristic, but also allowing us to experiment with different heuristics in the future. (And potentially upstreaming some of these ops.) Also trying to limit the number of "building blocks" that I'm adding. I.e., having one expressive transform that can handle both cloning and moving semantics instead of two separate ones.

Ok, I was working under the impression that you want to replicate the heuristics that current DispatchLinalgOnTensors does. I was trying to avoid adding hooks to existing pass to query current heuristics. There is a solution point here where you can use the current pass to create a flow.dispatch.region instead of a flow.dispatch.workgroups operation and then convert the former to the latter seemlessly. If that is not of interest to you, then we can decouple the two. The ops you want to add the the transform dialect to have different ways to experiment with dispatch region formation could be independent of the current pass. Instead of adding arbitrary hooks to the existing pass you can just replicate the logic in this approach. That might make it easier for you to land your changes....

@matthias-springer

Copy link
Copy Markdown
Contributor Author

Ok, I was working under the impression that you want to replicate the heuristics that current DispatchLinalgOnTensors does.

Yes that is one goal. But also other heuristics, to give us a more interesting playground.

I was trying to avoid adding hooks to existing pass to query current heuristics.

No hooks needed in the original heuristic. Everything is in a separate build unit. (FlowExtensions.cpp). But I think there is an opportunity to reuse some of this code to clean up/simplify the implementation in DispatchLinalgOnTensors.cpp. But not in this PR. That's a separate issue.

There is a solution point here where you can use the current pass to create a flow.dispatch.region instead of a flow.dispatch.workgroups operation and then convert the former to the latter seemlessly.

That's what's happening here. I am creating flow.dispatch.region ops. (These can then be converted to workgroups ops with the pass that I added a week ago.)

The ops you want to add the the transform dialect to have different ways to experiment with dispatch region formation could be independent of the current pass.

Yes let's do that for the moment. Let's go step by step and then we'll see...

@MaheshRavishankar MaheshRavishankar left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I am approving this CL under the understanding this is for experimental purposes (and want to unblock this long standing change). There are a few things here that I think dont generalize to the whole program, but the intent for these (at least for now) seem more targeted.
I did leave some comments based on having looked into these in detail for the current default heuristics. Those will need to be re-evaulated eventually, but I also believe these are not the final shape of these. Take these comments as suggestions if they help :) .

ShapedType shapedType = value.getType().cast<ShapedType>();

// Case 2: Value is a block argument.
if (auto bbArg = value.dyn_cast<BlockArgument>()) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I would just create a tensor.dim always and rely on post-processing to remove all the tensor.dim operations created. Typically resolving all the tensor.dim operations requires a fixed point iteration to resolve them completely in terms of shapes of operands of the function. Doing a single step here does not serve much purpose (from past experience).

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.

The problem with that approach is that the GreedyPatternRewriter hoists arith.constant ops that have been explicitly pulled into the region. "Step 3" (TiedOpInterface) is following the tied operands until the end. My hope is that this is as good as running a fixpoint iteration of tensor.dim canonicalizations.

static bool isAfterRegion(Operation *op, Flow::DispatchRegionOp regionOp) {
Operation *ancestor = regionOp->getBlock()->findAncestorOpInBlock(*op);
assert(ancestor && "expected that op and regionOp are in the same block");
return regionOp->isBeforeInBlock(ancestor);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This only works if both the regionOp and the op are in the same block. Thats not necessary in general. So if you really want to go down this path, then just use dominator information.
Going to add my warning that using dominator information while transforming the IR is a footgun. It is much better to use it to do "pre-processing" and then use transformation that assumes dominance based on pre-processing.

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.

Note, I'm using ancestor not op.

// Gather all uses of `target`.
SmallVector<OpOperand *> usesInsideOfRegion, usesOutsideOfRegion;
bool hasUsesBeforeRegion = false;
for (OpOperand &use : target->getUses()) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Ok fair enough.

}
}

// Clone op into dispatch region.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Just the sheer number of branching and if/else case handling done here is an indication to me that the ordering of things needs to be reconsidered.

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 this op will change/evolve as we experiment.

@matthias-springer

Copy link
Copy Markdown
Contributor Author

Thanks for the review!

@matthias-springer
matthias-springer merged commit bebb902 into iree-org:main Aug 15, 2022
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