[Fix][Relax][ONNX] Cast BatchNorm params to input dtype#19979
Conversation
There was a problem hiding this comment.
Code Review
This pull request updates the ONNX frontend's BatchNormalization implementation to automatically cast the scale, bias, mean, and variance parameters to match the input data type, preventing type mismatches. A new unit test is also added to verify this mixed-precision behavior. The review feedback suggests optimizing this casting logic for constant parameters by directly modifying the underlying numpy arrays and recreating relax.Constant nodes, thereby avoiding unnecessary astype operations in the Relax AST.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
tlopex
left a comment
There was a problem hiding this comment.
Thanks for fixing! But could you avoid casting the float32 parameters down to the data dtype, as this can lose precision and change the result.
Since Relax batch_norm requires matching dtypes, please promote all five inputs to a common computation dtype (float32 for this case), run batch_norm, and cast Y back to the original data dtype.
The test can verify that the batch_norm inputs are float32 while the final output remains float16 I think
5ebe44f to
ece4e07
Compare
Thx for pointing out! I'll fix it later. : D |
Signed-off-by: viiccwen <vicwen@apache.org>
ece4e07 to
d3d1034
Compare
|
Hello @tlopex, Updated the implementation. (Follow by ONNX BatchNormalization-15 schema) The strategy is:
|
Fixes #19977.
ONNX
BatchNormalizationallows the input/output tensor dtype, scale/bias dtype, and mean/variance dtype to be separate floating-point type parameters.For example, a valid ONNX model may use
float16data withfloat32gamma, beta, mean, and variance tensors.The Relax
batch_normoperator currently requires all five input tensors to have the same dtype. The ONNX frontend previously forwarded the ONNX inputs directly torelax.nn.batch_norm, causing import to fail during normalizationfor mixed-dtype ONNX models.
This patch casts the ONNX BatchNormalization parameter tensors (
scale,bias,mean, andvar) to the data tensor dtype before calling Relaxbatch_norm.This preserves the ONNX output dtype, which follows the input data dtype, while keeping the fix localized to the frontend compatibility layer.
The regression test builds a minimal ONNX BatchNormalization graph with
float16data andfloat32parameters, imports it through the Relax ONNX frontend, and checks that the generated Relaxbatch_normcall receives same-dtype inputs.Verification:
python -m pytest tests/python/relax/test_frontend_onnx.py::test_batch_norm_mixed_dtype_params tests/python/relax/test_frontend_onnx.py::test_batch_norm_defaults_to_inference_mode -q