-
Notifications
You must be signed in to change notification settings - Fork 244
feat: add tensor type #756
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
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
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 was deleted.
Oops, something went wrong.
This file was deleted.
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,4 +1,4 @@ | ||
| import numpy as np | ||
| from .tensor import Tensor | ||
|
|
||
| Tensor = np.ndarray | ||
| Embedding = 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 |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| from .tensor import 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 |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| from typing import Union, TypeVar, Any, TYPE_CHECKING, Type, cast | ||
|
|
||
| import numpy as np | ||
| if TYPE_CHECKING: | ||
| from pydantic.fields import ModelField | ||
| from pydantic import BaseConfig, PydanticValueError | ||
|
|
||
| from docarray.document.base_node import BaseNode | ||
| from docarray.proto import DocumentProto, NdArrayProto, NodeProto | ||
|
|
||
| T = TypeVar('T', bound='Tensor') | ||
|
|
||
|
|
||
| class Tensor(np.ndarray, BaseNode): | ||
|
Member
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. why does it inherit from |
||
| @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, Any], field: 'ModelField', config: 'BaseConfig') -> T: | ||
| if isinstance(value, np.ndarray): | ||
| return cls.from_ndarray(value) | ||
| elif isinstance(value, Tensor): | ||
| return cast(T, value) | ||
| 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, got {type(value)}') | ||
|
|
||
| @classmethod | ||
| def from_ndarray(cls: Type[T], value: np.ndarray) -> T: | ||
| return value.view(cls) | ||
|
|
||
| def _to_nested_item_protobuf(self: T) -> 'NodeProto': | ||
| """Convert Document into a nested item protobuf message. This function should be called when the Document | ||
| is nested into another Document that need to be converted into a protobuf | ||
|
|
||
| :return: the nested item protobuf message | ||
| """ | ||
| nd_proto = NdArrayProto() | ||
| self.flush_ndarray(nd_proto, value=self) | ||
| NodeProto(tensor=nd_proto) | ||
| return NodeProto(tensor=nd_proto) | ||
|
|
||
| @classmethod | ||
| def read_ndarray(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_ndarray(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 | ||
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
Empty file.
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,16 @@ | ||
| import numpy as np | ||
|
|
||
| from docarray.typing import Tensor | ||
| from docarray import Document | ||
|
|
||
|
|
||
| def test_set_tensor(): | ||
|
|
||
| class MyDocument(Document): | ||
| tensor: Tensor | ||
|
|
||
| d = MyDocument(tensor=np.zeros((3, 224, 224))) | ||
|
|
||
| assert isinstance(d.tensor, Tensor) | ||
| assert isinstance(d.tensor, np.ndarray) | ||
| assert (d.tensor == np.zeros((3, 224, 224))).all() |
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
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.
please use global import