Skip to content

Incorrect numerical results in stablehlo.reverse #23637

Closed

Description

@pstarkcdpr

What happened?

I have a model where a call to stablehlo.reverse gives very wrong answers. Instead of reversing elements in a tensor, it generates new values that aren't in the original tensor. This doesn't look like a direct issue with that operation, however, since it works on its own; it only fails based on what happened before it.

Here is a simple excerpt (constants removed to keep things brief, full MLIR files are attached). The following works:

    %1 = stablehlo.constant dense<...> : tensor<50x2x16xf32>
    %2 = stablehlo.reverse %1, dims = [1] : tensor<50x2x16xf32>

However, if there are previous operations

    %cst = stablehlo.constant dense<...> : tensor<50x3x32xf32>
    %cst_0 = stablehlo.constant dense<...> : tensor<50x6x16xf32>
    %c = stablehlo.constant dense<...> : tensor<50x8xi32>
    %cst_1 = stablehlo.constant dense<...> : tensor<2x32xf32>
    %0:6 = call @combine(%cst_1, %cst, %cst_0, %c) : (tensor<2x32xf32>, tensor<50x3x32xf32>, tensor<50x6x16xf32>, tensor<50x8xi32>) -> (tensor<50x3x32xf32>, tensor<50x6xf32>, tensor<50x6x16xf32>, tensor<50x6x16x8xf32>, tensor<50xi32>, tensor<2x32xf32>)
    %1 = stablehlo.slice %0#2 [0:50, 4:6, 0:16] : (tensor<50x6x16xf32>) -> tensor<50x2x16xf32>
    %2 = stablehlo.reverse %1, dims = [1] : tensor<50x2x16xf32>

then the answer is wrong. In the included models, I have made certain that the input to stablehlo.reverse is the same in both cases. The only difference is whether these previous operation are included.
If I isolate the stablehlo.reverse by putting in a barrier, then things work again

    %1 = stablehlo.slice %0#2 [0:50, 4:6, 0:16] : (tensor<50x6x16xf32>) -> tensor<50x2x16xf32>
    %2 = stablehlo.optimization_barrier %1 : tensor<50x2x16xf32>
    %3 = stablehlo.reverse %2, dims = [1] : tensor<50x2x16xf32>

I have included 3 models:

  • flip_good.mlir - simple model that just calls stablehlo.reverse.
  • flip_bad.mlir - repro case that gets the wrong answer.
  • flip_barrier.mlir - same as the bad case but with an optimization barrier that causes it to get the right answer again.

All three models output the input and output tensors of stablehlo.reverse so that it's easy to compare. This shows that the same input is used in all models, but that flip_bad.mlir gets the wrong result.

This was tested on CPU, Vulkan, and CUDA, and IREE behaves the same way in all cases.

models.zip

Steps to reproduce your issue

  1. Compile flip_good.mlir, flip_bad,mlir and flip_barrier.mlir.
  2. Note that output 1 matches for all three models, but that flip_bad.mlir has an incorrect second output.

What component(s) does this issue relate to?

Compiler

Version information

Tested with 3.11.0rc20260224, but I've seen the issue as far back as 3.5.0

Additional context

No response

