Executable Network

ExecutableNetwork class functionality:

  • Compile an InferenceEngine::ICNNNetwork instance to a backend specific graph representation

  • Create an arbitrary number of InferRequest objects

  • Hold some common resources shared between different instances of InferRequest. For example:

    • InferenceEngine::IExecutableNetworkInternal::_taskExecutor task executor to implement asynchronous execution

    • InferenceEngine::IExecutableNetworkInternal::_callbackExecutor task executor to run an asynchronous inference request callback in a separate thread

Class

Inference Engine Plugin API provides the helper InferenceEngine::ExecutableNetworkThreadSafeDefault class recommended to use as a base class for an executable network. Based on that, a declaration of an executable network class can look as follows:

class CompiledModel : public ov::ICompiledModel {
public:
    CompiledModel(const std::shared_ptr<ov::Model>& model,
                  const std::shared_ptr<const ov::IPlugin>& plugin,
                  const InferenceEngine::ITaskExecutor::Ptr& task_executor,
                  const Configuration& cfg);

    // Methods from a base class ov::ICompiledModel
    void export_model(std::ostream& model) const override;

    std::shared_ptr<const ov::Model> get_runtime_model() const override;

    void set_property(const ov::AnyMap& properties) override;

    virtual ov::Any get_property(const std::string& name) const override;

    ov::RemoteContext get_context() const override;
    std::shared_ptr<InferenceEngine::IInferRequestInternal> create_infer_request() const override;

protected:
    std::shared_ptr<InferenceEngine::IInferRequestInternal> create_sync_infer_request() const override;

private:
    friend class TemplateInferRequest;
    friend class Plugin;

    void compile_model(const std::shared_ptr<ov::Model>& model);
    std::shared_ptr<const Plugin> get_template_plugin() const;

    std::atomic<std::size_t> _requestId = {0};
    Configuration _cfg;
    std::shared_ptr<ov::Model> m_model;
    std::map<std::string, std::size_t> _inputIndex;
    std::map<std::string, std::size_t> _outputIndex;
};

Class Fields

The example class has several fields:

  • _requestId - Tracks a number of created inference requests, which is used to distinguish different inference requests during profiling via the Intel® Instrumentation and Tracing Technology (ITT) library.

  • _cfg - Defines a configuration an executable network was compiled with.

  • _plugin - Refers to a plugin instance.

  • _function - Keeps a reference to transformed ngraph::Function which is used in ngraph reference backend computations. Note, in case of other backends with backend specific graph representation _function has different type and represents backend specific graph or just a set of computational kernels to perform an inference.

  • _inputIndex - maps a name of input with its index among all network inputs.

  • _outputIndex - maps a name of output with its index among all network outputs.

Constructor with

This constructor accepts a generic representation of a neural network as an InferenceEngine::ICNNNetwork reference and is compiled into a backend specific device graph:

TemplatePlugin::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,
                                             const std::shared_ptr<const ov::IPlugin>& plugin,
                                             const InferenceEngine::ITaskExecutor::Ptr& task_executor,
                                             const Configuration& cfg)
    : ov::ICompiledModel(model, plugin, task_executor),  // Disable default threads creation
      m_model(model),
      _cfg(cfg) {
    // TODO: if your plugin supports device ID (more that single instance of device can be on host machine)
    // you should select proper device based on KEY_DEVICE_ID or automatic behavior
    // In this case, _waitExecutor should also be created per device.
    try {
        compile_model(m_model);
    } catch (const InferenceEngine::Exception&) {
        throw;
    } catch (const std::exception& e) {
        OPENVINO_ASSERT(false, "Standard exception from compilation library: ", e.what());
    } catch (...) {
        throw ov::Exception("Generic exception is thrown");
    }
}

The implementation CompileNetwork is fully device-specific.

The function accepts a const shared pointer to ngraph::Function object and performs the following steps:

  1. Applies nGraph passes using TransformNetwork function, which defines plugin-specific conversion pipeline. To support low precision inference, the pipeline can include Low Precision Transformations. These transformations are usually hardware specific. You can find how to use and configure Low Precisions Transformations in Low Precision Transformations guide.

  2. Maps the transformed graph to a backend specific graph representation (for example, to CPU plugin internal graph representation).

  3. Allocates and fills memory for graph weights, backend specific memory handles and so on.

