Skip to content

Commit

Permalink
[FXML-2939] Fix rsqrt folder for bfloat16 (#81)
Browse files Browse the repository at this point in the history
  • Loading branch information
TinaAMD authored Sep 14, 2023
1 parent faf28e5 commit dd37d22
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
7 changes: 6 additions & 1 deletion mlir/lib/Dialect/Tosa/Transforms/TosaFolders.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -588,6 +588,11 @@ struct TosaFoldConstantRSQRT
auto floatVal = apFloatVal.convertToFloat();
auto sqrtVal = std::sqrt(floatVal);
APFloat apSqrtVal(sqrtVal);
// We fold only float32 and bfloat16, so we do not expect any precision loss
// for float32 and the tosa spec explicitly allows to implement bfloat16 as
// float32, so any precision loss on the conversion back is fine.
bool losesInfo = false;
apSqrtVal.convert(apFloatVal.getSemantics(), tosaRoundingMode, &losesInfo);

// Compute the reciprocal
return computeReciprocal(apSqrtVal, floatTy);
Expand All @@ -600,7 +605,7 @@ struct TosaFoldConstantRSQRT
}

bool isSupportedElementType(Type type) const {
return type.isBF16() || type.isF16() || type.isF32();
return type.isBF16() || type.isF32();
}
};

Expand Down
10 changes: 10 additions & 0 deletions mlir/test/Dialect/Tosa/constant-rsqrt-opt.mlir
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,16 @@ func.func @rsqrt_fold() -> tensor<4x6xf32> {
return %1 : tensor<4x6xf32>
}

// CHECK-LABEL: @rsqrt_fold_single_valued_bf16
func.func @rsqrt_fold_single_valued_bf16() -> tensor<bf16> {
// CHECK: [[RES:]] ={{.*}}tosa.const{{.*}}2.890630e-01{{.*}}tensor<bf16>
// CHECK-NOT: tosa.rsqrt
// CHECK: return [[RES]]
%0 = "tosa.const"() {value = dense<12.0> : tensor<bf16>} : () -> tensor<bf16>
%1 = "tosa.rsqrt"(%0) : (tensor<bf16>) -> tensor<bf16>
return %1 : tensor<bf16>
}

// CHECK-LABEL: @rsqrt_of_const_sparse
// Sparse tensors are currently not supported
func.func @rsqrt_of_const_sparse() -> tensor<32xbf16> {
Expand Down

0 comments on commit dd37d22

Please sign in to comment.