OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[TF FE] Check OV and FW outputs shapes and types in layer tests (#27375)
Roman Kazantsev0a3f43995376
diff --git a/src/frontends/tensorflow_common/src/op/tensor_list_operations.cpp b/src/frontends/tensorflow_common/src/op/tensor_list_operations.cppindex 5cbf4c92b8a..e082be49439 100644--- a/src/frontends/tensorflow_common/src/op/tensor_list_operations.cpp+++ b/src/frontends/tensorflow_common/src/op/tensor_list_operations.cpp@@ -199,8 +199,13 @@ OutputVector translate_tensor_list_length_op(const NodeContext& node) {auto tensor_list_shape = make_shared<v3::ShapeOf>(input_handle, element::i32);auto list_length = make_shared<v8::Slice>(tensor_list_shape, zero_const, one_const, one_const);- set_node_name(node.get_name(), list_length);- return {list_length};+ // output of TensorListLength must be a scalar+ // after Slice operation it is a 1D tensor with one element+ auto scalar_shape = make_shared<v0::Constant>(element::i32, Shape{0}, std::vector<int32_t>{});+ auto list_length_scalar = make_shared<v1::Reshape>(list_length, scalar_shape, false);++ set_node_name(node.get_name(), list_length_scalar);+ return {list_length_scalar};}OutputVector translate_tensor_list_concat_v2_op(const NodeContext& node) {diff --git a/src/frontends/tensorflow_common/src/op/tobool.cpp b/src/frontends/tensorflow_common/src/op/tobool.cppindex 9f1082d5df8..9025a35f549 100644--- a/src/frontends/tensorflow_common/src/op/tobool.cpp+++ b/src/frontends/tensorflow_common/src/op/tobool.cpp@@ -9,6 +9,8 @@#include "openvino/op/logical_and.hpp"#include "openvino/op/logical_or.hpp"#include "openvino/op/not_equal.hpp"+#include "openvino/op/range.hpp"+#include "openvino/op/reduce_logical_and.hpp"#include "openvino/op/reduce_prod.hpp"#include "openvino/op/select.hpp"#include "openvino/op/shape_of.hpp"@@ -22,47 +24,49 @@ namespace tensorflow {namespace op {OutputVector translate_tobool_op(const NodeContext& node) {// (rank(x) == 0 && x != 0) || (rank > 0 && ReduceProd(ShapeOf(x))) > 0-default_op_checks(node, 1, {"ToBool"});auto x = node.get_input(0);// prepare auxiliary zero and zero constants of the same type as the inputs- auto zero = create_same_type_const_scalar<int32_t>(x, 0);- auto zero_2 = make_shared<v0::Constant>(element::i32, Shape{}, 0);- auto true_const = make_shared<v0::Constant>(element::boolean, Shape{}, true);+ auto zero_x = create_same_type_const_scalar<int32_t>(x, 0);+ auto zero_i64 = make_shared<v0::Constant>(element::i64, Shape{}, 0);+ auto one_i64 = make_shared<v0::Constant>(element::i64, Shape{}, 1);auto false_const = make_shared<v0::Constant>(element::boolean, Shape{}, false);// compute a mask to get rank(x) == 0- auto x_rank = compute_subgraph_scalar_rank(x, element::i32);+ auto x_rank = compute_subgraph_scalar_rank(x, element::i64, true);+ // 1. try to evaluate if it satisfy non-zero scalar input// compute rank(x) == 0- auto is_zero = make_shared<v1::Equal>(x_rank, zero_2);-+ auto is_rank_zero = make_shared<v1::Equal>(x_rank, zero_i64);// compute mask to get x != 0- auto is_not_zero = make_shared<v1::NotEqual>(x, zero);-+ auto is_x_not_zero = make_shared<v1::NotEqual>(x, zero_x)->output(0);// compute (rank(x) == 0 && x != 0)- auto logical_and = make_shared<v1::LogicalAnd>(is_zero, is_not_zero);- // compute rank(x) > 0- auto greater_than_zero = make_shared<v1::Greater>(x_rank, zero_2);+ auto scalar_cond = make_shared<v1::LogicalAnd>(is_rank_zero, is_x_not_zero)->output(0);+ // generate reduce_axes+ auto reduce_axes = make_shared<v0::Range>(zero_i64, x_rank, one_i64);+ scalar_cond = make_shared<v1::ReduceLogicalAnd>(scalar_cond, reduce_axes, false);+ // correct result for empty tensor, for which scalar_cond is still equal to True+ scalar_cond = make_shared<v1::Select>(is_rank_zero, scalar_cond, false_const);+ // 2. try to evaluate if it is non-scalar input tensor and not empty tensor+ // compute rank(x) > 0+ auto rank_greater_than_zero = make_shared<v1::Greater>(x_rank, zero_i64);// compute ShapeOf(x)- auto cond_shape = make_shared<v3::ShapeOf>(x, element::i32);+ auto x_shape = make_shared<v3::ShapeOf>(x, element::i64);// compute ReduceProd(ShapeOf(x))) and axis- auto axis = make_shared<v0::Constant>(element::i32, Shape{}, 0);- auto reduce_prod = make_shared<v1::ReduceProd>(cond_shape, axis);-+ auto reduce_axis = make_shared<v0::Constant>(element::i32, Shape{}, 0);+ auto num_elems = make_shared<v1::ReduceProd>(x_shape, reduce_axis, false);// compute ReduceProd(ShapeOf(x))) > 0- auto greater_than__zero_2 = make_shared<v1::Greater>(reduce_prod, zero_2);+ auto num_elems_greater_than_zero = make_shared<v1::Greater>(num_elems, zero_i64);// compute (rank > 0 && ReduceProd(ShapeOf(x))) > 0- auto logical_and_2 = make_shared<v1::LogicalAnd>(greater_than_zero, greater_than__zero_2);-- auto logical_or = make_shared<v1::LogicalOr>(logical_and, logical_and_2);+ // it will be a scalar+ auto non_scalar_tensor_not_empty = make_shared<v1::LogicalAnd>(rank_greater_than_zero, num_elems_greater_than_zero);- auto tobool = make_shared<v1::Select>(logical_or, true_const, false_const);- set_node_name(node.get_name(), tobool);- return tobool->outputs();+ auto to_bool = make_shared<v1::LogicalOr>(scalar_cond, non_scalar_tensor_not_empty);+ set_node_name(node.get_name(), to_bool);+ return to_bool->outputs();}} // namespace op} // namespace tensorflow} // namespace frontend-} // namespace ov\ No newline at end of file+} // namespace ovdiff --git a/src/frontends/tensorflow_common/src/op/unique_with_counts.cpp b/src/frontends/tensorflow_common/src/op/unique_with_counts.cppindex 7c5c0a196aa..d3ca3156ed1 100644--- a/src/frontends/tensorflow_common/src/op/unique_with_counts.cpp+++ b/src/frontends/tensorflow_common/src/op/unique_with_counts.cpp@@ -6,6 +6,7 @@#include "openvino/op/unique.hpp"using namespace std;+using namespace ov;using namespace ov::op;namespace ov {@@ -19,8 +20,9 @@ OutputVector translate_unique_with_counts_op(const NodeContext& node) {// get input 'x' from node and node nameauto x = node.get_input(0);auto node_name = node.get_name();+ auto out_idx = node.get_attribute<element::Type>("out_idx", element::i32);- auto unique = make_shared<v10::Unique>(x, false, ov::element::i32, ov::element::i32);+ auto unique = make_shared<v10::Unique>(x, false, out_idx, out_idx);set_node_name(node_name, unique);// story 'y', 'idx', and 'count' outputs from Unique in separate variables@@ -34,4 +36,4 @@ OutputVector translate_unique_with_counts_op(const NodeContext& node) {} // namespace op} // namespace tensorflow} // namespace frontend-} // namespace ov\ No newline at end of file+} // namespace ovdiff --git a/tests/layer_tests/common/tf_layer_test_class.py b/tests/layer_tests/common/tf_layer_test_class.pyindex 99ade173772..98f47af542a 100644--- a/tests/layer_tests/common/tf_layer_test_class.py+++ b/tests/layer_tests/common/tf_layer_test_class.py@@ -1,14 +1,18 @@# Copyright (C) 2018-2024 Intel Corporation# SPDX-License-Identifier: Apache-2.0-from common.layer_test_class import CommonLayerTest+import numpy as np+from common.layer_utils import InferAPI+from common.utils.common_utils import generate_ir_python_api+from common.utils.tf_utils import save_to_pbfrom common.utils.tf_utils import summarize_graph-from common.utils.tflite_utils import get_tflite_results, save_pb_to_tflite-from common.utils.tf_utils import save_to_pb+from pathlib import Path++class CommonTFLayerTest:+ input_model_key = "input_model"-class CommonTFLayerTest(CommonLayerTest):def prepare_tf_inputs(self, inputs_dict):input = dict()for key in inputs_dict.keys():@@ -62,3 +66,130 @@ class CommonTFLayerTest(CommonLayerTest):else:# get results from tflitereturn get_tflite_results(self.use_legacy_frontend, inputs_dict, model_path)++ def _test(self, framework_model, ref_net, ie_device, precision, ir_version, temp_dir,+ use_legacy_frontend=False, infer_timeout=60, **kwargs):+ model_path = self.produce_model_path(framework_model=framework_model, save_path=temp_dir)+ self.use_legacy_frontend = use_legacy_frontend++ compress_to_fp16 = False if precision == 'FP32' else True++ if use_legacy_frontend:+ mo_params = {self.input_model_key: model_path,+ "output_dir": temp_dir,+ "compress_to_fp16": compress_to_fp16,+ "model_name": 'model'}++ if 'input_shapes' in kwargs and len(kwargs['input_shapes']):+ input_shapes_str = []+ for ishape in kwargs['input_shapes']:+ input_shapes_str.append('[' + ','.join([str(i) for i in ishape]) + ']')+ mo_params.update(dict(input_shape=','.join(input_shapes_str)))++ if 'input_names' in kwargs and len(kwargs['input_names']):+ mo_params.update(dict(input=','.join(kwargs['input_names'])))+ mo_params["use_legacy_frontend"] = True+ else:+ # pack input parameters for convert_model of OVC+ # that are different from MO+ mo_params = {"input_model": model_path,+ "output_dir": temp_dir,+ "compress_to_fp16": compress_to_fp16+ }++ if 'input_shapes' in kwargs and 'input_names' in kwargs:+ input_shapes = kwargs['input_shapes']+ input_names = kwargs['input_names']+ assert len(input_shapes) == len(input_names)+ input_dict = {}+ for input_name, input_shape in zip(input_names, input_shapes):+ input_dict[input_name] = input_shape+ mo_params.update(dict(input=input_dict))+ elif 'input_names' in kwargs:+ mo_params.update(dict(input=kwargs['input_names']))+ elif 'input_shapes' in kwargs:+ mo_params.update(dict(input=kwargs['input_shapes']))++ exit_code, stderr = generate_ir_python_api(**mo_params)+ assert not exit_code, (+ "IR generation failed with {} exit code: {}".format(exit_code, stderr))++ path_to_xml = Path(temp_dir, 'model.xml')+ path_to_bin = Path(temp_dir, 'model.bin')++ config = None+ # GPU default execution precision is FP16, so if we want to check FP32 inference+ # we need to set explicit precision hint+ if ie_device == 'GPU' and precision == 'FP32':+ config = {'INFERENCE_PRECISION_HINT': 'f32'}++ ie_engine = InferAPI(model=path_to_xml,+ weights=path_to_bin,+ device=ie_device,+ use_legacy_frontend=use_legacy_frontend)+ # Prepare feed dict+ if 'kwargs_to_prepare_input' in kwargs and kwargs['kwargs_to_prepare_input']:+ inputs_dict = self._prepare_input(ie_engine.get_inputs_info(precision),+ kwargs['kwargs_to_prepare_input'])+ else:+ inputs_dict = self._prepare_input(ie_engine.get_inputs_info(precision))++ # Infer using OpenVINO+ infer_res = ie_engine.infer(input_data=inputs_dict, infer_timeout=infer_timeout, config=config)++ # Infer using the original framework (TensorFlow or TFLite)+ fw_res = self.get_framework_results(inputs_dict=inputs_dict, model_path=model_path)++ if 'custom_eps' in kwargs and kwargs['custom_eps'] is not None:+ custom_eps = kwargs['custom_eps']+ else:+ if precision == 'FP32':+ custom_eps = 1e-4+ else:+ custom_eps = 5e-2+ # Compare Ie results with Framework results+ assert self.compare_ie_results_with_framework(infer_res=infer_res, framework_res=fw_res,+ framework_eps=custom_eps), \+ "Comparing with Framework failed: ie_res={}; framework_res={}.".format(infer_res,+ fw_res)++ # Feed dict for each input is filled with random number.+ # It is possible to redefine this function and generate your own input+ def _prepare_input(self, inputs_dict):+ for input in inputs_dict.keys():+ inputs_dict[input] = np.random.randint(-10, 10, inputs_dict[input]).astype(np.float32)+ return inputs_dict++ def compare_ie_results_with_framework(self, infer_res, framework_res, framework_eps):+ is_ok = True+ from common.utils.common_utils import allclose+ for framework_out_name in framework_res:+ if framework_out_name not in infer_res and len(infer_res) == 1:+ ov_res = list(infer_res.values())[0]+ else:+ ov_res = infer_res[framework_out_name]++ fw_res = np.array(framework_res[framework_out_name])++ assert fw_res.dtype == ov_res.dtype or \+ ov_res.dtype.type == str or \+ ov_res.dtype.type == np.str_, 'Outputs types are different: ' \+ 'OpenVINO output type - {}, ' \+ 'Framework output type - {}'.format(ov_res.dtype, fw_res.dtype)+ assert fw_res.shape == ov_res.shape, 'Outputs shapes are different: ' \+ 'OpenVINO output shape - {}, ' \+ 'Framework output shape - {}'.format(ov_res.shape, fw_res.shape)++ if not allclose(ov_res, fw_res,+ atol=framework_eps,+ rtol=framework_eps):+ is_ok = False+ if ov_res.dtype != bool:+ diff = np.array(abs(ov_res - fw_res)).max()+ print("Max diff is {}".format(diff))+ else:+ print("Boolean results are not equal")+ else:+ print("Accuracy validation successful!\n")+ print("absolute eps: {}, relative eps: {}".format(framework_eps, framework_eps))+ return is_okdiff --git a/tests/layer_tests/tensorflow_tests/test_tf_Equal.py b/tests/layer_tests/tensorflow_tests/test_tf_Equal.pyindex 8c0b496a7b4..4db05e00b58 100644--- a/tests/layer_tests/tensorflow_tests/test_tf_Equal.py+++ b/tests/layer_tests/tensorflow_tests/test_tf_Equal.py@@ -1,9 +1,8 @@# Copyright (C) 2022 Intel Corporation# SPDX-License-Identifier: Apache-2.0-import platform-import numpy as np+import platformimport pytestimport tensorflow as tffrom common.tf_layer_test_class import CommonTFLayerTest@@ -233,7 +232,7 @@ class TestEqualStr(CommonTFLayerTest):tf.compat.v1.reset_default_graph()with tf.compat.v1.Session() as sess:x = tf.compat.v1.placeholder(tf.string, x_shape, 'x')- y = tf.compat.v1.placeholder(tf.string, x_shape, 'y')+ y = tf.compat.v1.placeholder(tf.string, y_shape, 'y')tf.raw_ops.Equal(x=x, y=y)tf.compat.v1.global_variables_initializer()tf_net = sess.graph_def@@ -253,6 +252,8 @@ class TestEqualStr(CommonTFLayerTest):def test_equal_str(self, x_shape, y_shape,ie_device, precision, ir_version, temp_dir,use_legacy_frontend):+ if x_shape == [] and y_shape == []:+ pytest.skip("156746: EqualStr operation outputs 1D tensor for two input scalars")if ie_device == 'GPU' or run_in_jenkins():pytest.skip("operation extension is not supported on GPU")self._test(*self.create_equal_net(x_shape=x_shape, y_shape=y_shape),diff --git a/tests/layer_tests/tensorflow_tests/test_tf_ToBool.py b/tests/layer_tests/tensorflow_tests/test_tf_ToBool.pyindex 1beab798e14..789cc820502 100644--- a/tests/layer_tests/tensorflow_tests/test_tf_ToBool.py+++ b/tests/layer_tests/tensorflow_tests/test_tf_ToBool.py@@ -13,10 +13,16 @@ class TestToBool(CommonTFLayerTest):x_shape = inputs_info['x:0']inputs_data = {}inputs_data['x:0'] = np.random.randint(-10, 10, x_shape).astype(np.float32)-+ if self.input_shape == [] and self.with_zero:+ inputs_data['x:0'] = np.array(0, dtype=np.float32)+ elif self.input_shape == [] and not self.with_zero:+ inputs_data['x:0'] = np.array(1, dtype=np.float32)+return inputs_data- def create_tobool_net(self, input_shape, input_type):+ def create_tobool_net(self, input_shape, input_type, with_zero=None):+ self.with_zero = with_zero+ self.input_shape = input_shapeself.input_type = input_typetf.compat.v1.reset_default_graph()# Create the graph and model@@ -29,6 +35,10 @@ class TestToBool(CommonTFLayerTest):return tf_net, Nonetest_data_basic = [+ dict(input_shape=[], input_type=np.float32, with_zero=True),+ dict(input_shape=[], input_type=np.float32, with_zero=False),+ dict(input_shape=[0], input_type=np.float32),+ dict(input_shape=[4, 2, 0], input_type=np.float32),dict(input_shape=[10, 20], input_type=np.float32),dict(input_shape=[2, 3, 4], input_type=np.float32),]@@ -37,7 +47,7 @@ class TestToBool(CommonTFLayerTest):@pytest.mark.precommit@pytest.mark.nightlydef test_to_bool_basic(self, params, ie_device, precision, ir_version, temp_dir,- use_legacy_frontend):+ use_legacy_frontend):self._test(*self.create_tobool_net(**params),ie_device, precision, ir_version, temp_dir=temp_dir,- use_legacy_frontend=use_legacy_frontend)\ No newline at end of file+ use_legacy_frontend=use_legacy_frontend)