// forward declaration
void transform_model(const std::shared_ptr<ov::Model>& model);

void TemplatePlugin::CompiledModel::compile_model(const std::shared_ptr<ov::Model>& model) {
    // apply plugins transformations
    transform_model(model);
    // Generate backend specific blob mappings. For example Inference Engine uses not ngraph::Result nodes friendly name
    // as inference request output names but the name of the layer before.
    // TODO: Remove it
    size_t idx = 0;
    for (auto&& result : model->get_results()) {
        const auto& input = result->input_value(0);
        auto name = ov::op::util::get_ie_output_name(input);
        if (_outputIndex.emplace(name, idx).second)
            idx++;
    }
    for (auto&& parameter : model->get_parameters()) {
        _inputIndex.emplace(parameter->get_friendly_name(), model->get_parameter_index(parameter));
    }

    // Perform any other steps like allocation and filling backend specific memory handles and so on
}

Note

After all these steps, the backend specific graph is ready to create inference requests and perform inference.

Constructor Importing from Stream

This constructor creates a backend specific graph by importing from a stream object:

Note

The export of backend specific graph is done in the Export method, and data formats must be the same for both import and export.

The implementation of the method should write all data to the model stream, which is required to import a backend specific graph later in the Plugin::Import method:

void TemplatePlugin::CompiledModel::export_model(std::ostream& modelStream) const {
    OV_ITT_SCOPED_TASK(itt::domains::TemplatePlugin, "ExecutableNetwork::Export");

    std::stringstream xmlFile, binFile;
    ov::pass::Serialize serializer(xmlFile, binFile);
    serializer.run_on_model(m_model);

    auto m_constants = binFile.str();
    auto m_model = xmlFile.str();

    auto dataSize = static_cast<std::uint64_t>(m_model.size());
    modelStream.write(reinterpret_cast<char\*>(&dataSize), sizeof(dataSize));
    modelStream.write(m_model.c_str(), dataSize);

    dataSize = static_cast<std::uint64_t>(m_constants.size());
    modelStream.write(reinterpret_cast<char\*>(&dataSize), sizeof(dataSize));
    modelStream.write(reinterpret_cast<char\*>(&m_constants[0]), dataSize);
}

The method creates an asynchronous inference request and returns it. While the public Inference Engine API has a single interface for inference request, which can be executed in synchronous and asynchronous modes, a plugin library implementation has two separate classes:

  • Synchronous inference request, which defines pipeline stages and runs them synchronously in the Infer method.

  • Asynchronous inference request, which is a wrapper for a synchronous inference request and can run a pipeline asynchronously. Depending on a device pipeline structure, it can has one or several stages:

    • For single-stage pipelines, there is no need to define this method and create a class derived from InferenceEngine::AsyncInferRequestThreadSafeDefault. For single stage pipelines, a default implementation of this method creates InferenceEngine::AsyncInferRequestThreadSafeDefault wrapping a synchronous inference request and runs it asynchronously in the _taskExecutor executor.

    • For pipelines with multiple stages, such as performing some preprocessing on host, uploading input data to a device, running inference on a device, or downloading and postprocessing output data, schedule stages on several task executors to achieve better device use and performance. You can do it by creating a sufficient number of inference requests running in parallel. In this case, device stages of different inference requests are overlapped with preprocessing and postprocessing stage giving better performance.

      Warning

      It is up to you to decide how many task executors you need to optimally execute a device pipeline.

      std::shared_ptr<InferenceEngine::IInferRequestInternal> TemplatePlugin::CompiledModel::create_infer_request() const {
          auto internal_request = create_sync_infer_request();
          return std::make_shared<TemplateAsyncInferRequest>(
              std::static_pointer_cast<TemplatePlugin::TemplateInferRequest>(internal_request),
              get_task_executor(),
              get_template_plugin()->_waitExecutor,
              get_callback_executor());
      }
      
      std::shared_ptr<InferenceEngine::IInferRequestInternal> TemplatePlugin::CompiledModel::create_sync_infer_request()
          const {
          std::vector<std::shared_ptr<const ov::Node>> _inputs, _outputs;
          for (const auto& output : m_model->inputs()) {
              _inputs.emplace_back(output.get_node_shared_ptr());
          }
          for (const auto& output : outputs()) {
              _outputs.emplace_back(output.get_node_shared_ptr());
          }
      
          return std::make_shared<TemplateInferRequest>(
              _inputs,
              _outputs,
              std::static_pointer_cast<const TemplatePlugin::CompiledModel>(shared_from_this()));
      }

