PSNRB: `block_size` input validation is broken
🐛 Bug
Input validation for block_size in PeakSignalNoiseRatioWithBlockedEffect is broken: invalid values either slip through silently or raise TypeError, instead of the intended ValueError.
src/torchmetrics/image/psnrb.py:82 uses and where or is intended:
if not isinstance(block_size, int) and block_size < 1:
raise ValueError("Argument ``block_size`` should be a positive integer")
With and, the first clause (not isinstance(..., int)) is False for every int, which short-circuits the expression and skips the < 1 check, so invalid ints like 0 and -5 slip through. For non-ints, the second comparison runs and either returns False (e.g. 1.5 < 1) or raises TypeError (e.g. "foo" < 1). Neither path reaches the intended ValueError.
| Input | Observed | Expected |
|---|---|---|
0 |
no error | ValueError |
-5 |
no error | ValueError |
1.5 |
no error | ValueError |
"foo" |
TypeError: '<' not supported between instances of 'str' and 'int' |
ValueError |
To Reproduce
Code sample
from torchmetrics.image import PeakSignalNoiseRatioWithBlockedEffect
# All four should raise ValueError per the existing error message.
# Silently accepted (no error):
PeakSignalNoiseRatioWithBlockedEffect(data_range=1.0, block_size=0)
PeakSignalNoiseRatioWithBlockedEffect(data_range=1.0, block_size=-5)
PeakSignalNoiseRatioWithBlockedEffect(data_range=1.0, block_size=1.5)
# Raises TypeError instead of ValueError:
PeakSignalNoiseRatioWithBlockedEffect(data_range=1.0, block_size="foo")
Environment
- TorchMetrics version: 1.9.0
- Python version: 3.12.13
- PyTorch version: 2.11.0
- OS: macOS 26.4.1
Fix is a one-word change (and -> or). Will open a PR shortly with targeted tests covering the four cases above.
The functional psnrb() in src/torchmetrics/functional/image/psnrb.py has no input validation on block_size at all. I'll scope that as a separate follow-up unless maintainers prefer it bundled here, please let me know.
You correctly pointed out that and should be or in the input validation for block_size. I'd handle this by updating the condition to if not isinstance(block_size, int) or block_size < 1: which will raise a ValueError for both non-integers and invalid integers. Can have a PR up within 24 hours. I've built similar input validation logic in Python projects before and can resolve this efficiently.