forked from ray-project/ray
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[AIR] Add
TorchVisionPreprocessor
(ray-project#30578)
Co-authored-by: Clark Zinzow <clarkzinzow@gmail.com> Closes ray-project#30403 Signed-off-by: tmynn <hovhannes.tamoyan@gmail.com>
- Loading branch information
1 parent
887eb88
commit c488327
Showing
9 changed files
with
285 additions
and
88 deletions.
There are no files selected for viewing
This file contains 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 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 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 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 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 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,95 @@ | ||
from typing import TYPE_CHECKING, Callable, Dict, List, Union | ||
|
||
import numpy as np | ||
|
||
from ray.data.preprocessor import Preprocessor | ||
from ray.util.annotations import PublicAPI | ||
|
||
if TYPE_CHECKING: | ||
import torch | ||
|
||
|
||
@PublicAPI(stability="alpha") | ||
class TorchVisionPreprocessor(Preprocessor): | ||
"""Apply a `TorchVision transform <https://pytorch.org/vision/stable/transforms.html>`_ | ||
to image columns. | ||
Examples: | ||
>>> import ray | ||
>>> dataset = ray.data.read_images("s3://anonymous@air-example-data-2/imagenet-sample-images") | ||
>>> dataset # doctest: +ellipsis | ||
Dataset(num_blocks=..., num_rows=..., schema={image: ArrowTensorType(shape=(..., 3), dtype=float)}) | ||
:class:`TorchVisionPreprocessor` passes ndarrays to your transform. To convert | ||
ndarrays to Torch tensors, add ``ToTensor`` to your pipeline. | ||
>>> from torchvision import transforms | ||
>>> from ray.data.preprocessors import TorchVisionPreprocessor | ||
>>> transform = transforms.Compose([ | ||
... transforms.ToTensor(), | ||
... transforms.Resize((224, 224)), | ||
... ]) | ||
>>> preprocessor = TorchVisionPreprocessor(["image"], transform=transform) | ||
>>> preprocessor.transform(dataset) # doctest: +ellipsis | ||
Dataset(num_blocks=..., num_rows=..., schema={image: ArrowTensorType(shape=(3, 224, 224), dtype=float)}) | ||
For better performance, set ``batched`` to ``True`` and replace ``ToTensor`` | ||
with a batch-supporting ``Lambda``. | ||
>>> transform = transforms.Compose([ | ||
... transforms.Lambda( | ||
... lambda batch: torch.as_tensor(batch).permute(0, 3, 1, 2)) | ||
... ), | ||
... transforms.Resize((224, 224)) | ||
... ]) | ||
>>> preprocessor = TorchVisionPreprocessor( | ||
... ["image"], transform=transform, batched=True | ||
... ) | ||
>>> preprocessor.transform(dataset) # doctest: +ellipsis | ||
Dataset(num_blocks=..., num_rows=..., schema={image: ArrowTensorType(shape=(3, 224, 224), dtype=float)}) | ||
Args: | ||
columns: The columns to apply the TorchVision transform to. | ||
transform: The TorchVision transform you want to apply. This transform should | ||
accept an ``np.ndarray`` as input and return a ``torch.Tensor`` as output. | ||
batched: If ``True``, apply ``transform`` to batches of shape | ||
:math:`(B, H, W, C)`. Otherwise, apply ``transform`` to individual images. | ||
""" # noqa: E501 | ||
|
||
_is_fittable = False | ||
|
||
def __init__( | ||
self, | ||
columns: List[str], | ||
transform: Callable[["np.ndarray"], "torch.Tensor"], | ||
batched: bool = False, | ||
): | ||
self._columns = columns | ||
self._fn = transform | ||
self._batched = batched | ||
|
||
def __repr__(self) -> str: | ||
return ( | ||
f"{self.__class__.__name__}(columns={self._columns}, " | ||
f"transform={self._fn!r})" | ||
) | ||
|
||
def _transform_numpy( | ||
self, np_data: Union["np.ndarray", Dict[str, "np.ndarray"]] | ||
) -> Union["np.ndarray", Dict[str, "np.ndarray"]]: | ||
def transform(batch: np.ndarray) -> np.ndarray: | ||
if self._batched: | ||
return self._fn(batch).numpy() | ||
return np.array([self._fn(array).numpy() for array in batch]) | ||
|
||
if isinstance(np_data, dict): | ||
outputs = {} | ||
for column, batch in np_data.items(): | ||
if column in self._columns: | ||
outputs[column] = transform(batch) | ||
else: | ||
outputs[column] = batch | ||
else: | ||
outputs = transform(np_data) | ||
|
||
return outputs |
Oops, something went wrong.