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] Keep constants in device memory during program build on discrete GPUs (#39710)
Omkar Vivek Sabnis442567991d30
diff --git a/src/plugins/intel_gpu/docs/memory_allocation_gpu_plugin.md b/src/plugins/intel_gpu/docs/memory_allocation_gpu_plugin.mdindex 183df1a496b..749fe36a47f 100644--- a/src/plugins/intel_gpu/docs/memory_allocation_gpu_plugin.md+++ b/src/plugins/intel_gpu/docs/memory_allocation_gpu_plugin.md@@ -34,7 +34,7 @@ Here, `current` denotes the amount of total allocated memory at that moment, whi## Allocated memory objectsThe typical memory allocation performed in the GPU plugin can be categorized as follows:-* `Constant memory allocation`: In GPU plugin, constant data are held by the `data` primitives and the required memory objects are [allocated](https://github.com/openvinotoolkit/openvino/blob/de47a3b4a4ba1f8464b85a665c4d58403e0d16b8/src/plugins/intel_gpu/src/plugin/ops/constant.cpp#L181) and assigned at the creation of the data primitive. First, it is allocated on the host memory and the constant data are copied from the corresponding blob in ngraph. Once all the transformation and optimization processes in `cldnn::program` are finished and the user nodes of the data are known as the GPU operations using the device memory, then the memory is reallocated on the device memory and the constant data is copied to there (that is, [transferred](https://github.com/openvinotoolkit/openvino/blob/de47a3b4a4ba1f8464b85a665c4d58403e0d16b8/src/plugins/intel_gpu/src/graph/program.cpp#L457)). Note that constant data is shared within batches and streams.+* `Constant memory allocation`: In GPU plugin, constant data are held by the `data` primitives and the required memory objects are allocated and assigned at the creation of the data primitive. On discrete GPUs, the memory is allocated on the device and the constant data are copied there directly, so the build does not hold a host copy of every constant. Once all the transformation and optimization processes in `cldnn::program` are finished, `program::transfer_memory_to_device()` moves the constants that are read on the host (shape inference dependencies and inputs of CPU implementations) to host-accessible memory. On other devices, the memory is allocated on the host memory, and constants whose users are GPU operations are transferred to the device memory at that point. Note that constant data is shared within batches and streams.* `Output memory allocation`: A memory object to store the output result of each primitive is created at the creation of each `primitive_inst` ([link](https://github.com/openvinotoolkit/openvino/blob/de47a3b4a4ba1f8464b85a665c4d58403e0d16b8/src/plugins/intel_gpu/src/graph/primitive_inst.cpp#L263)), except when the output is reusing the input memory. Note that the creation of a `primitive_inst` is done in descending order of the output memory size for achieving better memory reusing efficiency.* `Intermediate memory allocation`: Some primitives such as _detection_output_ and _non_max_suppression_ consisting of multiple kernels require intermediate memories to exchange data b/w those kernels. The allocation of such intermediate memories happens after all allocation for `primitive_insts` is finished ([link](https://github.com/openvinotoolkit/openvino/blob/4c01d6c50c6d314373dffd2a8ddbc294011b2508/src/plugins/intel_gpu/src/graph/network.cpp#L592)). After all, it needs to be processed in a processing order to use the predecessors' allocation information to decide whether to allocate it on device memory or not by checking the memory allocation restriction described above.diff --git a/src/plugins/intel_gpu/include/intel_gpu/runtime/engine.hpp b/src/plugins/intel_gpu/include/intel_gpu/runtime/engine.hppindex 046114bd206..ab14b4e4161 100644--- a/src/plugins/intel_gpu/include/intel_gpu/runtime/engine.hpp+++ b/src/plugins/intel_gpu/include/intel_gpu/runtime/engine.hpp@@ -121,6 +121,9 @@ public:/// Returns true if current engine supports zero copy via host buffer accessbool can_use_host_usm_zero_copy() const;+ /// Returns true if constants are kept in usm_device memory on this engine+ bool keeps_constants_in_device_memory() const;+/// Returns device structure which represents stores device capabilitiesconst device_info& get_device_info() const;diff --git a/src/plugins/intel_gpu/src/graph/network.cpp b/src/plugins/intel_gpu/src/graph/network.cppindex 0da74b201e1..fca01a529ce 100644--- a/src/plugins/intel_gpu/src/graph/network.cpp+++ b/src/plugins/intel_gpu/src/graph/network.cpp@@ -1477,11 +1477,7 @@ void network::transfer_memory_to_device(std::shared_ptr<primitive_inst> instancereturn;}- if (!get_engine().supports_allocation(allocation_type::usm_device)) {- return;- }-- if (!get_engine().get_device_info().has_separate_cache) {+ if (!get_engine().keeps_constants_in_device_memory()) {return;}@@ -1494,11 +1490,6 @@ void network::transfer_memory_to_device(std::shared_ptr<primitive_inst> instance}if (alloc_type == allocation_type::usm_host || alloc_type == allocation_type::usm_shared) {- // usm_device memory does not provide performance benefits on the integrated Xe2+ platforms- if (get_engine().get_device_info().arch >= gpu_arch::xe2 && get_engine().get_device_info().dev_type == device_type::integrated_gpu) {- return;- }-// Allocate and transfer memoryauto device_mem = inst_mem.get_engine()->allocate_memory(inst_mem.get_layout(), allocation_type::usm_device, false);device_mem->copy_from(get_stream(), inst_mem);diff --git a/src/plugins/intel_gpu/src/graph/program.cpp b/src/plugins/intel_gpu/src/graph/program.cppindex 1931bc3cd6b..5c759b85b5b 100644--- a/src/plugins/intel_gpu/src/graph/program.cpp+++ b/src/plugins/intel_gpu/src/graph/program.cpp@@ -754,10 +754,21 @@ void program::transfer_memory_to_device() {get_stream().finish();};for (const auto& node : processing_order) {- if (node->is_shape_infer_dep()) {+ if (node->is_shape_infer_dep() || node->need_lockable_memory()) {+ // CreateConstantOp allocates constants in usm_device when the engine keeps them there; the ones that+ // are read on the host move back to lockable memory. Constants without users stay where they are.+ if (node->is_type<data>() && !node->get_users().empty() && !node->as<data>().get_primitive()->skip_device_transfer()) {+ auto& data_node = node->as<data>();+ const auto& mem = data_node.get_attached_memory();+ const auto& mem_layout = mem.get_layout();+ if (mem.get_allocation_type() == allocation_type::usm_device && mem_layout.count() != 0) {+ const auto lockable_type = get_engine().get_lockable_preferred_memory_allocation_type(mem_layout.format.is_image_2d());+ allocate_and_transfer(data_node, mem_layout, mem, lockable_type);+ }+ }continue;}- if (node->is_type<data>() && !node->need_lockable_memory()) {+ if (node->is_type<data>()) {auto& data_node = node->as<data>();auto data_node_layout = data_node.get_output_layout();auto prim = data_node.get_primitive();@@ -773,11 +784,8 @@ void program::transfer_memory_to_device() {}allocation_type target_alloc_type = alloc_type;- // usm_device memory does not provide performance benefits on the LNL platformif ((alloc_type == allocation_type::usm_host || alloc_type == allocation_type::usm_shared) &&- (get_engine().get_device_info().arch < gpu_arch::xe2 ||- get_engine().get_device_info().dev_type != device_type::integrated_gpu)) {- // Convert to usm_device for performance optimization+ get_engine().keeps_constants_in_device_memory()) {target_alloc_type = allocation_type::usm_device;}diff --git a/src/plugins/intel_gpu/src/plugin/ops/constant.cpp b/src/plugins/intel_gpu/src/plugin/ops/constant.cppindex c080af31568..c2635182c4b 100644--- a/src/plugins/intel_gpu/src/plugin/ops/constant.cpp+++ b/src/plugins/intel_gpu/src/plugin/ops/constant.cpp@@ -171,7 +171,16 @@ static void create_data(ProgramBuilder& p, const ov::Shape& const_shape, const sif (partial_upload.enabled) {mem = partial_upload.memory;} else if (constLayout.bytes_count() > 0) {- mem = p.get_engine().allocate_memory(constLayout, false);+ // Allocating in usm_device right away avoids holding a host copy of every constant until+ // program::transfer_memory_to_device() runs at the end of the build. Integrated GPUs keep the host+ // allocation: there the per-constant uploads and the host reads cost more compile time than they save.+ auto& engine = p.get_engine();+ const bool is_image = constLayout.format.is_image_2d();+ const bool is_dgpu = engine.get_device_info().dev_type == cldnn::device_type::discrete_gpu;+ const auto alloc_type = engine.keeps_constants_in_device_memory() && is_dgpu && !is_image+ ? cldnn::allocation_type::usm_device+ : engine.get_lockable_preferred_memory_allocation_type(is_image);+ mem = engine.allocate_memory(constLayout, alloc_type, false);} else {// In the case of empty const data with {0} shape, it has zero byte.// To avoid zero byte memory allocation issue, reinterpret one dimension memory to zero dimension memory.@@ -185,8 +194,6 @@ static void create_data(ProgramBuilder& p, const ov::Shape& const_shape, const sif (!partial_upload.enabled) {auto& stream = p.get_engine().get_service_stream();- cldnn::mem_lock<char> lock{mem, stream};- auto* buf = lock.data();auto bufSize = constLayout.bytes_count();auto upload_count = ov::shape_size(const_shape);@@ -194,10 +201,23 @@ static void create_data(ProgramBuilder& p, const ov::Shape& const_shape, const s// instead. Convert the data in that case, otherwise just copy it.const auto src_et = op->get_output_element_type(0);const auto dst_et = ov::element::Type(out_dtype);- if (src_et == dst_et) {- std::memcpy(&buf[0], &data[0], bufSize);+ if (mem->get_allocation_type() == cldnn::allocation_type::usm_device) {+ // A lock of usm_device memory would copy it to the host first, so upload with one copy instead+ if (src_et == dst_et) {+ mem->copy_from(stream, data, 0, 0, bufSize, true);+ } else {+ std::vector<char> converted(bufSize);+ convert_and_copy(data, src_et, converted.data(), dst_et, upload_count, constLayout);+ mem->copy_from(stream, converted.data(), 0, 0, bufSize, true);+ }} else {- convert_and_copy(data, src_et, buf, dst_et, upload_count, constLayout);+ cldnn::mem_lock<char> lock{mem, stream};+ auto* buf = lock.data();+ if (src_et == dst_et) {+ std::memcpy(&buf[0], &data[0], bufSize);+ } else {+ convert_and_copy(data, src_et, buf, dst_et, upload_count, constLayout);+ }}}ov::wsh::Extension::hint_evict(*op);diff --git a/src/plugins/intel_gpu/src/runtime/engine.cpp b/src/plugins/intel_gpu/src/runtime/engine.cppindex f991551abca..5d590f8f327 100644--- a/src/plugins/intel_gpu/src/runtime/engine.cpp+++ b/src/plugins/intel_gpu/src/runtime/engine.cpp@@ -109,6 +109,13 @@ bool engine::can_use_host_usm_zero_copy() const {return info.dev_type == cldnn::device_type::integrated_gpu && info.arch >= cldnn::gpu_arch::xe2 && supports_allocation(cldnn::allocation_type::usm_host);}+bool engine::keeps_constants_in_device_memory() const {+ const auto& info = get_device_info();+ // usm_device memory does not provide performance benefits on integrated Xe2+ platforms+ return supports_allocation(cldnn::allocation_type::usm_device) && info.has_separate_cache &&+ (info.arch < cldnn::gpu_arch::xe2 || info.dev_type != cldnn::device_type::integrated_gpu);+}+allocation_type engine::get_lockable_preferred_memory_allocation_type(bool is_image_layout) const {if (!use_unified_shared_memory() || is_image_layout) {return get_default_allocation_type();@@ -117,7 +124,8 @@ allocation_type engine::get_lockable_preferred_memory_allocation_type(bool is_im/*We do not check device allocation here.Device allocation is reserved for buffers of hidden layers.- Const buffers are propagated to device if possible.+ Const buffers are allocated in device memory directly on discrete GPUs, otherwise they are propagated to+ device if keeps_constants_in_device_memory() is true.*/bool support_usm_host = supports_allocation(allocation_type::usm_host);diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/data_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/data_gpu_test.cppindex b8d3a78e438..a18fb209e33 100644--- a/src/plugins/intel_gpu/tests/unit/test_cases/data_gpu_test.cpp+++ b/src/plugins/intel_gpu/tests/unit/test_cases/data_gpu_test.cpp@@ -11,6 +11,8 @@#include <intel_gpu/primitives/input_layout.hpp>#include <intel_gpu/primitives/data.hpp>#include <intel_gpu/primitives/fully_connected.hpp>+#include <intel_gpu/primitives/reshape.hpp>+#include <intel_gpu/primitives/activation.hpp>#include <cstddef>@@ -169,3 +171,44 @@ TEST(data_gpu, transfer_memory_padding_mismatch_forced) {}ASSERT_FALSE(exception_thrown) << "Padding fix failed! Exception: " << exception_msg;}++TEST(data_gpu, transfer_memory_keeps_shape_infer_constant_lockable) {+ auto& engine = get_test_engine();+ if (!engine.keeps_constants_in_device_memory()) {+ GTEST_SKIP() << "Constants are not kept in usm_device memory on this device";+ }++ // CreateConstantOp allocates constants in usm_device on such devices, including a Reshape pattern+ // that shape inference reads on the host.+ auto pattern_layout = layout{ov::PartialShape{2}, data_types::i64, format::bfyx};+ auto pattern_mem = engine.allocate_memory(pattern_layout, allocation_type::usm_device, false);+ std::vector<int64_t> pattern = {-1, 4};+ pattern_mem->copy_from(get_test_stream(), pattern.data(), true);++ auto in_layout = layout{ov::PartialShape::dynamic(2), data_types::f32, format::bfyx};+ topology topology(input_layout("input", in_layout),+ data("pattern", pattern_mem),+ reshape("reshape", input_info("input"), input_info("pattern"), false, ov::PartialShape::dynamic(2)),+ activation("relu", input_info("reshape"), activation_func::relu));++ ExecutionConfig config = get_test_default_config(engine);+ config.set_property(ov::intel_gpu::optimize_data(true));+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));+ network network(engine, topology, config);++ ASSERT_NE(network.get_primitive("pattern")->output_memory().get_allocation_type(), allocation_type::usm_device);++ auto input_mem = engine.allocate_memory(layout{ov::PartialShape{2, 6}, data_types::f32, format::bfyx});+ std::vector<float> input = {1.f, -2.f, 3.f, -4.f, 5.f, -6.f, 7.f, -8.f, 9.f, -10.f, 11.f, -12.f};+ set_values(input_mem, input);+ network.set_input_data("input", input_mem);++ auto outputs = network.execute();+ auto output_mem = outputs.at("relu").get_memory();+ ASSERT_EQ(output_mem->get_layout().get_shape(), (ov::Shape{3, 4}));++ cldnn::mem_lock<float, mem_lock_type::read> output_ptr(output_mem, get_test_stream());+ for (size_t i = 0; i < input.size(); i++) {+ ASSERT_EQ(std::max(input[i], 0.f), output_ptr[i]);+ }+}