Skip to content

[flow] Fuse reduction into consumer elementwise op - #9693

Merged
okkwon merged 9 commits into
iree-org:mainfrom
okkwon:fuse_reduction_into_consumer
Jul 13, 2022
Merged

okkwon merged 9 commits into
iree-org:mainfrom
okkwon:fuse_reduction_into_consumer

Conversation

@okkwon

@okkwon okkwon commented Jul 1, 2022 •

Copy link
Copy Markdown
Member

Support fusion of reduction + elementwise.

The fusion is disabled by default because CUDA fails to compile.

The number of dispatches for miniLM is reduced from 271 to 221.

@okkwon
okkwon force-pushed the fuse_reduction_into_consumer branch from c2a4e39 to 4918f27 Compare July 1, 2022 01:51
@iree-github-actions-bot

iree-github-actions-bot commented Jul 1, 2022 •

Copy link
Copy Markdown
Contributor

Abbreviated x86_64 Benchmark Summary (experimental)

@ commit 88e03c6a90c3a8eb9e48b16f59899a3c0fee36b8 (vs. base eeb0b1a309c2d49713a95eb95432bfb8eb5f36bd)

Regressed Latencies 🚩

Benchmark Name Average Latency (ms) Median Latency (ms) Latency Standard Deviation (ms)
MobileNetV3Small [fp32,imagenet] (TFLite) 1-thread,full-inference,default-flags with IREE-Dylib @ GCP-c2-standard-16 (CPU-x86\_64-CascadeLake) 5 (vs. 4, 25.00%↑) 5 0

No improved or regressed compilation metrics 🏖️

For more information:

@iree-github-actions-bot

iree-github-actions-bot commented Jul 1, 2022 •

Copy link
Copy Markdown
Contributor

@okkwon

okkwon commented Jul 1, 2022

Copy link
Copy Markdown
Member Author

x86 and Android perf results look good, but there is a compilation failure for CUDA. The pattern seems very simple, but CUDA fails to compile.

After Outlining:

  flow.executable private @_serving_default_dispatch_14 {
    flow.executable.export public @_serving_default_dispatch_14 
    builtin.module {
      func.func @_serving_default_dispatch_14(%arg0: !flow.dispatch.tensor<readonly:4x384x384xf32>, %arg1: !flow.dispatch.tensor<writeonly:4x384x384xf32>) {
        %cst = arith.constant 0xFF800000 : f32
        %0 = flow.dispatch.tensor.load %arg0, offsets = [0, 0, 0], sizes = [4, 384, 384], strides = [1, 1, 1] : !flow.dispatch.tensor<readonly:4x384x384xf32> -> tensor<4x384x384xf32>
        %1 = linalg.init_tensor [4, 384, 384] : tensor<4x384x384xf32>
        %2 = linalg.init_tensor [4, 384] : tensor<4x384xf32>
        %3 = linalg.fill ins(%cst : f32) outs(%2 : tensor<4x384xf32>) -> tensor<4x384xf32>
        %4 = linalg.generic {indexing_maps = [#map1, #map0], iterator_types = ["parallel", "parallel", "reduction"]} ins(%0 : tensor<4x384x384xf32>) outs(%3 : tensor<4x384xf32>) {
        ^bb0(%arg2: f32, %arg3: f32):
          %6 = arith.maxf %arg2, %arg3 : f32
          linalg.yield %6 : f32
        } -> tensor<4x384xf32>
        %5 = linalg.generic {indexing_maps = [#map1, #map0, #map1], iterator_types = ["parallel", "parallel", "parallel"]} ins(%0, %4 : tensor<4x384x384xf32>, tensor<4x384xf32>) outs(%1 : tensor<4x384x384xf32>) {
        ^bb0(%arg2: f32, %arg3: f32, %arg4: f32):
          %6 = arith.subf %arg2, %arg3 : f32
          %7 = math.exp %6 : f32
          linalg.yield %7 : f32
        } -> tensor<4x384x384xf32>
        flow.dispatch.tensor.store %5, %arg1, offsets = [0, 0, 0], sizes = [4, 384, 384], strides = [1, 1, 1] : tensor<4x384x384xf32> -> !flow.dispatch.tensor<writeonly:4x384x384xf32>
        return
      }
    }
  }

Before LLVMGPUReduceToGPU:

func.func @_serving_default_dispatch_14() {
  %cst = arith.constant dense<0xFF800000> : vector<1xf32>
  %c0 = arith.constant 0 : index
  %cst_0 = arith.constant 0.000000e+00 : f32
  %c32 = arith.constant 32 : index
  %c384 = arith.constant 384 : index
  %0 = hal.interface.constant.load[0] values([1966080 : i32, 2555904 : i32]) : i32
  %1 = hal.interface.constant.load[1] values([4325376 : i32, 4915200 : i32]) : i32
  %2 = arith.index_cast %0 : i32 to index
  %3 = arith.index_cast %1 : i32 to index
  %4 = hal.interface.binding.subspan set(0) binding(0) type(storage_buffer) offset(%2) alignment(64) : memref<4x384x384xf32>
  memref.assume_alignment %4, 64 : memref<4x384x384xf32>
  %5 = hal.interface.binding.subspan set(0) binding(1) type(storage_buffer) offset(%3) alignment(64) : memref<4x384x384xf32>
  memref.assume_alignment %5, 64 : memref<4x384x384xf32>
  %workgroup_id_x = hal.interface.workgroup.id[0] : index
  %workgroup_id_y = hal.interface.workgroup.id[1] : index
  %6 = memref.alloc() : memref<1x2xf32, 3>
  %7 = gpu.thread_id  x
  %8 = affine.apply affine_map<()[s0, s1] -> (s1 * 2 + s0 floordiv 32)>()[%7, %workgroup_id_x]
  %9 = scf.for %arg0 = %c0 to %c384 step %c32 iter_args(%arg1 = %cst) -> (vector<1xf32>) {
    %15 = vector.transfer_read %4[%workgroup_id_y, %8, %arg0], %cst_0 {in_bounds = [true]} : memref<4x384x384xf32>, vector<32xf32>
    %16 = vector.broadcast %15 : vector<32xf32> to vector<1x1x32xf32>
    %17 = vector.multi_reduction <maxf>, %16 [2] : vector<1x1x32xf32> to vector<1x1xf32>
    %18 = vector.extract %17[0] : vector<1x1xf32>
    %19 = arith.maxf %18, %arg1 : vector<1xf32>
    scf.yield %19 : vector<1xf32>
  }
  %10 = affine.apply affine_map<()[s0] -> (s0 floordiv 32)>()[%7]
  vector.transfer_write %9, %6[%c0, %10] {in_bounds = [true]} : vector<1xf32>, memref<1x2xf32, 3>
  %11 = gpu.thread_id  y
  %12 = affine.apply affine_map<()[s0] -> ((s0 floordiv 32) * 16)>()[%7]
  %13 = affine.apply affine_map<()[s0, s1] -> (s0 * 2 + s1 * 2)>()[%11, %workgroup_id_x]
  %14 = affine.apply affine_map<()[s0] -> (s0 * 2)>()[%11]
  scf.for %arg0 = %12 to %c384 step %c32 {
    %15 = vector.transfer_read %4[%workgroup_id_y, %13, %arg0], %cst_0 {in_bounds = [true, true]} : memref<4x384x384xf32>, vector<2x16xf32>
    %16 = vector.transfer_read %6[%c0, %14], %cst_0 {in_bounds = [true, true], permutation_map = affine_map<(d0, d1) -> (d1, 0)>} : memref<1x2xf32, 3>, vector<2x16xf32>
    %17 = arith.subf %15, %16 : vector<2x16xf32>
    %18 = math.exp %17 : vector<2x16xf32>
    vector.transfer_write %18, %5[%workgroup_id_y, %13, %arg0] {in_bounds = [true, true]} : vector<2x16xf32>, memref<4x384x384xf32>
  }
  return
}

@okkwon

okkwon commented Jul 1, 2022

Copy link
Copy Markdown
Member Author

@ThomasRaoux would you mind checking if the code above is supported by the CUDA backend?

@okkwon

okkwon commented Jul 1, 2022

Copy link
Copy Markdown
Member Author

I had an offline discussion with @ThomasRaoux, and he already has a plan for this, but it needs a little bit of more work. My next step would be adding an option for this transformation (turned off by default), and make it available in the repo for the later work.

@okkwon

okkwon commented Jul 1, 2022

Copy link
Copy Markdown
Member Author

This is the dispatch graph: dispatch.pdf

@okkwon
okkwon force-pushed the fuse_reduction_into_consumer branch from d1c1d3c to 8fc3e17 Compare July 6, 2022 17:20
@okkwon

okkwon commented Jul 6, 2022

Copy link
Copy Markdown
Member Author

Added a unit test and an option to make it disabled by default.

@okkwon
okkwon force-pushed the fuse_reduction_into_consumer branch from 8fc3e17 to 612eb49 Compare July 6, 2022 17:30
@okkwon okkwon self-assigned this Jul 6, 2022
@okkwon
okkwon marked this pull request as ready for review July 6, 2022 18:55
@okkwon
okkwon requested a review from MaheshRavishankar as a code owner July 6, 2022 18:55
@okkwon
okkwon requested review from ThomasRaoux and hanhanW July 6, 2022 18:56
@okkwon okkwon changed the title WIP: Fuse reduction into consumer [flow] Fuse reduction into consumer elementwise op Jul 6, 2022
@okkwon

okkwon commented Jul 6, 2022

Copy link
Copy Markdown
Member Author

Note that the pass is disabled by default until the GPU backends can support it.

@okkwon
okkwon force-pushed the fuse_reduction_into_consumer branch from 612eb49 to 1bc1343 Compare July 6, 2022 19:30
@okkwon

okkwon commented Jul 6, 2022 •

Copy link
Copy Markdown
Member Author

I have found that the additional check for the input indexing maps in isSimpleReduction() actually prevented some fusion opportunities, which changed the number of dispatches from 271 to 247. I am testing the code that removed the restriction on the input to the reduction.

@okkwon
okkwon force-pushed the fuse_reduction_into_consumer branch from e207efb to 88e03c6 Compare July 6, 2022 23:52
@okkwon
okkwon requested a review from ThomasRaoux July 6, 2022 23:54
@okkwon

okkwon commented Jul 6, 2022

Copy link
Copy Markdown
Member Author

@ThomasRaoux Resolved your comments. Please take another look. Thanks!

@okkwon

okkwon commented Jul 8, 2022

Copy link
Copy Markdown
Member Author

miniLM and bertencoder see the reduction on the number of dispatches.
miniLM: 271 -> 221
bertencoder: 609 -> 561

@okkwon

okkwon commented Jul 8, 2022

Copy link
Copy Markdown
Member Author

There must be more pattern matchings with other models and I will handle the cases in a different PR.

@hanhanW

hanhanW commented Jul 11, 2022 •

Copy link
Copy Markdown
Contributor

Hey @okkwon , sorry for the late update. I benchmarked the miniLM bert model on a2-highgpu-1g. With the flag on, I can get 19.0 ms versus 20.4 ms w/ the flag off. There are 7% improvements on multi-threaded. Nice work!

@MaheshRavishankar

Copy link
Copy Markdown
Collaborator

I'd like to take a pass before this lands. Can we wait till EoD today to land?

@okkwon

okkwon commented Jul 11, 2022

Copy link
Copy Markdown
Member Author

Having your review would be great @MaheshRavishankar. Thanks!

@okkwon

okkwon commented Jul 11, 2022

Copy link
Copy Markdown
Member Author

@hanhanW Thanks for running the benchmark!

/// An example:
/// s = sum(a: <16x32xf32>) -> <16xf32>
/// d = div(a: <16x32xf32>, broadcast(s to <16x32xf32>)) -> <16x32xf32>
static bool isReductionBroadcastElementwise(OpOperand *operand) {

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.

It is great to see that relatively simple conditions / filters allow creating more powerful dispatch regions!

I am not clear about the structure of the code here though, these are somewhat adhoc constraints that are conjunctions of things hardcoded deep in C++. I would love to see a common effort towards more composable constraints that we can reuse and reassemble better, esp. as we decouple more and more the control from hardcoded C++.

I'd encourage you to think about refactoring to allow easily plugging and composing with the PR I sent out here: #9756 (last commit).

Another way to phrase my request is: "what are the atomic units of useful matching and filtering" that we can reuse; isReductionBroadcastElementwise looks to me like a very non-atomic that we should build out of atoms that we want to properly define to make them reusable.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Thanks @nicolasvasilache! I agree. When I worked on this to recover the original tensor op's info, I felt like I am trying recovering the upper IR level representation (tosa or mhlo) at the linalg generic op level reversely.

This led me to thinking of the new compilation pipeline, which needs a common high level tensor ops, such as tosa, mhlo, or purely linalg name ops before linalg. This could have made the pattern matching code a lot easy and clean. This would need a great amount of discussion, so I will initiate the discussion later.

I am further working on the reduction code to support dispatch fusions including softmax and layer normalization, and I will put the refactoring effort while working on them by referencing your PR. Thanks for the pointer!

@okkwon okkwon Jul 11, 2022 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Also, there is a GPU work based on this PR happening at the same time, so I'd like to push it first and do refactor in subsequent changes.

@MaheshRavishankar

Copy link
Copy Markdown
Collaborator

@okkwon can you summarize the discussion above a bit so that I dont rehash things. Mostly looking for divergence from what we had discussed.

@okkwon

okkwon commented Jul 11, 2022

Copy link
Copy Markdown
Member Author

It was mostly about the edge cases that the pattern matching code unexpectedly matches. Matmul and dynamic dims are the cases, so I put more restrictions to match what I expect to match.

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

Thanks Okwan! First set of comments here.

@okkwon
okkwon dismissed nicolasvasilache’s stale review July 11, 2022 18:01

The refactoring work will be done in subsequent PRs.

okkwon added 3 commits July 11, 2022 11:15
1. Bail out dynamic shapes.
2. Bail out the case where the input type for the reduction is not the same as
the output type of the elementwise operation.
3. Check whether the elementwise output has the identity indexing map.
- Check if a reduction is unary or binary.
- Check if an input with a full dimension has the same shape as the elementwise
  op's output shape.
- Check if the other input has the identity map or is broadcasted.
@okkwon
okkwon force-pushed the fuse_reduction_into_consumer branch from 7af55af to e886d24 Compare July 11, 2022 18:16
@MaheshRavishankar

Copy link
Copy Markdown
Collaborator

Drive by: is this only handling cases that can't be fused into producers? We really want to be fusing into producers where possible (anything that lets us perform fewer memory operations), so curious how this fits in with existing producer fusion - do we have any existing producer fusion? There are definite use cases for each type and I think this is useful - just trying to understand the bigger picture.

I don't know if Okwan answered this, but this should all be producer fusion.

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

Updating comments based on offline discussions.

@okkwon please document each constraint here, especially those that are made restrictive that can be generalized later vs. those that are core to the pattern being checked. It would be good to have some documentation in code about what each constraint is for.

1. remove matchReduction(),
2. remove hasOnlyScaleElementwiseOp(), and
3. remove dynamic shape check since having a same indexing map guarantees
   the same shape at runtime.
@okkwon

okkwon commented Jul 11, 2022

Copy link
Copy Markdown
Member Author

I have updated the PR to address Mahesh's comments. Thanks for the offline discussion!

Also, I have added a few comments about the restriction that can be relaxed later. For now,

There are several restrictions to match simple reduction + broadcast + elementwise.

  1. The number of inputs to reduction is 1 or 2.
  2. One of them is identity and the other one is identity or broadcast.
  3. The elementwise op does not have an output transpose.
  4. A same indexing map is used for reduction and broadcast.

This is the common pattern we can see from the real applications. As I find more patterns, I will relax the conditions to cover more cases.

@okkwon
okkwon requested a review from MaheshRavishankar July 11, 2022 21:58
@okkwon
okkwon dismissed MaheshRavishankar’s stale review July 11, 2022 21:58

Resolved in the latest update.

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

Few more comments. Should be good after that.

Though as a follow up, I'd suggest dropping all the restrictive conditions. The only real conditions you need is probably that the indexing maps used for the fused operand in the producer and consumer "match". (A version of this was strawman implemented here MaheshRavishankar@11a3f70 - following whats described here #9139 (comment)). Rest all should be droppable.

@okkwon
okkwon requested a review from MaheshRavishankar July 11, 2022 23:16
In the current development stage, we take aggresssive fusion as our
default fusion policy and we do type checking only when the types are known to
be static. When the types are dynamic, we optimistically assume that they are
compatible for fusion and do fusion aggressively.
@okkwon

okkwon commented Jul 12, 2022

Copy link
Copy Markdown
Member Author

I'd like to suggest doing further enhancements in subsequent PRs. The narrow conditions don't do any harm, but relaxing the conditions needs a broad testing in codegen & perf.

@okkwon

okkwon commented Jul 12, 2022

Copy link
Copy Markdown
Member Author

Filed an issue: #9772

// When we have static shapes, we do extra checks for the type. For dynamic
// shape cases, we do not check the shape and do aggressive fusion with high
// optimism, which is the default approach we are pursuing now.
bool hasStaticShape =

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.

Nit: Move this closer to where it is used.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Both if and else blocks just below use the variable and that's why it is outside.

@okkwon
okkwon merged commit 2bcef5e into iree-org:main Jul 13, 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.

7 participants