Activity

  1. added
    bug 🐞
    on Mar 3, 2026
  2. MaheshRavishankar commented on Mar 3, 2026

    @MaheshRavishankar
    Collaborator

    @IanWood1 when you have some time can you triage this?

  3. pstarkcdpr commented on Mar 3, 2026

    @pstarkcdpr
    ContributorAuthor

    Okay, I've managed to reduce this even further. I'm including an updated model that has the issue, but only does 2 operations:

        %cst = stablehlo.constant dense<...> : tensor<50x6x16xf32>
        %1 = stablehlo.slice %cst [0:50, 4:6, 0:16] : (tensor<50x6x16xf32>) -> tensor<50x2x16xf32>
        %2 = stablehlo.reverse %1, dims = [1] : tensor<50x2x16xf32>
    

    I've added updated models. The good model is the same. The bad and optimization barrier models have been simplified:
    updated_models.zip

  4. IanWood1 commented on Mar 3, 2026

    @IanWood1
    Member

    Yep, that makes sense. This is an issue with vector.gather operating on strided memrefs. I'm trying to get a reproducer just before the pass generates the incorrect IR.

  5. IanWood1 commented on Mar 4, 2026

    @IanWood1
    Member

    It looks like the problem is that vectorization is trying to convert the following to a vector.gather (https://github.com/llvm/llvm-project/blob/5e5f7efd77064a1b05b2596dfab39966ce828359/mlir/lib/Dialect/Linalg/Transforms/Vectorization.cpp#L1194-L1205)

          %6 = linalg.generic {indexing_maps = [affine_map<(d0) -> (d0)>], iterator_types = ["parallel"]} outs(%extracted_slice : tensor<16xf32>) attrs =  {lowering_config = #iree_cpu.lowering_config<distribution = [1600], vector_common_parallel = [16]>} {
          ^bb0(%out: f32):
            %7 = linalg.index 0 : index
            %8 = affine.apply affine_map<(d0)[s0] -> (d0 + s0)>(%arg2)[%7]
            %9 = arith.remsi %8, %c16 : index
            %10 = arith.divsi %8, %c16 : index
            %11 = arith.remsi %10, %c2 : index
            %12 = arith.divsi %10, %c2 : index
            %13 = arith.subi %c1, %11 : index
            %extracted = tensor.extract %2[%12, %13, %9] : tensor<50x2x16xf32>
            linalg.yield %extracted : f32
          } -> tensor<16xf32>
    

    But this isn't actually representable as vector.gather. indices only modifies the innermost index during the gather. The lowering tries to get around this restriction by overflowing the innermost index. This only works when the gather is on an identity stride memref which this is not. @Groverkss since I think you have the most context on this, does this make sense to you?

    Here's the gist with the logs flip_bad1.mlir https://gist.github.com/IanWood1/e92ae5d6fd19226e72d49ed6c42e2bfb

  6. IanWood1 commented on Mar 4, 2026

    @IanWood1
    Member

    Looks like the same issue as #20011

  7. pstarkcdpr commented on Mar 4, 2026

    @pstarkcdpr
    ContributorAuthor

    Thanks @IanWood1. It looks like this will be non-trivial to fix? This issue is kind of blocking us, so I'm wondering if there are any workarounds or a way for the compiler to throw an error instead of getting the wrong answer (I'd prefer to know in advance if the model will fail rather than see unexpected behaviour)?

    Based on the above failure case, I threw together a quick unit test in the style of tests/e2e/stablehlo_ops that reproduces the issue:

    func.func @reverse_strided() {
      %cst = stablehlo.constant dense<[[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]], [[9.0, 10.0], [11.0, 12.0], [13.0, 14.0], [15.0, 16.0]]]> : tensor<2x4x2xf32>
      %1 = stablehlo.slice %cst [0:2, 1:3, 0:2] : (tensor<2x4x2xf32>) -> tensor<2x2x2xf32>
      %2 = stablehlo.reverse %1, dims = [1] : tensor<2x2x2xf32>
      check.expect_eq_const(
        %2,
        dense<[[[5.0, 6.0], [3.0, 4.0]], [[13.0, 14.0], [11.0, 12.0]]]> : tensor<2x2x2xf32>
      ) : tensor<2x2x2xf32>
      return
    }
    
  8. MaheshRavishankar commented on Mar 4, 2026

    @MaheshRavishankar
    Collaborator

    @hanhanW I am moving this issue to you. You might have more context on this (its the reverse operation). I think we used to have a dedicated reverse operation, but it is now removed, and might be causing issues.

  9. hanhanW commented on Mar 4, 2026

    @hanhanW
    Contributor

    Let me take a look, I'll check if it is a pre-existing issue that @IanWood1 pointed out (which will be very useful).

  10. pstarkcdpr commented on Mar 4, 2026

    @pstarkcdpr
    ContributorAuthor

    Okay, now that we know the pattern, I think that we can work around this issue in JAX. Basically, whenever we have a jnp.flip that works on a slice, we can just reverse the operations (flip then slice). If there isn't a quick fix for the compiler, I'm wondering if there's an easy way to add a compile error when the bad situation arises. It doesn't need to be committed, we build a local compiler anyways. This would give us confidence that we've worked around all the instances of this issue.

  11. IanWood1 commented on Mar 4, 2026

    @IanWood1
    Member

    If you just need something hacky, this should identify when it will produce incorrect results:

    diff --git a/compiler/src/iree/compiler/Codegen/Common/IREEComprehensiveBufferizePass.cpp b/compiler/src/iree/compiler/Codegen/Common/IREEComprehensiveBufferizePass.cpp
    index 2ad5ce127f..732ca75489 100644
    --- a/compiler/src/iree/compiler/Codegen/Common/IREEComprehensiveBufferizePass.cpp
    +++ b/compiler/src/iree/compiler/Codegen/Common/IREEComprehensiveBufferizePass.cpp
    @@ -291,6 +291,13 @@ void IREEComprehensiveBufferizePass::runOnOperation() {
           return signalPassFailure();
         }
       }
    +
    +  funcOp.walk([this](vector::GatherOp op) {
    +    auto ty = cast<MemRefType>(op.getBase().getType());
    +    if (!ty.getLayout().isIdentity()) {
    +      signalPassFailure();
    +    }
    +  });
     }
    
     void IREEBufferizeConstantsPass::runOnOperation() {
  12. hanhanW commented on Mar 4, 2026

    @hanhanW
    Contributor

    Just a heads-up that I got a fix (but I need to verify and review) from Claude:


    Issue #23637 / #20011: vector.gather produces incorrect results on strided memrefs

    Root cause chain:

    1. stablehlo.reverse on a sliced tensor → linalg.generic with tensor.extract using reversed indices
    2. IREE's CollapseDimensionsPass flattens to 1D with complex index arithmetic
    3. MLIR's calculateGatherOffset() linearizes multi-D indices into a 1D offset: offset = i * dim1 + j (e.g., [6, 4, 2, 0] for a 4x2 tensor)
    4. After bufferization, the sliced tensor becomes a strided memref (e.g., memref<4x2xf32, strided<[4, 1]>>)
    5. Gather1DToConditionalLoads adds the offset to the innermost index: load %subview[0, 6] → address 04 + 6 = 6 (WRONG, should be 34 + 0 = 12)

    Fix: Modified Gather1DToConditionalLoads in LowerVectorGather.cpp to detect non-contiguous strided memrefs and delinearize the 1D gather offset back into proper multi-dimensional load indices:

    • col = offset % dim1, row = offset / dim1
    • load %subview[row, col] → address row * stride0 + col * stride1 → correct

    Verification:

    • Before fix: repro_bad.mlir → 4xf32=6 4 2 0 (wrong)
    • After fix: repro_bad.mlir → 4xf32=12 8 4 0 (correct, matches repro_good.mlir)
    • Issue Incorrect numerical results in stablehlo.reverse #23637 flip_bad1.mlir output now matches flip_good.mlir (identical MD5 hashes)
    • All 425 runnable Codegen tests pass (3 pre-existing failures unrelated to this change)

    Note: The root cause is in MLIR's calculateGatherOffset() which creates vector.gather with indices that overflow the innermost dimension — technically undefined behavior per the vector.gather spec. This should be fixed upstream.
    The fix in Gather1DToConditionalLoads handles it at the lowering level for all backends that use populateVectorGatherToConditionalLoadPatterns (LLVMCPU, SPIRV).

  13. hanhanW commented on Mar 5, 2026

    @hanhanW
    Contributor

    Here is the fix: llvm/llvm-project#184706

    @IanWood1 feel free to review if you want to.

  14. MaheshRavishankar commented on Mar 5, 2026

    @MaheshRavishankar
    Collaborator

    Fast progress! Thanks @hanhanW

  15. pstarkcdpr commented on Mar 5, 2026

    @pstarkcdpr
    ContributorAuthor

    Thanks @hanhanW. I tried your fix in my local compiler build and, so far, it looks like that fixes a bunch of issues for us. JAX and IREE are matching now.

  16. hanhanW commented on Mar 13, 2026

    @hanhanW
    Contributor

    The upstream change is landed. I'll close the issue after it propagates to IREE.

  17. hanhanW commented on Mar 17, 2026

    @hanhanW
    Contributor

    Confirmed that it is fixed on ToT, closing the issue

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

Metadata

Metadata

Assignees

Labels

bug 🐞

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions