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
[Samples] benchmark_app: introduced compile_only mode (#35113)
Vladislav Golubev9ac988fde16c
diff --git a/samples/cpp/benchmark_app/benchmark_app.hpp b/samples/cpp/benchmark_app/benchmark_app.hppindex 475cd455fe7..e6f5d034a09 100644--- a/samples/cpp/benchmark_app/benchmark_app.hpp+++ b/samples/cpp/benchmark_app/benchmark_app.hpp@@ -55,7 +55,9 @@ static const char target_device_message[] =/// @brief message for iterations countstatic const char iterations_count_message[] ="Optional. Number of iterations. "- "If not specified, the number of iterations is calculated depending on a device.";+ "If not specified, the number of iterations is calculated depending on a device. "+ "Set -niter 0 to compile the model and exit without running inference "+ "(useful for models with dynamic shapes that would otherwise require -shape, -data_shape, or -i).";// @brief message for enabling cachingstatic const char cache_dir_message[] = "Optional. Enables caching of loaded models to specified directory. "diff --git a/samples/cpp/benchmark_app/main.cpp b/samples/cpp/benchmark_app/main.cppindex 7552906710b..a31215a5f40 100644--- a/samples/cpp/benchmark_app/main.cpp+++ b/samples/cpp/benchmark_app/main.cpp@@ -147,7 +147,7 @@ bool parse_and_check_command_line(int argc, char* argv[]) {throw std::logic_error("Incorrect API. Please set -api option to `sync` or `async` value.");}if (FLAGS_api == "sync") {- if ((FLAGS_t == 0) && (FLAGS_nireq > FLAGS_niter)) {+ if ((FLAGS_t == 0) && FLAGS_niter != 0 && (FLAGS_nireq > FLAGS_niter)) {throw std::logic_error("Number of iterations should be greater than number of infer requests when using sync API.");}@@ -636,6 +636,11 @@ int main(int argc, char* argv[]) {});};+ // When -niter 0 is explicitly passed, compile the model and exit without running inference.+ // This is useful for validating compilation of models with dynamic shapes that would otherwise+ // require -shape, -data_shape, or -i to be specified.+ const bool compile_only = isFlagSetInCommandLine("niter") && FLAGS_niter == 0;+if (FLAGS_load_from_file && !isNetworkCompiled) {if (!FLAGS_mean_values.empty() || !FLAGS_scale_values.empty()) {throw std::runtime_error("--mean_values and --scale_values aren't supported with --load_from_file. "@@ -675,7 +680,8 @@ int main(int argc, char* argv[]) {inputFiles,FLAGS_scale_values,FLAGS_mean_values,- compiledModel.inputs());+ compiledModel.inputs(),+ compile_only);if (batchSize == 0) {batchSize = 1;}@@ -723,7 +729,8 @@ int main(int argc, char* argv[]) {FLAGS_scale_values,FLAGS_mean_values,inputInfo,- reshape);+ reshape,+ compile_only);if (reshape) {benchmark_app::PartialShapes shapes = {};for (auto& item : app_inputs_info[0])@@ -829,9 +836,13 @@ int main(int argc, char* argv[]) {topology_name = model->get_friendly_name();- batchSize = get_batch_size(app_inputs_info.at(0));- warn_if_no_batch(app_inputs_info.at(0));- slog::info << "Model batch size: " << batchSize << slog::endl;+ // In compile_only mode dataShape is left empty (no inference will run), so+ // get_batch_size() would crash. batchSize is only needed for steps 8-10 anyway.+ if (!compile_only) {+ batchSize = get_batch_size(app_inputs_info.at(0));+ warn_if_no_batch(app_inputs_info.at(0));+ slog::info << "Model batch size: " << batchSize << slog::endl;+ }printInputAndOutputsInfoShort(*model);// ----------------- 7. Loading the model to the device@@ -903,18 +914,41 @@ int main(int argc, char* argv[]) {inputFiles,FLAGS_scale_values,FLAGS_mean_values,- compiledModel.inputs());+ compiledModel.inputs(),+ compile_only);isDynamicNetwork = areNetworkInputsDynamic(app_inputs_info.at(0));- batchSize = get_batch_size(app_inputs_info.at(0));- warn_if_no_batch(app_inputs_info.at(0));- slog::info << "Model batch size: " << batchSize << slog::endl;+ // In compile_only mode dataShape is left empty (no inference will run), so+ // get_batch_size() would crash. batchSize is only needed for steps 8-10 anyway.+ if (!compile_only) {+ batchSize = get_batch_size(app_inputs_info.at(0));+ warn_if_no_batch(app_inputs_info.at(0));+ slog::info << "Model batch size: " << batchSize << slog::endl;+ }if (batchSize == 0) {batchSize = 1;}}+ if (compile_only) {+ slog::info << "Model compiled successfully. Skipping inference due to -niter 0." << slog::endl;+ next_step("skipped"); // 8 - Querying optimal runtime parameters+ next_step("skipped"); // 9 - Creating infer requests and preparing input tensors+ next_step("skipped"); // 10 - Measuring performance+ // ----------------- 11. Dumping statistics report+ // -------------------------------------------------------------+ next_step();+ if (!FLAGS_dump_config.empty()) {+ dump_config(FLAGS_dump_config, config);+ slog::info << "OpenVINO Runtime configuration settings were dumped to " << FLAGS_dump_config+ << slog::endl;+ }+ if (statistics)+ statistics->dump();+ return 0;+ }+bool allow_inference_only_or_sync = can_measure_as_static(app_inputs_info);if (!allow_inference_only_or_sync && FLAGS_api == "sync") {diff --git a/samples/cpp/benchmark_app/utils.cpp b/samples/cpp/benchmark_app/utils.cppindex 4cfd4558797..690ba600839 100644--- a/samples/cpp/benchmark_app/utils.cpp+++ b/samples/cpp/benchmark_app/utils.cpp@@ -480,7 +480,8 @@ std::vector<benchmark_app::InputsInfo> get_inputs_info(const std::string& shape_const std::string& scale_string,const std::string& mean_string,const std::vector<ov::Output<const ov::Node>>& input_info,- bool& reshape_required) {+ bool& reshape_required,+ bool compile_only) {std::map<std::string, std::vector<std::string>> shape_map = parse_input_parameters(shape_string, input_info);std::map<std::string, std::vector<std::string>> data_shapes_map =parse_input_parameters(data_shapes_string, input_info);@@ -711,15 +712,27 @@ std::vector<benchmark_app::InputsInfo> get_inputs_info(const std::string& shape_} else if (!data_shapes_map.empty()) {throw std::logic_error("Can't find model input name \"" + name + "\" in \"-data_shape " +data_shapes_string + "\" command line parameter");- } else {+ } else if (!compile_only) {throw std::logic_error("-i or -data_shape command line parameter should be set for all inputs in case "- "of model with dynamic shapes.");+ "of model with dynamic shapes. "+ "If you only need to compile the model without running inference, "+ "use -niter 0 to skip this requirement.");}// Update shape with batch if needed (only in static shape case)// Update blob shape only not affecting network shape to trigger dynamic batch size caseif (batch_size != 0) {- if (ov::layout::has_batch(info.layout)) {+ if (info.dataShape.empty()) {+ // dataShape can be empty only when compile_only=true and the input is dynamic with no+ // -data_shape/-i provided.+ if (!compile_only) {+ throw std::logic_error("dataShape is empty for input '" + item.get_any_name() ++ "' in non-compile_only mode.");+ }+ slog::warn << "-b option is ignored in compile_only mode (no concrete data shape available for '"+ << item.get_any_name() << "')." << slog::endl;+ is_there_at_least_one_batch_dim = true;+ } else if (ov::layout::has_batch(info.layout)) {std::size_t batch_index = ov::layout::batch_idx(info.layout);if (info.dataShape.at(batch_index) != batch_size) {if (info.partialShape.is_static()) {@@ -772,7 +785,8 @@ std::vector<benchmark_app::InputsInfo> get_inputs_info(const std::string& shape_const std::map<std::string, std::vector<std::string>>& fileNames,const std::string& scale_string,const std::string& mean_string,- const std::vector<ov::Output<const ov::Node>>& input_info) {+ const std::vector<ov::Output<const ov::Node>>& input_info,+ bool compile_only) {bool reshape_required = false;return get_inputs_info(shape_string,layout_string,@@ -782,7 +796,8 @@ std::vector<benchmark_app::InputsInfo> get_inputs_info(const std::string& shape_scale_string,mean_string,input_info,- reshape_required);+ reshape_required,+ compile_only);}void dump_config(const std::string& filename, const std::map<std::string, ov::AnyMap>& config) {diff --git a/samples/cpp/benchmark_app/utils.hpp b/samples/cpp/benchmark_app/utils.hppindex fec43ba73e2..230a0d52f65 100644--- a/samples/cpp/benchmark_app/utils.hpp+++ b/samples/cpp/benchmark_app/utils.hpp@@ -107,7 +107,8 @@ std::vector<benchmark_app::InputsInfo> get_inputs_info(const std::string& shape_const std::string& scale_string,const std::string& mean_string,const std::vector<ov::Output<const ov::Node>>& input_info,- bool& reshape_required);+ bool& reshape_required,+ bool compile_only = false);/// <summary>/// Parses command line data and data obtained from the function and returns configuration of each input@@ -132,7 +133,8 @@ std::vector<benchmark_app::InputsInfo> get_inputs_info(const std::string& shape_const std::map<std::string, std::vector<std::string>>& fileNames,const std::string& scale_string,const std::string& mean_string,- const std::vector<ov::Output<const ov::Node>>& input_info);+ const std::vector<ov::Output<const ov::Node>>& input_info,+ bool compile_only = false);void dump_config(const std::string& filename, const std::map<std::string, ov::AnyMap>& config);void load_config(const std::string& filename, std::map<std::string, ov::AnyMap>& config);diff --git a/tests/samples_tests/smoke_tests/test_benchmark_app.py b/tests/samples_tests/smoke_tests/test_benchmark_app.pyindex 81667f9007d..2c324168c43 100755--- a/tests/samples_tests/smoke_tests/test_benchmark_app.py+++ b/tests/samples_tests/smoke_tests/test_benchmark_app.py@@ -266,6 +266,175 @@ def test_benchmark_app_no_warmup_help(sample_language):assert 'Skip warmup inference' in output[email protected]('sample_language', ['C++', 'Python'])[email protected]('device', get_devices())+def test_compile_only_via_niter_0(sample_language, device, cache, tmp_path):+ """Test that -niter 0 compiles the model and exits without running inference."""+ output = get_cmd_output(+ get_executable(sample_language),+ *prepend(cache, 'dog-224x224.bmp', 'bvlcalexnet-12.onnx', tmp_path),+ '-d', device,+ '-niter', '0',+ )+ assert 'FPS' not in output+ assert 'Model compiled successfully' in output+ assert 'Skipping inference due to -niter 0' in output+ assert '(skipped)' in output++[email protected]('sample_language', ['C++', 'Python'])[email protected]('device', get_devices())+def test_compile_only_niter_0_dynamic_shape(sample_language, device, tmp_path):+ """Test that -niter 0 compiles a dynamic-shape model without requiring -data_shape or -i."""+ param = opset.parameter([-1, -1, 3, -1], ov.Type.f32, name='input')+ result = opset.result(opset.relu(param), name='output')+ model = ov.Model([result], [param], 'dynamic_model')++ model_path = tmp_path / 'dynamic_model.xml'+ ov.save_model(model, model_path)++ output = get_cmd_output(+ get_executable(sample_language),+ '-m', model_path,+ '-d', device,+ '-niter', '0',+ )+ assert 'FPS' not in output+ assert 'Model compiled successfully' in output+ assert 'Skipping inference due to -niter 0' in output++[email protected]('device', get_devices())+def test_compile_only_niter_0_dynamic_shape_with_batch(device, tmp_path):+ """Test that -b combined with -niter 0 and a dynamic-shape model is handled correctly.++ C++: dataShape is empty for dynamic inputs in compile_only mode (no -data_shape/-i provided).+ The batch update block must not access dataShape.at(batch_index) — it should warn and+ skip instead.+ Python: batch update uses partial_shape (always populated from the model), so -b is applied+ correctly without any special handling or warning.+ """+ param = opset.parameter([-1, 3, -1, -1], ov.Type.f32, name='input')+ param.set_layout(ov.Layout('NCHW'))+ result = opset.result(opset.relu(param), name='output')+ model = ov.Model([result], [param], 'dynamic_model_with_batch')++ model_path = tmp_path / 'dynamic_model.xml'+ ov.save_model(model, model_path)++ # C++: -b is ignored (cannot update empty dataShape), a warning is emitted+ cpp_output = get_cmd_output(+ get_executable('C++'),+ '-m', model_path,+ '-d', device,+ '-niter', '0',+ '-b', '4',+ )+ assert 'FPS' not in cpp_output+ assert 'Model compiled successfully' in cpp_output+ assert 'Skipping inference due to -niter 0' in cpp_output+ assert '-b option is ignored in compile_only mode' in cpp_output++ # Python: -b is applied to partial_shape before compilation — compiles successfully, no warning+ py_output = get_cmd_output(+ get_executable('Python'),+ '-m', model_path,+ '-d', device,+ '-niter', '0',+ '-b', '4',+ )+ assert 'FPS' not in py_output+ assert 'Model compiled successfully' in py_output+ assert 'Skipping inference due to -niter 0' in py_output+ assert '-b option is ignored in compile_only mode' not in py_output+++# Note: devices which do not support export_model() are excluded.[email protected]('device', sorted({'CPU', 'GPU'} & set(get_devices())))+def test_compile_only_niter_0_compiled_blob(device, tmp_path):+ """Test that -niter 0 works with a pre-compiled blob model (C++ only, blob path)."""+ param = opset.parameter([1, 3, 224, 224], ov.Type.f32, name='input')+ result = opset.result(opset.relu(param), name='output')+ model = ov.Model([result], [param], 'static_model')++ blob_path = tmp_path / 'model.blob'+ core = ov.Core()+ blob_path.write_bytes(core.compile_model(model, device).export_model().getvalue())++ output = get_cmd_output(+ get_executable('C++'),+ '-m', blob_path,+ '-d', device,+ '-niter', '0',+ )+ assert 'FPS' not in output+ assert 'Model compiled successfully' in output+ assert 'Skipping inference due to -niter 0' in output++[email protected]('device', get_devices())+def test_compile_only_via_long_form_number_iterations(device, cache, tmp_path):+ """Test that --number_iterations 0 (long form) also triggers compile-only mode in Python.+ Previously only the short -niter flag was detected; this covers the fix that uses+ args.number_iterations == 0 instead of is_flag_set_in_command_line('niter')."""+ output = get_cmd_output(+ get_executable('Python'),+ *prepend(cache, 'dog-224x224.bmp', 'bvlcalexnet-12.onnx', tmp_path),+ '-d', device,+ '--number_iterations', '0',+ )+ assert 'FPS' not in output+ assert 'Model compiled successfully' in output+ assert 'Skipping inference due to -niter 0' in output+ assert '(skipped)' in output++[email protected]('sample_language', ['C++', 'Python'])[email protected]('device', get_devices())+def test_compile_only_sync_nireq_skips_validation(sample_language, device, cache, tmp_path):+ """Both C++ and Python: -api sync -nireq 2 -niter 0 must not raise the nireq > niter+ validation error.+ """+ # compile-only: nireq > niter is allowed, inference is entirely skipped+ output = get_cmd_output(+ get_executable(sample_language),+ *prepend(cache, 'dog-224x224.bmp', 'bvlcalexnet-12.onnx', tmp_path),+ '-d', device,+ '-api', 'sync',+ '-nireq', '2',+ '-niter', '0',+ )+ assert 'FPS' not in output+ assert 'Model compiled successfully' in output+ assert 'Skipping inference due to -niter 0' in output++ # sanity-check: the nireq > niter guard must still fire for normal runs+ try:+ get_cmd_output(+ get_executable(sample_language),+ *prepend(cache, 'dog-224x224.bmp', 'bvlcalexnet-12.onnx', tmp_path),+ '-d', device,+ '-api', 'sync',+ '-nireq', '2',+ '-niter', '1',+ )+ pytest.fail('Expected an error for nireq > niter in sync mode, but no error was raised')+ except Exception as e:+ error_text = str(getattr(e, 'output', str(e)))+ # C++ message: "Number of iterations should be greater than number of infer requests when using sync API."+ # Python message: "Number of infer requests should be less than or equal to number of iterations in sync mode."+ assert ('Number of iterations should be greater than number of infer requests' in error_text or+ 'Number of infer requests should be less than or equal to number of iterations' in error_text)++[email protected]('sample_language', ['C++', 'Python'])+def test_niter_0_in_help(sample_language):+ """Test that -niter help text documents the compile-only special case."""+ output = get_cmd_output(get_executable(sample_language), '-h')+ assert '-niter' in output+ assert 'niter 0' in output++@pytest.mark.parametrize('sample_language', ['C++', 'Python'])@pytest.mark.parametrize('device', get_devices())@pytest.mark.parametrize('api', ['sync', 'async'])diff --git a/tools/benchmark_tool/openvino/tools/benchmark/main.py b/tools/benchmark_tool/openvino/tools/benchmark/main.pyindex f1d4e0c6613..16bb3ed658c 100755--- a/tools/benchmark_tool/openvino/tools/benchmark/main.py+++ b/tools/benchmark_tool/openvino/tools/benchmark/main.py@@ -76,7 +76,8 @@ def parse_and_check_command_line():args.api_type = "sync" if args.perf_hint == "latency" else "async"if args.api_type == "sync":- if args.time == 0 and (args.number_infer_requests > args.number_iterations):+ if args.time is None and args.number_iterations is not None and args.number_iterations != 0 \+ and args.number_infer_requests > args.number_iterations:raise Exception("Number of infer requests should be less than or equal to number of iterations in sync mode.")return args, is_network_compiled@@ -98,6 +99,12 @@ def main():def is_flag_set_in_command_line(flag):return any(x.strip('-') == flag for x, y in command_line_arguments)+ # When number_iterations is explicitly set to 0 (via -niter 0 or --number_iterations 0),+ # compile the model and exit without running inference. The default is None, so == 0+ # is only true on an explicit user request. Useful for validating compilation of models+ # with dynamic shapes that would otherwise require -shape, -data_shape, or -i.+ compile_only = args.number_iterations == 0+device_name = args.target_devicedevices = parse_devices(device_name)@@ -490,6 +497,19 @@ def main():app_inputs_info, _ = get_inputs_info(args.shape, args.data_shape, args.layout, args.batch_size, args.scale_values, args.mean_values, compiled_model.inputs)batch_size = get_network_batch_size(app_inputs_info)+ if compile_only:+ logger.info("Model compiled successfully. Skipping inference due to -niter 0.")+ next_step(additional_info='skipped') # 8 - Querying optimal runtime parameters+ next_step(additional_info='skipped') # 9 - Creating infer requests and preparing input tensors+ next_step(additional_info='skipped') # 10 - Measuring performance+ next_step() # 11 - Dumping statistics report+ if args.dump_config:+ dump_config(args.dump_config, config)+ logger.info(f"OpenVINO configuration settings were dumped to {args.dump_config}")+ if statistics:+ statistics.dump()+ return+# --------------------- 8. Querying optimal runtime parameters --------------------------------------------------next_step()diff --git a/tools/benchmark_tool/openvino/tools/benchmark/parameters.py b/tools/benchmark_tool/openvino/tools/benchmark/parameters.pyindex 5f727f5e965..196801d4979 100644--- a/tools/benchmark_tool/openvino/tools/benchmark/parameters.py+++ b/tools/benchmark_tool/openvino/tools/benchmark/parameters.py@@ -25,6 +25,12 @@ def check_positive(value):raise argparse.ArgumentTypeError(f"{value} is an invalid positive int value")return ivalue+def check_nonneg(value):+ ivalue = int(value)+ if ivalue < 0:+ raise argparse.ArgumentTypeError(f"{value} is an invalid non-negative int value")+ return ivalue+class print_help(argparse.Action):def __call__(self, parser, namespace, values, option_string=None):parser.print_help()@@ -69,9 +75,11 @@ def parse_args():'\'latency\': device performance mode will be set to LATENCY. \n''\'none\': no device performance mode will be set. \n''Using explicit \'nstreams\' or other device-specific options, please set hint to \'none\'')- args.add_argument('-niter', '--number_iterations', type=check_positive, required=False, default=None,+ args.add_argument('-niter', '--number_iterations', type=check_nonneg, required=False, default=None,help='Optional. Number of iterations. '- 'If not specified, the number of iterations is calculated depending on a device.')+ 'If not specified, the number of iterations is calculated depending on a device. '+ 'Set -niter 0 to compile the model and exit without running inference '+ '(useful for models with dynamic shapes that would otherwise require -shape, -data_shape, or -i).')args.add_argument('-max_irate', '--maximum_inference_rate', type=float, required=False, default=0,help='Optional. Maximum inference rate by frame per second. ''If not specified, default value is 0, the inference will run at maximium rate depending on a device capabilities. '