-
Notifications
You must be signed in to change notification settings - Fork 244
feat: universal tensor type #843
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 all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
bd8328b
refactor: rename tensor type to ndarray type
JohannesMessner 79c9f09
feat: add tensor type for any kind of tensor
JohannesMessner 2eaa190
Merge branch 'feat-rewrite-v2' into feat-universal-tensor
JohannesMessner 6e1f3b7
test: add more tests for proto
JohannesMessner 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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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 |
|---|---|---|
| @@ -1,14 +1,15 @@ | ||
| from docarray.typing.id import ID | ||
| from docarray.typing.tensor import Tensor, TorchTensor | ||
| from docarray.typing.tensor import NdArray, Tensor, TorchTensor | ||
| from docarray.typing.tensor.embedding import Embedding | ||
| from docarray.typing.url import AnyUrl, ImageUrl, TextUrl | ||
|
|
||
| __all__ = [ | ||
| 'TorchTensor', | ||
| 'Tensor', | ||
| 'NdArray', | ||
| 'Embedding', | ||
| 'ImageUrl', | ||
| 'TextUrl', | ||
| 'AnyUrl', | ||
| 'ID', | ||
| 'Tensor', | ||
| ] |
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 |
|---|---|---|
| @@ -1,4 +1,5 @@ | ||
| from docarray.typing.tensor.ndarray import NdArray | ||
| from docarray.typing.tensor.tensor import Tensor | ||
| from docarray.typing.tensor.torch_tensor import TorchTensor | ||
|
|
||
| __all__ = ['Tensor', 'TorchTensor'] | ||
| __all__ = ['NdArray', 'TorchTensor', 'Tensor'] |
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,121 @@ | ||
| from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Type, TypeVar, Union, cast | ||
|
|
||
| import numpy as np | ||
|
|
||
| from docarray.typing.abstract_type import AbstractType | ||
|
|
||
| if TYPE_CHECKING: | ||
| from pydantic.fields import ModelField | ||
| from pydantic import BaseConfig | ||
|
|
||
| from docarray.proto import NdArrayProto, NodeProto | ||
|
|
||
| T = TypeVar('T', bound='NdArray') | ||
|
|
||
|
|
||
| class NdArray(np.ndarray, AbstractType): | ||
| @classmethod | ||
| def __get_validators__(cls): | ||
| # one or more validators may be yielded which will be called in the | ||
| # order to validate the input, each validator will receive as an input | ||
| # the value returned from the previous validator | ||
| yield cls.validate | ||
|
|
||
| @classmethod | ||
| def validate( | ||
| cls: Type[T], | ||
| value: Union[T, np.ndarray, List[Any], Tuple[Any], Any], | ||
| field: 'ModelField', | ||
| config: 'BaseConfig', | ||
| ) -> T: | ||
| if isinstance(value, np.ndarray): | ||
| return cls.from_ndarray(value) | ||
| elif isinstance(value, NdArray): | ||
| return cast(T, value) | ||
| elif isinstance(value, list) or isinstance(value, tuple): | ||
| try: | ||
| arr_from_list: np.ndarray = np.asarray(value) | ||
| return cls.from_ndarray(arr_from_list) | ||
| except Exception: | ||
| pass # handled below | ||
| else: | ||
| try: | ||
| arr: np.ndarray = np.ndarray(value) | ||
| return cls.from_ndarray(arr) | ||
| except Exception: | ||
| pass # handled below | ||
| raise ValueError(f'Expected a numpy.ndarray compatible type, got {type(value)}') | ||
|
|
||
| @classmethod | ||
| def from_ndarray(cls: Type[T], value: np.ndarray) -> T: | ||
| return value.view(cls) | ||
|
|
||
| @classmethod | ||
| def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: | ||
| # this is needed to dump to json | ||
| field_schema.update(type='string', format='tensor') | ||
|
|
||
| def _to_json_compatible(self) -> np.ndarray: | ||
| """ | ||
| Convert tensor into a json compatible object | ||
| :return: a list representation of the tensor | ||
| """ | ||
| return self.unwrap() | ||
|
|
||
| def unwrap(self) -> np.ndarray: | ||
| """ | ||
| Return the original ndarray without any memory copy. | ||
|
|
||
| The original view rest intact and is still a Document NdArray | ||
| but the return object is a pure np.ndarray but both object share | ||
| the same memory layout. | ||
|
|
||
| EXAMPLE USAGE | ||
| .. code-block:: python | ||
| from docarray.typing import NdArray | ||
| import numpy as np | ||
|
|
||
| t1 = NdArray.validate(np.zeros((3, 224, 224)), None, None) | ||
| # here t is a docarray TenNdArray | ||
| t2 = t.unwrap() | ||
| # here t2 is a pure np.ndarray but t1 is still a Docarray NdArray | ||
| # But both share the same underlying memory | ||
|
|
||
|
|
||
| :return: a numpy ndarray | ||
| """ | ||
| return self.view(np.ndarray) | ||
|
|
||
| def _to_node_protobuf(self: T, field: str = 'ndarray') -> NodeProto: | ||
| """Convert itself into a NodeProto protobuf message. This function should | ||
| be called when the Document is nested into another Document that need to be | ||
| converted into a protobuf | ||
| :param field: field in which to store the content in the node proto | ||
| :return: the nested item protobuf message | ||
| """ | ||
| nd_proto = NdArrayProto() | ||
| self._flush_tensor_to_proto(nd_proto, value=self) | ||
| return NodeProto(**{field: nd_proto}) | ||
|
|
||
| @classmethod | ||
| def from_protobuf(cls: Type[T], pb_msg: 'NdArrayProto') -> 'T': | ||
| """ | ||
| read ndarray from a proto msg | ||
| :param pb_msg: | ||
| :return: a numpy array | ||
| """ | ||
| source = pb_msg.dense | ||
| if source.buffer: | ||
| x = np.frombuffer(source.buffer, dtype=source.dtype) | ||
| return cls.from_ndarray(x.reshape(source.shape)) | ||
| elif len(source.shape) > 0: | ||
| return cls.from_ndarray(np.zeros(source.shape)) | ||
| else: | ||
| raise ValueError(f'proto message {pb_msg} cannot be cast to a NdArray') | ||
|
|
||
| @staticmethod | ||
| def _flush_tensor_to_proto(pb_msg: 'NdArrayProto', value: 'NdArray'): | ||
| pb_msg.dense.buffer = value.tobytes() | ||
| pb_msg.dense.ClearField('shape') | ||
| pb_msg.dense.shape.extend(list(value.shape)) | ||
| pb_msg.dense.dtype = value.dtype.str |
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 |
|---|---|---|
| @@ -1,121 +1,6 @@ | ||
| from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Type, TypeVar, Union, cast | ||
| from typing import Union | ||
|
|
||
| import numpy as np | ||
| from docarray.typing.tensor.ndarray import NdArray | ||
| from docarray.typing.tensor.torch_tensor import TorchTensor | ||
|
|
||
| from docarray.typing.abstract_type import AbstractType | ||
|
|
||
| if TYPE_CHECKING: | ||
| from pydantic.fields import ModelField | ||
| from pydantic import BaseConfig | ||
|
|
||
| from docarray.proto import NdArrayProto, NodeProto | ||
|
|
||
| T = TypeVar('T', bound='Tensor') | ||
|
|
||
|
|
||
| class Tensor(np.ndarray, AbstractType): | ||
| @classmethod | ||
| def __get_validators__(cls): | ||
| # one or more validators may be yielded which will be called in the | ||
| # order to validate the input, each validator will receive as an input | ||
| # the value returned from the previous validator | ||
| yield cls.validate | ||
|
|
||
| @classmethod | ||
| def validate( | ||
| cls: Type[T], | ||
| value: Union[T, np.ndarray, List[Any], Tuple[Any], Any], | ||
| field: 'ModelField', | ||
| config: 'BaseConfig', | ||
| ) -> T: | ||
| if isinstance(value, np.ndarray): | ||
| return cls.from_ndarray(value) | ||
| elif isinstance(value, Tensor): | ||
| return cast(T, value) | ||
| elif isinstance(value, list) or isinstance(value, tuple): | ||
| try: | ||
| arr_from_list: np.ndarray = np.asarray(value) | ||
| return cls.from_ndarray(arr_from_list) | ||
| except Exception: | ||
| pass # handled below | ||
| else: | ||
| try: | ||
| arr: np.ndarray = np.ndarray(value) | ||
| return cls.from_ndarray(arr) | ||
| except Exception: | ||
| pass # handled below | ||
| raise ValueError(f'Expected a numpy.ndarray compatible type, got {type(value)}') | ||
|
|
||
| @classmethod | ||
| def from_ndarray(cls: Type[T], value: np.ndarray) -> T: | ||
| return value.view(cls) | ||
|
|
||
| @classmethod | ||
| def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: | ||
| # this is needed to dump to json | ||
| field_schema.update(type='string', format='tensor') | ||
|
|
||
| def _to_json_compatible(self) -> np.ndarray: | ||
| """ | ||
| Convert tensor into a json compatible object | ||
| :return: a list representation of the tensor | ||
| """ | ||
| return self.unwrap() | ||
|
|
||
| def unwrap(self) -> np.ndarray: | ||
| """ | ||
| Return the original ndarray without any memory copy. | ||
|
|
||
| The original view rest intact and is still a Document Tensor | ||
| but the return object is a pure np.ndarray but both object share | ||
| the same memory layout. | ||
|
|
||
| EXAMPLE USAGE | ||
| .. code-block:: python | ||
| from docarray.typing import Tensor | ||
| import numpy as np | ||
|
|
||
| t1 = Tensor.validate(np.zeros((3, 224, 224)), None, None) | ||
| # here t is a docarray Tensor | ||
| t2 = t.unwrap() | ||
| # here t2 is a pure np.ndarray but t1 is still a Docarray Tensor | ||
| # But both share the same underlying memory | ||
|
|
||
|
|
||
| :return: a numpy ndarray | ||
| """ | ||
| return self.view(np.ndarray) | ||
|
|
||
| def _to_node_protobuf(self: T, field: str = 'tensor') -> NodeProto: | ||
| """Convert itself into a NodeProto protobuf message. This function should | ||
| be called when the Document is nested into another Document that need to be | ||
| converted into a protobuf | ||
| :param field: field in which to store the content in the node proto | ||
| :return: the nested item protobuf message | ||
| """ | ||
| nd_proto = NdArrayProto() | ||
| self._flush_tensor_to_proto(nd_proto, value=self) | ||
| return NodeProto(**{field: nd_proto}) | ||
|
|
||
| @classmethod | ||
| def from_protobuf(cls: Type[T], pb_msg: 'NdArrayProto') -> 'T': | ||
| """ | ||
| read ndarray from a proto msg | ||
| :param pb_msg: | ||
| :return: a numpy array | ||
| """ | ||
| source = pb_msg.dense | ||
| if source.buffer: | ||
| x = np.frombuffer(source.buffer, dtype=source.dtype) | ||
| return cls.from_ndarray(x.reshape(source.shape)) | ||
| elif len(source.shape) > 0: | ||
| return cls.from_ndarray(np.zeros(source.shape)) | ||
| else: | ||
| raise ValueError(f'proto message {pb_msg} cannot be cast to a Tensor') | ||
|
|
||
| @staticmethod | ||
| def _flush_tensor_to_proto(pb_msg: 'NdArrayProto', value: 'Tensor'): | ||
| pb_msg.dense.buffer = value.tobytes() | ||
| pb_msg.dense.ClearField('shape') | ||
| pb_msg.dense.shape.extend(list(value.shape)) | ||
| pb_msg.dense.dtype = value.dtype.str | ||
| Tensor = Union[NdArray, TorchTensor] |
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.