Skip to content

Lots of elidable loop code generated on CPU. #8053

Open

Description

@benvanik

Repro:

builtin.func @main(%arg0: tensor<1x320x320x3xi8>) -> tensor<1x320x320x3xi8> {
  %0 = "tosa.rescale"(%arg0) {double_round = false, input_zp = 128 : i32, multiplier = [1073741824 : i32], output_zp = 0 : i32, per_channel = false, scale32 = true, shift = [30 : i32]} : (tensor<1x320x320x3xi8>) -> tensor<1x320x320x3xi8>
  return %0 : tensor<1x320x320x3xi8>
}

This produces the following dispatch:

  stream.executable private @main_dispatch_0 {
    stream.executable.export public @main_dispatch_0
    builtin.module  {
      func @main_dispatch_0(%arg0: !stream.binding {stream.alignment = 32 : index}, %arg1: !stream.binding {stream.alignment = 32 : index}) {
        %c3 = arith.constant 3 : index
        %c320 = arith.constant 320 : index
        %c128_i32 = arith.constant 128 : i32
        %c1073741824_i32 = arith.constant 1073741824 : i32
        %c30_i8 = arith.constant 30 : i8
        %c-128_i32 = arith.constant -128 : i32
        %c127_i32 = arith.constant 127 : i32
        %c0 = arith.constant 0 : index
        %0 = stream.binding.subspan %arg0[%c0] : !stream.binding -> !flow.dispatch.tensor<readonly:320x320x3xi8>
        %1 = stream.binding.subspan %arg1[%c0] : !stream.binding -> !flow.dispatch.tensor<writeonly:320x320x3xi8>
        %workgroup_size_0 = flow.dispatch.workgroup.size[0] : index
        %workgroup_size_1 = flow.dispatch.workgroup.size[1] : index
        %workgroup_size_2 = flow.dispatch.workgroup.size[2] : index
        %workgroup_id_0 = flow.dispatch.workgroup.id[0] : index
        %workgroup_count_0 = flow.dispatch.workgroup.count[0] : index
        %workgroup_id_1 = flow.dispatch.workgroup.id[1] : index
        %workgroup_count_1 = flow.dispatch.workgroup.count[1] : index
        %workgroup_id_2 = flow.dispatch.workgroup.id[2] : index
        %workgroup_count_2 = flow.dispatch.workgroup.count[2] : index
        %2 = affine.apply #map0()[%workgroup_id_2, %workgroup_size_2]
        %3 = affine.apply #map0()[%workgroup_count_2, %workgroup_size_2]
        scf.for %arg2 = %2 to %c320 step %3 {
          %4 = affine.apply #map0()[%workgroup_id_1, %workgroup_size_1]
          %5 = affine.apply #map0()[%workgroup_count_1, %workgroup_size_1]
          scf.for %arg3 = %4 to %c320 step %5 {
            %6 = affine.apply #map0()[%workgroup_id_0, %workgroup_size_0]
            %7 = affine.apply #map0()[%workgroup_count_0, %workgroup_size_0]
            scf.for %arg4 = %6 to %c3 step %7 {
              %8 = affine.min #map1(%arg2)[%workgroup_size_2]
              %9 = affine.min #map1(%arg3)[%workgroup_size_1]
              %10 = affine.min #map2(%arg4)[%workgroup_size_0]
              %11 = flow.dispatch.tensor.load %0, offsets = [%arg2, %arg3, %arg4], sizes = [%8, %9, %10], strides = [1, 1, 1] : !flow.dispatch.tensor<readonly:320x320x3xi8> -> tensor<?x?x?xi8>
              %12 = linalg.init_tensor [%8, %9, %10] : tensor<?x?x?xi8>
              %13 = linalg.generic {indexing_maps = [#map3, #map3], iterator_types = ["parallel", "parallel", "parallel"]} ins(%11 : tensor<?x?x?xi8>) outs(%12 : tensor<?x?x?xi8>) {
              ^bb0(%arg5: i8, %arg6: i8):  // no predecessors
                %14 = arith.extsi %arg5 : i8 to i32
                %15 = arith.subi %14, %c128_i32 : i32
                %16 = "tosa.apply_scale"(%15, %c1073741824_i32, %c30_i8) {double_round = false} : (i32, i32, i8) -> i32
                %17 = arith.cmpi slt, %16, %c-128_i32 : i32
                %18 = select %17, %c-128_i32, %16 : i32
                %19 = arith.cmpi slt, %c127_i32, %16 : i32
                %20 = select %19, %c127_i32, %18 : i32
                %21 = arith.trunci %20 : i32 to i8
                linalg.yield %21 : i8
              } -> tensor<?x?x?xi8>
              flow.dispatch.tensor.store %13, %1, offsets = [%arg2, %arg3, %arg4], sizes = [%8, %9, %10], strides = [1, 1, 1] : tensor<?x?x?xi8> -> !flow.dispatch.tensor<writeonly:320x320x3xi8>
            }
          }
        }
        return
      }
    }
  }

Which lowers into quite a bit of code through LLVM and a pretty complex function:
image

Unrelated (but interesting), LLVM also produces weird empty spin loops:

.LBB0_27:
	addq	%r8, %rcx
	cmpq	$320, %rcx
	jl	.LBB0_27

Activity

  1. added
    codegen
    performance ⚡
    on Jan 8, 2022
  2. benvanik commented on Jan 8, 2022

    @benvanik
    CollaboratorAuthor

    If hand-authored, the red blocks would be the only ones present (parameter unpack/setup, core loop, exit), so a reasonable target to shoot for:
    image

  3. nicolasvasilache commented on Feb 9, 2022

    @nicolasvasilache
    Contributor

    nice, could you elaborate a bit on how you got this viz?

  4. benvanik commented on Feb 9, 2022

    @benvanik
    CollaboratorAuthor

    https://cutter.re/ loading one of the shared libraries we spit out (with -iree-llvm-keep-linker-artifacts) - since the .so's only contain the codegened functions they are easy to pick out and inspect via the graph tab; the decompiler is also a good way to see the control flow (I find it much more useful than looking at LLVM IR dumps and such):
    image

    It makes it easy to spot the weird empty loops we end up with too:
    image

  5. benvanik commented on Feb 9, 2022

    @benvanik
    CollaboratorAuthor

    (those shots are from dynamic_abs.mlir - which is just an elementwise abs on dense data - so the target would be a single loop and no pointer manipulation/striding/etc - don't expect us to get there in one step but good to know where we should be :)

  6. MaheshRavishankar commented on Feb 9, 2022

    @MaheshRavishankar
    Collaborator

    There is a long thread that will eventually connect to this working

    1. We move tile and distribute out of Flow and into codegen. That is taking view of dimensionality and making some early unrevertable decisions.
    2. Then in Flow dispatches we can easily figure out cases where a generic op is essentially a 1D op. Then we collapse those dimensions with reshapes at the boundaries. This will remove all these loops.

    I already have the code for (2) in another patch I am working on. (1) should follow next.

  7. MaheshRavishankar commented on Mar 11, 2022

    @MaheshRavishankar
    Collaborator

    Adding a bit more detail here before assigning it to Okwan.

    There are two kinds of dispatches in IREE, one where the op driving compilation in the dispatch is a GEMM, Convolution, etc. and one where the dispatch region contains just a generic op. Removing the loops generated by the compilation process in the former need to be done at the very end stage. There are several reasons for this, most important of which is that tensors + distributions dont gel that well, and the loop becomes semantically load bearing (see this that has more info and a lot more other things). For such cases, removing the loops should be the last step in the code generation (and it might well turn out that we dont have all the information to remove/collapse such loops. We might have to live with those for now, we just dont have the constructs to linearize them after the fact currently).

    For the second case , i.e. just a generic operation, flattening it makes sense in most common case.

    #map0 = affine_map<(d0, d1) -> (d0, d1)>
    %0 = linalg.generic {
        iterator_types = ["parallel", "parallel"]
        indexing_maps = [#map0, #map0, #map0]}
        ins(%in0, %in1 : tensor<?x?xf32>, tensor<?x?xf32>) outs(%out : tensor<?x?xf32>) { ... }
    

    can be linearized. to

    #map0 = affine_map<(d0) -> (d0)>
    %0 = linalg.generic {
        iterator_types = ["parallel"]
        indexing_maps = [#map0, #map0, #map0]}
        ins(%in0, %in1 : tensor<?xf32>, tensor<?xf32>) outs(%out : tensor<?xf32>) { ... }
    

    but some generics op are better off not being linearized this way.
    For example

    #map0 = affine_map<(d0, d1) -> (d0, d1)>
    #map1 = affine_map<(d0, d1) -> (d0)>
    %0 = linalg.generic {
        iterator_types = ["parallel", "parallel"]
        indexing_maps = [#map0, #map1, #map0]}
        ins(%in0, %in1 : tensor<?x?xf32>, tensor<?xf32>) outs(%out : tensor<?x?xf32>) { ... }
    

    and

    #map0 = affine_map<(d0, d1) -> (d0, d1)>
    #map1 = affine_map<(d0, d1) -> (d1, d0)>
    %0 = linalg.generic {
        iterator_types = ["parallel", "parallel"]
        indexing_maps = [#map0, #map1]}
        ins(%in0: tensor<?x?xf32>) outs(%out : tensor<?x?xf32>) { ... }
    

    reason being that linearizing those result in the affine maps not being projected permutation which foils a lot of transformations downstream.

    Coming to the transformation for linearizing the iteration space itself, a lot of the code for this can probably reused from here https://github.com/llvm/llvm-project/blob/097035f308d1cdc00d71d3d216564fddffda0be7/mlir/lib/Dialect/Linalg/Transforms/ElementwiseOpFusion.cpp#L1466

  8. MaheshRavishankar commented on Mar 11, 2022

    @MaheshRavishankar
    Collaborator

    Assigning to Okwan for now to start with the linearization of "some" generic ops to see if it helps the situation

  9. okkwon commented on Mar 28, 2022

    @okkwon
    Member

    For the rescale tosa input, I don't see a bad graph. @benvanik would you mind attaching the dynamic_abs.mlir?

    image

  10. benvanik commented on Mar 28, 2022

    @benvanik
    CollaboratorAuthor

    It's possible it's been improved for certain cases since this was filed - that'd be great! Did you try a rescale with several non-unit dimensions? You can track the dispatch region through and see what happens - if for example you don't get the same IR after dispatch region formation as in the issue comment then you won't see the same output, or you may find that there's now something inbetween that's flattening out the loops.

  11. okkwon commented on Mar 28, 2022

    @okkwon
    Member

    several non-unit dimensions?

    Would you give me an example?

    BTW, RemoveSingleIterationLoop removes the outer loops related to the workgroup counters, which means there are outer loops in which the dispatch function is called, but in the dispatch function we are not supposed to see the outer loops (unless there is an transformation that sinks the outer loops into the dispatch function.)

  12. MaheshRavishankar commented on Mar 28, 2022

    @MaheshRavishankar
    Collaborator

    Yeah, RemoveSingleIterationLoop was meant to help this a bit, but there is still the loops created while lowering to loops, or with second-level tiling. If it is not a trivially elidable loop, then these need linearization to be able to remove those loops (as well as associated index computation).

  13. 9 remaining items

  14. okkwon commented on Mar 28, 2022

    @okkwon
    Member

    Working with tensor<1024x2xf32> vs tensor<2x1024xf32> (or tensor<2x?x1024xf32> etc) should have zero performance difference

    I understand the expectation, but it depends on how the work is distributed to the computational units. For example, due to a data dependency, the previous work might have been done with a column partitioning. (This is gonna be more relevant with affine-based HPC applications rather than ML application.) The proposed linearization is equivalent to a row partitioning. It implicitly dictates how the tiling is done since it happens before tiling. In this case, the communication (or data movement pattern) between the column partitioning and the row partitioning causes a lot of data movement. This is the All-to-All communication pattern. (I am extending my view of the problem to the distributed memory systems, which we may want to support later with multi-gpu or multi-node.) If we did a column partitioning for the second operation, there would be no communication at all.

    linalg.generic affine maps provide what we need (IIUC)

    After the linearization transform, we would have different affine map. In particular, having a different iteration space representation might make the dispatch fusion more difficult.

    Tile size changes alone don't help the problem here ...

    I agree. I am trying to separate out the loop overhead reduction from tiling. Again, linearizing the element-wise generic op affects how the tiling happens, and it makes me pause and think..

  15. MaheshRavishankar commented on Mar 28, 2022

    @MaheshRavishankar
    Collaborator

    After the linearization transform, we would have different affine map. In particular, having a different iteration space representation might make the dispatch fusion more difficult.

    That really depends. It could also open up more avenues for fusion. If you had something with an iteration space of 20x30 and another with an iteration space of 30x20, earlier they are not easy to fuse, after linearization, they are now potentially fusable.

  16. okkwon commented on Mar 28, 2022

    @okkwon
    Member

    Keeping the discussion noted, I will go ahead and implement the linearization. We can revisit and enhance once we have more concrete problems. Thanks Ben and Mahesh!

  17. MaheshRavishankar commented on Mar 28, 2022

    @MaheshRavishankar
    Collaborator

    Keeping the discussion noted, I will go ahead and implement the linearization. We can revisit and enhance once we have more concrete problems. Thanks Ben and Mahesh!

    Your point about distributed memory system is valid. When we cross that bridge we can decide how and where the transformation here would trigger. It will probably still have a place "post distribution".

  18. removed their assignment
    on Aug 3, 2022
  19. grypp commented on Dec 9, 2022

    @grypp
    Contributor

    Hi all, #11295 could linearize linalg.generic to 1D on this issue. Please let me know if you have other uses case so I could try.

  20. moved this from Not Started to In Progress in (Deprecated) IREEon Apr 14, 2023
  21. removed their assignment
    on Apr 17, 2023
  22. moved this from In Progress to Backlog in (Deprecated) IREEon Apr 18, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

codegenperformance ⚡

Type

No type

Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions