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][Custom] Offload temp buffers to global memory in GPU ext kernels (#35250)
pravin2544c402372195
diff --git a/src/plugins/intel_gpu/include/intel_gpu/plugin/custom_layer.hpp b/src/plugins/intel_gpu/include/intel_gpu/plugin/custom_layer.hppindex bc58959185f..023ede61d66 100644--- a/src/plugins/intel_gpu/include/intel_gpu/plugin/custom_layer.hpp+++ b/src/plugins/intel_gpu/include/intel_gpu/plugin/custom_layer.hpp@@ -25,6 +25,7 @@ public:Input,Output,Data,+ Internal,} ParamType;struct KerenlParam {KerenlParam() :type(Input), paramIndex(-1), portIndex(-1),@@ -33,6 +34,7 @@ public:int paramIndex;int portIndex;std::string blobName;+ std::string size_expr;cldnn::format format;};diff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/custom_gpu_primitive.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/custom_gpu_primitive.hppindex 0ebe2ebc75b..c35b651f2db 100644--- a/src/plugins/intel_gpu/include/intel_gpu/primitives/custom_gpu_primitive.hpp+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/custom_gpu_primitive.hpp@@ -23,6 +23,7 @@ struct custom_gpu_primitive : public primitive_base<custom_gpu_primitive> {enum arg_type {arg_input,arg_output,+ arg_internal,};///// @brief Custom primitive kernel argument index@@ -32,19 +33,22 @@ struct custom_gpu_primitive : public primitive_base<custom_gpu_primitive> {struct arg_desc {arg_type type;arg_index index;+ std::string size_expr;bool operator==(const arg_desc& rhs) const {- return (type == rhs.type && index == rhs.index);+ return (type == rhs.type && index == rhs.index && size_expr == rhs.size_expr);}void save(BinaryOutputBuffer& ob) const {ob << make_data(&type, sizeof(arg_type));ob << index;+ ob << size_expr;}void load(BinaryInputBuffer& ib) {ib >> make_data(&type, sizeof(arg_type));ib >> index;+ ib >> size_expr;}};@@ -157,6 +161,7 @@ struct custom_gpu_primitive : public primitive_base<custom_gpu_primitive> {for (auto& args : kernel_arguments) {seed = hash_combine(seed, args.index);seed = hash_combine(seed, args.type);+ seed = hash_combine(seed, args.size_expr);}seed = hash_combine(seed, build_options);seed = hash_range(seed, kernels_code.begin(), kernels_code.end());diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl/custom_primitive.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl/custom_primitive.cppindex 6a7df62e83c..a158406059a 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl/custom_primitive.cpp+++ b/src/plugins/intel_gpu/src/graph/impls/ocl/custom_primitive.cpp@@ -6,6 +6,7 @@#include "custom_gpu_primitive_inst.h"#include "jitter.h"+#include "intel_gpu/graph/serialization/map_serializer.hpp"#include <map>#include <sstream>@@ -20,6 +21,50 @@ using jit_constants = kernel_selector::JitConstants;namespace cldnn {namespace ocl {+static size_t evaluate_size_expr(const std::string& size_expr, const kernel_impl_params& impl_params) {+ std::string expr = size_expr;++ // if INPUTn_DIMS[i] tokens+ for (size_t n = 0; n < impl_params.input_layouts.size(); ++n) {+ auto shape = impl_params.input_layouts[n].get_shape();+ for (size_t i = 0; i < shape.size(); ++i) {+ std::string token = "INPUT" + std::to_string(n) + "_DIMS[" + std::to_string(i) + "]";+ size_t pos = 0;+ while ((pos = expr.find(token, pos)) != std::string::npos) {+ auto val = std::to_string(shape[i]);+ expr.replace(pos, token.length(), val);+ pos += val.length();+ }+ }+ }++ // if OUTPUTn_DIMS[i] tokens+ for (size_t n = 0; n < impl_params.output_layouts.size(); ++n) {+ auto shape = impl_params.output_layouts[n].get_shape();+ for (size_t i = 0; i < shape.size(); ++i) {+ std::string token = "OUTPUT" + std::to_string(n) + "_DIMS[" + std::to_string(i) + "]";+ size_t pos = 0;+ while ((pos = expr.find(token, pos)) != std::string::npos) {+ auto val = std::to_string(shape[i]);+ expr.replace(pos, token.length(), val);+ pos += val.length();+ }+ }+ }++ SimpleMathExpression math_expr;+ OPENVINO_ASSERT(math_expr.SetExpression(expr),+ "[GPU] Failed to parse internal buffer size expression: '", size_expr,+ "' (resolved to: '", expr, "')");++ int result = math_expr.Evaluate();+ OPENVINO_ASSERT(result > 0,+ "[GPU] Internal buffer size expression evaluated to non-positive value: ", result,+ " for expression: '", size_expr, "'");++ return static_cast<size_t>(result);+}+struct custom_gpu_primitive_impl : typed_primitive_impl<custom_gpu_primitive> {using parent = typed_primitive_impl<custom_gpu_primitive>;using parent::parent;@@ -28,6 +73,7 @@ struct custom_gpu_primitive_impl : typed_primitive_impl<custom_gpu_primitive> {std::shared_ptr<kernel_selector::cl_kernel_data> cl_kernel;std::vector<kernel::ptr> _kernels;+ std::map<uint32_t, std::string> size_expr_map;std::unique_ptr<primitive_impl> clone() const override {return std::make_unique<custom_gpu_primitive_impl>(*this);@@ -38,7 +84,8 @@ struct custom_gpu_primitive_impl : typed_primitive_impl<custom_gpu_primitive> {custom_gpu_primitive_impl(const custom_gpu_primitive_impl& other): cl_kernel(other.cl_kernel)- , _kernels({}) {+ , _kernels({})+ , size_expr_map(other.size_expr_map) {for (const auto& kernel : other._kernels) {_kernels.emplace_back(kernel->clone(other.can_share_kernels));}@@ -49,6 +96,13 @@ struct custom_gpu_primitive_impl : typed_primitive_impl<custom_gpu_primitive> {: cl_kernel(cl_kernel), _kernels() { }+ custom_gpu_primitive_impl(const custom_gpu_primitive_node& arg,+ std::shared_ptr<kernel_selector::cl_kernel_data>& cl_kernel,+ const std::map<uint32_t, std::string>& size_expr_map)+ : cl_kernel(cl_kernel)+ , _kernels()+ , size_expr_map(size_expr_map) { }+std::vector<std::shared_ptr<cldnn::kernel_string>> get_kernels_source() override {std::vector<std::shared_ptr<cldnn::kernel_string>> kernel_strings;kernel_strings.push_back(cl_kernel->code.kernelString);@@ -82,32 +136,51 @@ struct custom_gpu_primitive_impl : typed_primitive_impl<custom_gpu_primitive> {}}+ std::vector<BufferDescriptor> get_internal_buffer_descs(const kernel_impl_params& impl_params) const override {+ if (size_expr_map.empty())+ return {};++ const auto& input_layout = impl_params.input_layouts[0];+ auto shape = input_layout.get_shape();+ std::vector<int64_t> input_dims(shape.begin(), shape.end());+ auto data_type = impl_params.input_layouts[0].data_type;++ std::vector<BufferDescriptor> descs;+ for (const auto& [index, size_expr] : size_expr_map) {+ size_t element_count = evaluate_size_expr(size_expr, impl_params);+ descs.emplace_back(element_count, data_type);+ }+ return descs;+ }+void set_arguments_impl(custom_gpu_primitive_inst& instance) override {auto& stream = instance.get_network().get_stream();kernel_arguments_data args;for (auto& dep : instance.dependencies()) {args.inputs.push_back(dep.first->output_memory_ptr());}-for (size_t i = 0; i < instance.outputs_memory_count(); i++) {args.outputs.push_back(instance.output_memory_ptr(i));}-+ for (const auto& buf : instance.get_intermediates_memories()) {+ args.intermediates.push_back(buf);+ }stream.set_arguments(*_kernels.front(), cl_kernel.get()->params, args);}event::ptr execute_impl(const std::vector<event::ptr>& events,- custom_gpu_primitive_inst& instance) override {+ custom_gpu_primitive_inst& instance) override {auto& stream = instance.get_network().get_stream();kernel_arguments_data args;for (auto& dep : instance.dependencies()) {args.inputs.push_back(dep.first->output_memory_ptr());}-for (size_t i = 0; i < instance.outputs_memory_count(); i++) {args.outputs.push_back(instance.output_memory_ptr(i));}-+ for (const auto& buf : instance.get_intermediates_memories()) {+ args.intermediates.push_back(buf);+ }return stream.enqueue_kernel(*_kernels.front(), cl_kernel.get()->params, args, events, instance.is_output());}@@ -118,12 +191,14 @@ struct custom_gpu_primitive_impl : typed_primitive_impl<custom_gpu_primitive> {void save(BinaryOutputBuffer& ob) const override {parent::save(ob);ob << *cl_kernel;+ ob << size_expr_map;}void load(BinaryInputBuffer& ib) override {parent::load(ib);cl_kernel = std::make_shared<kernel_selector::cl_kernel_data>();ib >> *cl_kernel;+ ib >> size_expr_map;}};@@ -136,6 +211,9 @@ static kernel_selector::kernel_argument_element get_arg(custom_gpu_primitive::arcase custom_gpu_primitive::arg_output:ret.t = kernel_selector::kernel_argument_types::OUTPUT;break;+ case custom_gpu_primitive::arg_internal:+ ret.t = kernel_selector::kernel_argument_types::INTERNAL_BUFFER;+ break;default:throw std::runtime_error("Unknown argument type");break;@@ -295,11 +373,18 @@ static std::unique_ptr<primitive_impl> create(const custom_gpu_primitive_node& acl_kernel->params.workGroups.global = gws;cl_kernel->params.workGroups.local = lws;+ std::map<uint32_t, std::string> size_expr_map;for (const auto& p : primitive->kernel_arguments) {cl_kernel->params.arguments.push_back(get_arg(p));+ if (p.type == custom_gpu_primitive::arg_internal) {+ size_expr_map[p.index] = p.size_expr;+ }+ }+ if (!size_expr_map.empty()) {+ return std::make_unique<custom_gpu_primitive_impl>(arg, cl_kernel, size_expr_map);+ } else {+ return std::make_unique<custom_gpu_primitive_impl>(arg, cl_kernel);}-- return std::make_unique<custom_gpu_primitive_impl>(arg, cl_kernel);}namespace detail {diff --git a/src/plugins/intel_gpu/src/plugin/custom_layer.cpp b/src/plugins/intel_gpu/src/plugin/custom_layer.cppindex 4bb14beea12..6613e817569 100644--- a/src/plugins/intel_gpu/src/plugin/custom_layer.cpp+++ b/src/plugins/intel_gpu/src/plugin/custom_layer.cpp@@ -107,6 +107,10 @@ void CustomLayer::ProcessBuffersNode(const pugi::xml_node & node) {kp.type = ParamType::Input;} else if (typeStr.compare("output") == 0) {kp.type = ParamType::Output;+ } else if (typeStr.compare("internal") == 0) {+ kp.type = ParamType::Internal;+ kp.size_expr = get_str_attr(tensorNode, "size", "");+ CheckAndReturnError(kp.size_expr.empty(), "Internal buffer requires a size attribute");} else {CheckAndReturnError(true, "Tensor node has an invalid type: " << typeStr);}diff --git a/src/plugins/intel_gpu/src/plugin/ops/custom.cpp b/src/plugins/intel_gpu/src/plugin/ops/custom.cppindex 6f428ae5cd6..a04b52bf663 100644--- a/src/plugins/intel_gpu/src/plugin/ops/custom.cpp+++ b/src/plugins/intel_gpu/src/plugin/ops/custom.cpp@@ -165,6 +165,13 @@ void CreateCustomOp(ProgramBuilder& p, const std::shared_ptr<ov::Node>& op, CustoutputFormats.push_back(param.format);break;}+ case CustomLayer::ParamType::Internal: {+ kernelParameters.resize(kernelParameters.size() > size_t(param.paramIndex + 1) ? kernelParameters.size() : size_t(param.paramIndex + 1));+ kernelParameters[param.paramIndex].type = cldnn::custom_gpu_primitive::arg_internal;+ kernelParameters[param.paramIndex].index = static_cast<cldnn::custom_gpu_primitive::arg_index>(param.portIndex);+ kernelParameters[param.paramIndex].size_expr = param.size_expr;+ break;+ }default:OPENVINO_THROW("Invalid custom layer param type: ", param.type, " in operation: ", op->get_friendly_name());}diff --git a/src/plugins/intel_gpu/tests/functional/custom_op/custom_op.cpp b/src/plugins/intel_gpu/tests/functional/custom_op/custom_op.cppindex 56dd8f9d174..baae39c2fdd 100644--- a/src/plugins/intel_gpu/tests/functional/custom_op/custom_op.cpp+++ b/src/plugins/intel_gpu/tests/functional/custom_op/custom_op.cpp@@ -92,6 +92,101 @@ TEST(CustomOp, NoRedundantReordersInserted) {ASSERT_STREQ(ops[2]->get_rt_info()[ov::exec_model_info::LAYER_TYPE].as<std::string>().c_str(), "Result");}+class CustomOpIntBuf : public ov::op::Op {+public:+ OPENVINO_OP("CustomOpIntBuf", "gpu_opset"); // must match XML layer name++ CustomOpIntBuf() = default;++ CustomOpIntBuf(const ov::Output<ov::Node>& input) : Op({input}) {+ constructor_validate_and_infer_types();+ }++ void validate_and_infer_types() override {+ set_output_size(1);+ set_output_type(0, get_input_element_type(0), get_input_partial_shape(0));+ }++ std::shared_ptr<ov::Node> clone_with_new_inputs(const ov::OutputVector& inputs) const override {+ return std::make_shared<CustomOpIntBuf>(inputs[0]);+ }++ bool has_evaluate() const override { return true; }++ bool evaluate(ov::TensorVector& outputs, const ov::TensorVector& inputs) const override {+ auto in = inputs[0];+ auto out = outputs[0];+ out.set_shape(in.get_shape());++ // minimal test: copy input to output+ for (size_t i = 0; i < out.get_size(); i++)+ out.data<float>()[i] = in.data<float>()[i];++ return true;+ }+};++static std::shared_ptr<ov::Model> get_simple_model_with_internal_buffer_static() {+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, 2, 3, 4});+ auto op = std::make_shared<CustomOpIntBuf>(param);+ auto result = std::make_shared<ov::op::v0::Result>(op);+ return std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{param}, "model_with_internal_buffer");+}++static std::shared_ptr<ov::Model> get_simple_model_with_internal_buffer_dynamic() {+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{-1, 2, 3, 4});+ auto op = std::make_shared<CustomOpIntBuf>(param);+ auto result = std::make_shared<ov::op::v0::Result>(op);+ return std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{param}, "model_with_internal_buffer");+}++TEST(CustomOpIntBuf, InternalBufferKernelStaticRuns) {+ ov::Core core;++ ov::AnyMap config = { {"CONFIG_FILE", TEST_CUSTOM_OP_CONFIG_PATH} };+ auto model = get_simple_model_with_internal_buffer_static();+ auto compiled_model = core.compile_model(model, ov::test::utils::DEVICE_GPU, config);+ auto infer_request = compiled_model.create_infer_request();++ std::vector<float> input_data(1*2*3*4);+ for (size_t i = 0; i < input_data.size(); i++) input_data[i] = float(i);++ ov::Tensor input_tensor(ov::element::f32, {1,2,3,4}, input_data.data());+ infer_request.set_input_tensor(input_tensor);++ infer_request.infer();++ auto output_tensor = infer_request.get_output_tensor();+ const float* out = output_tensor.data<const float>();++ for (size_t i = 0; i < input_data.size(); i++) {+ ASSERT_NEAR(out[i], input_data[i], 1e-5);+ }+}++TEST(CustomOpIntBuf, InternalBufferKernelDynamicRuns) {+ ov::Core core;++ ov::AnyMap config = { {"CONFIG_FILE", TEST_CUSTOM_OP_CONFIG_PATH} };+ auto model = get_simple_model_with_internal_buffer_dynamic();+ auto compiled_model = core.compile_model(model, ov::test::utils::DEVICE_GPU, config);+ auto infer_request = compiled_model.create_infer_request();++ std::vector<float> input_data(1*2*3*4);+ for (size_t i = 0; i < input_data.size(); i++) input_data[i] = float(i);++ ov::Tensor input_tensor(ov::element::f32, {1,2,3,4}, input_data.data());+ infer_request.set_input_tensor(input_tensor);++ infer_request.infer();++ auto output_tensor = infer_request.get_output_tensor();+ const float* out = output_tensor.data<const float>();++ for (size_t i = 0; i < input_data.size(); i++) {+ ASSERT_NEAR(out[i], input_data[i], 1e-5);+ }+}} // namespace intel_gpu} // namespace test} // namespace ovdiff --git a/src/plugins/intel_gpu/tests/functional/custom_op/custom_op.xml b/src/plugins/intel_gpu/tests/functional/custom_op/custom_op.xmlindex 412aec3b35b..c21f9795328 100644--- a/src/plugins/intel_gpu/tests/functional/custom_op/custom_op.xml+++ b/src/plugins/intel_gpu/tests/functional/custom_op/custom_op.xml@@ -11,3 +11,17 @@<CompilerOptions options="-cl-mad-enable"/><WorkSizes global="B*F*Y*X,1,1"/></CustomLayer>++<CustomLayer name="CustomOpIntBuf" type="SimpleGPU" version="1">+ <Kernel entry="custom_kernel_intr_buffer">+ <Source filename="custom_op_internal_buffer.cl"/>+ </Kernel>+ <Buffers>+ <Tensor arg-index="0" type="input" port-index="0" /> <!-- pts -->+ <Tensor arg-index="1" type="output" port-index="0" format="BFYX"/> <!-- output -->+ <Tensor arg-index="2" type="internal" port-index="0" size="INPUT0_DIMS[0]*INPUT0_DIMS[1]*INPUT0_DIMS[2]*INPUT0_DIMS[3]" format="BFYX"/> <!-- simple fixed size -->+ <!-- need to pass total memory required for allocation -->+ </Buffers>+ <CompilerOptions options="-cl-mad-enable"/>+ <WorkSizes global="B*F*Y*X,1,1"/>+</CustomLayer>diff --git a/src/plugins/intel_gpu/tests/functional/custom_op/custom_op_internal_buffer.cl b/src/plugins/intel_gpu/tests/functional/custom_op/custom_op_internal_buffer.clnew file mode 100644index 00000000000..ac220e5d60e--- /dev/null+++ b/src/plugins/intel_gpu/tests/functional/custom_op/custom_op_internal_buffer.cl@@ -0,0 +1,13 @@+__kernel void custom_kernel_intr_buffer(+ __global const float* input,+ __global float* output,+ __global float* internal_buf+) {+ uint id = get_global_id(0);++ // store intermediate+ internal_buf[id] = input[id];++ // use it later+ output[id] = internal_buf[id];+}