Skip to content

Conversation

@locnd182644
Copy link
Contributor

@locnd182644 locnd182644 commented Jan 8, 2026

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 resolves an inconsistency in TVM's LLVM code generation where casting a floating-point NaN value to a boolean type resulted in False, contrary to common programming language conventions. By modifying the underlying LLVM comparison instruction, the system now correctly interprets NaN as True when converted to a boolean, enhancing compatibility and ensuring predictable behavior across different computational frameworks.

Highlights

  • Standardizing NaN to Bool Casting: Aligns TVM's LLVM codegen behavior for casting NaN (Not a Number) to boolean with established frameworks like C, C++, Python, Torch, NumPy, and OnnxRuntime, where NaN evaluates to True.
  • LLVM Instruction Update: Implements this change by replacing the fcmp one instruction with fcmp une in the LLVM codegen, specifically within the CreateCast function for float-to-bool conversions.
  • New Test Case: Introduces test_llvm_cast_float_to_bool to validate the updated casting logic for various float values, including 0.0, 1.0, NaN, and Infinity, ensuring they correctly map to False, True, True, and True respectively.

🧠 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.

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 addresses an inconsistency in how TVM handles casting NaN to a boolean value. The change from CreateFCmpONE to CreateFCmpUNE in the LLVM codegen aligns TVM's behavior with other major frameworks like C++, Python, and NumPy, ensuring that NaN correctly evaluates to true. The addition of a new test case is also a great step to verify this fix. I've added a suggestion to parameterize this new test to cover more floating-point types (float16, float32, float64), which will make it more robust.

Comment on lines +381 to +403
@tvm.testing.requires_llvm
def test_llvm_cast_float_to_bool():
a_np = np.array([0.0, 1.0, np.nan, np.inf], dtype="float32")
n = a_np.shape[0]

A = te.placeholder((n,), name="A", dtype="float32")
C = te.compute((n,), lambda i: A[i].astype("bool"), name="C")

# Convert to TIR and create schedule
mod = te.create_prim_func([A, C])
sch = tir.Schedule(mod)

# build and invoke the kernel.
f = tvm.compile(sch.mod, target="llvm")
dev = tvm.cpu(0)

# launch the kernel.
a = tvm.runtime.tensor(a_np, 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 case that covers the essential scenarios for casting floats to booleans. To make it even more comprehensive, I suggest parameterizing it to run against multiple float dtypes (float16, float32, and float64). This will ensure the fix holds for different precisions and improve test coverage.

@tvm.testing.requires_llvm
@pytest.mark.parametrize("dtype", ["float16", "float32", "float64"])
def test_llvm_cast_float_to_bool(dtype):
    if dtype == "float16" and tvm.target.codegen.llvm_version_major() < 8:
        pytest.skip("float16 support requires LLVM 8 or greater")

    a_np = np.array([0.0, 1.0, np.nan, np.inf], dtype=dtype)
    n = a_np.shape[0]

    A = te.placeholder((n,), name="A", dtype=dtype)
    C = te.compute((n,), lambda i: A[i].astype("bool"), name="C")

    # Convert to TIR and create schedule
    mod = te.create_prim_func([A, C])
    sch = tir.Schedule(mod)

    # build and invoke the kernel.
    f = tvm.compile(sch.mod, target="llvm")
    dev = tvm.cpu(0)

    # launch the kernel.
    a = tvm.runtime.tensor(a_np, 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)

@locnd182644 locnd182644 changed the title [LLVM][Codegen] Cast NAN to bool gives true [LLVM][Codegen] Cast NaN to bool gives true Jan 8, 2026
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