Tensor
docarray.typing.tensor.abstract_tensor
AbstractTensor
Bases: Generic[TTensor, T]
, AbstractType
, ABC
, Sized
Source code in docarray/typing/tensor/abstract_tensor.py
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 351 352 353 354 355 356 357 358 |
|
__docarray_validate_getitem__(item)
classmethod
This method validates the input to AbstractTensor.__class_getitem__
.
It is called at "class creation time", i.e. when a class is created with syntax of the form AnyTensor[shape].
The default implementation tries to cast any item
to a tuple of ints.
A subclass can override this method to implement custom validation logic.
The output of this is eventually passed to
AbstractTensor.__docarray_validate_shape__
as its shape
argument.
Raises ValueError
if the input item
does not pass validation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
item |
Any
|
The item to validate, passed to |
required |
Returns:
Type | Description |
---|---|
Tuple[int]
|
The validated item == the target shape of this tensor. |
Source code in docarray/typing/tensor/abstract_tensor.py
__docarray_validate_shape__(t, shape)
classmethod
Every tensor has to implement this method in order to enable syntax of the form AnyTensor[shape]. It is called when a tensor is assigned to a field of this type. i.e. when a tensor is passed to a Document field of type AnyTensor[shape].
The intended behaviour is as follows:
- If the shape of
t
is equal toshape
, returnt
. - If the shape of
t
is not equal toshape
, but can be reshaped toshape
, returnt
reshaped toshape
. - If the shape of
t
is not equal toshape
and cannot be reshaped toshape
, raise a ValueError.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
t |
T
|
The tensor to validate. |
required |
shape |
Tuple[Union[int, str], ...]
|
The shape to validate against. |
required |
Returns:
Type | Description |
---|---|
T
|
The validated tensor. |
Source code in docarray/typing/tensor/abstract_tensor.py
__getitem__(item)
abstractmethod
__iter__()
abstractmethod
__setitem__(index, value)
abstractmethod
get_comp_backend()
abstractmethod
staticmethod
to_protobuf()
abstractmethod
docarray.typing.tensor.ndarray
NdArray
Bases: np.ndarray
, AbstractTensor
, Generic[ShapeT]
Subclass of np.ndarray
, intended for use in a Document.
This enables (de)serialization from/to protobuf and json, data validation,
and coercion from compatible types like torch.Tensor
.
This type can also be used in a parametrized way, specifying the shape of the array.
from docarray import BaseDoc
from docarray.typing import NdArray
import numpy as np
class MyDoc(BaseDoc):
arr: NdArray
image_arr: NdArray[3, 224, 224]
square_crop: NdArray[3, 'x', 'x']
random_image: NdArray[3, ...] # first dimension is fixed, can have arbitrary shape
# create a document with tensors
doc = MyDoc(
arr=np.zeros((128,)),
image_arr=np.zeros((3, 224, 224)),
square_crop=np.zeros((3, 64, 64)),
random_image=np.zeros((3, 128, 256)),
)
assert doc.image_arr.shape == (3, 224, 224)
# automatic shape conversion
doc = MyDoc(
arr=np.zeros((128,)),
image_arr=np.zeros((224, 224, 3)), # will reshape to (3, 224, 224)
square_crop=np.zeros((3, 128, 128)),
random_image=np.zeros((3, 64, 128)),
)
assert doc.image_arr.shape == (3, 224, 224)
# !! The following will raise an error due to shape mismatch !!
from pydantic import ValidationError
try:
doc = MyDoc(
arr=np.zeros((128,)),
image_arr=np.zeros((224, 224)), # this will fail validation
square_crop=np.zeros((3, 128, 64)), # this will also fail validation
random_image=np.zeros((4, 64, 128)), # this will also fail validation
)
except ValidationError as e:
pass
Source code in docarray/typing/tensor/ndarray.py
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 |
|
from_protobuf(pb_msg)
classmethod
Read ndarray from a proto msg
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pb_msg |
NdArrayProto
|
required |
Returns:
Type | Description |
---|---|
T
|
a numpy array |
Source code in docarray/typing/tensor/ndarray.py
get_comp_backend()
staticmethod
Return the computational backend of the tensor
to_protobuf()
Transform self into a NdArrayProto protobuf message
Source code in docarray/typing/tensor/ndarray.py
unwrap()
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.
from docarray.typing import NdArray
import numpy as np
t1 = NdArray.validate(np.zeros((3, 224, 224)), None, None)
# here t1 is a docarray NdArray
t2 = t1.unwrap()
# here t2 is a pure np.ndarray but t1 is still a Docarray NdArray
# But both share the same underlying memory
Returns:
Type | Description |
---|---|
np.ndarray
|
a |
Source code in docarray/typing/tensor/ndarray.py
docarray.typing.tensor.tensorflow_tensor
TensorFlowTensor
Bases: AbstractTensor
, Generic[ShapeT]
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
and
NdArray
,
TensorFlowTensor
is not a subclass of tf.Tensor
(or torch.Tensor
, np.ndarray
respectively).
Instead, the tf.Tensor
is stored in
TensorFlowTensor.tensor
.
Therefore, to do operations on the actual tensor data you have to always access the
TensorFlowTensor.tensor
attribute.
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
instances.
Here, you do not have to access the .tensor
attribute,
but can instead just hand over your
TensorFlowTensor
instance.
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
in a Document as follows:
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
Source code in docarray/typing/tensor/tensorflow_tensor.py
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 351 352 353 354 355 356 357 |
|
__iter__()
__setitem__(index, value)
Set a slice of this tensor's tf.Tensor
Source code in docarray/typing/tensor/tensorflow_tensor.py
from_ndarray(value)
classmethod
Create a TensorFlowTensor
from a numpy array.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value |
np.ndarray
|
the numpy array |
required |
Returns:
Type | Description |
---|---|
T
|
a |
Source code in docarray/typing/tensor/tensorflow_tensor.py
from_protobuf(pb_msg)
classmethod
Read ndarray from a proto msg.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pb_msg |
NdArrayProto
|
required |
Returns:
Type | Description |
---|---|
T
|
a |
Source code in docarray/typing/tensor/tensorflow_tensor.py
get_comp_backend()
staticmethod
Return the computational backend of the tensor
Source code in docarray/typing/tensor/tensorflow_tensor.py
to_protobuf()
Transform self into an NdArrayProto protobuf message.
Source code in docarray/typing/tensor/tensorflow_tensor.py
unwrap()
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.
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
Returns:
Type | Description |
---|---|
tf.Tensor
|
a |
Source code in docarray/typing/tensor/tensorflow_tensor.py
docarray.typing.tensor.torch_tensor
TorchTensor
Bases: torch.Tensor
, AbstractTensor
, Generic[ShapeT]
Subclass of torch.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.
from docarray import BaseDoc
from docarray.typing import TorchTensor
import torch
class MyDoc(BaseDoc):
tensor: TorchTensor
image_tensor: TorchTensor[3, 224, 224]
square_crop: TorchTensor[3, 'x', 'x']
random_image: TorchTensor[
3, ...
] # first dimension is fixed, can have arbitrary shape
# create a document with tensors
doc = MyDoc(
tensor=torch.zeros(128),
image_tensor=torch.zeros(3, 224, 224),
square_crop=torch.zeros(3, 64, 64),
random_image=torch.zeros(3, 128, 256),
)
# automatic shape conversion
doc = MyDoc(
tensor=torch.zeros(128),
image_tensor=torch.zeros(224, 224, 3), # will reshape to (3, 224, 224)
square_crop=torch.zeros(3, 128, 128),
random_image=torch.zeros(3, 64, 128),
)
# !! The following will raise an error due to shape mismatch !!
from pydantic import ValidationError
try:
doc = MyDoc(
tensor=torch.zeros(128),
image_tensor=torch.zeros(224, 224), # this will fail validation
square_crop=torch.zeros(3, 128, 64), # this will also fail validation
random_image=torch.zeros(4, 64, 128), # this will also fail validation
)
except ValidationError as e:
pass
Compatibility with torch.compile()
PyTorch 2 introduced compilation support in the form of torch.compile()
.
Currently, torch.compile()
does not properly support subclasses of torch.Tensor
such as TorchTensor
.
The PyTorch team is currently working on a fix for this issue.
In the meantime, you can use the following workaround:
Workaround: Convert TorchTensor
to torch.Tensor
before calling torch.compile()
Converting any TorchTensor
s tor torch.Tensor
before calling torch.compile()
side-steps the issue:
from docarray import BaseDoc
from docarray.typing import TorchTensor
import torch
class MyDoc(BaseDoc):
tensor: TorchTensor
doc = MyDoc(tensor=torch.zeros(128))
def foo(tensor: torch.Tensor):
return tensor @ tensor.t()
foo_compiled = torch.compile(foo)
# unwrap the tensor before passing it to torch.compile()
foo_compiled(doc.tensor.unwrap())
Source code in docarray/typing/tensor/torch_tensor.py
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 |
|
from_ndarray(value)
classmethod
Create a TorchTensor
from a numpy array
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value |
np.ndarray
|
the numpy array |
required |
Returns:
Type | Description |
---|---|
T
|
a |
Source code in docarray/typing/tensor/torch_tensor.py
from_protobuf(pb_msg)
classmethod
Read ndarray from a proto msg
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pb_msg |
NdArrayProto
|
required |
Returns:
Type | Description |
---|---|
T
|
a |
Source code in docarray/typing/tensor/torch_tensor.py
get_comp_backend()
staticmethod
Return the computational backend of the tensor
new_empty(*args, **kwargs)
This method enables the deepcopy of TorchTensor
by returning another instance of this subclass.
If this function is not implemented, the deepcopy will throw an RuntimeError from Torch.
Source code in docarray/typing/tensor/torch_tensor.py
to_protobuf()
Transform self into a NdArrayProto
protobuf message
Source code in docarray/typing/tensor/torch_tensor.py
unwrap()
Return the original torch.Tensor
without any memory copy.
The original view rest intact and is still a Document TorchTensor
but the return object is a pure torch.Tensor
but both object share
the same memory layout.
from docarray.typing import TorchTensor
import torch
t = TorchTensor.validate(torch.zeros(3, 224, 224), None, None)
# here t is a docarray TorchTensor
t2 = t.unwrap()
# here t2 is a pure torch.Tensor but t1 is still a Docarray TorchTensor
# But both share the same underlying memory
Returns:
Type | Description |
---|---|
torch.Tensor
|
a |
Source code in docarray/typing/tensor/torch_tensor.py
docarray.typing.tensor.AnyTensor
Bases: AbstractTensor
, Generic[ShapeT]
Represents a tensor object that can be used with TensorFlow, PyTorch, and NumPy type. !!! note: when doing type checking (mypy or pycharm type checker), this class will actually be replace by a Union of the three tensor types. You can reason about this class as if it was a Union.
from docarray import BaseDoc
from docarray.typing import AnyTensor
class MyTensorDoc(BaseDoc):
tensor: AnyTensor
# Example usage with TensorFlow:
# import tensorflow as tf
# doc = MyTensorDoc(tensor=tf.zeros(1000, 2))
# Example usage with PyTorch:
import torch
doc = MyTensorDoc(tensor=torch.zeros(1000, 2))
# Example usage with NumPy:
import numpy as np
doc = MyTensorDoc(tensor=np.zeros((1000, 2)))
Source code in docarray/typing/tensor/tensor.py
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 |
|