-
Notifications
You must be signed in to change notification settings - Fork 237
Expand file tree
/
Copy pathtensorflow_tensor.py
More file actions
350 lines (276 loc) · 11 KB
/
tensorflow_tensor.py
File metadata and controls
350 lines (276 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
from typing import TYPE_CHECKING, Any, Generic, Type, TypeVar, Union, cast
import numpy as np
import orjson
from docarray.base_doc.base_node import BaseNode
from docarray.typing.proto_register import _register_proto
from docarray.typing.tensor.abstract_tensor import AbstractTensor
from docarray.utils._internal.misc import (
import_library,
is_jax_available,
is_torch_available,
)
if TYPE_CHECKING:
import tensorflow as tf # type: ignore
from docarray.computation.tensorflow_backend import TensorFlowCompBackend
from docarray.proto import NdArrayProto
else:
tf = import_library('tensorflow', raise_error=True)
torch_available = is_torch_available()
if torch_available:
import torch
jax_available = is_jax_available()
if jax_available:
import jax.numpy as jnp
T = TypeVar('T', bound='TensorFlowTensor')
ShapeT = TypeVar('ShapeT')
tf_base: type = type(tf.Tensor)
node_base: type = type(BaseNode)
# the mypy error suppression below should not be necessary anymore once the following
# is released in mypy: https://github.com/python/mypy/pull/14135
class metaTensorFlow(
AbstractTensor.__parametrized_meta__, # type: ignore
node_base, # type: ignore
tf_base, # type: ignore
): # type: ignore
pass
@_register_proto(proto_type_name='tensorflow_tensor')
class TensorFlowTensor(AbstractTensor, Generic[ShapeT], metaclass=metaTensorFlow):
"""
TensorFlowTensor class with a `.tensor` attribute of type `tf.Tensor`,
intended for use in a Document.
This enables (de)serialization from/to protobuf and json, data validation,
and coercion from compatible types like numpy.ndarray.
This type can also be used in a parametrized way, specifying the shape of the
tensor.
In comparison to [`TorchTensor`][docarray.typing.TorchTensor] and
[`NdArray`][docarray.typing.tensor.ndarray.NdArray],
[`TensorFlowTensor`][docarray.typing.tensor.tensorflow_tensor.TensorFlowTensor]
is not a subclass of `tf.Tensor` (or `torch.Tensor`, `np.ndarray` respectively).
Instead, the `tf.Tensor` is stored in
[`TensorFlowTensor.tensor`][docarray.typing.tensor.tensorflow_tensor.TensorFlowTensor].
Therefore, to do operations on the actual tensor data you have to always access the
[`TensorFlowTensor.tensor`][docarray.typing.tensor.tensorflow_tensor.TensorFlowTensor]
attribute.
---
```python
import tensorflow as tf
from docarray.typing import TensorFlowTensor
t = TensorFlowTensor(tensor=tf.zeros((224, 224)))
# tensorflow functions
broadcasted = tf.broadcast_to(t.tensor, (3, 224, 224))
broadcasted = tf.broadcast_to(t.unwrap(), (3, 224, 224))
# this will fail:
# broadcasted = tf.broadcast_to(t, (3, 224, 224))
# tensorflow.Tensor methods:
arr = t.tensor.numpy()
arr = t.unwrap().numpy()
# this will fail:
# arr = t.numpy()
```
---
The [`TensorFlowBackend`] however, operates on our
[`TensorFlowTensor`][docarray.typing.TensorFlowTensor] instances.
Here, you do not have to access the `.tensor` attribute,
but can instead just hand over your
[`TensorFlowTensor`][docarray.typing.TensorFlowTensor] instance.
---
```python
import tensorflow as tf
from docarray.typing import TensorFlowTensor
zeros = TensorFlowTensor(tensor=tf.zeros((3, 224, 224)))
comp_be = zeros.get_comp_backend()
reshaped = comp_be.reshape(zeros, (224, 224, 3))
assert comp_be.shape(reshaped) == (224, 224, 3)
```
---
You can use [`TensorFlowTensor`][docarray.typing.TensorFlowTensor] in a Document as follows:
---
```python
from docarray import BaseDoc
from docarray.typing import TensorFlowTensor
import tensorflow as tf
class MyDoc(BaseDoc):
tensor: TensorFlowTensor
image_tensor: TensorFlowTensor[3, 224, 224]
square_crop: TensorFlowTensor[3, 'x', 'x']
random_image: TensorFlowTensor[
3, ...
] # first dimension is fixed, can have arbitrary shape
# create a document with tensors
doc = MyDoc(
tensor=tf.zeros((128,)),
image_tensor=tf.zeros((3, 224, 224)),
square_crop=tf.zeros((3, 64, 64)),
random_image=tf.zeros((3, 128, 256)),
)
# automatic shape conversion
doc = MyDoc(
tensor=tf.zeros((128,)),
image_tensor=tf.zeros((224, 224, 3)), # will reshape to (3, 224, 224)
square_crop=tf.zeros((3, 128, 128)),
random_image=tf.zeros((3, 64, 128)),
)
# !! The following will raise an error due to shape mismatch !!
from pydantic import ValidationError
try:
doc = MyDoc(
tensor=tf.zeros((128,)),
image_tensor=tf.zeros((224, 224)), # this will fail validation
square_crop=tf.zeros((3, 128, 64)), # this will also fail validation
random_image=tf.zeros(4, 64, 128), # this will also fail validation
)
except ValidationError as e:
pass
```
---
"""
__parametrized_meta__ = metaTensorFlow
def __init__(self, tensor: tf.Tensor):
super().__init__()
self.tensor = tensor
def __getitem__(self, item):
from docarray.computation.tensorflow_backend import TensorFlowCompBackend
tensor = self.unwrap()
if tensor is not None:
tensor = tensor[item]
return TensorFlowCompBackend._cast_output(t=tensor)
def __setitem__(self, index, value):
"""Set a slice of this tensor's `tf.Tensor`"""
t = self.unwrap()
value = tf.cast(value, dtype=t.dtype)
var = tf.Variable(t)
var[index].assign(value)
self.tensor = tf.constant(var)
def __iter__(self):
"""Iterate over the elements of this tensor's `tf.Tensor`."""
for i in range(len(self)):
yield self[i]
@classmethod
def _docarray_validate(
cls: Type[T],
value: Union[T, np.ndarray, str, Any],
) -> T:
if isinstance(value, TensorFlowTensor):
return cast(T, value)
elif isinstance(value, tf.Tensor):
return cls._docarray_from_native(value)
elif isinstance(value, np.ndarray):
return cls._docarray_from_ndarray(value)
elif isinstance(value, AbstractTensor):
return cls._docarray_from_ndarray(value._docarray_to_ndarray())
elif torch_available and isinstance(value, torch.Tensor):
return cls._docarray_from_native(value.detach().cpu().numpy())
elif jax_available and isinstance(value, jnp.ndarray):
return cls._docarray_from_native(value.__array__())
elif isinstance(value, str):
value = orjson.loads(value)
try:
arr: tf.Tensor = tf.constant(value)
return cls(tensor=arr)
except Exception:
pass # handled below
raise ValueError(
f'Expected a tensorflow.Tensor compatible type, got {type(value)}'
)
@classmethod
def _docarray_from_native(cls: Type[T], value: Union[tf.Tensor, T]) -> T:
"""
Create a `TensorFlowTensor` from a `tf.Tensor` or `TensorFlowTensor`
instance.
:param value: instance of `tf.Tensor` or `TensorFlowTensor`
:return: a `TensorFlowTensor`
"""
if isinstance(value, TensorFlowTensor):
if cls.__unparametrizedcls__: # None if the tensor is parametrized
value.__class__ = cls.__unparametrizedcls__ # type: ignore
else:
value.__class__ = cls
return cast(T, value)
else:
if cls.__unparametrizedcls__: # None if the tensor is parametrized
cls_param_ = cls.__unparametrizedcls__
cls_param = cast(Type[T], cls_param_)
else:
cls_param = cls
return cls_param(tensor=value)
@staticmethod
def get_comp_backend() -> 'TensorFlowCompBackend':
"""Return the computational backend of the tensor"""
from docarray.computation.tensorflow_backend import TensorFlowCompBackend
return TensorFlowCompBackend()
def _docarray_to_json_compatible(self) -> np.ndarray:
"""
Convert `TensorFlowTensor` into a json compatible object
:return: a representation of the tensor compatible with orjson
"""
return self.unwrap().numpy()
def to_protobuf(self) -> 'NdArrayProto':
"""
Transform self into an NdArrayProto protobuf message.
"""
from docarray.proto import NdArrayProto
nd_proto = NdArrayProto()
value_np = self.tensor.numpy()
nd_proto.dense.buffer = value_np.tobytes()
nd_proto.dense.ClearField('shape')
nd_proto.dense.shape.extend(list(value_np.shape))
nd_proto.dense.dtype = value_np.dtype.str
return nd_proto
@classmethod
def from_protobuf(cls: Type[T], pb_msg: 'NdArrayProto') -> 'T':
"""
Read ndarray from a proto msg.
:param pb_msg:
:return: a `TensorFlowTensor`
"""
source = pb_msg.dense
if source.buffer:
x = np.frombuffer(bytearray(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 TensorFlowTensor.'
)
@classmethod
def from_ndarray(cls: Type[T], value: np.ndarray) -> T:
"""Create a `TensorFlowTensor` from a numpy array.
:param value: the numpy array
:return: a `TensorFlowTensor`
"""
return cls._docarray_from_native(tf.convert_to_tensor(value))
def unwrap(self) -> tf.Tensor:
"""
Return the original `tf.Tensor` without any memory copy.
The original view rest intact and is still a Document `TensorFlowTensor`
but the return object is a pure `tf.Tensor` but both object share
the same memory layout.
---
```python
from docarray.typing import TensorFlowTensor
import tensorflow as tf
t1 = TensorFlowTensor.validate(tf.zeros((3, 224, 224)), None, None)
# here t1 is a docarray TensorFlowTensor
t2 = t1.unwrap()
# here t2 is a pure tf.Tensor but t1 is still a Docarray TensorFlowTensor
```
---
:return: a `tf.Tensor`
"""
return self.tensor
def __len__(self) -> int:
return len(self.tensor)
@classmethod
def _docarray_from_ndarray(cls: Type[T], value: np.ndarray) -> T:
"""Create a `tensor from a numpy array
PS: this function is different from `from_ndarray` because it is private under the docarray namesapce.
This allows us to avoid breaking change if one day we introduce a Tensor backend with a `from_ndarray` method.
"""
return cls.from_ndarray(value)
def _docarray_to_ndarray(self) -> np.ndarray:
"""cast itself to a numpy array"""
return self.tensor.numpy()
@property
def shape(self):
return tf.shape(self.tensor)