Skip to content

Mesh: keep float32 accuracy in transform when TF32 matmuls are allowed - #2319

Merged
melo-gonzo merged 5 commits into
NVIDIA:mainfrom
melo-gonzo:mesh-transform-tf32
Nov 25, 2026
Merged

melo-gonzo merged 5 commits into
NVIDIA:mainfrom
melo-gonzo:mesh-transform-tf32

Conversation

@melo-gonzo

@melo-gonzo melo-gonzo commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

PhysicsNeMo Pull Request

Description

Mesh.transform moves the points with a float32 matrix product, mesh.points @ matrix.T. rotate and scale build a matrix and call transform. The cached centroids, the cached normals, and vector and rank-2 tensor fields go through products of the same kind. On CUDA, a float32 matrix product runs in TF32 when torch.backends.cuda.matmul.allow_tf32 is set, and TF32 rounds each input to about three significant digits. That precision is meant for network layers. Here it rounds the coordinates of the mesh.

The setting applies to the whole process. A training script that allows TF32 for its model also allows it for every mesh transform in its data pipeline. NGC PyTorch containers allow it by default through TORCH_ALLOW_TF32_CUBLAS_OVERRIDE=1. The test suite starts every test with torch.set_float32_matmul_precision("highest") (full_fp32_matmul in test/conftest.py), so CI cannot see the rounding.

Measured on a GB300 with torch 2.14.1, on 200,000 float32 points with coordinates of a few units. Each error is an absolute error divided by the largest value of the result, against the same product in float64.

Product TF32 off, max TF32 on, median TF32 on, max
points @ matrix.T, a rotation 8.5e-8 4.3e-5 4.9e-4
points @ matrix.T, a diagonal scale 4.0e-8 3.6e-5 4.1e-4
Rank-2 tensor field, einsum("ij,bjk,lk->bil", ...) 1.3e-7 3.2e-5 5.1e-4
Points as column products (this PR) 8.5e-8 7.1e-9 8.5e-8

A B300 with torch 2.13.0 gives the same errors with TF32 on.

On a mesh 8 m long, 4.9e-4 is 4 mm. Two vertices closer together than the rounding step can land on the same value, and their face then has zero area.

This PR computes those products without a GEMM, so TF32 does not apply to them.

Changes:

  • physicsnemo/mesh/utilities/_thin_matmul.py: new thin_matmul(rows, matrix). It computes rows @ matrix as one scaled copy of each matrix row, summed. It keeps the dtype of its inputs and raises a ValueError when the length of the rows differs from the number of matrix rows. It sums float16 and bfloat16 inputs in float32, as a partial sum can overflow float16 where the result does not, and it returns zeros for rows of length zero. It accumulates the sum in place, so it holds no temporaries beyond the result. frame_coordinates already computed its product this way and now calls thin_matmul.
  • transform in physicsnemo/mesh/transformations/geometric.py: the points, the cached cell centroids, and the cached cell and point normals use thin_matmul.
  • _transform_tensordict in the same file: one loop over the spatial indices of a field replaces the vector product, the two rank-2 einsum calls and the generated einsum strings for higher ranks.
  • transform raises a ValueError for a matrix whose dtype differs from the dtype of the points, and for a vector or tensor field of an integer or boolean dtype. The matrix product raised a RuntimeError for both inputs. The column products would promote them instead.
  • test/mesh/transformations/test_transformations.py: TestTransformAccuracy rotates, scales and shears a float32 sphere of 40,962 points with TF32 allowed, on CPU and on CUDA. It checks the points, a vector field, a rank-2 and a rank-3 tensor field, the cached centroids, the cached cell normals and, for the rotation, the cached point normals. The references are float64 products, and the tolerance is 16 float32 eps of the largest value. Two more tests cover the new ValueError cases. TestTransformEdgeShapes covers a float16 transform whose partial sums exceed the float16 range, and a mesh with zero spatial dimensions.
  • test/mesh/utilities/test_thin_matmul.py: thin_matmul equals rows @ matrix for a vector, for rows, for a batch of rows, and for matrices that change the row length. It raises for rows of the wrong length, stays finite for float16 and bfloat16 partial sums beyond the float16 range, and gives zeros for rows of length zero.
  • project transforms fields through _transform_tensordict, so its transform_*_data flags get the same fix with no change to its file. test_project_selects_field_components_exactly in test/mesh/projections/test_projections.py projects a float32 vector field and a rank-2 field of 50,000 points with TF32 allowed, on CPU and on CUDA, and compares them with the selected components by torch.equal.
  • CHANGELOG.md.

Cost, measured on the same GPU with TF32 off:

  • The points product is several kernels where the matrix product is one. It takes 0.06 to 0.07 ms against 0.02 to 0.03 ms from 1,000 to 100,000 points, and 0.25 ms against 0.77 ms at 10M points.
  • The column products accumulate in place. Like the matrix product, they hold no temporaries beyond the result.
  • A rank-2 tensor field at 1M points takes 0.14 ms as the loop with 34 MiB of temporaries, and 0.39 ms as einsum with 69 MiB.
  • A whole transform of a mesh with four caches and one vector field takes 1.31 to 1.44 ms, against 1.13 to 1.28 ms on main, from 162 to 655,362 points. The difference is 0.16 to 0.19 ms.

