Skip to content

[MLIR] Fix canonicalization pattern for 'shape.shape_of' #134234

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Apr 4, 2025

Conversation

alaa-ali
Copy link
Contributor

@alaa-ali alaa-ali commented Apr 3, 2025

This PR will fix a bug in a canonicalization pattern (operation shape.shape_of: shape of reshape)

// Before
func.func @f(%arg0: tensor<?x1xf32>, %arg1: tensor<3xi32>) -> tensor<3xindex> {
  %reshape = tensor.reshape %arg0(%arg1) : (tensor<?x1xf32>, tensor<3xi32>) -> tensor<?x1x1xf32>
  %0 = shape.shape_of %reshape : tensor<?x1x1xf32> -> tensor<3xindex>
  return %0 : tensor<3xindex>
}
//This is will error out as follows:
error: 'tensor.cast' op operand type 'tensor<3xi32>' and result type 'tensor<3xindex>' are cast incompatible
  %0 = shape.shape_of %reshape : tensor<?x1x1xf32> -> tensor<3xindex>
       ^
note: see current operation: %0 = "tensor.cast"(%arg1) : (tensor<3xi32>) -> tensor<3xindex>
// After
func.func @f(%arg0: tensor<?x1xf32>, %arg1: tensor<3xi32>) -> tensor<3xindex> {
  %0 = arith.index_cast %arg1 : tensor<3xi32> to tensor<3xindex>
  return %0 : tensor<3xindex>
}

See file canonicalize.mlir in the change list for an example.

For the context, this bug was found while running a test on Keras 3, the canonicalizer errors out due to an invalid tensor.cast operation when the batch size is dynamic.
The operands of the op are tensor<3xi32> cast to tensor<3xindex>.
This change is related to a previous PR: #98531

Copy link

github-actions bot commented Apr 3, 2025

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@llvmbot
Copy link
Member

llvmbot commented Apr 3, 2025

@llvm/pr-subscribers-mlir

@llvm/pr-subscribers-mlir-shape

Author: Alaa Ali (alaa-ali)

Changes

This PR will fix a bug in a canonicalization pattern (operation shape.shape_of: shape of reshape)

// Before
func.func @<!-- -->f(%arg0: tensor&lt;?x1xf32&gt;, %arg1: tensor&lt;3xi32&gt;) -&gt; tensor&lt;3xindex&gt; {
  %reshape = tensor.reshape %arg0(%arg1) : (tensor&lt;?x1xf32&gt;, tensor&lt;3xi32&gt;) -&gt; tensor&lt;?x1x1xf32&gt;
  %0 = shape.shape_of %reshape : tensor&lt;?x1x1xf32&gt; -&gt; tensor&lt;3xindex&gt;
  return %0 : tensor&lt;3xindex&gt;
}
//This is will error out as follows:
error: 'tensor.cast' op operand type 'tensor&lt;3xi32&gt;' and result type 'tensor&lt;3xindex&gt;' are cast incompatible
  %0 = shape.shape_of %reshape : tensor&lt;?x1x1xf32&gt; -&gt; tensor&lt;3xindex&gt;
       ^
note: see current operation: %0 = "tensor.cast"(%arg1) : (tensor&lt;3xi32&gt;) -&gt; tensor&lt;3xindex&gt;
// After
func.func @<!-- -->f(%arg0: tensor&lt;?x1xf32&gt;, %arg1: tensor&lt;3xi32&gt;) -&gt; tensor&lt;3xindex&gt; {
  %0 = arith.index_cast %arg1 : tensor&lt;3xi32&gt; to tensor&lt;3xindex&gt;
  return %0 : tensor&lt;3xindex&gt;
}

See file canonicalize.mlir in the change list for an example.

For the context, this bug was found while running a test on Keras 3, the canonicalizer errors out due to an invalid tensor.cast operation when the batch size is dynamic.
The operands of the op are tensor<3xi32> cast to tensor<3xindex>.
This change is related to a previous PR: #98531

@sjarus
@jpienaar
@sahas3
@Hanumanth04
@ivangarcia44
@rafaelubalmw


Full diff: https://github.com/llvm/llvm-project/pull/134234.diff

2 Files Affected:

  • (modified) mlir/lib/Dialect/Shape/IR/Shape.cpp (+15-3)
  • (modified) mlir/test/Dialect/Shape/canonicalize.mlir (+31-2)
diff --git a/mlir/lib/Dialect/Shape/IR/Shape.cpp b/mlir/lib/Dialect/Shape/IR/Shape.cpp
index 10ba808cd26c2..b8eac7c86797b 100644
--- a/mlir/lib/Dialect/Shape/IR/Shape.cpp
+++ b/mlir/lib/Dialect/Shape/IR/Shape.cpp
@@ -1734,10 +1734,22 @@ struct ShapeOfFromReshape : public OpRewritePattern<shape::ShapeOfOp> {
     // Operand 'shape' of 'tensor.reshape' may now be used as the result of
     // 'shape.shape_of'. While its type is guaranteed to be compatible in well-
     // formed IR, it may not be identical (dynamically vs statically shaped),
-    // in which case it needs to be cast first.
+    // in which case it needs to be cast first using 'tensor.cast'.
+    // Additionally, it may not have identical element type (i32 vs index) 
+    // while it has identical shaped type (dynamic vs static), in which case it needs 
+    // to be cast first using 'arith.index_cast'.
+    // Note: 'shape.shape_of' op result must be shape or extent tensor.
     Value shape = tensorReshapeOp.getShape();
-    if (op.getType() != shape.getType())
-      shape = rewriter.create<tensor::CastOp>(op.getLoc(), op.getType(), shape);
+
+    auto opTensorType = llvm::dyn_cast<RankedTensorType>(op.getType());
+    auto shapeTensorType = llvm::dyn_cast<RankedTensorType>(shape.getType());
+
+    if (op.getType() != shape.getType()) {
+        if (opTensorType.getElementType() == shapeTensorType.getElementType())
+          shape = rewriter.create<tensor::CastOp>(op.getLoc(), op.getType(), shape);        
+        else if (!isExtentTensorType(shape.getType()))
+          shape = rewriter.create<arith::IndexCastOp>(op.getLoc(), op.getType(), shape);        
+    }
 
     rewriter.replaceOp(op, shape);
     return success();
diff --git a/mlir/test/Dialect/Shape/canonicalize.mlir b/mlir/test/Dialect/Shape/canonicalize.mlir
index cf439c9c1b854..9b25468b3ab1e 100644
--- a/mlir/test/Dialect/Shape/canonicalize.mlir
+++ b/mlir/test/Dialect/Shape/canonicalize.mlir
@@ -1389,10 +1389,25 @@ func.func @shape_of_from_reshape(%arg0: tensor<*xf32>, %arg1: tensor<?xindex>) -
 
 // -----
 
-// CHECK-LABEL: func @shape_of_from_reshape_compatible_types
+// Check statically shaped types, with element types i32 to index.
+// CHECK-LABEL: func @shape_of_from_reshape_compatible_types1
+// CHECK-SAME: %[[INPUT:.*]]: tensor<?x1xf32>
+// CHECK-SAME: %[[SHAPE:.*]]: tensor<3xi32>
+func.func @shape_of_from_reshape_compatible_types1(%arg0: tensor<?x1xf32>, %arg1: tensor<3xi32>) -> tensor<3xindex> {
+  // CHECK: %[[CAST_SHAPE:.*]] = arith.index_cast %[[SHAPE]] : tensor<3xi32> to tensor<3xindex>
+  // CHECK: return %[[CAST_SHAPE]] : tensor<3xindex>
+    %0 = tensor.reshape %arg0(%arg1) : (tensor<?x1xf32>, tensor<3xi32>) -> tensor<?x1x1xf32>
+    %1 = shape.shape_of %0 : tensor<?x1x1xf32> -> tensor<3xindex>
+    return %1 : tensor<3xindex>
+}
+
+// -----
+
+// Check similar element types, with statically shaped to dynamically shaped.
+// CHECK-LABEL: func @shape_of_from_reshape_compatible_types2
 // CHECK-SAME: %[[INPUT:.*]]: tensor<*xf32>
 // CHECK-SAME: %[[SHAPE:.*]]: tensor<5xindex>
-func.func @shape_of_from_reshape_compatible_types(%arg0: tensor<*xf32>, %arg1: tensor<5xindex>) -> tensor<?xindex> {
+func.func @shape_of_from_reshape_compatible_types2(%arg0: tensor<*xf32>, %arg1: tensor<5xindex>) -> tensor<?xindex> {
   // CHECK: %[[CAST_SHAPE:.*]] = tensor.cast %[[SHAPE]] : tensor<5xindex> to tensor<?xindex>
   // CHECK: return %[[CAST_SHAPE]] : tensor<?xindex>
   %0 = tensor.reshape %arg0(%arg1) : (tensor<*xf32>, tensor<5xindex>) -> tensor<*xf32>
@@ -1402,6 +1417,20 @@ func.func @shape_of_from_reshape_compatible_types(%arg0: tensor<*xf32>, %arg1: t
 
 // -----
 
+// Check similar element types, with dynamically shaped to statically shaped.
+// CHECK-LABEL: func @shape_of_from_reshape_compatible_types3
+// CHECK-SAME: %[[INPUT:.*]]: tensor<*xf32>
+// CHECK-SAME: %[[SHAPE:.*]]: tensor<?xindex>
+func.func @shape_of_from_reshape_compatible_types3(%arg0: tensor<*xf32>, %arg1: tensor<?xindex>) -> tensor<5xindex> {
+  // CHECK: %[[CAST_SHAPE:.*]] = tensor.cast %[[SHAPE]] : tensor<?xindex> to tensor<5xindex>
+  // CHECK: return %[[CAST_SHAPE]] : tensor<5xindex>
+  %0 = tensor.reshape %arg0(%arg1) : (tensor<*xf32>, tensor<?xindex>) -> tensor<*xf32>
+  %1 = shape.shape_of %0 : tensor<*xf32> -> tensor<5xindex>
+  return %1 : tensor<5xindex>
+}
+
+// -----
+
 // CHECK-LABEL: func @shape_of_from_reshape_nofold
 // CHECK-SAME: %[[INPUT:.*]]: tensor<*xf32>
 // CHECK-SAME: %[[SHAPE:.*]]: tensor<?xindex>

@ivangarcia44
Copy link
Contributor

ivangarcia44 commented Apr 3, 2025 via email

Copy link
Collaborator

@joker-eph joker-eph left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LG with some nits

Copy link

github-actions bot commented Apr 3, 2025

✅ With the latest revision this PR passed the C/C++ code formatter.

Copy link
Member

@sahas3 sahas3 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, one minor nit about the LIT tests.

@joker-eph joker-eph merged commit 5812516 into llvm:main Apr 4, 2025
11 checks passed
Copy link

github-actions bot commented Apr 4, 2025

@alaa-ali Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

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

Successfully merging this pull request may close these issues.

5 participants