Skip to content

Making flow ops shape-aware to avoid the need for tie shapes. - #4881

Merged
benvanik merged 6 commits into
mainfrom
benvanik-flow
Mar 11, 2021
Merged

benvanik merged 6 commits into
mainfrom
benvanik-flow

Conversation

@benvanik

@benvanik benvanik commented Feb 18, 2021 •

Copy link
Copy Markdown
Collaborator

This adds a new ShapeCarryingOpInterface that can be used to perform the same kind of operations tie_shape was performing only without the need for the dedicated tie_shape op and IR traversal: a shape-aware op is one that contains all of the information required to materialize a ranked_shape on its own. This eliminates an entire class of issues with operation order ("#0 does not dominate op" etc) thus making transformations more stable. tie_shape now implements this interface and the code for building shapes only relies on that.

By implementing the interface on a bunch of flow ops it's now possible to elide almost all shape stuff in the IR after initial shape materialization. There will still be tie_shapes for example around custom ops that don't implement this interface, but after coming into the flow dialect they can fold away.

To enable this, the flow ops got a new syntax which inlines the shapes onto the types. I like it - it's clean and easy to read:

%5 = flow.dispatch @dynamic_tensor_ex_dispatch_0::@dynamic_tensor_ex_dispatch_0[%4](%1, %2, %0) :
       (index, index, tensor<?x?xf32>{%1, %2}) -> (tensor<?x?xf32>{%1, %2})

Operand and result dynamic dimensions are captured and associated with each operand/result. This was all motivated by buffer allocation: it's now possible to cleanly know which operands/results have matching shapes (symbolically, so even when dynamic) and perform some significant op restructuring without worrying about preserving shape metadata ops. This is a different kind of behavior to the initial shape materialization (upstream shape dialect and most of the IREE shape stuff) where you want to insert new IR to get/compute shapes - here the assumption is that it's already been done and the critical requirement is that it's possible to reason about shapes without modifying the IR to do so.

The primary flow ops of flow.dispatch.workgroups, flow.dispatch, and flow.ex.stream.fragment (which will be getting some major improvements soon) are all switched to this format as well as the flow.tensor.* streamable ops. flow.dispatch.region hasn't been updated as all the dispatch region formation/folding/etc is making a lot of disgusting assumptions about the op structure. Hopefully soon only the vmla path will be using that (hooray linalg-on-tensors).

flow.dispatch.region, flow.dispatch.workgroups, and flow.ex.stream.fragment all gained a new interface and the ClosureOpDce util was reworked to now function on all of them via the interface. This was required as the existing ClosureOpDce was brittle in the face of ops with more than one set of operands - it was never enabled on flow.dispatch.workgroups because of that and the changes to make flow.ex.stream.fragment shape-aware made it incompatible as well. Now any closure-shaped op (of which there will be more in the flow dialect soon) can run the closure optimizations.

@benvanik benvanik added the compiler/dialects Relating to the IREE compiler dialects (flow, hal, vm) label Feb 18, 2021
@google-cla google-cla Bot added the cla: yes label Feb 18, 2021
@benvanik
benvanik force-pushed the benvanik-flow branch 6 times, most recently from 820d5b1 to f526821 Compare March 2, 2021 22:54
@benvanik
benvanik requested a review from silvasean March 8, 2021 16:44
@benvanik
benvanik force-pushed the benvanik-flow branch 4 times, most recently from 088fea8 to 3ad7762 Compare March 8, 2021 18:55

@silvasean silvasean 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.

