Skip to content

[BugFix][Codegen] Preserve floating-point literal precision - #75

Open
anerli wants to merge 1 commit into
tile-ai:tilelang_mainfrom
magnitudedev:pr/float-literal-precision
Open

anerli wants to merge 1 commit into
tile-ai:tilelang_mainfrom
magnitudedev:pr/float-literal-precision

Conversation

@anerli

@anerli anerli commented Sep 15, 2026

Copy link
Copy Markdown

Problem and root cause

C and Metal code generation use the default stream precision when printing floating-point literals. This can change the value held by a FloatImm: for example, a float32 value near 1.23456789 is emitted as 1.234568e+00f, which rounds to a different float32 value.

Change

  • src/target/source/codegen_c.cc: use enough scientific-notation digits to round-trip the stored double value; use a temporary stream for float16 output as well.
  • src/target/metal/codegen_metal.cc: apply the same precision while preserving dtype suffixes and existing infinity/NaN handling.
  • tests/python/codegen/test_float_literal_precision.py: add device-independent source-generation checks for positive, negative, and small values across C float32/float64 and Metal float32/float16, comparing round-tripped values bitwise.

Tests and validation

12 new regression tests and 6 existing C-host tests pass, 0 skipped. Before the codegen fix, nine new cases fail due to precision loss; the three float16 cases pass.

PYTHONPATH=$PWD/python python -m pytest -q \
  tests/python/codegen/test_float_literal_precision.py
PYTHONPATH=$PWD/python python -m pytest -q \
  tests/python/codegen/test_target_codegen_c_host.py
pre-commit run --files src/target/metal/codegen_metal.cc \
  src/target/source/codegen_c.cc \
  tests/python/codegen/test_float_literal_precision.py

The broader tests/python/codegen/test_target_codegen_metal.py suite segfaults in its first test, test_metal_inf_nan, during execution. The same crash was reproduced after rebuilding unmodified upstream. Thus Metal source generation is validated here, but the Metal execution suite is not green.

Validation environment: Apple M4 Max, macOS/Darwin 24.5.0 arm64, Python 3.12.11. Each branch was rebuilt separately from upstream 907a88c87 with:

cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release \
  -DUSE_METAL=ON -DUSE_LLVM=OFF -DUSE_CUDA=OFF -DUSE_Z3=OFF
cmake --build build --target tvm tvm_compiler tvm_runtime -j 8

git diff --check passes. The applicable formatting and other pre-commit hooks pass. The repository-wide ASF-header hook reports 11 existing violations, reproduced on unmodified upstream; none is in the changed files.

Related

No duplicate open PR was found. This literal-formatting change is independent of Metal target-property discovery in #71.

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.

1 participant