Skip to content

Add a flow.dispatch.workgroups op #4140

Closed

Description

@benvanik

The current flow.dispatch.region is meant to model entire tensor -> tensor operations. This is useful for things that start this way like when forming regions from traditional tensor-based ops, but if trying to perform tiling and then forming dispatch regions it creates a layering issue where a dispatch tile body has to be shoehorned into a non-tiled region and then back out again during code generation.

Instead, a native flow.dispatch.workgroups that had the body region specified as per-tile and attached the related tiling information/functions (like one to calculate the workgroup count) would let us avoid going back in-to/out-of untiled form as well as help with #3737 by eliminating layer inversion that is causing the workgroup calculation generation to be done too-late. Instead, as the flow dialect is target-agnostic we could have the flow.dispatch.workgroups op completely parameterized on workgroup size values such that all targets could use the same calculation (possibly with modifications to the indexing/tile size/etc ops).

The current workload as used by the dispatch region ops could be removed as we would (possibly) not perform fusion of such ops and instead rely on whatever produced the tiled dispatch to have done that beforehand. There may still be utility in exposing a tile map to allow per-region dependencies (tile 0 in dispatch B only consumes outputs from tile 0 in prior dispatch A), but that's strictly an enhancement.

Sketch:

%ret0, %ret1 = flow.dispatch.workgroups(%arg0 : tensor<?xf32>, %arg1 : tensor<?xf32>, %runtime_param : index) -> (tensor<?xf32>, tensor<?xf32>)
  apply(%runtime_param : index) {
    %0 = flow.interface.workgroup.count // placeholder for total workgroup count xyz
    %1 = flow.interface.workgroup.id // placeholder for current workgroup ID xyz
    %4 = flow.interface.load.tile arg[0], offsets = [...], sizes = [...], strides = [...] : tensor<1x3xf32>
    %5 = flow.interface.load.tile arg[1], offsets = [...], sizes = [...], strides = [...] : tensor<3x1xf32>
    %7 = <some op working on the tile like linalg.matmul>
    flow.interface.store.tile %7, ret[0], offsets = [...], sizes = [...], strides = [...] : tensor<1x1xf32>
    flow.return
  },
  count(%shape0 : !shapex.ranked_shape<?>, %shape1 : !shapex.ranked_shape<?>) -> !shapex.ranked_shape<?> {
    // shape math --- arguments could also include data values for data-dependent shapes
    flow.return %computed_shape : !shapex.ranked_shape<?>
  }

The goals here are to make it easy to lower into the HAL, be completely parameterized such that it's agnostic to the target backend (which then may pick one or more tile sizes/iteration types/etc), and exposing flow-aware information that can be used for device placement and stream creation (like knowing the workgroup count computation, tile mapping across dispatches, etc), and have a place to put data-dependent size computations that we want to then emit additional executables to use to compute indirect dispatch parameters.

The primary difference with the HAL is that we don't yet have a fixed interface (that's computed/refined later per-target) and instead have fixed argument/results that are referenced to load/store the tiles. This is different than taking tile inputs/outputs intentionally so that each workgroup in our grid does not have operate on specific tiles and can instead load/store multiple tiles, have imperfectly nested loops, etc. In many cases a workgroup in the dispatch may be 1:1 with tiles loaded/stored, but that should just be treated as a lucky case where we may be able to emit less indexing math in the end.

