Skip to content

[CodeGen] Enable fusion with consumer elementwise ops - #5282

Merged
antiagainst merged 8 commits into
iree-org:mainfrom
antiagainst:fuse-consumer-elementwise
Apr 6, 2021
Merged

antiagainst merged 8 commits into
iree-org:mainfrom
antiagainst:fuse-consumer-elementwise

Conversation

@antiagainst

@antiagainst antiagainst commented Apr 1, 2021 •

Copy link
Copy Markdown
Member

This commit adjusts dispatch region formation logic to
allow fusing operands of root ops. Given linalg.generic
as a root and consumer op, this enables fusing producer
convolution ops into the same region.

This fixes the MobileNet v2 performance regression on
the tensor path: the number of kernel dispatches for
MobileNet v2 goes from 146 down to 103; the latency
goes from 30+ms down to 18ms. (On the buffer path we
were at ~20ms.)

This commit adjusts dispatch region formation logic to
allow fusing operands of root ops. Given linalg.generic
as a root and consumer op, this enables fusing producer
convolution ops into the same region.

This fixes the MobileNet v2 performance regression on
the tensor path: the number of kernel dispatches for
MobileNet v2 goes from 148 down to 104; the latency
goes from 30+ms down to 18ms. (On the buffer path we
were at ~20ms.)
@google-cla google-cla Bot added the cla: yes label Apr 1, 2021
@benvanik benvanik added the performance ⚡ Performance/optimization related work across the compiler and runtime label Apr 1, 2021

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

Awesome! Overall looks great. Few comments to resolve!


