Skip to content

Pathologically bad workgroup distribution for elementwise dispatches on CPU. #9660

Closed

Description

@benvanik

While tracing I noticed some really tiny workgroups and took a quick look; it seems like we're still generating bad workgroup distributions on CPU for certain workloads. This may be a regression with the recent pipeline changes as I believe when I saw this before many moons ago it was mentioned it was fixed. I'm seeing this on x86_64 w/ and w/o avx2, aarch64, and vmvx so it probably impacts all CPU targets. I've only tested elementwise ops but am seeing similar things in traces with other similar ones.

Perfect distribution is a really hard problem but we should make sure we're doing at least something in the right ballpark for the trivial cases. I know there's a lot in flight here and if the current stuff is on the way out this could be considered as "the new system isn't ready until we are no longer doing this so let's add some tests for that and confirm it'll do better" vs. something that needs to be fixed in the old code. If this is a regression in the new paths we should spend some time making it better as it's really hard to do other optimization work so long as we are so skewed towards overheads. I mean, it does help me cut down the runtime overheads as I see them more clearly but it's hard to prioritize what's really an issue vs what is triggered by the current poor distribution and at some point the speed of light is only so fast :)

As a general rule workgroups like these should be processing thousands to tens of thousands of operations in order to amortize the scheduling overheads. Ideally each workgroup would roughly take 100us-500us; less than that and overhead starts to dominate and more than that needs to be balanced with total count: ~200 workgroups is more than enough to hide latencies and more than that adds overhead with diminishing returns. Again doing this perfectly is hard but the heuristics are fairly well known and easy to characterize for certain classes of work: you want to spend enough time inside each workgroup to justify the overhead involved in launching it but not so much time and so few total that variance in the system can't be hidden (4 x 400ms workgroups on 3 threads will always have 400ms of work happen on one thread with the other 2 idle, or 4 x 400ms on 4 threads where 1 thread gets delayed 50ms will cause the total latency to increase 50ms, etc).

As a concrete example of a trivial case, I'd expect a 5000xf32 elementwise dispatch to run in ~1 workgroup, but today it runs in orders of magnitude more:

hal.command_buffer.dispatch<%cmd : !hal.command_buffer> target(%exe : !hal.executable)[0] workgroups([%c625, %c1, %c1])

because each workgroup processes 8 elements when using avx2:

hal.executable.variant public @embedded_elf_x86_64, target = <"llvm", "embedded-elf-x86_64", {cpu_features = "-avx512pf,-tsxldtrk,+cx16,+sahf,-tbm,-avx512ifma,+sha,+crc32,-fma4,-vpclmulqdq,+prfchw,+bmi2,-cldemote,+fsgsbase,-ptwrite,-amx-tile,-uintr,-gfni,+popcnt,-widekl,+aes,-avx512bitalg,-movdiri,+xsaves,-avx512er,-avxvnni,-avx512fp16,-avx512vnni,-amx-bf16,-avx512vpopcntdq,-pconfig,+clwb,-avx512f,+xsavec,+clzero,-pku,+mmx,-lwp,+rdpid,-xop,+rdseed,-waitpkg,-kl,-movdir64b,+sse4a,-avx512bw,+clflushopt,+xsave,-avx512vbmi2,+64bit,-avx512vl,-serialize,-hreset,-invpcid,-avx512cd,+avx,-vaes,-avx512bf16,+cx8,+fma,-rtm,+bmi,-enqcmd,+rdrnd,-mwaitx,+sse4.1,+sse4.2,+avx2,+fxsr,-wbnoinvd,+sse,+lzcnt,+pclmul,-prefetchwt1,+f16c,+ssse3,-sgx,-shstk,+cmov,-avx512vbmi,-amx-int8,+movbe,-avx512vp2intersect,+xsaveopt,-avx512dq,+sse2,+adx,+sse3", data_layout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128", native_vector_size = 32 : index, target_triple = "x86_64-unknown-unknown-eabi-elf"}> {
  hal.executable.export public @simple_mul_dispatch_0 ordinal(0) layout(#hal.executable.layout<push_constants = 0, sets = [#hal.descriptor_set.layout<0, bindings = [#hal.descriptor_set.binding<0, storage_buffer>, #hal.descriptor_set.binding<1, storage_buffer>, #hal.descriptor_set.binding<2, storage_buffer>]>]>) {translation_info = #iree_codegen.translation_info<CPUDoubleTilingExpert workload_per_wg = [8]>} {
  ^bb0(%arg0: !hal.device, %arg1: index):
    %c1 = arith.constant 1 : index
    %0 = affine.apply affine_map<()[s0] -> (s0 ceildiv 8)>()[%arg1]
    hal.return %0, %c1, %c1 : index, index, index
  }
  builtin.module {
    func.func @simple_mul_dispatch_0() {
      %c0 = arith.constant 0 : index
      %0 = hal.interface.binding.subspan set(0) binding(0) type(storage_buffer) offset(%c0) alignment(64) : memref<5000xf32>
      memref.assume_alignment %0, 64 : memref<5000xf32>
      %1 = hal.interface.binding.subspan set(0) binding(1) type(storage_buffer) offset(%c0) alignment(64) : memref<5000xf32>
      memref.assume_alignment %1, 64 : memref<5000xf32>
      %2 = hal.interface.binding.subspan set(0) binding(2) type(storage_buffer) offset(%c0) alignment(64) : memref<5000xf32>
      memref.assume_alignment %2, 64 : memref<5000xf32>
      %workgroup_id_x = hal.interface.workgroup.id[0] : index
      %3 = affine.apply affine_map<()[s0] -> (s0 * 8)>()[%workgroup_id_x]
      %4 = memref.subview %2[%3] [8] [1] : memref<5000xf32> to memref<8xf32, affine_map<(d0)[s0] -> (d0 + s0)>>
      %5 = memref.subview %0[%3] [8] [1] : memref<5000xf32> to memref<8xf32, affine_map<(d0)[s0] -> (d0 + s0)>>
      %6 = memref.subview %1[%3] [8] [1] : memref<5000xf32> to memref<8xf32, affine_map<(d0)[s0] -> (d0 + s0)>>
      %7 = vector.load %5[%c0] : memref<8xf32, affine_map<(d0)[s0] -> (d0 + s0)>>, vector<8xf32>
      %8 = vector.load %6[%c0] : memref<8xf32, affine_map<(d0)[s0] -> (d0 + s0)>>, vector<8xf32>
      %9 = arith.mulf %7, %8 : vector<8xf32>
      vector.store %9, %4[%c0] : memref<8xf32, affine_map<(d0)[s0] -> (d0 + s0)>>, vector<8xf32>
      return
    }
  }
}

