Files
openvino/runtime/bindings/python/tests/runtime.py
T
+2 2c9a4c59f2 [Python API] add new api (#8149)
* Bind exec core ov (#50)

* Output const node python tests (#52)

* add python bindings tests for Output<const ov::None>

* add proper tests

* add new line

* rename ie_version to version

* Pszmel/bind infer request (#51)

* remove set_batch, get_blob and set_blob

* update InferRequest class

* change InferenceEngine::InferRequest to ov::runtime::InferRequest

* update set_callback body

* update bindings to reflect ov::runtime::InferRequest

* bind set_input_tensor and get_input_tensor

* style fix

* clen ie_infer_queue.cpp

* Bind exec core ov (#50)

* bind core, exec_net classes

* rm unused function

* add new line

* rename ie_infer_request -> infer_request

* update imports

* update __init__.py

* update ie_api.py

* Replace old containers with the new one

* create impl for create_infer_request

* comment out infer_queue to avoid errors with old infer_request

* update infer_request bind to reflect new infer_request api

* comment out inpuit_info from ie_network to avoid errors with old containers

* Register new containers and comment out InferQueue

* update infer request tests

* style fix

* remove unused imports

* remove unused imports and 2 methods

* add tests to cover all new methods from infer_request

* style fix

* add test

* remove registration of InferResults

* update name of exception_ptr parameter

* update the loops that iterate through inputs and outputs

* clean setCustomCallbacks

* style fix

* add Tensor import

* style fix

* update infer and normalize_inputs

* style fix

* rename startTime and endTime

* Create test for mixed keys as infer arguments

* update infer function

* update return type of infer

Co-authored-by: Bartek Szmelczynski <bartosz.szmelczynski@intel.com>

* fix get_version

* fix opaque issue

* some cosmetic changes

* fix codestyle in tests

* make tests green

* Extend python InferRequest

* Extend python Function

* Change return value of infer call

* Fix missing precisions conversions in CPU plugin

* Rework of runtime for new tests

* Fixed onnx reading in python tests

* Edit compatibility tests

* Edit tests

* Add FLOAT_LIKE xfails

* [Python API] bind ProfilingInfo (#55)

* bind ProfilingInfo

* Add tests

* Fix code style

* Add property

* fix codestyle

* Infer new request method (#56)

* fix conflicts, add infer_new_request function

* remove redundant functions, fix style

* revert the unwanted changes

* revert removal of the Blob

* revert removal of isTblob

* add add_extension from path

* codestyle

* fix win build

* add inputs-outputs to function

* Hot-fix CPU plugin with precision

* fix start_async

* add performance hint to time infer (#8480)

* Updated common migration pipeline (#8176)

* Updated common migration pipeline

* Fixed merge issue

* Added new model and extended example

* Fixed typo

* Added v10-v11 comparison

* Avoid redundant graph nodes scans (#8415)

* Refactor work with env variables (#8208)

* del MO_ROOT

* del MO_ROOT from common_utils.py

* add MO_PATH to common_utils.py

* change mo_path

* [IE Sample Scripts] Use cmake to build samples (#8442)

* Use cmake to build samples

* Add the option to set custom build output folder

* Remove opset8 from compatibility ngraph python API (#8452)

* [GPU] OneDNN gpu submodule update to version 2.5 (#8449)

* [GPU] OneDNN gpu submodule update to version 2.5

* [GPU] Updated onednn submodule and added layout optimizer fix

* Install rules for static libraries case (#8384)

* Proper cmake install for static libraries case

* Added an ability to skip template plugin

* Added install rules for VPU / GPU

* Install more libraries

* Fixed absolute TBB include paths

* Disable GNA

* Fixed issue with linker

* Some fixes

* Fixed linkage issues in tests

* Disabled some tests

* Updated CI pipelines

* Fixed Windows linkage

* Fixed custom_opset test for static casr

* Fixed CVS-70313

* Continue on error

* Fixed clanf-format

* Try to fix Windows linker

* Fixed compilation

* Disable samples

* Fixed samples build with THREADING=SEQ

* Fixed link error on Windows

* Fixed ieFuncTests

* Added static Azure CI

* Revert "Fixed link error on Windows"

This reverts commit 78cca36fd2.

* Merge static and dynamic linux pipelines

* Fixed Azure

* fix codestyle

Co-authored-by: Bartek Szmelczynski <bartosz.szmelczynski@intel.com>
Co-authored-by: Piotr Szmelczynski <piotr.szmelczynski@intel.com>
Co-authored-by: jiwaszki <jan.iwaszkiewicz@intel.com>
Co-authored-by: Alexey Lebedev <alexey.lebedev@intel.com>
Co-authored-by: Victor Kuznetsov <victor.kuznetsov@intel.com>
Co-authored-by: Ilya Churaev <ilya.churaev@intel.com>
Co-authored-by: Tomasz Jankowski <tomasz1.jankowski@intel.com>
Co-authored-by: Dmitry Pigasin <dmitry.pigasin@intel.com>
Co-authored-by: Artur Kulikowski <artur.kulikowski@intel.com>
Co-authored-by: Ilya Znamenskiy <ilya.znamenskiy@intel.com>
Co-authored-by: Ilya Lavrenov <ilya.lavrenov@intel.com>
2021-11-12 22:44:44 +03:00

146 lines
5.9 KiB
Python

# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""Provide a layer of abstraction for an OpenVINO runtime environment."""
import logging
from typing import Dict, List, Union
import numpy as np
from openvino import Core
from openvino.exceptions import UserInputError
from openvino.impl import Function, Node, PartialShape, Type
from openvino.utils.types import NumericData, get_shape, get_dtype
import tests
log = logging.getLogger(__name__)
def runtime(backend_name: str = "CPU") -> "Runtime":
"""Create a Runtime object (helper factory)."""
return Runtime(backend_name)
def get_runtime():
"""Return runtime object."""
if tests.BACKEND_NAME is not None:
return runtime(backend_name=tests.BACKEND_NAME)
else:
return runtime()
class Runtime(object):
"""Represents an nGraph runtime environment."""
def __init__(self, backend_name: str) -> None:
self.backend_name = backend_name
log.debug("Creating Inference Engine for %s" % backend_name)
self.backend = Core()
assert backend_name in self.backend.available_devices, (
'The requested device "' + backend_name + '" is not supported!'
)
def set_config(self, config: Dict[str, str]) -> None:
"""Set the inference engine configuration."""
self.backend.set_config(config, device_name=self.backend_name)
def __repr__(self) -> str:
return "<Runtime: Backend='{}'>".format(self.backend_name)
def computation(self, node_or_function: Union[Node, Function], *inputs: Node) -> "Computation":
"""Return a callable Computation object."""
if isinstance(node_or_function, Node):
ng_function = Function(node_or_function, inputs, node_or_function.name)
return Computation(self, ng_function)
elif isinstance(node_or_function, Function):
return Computation(self, node_or_function)
else:
raise TypeError(
"Runtime.computation must be called with an nGraph Function object "
"or an nGraph node object an optionally Parameter node objects. "
"Called with: %s",
node_or_function,
)
class Computation(object):
"""nGraph callable computation object."""
def __init__(self, runtime: Runtime, ng_function: Function) -> None:
self.runtime = runtime
self.function = ng_function
self.parameters = ng_function.get_parameters()
self.results = ng_function.get_results()
self.network_cache = {}
def __repr__(self) -> str:
params_string = ", ".join([param.name for param in self.parameters])
return "<Computation: {}({})>".format(self.function.get_name(), params_string)
def convert_buffers(self, source_buffers, target_dtypes):
converted_buffers = []
for i in range(len(source_buffers)):
target_dtype = target_dtypes[i]
# custom conversion for bf16
if self.results[i].get_output_element_type(0) == Type.bf16:
converted_buffers.append((source_buffers[i].view(np.uint32) >> 16).astype(np.uint16))
else:
converted_buffers.append(source_buffers[i].astype(target_dtype))
return converted_buffers
def __call__(self, *input_values: NumericData) -> List[NumericData]:
"""Run computation on input values and return result."""
# Input validation
if len(input_values) < len(self.parameters):
raise UserInputError(
"Expected %s params, received not enough %s values.", len(self.parameters), len(input_values)
)
param_types = [param.get_element_type() for param in self.parameters]
param_names = [param.friendly_name for param in self.parameters]
# ignore not needed input values
input_values = [
np.array(input_value[0], dtype=get_dtype(input_value[1]))
for input_value in zip(input_values[: len(self.parameters)], param_types)
]
input_shapes = [get_shape(input_value) for input_value in input_values]
if self.network_cache.get(str(input_shapes)) is None:
function = self.function
if self.function.is_dynamic():
function.reshape(dict(zip(param_names, [PartialShape(i) for i in input_shapes])))
self.network_cache[str(input_shapes)] = function
else:
function = self.network_cache[str(input_shapes)]
executable_network = self.runtime.backend.compile_model(function, self.runtime.backend_name)
for parameter, input in zip(self.parameters, input_values):
parameter_shape = parameter.get_output_partial_shape(0)
input_shape = PartialShape(input.shape)
if len(input.shape) > 0 and not parameter_shape.compatible(input_shape):
raise UserInputError(
"Provided tensor's shape: %s does not match the expected: %s.",
input_shape,
parameter_shape,
)
request = executable_network.create_infer_request()
result_buffers = request.infer(dict(zip(param_names, input_values)))
# # Note: other methods to get result_buffers from request
# # First call infer with no return value:
# request.infer(dict(zip(param_names, input_values)))
# # Now use any of following options:
# result_buffers = [request.get_tensor(n).data for n in request.outputs]
# result_buffers = [request.get_output_tensor(i).data for i in range(len(request.outputs))]
# result_buffers = [t.data for t in request.output_tensors]
# # Since OV overwrite result data type we have to convert results to the original one.
original_dtypes = [get_dtype(result.get_output_element_type(0)) for result in self.results]
converted_buffers = self.convert_buffers(result_buffers, original_dtypes)
return converted_buffers