Love the direction and new syntax. Can you suggest a recommended review order to help me orient myself? (e.g. how I've done here: llvm/torch-mlir#177). That helps make these big multi-file patches easier to review.

Also, I see the PR is still "draft". Is that intentional?

@benvanik

benvanik commented Mar 9, 2021 •

Copy link
Copy Markdown
Collaborator Author

Also, I see the PR is still "draft". Is that intentional?

ah yeah this needs https://reviews.llvm.org/D97887 to land, but once it does there will be only a few lines of changes to support it (and a hopefully final passing test), so it's fine to review now!

The two major changes here are the addition of the ShapeCarryingOpInterface in commit Adding ShapeCarryingOpInterface to allow ops to carry shape values. and the extension of the flow ops to support it in commit Making flow ops shape-aware..

The former adds the interface, changes the TieShapeOp to implement it, and the shape lookup logic in iree/compiler/Dialect/Shape/IR/Builders.h/.cpp to use it. The changes are mostly mechanical (using the interface instead of TieShapeOp in a few places, etc).

The latter has 2 major parts:

  1. A new ClosureOpInterface (FlowInterfaces.td) and optimization routine optimizeClosureLikeOp (FlowOpUtils.h/cpp). This was needed because introducing the new shape-carrying behavior to the flow ops broke the old closure dce stuff and what that was doing was load-bearing to performance. The new interface here lets the same kind of DCE/CSE/etc behavior be applied to all of the flow ops that need it now that they all carry shapes (and in the follow up PR have tied results).

  2. A bunch of flow ops (FlowOps.td) got the new ShapeCarryingOpInterface added to them and new parsers/printers to support that (FlowOps.cpp).

Everything else is plumbing, lit test updates to the new op assembly formats, and in a few places capturing shapes when ops are created for the new ops that require them.

There are some things I'm still not happy with here in the .td but didn't want to contort myself in the same way HLO has as I find it makes things really unreadable - specifically around things like having the attributes that carry the shape dims added to each op that implements the interface. It'd be nice if I could have a mixin-style set of additional attributes like DeclareOpInterfaceAttributes alongside the mixin-style set of additional interface methods that DeclareOpInterfaceMethods provides. I'm fine with how it is now, though, and since some things need different behavior from the default it's almost better that there's just one way of doing things: the boilerplate is rather minimal in the grand scheme of things.

There's one or two syntax changes that were made here that then are fixed in #5016 - both of these PRs were designed together but splitting them up when they had so much overlap was difficult. I plan on landing both together. You may be interested in what it's doing too and I'd love your feedback there too :)

HTH!

@benvanik
benvanik marked this pull request as ready for review March 9, 2021 15:32
@silvasean

Copy link
Copy Markdown
Contributor

Thanks. That' suseful.

@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.

Looked through this a bit. I havent fully digested the implications of this. Part of the reason I was working on the Shape interface upstream was to also remove the thing of needing to keep the result around for just the shape. My thought there was with that interface and canonicalization we should be able to make sure we can propagate the shapes exactly exactly as needed. So trying to understand what this gives over and above what I had in mind above. Of course it doesnt block in any way, and I have no other issues I can think of right now.

// trees is hard and it'd be better to model that differently such as by having
// a wrapper region for immutable blobs that can be inlined that this then
// returns true for.
static bool shouldInlineIntoClosure(Value value) {

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.

Nice! I can add more things here (like linalg.init_tensor). Also does this subsume RematerializeConstants... Pass?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yep! That pass should go away - I'll see if I can do that now!

@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.

(clicked approve by mistake. Not that I have any changes to request either.)

@benvanik

benvanik commented Mar 10, 2021 •

Copy link
Copy Markdown
Collaborator Author

So trying to understand what this gives over and above what I had in mind above.

They compose - what you're doing is what is used to materialize the shapes and then once materialized this is what is used to carry them around the IR through transformations and lowering. This basically replaces shapex.tie_shape in most uses (non-interop) so anywhere you would have seen that (outside of dispatch regions, within/outside of streams, etc) now you won't. Where what you're writing fits in is just a placeholder in here right now and is last piece to complete this PR; the comments on #5041 have where I intend to use it.

The larger goal here is to only materialize shapes once - right now there's no way to reason about shapes without materializing them each time, which doesn't work for the kind of transformations required later on in our lowerings. Before this we were relying on the tie_shapes to persist and the IR to remain valid with them around and now we have no such requirements, which means the transformations are simpler and it's harder to produce invalid IR as you can write IR using dynamic shapes and not worry about whether you are coming into the pipeline before or after shape materialization.

@benvanik
benvanik force-pushed the benvanik-flow branch 2 times, most recently from 7595e4b to 87c1e2d Compare March 11, 2021 01:21
@benvanik

Copy link
Copy Markdown
Collaborator Author

Thanks both for the review! I applied all suggested changes (including a few from #5016).

@benvanik
benvanik force-pushed the benvanik-flow branch 2 times, most recently from 0e37936 to 893a9f1 Compare March 11, 2021 01:44
@benvanik

Copy link
Copy Markdown
Collaborator Author

Hrm a bunch of previously working tests are now crashing during compilation after I rebased, and I'm getting debug assertions deep inside LinalgBufferize when repro'ing. Seems related to mlir::iree_compiler::finalizeBufferAllocation. I'll try rebasing again. May be another midair collision between mahesh and my changes 💥

https://source.cloud.google.com/results/invocations/cfe4ee4d-1c46-47f8-af1d-dd753066df03/targets/iree%2Fgcp_ubuntu%2Fbazel%2Flinux%2Fx86-swiftshader%2Fcore%2Fpresubmit/log

Would be really, really nice to have an ASAN bot.
shapex.tie_shape now implements this interface and is no longer checked
for specifically. This allows any op to carry ranked shape-compatible
information. Its usage is kind of like ViewLikeOpInterface in that the
op stores the dynamic dimensions and can return them as needed via the
interface.
@benvanik

Copy link
Copy Markdown
Collaborator Author

@MaheshRavishankar is there anything about this that looks weird to you?

This triggers an assert in LinalgBufferizePass here, where v is not in the map (so lookup asserts):
https://github.com/google/iree/blob/0f455f26f5d473214ae91c6ce2c8f20a97df1fb5/iree/compiler/Conversion/Common/LinalgBufferizePass.cpp#L188

The input produced by LinalgVectorizePass:

func @scalar_ex_dispatch_0() {
  %c0 = constant 0 : index
  %0 = hal.interface.load.tensor @legacy_io::@arg0, offset = %c0 : tensor<f32>
  %1 = linalg.init_tensor [] : tensor<f32>
  %2 = linalg.generic {indexing_maps = [affine_map<() -> ()>, affine_map<() -> ()>], iterator_types = []} ins(%0 : tensor<f32>) outs(%1 : tensor<f32>) {
  ^bb0(%arg0: f32, %arg1: f32):  // no predecessors
    %3 = math.rsqrt %arg0 : f32
    linalg.yield %3 : f32
  } -> tensor<f32>
  hal.interface.store.tensor %2, @legacy_io::@ret0, offset = %c0 : tensor<f32>
  return
}

It seems fine, so I'm not sure why it's failing now - any tips of things I could look for?

@MaheshRavishankar

Copy link
Copy Markdown
Collaborator

@MaheshRavishankar is there anything about this that looks weird to you?

This triggers an assert in LinalgBufferizePass here, where v is not in the map (so lookup asserts):
https://github.com/google/iree/blob/0f455f26f5d473214ae91c6ce2c8f20a97df1fb5/iree/compiler/Conversion/Common/LinalgBufferizePass.cpp#L188

The input produced by LinalgVectorizePass:

func @scalar_ex_dispatch_0() {
  %c0 = constant 0 : index
  %0 = hal.interface.load.tensor @legacy_io::@arg0, offset = %c0 : tensor<f32>
  %1 = linalg.init_tensor [] : tensor<f32>
  %2 = linalg.generic {indexing_maps = [affine_map<() -> ()>, affine_map<() -> ()>], iterator_types = []} ins(%0 : tensor<f32>) outs(%1 : tensor<f32>) {
  ^bb0(%arg0: f32, %arg1: f32):  // no predecessors
    %3 = math.rsqrt %arg0 : f32
    linalg.yield %3 : f32
  } -> tensor<f32>
  hal.interface.store.tensor %2, @legacy_io::@ret0, offset = %c0 : tensor<f32>
  return
}

It seems fine, so I'm not sure why it's failing now - any tips of things I could look for?

Might just be a failing corner case. I will take a look later tonight.

@MaheshRavishankar

Copy link
Copy Markdown
Collaborator

@benvanik This is because the function has hal.interface.load.tensor. I think the new path expects flow.dispatch.input.load ops. So there is no "buffer" created for the input operand to the linalg.generic and it fails. I think this pass maybe had support for hal.interface.load.tensor but I removed it at some point and nothing broke. Is this something off upstream or is the new path expected to get hal.interface.load.tensor too. I can add support for that too if you need it.

@benvanik

Copy link
Copy Markdown
Collaborator Author

Ahh that's useful - I don't think the hal.interface.load.tensor is expected (at least, I don't expect it :). Maybe I messed up some pass that is now causing it to be introduced. I'll investigate that in the morning. Thanks for looking!

@benvanik

Copy link
Copy Markdown
Collaborator Author

That was it! Thanks so much for the tip - probably saved me a few hours :)
A case started slipping through the dispatch linalg on tensors pass, which then by the dragnet of the existing dispatch region formation was still carried down the old path enough to hit this error. Do you know if having the old path and the new path is required for anything, or could I put the old path in an else statement to the linalg on tensors path?

This removes most of the tie_shape uses outside of dispatch regions.
It required reworking ClosureOpDce so that the shape-aware ops can still
be optimized. Future changes will start edging us towards handling
shapes with this interface such that the ties are only required when
interoping with code that is not shape-aware.
The ClosureOpInterface canonicalizer does this now.
@MaheshRavishankar

Copy link
Copy Markdown
Collaborator

That was it! Thanks so much for the tip - probably saved me a few hours :)
A case started slipping through the dispatch linalg on tensors pass, which then by the dragnet of the existing dispatch region formation was still carried down the old path enough to hit this error. Do you know if having the old path and the new path is required for anything, or could I put the old path in an else statement to the linalg on tensors path?

No we dont need to use both at the same time. So you can put an else statement.

@benvanik

Copy link
Copy Markdown
Collaborator Author

No we dont need to use both at the same time. So you can put an else statement.

Cool - I'll do that as part of a followup. Will make it easier to spot these (and then eventually delete the entire else block :)

@benvanik
benvanik merged commit ffcd3fe into main Mar 11, 2021
@benvanik
benvanik deleted the benvanik-flow branch March 11, 2021 18:33
GMNGeoffrey added a commit to GMNGeoffrey/iree that referenced this pull request Mar 11, 2021
These come from midair collision between
iree-org#5063 and
iree-org#4881
GMNGeoffrey added a commit that referenced this pull request Mar 11, 2021
These come from midair collision between
#5063 and
#4881
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

compiler/dialects Relating to the IREE compiler dialects (flow, hal, vm)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants