Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[GPU] Fix memory corruption in in-place concat with dynamic batch sizes (#37165)

Yitong Dang41b854819abd
diff --git a/src/plugins/intel_gpu/src/graph/include/pass_manager.h b/src/plugins/intel_gpu/src/graph/include/pass_manager.h
index d1d3155741a..658e242ea99 100644
--- a/src/plugins/intel_gpu/src/graph/include/pass_manager.h
+++ b/src/plugins/intel_gpu/src/graph/include/pass_manager.h
@@ -4,23 +4,24 @@
#pragma once
+#include <fstream>
+#include <list>
+#include <memory>
+#include <set>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "concatenation_inst.h"
+#include "convolution_inst.h"
+#include "eltwise_inst.h"
#include "intel_gpu/graph/program.hpp"
#include "layout_optimizer.h"
+#include "lora_inst.h"
#include "quantize_inst.h"
-#include "eltwise_inst.h"
-#include "convolution_inst.h"
#include "read_value_inst.h"
-#include "lora_inst.h"
-#include <string>
-#include <vector>
-#include <memory>
-#include <list>
-#include <utility>
-#include <set>
-#include <fstream>
-
-#define GPU_DEBUG_LOG_PASS GPU_DEBUG_LOG << "[" << get_name() << "] "
+#define GPU_DEBUG_LOG_PASS GPU_DEBUG_LOG << "[" << get_name() << "] "
namespace cldnn {
class base_pass {
@@ -29,7 +30,9 @@ class base_pass {
public:
explicit base_pass(const std::string& pass_name) : name(pass_name) {}
virtual void run(program& p) = 0;
- std::string get_name() { return name; }
+ std::string get_name() {
+ return name;
+ }
private:
const std::string name;
@@ -134,8 +137,8 @@ private:
void handle_quantize_node(program& p, quantize_node& quantize_node);
void prepare_dequantize_merge(program& p, eltwise_node& eltwise_node);
void remove_fake_reorders(program& p, reorder_node& reorder_node);
- void prepare_scale_shift_opt(program &p, quantize_node& quantize_node);
- bool optimize_quantize(program &p, quantize_node& quantize_node);
+ void prepare_scale_shift_opt(program& p, quantize_node& quantize_node);
+ bool optimize_quantize(program& p, quantize_node& quantize_node);
};
// TODO: Remove this pass once no unexpected reshapes/reorders are added during ov::Model -> cldnn::topology conversion
@@ -151,19 +154,18 @@ public:
private:
void run(program& p) override;
- void fuse_bias(program &p);
- void fuse_swiglu(program &p);
+ void fuse_bias(program& p);
+ void fuse_swiglu(program& p);
void fuse_reorders(program& p);
- void fuse_simple_primitives(program &p);
- void fuse_constant_transposes(program &p);
- void optimize_fused_ops(program &p);
- void remove_redundant_reshape(program &p);
+ void fuse_simple_primitives(program& p);
+ void fuse_constant_transposes(program& p);
+ void optimize_fused_ops(program& p);
+ void remove_redundant_reshape(program& p);
};
class pre_replace_deconv : public base_pass {
public:
- explicit pre_replace_deconv() :
- base_pass("pre_replace_deconv") {}
+ explicit pre_replace_deconv() : base_pass("pre_replace_deconv") {}
private:
void run(program& p) override;
@@ -172,8 +174,10 @@ private:
class prepare_padding : public base_pass {
public:
explicit prepare_padding(bool output_size_handling_enabled_switch)
- : base_pass("prepare_padding"), output_size_handling_enabled(output_size_handling_enabled_switch) {}
+ : base_pass("prepare_padding"),
+ output_size_handling_enabled(output_size_handling_enabled_switch) {}
static cldnn::padding get_needed_padding_for_convolution(convolution_node& node);
+
private:
void run(program& p) override;
bool output_size_handling_enabled;
@@ -198,24 +202,33 @@ private:
size_t bias_offset;
// When using this ctor weights offset is added to the bias_offset
- weights_bias_offset(const size_t w_offset, const size_t b_offset)
- : weights_offset(w_offset)
- , bias_offset(weights_offset + b_offset)
- {}
+ weights_bias_offset(const size_t w_offset, const size_t b_offset) : weights_offset(w_offset), bias_offset(weights_offset + b_offset) {}
};
void run(program& p) override;
- template<typename T>
+ template <typename T>
weights_bias_offset get_weights_bias_offset(const T& node);
- template<typename T>
+ template <typename T>
void optimize_weights(T& node, program& p);
void select_implementation(program& p, program_node& node);
- void add_lstm_weights_reorder(primitive_id input_id, std::shared_ptr<WeightsReorderParams> reorder_params, program& p, cldnn::program_node&, \
- cldnn::program_node&, size_t);
- void add_gru_weights_reorder(primitive_id input_id, std::shared_ptr<WeightsReorderParams> reorder_params, program& p, cldnn::program_node&, \
- cldnn::program_node&, size_t);
- void add_lstm_bias_reorder(primitive_id input_id, std::shared_ptr<WeightsReorderParams> reorder_params, program& p, cldnn::program_node&, \
- cldnn::program_node&, size_t);
+ void add_lstm_weights_reorder(primitive_id input_id,
+ std::shared_ptr<WeightsReorderParams> reorder_params,
+ program& p,
+ cldnn::program_node&,
+ cldnn::program_node&,
+ size_t);
+ void add_gru_weights_reorder(primitive_id input_id,
+ std::shared_ptr<WeightsReorderParams> reorder_params,
+ program& p,
+ cldnn::program_node&,
+ cldnn::program_node&,
+ size_t);
+ void add_lstm_bias_reorder(primitive_id input_id,
+ std::shared_ptr<WeightsReorderParams> reorder_params,
+ program& p,
+ cldnn::program_node&,
+ cldnn::program_node&,
+ size_t);
reorder_factory& _rf;
std::map<reorder_cache_key, program_node*> _cached_lstm_weights_reorder;
@@ -228,13 +241,8 @@ public:
private:
void run(program& p) override;
- std::list<std::tuple<
- primitive_id,
- memory::ptr,
- std::tuple<std::shared_ptr<weightless_cache_manager>, std::shared_ptr<layout>, std::shared_ptr<reorder>>>>
- calculate(engine& engine,
- const ExecutionConfig& config,
- std::shared_ptr<ov::threading::IStreamsExecutor> task_executor);
+ std::list<std::tuple<primitive_id, memory::ptr, std::tuple<std::shared_ptr<weightless_cache_manager>, std::shared_ptr<layout>, std::shared_ptr<reorder>>>>
+ calculate(engine& engine, const ExecutionConfig& config, std::shared_ptr<ov::threading::IStreamsExecutor> task_executor);
bool has_non_const_user(program_node& node) const;
void handle_constant(program& prog, program_node& node);
void add_constant(program& prog, program_node& node);
@@ -248,8 +256,7 @@ private:
class remove_redundant_reorders : public base_pass {
public:
- explicit remove_redundant_reorders(bool enable_reorder_fusing = false, bool update_implementations = false,
- bool remove_output_reorders = false);
+ explicit remove_redundant_reorders(bool enable_reorder_fusing = false, bool update_implementations = false, bool remove_output_reorders = false);
void run(program& p) override;
private:
@@ -333,6 +340,20 @@ public:
return;
}
+ // Concat can be optimized out by in-place concat, so in this case, the output buffer
+ // of this concat node must not overlap with its dependencies' input buffers.
+ const bool dep_is_direct_pred =
+ std::any_of(node->get_dependencies().begin(), node->get_dependencies().end(), [&](const std::pair<program_node*, int32_t>& d) {
+ return d.first == dep;
+ });
+
+ if (node->is_type<concatenation>() && node->can_be_optimized() && node->is_runtime_skippable() && dep_is_direct_pred) {
+ for (const auto& subdep : dep->get_dependencies()) {
+ add_memory_dependency(node, subdep.first);
+ add_memory_dependency(subdep.first, node);
+ }
+ }
+
// LoRA can reuse the memory of the previous node, but not be optimized
// Therefore, the dependency of LoRA must also be the dependency of the current node
if (dep->is_type<lora>()) {
diff --git a/src/plugins/intel_gpu/src/graph/primitive_inst.cpp b/src/plugins/intel_gpu/src/graph/primitive_inst.cpp
index eb4a4c7853f..795944f04a8 100644
--- a/src/plugins/intel_gpu/src/graph/primitive_inst.cpp
+++ b/src/plugins/intel_gpu/src/graph/primitive_inst.cpp
@@ -729,6 +729,15 @@ void primitive_inst::realloc_outputs(bool prev_execution_skipped) {
this->_outputs[0] = concat_inst->_outputs[0];
GPU_DEBUG_TRACE_DETAIL << id() << ": use concat user's memory " << this->_outputs[0]->buffer_ptr() << std::endl;
return;
+ } else if (!_outputs.empty() && _outputs[0] != nullptr &&
+ !concat_inst->_outputs.empty() && concat_inst->_outputs[0] != nullptr &&
+ get_network().get_engine().is_the_same_buffer(*_outputs[0], *concat_inst->_outputs[0])) {
+ // In-place concat optimization is rejected now, but a previous execution with this optimization
+ // may have the same memory aliased to its deps' outputs and itself's output. In this case, we
+ // need to reallocate the memory for this node to avoid memory corruption.
+ GPU_DEBUG_TRACE_DETAIL << id() << ": reallocate memory for concat " << concat_inst->id()
+ << " after rejected in-place concat" << std::endl;
+ clear_output_memory();
}
}
@@ -1851,6 +1860,33 @@ void primitive_inst::do_runtime_in_place_concat() {
if (!concat_in_place_optimization::match(concat_inst->get_node(), *concat_inst->_impl_params, pred_params, true)) {
concat_inst->set_can_be_optimized(false);
GPU_DEBUG_TRACE_DETAIL << "[In place concat] " << concat_inst->id() << " cannot be optimized " << std::endl;
+
+ // If the in-place concat optimization is not possible on this iteration, but it is applied
+ // previously, we need to reset the paddings of its deps' output layouts to the natural
+ // values.
+
+ bool padding_reverted = false;
+ size_t dep_idx = 0;
+ for (auto& dep : concat_inst->_deps) {
+ if (dep.first->_impl_params->output_layouts[0].data_padding != dep.first->get_node().get_output_layout(0).data_padding) {
+ dep.first->set_flag(ExecutionFlags::SHAPE_CHANGED);
+ dep.first->_impl_params->output_layouts[0].data_padding = dep.first->get_node().get_output_layout(0).data_padding;
+ GPU_DEBUG_TRACE_DETAIL << "[In place concat] Revert padding of dep " << dep.first->id() << " : "
+ << dep.first->_impl_params->output_layouts[0].to_string() << std::endl;
+ padding_reverted = true;
+ }
+ if (dep_idx < concat_inst->_impl_params->input_layouts.size() &&
+ concat_inst->_impl_params->input_layouts[dep_idx].data_padding != dep.first->get_node().get_output_layout(0).data_padding) {
+ concat_inst->_impl_params->input_layouts[dep_idx].data_padding = dep.first->get_node().get_output_layout(0).data_padding;
+ GPU_DEBUG_TRACE_DETAIL << "[In place concat] Revert padding of input " << dep_idx << " : "
+ << concat_inst->_impl_params->input_layouts[dep_idx].to_string() << std::endl;
+ padding_reverted = true;
+ }
+ ++dep_idx;
+ }
+ if (padding_reverted)
+ concat_inst->set_flag(ExecutionFlags::SHAPE_CHANGED);
+
return;
}
@@ -1858,12 +1894,18 @@ void primitive_inst::do_runtime_in_place_concat() {
concat_in_place_optimization::update_in_place_concat_paddings(concat_layout, preds_layouts, concat_axis, true);
size_t i = 0;
for (auto& dep : concat_inst->_deps) {
- if (_impl_params->output_layouts[0] != preds_layouts[i]) {
+ if (dep.first->_impl_params->output_layouts[0] != preds_layouts[i]) {
dep.first->set_flag(ExecutionFlags::SHAPE_CHANGED);
dep.first->_impl_params->output_layouts[0] = preds_layouts[i];
+ GPU_DEBUG_TRACE_DETAIL << "[In place concat] Update padding of pred " << i << " : "
+ << dep.first->_impl_params->output_layouts[0].to_string() << std::endl;
+ }
+ if (i < concat_inst->_impl_params->input_layouts.size() &&
+ concat_inst->_impl_params->input_layouts[i].data_padding != preds_layouts[i].data_padding) {
+ concat_inst->_impl_params->input_layouts[i].data_padding = preds_layouts[i].data_padding;
+ GPU_DEBUG_TRACE_DETAIL << "[In place concat] Update padding of input " << i << " : "
+ << concat_inst->_impl_params->input_layouts[i].to_string() << std::endl;
}
- GPU_DEBUG_TRACE_DETAIL << "[In place concat] Update padding of pred " << i << " : "
- << dep.first->_impl_params->output_layouts[0].to_string() << std::endl;
++i;
}
concat_inst->_impl_params->output_layouts[0] = concat_layout; // TODO : Once this primitive_inst::can_be_optimized, consolidate it to impl_params->optimized
diff --git a/src/plugins/intel_gpu/tests/functional/subgraph_tests/dynamic/concat_in_place_dynamic_batch.cpp b/src/plugins/intel_gpu/tests/functional/subgraph_tests/dynamic/concat_in_place_dynamic_batch.cpp
new file mode 100644
index 00000000000..ef44c6f3d04
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/functional/subgraph_tests/dynamic/concat_in_place_dynamic_batch.cpp
@@ -0,0 +1,144 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+#include "shared_test_classes/base/ov_subgraph.hpp"
+#include "common_test_utils/ov_tensor_utils.hpp"
+#include "common_test_utils/node_builders/convolution.hpp"
+
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/result.hpp"
+#include "openvino/op/concat.hpp"
+#include "openvino/op/convolution.hpp"
+
+namespace {
+using ov::test::InputShape;
+
+typedef std::tuple<
+ std::vector<InputShape>, // input shapes
+ ov::element::Type, // Model type
+ std::string // Device name
+> concatInPlaceDynamicBatchGPUTestParamsSet;
+
+class ConcatInPlaceDynamicBatchGPUTest : public testing::WithParamInterface<concatInPlaceDynamicBatchGPUTestParamsSet>,
+ virtual public ov::test::SubgraphBaseTest {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<concatInPlaceDynamicBatchGPUTestParamsSet>& obj) {
+ concatInPlaceDynamicBatchGPUTestParamsSet basicParamsSet = obj.param;
+ std::ostringstream result;
+
+ const auto& [inputShapes, model_type, targetDevice] = basicParamsSet;
+ result << "IS=";
+ for (const auto& shape : inputShapes) {
+ result << ov::test::utils::partialShape2str({shape.first}) << "_";
+ for (const auto& actual_shape : shape.second) {
+ result << ov::test::utils::partialShape2str({actual_shape}) << "_";
+ }
+ }
+ result << "NetType=" << model_type << "_";
+ result << "targetDevice=" << targetDevice;
+ return result.str();
+ }
+
+protected:
+ void infer() override {
+ if (!inferRequest) {
+ inferRequest = compiledModel.create_infer_request();
+ }
+ for (const auto& input : inputs) {
+ inferRequest.set_tensor(input.first, input.second);
+ }
+ inferRequest.infer();
+ }
+
+ void generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) override {
+ inputs.clear();
+ const auto& funcInputs = function->inputs();
+ for (size_t i = 0; i < funcInputs.size(); ++i) {
+ const auto& funcInput = funcInputs[i];
+ ov::Tensor tensor;
+ ov::test::utils::InputGenerateData in_data;
+ in_data.start_from = -1;
+ in_data.range = 2;
+ in_data.resolution = 32;
+ tensor = ov::test::utils::create_and_fill_tensor(funcInput.get_element_type(), targetInputStaticShapes[i], in_data);
+ inputs.insert({funcInput.get_node_shared_ptr(), tensor});
+ }
+ }
+
+ void SetUp() override {
+ concatInPlaceDynamicBatchGPUTestParamsSet basicParamsSet = this->GetParam();
+
+ const auto& [inputShapes, model_type, _targetDevice] = basicParamsSet;
+ targetDevice = _targetDevice;
+
+ configuration.insert(ov::hint::inference_precision(ov::element::f16));
+ abs_threshold = 0.05f;
+
+ init_input_shapes(inputShapes);
+
+ ov::ParameterVector inputParams;
+ for (auto&& shape : inputDynamicShapes)
+ inputParams.push_back(std::make_shared<ov::op::v0::Parameter>(model_type, shape));
+
+ const auto inChannels = inputShapes[0].first[1].get_length();
+ const ov::Shape weightShape = {2, static_cast<size_t>(inChannels), 1, 1};
+
+ auto makeConv = [&](const ov::element::Type &model_type, const ov::Output<ov::Node> &in, int32_t seed) {
+ ov::test::utils::InputGenerateData in_data;
+ in_data.start_from = -1;
+ in_data.range = 2;
+ in_data.resolution = 32;
+ in_data.seed = seed;
+ auto tensor = ov::test::utils::create_and_fill_tensor(model_type, weightShape, in_data);
+ auto constantWeightOp = std::make_shared<ov::op::v0::Constant>(tensor);
+ return ov::test::utils::make_convolution(in, constantWeightOp, model_type, {1, 1}, {1, 1}, {0, 0}, {0, 0},
+ {1, 1}, ov::op::PadType::EXPLICIT, 2);
+ };
+
+ auto convolutionOp1 = makeConv(model_type, inputParams[0], 1);
+ convolutionOp1->set_friendly_name("convolution1");
+
+ auto convolutionOp2 = makeConv(model_type, inputParams[0], 2);
+ convolutionOp2->set_friendly_name("convolution2");
+
+ const auto concat = std::make_shared<ov::op::v0::Concat>(ov::OutputVector({convolutionOp1, convolutionOp2}), 1);
+
+ auto makeFunction = [](ov::ParameterVector &params, const std::shared_ptr<ov::Node> &lastNode) {
+ ov::ResultVector results;
+
+ for (size_t i = 0; i < lastNode->get_output_size(); i++)
+ results.push_back(std::make_shared<ov::op::v0::Result>(lastNode->output(i)));
+
+ return std::make_shared<ov::Model>(results, params, "Concat");
+ };
+ function = makeFunction(inputParams, concat);
+ }
+};
+
+TEST_P(ConcatInPlaceDynamicBatchGPUTest, Inference) {
+ run();
+}
+
+const std::vector<std::vector<InputShape>> dynInputShapes = {
+ {
+ {{-1, 4, 4, 4}, {{1, 4, 4, 4}}},
+ },
+ {
+ {{-1, 4, 4, 4}, {{8, 4, 4, 4}, {1, 4, 4, 4}, {8, 4, 4, 4}}},
+ },
+ {
+ {{-1, 4, 4, 4}, {{1, 4, 4, 4}, {1, 4, 4, 4}, {1, 4, 4, 4}}},
+ },
+ {
+ {{-1, 4, 4, 4}, {{1, 4, 4, 4}, {8, 4, 4, 4}, {3, 4, 4, 4}, {1, 4, 4, 4}}},
+ },
+};
+
+INSTANTIATE_TEST_SUITE_P(smoke_concat_in_place_dynamic_batch, ConcatInPlaceDynamicBatchGPUTest,
+ ::testing::Combine(::testing::ValuesIn(dynInputShapes),
+ ::testing::Values(ov::element::f32),
+ ::testing::Values(ov::test::utils::DEVICE_GPU)),
+ ConcatInPlaceDynamicBatchGPUTest::getTestCaseName);
+
+} // namespace