Skip to content

Conversation

@locnd182644
Copy link
Contributor

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

PR1-18605

- Ensure consistency with the existing framework (C/C++/Python/Torch/Numpy/...).
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @locnd182644, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses an inconsistency in TVM's handling of NaN-to-boolean conversions compared to other popular frameworks. By modifying the LLVM codegen and adding a new test case, the PR ensures that TVM now correctly casts NaN to True when converting to boolean, providing consistent behavior across different platforms.

Highlights

  • Consistency: Ensures that casting NaN (Not a Number) to boolean in TVM consistently returns True, aligning with the behavior of other frameworks like C, C++, Python, Torch, and NumPy.
  • LLVM Instruction Update: Replaces the fcmp one instruction with fcmp une in the LLVM codegen to achieve the desired NaN-to-boolean conversion.
  • Test Case Addition: Adds a new test case to verify the correct behavior of casting float to boolean in LLVM, specifically checking the NaN-to-boolean conversion.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • src/target/llvm/codegen_llvm.cc
    • Replaced fcmp one with fcmp une to ensure NaN is cast to true when converting to boolean.
  • tests/python/codegen/test_target_codegen_llvm.py
    • Added a test case to verify that float-to-boolean casting, including NaN, behaves as expected in LLVM.
Activity
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request correctly aligns TVM's behavior for casting NaN to bool with other major frameworks by changing the LLVM comparison instruction from fcmp one to fcmp une. The change is sound and the new test case effectively validates the behavior for NaN, 0.0, and inf. I've added one suggestion to parameterize the new test to improve coverage across different float types.

Comment on lines +373 to +394
@tvm.testing.requires_llvm
def test_llvm_cast_float_to_bool():
@I.ir_module
class Module:
@T.prim_func
def main(A: T.Buffer((4,), "float32"), C: T.Buffer((4,), "bool")):
T.func_attr({"tir.noalias": True})
for i in range(4):
with T.sblock("C"):
v_i = T.axis.spatial(4, i)
T.reads(A[v_i])
T.writes(C[v_i])
C[v_i] = T.Cast("bool", A[v_i])

n = 4
f = tvm.compile(Module, target="llvm")
dev = tvm.cpu(0)
a = tvm.runtime.tensor(np.array([0.0, 1.0, np.nan, np.inf], dtype="float32"), dev)
c = tvm.runtime.empty((n,), dtype="bool", device=dev)
f(a, c)
c_np = np.array([False, True, True, True], dtype="bool")
tvm.testing.assert_allclose(c.numpy(), c_np)
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

This is a great test for verifying the new behavior. To improve test coverage, consider parameterizing it to run against different float types (float16, float32, float64), since the change in codegen_llvm.cc affects all float types.

@tvm.testing.requires_llvm
@pytest.mark.parametrize("dtype", ["float16", "float32", "float64"])
def test_llvm_cast_float_to_bool(dtype):
    @I.ir_module
    class Module:
        @T.prim_func
        def main(A: T.Buffer((4,), dtype), C: T.Buffer((4,), "bool")):
            T.func_attr({"tir.noalias": True})
            for i in range(4):
                with T.sblock("C"):
                    v_i = T.axis.spatial(4, i)
                    T.reads(A[v_i])
                    T.writes(C[v_i])
                    C[v_i] = T.Cast("bool", A[v_i])

    n = 4
    f = tvm.compile(Module, target="llvm")
    dev = tvm.cpu(0)
    a = tvm.runtime.tensor(np.array([0.0, 1.0, np.nan, np.inf], dtype=dtype), dev)
    c = tvm.runtime.empty((n,), dtype="bool", device=dev)
    f(a, c)
    c_np = np.array([False, True, True, True], dtype="bool")
    tvm.testing.assert_allclose(c.numpy(), c_np)

@tqchen tqchen merged commit 84d05e9 into apache:main Feb 13, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] ONNX Cast treats NaN inconsistently in TVM LLVM codegen: Constant(NaN)->True but computed NaN->False

2 participants