At runtime this ends up being ~10000's of instructions/1000's of memory operations executed as part of scheduling work across threads, distributing to those threads, preparing bindings and other inputs for execution, jumping into the code, doing the buffer indexing, etc to then perform just 8 multiplications (likely as 1 single avx2 instruction). I tried 50000xf32 and it got up to 16 elements per workgroup and a total of 3125 workgroups. We're literally hundreds to thousands of times off from peak.

Removing the host flag and using the default x86_64 produces something only marginally better by processing 20 elements per workgroup, aarch64 will also do 20 elements, and vmvx will do 40 so ISA vector size is probably being taken into account but on its own that's not the most useful knob for distribution at the workgroup level. Inner loops nested within can be based on that but unless the ISA vector size is in the thousands of elements it shouldn't have much bearing on the workgroup counts.

Here's what to look for in traces:
image
Every gap between the workgroup invocations is 100ns to 1us, and there are other implications of this distribution as we aren't utilizing caches effectively and in many cases are actively pessimizing them as we touch partial cache lines on multiple cores concurrently (ideally each workgroup would operate on ~64B blocks at minimum; today we're doing 32/80/160 and never lining up right). I suspect this may be the cause of #9230 and it's going to be hard to make progress on that until we've at least ruled this out by distributing in at least somewhat of a reasonable way.

On the flip side, here's an example where we are putting too much work into a workgroup such that we end up with so few that we can't hide variance: we end up having up to 8ms of extra latency if any single thread takes longer than the others:
image
vs here where we have enough workgroups to cover for variances by redistributing work when those bottom two threads run a bit slower (context switch/core frequency differences/etc):
image

Steps to reproduce your issue

func.func @simple_mul(%arg0: tensor<5000xf32>, %arg1: tensor<5000xf32>) -> tensor<5000xf32> {
  %0 = "mhlo.multiply"(%arg0, %arg1) {name = "mul.1"} : (tensor<5000xf32>, tensor<5000xf32>) -> tensor<5000xf32>
  return %0 : tensor<5000xf32>
}

(on machine with avx2)

iree-compile --iree-hal-target-backends=dylib-llvm-aot --iree-llvm-target-triple=x86_64 --iree-llvm-target-cpu=host --iree-input-type=mhlo simple_mul.mlir

Activity

  1. added
    bug 🐞
    performance ⚡
    codegen/llvm
    on Jun 28, 2022
  2. hanhanW commented on Jun 29, 2022

    @hanhanW
    Contributor

    I've noticed a similar thing (esp. when the size is dim). The number of workgroups is increased because we'd like to vectorize as much kernel as possible. The dim sizes must be divisible by the tiling sizes.

    Today, we have padding and peeling support in Codegen. We're able to have smarter logic about distribution while vectorizing those kernels. I spent some time to get better codegen for element-wise dispatches in #9564, but I was distracted by other stuff. I'll pick it up again and see what we can push forward.

  3. hanhanW commented on Jun 29, 2022

    @hanhanW
    Contributor

    @dcaballe FYI, since you also looked into enabling peeling for element-wise dispatches.

  4. benvanik commented on Jun 29, 2022

    @benvanik
    CollaboratorAuthor

    The number of workgroups is increased because we'd like to vectorize as much kernel as possible. The dim sizes must be divisible by the tiling sizes.

    We want to vectorize the inner loop inside of a workgroup but not the entire workgroup itself - the workgroup size should almost always be >> the vector size and there should almost always be a loop inside as the overhead of a branch inside of a dispatch is like 1000x less than having the loop on the outside by way of workgroup ID. So, we'll need to optimize for lots of work inside of a dispatch and then that the work is vectorized, vs just that it is vectorized as today (cutting down the forest to save a single tree :).

  5. MaheshRavishankar commented on Jun 29, 2022

    @MaheshRavishankar
    Collaborator

    Yeah, I think the current heuristics (that mostly I wrote), really over indexed on the vector size. Probably need an additional factor of "minimum workgroup size" that needs to be added to the mix to avoid such cases....

  6. dcaballe commented on Jun 29, 2022

    @dcaballe
    Contributor

    From past experiences, it's really important that the workgroup size is multiple of the physical vector register, regardless of padding and peeling. If we distribute the work in chunks that are not multiple of the vector register, each thread will potentially start the computation from an iteration that is not aligned to the vector length boundary, leading to unaligned memory accesses and degrading performance. Of course, this is assuming that the tensor (and the vectorized dimension, specifically) is aligned accordingly.

  7. moved this to Done in IREEon Aug 29, 2022
  8. added a commit that references this issue on Aug 30, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

bug 🐞codegen/llvmperformance ⚡

Type

No type

Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions