Skip to content

[CPU] RoPE kernel producing incorrect results #20824

Open

Description

@IanWood1

What happened?

I'm getting incorrect results with a custom RoPE kernel when run on the CPU backend. The bug appears to only effect certain sizes/shapes (more info below).

This is impacting nod-ai/amd-shark-ai#1254 as seen in the unit test failure.

Steps to reproduce your issue

Here's a gist to help reproduce: https://gist.github.com/IanWood1/751d70791207fb6a53fd79f71fc219a6

It contains 3 files:

  1. repro.mlir: the problematic IR that produces incorrect results with the llvm-cpu backend
  2. repro2.mlir: same as repro.mlir but with a slight change to one of the dimension sizes. This IR produces correct results (maybe it will help with tracking down the problem)
  3. run.py: it will generate the inputs & expected outputs to run either repro.mlir or repro2.mlir through both iree-compile and iree-run-module

For context, the commands I used that generated incorrect results:

iree-compile repro.mlir -o out.vmfb --iree-hal-target-backends=llvm-cpu --iree-llvmcpu-target-cpu=host   

iree-run-module --module=out.vmfb [email protected] [email protected] [email protected] --device=local-task   

What component(s) does this issue relate to?

No response

Version information

cab896d

Additional context

No response

Activity

  1. added
    bug 🐞
    on May 15, 2025
  2. hanhanW commented on May 15, 2025

    @hanhanW
    Contributor

    I haven't seen complex types passed into generic ops for a while, interesting. I'll take a look at it.

    (It's so dumb that I use incognito mode every time when I need to click a shark-ai issue. :p)

  3. added
    codegen/llvm
    on May 15, 2025
  4. hanhanW commented on May 15, 2025

    @hanhanW
    Contributor

    I might know what's happening. The indexing map is too bad. It has d3 floordiv 2, and tiling should not happen in this case.

    The correct one passes just because it sets the tile size to 1, which scalarizes the dimension. It is off when the tile size is not a multiple of 2. IMO, we should not tile such dimension at all.

    #map = affine_map<(d0, d1, d2, d3) -> (d0, d1, d3)>
    #map1 = affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3 floordiv 2)>
    #map2 = affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>
    module {
      util.func public @sharktank_rotary_embedding_incorrect(%arg0: tensor<1x1x64x14xf32>, %arg1: tensor<1x1x14xf32>) -> tensor<1x1x64x14xf32> {
        %c0 = arith.constant 0 : index
        %c1 = arith.constant 1 : index
        %c2 = arith.constant 2 : index
        %c3 = arith.constant 3 : index
        %dim = tensor.dim %arg0, %c0 : tensor<1x1x64x14xf32>
        %dim_0 = tensor.dim %arg0, %c1 : tensor<1x1x64x14xf32>
        %dim_1 = tensor.dim %arg0, %c2 : tensor<1x1x64x14xf32>
        %dim_2 = tensor.dim %arg0, %c3 : tensor<1x1x64x14xf32>
        %0 = arith.divui %dim_2, %c2 : index
        %cast = tensor.cast %arg0 : tensor<1x1x64x14xf32> to tensor<?x?x?x?xf32>
        %1 = flow.tensor.bitcast %cast : tensor<?x?x?x?xf32>{%dim, %dim_0, %dim_1, %dim_2} -> tensor<?x?x?x?xcomplex<f32>>{%dim, %dim_0, %dim_1, %0}
        %2 = tensor.empty(%dim, %dim_0, %dim_1, %dim_2) : tensor<?x?x?x?xf32>
        %cast_3 = tensor.cast %2 : tensor<?x?x?x?xf32> to tensor<1x1x64x14xf32>
        %3 = linalg.generic {indexing_maps = [#map, #map1, #map2], iterator_types = ["parallel", "parallel", "parallel", "parallel"]} ins(%arg1, %1 : tensor<1x1x14xf32>, tensor<?x?x?x?xcomplex<f32>>) outs(%cast_3 : tensor<1x1x64x14xf32>) {
        ^bb0(%in: f32, %in_4: complex<f32>, %out: f32):
          %4 = linalg.index 0 : index
          %5 = linalg.index 1 : index
          %6 = linalg.index 2 : index
          %7 = linalg.index 3 : index
          %8 = arith.remui %7, %c2 : index
          %9 = math.cos %in : f32
          %10 = math.sin %in : f32
          %11 = complex.create %9, %10 : complex<f32>
          %12 = complex.mul %in_4, %11 : complex<f32>
          %13 = complex.re %12 : complex<f32>
          %14 = complex.im %12 : complex<f32>
          %15 = arith.cmpi eq, %8, %c0 : index
          %16 = arith.select %15, %13, %14 : f32
          linalg.yield %16 : f32
        } -> tensor<1x1x64x14xf32>
        util.return %3 : tensor<1x1x64x14xf32>
      }

    If what I claimed is correct, there are action items:

    1. Do not set the tile size when a result dim is not strided.
    2. Update the upstream implementation to return a failure when it is the case.

    @MaheshRavishankar Is it correct that tiling can happen only if all the result exprs are in strided form?

  5. hanhanW commented on May 15, 2025

    @hanhanW
    Contributor

    Here is a generalized convolution, and the result exprs are all in strided form.

    #map = affine_map<(d0, d1, d2, d3) -> ()>
    #map1 = affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>
    #map2 = affine_map<(d0, d1, d2, d3, d4, d5, d6) -> (d0, d1 * 2 + d4, d2 * 2 + d5, d6)>
    #map3 = affine_map<(d0, d1, d2, d3, d4, d5, d6) -> (d4, d5, d6, d3)>
    #map4 = affine_map<(d0, d1, d2, d3, d4, d5, d6) -> (d0, d1, d2, d3)>
    module {
      func.func @conv_static(%arg0: tensor<1x225x225x3xf32>, %arg1: tensor<3x3x3x16xf32>) -> tensor<1x112x112x16xf32> {
        %cst = arith.constant 0.000000e+00 : f32
        %0 = tensor.empty() : tensor<1x112x112x16xf32>
        %1 = linalg.generic {indexing_maps = [#map, #map1], iterator_types = ["parallel", "parallel", "parallel", "parallel"]} ins(%cst : f32) outs(%0 : tensor<1x112x112x16xf32>) {
        ^bb0(%in: f32, %out: f32):
          linalg.yield %in : f32
        } -> tensor<1x112x112x16xf32>
        %2 = linalg.generic {indexing_maps = [#map2, #map3, #map4], iterator_types = ["parallel", "parallel", "parallel", "parallel", "reduction", "reduction", "reduction"]} ins(%arg0, %arg1 : tensor<1x225x225x3xf32>, tensor<3x3x3x16xf32>) outs(%1 : tensor<
    1x112x112x16xf32>) {
        ^bb0(%in: f32, %in_0: f32, %out: f32):
          %3 = arith.mulf %in, %in_0 : f32
          %4 = arith.addf %out, %3 : f32
          linalg.yield %4 : f32
        } -> tensor<1x112x112x16xf32>
        return %2 : tensor<1x112x112x16xf32>
      }
    }
    
  6. MaheshRavishankar commented on May 15, 2025

    @MaheshRavishankar
    Collaborator

    Huh, I didnt realize that tiling is off. It is not immediately obvious to me why though. AFAICS you should still be able to tile this generic op even if floordiv exists...

  7. hanhanW commented on May 15, 2025

    @hanhanW
    Contributor

    I need to think more about it. It is not obvious to me how tiling works if there is floordiv. I can only understand the tiling when exprs are in strided form I think. Even for strided form, I'm only like 80% sure. I need to write things down to help me think.

  8. MaheshRavishankar commented on May 15, 2025

    @MaheshRavishankar
    Collaborator

    if you have the IR, could you post the IR before and after tiling

  9. hanhanW commented on May 15, 2025

    @hanhanW
    Contributor

    Yes, I have the IR. Here is the IR before and after scf.forall distrubution and first level of scf.for tiling: https://gist.githubusercontent.com/hanhanW/c0249ba70bd9e05f037dbacaff1b59b4/raw/19cf910e1bd69736e7c59cf386fd8381f5c2c057/dump.mlir

    Inlined:

    // -----// IR Dump After LLVMCPUSelectLoweringStrategyPass (iree-llvmcpu-select-lowering-strategy) //----- //
    module {
      func.func @sharktank_rotary_embedding_incorrect_dispatch_0_generic_Dx14_f32xcomplex_f32_xf32() attributes {translation_info = #iree_codegen.translation_info<pipeline = CPUDoubleTilingExpert, {enable_loop_peeling}>} {
        %c7 = arith.constant 7 : index
        %c64 = arith.constant 64 : index
        %c1 = arith.constant 1 : index
        %c0 = arith.constant 0 : index
        %c2 = arith.constant 2 : index
        %0 = hal.interface.binding.subspan layout(<bindings = [#hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, Indirect>], flags = Indirect>) binding(0) alignment(64) offset(%c0) flags("ReadOnly|Indirect") : !iree_tensor_ext.dispatch.tensor<readonly:tensor<14xf32>>
        %1 = hal.interface.binding.subspan layout(<bindings = [#hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, Indirect>], flags = Indirect>) binding(2) alignment(64) offset(%c0) flags(Indirect) : !iree_tensor_ext.dispatch.tensor<writeonly:tensor<64x14xf32>>
        %2 = hal.interface.binding.subspan layout(<bindings = [#hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, Indirect>], flags = Indirect>) binding(1) alignment(64) offset(%c0) flags("ReadOnly|Indirect") : !iree_tensor_ext.dispatch.tensor<readonly:tensor<?x?x?x?xcomplex<f32>>>{%c1, %c1, %c64, %c7}
        %3 = iree_tensor_ext.dispatch.tensor.load %0, offsets = [0], sizes = [14], strides = [1] : !iree_tensor_ext.dispatch.tensor<readonly:tensor<14xf32>> -> tensor<14xf32>
        %4 = iree_tensor_ext.dispatch.tensor.load %2, offsets = [0, 0, 0, 0], sizes = [1, 1, 64, 7], strides = [1, 1, 1, 1] : !iree_tensor_ext.dispatch.tensor<readonly:tensor<?x?x?x?xcomplex<f32>>>{%c1, %c1, %c64, %c7} -> tensor<1x1x64x7xcomplex<f32>>
        %5 = tensor.empty() : tensor<64x14xf32>
        %6 = linalg.generic {indexing_maps = [affine_map<(d0, d1) -> (d1)>, affine_map<(d0, d1) -> (0, 0, d0, d1 floordiv 2)>, affine_map<(d0, d1) -> (d0, d1)>], iterator_types = ["parallel", "parallel"]} ins(%3, %4 : tensor<14xf32>, tensor<1x1x64x7xcomplex<f32>>) outs(%5 : tensor<64x14xf32>) attrs =  {lowering_config = #iree_codegen.lowering_config<tile_sizes = [[8, 7], [1, 7], [0, 0], [0, 0]]>} {
        ^bb0(%in: f32, %in_0: complex<f32>, %out: f32):
          %7 = linalg.index 1 : index
          %8 = arith.remui %7, %c2 : index
          %9 = math.cos %in : f32
          %10 = math.sin %in : f32
          %11 = complex.create %9, %10 : complex<f32>
          %12 = complex.mul %in_0, %11 : complex<f32>
          %13 = complex.re %12 : complex<f32>
          %14 = complex.im %12 : complex<f32>
          %15 = arith.cmpi eq, %8, %c0 : index
          %16 = arith.select %15, %13, %14 : f32
          linalg.yield %16 : f32
        } -> tensor<64x14xf32>
        iree_tensor_ext.dispatch.tensor.store %6, %1, offsets = [0, 0], sizes = [64, 14], strides = [1, 1] : tensor<64x14xf32> -> !iree_tensor_ext.dispatch.tensor<writeonly:tensor<64x14xf32>>
        return
      }
    }
    
    // -----// IR Dump After TileAndDistributeToWorkgroupsUsingForallOpPass (iree-codegen-tile-and-distribute-to-workgroups-using-forall-op) //----- //
    func.func @sharktank_rotary_embedding_incorrect_dispatch_0_generic_Dx14_f32xcomplex_f32_xf32() attributes {translation_info = #iree_codegen.translation_info<pipeline = CPUDoubleTilingExpert, {enable_loop_peeling}>} {
      %c7 = arith.constant 7 : index
      %c64 = arith.constant 64 : index
      %c1 = arith.constant 1 : index
      %c0 = arith.constant 0 : index
      %c2 = arith.constant 2 : index
      %0 = hal.interface.binding.subspan layout(<bindings = [#hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, Indirect>], flags = Indirect>) binding(0) alignment(64) offset(%c0) flags("ReadOnly|Indirect") : !iree_tensor_ext.dispatch.tensor<readonly:tensor<14xf32>>
      %1 = hal.interface.binding.subspan layout(<bindings = [#hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, Indirect>], flags = Indirect>) binding(2) alignment(64) offset(%c0) flags(Indirect) : !iree_tensor_ext.dispatch.tensor<writeonly:tensor<64x14xf32>>
      %2 = hal.interface.binding.subspan layout(<bindings = [#hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, Indirect>], flags = Indirect>) binding(1) alignment(64) offset(%c0) flags("ReadOnly|Indirect") : !iree_tensor_ext.dispatch.tensor<readonly:tensor<?x?x?x?xcomplex<f32>>>{%c1, %c1, %c64, %c7}
      %3 = iree_tensor_ext.dispatch.tensor.load %0, offsets = [0], sizes = [14], strides = [1] : !iree_tensor_ext.dispatch.tensor<readonly:tensor<14xf32>> -> tensor<14xf32>
      %4 = iree_tensor_ext.dispatch.tensor.load %2, offsets = [0, 0, 0, 0], sizes = [1, 1, 64, 7], strides = [1, 1, 1, 1] : !iree_tensor_ext.dispatch.tensor<readonly:tensor<?x?x?x?xcomplex<f32>>>{%c1, %c1, %c64, %c7} -> tensor<1x1x64x7xcomplex<f32>>
      %5 = tensor.empty() : tensor<64x14xf32>
      %6 = scf.forall (%arg0, %arg1) = (0, 0) to (64, 14) step (8, 7) shared_outs(%arg2 = %5) -> (tensor<64x14xf32>) {
        %7 = affine.apply affine_map<(d0) -> (d0 floordiv 2)>(%arg1)
        %extracted_slice = tensor.extract_slice %3[%arg1] [7] [1] : tensor<14xf32> to tensor<7xf32>
        %extracted_slice_0 = tensor.extract_slice %4[0, 0, %arg0, %7] [1, 1, 8, 4] [1, 1, 1, 1] : tensor<1x1x64x7xcomplex<f32>> to tensor<1x1x8x4xcomplex<f32>>
        %extracted_slice_1 = tensor.extract_slice %arg2[%arg0, %arg1] [8, 7] [1, 1] : tensor<64x14xf32> to tensor<8x7xf32>
        %8 = linalg.generic {indexing_maps = [affine_map<(d0, d1) -> (d1)>, affine_map<(d0, d1) -> (0, 0, d0, d1 floordiv 2)>, affine_map<(d0, d1) -> (d0, d1)>], iterator_types = ["parallel", "parallel"]} ins(%extracted_slice, %extracted_slice_0 : tensor<7xf32>, tensor<1x1x8x4xcomplex<f32>>) outs(%extracted_slice_1 : tensor<8x7xf32>) attrs =  {lowering_config = #iree_codegen.lowering_config<tile_sizes = [[8, 7], [1, 7], [0, 0], [0, 0]]>} {
        ^bb0(%in: f32, %in_2: complex<f32>, %out: f32):
          %9 = linalg.index 1 : index
          %10 = affine.apply affine_map<(d0)[s0] -> (d0 + s0)>(%arg1)[%9]
          %11 = arith.remui %10, %c2 : index
          %12 = math.cos %in : f32
          %13 = math.sin %in : f32
          %14 = complex.create %12, %13 : complex<f32>
          %15 = complex.mul %in_2, %14 : complex<f32>
          %16 = complex.re %15 : complex<f32>
          %17 = complex.im %15 : complex<f32>
          %18 = arith.cmpi eq, %11, %c0 : index
          %19 = arith.select %18, %16, %17 : f32
          linalg.yield %19 : f32
        } -> tensor<8x7xf32>
        scf.forall.in_parallel {
          tensor.parallel_insert_slice %8 into %arg2[%arg0, %arg1] [8, 7] [1, 1] : tensor<8x7xf32> into tensor<64x14xf32>
        }
      } {mapping = [#iree_codegen.workgroup_mapping<y>, #iree_codegen.workgroup_mapping<x>]}
      iree_tensor_ext.dispatch.tensor.store %6, %1, offsets = [0, 0], sizes = [64, 14], strides = [1, 1] : tensor<64x14xf32> -> !iree_tensor_ext.dispatch.tensor<writeonly:tensor<64x14xf32>>
      return
    }
    
    
    
    // -----// IR Dump After LLVMCPUTileAndFusePass (iree-llvmcpu-tile-and-fuse) //----- //
    func.func @sharktank_rotary_embedding_incorrect_dispatch_0_generic_Dx14_f32xcomplex_f32_xf32() attributes {translation_info = #iree_codegen.translation_info<pipeline = CPUDoubleTilingExpert, {enable_loop_peeling}>} {
      %c8 = arith.constant 8 : index
      %c7 = arith.constant 7 : index
      %c64 = arith.constant 64 : index
      %c1 = arith.constant 1 : index
      %c0 = arith.constant 0 : index
      %c2 = arith.constant 2 : index
      %0 = hal.interface.binding.subspan layout(<bindings = [#hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, Indirect>], flags = Indirect>) binding(0) alignment(64) offset(%c0) flags("ReadOnly|Indirect") : !iree_tensor_ext.dispatch.tensor<readonly:tensor<14xf32>>
      %1 = hal.interface.binding.subspan layout(<bindings = [#hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, Indirect>], flags = Indirect>) binding(2) alignment(64) offset(%c0) flags(Indirect) : !iree_tensor_ext.dispatch.tensor<writeonly:tensor<64x14xf32>>
      %2 = hal.interface.binding.subspan layout(<bindings = [#hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, Indirect>], flags = Indirect>) binding(1) alignment(64) offset(%c0) flags("ReadOnly|Indirect") : !iree_tensor_ext.dispatch.tensor<readonly:tensor<?x?x?x?xcomplex<f32>>>{%c1, %c1, %c64, %c7}
      %3 = iree_tensor_ext.dispatch.tensor.load %0, offsets = [0], sizes = [14], strides = [1] : !iree_tensor_ext.dispatch.tensor<readonly:tensor<14xf32>> -> tensor<14xf32>
      %4 = iree_tensor_ext.dispatch.tensor.load %2, offsets = [0, 0, 0, 0], sizes = [1, 1, 64, 7], strides = [1, 1, 1, 1] : !iree_tensor_ext.dispatch.tensor<readonly:tensor<?x?x?x?xcomplex<f32>>>{%c1, %c1, %c64, %c7} -> tensor<1x1x64x7xcomplex<f32>>
      %5 = tensor.empty() : tensor<64x14xf32>
      %6 = scf.forall (%arg0, %arg1) = (0, 0) to (64, 14) step (8, 7) shared_outs(%arg2 = %5) -> (tensor<64x14xf32>) {
        %7 = affine.apply affine_map<(d0) -> (d0 floordiv 2)>(%arg1)
        %extracted_slice = tensor.extract_slice %3[%arg1] [7] [1] : tensor<14xf32> to tensor<7xf32>
        %extracted_slice_0 = tensor.extract_slice %4[0, 0, %arg0, %7] [1, 1, 8, 4] [1, 1, 1, 1] : tensor<1x1x64x7xcomplex<f32>> to tensor<1x1x8x4xcomplex<f32>>
        %extracted_slice_1 = tensor.extract_slice %arg2[%arg0, %arg1] [8, 7] [1, 1] : tensor<64x14xf32> to tensor<8x7xf32>
        %8 = scf.for %arg3 = %c0 to %c8 step %c1 iter_args(%arg4 = %extracted_slice_1) -> (tensor<8x7xf32>) {
          %extracted_slice_2 = tensor.extract_slice %extracted_slice_0[0, 0, %arg3, 0] [1, 1, 1, 4] [1, 1, 1, 1] : tensor<1x1x8x4xcomplex<f32>> to tensor<1x1x1x4xcomplex<f32>>
          %extracted_slice_3 = tensor.extract_slice %arg4[%arg3, 0] [1, 7] [1, 1] : tensor<8x7xf32> to tensor<1x7xf32>
          %9 = linalg.generic {indexing_maps = [affine_map<(d0, d1) -> (d1)>, affine_map<(d0, d1) -> (0, 0, d0, d1 floordiv 2)>, affine_map<(d0, d1) -> (d0, d1)>], iterator_types = ["parallel", "parallel"]} ins(%extracted_slice, %extracted_slice_2 : tensor<7xf32>, tensor<1x1x1x4xcomplex<f32>>) outs(%extracted_slice_3 : tensor<1x7xf32>) attrs =  {lowering_config = #iree_codegen.lowering_config<tile_sizes = [[8, 7], [1, 7], [0, 0], [0, 0]]>} {
          ^bb0(%in: f32, %in_4: complex<f32>, %out: f32):
            %10 = linalg.index 1 : index
            %11 = affine.apply affine_map<(d0)[s0] -> (d0 + s0)>(%arg1)[%10]
            %12 = arith.remui %11, %c2 : index
            %13 = math.cos %in : f32
            %14 = math.sin %in : f32
            %15 = complex.create %13, %14 : complex<f32>
            %16 = complex.mul %in_4, %15 : complex<f32>
            %17 = complex.re %16 : complex<f32>
            %18 = complex.im %16 : complex<f32>
            %19 = arith.cmpi eq, %12, %c0 : index
            %20 = arith.select %19, %17, %18 : f32
            linalg.yield %20 : f32
          } -> tensor<1x7xf32>
          %inserted_slice = tensor.insert_slice %9 into %arg4[%arg3, 0] [1, 7] [1, 1] : tensor<1x7xf32> into tensor<8x7xf32>
          scf.yield %inserted_slice : tensor<8x7xf32>
        }
        scf.forall.in_parallel {
          tensor.parallel_insert_slice %8 into %arg2[%arg0, %arg1] [8, 7] [1, 1] : tensor<8x7xf32> into tensor<64x14xf32>
        }
      } {mapping = [#iree_codegen.workgroup_mapping<y>, #iree_codegen.workgroup_mapping<x>]}
      iree_tensor_ext.dispatch.tensor.store %6, %1, offsets = [0, 0], sizes = [64, 14], strides = [1, 1] : tensor<64x14xf32> -> !iree_tensor_ext.dispatch.tensor<writeonly:tensor<64x14xf32>>
      return
    }
  10. hanhanW commented on May 15, 2025

    @hanhanW
    Contributor

    Putting a note here: I did not know that GPU produces correct output. It does not tile the dimension because the lowering config is [1, 128].

  11. hanhanW commented on May 16, 2025

    @hanhanW
    Contributor

    Here is the IR without distribution and setting the tile size to [0, 7]: https://gist.github.com/hanhanW/cb7686911e4541fe4837daf1ccb1eb36

    // -----// IR Dump After PropagateDispatchSizeBoundsPass (iree-codegen-propagate-dispatch-size-bounds) //----- //
    func.func @sharktank_rotary_embedding_incorrect_dispatch_0_generic_Dx14_f32xcomplex_f32_xf32() attributes {translation_info = #iree_codegen.translation_info<pipeline = CPUDoubleTilingExpert, {enable_loop_peeling}>} {
      %c7 = arith.constant 7 : index
      %c64 = arith.constant 64 : index
      %c1 = arith.constant 1 : index
      %c0 = arith.constant 0 : index
      %c2 = arith.constant 2 : index
      %0 = hal.interface.binding.subspan layout(<bindings = [#hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, Indirect>], flags = Indirect>) binding(0) alignment(64) offset(%c0) flags("ReadOnly|Indirect") : !iree_tensor_ext.dispatch.tensor<readonly:tensor<14xf32>>
      %1 = hal.interface.binding.subspan layout(<bindings = [#hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, Indirect>], flags = Indirect>) binding(2) alignment(64) offset(%c0) flags(Indirect) : !iree_tensor_ext.dispatch.tensor<writeonly:tensor<64x14xf32>>
      %2 = hal.interface.binding.subspan layout(<bindings = [#hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, Indirect>], flags = Indirect>) binding(1) alignment(64) offset(%c0) flags("ReadOnly|Indirect") : !iree_tensor_ext.dispatch.tensor<readonly:tensor<?x?x?x?xcomplex<f32>>>{%c1, %c1, %c64, %c7}
      %3 = iree_tensor_ext.dispatch.tensor.load %0, offsets = [0], sizes = [14], strides = [1] : !iree_tensor_ext.dispatch.tensor<readonly:tensor<14xf32>> -> tensor<14xf32>
      %4 = iree_tensor_ext.dispatch.tensor.load %2, offsets = [0, 0, 0, 0], sizes = [1, 1, 64, 7], strides = [1, 1, 1, 1] : !iree_tensor_ext.dispatch.tensor<readonly:tensor<?x?x?x?xcomplex<f32>>>{%c1, %c1, %c64, %c7} -> tensor<1x1x64x7xcomplex<f32>>
      %5 = tensor.empty() : tensor<64x14xf32>
      %6 = linalg.generic {indexing_maps = [affine_map<(d0, d1) -> (d1)>, affine_map<(d0, d1) -> (0, 0, d0, d1 floordiv 2)>, affine_map<(d0, d1) -> (d0, d1)>], iterator_types = ["parallel", "parallel"]} ins(%3, %4 : tensor<14xf32>, tensor<1x1x64x7xcomplex<f32>>) outs(%5 : tensor<64x14xf32>) attrs =  {lowering_config = #iree_codegen.lowering_config<tile_sizes = [[0, 0], [0, 7], [0, 0], [0, 0]]>} {
      ^bb0(%in: f32, %in_0: complex<f32>, %out: f32):
        %7 = linalg.index 1 : index
        %8 = arith.remui %7, %c2 : index
        %9 = math.cos %in : f32
        %10 = math.sin %in : f32
        %11 = complex.create %9, %10 : complex<f32>
        %12 = complex.mul %in_0, %11 : complex<f32>
        %13 = complex.re %12 : complex<f32>
        %14 = complex.im %12 : complex<f32>
        %15 = arith.cmpi eq, %8, %c0 : index
        %16 = arith.select %15, %13, %14 : f32
        linalg.yield %16 : f32
      } -> tensor<64x14xf32>
      iree_tensor_ext.dispatch.tensor.store %6, %1, offsets = [0, 0], sizes = [64, 14], strides = [1, 1] : tensor<64x14xf32> -> !iree_tensor_ext.dispatch.tensor<writeonly:tensor<64x14xf32>>
      return
    }
    
    // -----// IR Dump After LLVMCPUTileAndFusePass (iree-llvmcpu-tile-and-fuse) //----- //
    func.func @sharktank_rotary_embedding_incorrect_dispatch_0_generic_Dx14_f32xcomplex_f32_xf32() attributes {translation_info = #iree_codegen.translation_info<pipeline = CPUDoubleTilingExpert, {enable_loop_peeling}>} {
      %c14 = arith.constant 14 : index
      %c7 = arith.constant 7 : index
      %c64 = arith.constant 64 : index
      %c1 = arith.constant 1 : index
      %c0 = arith.constant 0 : index
      %c2 = arith.constant 2 : index
      %0 = hal.interface.binding.subspan layout(<bindings = [#hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, Indirect>], flags = Indirect>) binding(0) alignment(64) offset(%c0) flags("ReadOnly|Indirect") : !iree_tensor_ext.dispatch.tensor<readonly:tensor<14xf32>>
      %1 = hal.interface.binding.subspan layout(<bindings = [#hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, Indirect>], flags = Indirect>) binding(2) alignment(64) offset(%c0) flags(Indirect) : !iree_tensor_ext.dispatch.tensor<writeonly:tensor<64x14xf32>>
      %2 = hal.interface.binding.subspan layout(<bindings = [#hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, "ReadOnly|Indirect">, #hal.pipeline.binding<storage_buffer, Indirect>], flags = Indirect>) binding(1) alignment(64) offset(%c0) flags("ReadOnly|Indirect") : !iree_tensor_ext.dispatch.tensor<readonly:tensor<?x?x?x?xcomplex<f32>>>{%c1, %c1, %c64, %c7}
      %3 = iree_tensor_ext.dispatch.tensor.load %0, offsets = [0], sizes = [14], strides = [1] : !iree_tensor_ext.dispatch.tensor<readonly:tensor<14xf32>> -> tensor<14xf32>
      %4 = iree_tensor_ext.dispatch.tensor.load %2, offsets = [0, 0, 0, 0], sizes = [1, 1, 64, 7], strides = [1, 1, 1, 1] : !iree_tensor_ext.dispatch.tensor<readonly:tensor<?x?x?x?xcomplex<f32>>>{%c1, %c1, %c64, %c7} -> tensor<1x1x64x7xcomplex<f32>>
      %5 = tensor.empty() : tensor<64x14xf32>
      %6 = scf.for %arg0 = %c0 to %c14 step %c7 iter_args(%arg1 = %5) -> (tensor<64x14xf32>) {
        %7 = affine.apply affine_map<(d0) -> (d0 floordiv 2)>(%arg0)
        %extracted_slice = tensor.extract_slice %3[%arg0] [7] [1] : tensor<14xf32> to tensor<7xf32>
        %extracted_slice_0 = tensor.extract_slice %4[0, 0, 0, %7] [1, 1, 64, 4] [1, 1, 1, 1] : tensor<1x1x64x7xcomplex<f32>> to tensor<1x1x64x4xcomplex<f32>>
        %extracted_slice_1 = tensor.extract_slice %arg1[0, %arg0] [64, 7] [1, 1] : tensor<64x14xf32> to tensor<64x7xf32>
        %8 = linalg.generic {indexing_maps = [affine_map<(d0, d1) -> (d1)>, affine_map<(d0, d1) -> (0, 0, d0, d1 floordiv 2)>, affine_map<(d0, d1) -> (d0, d1)>], iterator_types = ["parallel", "parallel"]} ins(%extracted_slice, %extracted_slice_0 : tensor<7xf32>, tensor<1x1x64x4xcomplex<f32>>) outs(%extracted_slice_1 : tensor<64x7xf32>) attrs =  {lowering_config = #iree_codegen.lowering_config<tile_sizes = [[0, 0], [0, 7], [0, 0], [0, 0]]>} {
        ^bb0(%in: f32, %in_2: complex<f32>, %out: f32):
          %9 = linalg.index 1 : index
          %10 = affine.apply affine_map<(d0)[s0] -> (d0 + s0)>(%arg0)[%9]
          %11 = arith.remui %10, %c2 : index
          %12 = math.cos %in : f32
          %13 = math.sin %in : f32
          %14 = complex.create %12, %13 : complex<f32>
          %15 = complex.mul %in_2, %14 : complex<f32>
          %16 = complex.re %15 : complex<f32>
          %17 = complex.im %15 : complex<f32>
          %18 = arith.cmpi eq, %11, %c0 : index
          %19 = arith.select %18, %16, %17 : f32
          linalg.yield %19 : f32
        } -> tensor<64x7xf32>
        %inserted_slice = tensor.insert_slice %8 into %arg1[0, %arg0] [64, 7] [1, 1] : tensor<64x7xf32> into tensor<64x14xf32>
        scf.yield %inserted_slice : tensor<64x14xf32>
      }
      iree_tensor_ext.dispatch.tensor.store %6, %1, offsets = [0, 0], sizes = [64, 14], strides = [1, 1] : tensor<64x14xf32> -> !iree_tensor_ext.dispatch.tensor<writeonly:tensor<64x14xf32>>
      return
    }
  12. hanhanW commented on May 16, 2025

    @hanhanW
    Contributor

    Mirroring the discussion between @MaheshRavishankar and me to the issue:

    Okay, I think the tiling should not happen in this type of generic op. Reason:

    The indexing formula is f(x) = x / 2. (floordiv)

    The original indexing mapping is

    Idx: 0 1 2 3 4 5 6 | 7 8 9 10 11 12 13
    Div: 0 0 1 1 2 2 3 | 3 4 4 5 5 6 6
    

    If the tile size is 7, we get two slices. The | is the boundary of two slices.

    The offsets are not taken into account, so it produces (0 0 1 1 2 2 3) in the second slice. The correct version should be something like (0 1 1 2 2 3 3).

    This is why I think tiling can not be supported in this generic op. We are missing a symbol (which represents the offset) in the affine map.

    Does it make sense?

    I can't give a formal definition of what kind of generic ops can be tiled atm, but I'll provide a fix tomorrow.

    For now, my feeling is that we can not tile the ops when div or mod is involved in any of affine map. (There are exceptions, but it is not easy to identify the case. E.g., for this op, we can tile d0, but not d1.)

  13. MaheshRavishankar commented on May 16, 2025

    @MaheshRavishankar
    Collaborator

    Mirroring the discussion between @MaheshRavishankar and me to the issue:

    Okay, I think the tiling should not happen in this type of generic op. Reason:

    The indexing formula is f(x) = x / 2. (floordiv)

    The original indexing mapping is

    Idx: 0 1 2 3 4 5 6 | 7 8 9 10 11 12 13
    Div: 0 0 1 1 2 2 3 | 3 4 4 5 5 6 6
    

    If the tile size is 7, we get two slices. The | is the boundary of two slices.

    The offsets are not taken into account, so it produces (0 0 1 1 2 2 3) in the second slice. The correct version should be something like (0 1 1 2 2 3 3).

    This is why I think tiling can not be supported in this generic op. We are missing a symbol (which represents the offset) in the affine map.

    Does it make sense?

    I can't give a formal definition of what kind of generic ops can be tiled atm, but I'll provide a fix tomorrow.

    For now, my feeling is that we can not tile the ops when div or mod is involved in any of affine map. (There are exceptions, but it is not easy to identify the case. E.g., for this op, we can tile d0, but not d1.)

    Thanks Hanhan,

    I think its a matter of adjust the indexing maps produced while computing the slice offsets and sizes. I dont know what the math looks like though, but I think there is a closed form solution here. Basically the offset computation generation for Linalg ops needs to include "some extra math" to compute the right offset.

    Time to pick up a linear algebra book.

  14. hanhanW commented on May 16, 2025

    @hanhanW
    Contributor

    Yeah, that would need some more eyes, and I'm happy to help with this! This kind of work is always fun. (I'm also happy that we are not just looking for a workaround.)

    For now, do we disable the tiling for some dimensions, which makes it function? If the op is a root op, it is easier. If not, we need to track the SSA chain and make the decision. It is doable, it is just a little more complicated.

    The workaround in my mind is to enhance the LinalgOpInfo to carry such information, and we force some tile sizes to 0 when it identifies the case.

    class LinalgOpInfo {
    public:
    /// Returns true if a map represents a chosen transpose granularity.
    using TransposeMapFilter = std::function<bool(AffineMap map)>;
    LinalgOpInfo(linalg::LinalgOp linalgOp);
    LinalgOpInfo(linalg::LinalgOp linalgOp,
    TransposeMapFilter transposeMapFilter);
    bool isTranspose() const { return !transposeOperands.empty(); }
    bool isReduction() const { return reductionTrait; }
    bool isDynamic() const { return dynamicTrait; }
    ArrayRef<OpOperand *> getTransposeOperands() const {
    return transposeOperands;
    }
    private:
    void computeInfo(linalg::LinalgOp);
    TransposeMapFilter transposeMapFilter;
    bool reductionTrait;
    bool dynamicTrait;
    SmallVector<OpOperand *> transposeOperands;
    };

  15. IanWood1 commented on May 16, 2025

    @IanWood1
    MemberAuthor

    For now, do we disable the tiling for some dimensions, which makes it function? If the op is a root op, it is easier.

    For some context, I think this would unblock the shark-ai PR. All the dispatches have this op as the root

    Basically the offset computation generation for Linalg ops needs to include "some extra math" to compute the right offset.

    I don't think adjusting the offsets alone is enough. I'm not too familiar with tiling but this is my reasoning:

    Using Hanhan's example, we need the first tile to be (0 0 1 1 2 2 3) and the second to be (0 1 1 2 2 3 3). If the affine map is f(x) = x floordiv 2 an offset N has the effect of f(x) = (x floordiv 2) + N. This means we must transform the first sequence into the second sequence with only N as a parameter (shift the sequence left by 1). But this transformation only works if the function is affine: f(x) = ax+b could be shifted by subtracting a. However, since f(x) is not affine this appears impossible.

    What we really need (but I don't think it works) is for the first map to be x floordiv 2 and the second to be (x + 1) floordiv 2

  16. hanhanW commented on May 19, 2025

    @hanhanW
    Contributor

    Smaller repro: iree-compile --iree-hal-target-device=local --iree-hal-local-target-device-backends=llvm-cpu --iree-llvmcpu-target-cpu=host ~/repro.mlir

    #compilation0 = #iree_codegen.compilation_info<
        lowering_config = #iree_codegen.lowering_config<tile_sizes = [[0], [7], [0], [0]]>,
        translation_info = #iree_codegen.translation_info<pipeline = CPUDoubleTilingExpert>>
    func.func @floor_div(%src: tensor<7xf32>) -> tensor<14xf32> {
      %dest = tensor.empty() : tensor<14xf32>
      %0 = linalg.generic {
          indexing_maps = [affine_map<(d0) -> (d0 floordiv 2)>,
                           affine_map<(d0) -> (d0)>],
          iterator_types = ["parallel"],
          compilation_info = #compilation0
        }
        ins(%src: tensor<7xf32>)
        outs(%dest: tensor<14xf32>) {
        ^bb0(%in: f32, %out: f32):
          linalg.yield %in : f32
      } -> tensor<14xf32>
      return %0 : tensor<14xf32>
    }

    Output: 14xf32=0 0 1 1 2 2 3 3 3 4 4 5 5 6

    Expected output: 14xf32=0 0 1 1 2 2 3 3 4 4 5 5 6 6.

    (You can replace 7 with 0 in the lowering_config, which disables the tiling. It generates the expected output.)

  17. hanhanW commented on May 19, 2025

    @hanhanW
    Contributor

    Repro for tiling result: iree-opt --transform-interpreter ~/repro.mlir

    func.func @floor_div(%src: tensor<7xf32>) -> tensor<14xf32> {
      %dest = tensor.empty() : tensor<14xf32>
      %0 = linalg.generic {
          indexing_maps = [affine_map<(d0) -> (d0 floordiv 2)>,
                           affine_map<(d0) -> (d0)>],
          iterator_types = ["parallel"]
        }
        ins(%src: tensor<7xf32>)
        outs(%dest: tensor<14xf32>) {
        ^bb0(%in: f32, %out: f32):
          linalg.yield %in : f32
      } -> tensor<14xf32>
      return %0 : tensor<14xf32>
    }
    
    module attributes {transform.with_named_sequence} {
      transform.named_sequence @__transform_main(%arg1: !transform.any_op {transform.readonly}) {
        %0 = transform.structured.match ops{["linalg.generic"]} in %arg1 : (!transform.any_op) -> !transform.any_op
        %1, %loops = transform.structured.tile_using_for %0 tile_sizes [7] : (!transform.any_op) -> (!transform.any_op, !transform.any_op)
        transform.yield
      }
    }

    Output:

    #map = affine_map<(d0) -> (d0 floordiv 2)>
    #map1 = affine_map<(d0) -> (d0)>
    func.func @floor_div(%arg0: tensor<7xf32>) -> tensor<14xf32> {
      %0 = tensor.empty() : tensor<14xf32>
      %c0 = arith.constant 0 : index
      %c14 = arith.constant 14 : index
      %c7 = arith.constant 7 : index
      %1 = scf.for %arg1 = %c0 to %c14 step %c7 iter_args(%arg2 = %0) -> (tensor<14xf32>) {
        %2 = affine.apply #map(%arg1)
        %extracted_slice = tensor.extract_slice %arg0[%2] [4] [1] : tensor<7xf32> to tensor<4xf32>
        %extracted_slice_0 = tensor.extract_slice %arg2[%arg1] [7] [1] : tensor<14xf32> to tensor<7xf32>
        %3 = linalg.generic {indexing_maps = [#map, #map1], iterator_types = ["parallel"]} ins(%extracted_slice : tensor<4xf32>) outs(%extracted_slice_0 : tensor<7xf32>) {
        ^bb0(%in: f32, %out: f32):
          linalg.yield %in : f32
        } -> tensor<7xf32>
        %inserted_slice = tensor.insert_slice %3 into %arg2[%arg1] [7] [1] : tensor<7xf32> into tensor<14xf32>
        scf.yield %inserted_slice : tensor<14xf32>
      }
      return %1 : tensor<14xf32>
    }

    (I haven't figured out the expected output.)

  18. MaheshRavishankar commented on May 19, 2025

    @MaheshRavishankar
    Collaborator

    I havent figured it out yet, but just posting my starting point to ese if that helps. Going back to basics, lets start with a loop and any function of the induction variable used for accessing into some memory.

    for (i = 0; i < N ; ++i) {
      index = f(i);
    }
    

    f could be any arbitrary function, but lets put a constraint that f isnt "strided", i.e that the set of all index values is contiguous.

    Now tiling this loop by tile size t is

    for (i = 0; i < N ; i += t) {
      for (i0 = i; i0 < affine_min(t, N - i); i0 += t) {
         index = f(i0)
       } 
    }
    

    This is basically what we do in linalg tiling

    for (i = 0; i < N ; i += t) {
      i0_start = i
      i0_end = affine_min(t, N - i) // This is "exclusive" limit, i.e i0_end is 1 past the last value of `i0`.
      index_start = f(i0_start)
      index_end = f(i0_end - 1) + 1 // the +1 at the end makes index_end "exclusive" limit of `index`
      slice_offset = index_start
      slice_size = index_end - index_start.
    }
    

    In our case, f(i) is just floorDiv(i, k) where k is some constant. The logic above should still hold. I am not sure why it is not.

  19. hanhanW commented on May 20, 2025

    @hanhanW
    Contributor

    Leaving a note for the discussion that @MaheshRavishankar, @IanWood1 and I had in offline.

    The floorDiv case is tricky, and it is broken atm. We don't have a robust and easy solution, atm. The tile sizes can only be multiple of divisor in current tiling implementation. In this example, the tile size of d1 must be a multiple of 2.

    Next steps:

    • Update upstream to return a failure when floorDiv is present and the tile size is not valid. Also need to return a failure if mod is present. This prevents miscompiling the code.
    • Force the tile sizes to be multiple of divisors in CPU backend. This makes CPU codegen work reasonably.
    • Do the same thing for GPU and switch it to TileAndFuse pipeline.
  20. hanhanW commented on May 20, 2025

    @hanhanW
    Contributor

    I forgot a note, the tile size can also be 1, which is basically scalarize the generic op.

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

Metadata

Metadata

Assignees

Labels

bug 🐞codegen/llvm

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions