[all-commits] [llvm/llvm-project] d39ac3: [mlir][math] Reland 58ef9bec071383744fb703ff08df98...

srcarroll via All-commits all-commits at lists.llvm.org
Sun Mar 17 09:23:52 PDT 2024


  Branch: refs/heads/main
  Home:   https://github.com/llvm/llvm-project
  Commit: d39ac3a8e010582c25e5d7e193ad3153402b1c4f
      https://github.com/llvm/llvm-project/commit/d39ac3a8e010582c25e5d7e193ad3153402b1c4f
  Author: srcarroll <50210727+srcarroll at users.noreply.github.com>
  Date:   2024-03-17 (Sun, 17 Mar 2024)

  Changed paths:
    M mlir/lib/Dialect/Math/Transforms/ExpandPatterns.cpp
    M mlir/test/Dialect/Math/expand-math.mlir
    M mlir/test/mlir-cpu-runner/test-expand-math-approx.mlir

  Log Message:
  -----------
  [mlir][math] Reland 58ef9bec071383744fb703ff08df9806f25e4095 (#85436)

The previous implementation decomposes tanh(x) into
`(exp(2x) - 1)/(exp(2x)+1), x < 0`
`(1 - exp(-2x))/(1 + exp(-2x)), x >= 0`
This is fine as it avoids overflow with the exponential, but the whole
decomposition is computed for both cases unconditionally, then the
result is chosen based off the sign of the input. This results in doing
two expensive exp computations.

The proposed change avoids doing the whole computation twice by
exploiting the reflection symmetry `tanh(-x) = -tanh(x)`. We can
"normalize" the input to be positive by setting `y = sign(x) * x`, where
the sign of `x` is computed as `sign(x) = (float)(x > 0) * (-2) + 1`.
Then compute `z = tanh(y) `with the decomposition above for `x >=0` and
"denormalize" the result `z * sign(x)` to retain the sign. The reason it
is done this way is that it is very amenable to vectorization.

This method trades the duplicate decomposition computations (which takes
5 instructions including an extra expensive exp and div) for 4 cheap
instructions to compute the signs value

`arith.cmpf `(which is a pre-existing instruction in the previous impl)
`arith.sitofp`
`arith.mulf`
`arith.addf`
and 1 more instruction to get the right sign in the result
5. `arith.mulf`. 
Moreover, numerically, this implementation will yield the exact same
results as the previous implementation.

As part of the relanding, a casting issue from the original commit has
been fixed, i.e. casting bool to float with `uitofp`. Additionally a
correctness test with `mlir-cpu-runner` has been added.



To unsubscribe from these emails, change your notification settings at https://github.com/llvm/llvm-project/settings/notifications


More information about the All-commits mailing list