This PR covers transform and, through _transform_tensordict, project. Other float32 matrix products on coordinates, in the library or in the examples, were not audited.

Tested on a GB300 with torch 2.14.1. TestTransformAccuracy fails its three CUDA cases on the library files of main and passes all six cases here. Putting the matrix product back at any one of the five sites (points, centroids, cell normals, point normals, fields) fails it again. test/mesh gives 5,600 passed and 31 skipped here, and 5,591 passed and 31 skipped on the library files of main with the nine new transform tests deselected. With the two project cases added since, test/mesh gives 5,602 passed and 31 skipped here, and the project test fails its CUDA case on the library files of main. On the Arm CPU of the same machine in float64, the field transforms of main and of this branch give equal results for ranks 1 to 4, and so does the whole transform.

Minimal reproducer

Run from a checkout of main on a CUDA GPU.

import torch

from physicsnemo.mesh.primitives.surfaces import sphere_icosahedral
from physicsnemo.mesh.transformations.geometric import rotation_matrix

# A sphere of radius 3 centered at (5, 5, 5): 40,962 float32 points on the GPU.
mesh = sphere_icosahedral.load(radius=3.0, subdivisions=6, device="cuda")
mesh = mesh.translate([5.0, 5.0, 5.0])
angle, axis = 0.7, [1.0, 2.0, 3.0]
R = rotation_matrix(angle, axis, 3, mesh.points.device, torch.float64)
exact_rotated = mesh.points.double() @ R.T
exact_scaled = mesh.points.double() * 2.5

for precision in ("highest", "high"):  # "high" is what TORCH_ALLOW_TF32_CUBLAS_OVERRIDE=1 selects
    torch.set_float32_matmul_precision(precision)
    rotate_error = (mesh.rotate(angle, axis).points.double() - exact_rotated).abs().max()
    scale_error = (mesh.scale(2.5).points.double() - exact_scaled).abs().max()
    print(f"{precision:>7}: rotate max error {rotate_error:.1e}, scale max error {scale_error:.1e}")

Observed on main (GB300, torch 2.14.1):

highest: rotate max error 1.2e-06, scale max error 9.5e-07
   high: rotate max error 4.2e-03, scale max error 4.9e-03

Observed on this branch:

highest: rotate max error 1.2e-06, scale max error 9.5e-07
   high: rotate max error 1.2e-06, scale max error 9.5e-07

Expected: errors at float32 round-off, about 1e-6 for these coordinates, at both settings.

Checklist

Dependencies

None.

… round float32 coordinates, normals and fields.

Signed-off-by: Carmelo Gonzales <43048528+melo-gonzo@users.noreply.github.com>
Signed-off-by: Carmelo Gonzales <43048528+melo-gonzo@users.noreply.github.com>
@github-actions

Copy link
Copy Markdown
Contributor

CODEOWNERS review map

Current for commit 296319cd675e. An approval covers every file listed for that owner; one owner is sufficient for shared files.

⏳ @peterdsharpe — 5 file(s)
  • physicsnemo/mesh/spatial/_frame.py
  • physicsnemo/mesh/transformations/geometric.py
  • physicsnemo/mesh/utilities/_thin_matmul.py
  • test/mesh/transformations/test_transformations.py
  • test/mesh/utilities/test_thin_matmul.py

No CODEOWNER

  • CHANGELOG.md

Comment /codeowners-info to refresh.

@greptile-apps

greptile-apps Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in Greptile

[Medium impact] The changes affect mesh transformation workflows and canonical-frame coordinate calculations.

Fix the float16 overflow before merging; valid finite coordinates can become NaN.

Findings

  1. P1 Finite float16 points become NaN ▶
  2. P2 Zero-dimensional mesh transforms crash ▶

Summary

Replaces mesh matrix products with scaled-row sums to avoid TF32 rounding.

  • Mesh points and cached geometry keep float32 accuracy with TF32 allowed.
  • Vector and tensor fields keep their accuracy at every rank.
  • Mesh transforms reject matrices with a different point dtype.

Acknowledged intentional changes and costs:

  • melo-gonzo explicitly acknowledged extra kernels and temporary memory in the PR description.
  • melo-gonzo explicitly described the new ValueError behavior for incompatible dtypes as intentional.

Reviews (1) · Last reviewed commit: "Merge upstream main into fix/mesh-transf..." · Reviewed by Greptile

…f length zero in thin_matmul.

Signed-off-by: Carmelo Gonzales <43048528+melo-gonzo@users.noreply.github.com>

@peterdsharpe peterdsharpe left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks Carmelo, great catch! I reproduced it on an RTX 4090 and a GB300: your new accuracy tests fail their three CUDA cases on main's library and pass here, as does the rest of test/mesh. One suggestion inline makes thin_matmul memory-neutral and a bit faster. With main merged (the CHANGELOG conflicts), this looks good to me.

Comment thread CHANGELOG.md Resolved
Signed-off-by: Carmelo Gonzales <43048528+melo-gonzo@users.noreply.github.com>
…ngelog entry of the TF32 fix.

Signed-off-by: Carmelo Gonzales <43048528+melo-gonzo@users.noreply.github.com>
@melo-gonzo
melo-gonzo added this pull request to the merge queue Nov 25, 2026
Merged via the queue into NVIDIA:main with commit e812134 Nov 25, 2026
13 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.

2 participants