// If the output tensor is not actually used (for initialization) by this
// op, we can reuse the result tensor's buffer for some operand.
if (!op.payloadUsesValueFromOutputOperandIndex(resultIndex)) {

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.

Can you give me an example of why this is needed. This is not the intended contract of out tensor. Think of TiedOpInterface. The out operand is tied to the result. Tie-ing it to one of the operands is strange.
Some use case here would help, cause I cant think of a reason to have this if you are only fusing named ops with consumers.

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.

It's for eliding intermediate buffers needed between linalg.conv and its consumer linalg.generic. Without this, for the following fused IR in the same dispatch region:

scf.for
  scf.for
    scf.for
      %init0 = linalg.init_tensor
      %init1 = linalg.init_tensor
      %fill = linalg.fill(%init1, ...)
      %conv = linalg.conv_2d_input_nhwc_filter_hwcf outs(%fill)
      %generic = linalg.generic ins(%conv, ...) outs(%init0)

After bufferization, we'll see an allocation for the result for %conv:

scf.for
  scf.for
    scf.for
      %subview = memref.subview
      %alloc = memref.alloc
      linalg.fill(%alloc, ...)
      linalg.conv_2d_input_nhwc_filter_hwcf outs(%alloc)
      %generic = linalg.generic ins(%alloc, ...) outs(%subview)

The allocation is breaking the lowering to GPU and it's also unnecessary as we can just directly use %subview. The connection here is to basically tell the producer %conv to reuse the buffer for %subview.

I'm also feeling a bit uneasy about this.. But this seems the best way to make the connection, without performing more complicated analysis afterwards to elide the allocation. If you think there are better ways to handle this, I'm certainly happy to try out.

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.

Yeah, I suspected this was the case. This can get tricky though. Best approach to try here is to mark these as TiedOperands at dispatch region creation (and use that information here).
The advantage there would be if we can tie the operands, we just bail on the fusion. So we wont hit a case where at a later stage we have to allocate a buffer.

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.

I'm not sure how we can mark them as tied in dispatch region formation, given they are internal tensors to the flow.dispatch.workgroups op. The result of %conv is only used by the consumer %generic. It does not escape to the flow.dispatch.workgroups interface so there is no block argument for it.


// If the output tensor is not actually used (for initialization) by this
// op, we can reuse the result tensor's buffer for some operand.
if (!op.payloadUsesValueFromOutputOperandIndex(resultIndex)) {

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.

Yeah, I suspected this was the case. This can get tricky though. Best approach to try here is to mark these as TiedOperands at dispatch region creation (and use that information here).
The advantage there would be if we can tie the operands, we just bail on the fusion. So we wont hit a case where at a later stage we have to allocate a buffer.

@MaheshRavishankar

Copy link
Copy Markdown
Collaborator

Apart from the tied operands stuff, everything looks fine here. DO you have a solution for that?

@antiagainst

Copy link
Copy Markdown
Member Author

Apart from the tied operands stuff, everything looks fine here. DO you have a solution for that?

I have replied previously: #5282 (comment). I don't think it's possible to do it at dispatch region formation time. The other way I can think of is to do it afterwards with a pattern to look at buffers and try to elide them if they are of such usage. It will keep the bufferization clean, but at the cost of more code. Not sure it's better.

@MaheshRavishankar

Copy link
Copy Markdown
Collaborator

Apart from the tied operands stuff, everything looks fine here. DO you have a solution for that?

I have replied previously: #5282 (comment). I don't think it's possible to do it at dispatch region formation time. The other way I can think of is to do it afterwards with a pattern to look at buffers and try to elide them if they are of such usage. It will keep the bufferization clean, but at the cost of more code. Not sure it's better.

ok, lets leave it here. Might get very tricky, but lets see how it works out.

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

Looks good to me. Lets keep this turned off by default since there are issues with descriptors, etc. which might just make things less stable.

Fusion now allows putting multiple root ops in the same region.
This fixes test failures in edge_detection.mlir, where we pulled to
depthwise op into its consumer generic op and we cannot elide both
intermediate buffers.
@antiagainst

Copy link
Copy Markdown
Member Author

ok, lets leave it here. Might get very tricky, but lets see how it works out.

+1!

Looks good to me. Lets keep this turned off by default since there are issues with descriptors, etc. which might just make things less stable.

Further restricted the fusion to only fuse one input in 0389bb0 to be less aggressive. This will help. I'd like to leave it on though given all tests are passing. Default off just means it won't really be tested extensively and there are more chances to regress. We can turn it to default off if this really turns out to be problematic.

@antiagainst
antiagainst merged commit 86e7d29 into iree-org:main Apr 6, 2021
@antiagainst
antiagainst deleted the fuse-consumer-elementwise branch April 6, 2021 23:15
@hanhanW

hanhanW commented Apr 7, 2021

Copy link
Copy Markdown
Contributor

hmm, I think this breaks MobileNetV2 benchmark in Linalg on tensors.

https://buildkite.com/iree/iree-android-benchmark/builds/2224#f0c20f89-02d6-4e63-bd39-e33b16b67867

Full log shows that error: failed to legalize operation 'vector.transfer_read'

I thought this is because we didn't add -iree-spirv-enable-vectorization, and somehow a vector op was created, see #5190. However, I added the flag and got compile error too. And it works if I remove --iree-vulkan-target-triple=valhall-g77-unknown-android10. Could you check if this works on your local side?

To repro:

iree-translate --iree-mlir-to-vm-bytecode-module --iree-hal-target-backends=vulkan-spirv ~/mobilenet-v2/iree_input.mlir -o a.vmfb -iree-flow-dispatch-linalg-on-tensors -iree-codegen-spirv-experimental-linalg-on-tensors -iree-spirv-enable-vectorization --iree-vulkan-target-triple=valhall-g77-unknown-android10

@antiagainst

Copy link
Copy Markdown
Member Author

The reason is constant inlining. We can inline several large constants in the same kernel right now. After bufferization we'll have memref.buffer_cast for them. Those memref.buffer_cast ops aren't recognized by VectorizeMemRefPass, which expects hal.interface.binding.subspan ops and turns vector.transfer_read into normal load ops.

The interesting thing is that I wasn't seeing this before with compiling the full model and benchmarking it. It turns out that the model I was using actually has fake weights. I generated by following:

https://github.com/google/iree/blob/ccae793f8c7c208a0b1b0baf489cfd121e5f7b4c/integrations/tensorflow/e2e/keras/applications/BUILD#L33-L57

I previously thought that'd use the real weights given the imagenet parameter. But actually it is different from

https://github.com/google/iree/blob/ccae793f8c7c208a0b1b0baf489cfd121e5f7b4c/integrations/tensorflow/e2e/keras/applications/applications_test.py#L30-L40

There is a use_external_weights option that need to be turned on to use real weights..

@antiagainst

Copy link
Copy Markdown
Member Author

It might take some time before I come up with a proper fix. In the meanwhile we can use -iree-flow-inline-constants-max-byte-length=16 to unbreak.

hanhanW added a commit that referenced this pull request Apr 7, 2021
)

See #5282 for more details.

The Linalg on tensors path should work with `-iree-spirv-enable-vectorization`, also added the forgotten flag.
@NatashaKnk NatashaKnk mentioned this pull request Apr 7, 2021
@rsuderman rsuderman mentioned this pull request Apr 7, 2021
copybara-service Bot pushed a commit that referenced this pull request Apr 8, 2021
* 734ec24 Add smoketest_linalg_on_tensors to LLVM and Vulkan-SPIRV targets. (#5324)
* d8bcb78 Drop absl logging and flat_hash_map. (#5334)
* 5c63668 [vulkan] Disable ResNet50 test failing on NVIDIA GPUs (#5332)
* 55d3715 Fix vulkan_device struct manipulation issue with std::vector. (#5333)
* 47d00c6 Fix benchmarking MobileNetV2 on S20 GPU in Linalg on tensor path. (#5331)
* ccae793 Fix bugs in ExtractReduceWindowOpPaddingAttributes. (#5329)
* 652e328 Don't inline block arguments that can be written (#5247)
* 86e7d29 [CodeGen] Enable fusion with consumer elementwise ops (#5282)
* 44ad774 Integrate MLIR-EmitC at iml130/mlir-emitc@3c265bf (#5326)
* 0141857 Added pad test, update LegalizeInputTypes to allow linalg.yield (#5305)
* 5a3653f Add mobile-bert f16 version to Mako benchmark. (#5204)
* f596cdb Add a target_env_conversion test for Linalg on tensors. (#5309)
* f1aa6f4 Print out the status when iree-check-module fails (#5323)
* 40d7589 Check for VMLA and Vulkan components for simple_embedding_test. (#5318)

COPYBARA_INTEGRATE_REVIEW=#5339 from NatashaKnk:main-to-google dea40ed
PiperOrigin-RevId: 367330863
@hanhanW hanhanW mentioned this pull request Apr 9, 2021
@NatashaKnk NatashaKnk mentioned this pull request Apr 9, 2021
@rsuderman rsuderman mentioned this pull request Apr 12, 2021
copybara-service Bot pushed a commit that referenced this pull request Apr 13, 2021
* 0132538 Merge google -> main #5404
* 53e7279 Limit fusion of linalg.generic/indexed_generic ops to avoid redundant computat..
* 516d1ac Merge branch 'main' into google-to-main
* 9630450 Make PrePartitioningConversionPass not recurse into Linalg (#5358)
* 29610ce Merge google -> main (#5388)
* 692c586 Merge branch 'main' into google-to-main
* 9b159c1 [CUDA Codegen] Add support for promotion to workgroup memory. (#5386)
* 11b3bfe MaterializeCPULaunch configurations before bufferization (#5362)
* ee0ddf4 Legalize ui64 to i32 in Flow type converter (#5384)
* 87346a2 Handle tensor.cast bufferization in LinalgBufferizePass (#5369)
* 2922e11 Removes tied transient buffer assignment propagation. (#5365)
* 5b952e4 Making flow.tensor.reshape a tied-op. (#5368)
* 7048463 Fixing ASAN-instrumented dylib library loading. (#5382)
* 2f3ad70 Adding some basic flow.tensor.reshape folders. (#5366)
* 357fa58 Switch simple_embeddding to test on DyLib + Vulkan (#5374)
* cb7d144 Turn on operand fusion flag for benchmarks of Linalg on tensors (#5380)
* f2d74fd Disable fusion of named ops with elementwise operations by default. (#5363)
* 3fc84c3 Add support for returning Python tuples (#5347)
* 8fb65cb Remove handling of shape dialect in flow->hal stream conversion. (#5360)
* 68c27a0 Add logging for Android (#5232)
* 56307e1 Merge pull request #5328 from google/benvanik-constant-io
* d3eb8e4 Merge pull request #5357 from google/benvanik-host-visible
* 4f86152 Materialize interfaces based on usage for flow.dispatch.workgroups.
* f41b25d Splitting -iree-hal-materialize-interfaces into old/new paths. This will insul..
* 62a3dfd Move constant pool ops/hal.constant.subspan into streams. This dramatically re..
* 79dc138 [spirv] NFC: use upstream push constant utility functions (#5352)
* 38daefb Revert "Disable running BERT on Vulkan (see Issue #5268) (#5269)"
* 0995956 Revert "[vulkan] Disable ResNet50 test failing on NVIDIA GPUs (#5332)"
* 0eeb3f8 Removing hack that forced all Vulkan buffers to be host-visible. After removin..
* 8abc33b Tracy fixes for GPU name allocation and allocation callstack mode. (#5356)
* 55f76d3 Fix submodule check failure (#5355)
* 830b547 [CodeGen] Copy constant at the proper place during bufferization (#5343)
* 59ad168 Drop absl flat_hash_set and some unused includes. (#5346)
* de2aabc Control TF MLIR print options via flags (#5336)
* 2e2dfdd Merge google -> main (#5345)
* ef9b787 Merge branch 'main' into google-to-main
* 8b70733 Remove extra comma from context_wrapper.cc
* 8cc6256 Fix linalg-on-tensors smoketests (#5341)
* a578d6a Add TosaToStandard to cpu/gpu target pipeline from ApplyScale lowering (#5288)
* 0c92b88 Add mixed static-dynamic arguments interface for flow.dispatch.tensor.{load|st..
* 9890722 Update Java Bindings To Build In Experimental (#5226)
* 734ec24 Add smoketest_linalg_on_tensors to LLVM and Vulkan-SPIRV targets. (#5324)
* d8bcb78 Drop absl logging and flat_hash_map. (#5334)
* 5c63668 [vulkan] Disable ResNet50 test failing on NVIDIA GPUs (#5332)
* 55d3715 Fix vulkan_device struct manipulation issue with std::vector. (#5333)
* 47d00c6 Fix benchmarking MobileNetV2 on S20 GPU in Linalg on tensor path. (#5331)
* ccae793 Fix bugs in ExtractReduceWindowOpPaddingAttributes. (#5329)
* 652e328 Don't inline block arguments that can be written (#5247)
* 86e7d29 [CodeGen] Enable fusion with consumer elementwise ops (#5282)
* 44ad774 Integrate MLIR-EmitC at iml130/mlir-emitc@3c265bf (#5326)
* 0141857 Added pad test, update LegalizeInputTypes to allow linalg.yield (#5305)
* 5a3653f Add mobile-bert f16 version to Mako benchmark. (#5204)
* f596cdb Add a target_env_conversion test for Linalg on tensors. (#5309)
* f1aa6f4 Print out the status when iree-check-module fails (#5323)
* 40d7589 Check for VMLA and Vulkan components for simple_embedding_test. (#5318)

COPYBARA_INTEGRATE_REVIEW=#5407 from rsuderman:main-to-google c9c3ea7
PiperOrigin-RevId: 368121520
iree-github-actions-bot pushed a commit that referenced this pull request Apr 13, 2021
* 0132538 Merge google -> main #5404
* 53e7279 Limit fusion of linalg.generic/indexed_generic ops to avoid redundant computat..
* 516d1ac Merge branch 'main' into google-to-main
* 9630450 Make PrePartitioningConversionPass not recurse into Linalg (#5358)
* 29610ce Merge google -> main (#5388)
* 692c586 Merge branch 'main' into google-to-main
* 9b159c1 [CUDA Codegen] Add support for promotion to workgroup memory. (#5386)
* 11b3bfe MaterializeCPULaunch configurations before bufferization (#5362)
* ee0ddf4 Legalize ui64 to i32 in Flow type converter (#5384)
* 87346a2 Handle tensor.cast bufferization in LinalgBufferizePass (#5369)
* 2922e11 Removes tied transient buffer assignment propagation. (#5365)
* 5b952e4 Making flow.tensor.reshape a tied-op. (#5368)
* 7048463 Fixing ASAN-instrumented dylib library loading. (#5382)
* 2f3ad70 Adding some basic flow.tensor.reshape folders. (#5366)
* 357fa58 Switch simple_embeddding to test on DyLib + Vulkan (#5374)
* cb7d144 Turn on operand fusion flag for benchmarks of Linalg on tensors (#5380)
* f2d74fd Disable fusion of named ops with elementwise operations by default. (#5363)
* 3fc84c3 Add support for returning Python tuples (#5347)
* 8fb65cb Remove handling of shape dialect in flow->hal stream conversion. (#5360)
* 68c27a0 Add logging for Android (#5232)
* 56307e1 Merge pull request #5328 from google/benvanik-constant-io
* d3eb8e4 Merge pull request #5357 from google/benvanik-host-visible
* 4f86152 Materialize interfaces based on usage for flow.dispatch.workgroups.
* f41b25d Splitting -iree-hal-materialize-interfaces into old/new paths. This will insul..
* 62a3dfd Move constant pool ops/hal.constant.subspan into streams. This dramatically re..
* 79dc138 [spirv] NFC: use upstream push constant utility functions (#5352)
* 38daefb Revert "Disable running BERT on Vulkan (see Issue #5268) (#5269)"
* 0995956 Revert "[vulkan] Disable ResNet50 test failing on NVIDIA GPUs (#5332)"
* 0eeb3f8 Removing hack that forced all Vulkan buffers to be host-visible. After removin..
* 8abc33b Tracy fixes for GPU name allocation and allocation callstack mode. (#5356)
* 55f76d3 Fix submodule check failure (#5355)
* 830b547 [CodeGen] Copy constant at the proper place during bufferization (#5343)
* 59ad168 Drop absl flat_hash_set and some unused includes. (#5346)
* de2aabc Control TF MLIR print options via flags (#5336)
* 2e2dfdd Merge google -> main (#5345)
* ef9b787 Merge branch 'main' into google-to-main
* 8b70733 Remove extra comma from context_wrapper.cc
* 8cc6256 Fix linalg-on-tensors smoketests (#5341)
* a578d6a Add TosaToStandard to cpu/gpu target pipeline from ApplyScale lowering (#5288)
* 0c92b88 Add mixed static-dynamic arguments interface for flow.dispatch.tensor.{load|st..
* 9890722 Update Java Bindings To Build In Experimental (#5226)
* 734ec24 Add smoketest_linalg_on_tensors to LLVM and Vulkan-SPIRV targets. (#5324)
* d8bcb78 Drop absl logging and flat_hash_map. (#5334)
* 5c63668 [vulkan] Disable ResNet50 test failing on NVIDIA GPUs (#5332)
* 55d3715 Fix vulkan_device struct manipulation issue with std::vector. (#5333)
* 47d00c6 Fix benchmarking MobileNetV2 on S20 GPU in Linalg on tensor path. (#5331)
* ccae793 Fix bugs in ExtractReduceWindowOpPaddingAttributes. (#5329)
* 652e328 Don't inline block arguments that can be written (#5247)
* 86e7d29 [CodeGen] Enable fusion with consumer elementwise ops (#5282)
* 44ad774 Integrate MLIR-EmitC at iml130/mlir-emitc@3c265bf (#5326)
* 0141857 Added pad test, update LegalizeInputTypes to allow linalg.yield (#5305)
* 5a3653f Add mobile-bert f16 version to Mako benchmark. (#5204)
* f596cdb Add a target_env_conversion test for Linalg on tensors. (#5309)
* f1aa6f4 Print out the status when iree-check-module fails (#5323)
* 40d7589 Check for VMLA and Vulkan components for simple_embedding_test. (#5318)

PiperOrigin-RevId: 368121520
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

performance ⚡ Performance/optimization related work across the compiler and runtime

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants