-
Notifications
You must be signed in to change notification settings - Fork 7.2k
refactor Datapoint dispatch mechanism #7747
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
Merged
Merged
Changes from 16 commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
d9e1379
[PoC] refactor Datapoint dispatch mechanism
pmeier 36b9d36
fix test
pmeier f36c64c
Merge branch 'main' into kernel-registration
pmeier bbaa35c
add dispatch to adjust_brightness
pmeier ca4ad32
enforce no register overwrite
pmeier d23a80e
[PoC] make wrapping interal kernel more convenient
pmeier bf47188
[PoC] enforce explicit no-ops
pmeier 74d5054
fix adjust_brightness tests and remove methods
pmeier e88be5e
Merge branch 'main' into kernel-registration
pmeier f178373
address minor comments
pmeier 65e80d0
make no-op registration a decorator
pmeier 9614477
Merge branch 'main'
pmeier 6ac08e4
explicit metadata
pmeier cac079b
implement dispatchers for erase five/ten_crop and temporal_subsample
pmeier c7256b4
make shape getters proper dispatchers
pmeier bf78cd6
fix
pmeier f86f89b
port normalize and to_dtype
pmeier d90daf6
address comments
pmeier 09eec9a
address comments and cleanup
pmeier 3730811
more cleanup
pmeier 7203453
Merge branch 'main' into kernel-registration
pmeier 31bee5f
port all remaining dispatchers to the new mechanism
pmeier a924013
put back legacy test_dispatch_datapoint
pmeier b3c2c88
minor test fixes
pmeier a1f5ea4
Update torchvision/transforms/v2/functional/_utils.py
pmeier d29d95b
reinstante antialias tests
pmeier 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
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
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 |
|---|---|---|
|
|
@@ -26,6 +26,7 @@ | |
| make_image_tensor, | ||
| make_segmentation_mask, | ||
| make_video, | ||
| make_video_tensor, | ||
| needs_cuda, | ||
| set_rng_seed, | ||
| ) | ||
|
|
@@ -39,6 +40,7 @@ | |
| from torchvision.transforms._functional_tensor import _max_value as get_max_value | ||
| from torchvision.transforms.functional import pil_modes_mapping | ||
| from torchvision.transforms.v2 import functional as F | ||
| from torchvision.transforms.v2.functional._utils import _KERNEL_REGISTRY | ||
|
|
||
|
|
||
| @pytest.fixture(autouse=True) | ||
|
|
@@ -177,17 +179,20 @@ def _check_dispatcher_dispatch(dispatcher, kernel, input, *args, **kwargs): | |
| preserved in doing so. For bounding boxes also checks that the format is preserved. | ||
| """ | ||
| if isinstance(input, datapoints._datapoint.Datapoint): | ||
| # Due to our complex dispatch architecture for datapoints, we cannot spy on the kernel directly, | ||
| # but rather have to patch the `Datapoint.__F` attribute to contain the spied on kernel. | ||
| spy = mock.MagicMock(wraps=kernel, name=kernel.__name__) | ||
| with mock.patch.object(F, kernel.__name__, spy): | ||
| # Due to Python's name mangling, the `Datapoint.__F` attribute is only accessible from inside the class. | ||
| # Since that is not the case here, we need to prefix f"_{cls.__name__}" | ||
| # See https://docs.python.org/3/tutorial/classes.html#private-variables for details | ||
| with mock.patch.object(datapoints._datapoint.Datapoint, "_Datapoint__F", new=F): | ||
| output = dispatcher(input, *args, **kwargs) | ||
|
|
||
| spy.assert_called_once() | ||
| if dispatcher in {F.resize, F.adjust_brightness}: | ||
| output = dispatcher(input, *args, **kwargs) | ||
| else: | ||
| # Due to our complex dispatch architecture for datapoints, we cannot spy on the kernel directly, | ||
| # but rather have to patch the `Datapoint.__F` attribute to contain the spied on kernel. | ||
| spy = mock.MagicMock(wraps=kernel, name=kernel.__name__) | ||
| with mock.patch.object(F, kernel.__name__, spy): | ||
| # Due to Python's name mangling, the `Datapoint.__F` attribute is only accessible from inside the class. | ||
| # Since that is not the case here, we need to prefix f"_{cls.__name__}" | ||
| # See https://docs.python.org/3/tutorial/classes.html#private-variables for details | ||
| with mock.patch.object(datapoints._datapoint.Datapoint, "_Datapoint__F", new=F): | ||
| output = dispatcher(input, *args, **kwargs) | ||
|
|
||
| spy.assert_called_once() | ||
| else: | ||
| with mock.patch(f"{dispatcher.__module__}.{kernel.__name__}", wraps=kernel) as spy: | ||
| output = dispatcher(input, *args, **kwargs) | ||
|
|
@@ -261,6 +266,8 @@ def _check_dispatcher_kernel_signature_match(dispatcher, *, kernel, input_type): | |
|
|
||
| def _check_dispatcher_datapoint_signature_match(dispatcher): | ||
| """Checks if the signature of the dispatcher matches the corresponding method signature on the Datapoint class.""" | ||
| if dispatcher in {F.resize, F.adjust_brightness}: | ||
| return | ||
| dispatcher_signature = inspect.signature(dispatcher) | ||
| dispatcher_params = list(dispatcher_signature.parameters.values())[1:] | ||
|
|
||
|
|
@@ -433,6 +440,33 @@ def transform(bbox): | |
| return torch.stack([transform(b) for b in bounding_boxes.reshape(-1, 4).unbind()]).reshape(bounding_boxes.shape) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| ("dispatcher", "registered_datapoint_clss"), | ||
| [(dispatcher, set(registry.keys())) for dispatcher, registry in _KERNEL_REGISTRY.items()], | ||
| ) | ||
| def test_exhaustive_kernel_registration(dispatcher, registered_datapoint_clss): | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This test will also be removed in the future, since we'll remove the passthrough behavior and thus the noop registration. But let's keep it until that happens to be sure this PR in this intermediate design stage is good as is. |
||
| missing = { | ||
| datapoints.Image, | ||
| datapoints.BoundingBoxes, | ||
| datapoints.Mask, | ||
| datapoints.Video, | ||
| } - registered_datapoint_clss | ||
| if missing: | ||
| names = sorted(f"datapoints.{cls.__name__}" for cls in missing) | ||
| raise AssertionError( | ||
| "\n".join( | ||
| [ | ||
| f"The dispatcher '{dispatcher.__name__}' has no kernel registered for", | ||
| "", | ||
| *[f"- {name}" for name in names], | ||
| "", | ||
| f"If available, register the kernels with @_register_kernel_internal({dispatcher.__name__}, ...).", | ||
| f"If not, register explicit no-ops with @_register_explicit_noops({', '.join(names)})", | ||
| ] | ||
| ) | ||
| ) | ||
|
|
||
|
|
||
| class TestResize: | ||
| INPUT_SIZE = (17, 11) | ||
| OUTPUT_SIZES = [17, [17], (17,), [12, 13], (12, 13)] | ||
|
|
@@ -1899,6 +1933,56 @@ def test_errors_warnings(self, make_input): | |
| assert out["mask"].dtype == mask_dtype | ||
|
|
||
|
|
||
| class TestAdjustBrightness: | ||
pmeier marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| _CORRECTNESS_BRIGHTNESS_FACTORS = [0.5, 0.0, 1.0, 5.0] | ||
| _DEFAULT_BRIGHTNESS_FACTOR = _CORRECTNESS_BRIGHTNESS_FACTORS[0] | ||
|
|
||
| @pytest.mark.parametrize( | ||
| ("kernel", "make_input"), | ||
| [ | ||
| (F.adjust_brightness_image_tensor, make_image), | ||
| (F.adjust_brightness_video, make_video), | ||
| ], | ||
| ) | ||
| @pytest.mark.parametrize("dtype", [torch.float32, torch.uint8]) | ||
| @pytest.mark.parametrize("device", cpu_and_cuda()) | ||
| def test_kernel(self, kernel, make_input, dtype, device): | ||
| check_kernel(kernel, make_input(dtype=dtype, device=device), brightness_factor=self._DEFAULT_BRIGHTNESS_FACTOR) | ||
|
|
||
| @pytest.mark.parametrize( | ||
| ("kernel", "make_input"), | ||
| [ | ||
| (F.adjust_brightness_image_tensor, make_image_tensor), | ||
| (F.adjust_brightness_image_pil, make_image_pil), | ||
| (F.adjust_brightness_image_tensor, make_image), | ||
| (F.adjust_brightness_video, make_video), | ||
| ], | ||
| ) | ||
| def test_dispatcher(self, kernel, make_input): | ||
| check_dispatcher(F.adjust_brightness, kernel, make_input(), brightness_factor=self._DEFAULT_BRIGHTNESS_FACTOR) | ||
|
|
||
| @pytest.mark.parametrize( | ||
| ("kernel", "input_type"), | ||
| [ | ||
| (F.adjust_brightness_image_tensor, torch.Tensor), | ||
| (F.adjust_brightness_image_pil, PIL.Image.Image), | ||
| (F.adjust_brightness_image_tensor, datapoints.Image), | ||
| (F.adjust_brightness_video, datapoints.Video), | ||
| ], | ||
| ) | ||
| def test_dispatcher_signature(self, kernel, input_type): | ||
| check_dispatcher_signatures_match(F.adjust_brightness, kernel=kernel, input_type=input_type) | ||
|
|
||
| @pytest.mark.parametrize("brightness_factor", _CORRECTNESS_BRIGHTNESS_FACTORS) | ||
| def test_image_correctness(self, brightness_factor): | ||
| image = make_image(dtype=torch.uint8, device="cpu") | ||
|
|
||
| actual = F.adjust_brightness(image, brightness_factor=brightness_factor) | ||
| expected = F.to_image_tensor(F.adjust_brightness(F.to_image_pil(image), brightness_factor=brightness_factor)) | ||
|
|
||
| torch.testing.assert_close(actual, expected) | ||
|
|
||
|
|
||
| class TestCutMixMixUp: | ||
| class DummyDataset: | ||
| def __init__(self, size, num_classes): | ||
|
|
@@ -2036,3 +2120,92 @@ def test_labels_getter_default_heuristic(key, sample_type): | |
| # it takes precedence over other keys which would otherwise be a match | ||
| d = {key: "something_else", "labels": labels} | ||
| assert transforms._utils._find_labels_default_heuristic(d) is labels | ||
|
|
||
|
|
||
| class TestShapeGetters: | ||
pmeier marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| @pytest.mark.parametrize( | ||
| ("kernel", "make_input"), | ||
| [ | ||
| (F.get_dimensions_image_tensor, make_image_tensor), | ||
| (F.get_dimensions_image_pil, make_image_pil), | ||
| (F.get_dimensions_image_tensor, make_image), | ||
| (F.get_dimensions_video, make_video), | ||
| ], | ||
| ) | ||
| def test_get_dimensions(self, kernel, make_input): | ||
| size = (10, 10) | ||
| color_space, num_channels = "RGB", 3 | ||
|
|
||
| input = make_input(size, color_space=color_space) | ||
|
|
||
| assert kernel(input) == F.get_dimensions(input) == [num_channels, *size] | ||
|
|
||
| @pytest.mark.parametrize( | ||
| ("kernel", "make_input"), | ||
| [ | ||
| (F.get_num_channels_image_tensor, make_image_tensor), | ||
| (F.get_num_channels_image_pil, make_image_pil), | ||
| (F.get_num_channels_image_tensor, make_image), | ||
| (F.get_num_channels_video, make_video), | ||
| ], | ||
| ) | ||
| def test_get_num_channels(self, kernel, make_input): | ||
| color_space, num_channels = "RGB", 3 | ||
|
|
||
| input = make_input(color_space=color_space) | ||
|
|
||
| assert kernel(input) == F.get_num_channels(input) == num_channels | ||
|
|
||
| @pytest.mark.parametrize( | ||
| ("kernel", "make_input"), | ||
| [ | ||
| (F.get_size_image_tensor, make_image_tensor), | ||
| (F.get_size_image_pil, make_image_pil), | ||
| (F.get_size_image_tensor, make_image), | ||
| (F.get_size_bounding_boxes, make_bounding_box), | ||
| (F.get_size_mask, make_detection_mask), | ||
| (F.get_size_mask, make_segmentation_mask), | ||
| (F.get_size_video, make_video), | ||
| ], | ||
| ) | ||
| def test_get_size(self, kernel, make_input): | ||
| size = (10, 10) | ||
|
|
||
| input = make_input(size) | ||
|
|
||
| assert kernel(input) == F.get_size(input) == list(size) | ||
|
|
||
| @pytest.mark.parametrize( | ||
| ("kernel", "make_input"), | ||
| [ | ||
| (F.get_num_frames_video, make_video_tensor), | ||
| (F.get_num_frames_video, make_video), | ||
| ], | ||
| ) | ||
| def test_get_num_frames(self, kernel, make_input): | ||
| num_frames = 4 | ||
|
|
||
| input = make_input(num_frames=num_frames) | ||
|
|
||
| assert kernel(input) == F.get_num_frames(input) == num_frames | ||
|
|
||
| @pytest.mark.parametrize( | ||
| ("dispatcher", "make_input"), | ||
| [ | ||
| (F.get_dimensions, make_bounding_box), | ||
| (F.get_dimensions, make_detection_mask), | ||
| (F.get_dimensions, make_segmentation_mask), | ||
| (F.get_num_channels, make_bounding_box), | ||
| (F.get_num_channels, make_detection_mask), | ||
| (F.get_num_channels, make_segmentation_mask), | ||
| (F.get_num_frames, make_image), | ||
| (F.get_num_frames, make_bounding_box), | ||
| (F.get_num_frames, make_detection_mask), | ||
| (F.get_num_frames, make_segmentation_mask), | ||
| ], | ||
| ) | ||
| def test_unsupported_types(self, dispatcher, make_input): | ||
| input = make_input() | ||
|
|
||
| with pytest.raises(TypeError, match=re.escape(str(type(input)))): | ||
| dispatcher(input) | ||
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
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
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.
Uh oh!
There was an error while loading. Please reload this page.