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
[GPU][NPU] Weight sharing with cache (#37227)
Sergey Ivanov98f136269eb3
diff --git a/src/plugins/intel_gpu/include/intel_gpu/plugin/compiled_model.hpp b/src/plugins/intel_gpu/include/intel_gpu/plugin/compiled_model.hppindex 96131dfb23b..baa5edbc51b 100644--- a/src/plugins/intel_gpu/include/intel_gpu/plugin/compiled_model.hpp+++ b/src/plugins/intel_gpu/include/intel_gpu/plugin/compiled_model.hpp@@ -15,6 +15,7 @@#include "intel_gpu/plugin/plugin.hpp"#include "intel_gpu/plugin/remote_context.hpp"#include "intel_gpu/runtime/execution_config.hpp"+#include "openvino/runtime/internal_properties.hpp"#include "openvino/runtime/icompiled_model.hpp"namespace ov::intel_gpu {@@ -26,12 +27,14 @@ public:CompiledModel(std::shared_ptr<ov::Model> model,const std::shared_ptr<const ov::IPlugin>& plugin,RemoteContextImpl::Ptr context,- const ExecutionConfig& config);+ const ExecutionConfig& config,+ ov::internal::WeightSharingCtxPtr weightSharingContext = nullptr);CompiledModel(cldnn::BinaryInputBuffer& ib,const std::shared_ptr<const ov::IPlugin>& plugin,RemoteContextImpl::Ptr context,const ExecutionConfig& config,- const bool loaded_from_cache);+ const bool loaded_from_cache,+ ov::internal::WeightSharingCtxPtr weightSharingContext = nullptr);~CompiledModel() override {auto streams_executor = std::dynamic_pointer_cast<ov::threading::IStreamsExecutor>(get_task_executor());streams_executor->cpu_reset();@@ -108,6 +111,18 @@ private:bool m_loaded_from_cache;std::string m_runtime_requirements;std::shared_ptr<ov::Tensor> _backing_tensor;++ // The member m_weight_sharing_context holds the context for weight sharing currently used by cross-plugin sharing.+ // That context consists of the necessary information as source_id, constant_id, and the non-owning view of the source buffer, where the weights are stored.+ // As in the general case the view may not own the underlying storage,+ // the source buffer's must be kept alive by each plugin adhering to the weight-sharing contract.+ // Whenever the plugin is a consumer or the producer of+ // weight-sharing context, the source buffer track held on the plugin side. That means each consumer must retain+ // a strong reference to the source buffer for as long as the imported constant may still be used.+ // m_weight_sharing_source_buffers holds strong references to the source buffers, ensuring they remain valid even if+ // the original weight-sharing producer is destroyed.+ ov::internal::WeightSharingCtxPtr m_weight_sharing_context;+ std::set<std::shared_ptr<ov::AlignedBuffer>> m_weight_sharing_source_buffers;};} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/include/intel_gpu/plugin/graph.hpp b/src/plugins/intel_gpu/include/intel_gpu/plugin/graph.hppindex 61a2e349a61..da374856f04 100644--- a/src/plugins/intel_gpu/include/intel_gpu/plugin/graph.hpp+++ b/src/plugins/intel_gpu/include/intel_gpu/plugin/graph.hpp@@ -37,7 +37,7 @@ public:POSTPROC = 4};- Graph(std::shared_ptr<ov::Model> model, const RemoteContextImpl::Ptr& context, const ExecutionConfig& config, uint16_t stream_id = 0);+ Graph(std::shared_ptr<ov::Model> model, const RemoteContextImpl::Ptr& context, const ExecutionConfig& config, uint16_t stream_id = 0, ov::internal::WeightSharingCtxPtr weight_sharing_ctx = nullptr);Graph(cldnn::BinaryInputBuffer& ib, const RemoteContextImpl::Ptr& context, const ExecutionConfig& config, uint16_t stream_id = 0);Graph(std::shared_ptr<Graph> graph, uint16_t stream_id = 0);~Graph();@@ -78,6 +78,10 @@ public:bool use_external_queue() const;+ std::set<std::shared_ptr<ov::AlignedBuffer>> get_weight_sharing_source_buffers() const {+ return m_weight_sharing_source_buffers;+ }+std::vector<HostTimeProfilingEntry> host_exec_times;private:@@ -97,6 +101,7 @@ private:std::vector<cldnn::primitive_id> profilingIDs;std::map<size_t, cldnn::layout> m_input_layouts;+ std::set<std::shared_ptr<ov::AlignedBuffer>> m_weight_sharing_source_buffers;void build(std::shared_ptr<cldnn::program> program);std::shared_ptr<ov::Model> get_runtime_model(std::vector<cldnn::primitive_info>& pi, bool filter_const_primitives = true);diff --git a/src/plugins/intel_gpu/include/intel_gpu/plugin/program_builder.hpp b/src/plugins/intel_gpu/include/intel_gpu/plugin/program_builder.hppindex 5fc676a6f56..fc7f7f238b2 100644--- a/src/plugins/intel_gpu/include/intel_gpu/plugin/program_builder.hpp+++ b/src/plugins/intel_gpu/include/intel_gpu/plugin/program_builder.hpp@@ -22,6 +22,7 @@#include <cstdint>#include <mutex>#include <set>+#include <unordered_set>#if defined(_WIN32) && !defined(__GNUC__)# define __PRETTY_FUNCTION__ __FUNCSIG__@@ -82,7 +83,9 @@ public:ProgramBuilder(std::shared_ptr<ov::Model> model, cldnn::engine& engine, const ExecutionConfig& config,std::shared_ptr<ov::threading::IStreamsExecutor> task_executor = nullptr,std::shared_ptr<cldnn::ICompilationContext> compilation_context = nullptr,- bool innerProgram = false);+ bool innerProgram = false,+ ov::internal::WeightSharingCtxPtr weight_sharing_ctx = nullptr);+ ProgramBuilder(std::shared_ptr<ov::Model> model, cldnn::engine& engine, const ExecutionConfig& config, ov::internal::WeightSharingCtxPtr weight_sharing_ctx);ProgramBuilder(cldnn::engine& engine, const ExecutionConfig& config);static const cldnn::primitive_id m_preProcessTag;@@ -97,7 +100,8 @@ public:std::vector<cldnn::primitive_id> profiling_ids;std::map<size_t, cldnn::layout> inputLayouts;- using BlobCacheKey = std::tuple<const char*, ov::Shape, ov::element::Type>;+ using IsRemoteWeight = bool;+ using BlobCacheKey = std::tuple<const char*, ov::Shape, ov::element::Type, IsRemoteWeight>;std::map<BlobCacheKey, cldnn::primitive_id> blobMemCache;std::shared_ptr<cldnn::program> get_compiled_program() const;@@ -145,6 +149,11 @@ public:std::shared_ptr<cldnn::ICompilationContext> get_compilation_context() const { return m_compilation_context; }std::shared_ptr<ov::Model> get_model() const { return m_model; }+ ov::internal::WeightSharingCtxPtr get_weight_sharing_ctx() const { return m_weight_sharing_ctx; }+ void register_weight_sharing_source_buffer(std::shared_ptr<ov::AlignedBuffer> source);+ std::set<std::shared_ptr<ov::AlignedBuffer>> get_weight_sharing_source_buffers() const {+ return m_weight_sharing_source_buffers;+ }private:static factories_map_t factories_map;std::shared_ptr<cldnn::program> m_program;@@ -162,6 +171,8 @@ private:std::shared_ptr<cldnn::ICompilationContext> m_compilation_context;bool m_is_inner_program = false;+ ov::internal::WeightSharingCtxPtr m_weight_sharing_ctx;+ std::set<std::shared_ptr<ov::AlignedBuffer>> m_weight_sharing_source_buffers;void EnableQueryMode() { queryMode = true; }void DisableQueryMode() { queryMode = false; }diff --git a/src/plugins/intel_gpu/src/plugin/compiled_model.cpp b/src/plugins/intel_gpu/src/plugin/compiled_model.cppindex 91fca84d519..a6de37904f6 100644--- a/src/plugins/intel_gpu/src/plugin/compiled_model.cpp+++ b/src/plugins/intel_gpu/src/plugin/compiled_model.cpp@@ -56,7 +56,8 @@ std::shared_ptr<ov::threading::ITaskExecutor> create_task_executor(const std::shCompiledModel::CompiledModel(std::shared_ptr<ov::Model> model,const std::shared_ptr<const ov::IPlugin>& plugin,RemoteContextImpl::Ptr context,- const ExecutionConfig& config)+ const ExecutionConfig& config,+ ov::internal::WeightSharingCtxPtr weightSharingContext): ov::ICompiledModel(model, plugin, context, create_task_executor(plugin, config), nullptr),m_context(context),m_config(config),@@ -65,9 +66,11 @@ CompiledModel::CompiledModel(std::shared_ptr<ov::Model> model,m_model_name(model->get_friendly_name()),m_inputs(ov::ICompiledModel::inputs()),m_outputs(ov::ICompiledModel::outputs()),- m_loaded_from_cache(false) {+ m_loaded_from_cache(false),+ m_weight_sharing_context(std::move(weightSharingContext)) {m_runtime_requirements = build_runtime_requirements(m_context->get_engine().get_device_info());- auto graph_base = std::make_shared<Graph>(model, m_context, m_config, 0);+ auto graph_base = std::make_shared<Graph>(model, m_context, m_config, 0, m_weight_sharing_context);+ m_weight_sharing_source_buffers = graph_base->get_weight_sharing_source_buffers();for (uint16_t n = 0; n < m_config.get_num_streams(); n++) {auto graph = n == 0 ? graph_base : std::make_shared<Graph>(graph_base, n);m_graphs.push_back(graph);@@ -78,7 +81,8 @@ CompiledModel::CompiledModel(cldnn::BinaryInputBuffer& ib,const std::shared_ptr<const ov::IPlugin>& plugin,RemoteContextImpl::Ptr context,const ExecutionConfig& config,- const bool loaded_from_cache)+ const bool loaded_from_cache,+ ov::internal::WeightSharingCtxPtr weightSharingContext): ov::ICompiledModel(nullptr,plugin,context,@@ -87,7 +91,8 @@ CompiledModel::CompiledModel(cldnn::BinaryInputBuffer& ib,, m_context(context), m_config(config), m_wait_executor(std::make_shared<ov::threading::CPUStreamsExecutor>(ov::threading::IStreamsExecutor::Config{"Intel GPU plugin wait executor"}))- , m_loaded_from_cache(loaded_from_cache) {+ , m_loaded_from_cache(loaded_from_cache)+ , m_weight_sharing_context(std::move(weightSharingContext)) {// The compiled blob starts (after ov::CacheMode) with a magic-guarded, versioned// compatibility descriptor. Any rejection below throws ov::Exception;// So the caller (cache layer / OV EP) catches it and recompiles instead of consuming a bad blob.diff --git a/src/plugins/intel_gpu/src/plugin/graph.cpp b/src/plugins/intel_gpu/src/plugin/graph.cppindex 594378a935d..5aefcd206c8 100644--- a/src/plugins/intel_gpu/src/plugin/graph.cpp+++ b/src/plugins/intel_gpu/src/plugin/graph.cpp@@ -79,11 +79,11 @@ std::optional<std::chrono::microseconds> extract_start_time_from_intervals(namespace ov::intel_gpu {-Graph::Graph(std::shared_ptr<ov::Model> model, const RemoteContextImpl::Ptr& context, const ExecutionConfig& config, uint16_t stream_id)+Graph::Graph(std::shared_ptr<ov::Model> model, const RemoteContextImpl::Ptr& context, const ExecutionConfig& config, uint16_t stream_id, ov::internal::WeightSharingCtxPtr weight_sharing_ctx): m_context(context), m_config(config), m_stream_id(stream_id) {- auto program_builder = std::make_shared<ProgramBuilder>(model, get_engine(), config);+ auto program_builder = std::make_shared<ProgramBuilder>(model, get_engine(), config, weight_sharing_ctx);m_config = program_builder->get_config();build(program_builder->get_compiled_program());@@ -94,6 +94,7 @@ Graph::Graph(std::shared_ptr<ov::Model> model, const RemoteContextImpl::Ptr& conprofilingIDs = program_builder->profiling_ids;perfMap = program_builder->perfMap;m_input_layouts = program_builder->get_input_layouts();+ m_weight_sharing_source_buffers = program_builder->get_weight_sharing_source_buffers();}Graph::Graph(cldnn::BinaryInputBuffer &ib, const RemoteContextImpl::Ptr& context, const ExecutionConfig& config, uint16_t stream_id)diff --git a/src/plugins/intel_gpu/src/plugin/ops/constant.cpp b/src/plugins/intel_gpu/src/plugin/ops/constant.cppindex 249891379b9..84444ceda27 100644--- a/src/plugins/intel_gpu/src/plugin/ops/constant.cpp+++ b/src/plugins/intel_gpu/src/plugin/ops/constant.cpp@@ -40,6 +40,8 @@#include "openvino/op/util/binary_elementwise_bitwise.hpp"#include "openvino/op/util/op_types.hpp"#include "openvino/op/variadic_split.hpp"+#include "openvino/util/memory.hpp"+#include "openvino/util/mmap_object.hpp"#include "ov_ops/moe_compressed.hpp"namespace ov::intel_gpu {@@ -114,7 +116,29 @@ static void create_data(ProgramBuilder& p, const ov::Shape& const_shape, const scldnn::primitive_id constPrimID;const auto* data = op->get_data_ptr<char>();- const auto cache_key = std::make_tuple(data, const_shape, op->get_output_element_type(0));+ // Check whether this constant comes from a shared source buffer that may be used across devices.+ // The imported view may not own the underlying storage; though the actual backing buffer is not kept alive by the+ // weight-sharing context, the source buffer track held on the plugin side. That means each consumer must retain+ // a strong reference to the source buffer for as long as the imported constant may still be used.+ // ProgramBuilder registers each source buffer as a strong reference in its internal storage,+ // ensuring the buffer remains valid for the lifetime of the graph. Once the graph was created,+ // the instance of CompiledModel takes on the ownership of the buffer.+ // This ensures the validity of the buffer during the lifetime of the compiled model.+ std::shared_ptr<ov::AlignedBuffer> weight_sharing_constant_buffer_view;+ if (p.get_weight_sharing_ctx()) {+ // It's assumed that the constant is a shared constant with cross-device visibility if the model has+ // a weight sharing context and a valid source buffer and a constant id is registered in the weight sharing context.+ auto constant_source_id = weight_sharing::Extension::get_constant_source_id(*op);+ auto source_buffer = weight_sharing::Extension::get_constant_source_buffer(*op);+ if (source_buffer) {+ p.register_weight_sharing_source_buffer(source_buffer);+ auto constant_id = weight_sharing::Extension::get_constant_id(*op);+ weight_sharing_constant_buffer_view =+ weight_sharing::get_buffer(*p.get_weight_sharing_ctx(), constant_source_id, constant_id);+ }+ }+ const auto cache_key =+ std::make_tuple(data, const_shape, op->get_output_element_type(0), weight_sharing_constant_buffer_view != nullptr);auto bufIter = p.blobMemCache.find(cache_key);@@ -123,6 +147,24 @@ static void create_data(ProgramBuilder& p, const ov::Shape& const_shape, const sp.primitive_ids[initialconstPrimID] = constPrimID;p.profiling_ids.push_back(initialconstPrimID);} else {+ cldnn::memory::ptr mem = nullptr;+ if (weight_sharing_constant_buffer_view) {+ mem = p.get_engine().create_hostbuffer(+ weight_sharing_constant_buffer_view->get_ptr(),+ ov::util::align_size_up(weight_sharing_constant_buffer_view->size(), ov::util::get_system_page_size()),+ cldnn::allocation_type::cl_mem,+ constLayout);+ p.add_primitive(*op, cldnn::data(initialconstPrimID, mem));+ p.blobMemCache[cache_key] = initialconstPrimID;+ constPrimID = initialconstPrimID;+ GPU_DEBUG_LOG << "[" << initialconstPrimID << ": import shared constant] imported shared constant: source ID: "+ << weight_sharing::Extension::get_constant_source_id(*op)+ << ", constant ID: " << weight_sharing::Extension::get_constant_id(*op)+ << ", ptr: " << static_cast<void*>(weight_sharing_constant_buffer_view->get_ptr())+ << ", size: " << weight_sharing_constant_buffer_view->size()+ << ", layout: " << constLayout.to_short_string() << std::endl;+ return;+ }auto partial_upload = try_prepare_partial_upload(p.get_engine(),p.get_config(),op,@@ -131,7 +173,7 @@ static void create_data(ProgramBuilder& p, const ov::Shape& const_shape, const sconstFormat,constLayout);- cldnn::memory::ptr mem = nullptr;+if (partial_upload.enabled) {mem = partial_upload.memory;diff --git a/src/plugins/intel_gpu/src/plugin/plugin.cpp b/src/plugins/intel_gpu/src/plugin/plugin.cppindex e0c7f0ddcfb..e88aca3d6cc 100644--- a/src/plugins/intel_gpu/src/plugin/plugin.cpp+++ b/src/plugins/intel_gpu/src/plugin/plugin.cpp@@ -61,6 +61,22 @@ thread_local const size_t* g_current_tensor_base = nullptr;namespace ov::intel_gpu {+namespace {++ov::internal::WeightSharingCtxPtr extract_weight_sharing_context(ov::AnyMap& config) {+ const auto property_name = ov::internal::model_sharing_context.name();+ const auto property_it = config.find(property_name);+ if (property_it == config.end()) {+ return nullptr;+ }++ auto ctx = property_it->second.as<ov::internal::WeightSharingCtxPtr>();+ config.erase(property_it);+ return ctx;+}++} // namespace+#define FACTORY_DECLARATION(op_version, op_name) \void __register ## _ ## op_name ## _ ## op_version();@@ -273,14 +289,16 @@ std::shared_ptr<ov::ICompiledModel> Plugin::compile_model(const std::shared_ptr<OPENVINO_ASSERT(m_configs_map.find(device_id) != m_configs_map.end(), "[GPU] compile_model: Couldn't find config for GPU with id ", device_id);ExecutionConfig config = m_configs_map.at(device_id);- config.set_user_property(orig_config, OptionVisibility::RELEASE);+ auto user_config = orig_config;+ auto weight_sharing_context = extract_weight_sharing_context(user_config);+ config.set_user_property(user_config, OptionVisibility::RELEASE);auto transformed_model = clone_and_transform_model(model, config, context);config.finalize(context.get(), transformed_model.get());{OV_ITT_SCOPED_TASK(itt::domains::intel_gpu_plugin, "Plugin::compile_model::CreateCompiledModel");- return std::make_shared<CompiledModel>(transformed_model, shared_from_this(), context, config);+ return std::make_shared<CompiledModel>(transformed_model, shared_from_this(), context, config, weight_sharing_context);}}@@ -296,13 +314,15 @@ std::shared_ptr<ov::ICompiledModel> Plugin::compile_model(const std::shared_ptr<OPENVINO_ASSERT(m_configs_map.find(device_id) != m_configs_map.end(), "[GPU] compile_model: Couldn't find config for GPU with id ", device_id);ExecutionConfig config = m_configs_map.at(device_id);- config.set_user_property(orig_config, OptionVisibility::RELEASE);+ auto user_config = orig_config;+ auto weight_sharing_context = extract_weight_sharing_context(user_config);+ config.set_user_property(user_config, OptionVisibility::RELEASE);auto transformed_model = clone_and_transform_model(model, config, context_impl);config.finalize(context_impl.get(), transformed_model.get());- return std::make_shared<CompiledModel>(transformed_model, shared_from_this(), context_impl, config);+ return std::make_shared<CompiledModel>(transformed_model, shared_from_this(), context_impl, config, weight_sharing_context);}ov::SoPtr<ov::IRemoteContext> Plugin::create_context(const ov::AnyMap& remote_properties) const {@@ -453,6 +473,8 @@ std::shared_ptr<ov::ICompiledModel> Plugin::import_model(std::istream& model,_orig_config.erase(blob_it);}+ auto weight_sharing_context = extract_weight_sharing_context(_orig_config);+ExecutionConfig config = m_configs_map.at(device_id);config.set_user_property(_orig_config, OptionVisibility::RELEASE);@@ -493,7 +515,7 @@ std::shared_ptr<ov::ICompiledModel> Plugin::import_model(std::istream& model,}}- return std::make_shared<CompiledModel>(ib, shared_from_this(), context_impl, config, loaded_from_cache);+ return std::make_shared<CompiledModel>(ib, shared_from_this(), context_impl, config, loaded_from_cache, weight_sharing_context);}std::shared_ptr<ov::ICompiledModel> Plugin::import_model(const ov::Tensor& model,diff --git a/src/plugins/intel_gpu/src/plugin/program_builder.cpp b/src/plugins/intel_gpu/src/plugin/program_builder.cppindex 835306e2a86..b6e57b64f10 100644--- a/src/plugins/intel_gpu/src/plugin/program_builder.cpp+++ b/src/plugins/intel_gpu/src/plugin/program_builder.cpp@@ -60,10 +60,16 @@ std::string layer_type_name_ID(const std::shared_ptr<ov::Node>& op) {return layer_type_name_ID(op.get());}++ProgramBuilder::ProgramBuilder(std::shared_ptr<ov::Model> model, cldnn::engine& engine, const ExecutionConfig& config, ov::internal::WeightSharingCtxPtr weight_sharing_ctx) :+ ProgramBuilder(model, engine, config, nullptr, nullptr, false, weight_sharing_ctx) {+}+ProgramBuilder::ProgramBuilder(std::shared_ptr<ov::Model> model, cldnn::engine& engine, const ExecutionConfig& config,std::shared_ptr<ov::threading::IStreamsExecutor> task_executor,std::shared_ptr<cldnn::ICompilationContext> compilation_context,- bool is_inner_program)+ bool is_inner_program,+ ov::internal::WeightSharingCtxPtr weight_sharing_ctx): m_model(model), m_config(config), m_engine(engine)@@ -71,6 +77,9 @@ ProgramBuilder::ProgramBuilder(std::shared_ptr<ov::Model> model, cldnn::engine&, m_task_executor(task_executor), m_compilation_context(compilation_context), m_is_inner_program(is_inner_program) {+ // Remember weight sharing context for the program builder, so that it can be used to share weights across multiple compiled models+ m_weight_sharing_ctx = weight_sharing_ctx;+// Constant GPU uploads use the engine before cldnn::program ctor syncs config to the engine.m_engine.set_enable_large_allocations(m_config.get_enable_large_allocations());@@ -355,6 +364,10 @@ int64_t ProgramBuilder::get_result_index(const ov::Output<const ov::Node>& valuereturn m_model->get_result_index(value);}+void ProgramBuilder::register_weight_sharing_source_buffer(std::shared_ptr<ov::AlignedBuffer> source) {+ m_weight_sharing_source_buffers.insert(source);+}+void validate_inputs_count(const std::shared_ptr<ov::Node>& op, std::vector<size_t> valid_inputs_count) {for (auto ic : valid_inputs_count) {if (op->get_input_size() == ic) {diff --git a/src/plugins/intel_gpu/tests/functional/behavior/compatibility_string.cpp b/src/plugins/intel_gpu/tests/functional/behavior/compatibility_string.cppindex 44bc0e334b0..b5dd8f41fe8 100644--- a/src/plugins/intel_gpu/tests/functional/behavior/compatibility_string.cpp+++ b/src/plugins/intel_gpu/tests/functional/behavior/compatibility_string.cpp@@ -9,6 +9,7 @@#include "common_test_utils/subgraph_builders/conv_pool_relu.hpp"#include "openvino/runtime/core.hpp"+#include "openvino/runtime/internal_properties.hpp"#include "openvino/runtime/intel_gpu/properties.hpp"#include "openvino/runtime/properties.hpp"#include "shared_test_classes/base/ov_behavior_test_utils.hpp"@@ -48,6 +49,20 @@ TEST_F(CompatibilityStringGPU, CompatibilityCheckListedInSupportedProperties) {ASSERT_NE(std::find(supported.begin(), supported.end(), ov::compatibility_check.name()), supported.end());}+TEST_F(CompatibilityStringGPU, ModelSharingContextPropertyIsNotSupportedYet) {+ SKIP_IF_CURRENT_TEST_IS_DISABLED();+ ov::Core core;++ auto internal_supported = core.get_property(ov::test::utils::DEVICE_GPU, ov::internal::supported_properties);+ ASSERT_EQ(std::find(internal_supported.begin(), internal_supported.end(),+ ov::internal::model_sharing_context.name()),+ internal_supported.end()); // Expect it not to be found in internal supported properties++ auto supported = core.get_property(ov::test::utils::DEVICE_GPU, ov::supported_properties);+ ASSERT_EQ(std::find(supported.begin(), supported.end(), ov::internal::model_sharing_context.name()),+ supported.end()); // Expect it not to be found in public supported properties either+}+// A descriptor generated on this device is reported as SUPPORTED.TEST_F(CompatibilityStringGPU, GenerateAndCheckSupported) {SKIP_IF_CURRENT_TEST_IS_DISABLED();diff --git a/src/plugins/intel_gpu/tests/functional/behavior/weight_context.cpp b/src/plugins/intel_gpu/tests/functional/behavior/weight_context.cppnew file mode 100644index 00000000000..f15006fc60f--- /dev/null+++ b/src/plugins/intel_gpu/tests/functional/behavior/weight_context.cpp@@ -0,0 +1,195 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <gtest/gtest.h>++#include <cstring>+#include <filesystem>+#include <functional>+#include <memory>+#include <tuple>+#include <vector>++#include "common_test_utils/test_assertions.hpp"+#include "openvino/core/graph_util.hpp"+#include "openvino/core/model.hpp"+#include "openvino/core/weight_sharing_util.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/result.hpp"+#include "openvino/runtime/aligned_buffer.hpp"+#include "openvino/runtime/core.hpp"+#include "openvino/runtime/internal_properties.hpp"+#include "openvino/runtime/shared_buffer.hpp"+#include "openvino/util/memory.hpp"+#include "openvino/util/mmap_object.hpp"++namespace {+std::tuple<std::shared_ptr<ov::Model>, size_t> makeModelWithWeights(size_t elem_count) {+ size_t weight_count = 0;+ auto s = std::make_shared<ov::op::v0::Parameter>(ov::element::u8, ov::Shape{elem_count});+ auto one = ov::op::v0::Constant::create(ov::element::u8, ov::Shape{elem_count}, {1});+ weight_count++;+ auto add = std::make_shared<ov::op::v1::Add>(s, one);+ auto three = ov::op::v0::Constant::create(ov::element::u8, ov::Shape{elem_count}, {3});+ weight_count++;+ auto mul = std::make_shared<ov::op::v1::Multiply>(add, three);+ auto res = std::make_shared<ov::op::v0::Result>(mul);+ auto m = std::make_shared<ov::Model>(ov::ResultVector{res}, ov::ParameterVector{s}, "producer");+ m->input(0).set_names({"input"});+ m->output(0).set_names({"output"});+ return std::make_tuple(std::move(m), weight_count);+}++std::vector<std::shared_ptr<ov::op::v0::Constant>> collectConstants(ov::Model& model) {+ std::vector<std::shared_ptr<ov::op::v0::Constant>> constant_to_share;+ for (const auto& op : model.get_ops()) {+ auto weight_sharing_constant_candidate = std::dynamic_pointer_cast<ov::op::v0::Constant>(op);+ if (!weight_sharing_constant_candidate) {+ continue;+ }+ constant_to_share.push_back(weight_sharing_constant_candidate);+ }+ return constant_to_share;+}++std::tuple<std::shared_ptr<ov::weight_sharing::Context>, std::shared_ptr<::ov::SharedBuffer<std::shared_ptr<ov::AlignedBuffer>>>> makeWeightSharingContext(+ std::vector<std::shared_ptr<ov::op::v0::Constant>>&& constants,+ size_t alignment,+ std::function<size_t()> source_id_generator,+ size_t skew_constant_alignment = 0) {+ // Allocate a single shared buffer for all constants, with padding to the specified alignment.+ size_t source_buffer_size = 0;+ for (const auto& constant : constants) {+ source_buffer_size += ov::util::align_size_up(constant->get_byte_size(), alignment) + skew_constant_alignment;+ }++ const size_t source_id = source_id_generator();+ auto raw = std::make_shared<ov::AlignedBuffer>(source_buffer_size, alignment);++ auto source_buffer = std::make_shared<::ov::SharedBuffer<std::shared_ptr<ov::AlignedBuffer>>>(raw->get_ptr<char>(),+ raw->size(),+ raw,+ ::ov::create_base_descriptor(source_id, 0, raw));++ // slate the source buffer to hold all constants inside it with offets equal to the requested alignment.+ size_t constant_id = skew_constant_alignment; // constants ID is a weight offset in the shared source buffer+ std::vector<std::shared_ptr<ov::op::v0::Constant>> shared_constants;+ auto shared_ctx_ptr = std::make_shared<ov::weight_sharing::Context>();+ ov::weight_sharing::set_weight_source(*shared_ctx_ptr, source_buffer);+ for (const auto& constant : constants) {+ auto const_descriptor = ::ov::create_base_descriptor(source_id, constant_id, source_buffer);+ auto weight_sharing_constant_buffer_view =+ std::make_shared<::ov::SharedBuffer<std::shared_ptr<ov::AlignedBuffer>>>(source_buffer->get_ptr<char>() + constant_id,+ constant->get_byte_size(),+ source_buffer,+ const_descriptor);+ constant_id += ov::util::align_size_up(constant->get_byte_size(), alignment) + skew_constant_alignment;+ auto shared_constant =+ std::make_shared<ov::op::v0::Constant>(constant->get_element_type(), constant->get_shape(), weight_sharing_constant_buffer_view);+ shared_constant->set_friendly_name(constant->get_friendly_name());+ std::memcpy(weight_sharing_constant_buffer_view->get_ptr(), constant->get_data_ptr(), constant->get_byte_size());++ ov::replace_node(constant, shared_constant);++ // register the shared constant in the weight sharing context+ ov::weight_sharing::set_constant(*shared_ctx_ptr, *shared_constant);+ ov::weight_sharing::set_runtime_weight_source(*shared_ctx_ptr, source_buffer);+ }+ return std::make_tuple(std::move(shared_ctx_ptr), std::move(source_buffer));+}++std::tuple<std::shared_ptr<ov::weight_sharing::Context>, std::shared_ptr<::ov::SharedBuffer<std::shared_ptr<ov::AlignedBuffer>>>>+makeWeightSharingContextIncorrectAlignment(std::vector<std::shared_ptr<ov::op::v0::Constant>>&& constants, std::function<size_t()> source_id_generator) {+ size_t alignment_not_equal_to_page_size = 64;+ // This skew will cause the constants to be misaligned in the shared buffer, which should trigger an error during+ // during GPU memory importing.+ // The skew is required to be non-zero, as the system memory manager call allocates memory aligned to the system page size,+ // even if we request 64 bytes-alignment+ size_t individual_constant_alignment_skew = 13;+ return makeWeightSharingContext(std::move(constants), alignment_not_equal_to_page_size, source_id_generator, individual_constant_alignment_skew);+}++std::tuple<std::shared_ptr<ov::weight_sharing::Context>, std::shared_ptr<::ov::SharedBuffer<std::shared_ptr<ov::AlignedBuffer>>>>+makeCorrectWeightSharingContext(std::vector<std::shared_ptr<ov::op::v0::Constant>>&& constants, std::function<size_t()> source_id_generator) {+ size_t page_alignment = static_cast<size_t>(ov::util::get_system_page_size());+ return makeWeightSharingContext(std::move(constants), page_alignment, source_id_generator, 0);+}++class WeightContextTest : public ::testing::Test {+protected:+ void SetUp() override {+ auto cache_file_path = std::filesystem::path(testing::UnitTest::GetInstance()->current_test_info()->name()).replace_extension(".bin");+ if (std::filesystem::exists(cache_file_path)) {+ std::filesystem::remove(cache_file_path);+ }+ properties = ov::AnyMap{{ov::cache_path(cache_file_path)}};+ }++ void TearDown() override {+ auto cache_path_it = properties.find(ov::cache_path.name());+ assert(cache_path_it != properties.end());+ auto cache_path = cache_path_it->second.as<std::filesystem::path>();+ std::filesystem::remove(cache_path);+ }++ void enableWeightSharingContext(const ov::internal::WeightSharingCtxPtr& weightCtx) {+ const ov::internal::WeightSharingCtxPtr shared_ctx = weightCtx;+ properties[ov::internal::model_sharing_context.name()] = ov::Any{shared_ctx};+ }++ const ov::AnyMap& getProperties() const {+ return properties;+ }++private:+ ov::AnyMap properties;+};+} // namespace++TEST_F(WeightContextTest, smoke_weightContextCannotBeConsumedDueToUnsupportedAlignment) {+ auto core = ov::Core();+ const size_t weight_size = 1024;+ auto [model, weight_count] = makeModelWithWeights(weight_size);+ auto shared_constant_candidates = collectConstants(*model);+ ASSERT_EQ(shared_constant_candidates.size(), weight_count);++ auto [weightCtx, sourceBuffer] = makeWeightSharingContextIncorrectAlignment(std::move(shared_constant_candidates), []() {+ return 1;+ });+ ASSERT_TRUE(sourceBuffer->size() >= weight_size * weight_count);++ enableWeightSharingContext(weightCtx);+ EXPECT_THROW(core.compile_model(model, "GPU", getProperties()), ov::Exception);+}++TEST_F(WeightContextTest, smoke_weightContextInferenceWithSharedWeights) {+ auto core = ov::Core();+ const size_t weight_size = 1024;+ auto [model_to_mutate, weight_count] = makeModelWithWeights(weight_size);+ auto shared_constant_candidates = collectConstants(*model_to_mutate);+ ASSERT_EQ(shared_constant_candidates.size(), weight_count);++ auto [weightCtx, sourceBuffer] = makeCorrectWeightSharingContext(std::move(shared_constant_candidates), []() {+ return 2;+ });+ enableWeightSharingContext(weightCtx);+ auto mutated_exec_net = core.compile_model(model_to_mutate, "GPU", getProperties());+ auto mutated_inf_req = mutated_exec_net.create_infer_request();++ auto [intact_model, intact_weight_count] = makeModelWithWeights(weight_size);+ auto intact_exec_net = core.compile_model(intact_model, "GPU");+ auto intact_inf_req = intact_exec_net.create_infer_request();++ ov::Tensor input_tensor(ov::element::u8, ov::Shape{weight_size});+ OV_ASSERT_NO_THROW(mutated_inf_req.set_input_tensor(input_tensor));+ OV_ASSERT_NO_THROW(mutated_inf_req.infer());+ OV_ASSERT_NO_THROW(intact_inf_req.set_input_tensor(input_tensor));+ OV_ASSERT_NO_THROW(intact_inf_req.infer());+ ASSERT_EQ(+ std::memcmp(intact_inf_req.get_output_tensor().data(), mutated_inf_req.get_output_tensor().data(), intact_inf_req.get_output_tensor().get_byte_size()),+ 0);+}diff --git a/src/plugins/intel_gpu/tests/functional/sources.cmake b/src/plugins/intel_gpu/tests/functional/sources.cmakeindex 36554fe76de..c7d65aebc00 100644--- a/src/plugins/intel_gpu/tests/functional/sources.cmake+++ b/src/plugins/intel_gpu/tests/functional/sources.cmake@@ -9,6 +9,7 @@ set(GPU_FUNCTIONAL_TEST_SOURCES${CMAKE_CURRENT_LIST_DIR}/behavior/memory_dyn_batch.cpp${CMAKE_CURRENT_LIST_DIR}/behavior/model_cache.cpp${CMAKE_CURRENT_LIST_DIR}/behavior/properties.cpp+ ${CMAKE_CURRENT_LIST_DIR}/behavior/weight_context.cpp${CMAKE_CURRENT_LIST_DIR}/concurrency/gpu_concurrency_tests.cpp${CMAKE_CURRENT_LIST_DIR}/concurrency/gpu_reservation_test.cpp${CMAKE_CURRENT_LIST_DIR}/custom_op/custom_op.cpp