Skip to content

fix(transforms): handle float16/bfloat16 in convert_image_dtype#9485

Open
jashshah999 wants to merge 1 commit into
pytorch:mainfrom
jashshah999:fix/convert-image-dtype-fp16
Open

fix(transforms): handle float16/bfloat16 in convert_image_dtype#9485
jashshah999 wants to merge 1 commit into
pytorch:mainfrom
jashshah999:fix/convert-image-dtype-fp16

Conversation

@jashshah999
Copy link
Copy Markdown

Summary

Fixes two bugs in convert_image_dtype for half-precision floating point types (#6799, open since 2022):

  1. float16/bfloat16 to integer overflow: 1.0 * (255 + 1.0 - 0.001) = 255.999 rounds to 256.0 in float16 (insufficient mantissa bits), then .to(uint8) wraps to 0. Fix: upcast to float32 before the multiply, preserving the existing eps = 1e-3 distribution logic.

  2. int32/int64 to float16 produces NaN/inf: int32.max = 2^31-1 exceeds float16.max = 65504, so the .to(float16) cast silently produces inf. Fix: raise RuntimeError (same pattern as the existing float32->int32 safety check).

Both fixes are compatible with torch.jit.script (no isinstance calls, only direct dtype comparisons).

Test plan

  • Added test_convert_image_dtype_half_precision — verifies 0.0->0, 0.5->mid, 1.0->max for float16/bfloat16 to each integer dtype
  • Added test_convert_image_dtype_int_to_float16_raises — verifies int32/int64 to float16 raises RuntimeError

Fixes #6799.

Two bugs when using half-precision floating point dtypes:

1. float16/bfloat16 to integer: 255.999 rounds to 256.0 in float16
   due to limited precision, then .to(uint8) wraps to 0. Fix: upcast
   to float32 before the multiply.

2. int32/int64 to float16: max values exceed float16 range (65504),
   producing NaN/inf silently. Fix: raise RuntimeError (same pattern
   as the existing float32->int32 safety check).

Fixes pytorch#6799.
@pytorch-bot
Copy link
Copy Markdown

pytorch-bot Bot commented Apr 29, 2026

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/vision/9485

Note: Links to docs will display an error until the docs builds have been completed.

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@meta-cla meta-cla Bot added the cla signed label Apr 29, 2026
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.

convert_image_dtype overflows with low precision floating point dtypes

1 participant