Skip to content

[CPU] Fix FP4 tie rounding on CPU - #4805

Open
projekt11th wants to merge 2 commits into
ml-explore:mainfrom
projekt11th:fix-fp4-tie-rounding
Open

projekt11th wants to merge 2 commits into
ml-explore:mainfrom
projekt11th:fix-fp4-tie-rounding

Conversation

@projekt11th

@projekt11th projekt11th commented Oct 30, 2026 •

Copy link
Copy Markdown

The CPU fallback in fp_quantize used argmin, which selects the smaller value on exact ties. Update it to use the same rounding thresholds as Metal's fp4_e2m1, ensuring consistent FP4 quantization across backends.

Also changes CPU NaN quantization from code 0 to code 7.

Tests:

  • python3 python/tests/run.py
  • pre-commit run --all

Fixes #4753

  • ☑️ I understand it is strictly prohibited to use AI to write PR description
  • AI usage disclosure: Claude code reviewed and worked with me to improve my fix

The CPU fallback in fp_quantize used argmin, which selects the smaller value on exact ties. Update it to use the same rounding thresholds as Metal's fp4_e2m1, ensuring consistent FP4 quantization across backends.

Also changes CPU NaN quantization from code 0 to code 7.

Tests:
- python3 python/tests/run.py
- pre-commit run --all

Fixes ml-explore#4753

@zcbenz zcbenz left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This code feels very inefficient, can you try the algorithm used in https://github.com/ROCm/AMDMIGraphX/blob/4bba8e7bf4ab80ed198a06949f00175bd13d2a34/src/include/migraphx/fp4_casts.hpp#L83?

It should be possible to use searchsorted to replace the for loop, and there is a sign op.

Replace the iterative FP4 rounding loop with searchsorted-based tie detection and ties-to-even rounding.

Use sign(wq) to determine the sign instead of the view-as-int approach.

CPU produces code 0 for exact -0.0, while Metal produces code 8. Both decode to zero.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] FP4 quantization on CPU rounds ties toward zero while Metal rounds to even

2 participants