-
Notifications
You must be signed in to change notification settings - Fork 1.4k
ENH: support additional dtypes in pad_nd #8672
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
shubham-61969
wants to merge
2
commits into
Project-MONAI:dev
Choose a base branch
from
shubham-61969:7842-pad-nd-more-dtypes
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+79
−9
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| # Copyright (c) MONAI Consortium | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| """ | ||
| Tests for pad_nd dtype support and backend selection. | ||
| Validates PyTorch padding preference and NumPy fallback behavior. | ||
| """ | ||
| from __future__ import annotations | ||
| from unittest.mock import Mock, patch | ||
| import pytest | ||
| import torch | ||
| import monai.transforms.croppad.functional as F | ||
| from monai.transforms.croppad.functional import pad_nd | ||
|
|
||
| def test_pad_uses_pt_for_bool(): | ||
| """Test that pad_nd uses PyTorch backend for bool dtype in constant mode.""" | ||
| img = torch.ones((1, 4, 4), dtype=torch.bool) | ||
| to_pad = [(0, 0), (1, 1), (2, 2)] | ||
| with patch.object(F, "_pt_pad", wraps=F._pt_pad) as mock_pt, patch.object(F, "_np_pad", wraps=F._np_pad) as mock_np: | ||
| out = pad_nd(img, to_pad, mode="constant", value=0) | ||
|
|
||
| assert mock_pt.called | ||
| assert not mock_np.called | ||
| assert out.dtype == img.dtype | ||
|
|
||
| def test_pad_falls_back_to_np_if_pt_raises(): | ||
| """Test that pad_nd falls back to NumPy when PyTorch raises NotImplementedError.""" | ||
| img = torch.ones((1, 4, 4), dtype=torch.bool) | ||
| to_pad = [(0, 0), (1, 1), (2, 2)] | ||
| with ( | ||
| patch.object(F, "_pt_pad", new=Mock(side_effect=NotImplementedError("no"))) as mock_pt, | ||
| patch.object(F, "_np_pad", wraps=F._np_pad) as mock_np, | ||
| ): | ||
| out = pad_nd(img, to_pad, mode="constant", value=0) | ||
|
|
||
| assert mock_pt.called | ||
| assert mock_np.called | ||
| assert out.dtype == img.dtype | ||
|
|
||
| @pytest.mark.parametrize( | ||
| "dtype", [torch.bool, torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.float32] | ||
| ) | ||
| def test_pad_dtype_no_error_and_dtype_preserved(dtype): | ||
| """Test that pad_nd handles various dtypes without error and preserves dtype.""" | ||
| img = torch.ones((1, 4, 4), dtype=dtype) | ||
| to_pad = [(0, 0), (1, 1), (2, 2)] | ||
| out = pad_nd(img, to_pad, mode="constant", value=0) | ||
|
|
||
| assert out.shape == (1, 6, 8) | ||
| assert out.dtype == img.dtype | ||
|
|
||
| @pytest.mark.parametrize("mode", ["constant", "reflect", "replicate"]) | ||
| @pytest.mark.parametrize("dtype", [torch.bool, torch.int8, torch.float32]) | ||
| def test_pad_multiple_modes_dtype_preserved(mode, dtype): | ||
| """Test that pad_nd preserves dtype across multiple padding modes.""" | ||
| img = torch.ones((1, 4, 4), dtype=dtype) | ||
| to_pad = [(0, 0), (1, 1), (2, 2)] | ||
|
|
||
| out = pad_nd(img, to_pad, mode=mode, value=0) | ||
|
|
||
| assert out.shape == (1, 6, 8) | ||
| assert out.dtype == img.dtype |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
Repository: Project-MONAI/MONAI
Length of output: 178
🏁 Script executed:
Repository: Project-MONAI/MONAI
Length of output: 1953
🏁 Script executed:
Repository: Project-MONAI/MONAI
Length of output: 507
🌐 Web query:
PyTorch torch.nn.functional.pad exception types error handling documentation💡 Result:
Short answer: PyTorch's torch.nn.functional.pad doesn't have a dedicated "exceptions" section in the docs — it follows normal Python/C++ argument-checking and backend checks, so you should expect primarily TypeError and ValueError from bad arguments (and occasional RuntimeError from lower-level/back-end kernels). See examples and sources below.
Common cases and what raises them
References
If you want, I can: (a) show example inputs that trigger each exception and how to catch them (try/except), or (b) search the exact source-code checks for the PyTorch version you use — tell me your PyTorch version.
Error-handling approach is reasonable but fragile.
Matching substrings like "supported", "unexpected keyword", "implemented", "value" in exception messages works but is brittle—error text can change across PyTorch versions. The approach tries to distinguish fallback cases (unsupported modes/dtypes) from genuine errors, but PyTorch doesn't provide dedicated exception types for unsupported operations.
Document why substring matching is necessary here, or investigate whether PyTorch's error hierarchy or error codes could provide more stable detection. If documentation is chosen, explain the fallback detection strategy clearly for future maintainers.
🤖 Prompt for AI Agents