So, the new ops are:

  • flow.dispatch.workgroups
  • flow.interface.workgroup.* (to match the hal.interface.workgroup.* ops being added now)
  • flow.interface.load/store.tile (that are a subset of hal.interface.load/store.tensor.tile, as here we only have tensors and don't have byte offsets yet)

A straightforward conversion could today take a flow.dispatch.region and turn it into a 1x1x1 flow.dispatch.workgroups by a simple conversion pattern. This may still be useful to support coming from frontends that may not be tiled or may be using custom ops that don't have tiling concepts - the region then is just shorthand for a single thing.

Activity

  1. added
    compiler/dialects
    on Dec 9, 2020
  2. added this to the milestone on Dec 9, 2020
  3. self-assigned this
    on Dec 9, 2020
  4. benvanik commented on Dec 9, 2020

    @benvanik
    CollaboratorAuthor

    I'm still fiddling with the IR but another idea is to have a new type:

    %ret0, %ret1 = flow.dispatch.workgroups(%arg0 : tensor<?xf32>, %arg1 : tensor<?xf32>, %runtime_param : index) -> (tensor<?xf32>, tensor<?xf32>)
      apply(%arg0 : !flow.interface.input<?xf32>,
            %arg1 : !flow.interface.input<?xf32>,
            %runtime_param : index,
            %ret0 : !flow.interface.output<?xf32>) {
        %shape0 = flow.interface.shape %arg0 : !flow.interface.input<?xf32> -> !shape.ranked_shape<?>
        %0 = flow.interface.workgroup.count // placeholder for total workgroup count xyz
        %1 = flow.interface.workgroup.id // placeholder for current workgroup ID xyz
        %4 = flow.interface.load.tile %arg0, offsets = [...], sizes = [...], strides = [...] : tensor<1x3xf32>
        %5 = flow.interface.load.tile %arg1, offsets = [...], sizes = [...], strides = [...] : tensor<3x1xf32>
        %7 = <some op working on the tile like linalg.matmul>
        flow.interface.store.tile %7, %ret0, offsets = [...], sizes = [...], strides = [...] : tensor<1x1xf32>
        flow.return
      }

    I think that would play a bit better in the MLIR system (get us nicer verifiers) and ensure we exclusively use the interface load/store ops and preventing the risk of making assumptions too early about byte layouts.

  5. benvanik commented on Dec 9, 2020

    @benvanik
    CollaboratorAuthor

    Thoughts for @nicolasvasilache: basically you'd at the flow level emit the tiled loads/stores, the flow.interface.load/store.tile could take the !shapex.ranked_shape as an argument (I think in the issue I just copy/pasted the offsets/sizes/strides but that should really be shape), and when lowered into the HAL set that shape information is available for use. There wouldn't be a use of hal.interface.load.tensor at all, so no need to thread through metadata into hal.interface.load.tensor.tile manually (the flow->hal tile load/store ops should be straightforward lowerings).

    There still may be cases where you want to do an entire tensor, though, such as gathers where the output may be tiled writes but the inputs are not tiled (you're gathering from the entire input tensor). You may also want to perform multiple tile loads/stores in the same workgroup, or as in reduction load multiple tiles to store a single tile, etc. This should give you that flexibility.

  6. nicolasvasilache commented on Dec 9, 2020

    @nicolasvasilache
    Contributor

    Generally LGTM, thanks!

    The remaining issue I have for correct execution (after locally taking liberties with pass ordering) is that the X.interface.load.tile op wants to bufferize into a subview and for this it needs a "shaped source buffer" (i.e. something from which to get the base ptr + offset + sizes + strides).

    Starting from your latest version:

    %ret0, %ret1 = flow.dispatch.workgroups(%arg0 : tensor<?xf32>, %arg1 : tensor<?xf32>, %runtime_param : index) -> (tensor<?xf32>, tensor<?xf32>)
      apply(%arg0 : !flow.interface.input<?xf32>, ... ) {
        %shape0 = flow.interface.shape %arg0 : !flow.interface.input<?xf32> -> !shape.ranked_shape<?>
       ...
        %4 = flow.interface.load.tile %arg0, offsets = [...], sizes = [...], strides = [...] : tensor<1x3xf32>
    

    It is still unclear to me here how:

    flow.interface.load.tile %arg0, offsets = [...], sizes = [...], strides = [...] : tensor<1x3xf32>
    

    gets me the maximally statically typed source buffer shape information from just %arg0.

    To make it more concrete, here is what I currently generate (manually adapted adapted to your current flow IR, I used a 2-D tile size 1x1 to simplify):

    flow.dispatch.workgroups(%arg0 : memref<?xf32>, %arg1 : memref<?xf32>, %arg2 : memref<?xf32>, %runtime_param : index)
      apply(%arg0 : !flow.interface.input<?xf32>,
            %arg1 : !flow.interface.input<?xf32>,
            %arg2 : !flow.interface.input<?xf32>,
            %runtime_param : index,
            %ret0 : !flow.interface.output<?xf32>) {
        %c2 = constant 2 : index
        %shape0 = flow.interface.shape %arg0 : !flow.interface.input<?xf32> -> !shape.ranked_shape<?>
        %0 = flow.interface.workgroup.count // placeholder for total workgroup count xyz
        %1 = flow.interface.workgroup.id // placeholder for current workgroup ID xyz
    
        %b0 = flow.gimme_the_most_static_shape_you_can_op %ret0 : memref<?x?xf32>
        %b1 = flow.gimme_the_most_static_shape_you_can_op %arg0 : memref<?x2xf32>
        %b2 = flow.gimme_the_most_static_shape_you_can_op %arg1 : memref<?x?xf32>
        %b3 = flow.gimme_the_most_static_shape_you_can_op %arg2 : memref<?x?xf32>
    
        %9 = alloca() : memref<1x1xf32>
        scf.for %arg0 = %1#0 to %TODO(%dim b0, 0) step %0#0 {
          scf.for %arg1 = %1#1 to %TODO(%dim b0, 1) step %0#1 {
            %6 = subview %b3[%arg0, 0] [1, 2] [1, 1] : memref<?x?xf32> to memref<1x2xf32, affine_map<(d0, d1)[s0, s1] -> (d0 * s1 + s0 + d1)>>
            %7 = subview %b2[0, %arg1] [2, 1] [1, 1] : memref<?x?xf32> to memref<2x1xf32, affine_map<(d0, d1)[s0, s1] -> (d0 * s1 + s0 + d1)>>
            %8 = subview %b1[%arg0, %arg1] [1, 1] [1, 1] : memref<?x?xf32> to memref<1x1xf32, affine_map<(d0, d1)[s0, s1] -> (d0 * s1 + s0 + d1)>>
            linalg.copy(%8, %9) : memref<1x1xf32, affine_map<(d0, d1)[s0, s1] -> (d0 * s1 + s0 + d1)>>, memref<1x1xf32>
            linalg.matmul ins(%6, %7 : memref<1x2xf32, affine_map<(d0, d1)[s0, s1] -> (d0 * s1 + s0 + d1)>>, memref<2x1xf32, affine_map<(d0, d1)[s0, s1] -> (d0 * s1 + s0 + d1)>>) outs(%9 : memref<1x1xf32>)
            %10 = subview %b0[%arg0, %arg1] [1, 1] [1, 1] : memref<2x2xf32> to memref<1x1xf32, affine_map<(d0, d1)[s0, s1] -> (d0 * s1 + s0 + d1)>>
            linalg.copy(%9, %10) : memref<1x1xf32>, memref<1x1xf32, affine_map<(d0, d1)[s0, s1] -> (d0 * s1 + s0 + d1)>>
          }
        }
      }
    

    Don't mind the copies as they get fused away on tensors when appropriate.

    What should this op look like?

        %b0 = flow.gimme_the_most_static_shape_you_can_op %ret0 : memref<?x?xf32>
    

    In particular I started from the minimal amount of reasonable information:

    1. I magically know the rank here (I can infer it from #sizes in flow.interface.load.tile)
    2. I assumed the allocated memory region is contiguous for now (no layout map on memref<?x?xf32>)
    3. buffer size information seems type erased so I have to go for memref<?x?xf32> (more static typing would always be better but not a blocker; I do not see how to extract more static info from the IR you gave me here).

    flow.gimme_the_most_static_shape_you_can_op could potentially turn into a view to give a bare pointer some indexing semantics.

  7. MaheshRavishankar commented on Dec 9, 2020

    @MaheshRavishankar
    Collaborator

    AFAICS, getting a memref view of the operands to the dispatch region seems fairly reasonable to me. I am assuming the contract of dispatch region is that all tensors operands and result get their own buffer

  8. benvanik commented on Dec 9, 2020

    @benvanik
    CollaboratorAuthor

    noooo no memrefs please :)
    (in meetings, will respond afterward)

  9. nicolasvasilache commented on Dec 9, 2020

    @nicolasvasilache
    Contributor

    @benvanik it doesn't have to be at the flow level :)
    But there is going to be a bufferization and memrefs will come in existence at some point.
    Connecting the IREE representation for base pointer + offset + shape to a memref type has to happen somewhere.

    I am looking for that particular bridge of the abstraction gap that is not yet clear.

    If you're going as far as saying we should never try to have load/store from/to buffer granularity in codegen, I'd refer to this section: LLVM will spill us into oblivion and we want control over buffer aspects (although we are agressively moving away from traditional C + array-based inputs and analysis).

    Anyway, let's discuss in our VC, much higher BW :)

  10. benvanik commented on Dec 10, 2020

    @benvanik
    CollaboratorAuthor

    @MaheshRavishankar what are your thoughts on having the workgroup count as a function expression vs having it as just arguments to the op?

    Example:

    %x = shape_math_stuff
    %y = shape_math_stuff
    %foo = flow.dispatch.workgroups[%x, %y](%arg0 : tensor<...>)...

    My thinking here is that this will make it easier at the flow level to aggregate shape logic across multiple dispatches - especially when indirect - as it's possible to just use the SSA use-def chain and normal op reordering to get all the shape logic to the same place (dominating block, function entry, etc) at once. We can then do the things as a separate bit of logic for indirect/predicated dispatch, vs. having the workgroup count logic separate already.

    Sound ok?

    Also, I'm going to make the flow-level workgroup dimensions [1, inf) (not limited to a 3D xyz) - it can be a flow->hal step to take the N-dimensional grid and map it to the 3D grid when workgroup size is known (it's not in flow level as we don't know the target yet).

  11. MaheshRavishankar commented on Dec 10, 2020

    @MaheshRavishankar
    Collaborator

    So you are saying we keep the shape match stuff "outside" of flow.dispatch.workgroup and when we create that we just insert whatever logic we need there and the flow.dispatch.workgroup just uses these values. That would indeed be easier to generate.
    What about doing the same for workgroup size as well? So it would actually look like the CUDA <<<...>>> semantics in IR?

  12. benvanik commented on Dec 10, 2020

    @benvanik
    CollaboratorAuthor

    At the flow level we shouldn't have a workgroup size yet (you could still reference the workgroup size symbolically inside the region, but there's no way to specify it).

  13. MaheshRavishankar commented on Dec 10, 2020

    @MaheshRavishankar
    Collaborator

    I dont fully follow why that should be the case (we have the number of workgroups but not workgroup size?)

  14. benvanik commented on Dec 10, 2020

    @benvanik
    CollaboratorAuthor

    What would you use to compute it? At this point, you don't know the target device.
    Once you know it (when lowering flow->hal) you can factor that into the workgroup count calculation per-device easily. You can also factor in per-device + per-dispatch and dynamic shape math logic (clamping to maximum workgroup count along particular dimensions, padding, etc).

    For example:

    %x = constant 128 : index
    %y = constant 48 : index
    flow.dispatch.workgroups[%x, %y](...)

    ->

    %x = constant 128 : index
    %y = constant 48 : index
    hal.device.switch...
      match<"device_0">() {
        %workgroup_size_x_dev0 = constant 4 : index
        %workgroup_size_y_dev0 = constant 2 : index
        %x_dev0 = divi %x, %workgroup_size_x_dev0 : index
        %y_dev0 = divi %y, %workgroup_size_y_dev0 : index
        %z = constant 1 : index
        hal.dispatch %x_dev0, %y_dev0, %z
      },
      match<"device_1">() {
        %workgroup_size_x_dev1 = constant 64 : index
        %workgroup_size_y_dev1 = constant 8 : index
        %x_dev1 = divi %x, %workgroup_size_x_dev1 : index
        %y_dev1 = divi %y, %workgroup_size_y_dev1 : index
        %z = constant 1 : index
        hal.dispatch %x_dev1, %y_dev1, %z
      }
  15. benvanik commented on Dec 10, 2020

    @benvanik
    CollaboratorAuthor

    (way back in the day flow.dispatch.region could take multiple dimensions for the workload but then we simplified it to just a single one, this is effectively the same thing as the original one was)

  16. 26 remaining items

  17. benvanik commented on Dec 16, 2020

    @benvanik
    CollaboratorAuthor
    • me: some patterns for things like flow.dispatch.workgroup.count -> hal.interface.workgroup.count, etc that backends can add to their import pipeline

    Fiddling with this a bit, I think maybe just not having the hal ops at all is best - if we do flow->hal inside of the target backends that removes the extra bounce through the hal dialect. Will let it be as it is now until we decide otherwise.

    • me: push shape info into flow.dispatch.i/o.load/store and remove use of shapex/ties from IR

    As mentioned above, going to not touch this (keep the tie shapes that can be resolved) until we have more together.

    I'll put what I have into a PR.

  18. MaheshRavishankar commented on Dec 16, 2020

    @MaheshRavishankar
    Collaborator

    Ok, ill take a look probably later today, but mostly tomorrow. Thanks!

  19. MaheshRavishankar commented on Dec 16, 2020

    @MaheshRavishankar
    Collaborator

    If those were exposed that'd be great! (unless view always wants shape, then throw it there :)

    These are exposed in https://reviews.llvm.org/D93374. If you need it I can separate that out as a separate patch and submit it.

  20. benvanik commented on Dec 16, 2020

    @benvanik
    CollaboratorAuthor

    No rush - but looks good!

    That code would be a nice candidate to switch to the custom parser/printer directive format in the future, as then anyone would be able to compose it nicely without having to go to full custom printers/parsers in C++: https://mlir.llvm.org/docs/OpDefinitions/#custom-directives

  21. MaheshRavishankar commented on Dec 16, 2020

    @MaheshRavishankar
    Collaborator

    Oh nice idea. I will take a stab at that.

  22. nicolasvasilache commented on Dec 18, 2020

    @nicolasvasilache
    Contributor

    Didn't have a single cycle to devote to this this week, unfortunately.
    I'll pick it up and connect to the dispatch region creation when I come back in 10 days.

  23. MaheshRavishankar commented on Feb 2, 2021

    @MaheshRavishankar
    Collaborator

    Closing this. All issues discussed on this bug has been resolved...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

compiler/dialects

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions