-
Notifications
You must be signed in to change notification settings - Fork 64
RSDK-4895: Make numpy an extra dependency #429
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
8 commits
Select commit
Hold shift + click to select a range
cbcb2dd
Changed toml to not require numpy, adding it as an extra/dev dependen…
233df56
Moved numpy utils into services/mlmodel/utils.py; changed imports acc…
9dbf519
Fixed lint errors
1719682
Made mlmodel utils tests separate; extracted error string out to utils
d8987be
Moved try except check for numpy only in __init__; Removed dev depend…
1be406e
Removed all str variable for import error
10c19f7
Merge branch 'main' into RSDK-4895
hexbabe 1f2d528
Removed unused imports and made lint
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
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
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
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,90 @@ | ||
import numpy as np | ||
from numpy.typing import NDArray | ||
from typing import Dict | ||
|
||
from viam.proto.service.mlmodel import ( | ||
FlatTensors, | ||
FlatTensor, | ||
FlatTensorDataDouble, | ||
FlatTensorDataFloat, | ||
FlatTensorDataInt16, | ||
FlatTensorDataInt32, | ||
FlatTensorDataInt64, | ||
FlatTensorDataInt8, | ||
FlatTensorDataUInt16, | ||
FlatTensorDataUInt32, | ||
FlatTensorDataUInt64, | ||
FlatTensorDataUInt8, | ||
) | ||
|
||
|
||
def flat_tensors_to_ndarrays(flat_tensors: FlatTensors) -> Dict[str, NDArray]: | ||
property_name_to_dtype = { | ||
"float_tensor": np.float32, | ||
"double_tensor": np.float64, | ||
"int8_tensor": np.int8, | ||
"int16_tensor": np.int16, | ||
"int32_tensor": np.int32, | ||
"int64_tensor": np.int64, | ||
"uint8_tensor": np.uint8, | ||
"uint16_tensor": np.uint16, | ||
"uint32_tensor": np.uint32, | ||
"uint64_tensor": np.uint64, | ||
} | ||
|
||
def make_ndarray(flat_data, dtype, shape): | ||
"""Takes flat data (protobuf RepeatedScalarFieldContainer | bytes) to output an ndarray | ||
of appropriate dtype and shape""" | ||
make_array = np.frombuffer if dtype == np.int8 or dtype == np.uint8 else np.array | ||
return make_array(flat_data, dtype).reshape(shape) | ||
|
||
ndarrays: Dict[str, NDArray] = dict() | ||
for name, flat_tensor in flat_tensors.tensors.items(): | ||
property_name = flat_tensor.WhichOneof("tensor") or flat_tensor.WhichOneof(b"tensor") | ||
if property_name: | ||
tensor_data = getattr(flat_tensor, property_name) | ||
flat_data, dtype, shape = tensor_data.data, property_name_to_dtype[property_name], flat_tensor.shape | ||
ndarrays[name] = make_ndarray(flat_data, dtype, shape) | ||
return ndarrays | ||
|
||
|
||
def ndarrays_to_flat_tensors(ndarrays: Dict[str, NDArray]) -> FlatTensors: | ||
dtype_name_to_tensor_data_class = { | ||
"float32": FlatTensorDataFloat, | ||
"float64": FlatTensorDataDouble, | ||
"int8": FlatTensorDataInt8, | ||
"int16": FlatTensorDataInt16, | ||
"int32": FlatTensorDataInt32, | ||
"int64": FlatTensorDataInt64, | ||
"uint8": FlatTensorDataUInt8, | ||
"uint16": FlatTensorDataUInt16, | ||
"uint32": FlatTensorDataUInt32, | ||
"uint64": FlatTensorDataUInt64, | ||
} | ||
|
||
def get_tensor_data(ndarray: NDArray): | ||
"""Takes an ndarray and returns the corresponding tensor data class instance | ||
e.g. FlatTensorDataInt8, FlatTensorDataUInt8 etc.""" | ||
tensor_data_class = dtype_name_to_tensor_data_class[ndarray.dtype.name] | ||
data = ndarray.flatten() | ||
if tensor_data_class == FlatTensorDataInt8 or tensor_data_class == FlatTensorDataUInt8: | ||
data = data.tobytes() # as per the proto, int8 and uint8 are stored as bytes | ||
elif tensor_data_class == FlatTensorDataInt16 or tensor_data_class == FlatTensorDataUInt16: | ||
data = data.astype(np.uint32) # as per the proto, int16 and uint16 are stored as uint32 | ||
tensor_data = tensor_data_class(data=data) | ||
return tensor_data | ||
|
||
def get_tensor_data_type(ndarray: NDArray): | ||
"""Takes ndarray and returns a FlatTensor datatype property to be set | ||
e.g. "float_tensor", "uint32_tensor" etc.""" | ||
if ndarray.dtype == np.float32: | ||
return "float_tensor" | ||
elif ndarray.dtype == np.float64: | ||
return "double_tensor" | ||
return f"{ndarray.dtype.name}_tensor" | ||
|
||
tensors_mapping: Dict[str, FlatTensor] = dict() | ||
for name, ndarray in ndarrays.items(): | ||
prop_name, prop_value = get_tensor_data_type(ndarray), get_tensor_data(ndarray) | ||
tensors_mapping[name] = FlatTensor(shape=ndarray.shape, **{prop_name: prop_value}) | ||
return FlatTensors(tensors=tensors_mapping) |
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
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,57 @@ | ||
import builtins | ||
import numpy as np | ||
import pytest | ||
|
||
from .mocks.services import MockMLModel | ||
|
||
from viam.services.mlmodel.utils import flat_tensors_to_ndarrays, ndarrays_to_flat_tensors | ||
|
||
|
||
# ignore warning about our out-of-bound int casting (i.e. uint32 -> int16) because we don't store uint32s for int16 & uint16 tensor data | ||
# > 2^16-1 in the first place (inherently they are int16, we just cast them to uint32 for the grpc message) | ||
@pytest.mark.filterwarnings("ignore::DeprecationWarning") | ||
def test_flat_tensors_to_ndarrays(): | ||
output = flat_tensors_to_ndarrays(MockMLModel.INTS_FLAT_TENSORS) | ||
assert len(output.keys()) == 4 | ||
assert all(name in output.keys() for name in ["0", "1", "2", "3"]) | ||
assert np.array_equal(output["0"], MockMLModel.INT8_NDARRAY) | ||
assert output["0"].dtype == np.int8 | ||
assert np.array_equal(output["1"], MockMLModel.INT16_NDARRAY) | ||
assert output["1"].dtype == np.int16 | ||
assert np.array_equal(output["2"], MockMLModel.INT32_NDARRAY) | ||
assert output["2"].dtype == np.int32 | ||
assert np.array_equal(output["3"], MockMLModel.INT64_NDARRAY) | ||
assert output["3"].dtype == np.int64 | ||
|
||
output = flat_tensors_to_ndarrays(MockMLModel.UINTS_FLAT_TENSORS) | ||
assert len(output.keys()) == 4 | ||
assert all(name in output.keys() for name in ["0", "1", "2", "3"]) | ||
assert np.array_equal(output["0"], MockMLModel.UINT8_NDARRAY) | ||
assert output["0"].dtype == np.uint8 | ||
assert np.array_equal(output["1"], MockMLModel.UINT16_NDARRAY) | ||
assert output["1"].dtype == np.uint16 | ||
assert np.array_equal(output["2"], MockMLModel.UINT32_NDARRAY) | ||
assert output["2"].dtype == np.uint32 | ||
assert np.array_equal(output["3"], MockMLModel.UINT64_NDARRAY) | ||
assert output["3"].dtype == np.uint64 | ||
|
||
output = flat_tensors_to_ndarrays(MockMLModel.DOUBLE_FLOAT_TENSORS) | ||
assert len(output.keys()) == 2 | ||
assert all(name in output.keys() for name in ["0", "1"]) | ||
assert np.array_equal(output["0"], MockMLModel.DOUBLE_NDARRAY) | ||
assert output["0"].dtype == np.float64 | ||
assert np.array_equal(output["1"], MockMLModel.FLOAT_NDARRAY) | ||
assert output["1"].dtype == np.float32 | ||
|
||
|
||
@pytest.mark.filterwarnings("ignore::DeprecationWarning") | ||
def test_ndarrays_to_flat_tensors(): | ||
output = ndarrays_to_flat_tensors(MockMLModel.INTS_NDARRAYS) | ||
assert len(output.tensors) == 4 | ||
assert all(name in output.tensors.keys() for name in ["0", "1", "2", "3"]) | ||
assert type(output.tensors["0"].int8_tensor.data) is builtins.bytes | ||
bytes_buffer = output.tensors["0"].int8_tensor.data | ||
assert np.array_equal(np.frombuffer(bytes_buffer, dtype=np.int8).reshape(output.tensors["0"].shape), MockMLModel.INT8_NDARRAY) | ||
assert np.array_equal(np.array(output.tensors["1"].int16_tensor.data, dtype=np.int16), MockMLModel.INT16_NDARRAY) | ||
assert np.array_equal(np.array(output.tensors["2"].int32_tensor.data, dtype=np.int32), MockMLModel.INT32_NDARRAY) | ||
assert np.array_equal(np.array(output.tensors["3"].int64_tensor.data, dtype=np.int64), MockMLModel.INT64_NDARRAY) |
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.