Commit 84d05e9
authored
[LLVM][Codegen] Cast NaN to bool gives true (#18772)
Due to some recent changes to CI, PR #18646 will be closed and a new PR
created. This PR was created by opening a new pull request on the main
branch.
- Update test code: using tvmscript instead of schedule te.
### Summary
Cast NaN to bool gives true to ensure consistency with the existing
framework (C, C++, Python, Torch, NumPy, OnnxRuntime, ...).
### Steps to Reproduce
- Python:
```
bool(float('nan'))
```
> True
- Torch:
```
torch.tensor(float("nan"), dtype=torch.float32).to(torch.bool)
```
> tensor(True)
- Numpy:
```
import numpy as np
bool(np.nan)
```
> True
- TVM:
```
class Module:
def main(x: R.Tensor((), dtype="float32")) -> R.Tensor((), dtype="bool"):
with R.dataflow():
gv: R.Tensor((), dtype="bool") = R.astype(x, dtype="bool")
R.output(gv)
return gv
x = np.array(float("nan"), dtype="float32")
```
> False
### Expected
- TVM:
```
class Module:
def main(x: R.Tensor((), dtype="float32")) -> R.Tensor((), dtype="bool"):
with R.dataflow():
gv: R.Tensor((), dtype="bool") = R.astype(x, dtype="bool")
R.output(gv)
return gv
x = np.array(float("nan"), dtype="float32")
```
> True
### Resolved
- Replace the instruction `fcmp one` with `fcmp une` in LLVM.
- Citation:
https://releases.llvm.org/20.1.0/docs/LangRef.html#fcmp-instruction
<img width="400" height="200" alt="PR1-18605"
src="https://github.com/user-attachments/assets/cffeebd8-dfe6-436e-9c4c-61e1e84d5439"
/>
- Related:
+
https://stackoverflow.com/questions/9158567/nan-to-bool-conversion-true-or-false
+
https://stackoverflow.com/questions/15686318/why-do-not-a-number-values-equal-true-when-cast-as-boolean-in-python-numpy
- Fixed: #186051 parent 783a9bf commit 84d05e9
File tree
2 files changed
+25
-1
lines changed- src/target/llvm
- tests/python/codegen
2 files changed
+25
-1
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
928 | 928 | | |
929 | 929 | | |
930 | 930 | | |
931 | | - | |
| 931 | + | |
932 | 932 | | |
933 | 933 | | |
934 | 934 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
370 | 370 | | |
371 | 371 | | |
372 | 372 | | |
| 373 | + | |
| 374 | + | |
| 375 | + | |
| 376 | + | |
| 377 | + | |
| 378 | + | |
| 379 | + | |
| 380 | + | |
| 381 | + | |
| 382 | + | |
| 383 | + | |
| 384 | + | |
| 385 | + | |
| 386 | + | |
| 387 | + | |
| 388 | + | |
| 389 | + | |
| 390 | + | |
| 391 | + | |
| 392 | + | |
| 393 | + | |
| 394 | + | |
| 395 | + | |
| 396 | + | |
373 | 397 | | |
374 | 398 | | |
375 | 399 | | |
| |||
0 commit comments