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
Optimize Node.js import_model Buffer handling (#38633)
Yug Shah4513efe8a6b3
diff --git a/src/bindings/js/node/include/core_wrap.hpp b/src/bindings/js/node/include/core_wrap.hppindex 667ee99407e..61469f59aa2 100644--- a/src/bindings/js/node/include/core_wrap.hpp+++ b/src/bindings/js/node/include/core_wrap.hpp@@ -6,6 +6,7 @@#include <napi.h>+#include <sstream>#include <thread>#include <variant>@@ -133,6 +134,10 @@ struct ImportModelContext {Napi::ThreadSafeFunction tsfn;std::stringstream _stream;+ Napi::Reference<Napi::Buffer<uint8_t>> _buffer;+ const char* _buffer_data = nullptr;+ size_t _buffer_size = 0;+std::string _device;std::map<std::string, ov::Any> _config = {};ov::Core& _core;diff --git a/src/bindings/js/node/src/core_wrap.cpp b/src/bindings/js/node/src/core_wrap.cppindex 3b94bd6b4fa..bd90245a706 100644--- a/src/bindings/js/node/src/core_wrap.cpp+++ b/src/bindings/js/node/src/core_wrap.cpp@@ -15,6 +15,7 @@#include "node/include/read_model_args.hpp"#include "node/include/type_validation.hpp"#include "openvino/core/model_util.hpp"+#include "openvino/runtime/shared_buffer.hpp"#include "openvino/util/common_util.hpp"void validate_set_property_args(const Napi::CallbackInfo& info) {@@ -300,15 +301,14 @@ Napi::Value CoreWrap::import_model(const Napi::CallbackInfo& info) {if (ov::js::validate<Napi::Buffer<uint8_t>, Napi::String>(info, allowed_signatures) ||ov::js::validate<Napi::Buffer<uint8_t>, Napi::String, Napi::Object>(info, allowed_signatures)) {const auto& model_data = info[0].As<Napi::Buffer<uint8_t>>();- const auto model_stream = std::string(reinterpret_cast<char*>(model_data.Data()), model_data.Length());- std::stringstream _stream;- _stream << model_stream;+ ov::SharedStreamBuffer buffer{model_data.Data(), model_data.Length()};+ std::istream stream{&buffer};ov::CompiledModel compiled;if (info.Length() == 2) {- compiled = _core.import_model(_stream, std::string(info[1].ToString()));+ compiled = _core.import_model(stream, std::string(info[1].ToString()));} else {- compiled = _core.import_model(_stream, std::string(info[1].ToString()), to_anyMap(info.Env(), info[2]));+ compiled = _core.import_model(stream, std::string(info[1].ToString()), to_anyMap(info.Env(), info[2]));}return CompiledModelWrap::wrap(info.Env(), compiled);@@ -324,14 +324,23 @@ Napi::Value CoreWrap::import_model(const Napi::CallbackInfo& info) {void ImportModelFinalizer(Napi::Env env, void* finalizeData, ImportModelContext* context) {context->nativeThread.join();+ context->_buffer.Reset();delete context;-};+}void import_model_thread(ImportModelContext* context, std::mutex& mutex) {std::exception_ptr stored_exception;try {const std::lock_guard<std::mutex> lock(mutex);- context->_compiled_model = context->_core.import_model(context->_stream, context->_device, context->_config);++ if (!context->_buffer.IsEmpty()) {+ ov::SharedStreamBuffer buffer{context->_buffer_data, context->_buffer_size};+ std::istream stream{&buffer};+ context->_compiled_model = context->_core.import_model(stream, context->_device, context->_config);+ } else {+ context->_compiled_model =+ context->_core.import_model(context->_stream, context->_device, context->_config);+ }} catch (...) {stored_exception = std::current_exception();}@@ -362,7 +371,7 @@ Napi::Value CoreWrap::import_model_async(const Napi::CallbackInfo& info) {ov::js::validate<Napi::Buffer<uint8_t>, Napi::String>(info, allowed_signatures) ||ov::js::validate<Napi::Buffer<uint8_t>, Napi::String, Napi::Object>(info, allowed_signatures)) {// Prepare validated data that will be transferred to the new thread.- auto context_data = new ImportModelContext(env, _core);+ std::unique_ptr<ImportModelContext> context_data(new ImportModelContext(env, _core));// Handle Tensor inputif (ov::js::validate_value<TensorWrap>(env, info[0])) {@@ -370,10 +379,11 @@ Napi::Value CoreWrap::import_model_async(const Napi::CallbackInfo& info) {const auto* data_ptr = reinterpret_cast<const char*>(tensor.data());context_data->_stream << std::string(data_ptr, tensor.get_byte_size());} else {- // Handle Buffer input+ // Handle Buffer input without copying the model data.const auto& model_data = info[0].As<Napi::Buffer<uint8_t>>();- const auto model_stream = std::string(reinterpret_cast<char*>(model_data.Data()), model_data.Length());- context_data->_stream << model_stream;+ context_data->_buffer = Napi::Persistent(model_data);+ context_data->_buffer_data = reinterpret_cast<const char*>(model_data.Data());+ context_data->_buffer_size = model_data.Length();}context_data->_device = info[1].ToString();@@ -384,12 +394,14 @@ Napi::Value CoreWrap::import_model_async(const Napi::CallbackInfo& info) {"TSFN",0,1,- context_data,+ context_data.get(),ImportModelFinalizer,(void*)nullptr);- context_data->nativeThread = std::thread(import_model_thread, context_data, std::ref(_mutex));- return context_data->deferred.Promise();+ context_data->nativeThread = std::thread(import_model_thread, context_data.get(), std::ref(_mutex));+ const auto promise = context_data->deferred.Promise();+ context_data.release(); // ownership is transferred to the TSFN finalizer callback+ return promise;} else {OPENVINO_THROW("'importModel'", ov::js::get_parameters_error_msg(info, allowed_signatures));}diff --git a/src/bindings/js/node/tests/unit/basic.test.js b/src/bindings/js/node/tests/unit/basic.test.jsindex 056b412a1e4..671245562a6 100644--- a/src/bindings/js/node/tests/unit/basic.test.js+++ b/src/bindings/js/node/tests/unit/basic.test.js@@ -343,7 +343,7 @@ describe("ov basic tests.", () => {res1 = inferRequest.infer([tensor]);});- it("Test importModelSync(stream, device)", () => {+ it("Test importModelSync(Buffer, device)", () => {const newCompiled = core.importModelSync(userStream, "CPU");assert.ok(newCompiled instanceof ov.CompiledModel);const newInferRequest = newCompiled.createInferRequest();@@ -352,7 +352,7 @@ describe("ov basic tests.", () => {assert.deepStrictEqual(res1["fc_out"].data[0], res2["fc_out"].data[0]);});- it("Test importModelSync(stream, device, config)", () => {+ it("Test importModelSync(Buffer, device, config)", () => {const newCompiled = core.importModelSync(userStream, "CPU", {NUM_STREAMS: 1,});@@ -362,34 +362,34 @@ describe("ov basic tests.", () => {assert.deepStrictEqual(res1["fc_out"].data[0], res2["fc_out"].data[0]);});- it("Test importModelSync(stream, device) throws", () => {+ it("Test importModelSync with invalid model argument throws", () => {assert.throws(() => core.importModelSync(model, "CPU"),/'importModelSync' method called with incorrect parameters./,);});- it("importModelSync(stream, device) - C++ API error", () => {+ it("importModelSync(Buffer, device) - C++ API error", () => {assert.throws(() => core.importModelSync(userStream, "DEVICE"),/Device .* is not registered/,);});- it("Test importModelSync(stream, device) throws", () => {+ it("Test importModelSync with invalid device argument throws", () => {assert.throws(() => core.importModelSync(userStream, tensor),/'importModelSync' method called with incorrect parameters./,);});- it("Test importModelSync(stream, device, config: tensor) throws", () => {+ it("Test importModelSync(Buffer, device, config: tensor) throws", () => {assert.throws(() => core.importModelSync(userStream, "CPU", tensor),/NotFound: Unsupported property 0 by CPU plugin./,);});- it("Test importModelSync(stream, device, config: string) throws", () => {+ it("Test importModelSync(Buffer, device, config: string) throws", () => {const testString = "test";assert.throws(() => core.importModelSync(userStream, "CPU", testString),@@ -397,7 +397,7 @@ describe("ov basic tests.", () => {);});- it("Test importModelSync(stream, device, config: unsupported property) \+ it("Test importModelSync(Buffer, device, config: unsupported property) \throws", () => {assert.throws(() => core.importModelSync(userStream, "CPU", { NPU_DEVICE_TOTAL_MEM_SIZE: 1024 }),@@ -412,14 +412,14 @@ describe("ov basic tests.", () => {assert.ok(cm instanceof ov.CompiledModel);});- it("Test importModel(stream, device)", async () => {+ it("Test importModel(Buffer, device)", async () => {const newCompiled = await core.importModel(userStream, "CPU");const newInferRequest = newCompiled.createInferRequest();const res2 = newInferRequest.infer([tensor]);assert.deepStrictEqual(res1["fc_out"].data[0], res2["fc_out"].data[0]);});- it("Test importModel(stream, device, config)", async () => {+ it("Test importModel(Buffer, device, config)", async () => {const newCompiled = await core.importModel(userStream, "CPU", { NUM_STREAMS: 1 });const newInferRequest = newCompiled.createInferRequest();const res2 = newInferRequest.infer([tensor]);@@ -427,28 +427,28 @@ describe("ov basic tests.", () => {assert.deepStrictEqual(res1["fc_out"].data[0], res2["fc_out"].data[0]);});- it("Test importModel(stream, device) throws", async () => {+ it("Test importModel(Buffer, device) throws", async () => {await assert.rejects(async () => await core.importModel(model, "CPU"),/'importModel' method called with incorrect parameters./,);});- it("importModel(stream, device) - C++ API error", async () => {+ it("importModel(Buffer, device) - C++ API error", async () => {await assert.rejects(async () => await core.importModel(userStream, "DEVICE"),/Device .* is not registered/,);});- it("Test importModel(stream, device) throws", async () => {+ it("Test importModel(Buffer, device) throws", async () => {await assert.rejects(async () => await core.importModel(userStream, tensor),/'importModel' method called with incorrect parameters./,);});- it("Test importModel(stream, device, config: string) throws", async () => {+ it("Test importModel(Buffer, device, config: string) throws", async () => {const testString = "test";await assert.rejects(async () => await core.importModel(userStream, "CPU", testString),