Returns a metric value for a metric with the name name. A metric is a static type of information about an executable network. Examples of metrics:

  • EXEC_NETWORK_METRIC_KEY(NETWORK_NAME) - name of an executable network

  • EXEC_NETWORK_METRIC_KEY(OPTIMAL_NUMBER_OF_INFER_REQUESTS) - heuristic to denote an optimal (or at least sub-optimal) number of inference requests needed to run asynchronously to use the current device fully

  • Any other executable network metric specific for a particular device. Such metrics and possible values must be declared in a plugin configuration public header, for example, template/config.hpp

The IE_SET_METRIC_RETURN helper macro sets metric value and checks that the actual metric type matches a type of the specified value.

Returns a current value for a configuration key with the name name. The method extracts configuration values an executable network is compiled with.

InferenceEngine::Parameter TemplatePlugin::CompiledModel::get_property(const std::string& name) const {
    const auto& add_ro_properties = [](const std::string& name, std::vector<ov::PropertyName>& properties) {
        properties.emplace_back(ov::PropertyName{name, ov::PropertyMutability::RO});
    };
    const auto& default_ro_properties = []() {
        std::vector<ov::PropertyName> ro_properties{ov::model_name,
                                                    ov::supported_properties,
                                                    ov::optimal_number_of_infer_requests};
        return ro_properties;
    };
    const auto& default_rw_properties = []() {
        std::vector<ov::PropertyName> rw_properties{ov::device::id,
                                                    ov::enable_profiling,
                                                    ov::template_plugin::throughput_streams};
        return rw_properties;
    };
    const auto& to_string_vector = [](const std::vector<ov::PropertyName>& properties) {
        std::vector<std::string> ret;
        for (const auto& property : properties) {
            ret.emplace_back(property);
        }
        return ret;
    };
    // TODO: return more supported values for metrics
    if (EXEC_NETWORK_METRIC_KEY(SUPPORTED_METRICS) == name) {
        auto metrics = default_ro_properties();
        add_ro_properties(METRIC_KEY(SUPPORTED_METRICS), metrics);
        add_ro_properties(METRIC_KEY(SUPPORTED_CONFIG_KEYS), metrics);
        return to_string_vector(metrics);
    } else if (EXEC_NETWORK_METRIC_KEY(SUPPORTED_CONFIG_KEYS) == name) {
        auto configs = default_rw_properties();
        auto streamExecutorConfigKeys = InferenceEngine::IStreamsExecutor::Config{}.SupportedKeys();
        for (auto&& configKey : streamExecutorConfigKeys) {
            configs.emplace_back(configKey);
        }
        return to_string_vector(configs);
    } else if (ov::model_name == name) {
        auto model_name = m_model->get_friendly_name();
        return decltype(ov::model_name)::value_type(model_name);
    } else if (ov::optimal_number_of_infer_requests == name) {
        unsigned int value = _cfg._streamsExecutorConfig._streams;
        return decltype(ov::optimal_number_of_infer_requests)::value_type(value);
    }

    if (ov::supported_properties == name) {
        auto ro_properties = default_ro_properties();
        auto rw_properties = default_rw_properties();

        std::vector<ov::PropertyName> supported_properties;
        supported_properties.reserve(ro_properties.size() + rw_properties.size());
        supported_properties.insert(supported_properties.end(), ro_properties.begin(), ro_properties.end());
        supported_properties.insert(supported_properties.end(), rw_properties.begin(), rw_properties.end());
        return decltype(ov::supported_properties)::value_type(supported_properties);
    }

    return _cfg.Get(name);
}

This function is the only way to get configuration values when a network is imported and compiled by other developers and tools (for example, the Compile tool.

The next step in plugin library implementation is the Synchronous Inference Request class.