Skip to content

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

[GPU] Fix four CustomLayer defects: reorder id collision, ANY output layout, host-memory allocation, and the _OFFSET jit constant (#37461)

da3dsoul6f81543dcfcf
diff --git a/src/bindings/python/tests/test_runtime/test_custom_layer_gpu.py b/src/bindings/python/tests/test_runtime/test_custom_layer_gpu.py
new file mode 100644
index 00000000000..f243be9ccfe
--- /dev/null
+++ b/src/bindings/python/tests/test_runtime/test_custom_layer_gpu.py
@@ -0,0 +1,172 @@
+# -*- coding: utf-8 -*-
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+import os
+
+import numpy as np
+import pytest
+
+import openvino.opset14 as ops
+from openvino import Core, DiscreteTypeInfo, Model, Op, Shape
+
+gpu_only = pytest.mark.skipif(
+ os.environ.get("TEST_DEVICE") not in ["GPU"],
+ reason="Device dependent test",
+)
+
+
+def make_custom_op_type(type_name):
+ """Build an Op whose type name the GPU plugin resolves against a CustomLayer entry."""
+
+ class CustomLayerOp(Op):
+ class_type_info = DiscreteTypeInfo(type_name, "gpu_opset")
+
+ def __init__(self, inputs=None):
+ super().__init__(self)
+ if inputs is not None:
+ self.set_arguments(inputs)
+ self.constructor_validate_and_infer_types()
+
+ def validate_and_infer_types(self):
+ self.set_output_type(0, self.get_input_element_type(0), self.get_input_partial_shape(0))
+
+ def clone_with_new_inputs(self, new_inputs):
+ return CustomLayerOp(new_inputs)
+
+ def get_type_info(self):
+ return CustomLayerOp.class_type_info
+
+ return CustomLayerOp
+
+
+def write_config(tmp_path, layer_xml, kernels):
+ for name, source in kernels.items():
+ (tmp_path / name).write_text(source)
+ config = tmp_path / "custom_layers.xml"
+ config.write_text(layer_xml)
+ return str(config)
+
+
+AXIS_PROBE_KERNEL = """
+__kernel void axis_probe(__global const INPUT0_TYPE* input, __global OUTPUT0_TYPE* output) {
+ const int x = get_global_id(0);
+ const int y = get_global_id(1);
+ output[y * OUTPUT0_DIMS[3] + x] = (OUTPUT0_TYPE)(y * 1000 + x);
+}
+"""
+
+COPY_KERNEL = """
+__kernel void copy(__global const INPUT0_TYPE* input, __global OUTPUT0_TYPE* output) {
+ const int id = get_global_id(0);
+ output[id] = input[INPUT0_OFFSET + id];
+}
+"""
+
+ADD_KERNEL = """
+__kernel void add(__global const INPUT0_TYPE* a, __global const INPUT1_TYPE* b,
+ __global OUTPUT0_TYPE* output) {
+ const int id = get_global_id(0);
+ output[id] = a[id] + b[id];
+}
+"""
+
+
+@gpu_only
+def test_custom_layer_output_format_any_keeps_axis_order(device, tmp_path):
+ # format="ANY" on an output means "no conversion reorder after me". It must not change
+ # the axis order the op's own WorkSizes resolution, or the rest of the graph, sees.
+ # The shape is non-square and the dispatch is over X and Y separately, so a transposed
+ # layout cannot cancel out.
+ config = write_config(
+ tmp_path,
+ """<CustomLayer name="CustomLayerAnyFmt" type="SimpleGPU" version="1">
+ <Kernel entry="axis_probe">
+ <Source filename="axis_probe.cl"/>
+ </Kernel>
+ <Buffers>
+ <Tensor arg-index="0" type="input" port-index="0"/>
+ <Tensor arg-index="1" type="output" port-index="0" format="ANY"/>
+ </Buffers>
+ <WorkSizes global="X,Y,1"/>
+</CustomLayer>""",
+ {"axis_probe.cl": AXIS_PROBE_KERNEL},
+ )
+
+ shape = [1, 1, 3, 4]
+ param = ops.parameter(Shape(shape), dtype=np.float32, name="data")
+ custom = make_custom_op_type("CustomLayerAnyFmt")([param.output(0)])
+ model = Model([custom.output(0)], [param], "any_fmt")
+
+ compiled = Core().compile_model(model, device, {"CONFIG_FILE": config})
+ result = compiled(np.zeros(shape, dtype=np.float32))[0]
+
+ expected = np.array([[y * 1000 + x for x in range(4)] for y in range(3)], dtype=np.float32)
+ assert np.array_equal(result.reshape(3, 4), expected)
+
+
+@gpu_only
+def test_custom_layer_reads_offset_slice(device, tmp_path):
+ # The custom layer consumes the second half of a Split, i.e. a non-zero-offset view of
+ # its producer. The view is optimized in place, so the kernel is handed the parent
+ # buffer and reaches the cropped data through INPUT0_OFFSET, as the CustomLayer
+ # documentation prescribes.
+ config = write_config(
+ tmp_path,
+ """<CustomLayer name="CustomLayerCopy" type="SimpleGPU" version="1">
+ <Kernel entry="copy">
+ <Source filename="copy.cl"/>
+ </Kernel>
+ <Buffers>
+ <Tensor arg-index="0" type="input" port-index="0"/>
+ <Tensor arg-index="1" type="output" port-index="0"/>
+ </Buffers>
+ <WorkSizes global="B*F*Y*X,1,1"/>
+</CustomLayer>""",
+ {"copy.cl": COPY_KERNEL},
+ )
+
+ shape = [1, 4, 1, 2]
+ param = ops.parameter(Shape(shape), dtype=np.float32, name="data")
+ axis = ops.constant(np.int32(1))
+ upper_half = ops.split(param, axis, 2).output(1)
+ custom = make_custom_op_type("CustomLayerCopy")([upper_half])
+ model = Model([custom.output(0)], [param], "offset_slice")
+
+ data = np.array([0, 1, 10, 11, 20, 21, 30, 31], dtype=np.float32).reshape(shape)
+ compiled = Core().compile_model(model, device, {"CONFIG_FILE": config})
+ result = compiled(data)[0]
+
+ assert np.array_equal(result.reshape(-1), np.array([20, 21, 30, 31], dtype=np.float32))
+
+
+@gpu_only
+def test_custom_layer_same_producer_on_two_ports(device, tmp_path):
+ # Both input ports declare a format, so a pre-reorder is inserted for each. When one
+ # producer feeds both, the two reorders must still get distinct primitive ids.
+ config = write_config(
+ tmp_path,
+ """<CustomLayer name="CustomLayerAdd" type="SimpleGPU" version="1">
+ <Kernel entry="add">
+ <Source filename="add.cl"/>
+ </Kernel>
+ <Buffers>
+ <Tensor arg-index="0" type="input" port-index="0" format="BFYX"/>
+ <Tensor arg-index="1" type="input" port-index="1" format="BFYX"/>
+ <Tensor arg-index="2" type="output" port-index="0" format="BFYX"/>
+ </Buffers>
+ <WorkSizes global="B*F*Y*X,1,1"/>
+</CustomLayer>""",
+ {"add.cl": ADD_KERNEL},
+ )
+
+ shape = [1, 2, 3, 4]
+ param = ops.parameter(Shape(shape), dtype=np.float32, name="data")
+ custom = make_custom_op_type("CustomLayerAdd")([param.output(0), param.output(0)])
+ model = Model([custom.output(0)], [param], "shared_producer")
+
+ data = np.arange(np.prod(shape), dtype=np.float32).reshape(shape)
+ compiled = Core().compile_model(model, device, {"CONFIG_FILE": config})
+ result = compiled(data)[0]
+
+ assert np.array_equal(result, data * 2)
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.cpp
index 58f6710619a..62a9ceca37b 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
@@ -69,6 +69,8 @@ struct custom_gpu_primitive_impl : typed_primitive_impl<custom_gpu_primitive> {
using parent = typed_primitive_impl<custom_gpu_primitive>;
using parent::parent;
+ bool is_cpu() const override { return false; }
+
DECLARE_OBJECT_TYPE_SERIALIZATION(cldnn::ocl::custom_gpu_primitive_impl)
std::shared_ptr<kernel_selector::cl_kernel_data> cl_kernel;
@@ -306,7 +308,7 @@ static void add_layout_to_jit(kernel_selector::jit_constants& mem_consts, const
// #define INPUT0_OFFSET 0
auto offset =
(pitches[0] * l.data_padding._lower_size[0]) + (pitches[1] * l.data_padding._lower_size[1]) +
- (pitches[2] * l.data_padding._lower_size[3]) + (pitches[3] * l.data_padding._lower_size[2]);
+ (pitches[2] * l.data_padding._lower_size[2]) + (pitches[3] * l.data_padding._lower_size[3]);
mem_consts.AddConstant(kernel_selector::MakeJitConstant(name + "_OFFSET", std::to_string(offset)));
}
diff --git a/src/plugins/intel_gpu/src/plugin/ops/custom.cpp b/src/plugins/intel_gpu/src/plugin/ops/custom.cpp
old mode 100644
new mode 100755
index 6449b392576..8ebf54132cb
--- a/src/plugins/intel_gpu/src/plugin/ops/custom.cpp
+++ b/src/plugins/intel_gpu/src/plugin/ops/custom.cpp
@@ -142,9 +142,9 @@ void CreateCustomOp(ProgramBuilder& p, const std::shared_ptr<ov::Node>& op, Cust
// Handle input reorder
if (param.portIndex < static_cast<int>(inputs.size()) && reordered_inputs[param.portIndex].pid.empty()) {
- // todo: add support for multiple reorders of the same input? (read as bfyx for one arg and yxfb for another)
if (param.format != cldnn::format::any) {
- auto reorderPrimName = inputs[param.portIndex].pid + "_" + op->get_friendly_name() + ProgramBuilder::m_preCustomLayerTag;
+ auto reorderPrimName = inputs[param.portIndex].pid + "_" + op->get_friendly_name() +
+ "_" + std::to_string(param.portIndex) + ProgramBuilder::m_preCustomLayerTag;
auto preprocessPrim = cldnn::reorder(
reorderPrimName,
inputs[param.portIndex],
@@ -188,15 +188,16 @@ void CreateCustomOp(ProgramBuilder& p, const std::shared_ptr<ov::Node>& op, Cust
for (size_t i = 0; i < op->get_output_size(); i++) {
auto dims = op->get_output_partial_shape(i);
- constexpr size_t kDynamic = std::numeric_limits<size_t>::max();
- size_t N = (dims.size() > 0) ? dims[0].is_dynamic() ? kDynamic : dims[0].get_length() : 1;
- size_t C = (dims.size() > 1) ? dims[1].is_dynamic() ? kDynamic : dims[1].get_length() : 1;
- size_t H = (dims.size() > 2) ? dims[2].is_dynamic() ? kDynamic : dims[2].get_length() : 1;
- size_t W = (dims.size() > 3) ? dims[3].is_dynamic() ? kDynamic : dims[3].get_length() : 1;
-
- if (dims.is_dynamic()) {
+ // format::any needs the shape-based ctor for the same reason a dynamic shape does:
+ // the tensor ctor stores an `any` layout's sizes in raw internal order at full
+ // internal rank, transposing the WorkSizes resolution and the downstream shape.
+ if (dims.is_dynamic() || outputFormats[i] == cldnn::format::any) {
outputLayouts[i] = cldnn::layout(dims, cldnn::element_type_to_data_type(op->get_output_element_type(i)), outputFormats[i]);
} else {
+ size_t N = (dims.size() > 0) ? dims[0].get_length() : 1;
+ size_t C = (dims.size() > 1) ? dims[1].get_length() : 1;
+ size_t H = (dims.size() > 2) ? dims[2].get_length() : 1;
+ size_t W = (dims.size() > 3) ? dims[3].get_length() : 1;
cldnn::tensor outputTensor = cldnn::tensor(cldnn::batch(N), cldnn::feature(C), cldnn::spatial(W, H));
outputLayouts[i] = cldnn::layout(cldnn::element_type_to_data_type(op->get_output_element_type(i)), outputFormats[i], outputTensor);
}
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.cpp
index baae39c2fdd..777956921a3 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
@@ -187,6 +187,352 @@ TEST(CustomOpIntBuf, InternalBufferKernelDynamicRuns) {
ASSERT_NEAR(out[i], input_data[i], 1e-5);
}
}
+
+// format="ANY" on an output must not change the axis order the op or the graph sees.
+// The shape is non-square in Y and X, WorkSizes dispatches over X and Y separately, and
+// the kernel derives its output from its dispatch coordinates: with a product-form
+// WorkSizes and a flat copy kernel a transposed layout cancels out and the test cannot
+// fail.
+class CustomOpAnyFmt : public ov::op::Op {
+public:
+ OPENVINO_OP("CustomOpAnyFmt", "gpu_opset");
+
+ CustomOpAnyFmt() = default;
+
+ explicit CustomOpAnyFmt(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<CustomOpAnyFmt>(inputs[0]);
+ }
+};
+
+TEST(CustomOpAnyFmt, OutputFormatAnyPreservesAxisOrder) {
+ ov::Core core;
+
+ constexpr size_t kY = 3;
+ constexpr size_t kX = 4;
+ const ov::Shape shape{1, 1, kY, kX};
+
+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape(shape));
+ auto op = std::make_shared<CustomOpAnyFmt>(param);
+ auto result = std::make_shared<ov::op::v0::Result>(op);
+ auto model = std::make_shared<ov::Model>(ov::ResultVector{result},
+ ov::ParameterVector{param},
+ "model_with_any_format_output");
+
+ ov::AnyMap config = {{"CONFIG_FILE", TEST_CUSTOM_OP_CONFIG_PATH}};
+ 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(ov::shape_size(shape), 0.0f);
+ ov::Tensor input_tensor(ov::element::f32, shape, input_data.data());
+ infer_request.set_input_tensor(input_tensor);
+ infer_request.infer();
+
+ auto output_tensor = infer_request.get_output_tensor();
+ ASSERT_EQ(output_tensor.get_shape(), shape);
+
+ const float* out = output_tensor.data<const float>();
+ for (size_t y = 0; y < kY; y++) {
+ for (size_t x = 0; x < kX; x++) {
+ ASSERT_NEAR(out[y * kX + x], static_cast<float>(y * 1000 + x), 1e-5f)
+ << "at y=" << y << " x=" << x;
+ }
+ }
+}
+
+// Same defect on a rank-3 output, which resolves through get_default_format(3) rather
+// than (4).
+class CustomOpAnyFmt3D : public ov::op::Op {
+public:
+ OPENVINO_OP("CustomOpAnyFmt3D", "gpu_opset");
+
+ CustomOpAnyFmt3D() = default;
+
+ explicit CustomOpAnyFmt3D(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<CustomOpAnyFmt3D>(inputs[0]);
+ }
+};
+
+TEST(CustomOpAnyFmt3D, OutputFormatAnyPreservesAxisOrder3D) {
+ ov::Core core;
+
+ constexpr size_t kB = 2;
+ constexpr size_t kF = 3;
+ constexpr size_t kY = 4;
+ const ov::Shape shape{kB, kF, kY};
+
+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape(shape));
+ auto op = std::make_shared<CustomOpAnyFmt3D>(param);
+ auto result = std::make_shared<ov::op::v0::Result>(op);
+ auto model = std::make_shared<ov::Model>(ov::ResultVector{result},
+ ov::ParameterVector{param},
+ "model_with_any_format_3d_output");
+
+ ov::AnyMap config = {{"CONFIG_FILE", TEST_CUSTOM_OP_CONFIG_PATH}};
+ 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(ov::shape_size(shape), 0.0f);
+ ov::Tensor input_tensor(ov::element::f32, shape, input_data.data());
+ infer_request.set_input_tensor(input_tensor);
+ infer_request.infer();
+
+ auto output_tensor = infer_request.get_output_tensor();
+ ASSERT_EQ(output_tensor.get_shape(), shape);
+
+ const float* out = output_tensor.data<const float>();
+ for (size_t b = 0; b < kB; b++) {
+ for (size_t f = 0; f < kF; f++) {
+ for (size_t y = 0; y < kY; y++) {
+ ASSERT_NEAR(out[(b * kF + f) * kY + y],
+ static_cast<float>(b * 100 + f * 10 + y), 1e-5f)
+ << "at b=" << b << " f=" << f << " y=" << y;
+ }
+ }
+ }
+}
+
+// Two input ports fed by the same producer used to build colliding pre-reorder primitive
+// ids and fail to compile. Both ports declare a concrete format so a reorder is inserted
+// for each.
+class CustomOpTwoIn : public ov::op::Op {
+public:
+ OPENVINO_OP("CustomOpTwoIn", "gpu_opset");
+
+ CustomOpTwoIn() = default;
+
+ CustomOpTwoIn(const ov::Output<ov::Node>& a, const ov::Output<ov::Node>& b) : Op({a, b}) {
+ 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<CustomOpTwoIn>(inputs[0], inputs[1]);
+ }
+};
+
+TEST(CustomOpTwoIn, SameProducerOnTwoPortsCompiles) {
+ ov::Core core;
+
+ const ov::Shape shape{1, 2, 3, 4};
+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape(shape));
+ // Both ports deliberately read the same producer tensor.
+ auto op = std::make_shared<CustomOpTwoIn>(param, param);
+ auto result = std::make_shared<ov::op::v0::Result>(op);
+ auto model = std::make_shared<ov::Model>(ov::ResultVector{result},
+ ov::ParameterVector{param},
+ "model_with_shared_producer_on_two_ports");
+
+ ov::AnyMap config = {{"CONFIG_FILE", TEST_CUSTOM_OP_CONFIG_PATH}};
+ ov::CompiledModel compiled_model;
+ OV_ASSERT_NO_THROW(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(ov::shape_size(shape));
+ for (size_t i = 0; i < input_data.size(); i++)
+ input_data[i] = static_cast<float>(i);
+
+ ov::Tensor input_tensor(ov::element::f32, shape, 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] * 2.0f, 1e-5f) << "element " << i;
+ }
+}
+
+
+// format="ANY" on an output means "inherit the first input's format", resolved in
+// custom_gpu_primitive_inst::calc_output_layout. With input port 0 declared
+// YXFB, the kernel writes YXFB-ordered data, so the plugin must treat the output as YXFB
+// and reorder it to BFYX for the Result. If ANY is instead resolved to the default
+// format, the YXFB bytes are read as BFYX and the result is permuted.
+class CustomOpAnyFmtYxfb : public ov::op::Op {
+public:
+ OPENVINO_OP("CustomOpAnyFmtYxfb", "gpu_opset");
+
+ CustomOpAnyFmtYxfb() = default;
+
+ explicit CustomOpAnyFmtYxfb(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<CustomOpAnyFmtYxfb>(inputs[0]);
+ }
+};
+
+TEST(CustomOpAnyFmtYxfb, OutputFormatAnyInheritsFirstInputFormat) {
+ ov::Core core;
+
+ const ov::Shape shape{1, 2, 2, 3};
+ const size_t n = ov::shape_size(shape);
+
+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape(shape));
+ auto op = std::make_shared<CustomOpAnyFmtYxfb>(param);
+ auto result = std::make_shared<ov::op::v0::Result>(op);
+ auto model = std::make_shared<ov::Model>(ov::ResultVector{result},
+ ov::ParameterVector{param},
+ "model_with_any_output_and_yxfb_input");
+
+ ov::AnyMap config = {{"CONFIG_FILE", TEST_CUSTOM_OP_CONFIG_PATH}};
+ 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(n);
+ for (size_t i = 0; i < n; i++)
+ input_data[i] = static_cast<float>(i);
+ ov::Tensor input_tensor(ov::element::f32, shape, input_data.data());
+ infer_request.set_input_tensor(input_tensor);
+ infer_request.infer();
+
+ auto output_tensor = infer_request.get_output_tensor();
+ ASSERT_EQ(output_tensor.get_shape(), shape);
+
+ const float* out = output_tensor.data<const float>();
+
+ for (size_t i = 0; i < n; i++)
+ ASSERT_NEAR(out[i], static_cast<float>(i + 1), 1e-5f) << "at flat index " << i;
+}
+
+
+// Two ports of one custom op read the same producer but ask for different formats. Each
+// port needs its own pre-reorder; the kernel copies port 1 (YXFB) and the output is
+// declared YXFB, so the plugin reorders it back and the result must equal the input.
+class CustomOpTwoInFmt : public ov::op::Op {
+public:
+ OPENVINO_OP("CustomOpTwoInFmt", "gpu_opset");
+
+ CustomOpTwoInFmt() = default;
+
+ CustomOpTwoInFmt(const ov::Output<ov::Node>& a, const ov::Output<ov::Node>& b) : Op({a, b}) {
+ 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<CustomOpTwoInFmt>(inputs[0], inputs[1]);
+ }
+};
+
+TEST(CustomOpTwoInFmt, SameProducerOnTwoPortsWithDifferentFormats) {
+ ov::Core core;
+
+ const ov::Shape shape{1, 2, 2, 3};
+ auto param = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape(shape));
+ auto op = std::make_shared<CustomOpTwoInFmt>(param, param);
+ auto result = std::make_shared<ov::op::v0::Result>(op);
+ auto model = std::make_shared<ov::Model>(ov::ResultVector{result},
+ ov::ParameterVector{param},
+ "model_with_two_formats_on_one_producer");
+
+ ov::AnyMap config = {{"CONFIG_FILE", TEST_CUSTOM_OP_CONFIG_PATH}};
+ ov::CompiledModel compiled_model;
+ OV_ASSERT_NO_THROW(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(ov::shape_size(shape));
+ for (size_t i = 0; i < input_data.size(); i++)
+ input_data[i] = static_cast<float>(i);
+ ov::Tensor input_tensor(ov::element::f32, shape, input_data.data());
+ infer_request.set_input_tensor(input_tensor);
+ infer_request.infer();
+
+ auto output_tensor = infer_request.get_output_tensor();
+ ASSERT_EQ(output_tensor.get_shape(), shape);
+ 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-5f) << "element " << i;
+}
+
+// The ANY sentinel survives into the dynamic path, where the format is resolved per shape
+// in custom_gpu_primitive_inst::calc_output_layouts rather than at graph build time.
+class CustomOpAnyFmtDyn : public ov::op::Op {
+public:
+ OPENVINO_OP("CustomOpAnyFmtDyn", "gpu_opset");
+
+ CustomOpAnyFmtDyn() = default;
+
+ explicit CustomOpAnyFmtDyn(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<CustomOpAnyFmtDyn>(inputs[0]);
+ }
+};
+
+TEST(CustomOpAnyFmtDyn, OutputFormatAnyOnDynamicShape) {
+ ov::Core core;
+
+ auto param = std::make_shared<ov::op::v0::Parameter>(
+ ov::element::f32, ov::PartialShape{1, 2, ov::Dimension::dynamic(), ov::Dimension::dynamic()});
+ auto op = std::make_shared<CustomOpAnyFmtDyn>(param);
+ auto result = std::make_shared<ov::op::v0::Result>(op);
+ auto model = std::make_shared<ov::Model>(ov::ResultVector{result},
+ ov::ParameterVector{param},
+ "model_with_any_format_output_dynamic");
+
+ ov::AnyMap config = {{"CONFIG_FILE", TEST_CUSTOM_OP_CONFIG_PATH}};
+ auto compiled_model = core.compile_model(model, ov::test::utils::DEVICE_GPU, config);
+ auto infer_request = compiled_model.create_infer_request();
+
+ // run twice at different shapes so the layout is re-resolved between inferences
+ for (const ov::Shape& shape : {ov::Shape{1, 2, 3, 4}, ov::Shape{1, 2, 5, 2}}) {
+ std::vector<float> input_data(ov::shape_size(shape));
+ for (size_t i = 0; i < input_data.size(); i++)
+ input_data[i] = static_cast<float>(i);
+
+ ov::Tensor input_tensor(ov::element::f32, shape, input_data.data());
+ infer_request.set_input_tensor(input_tensor);
+ infer_request.infer();
+
+ auto output_tensor = infer_request.get_output_tensor();
+ ASSERT_EQ(output_tensor.get_shape(), shape);
+ 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] + 1.0f, 1e-5f)
+ << "element " << i << " at shape " << shape;
+ }
+}
+
} // namespace intel_gpu
} // namespace test
} // namespace ov
diff --git a/src/plugins/intel_gpu/tests/functional/custom_op/custom_op.xml b/src/plugins/intel_gpu/tests/functional/custom_op/custom_op.xml
index c21f9795328..b70d4e7e152 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
@@ -25,3 +25,79 @@
<CompilerOptions options="-cl-mad-enable"/>
<WorkSizes global="B*F*Y*X,1,1"/>
</CustomLayer>
+
+<CustomLayer name="CustomOpAnyFmt" type="SimpleGPU" version="1">
+ <Kernel entry="custom_kernel_axis_probe">
+ <Source filename="custom_op_any_format.cl"/>
+ </Kernel>
+ <Buffers>
+ <Tensor arg-index="0" type="input" port-index="0"/>
+ <Tensor arg-index="1" type="output" port-index="0" format="ANY"/>
+ </Buffers>
+ <CompilerOptions options="-cl-mad-enable"/>
+ <!-- Over the individual X and Y extents, not their product, so a transposed output
+ layout changes the dispatch instead of cancelling out. -->
+ <WorkSizes global="X,Y,1"/>
+</CustomLayer>
+
+<CustomLayer name="CustomOpAnyFmt3D" type="SimpleGPU" version="1">
+ <Kernel entry="custom_kernel_axis_probe_3d">
+ <Source filename="custom_op_any_format_3d.cl"/>
+ </Kernel>
+ <Buffers>
+ <Tensor arg-index="0" type="input" port-index="0"/>
+ <Tensor arg-index="1" type="output" port-index="0" format="ANY"/>
+ </Buffers>
+ <CompilerOptions options="-cl-mad-enable"/>
+ <WorkSizes global="Y,F,B"/>
+</CustomLayer>
+
+<CustomLayer name="CustomOpTwoIn" type="SimpleGPU" version="1">
+ <Kernel entry="custom_kernel_two_inputs">
+ <Source filename="custom_op_two_inputs.cl"/>
+ </Kernel>
+ <Buffers>
+ <Tensor arg-index="0" type="input" port-index="0" format="BFYX"/>
+ <Tensor arg-index="1" type="input" port-index="1" format="BFYX"/>
+ <Tensor arg-index="2" type="output" port-index="0" format="BFYX"/>
+ </Buffers>
+ <CompilerOptions options="-cl-mad-enable"/>
+ <WorkSizes global="B*F*Y*X,1,1"/>
+</CustomLayer>
+
+<CustomLayer name="CustomOpAnyFmtYxfb" type="SimpleGPU" version="1">
+ <Kernel entry="custom_kernel_yxfb_copy">
+ <Source filename="custom_op_any_format_yxfb.cl"/>
+ </Kernel>
+ <Buffers>
+ <Tensor arg-index="0" type="input" port-index="0" format="YXFB"/>
+ <Tensor arg-index="1" type="output" port-index="0" format="ANY"/>
+ </Buffers>
+ <CompilerOptions options="-cl-mad-enable"/>
+ <WorkSizes global="B*F*Y*X,1,1"/>
+</CustomLayer>
+
+<CustomLayer name="CustomOpTwoInFmt" type="SimpleGPU" version="1">
+ <Kernel entry="custom_kernel_second_port_copy">
+ <Source filename="custom_op_two_inputs_fmt.cl"/>
+ </Kernel>
+ <Buffers>
+ <Tensor arg-index="0" type="input" port-index="0" format="BFYX"/>
+ <Tensor arg-index="1" type="input" port-index="1" format="YXFB"/>
+ <Tensor arg-index="2" type="output" port-index="0" format="YXFB"/>
+ </Buffers>
+ <CompilerOptions options="-cl-mad-enable"/>
+ <WorkSizes global="B*F*Y*X,1,1"/>
+</CustomLayer>
+
+<CustomLayer name="CustomOpAnyFmtDyn" type="SimpleGPU" version="1">
+ <Kernel entry="custom_kernel_dyn_copy">
+ <Source filename="custom_op_any_format_dyn.cl"/>
+ </Kernel>
+ <Buffers>
+ <Tensor arg-index="0" type="input" port-index="0"/>
+ <Tensor arg-index="1" type="output" port-index="0" format="ANY"/>
+ </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_any_format.cl b/src/plugins/intel_gpu/tests/functional/custom_op/custom_op_any_format.cl
new file mode 100644
index 00000000000..3ecc26b9a5e
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/functional/custom_op/custom_op_any_format.cl
@@ -0,0 +1,10 @@
+// Derives its output from its dispatch coordinates and the declared output width; a flat
+// copy would map element i to element i whatever the layout.
+__kernel void custom_kernel_axis_probe(__global const INPUT0_TYPE* input,
+ __global OUTPUT0_TYPE* output) {
+ const int x = get_global_id(0);
+ const int y = get_global_id(1);
+ const int w = OUTPUT0_DIMS[3];
+
+ output[y * w + x] = (OUTPUT0_TYPE)(y * 1000 + x);
+}
diff --git a/src/plugins/intel_gpu/tests/functional/custom_op/custom_op_any_format_3d.cl b/src/plugins/intel_gpu/tests/functional/custom_op/custom_op_any_format_3d.cl
new file mode 100644
index 00000000000..9e863ebdeb4
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/functional/custom_op/custom_op_any_format_3d.cl
@@ -0,0 +1,12 @@
+// Rank-3 companion to custom_op_any_format.cl.
+__kernel void custom_kernel_axis_probe_3d(__global const INPUT0_TYPE* input,
+ __global OUTPUT0_TYPE* output) {
+ const int y = get_global_id(0);
+ const int f = get_global_id(1);
+ const int b = get_global_id(2);
+
+ const int fnum = OUTPUT0_DIMS[1];
+ const int ynum = OUTPUT0_DIMS[2];
+
+ output[(b * fnum + f) * ynum + y] = (OUTPUT0_TYPE)(b * 100 + f * 10 + y);
+}
diff --git a/src/plugins/intel_gpu/tests/functional/custom_op/custom_op_any_format_dyn.cl b/src/plugins/intel_gpu/tests/functional/custom_op/custom_op_any_format_dyn.cl
new file mode 100644
index 00000000000..62be6333f94
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/functional/custom_op/custom_op_any_format_dyn.cl
@@ -0,0 +1,6 @@
+// Flat copy for the dynamic-shape ANY-output case.
+__kernel void custom_kernel_dyn_copy(__global const INPUT0_TYPE* input,
+ __global OUTPUT0_TYPE* output) {
+ const int i = get_global_id(0);
+ output[i] = input[i] + (OUTPUT0_TYPE)1;
+}
diff --git a/src/plugins/intel_gpu/tests/functional/custom_op/custom_op_any_format_yxfb.cl b/src/plugins/intel_gpu/tests/functional/custom_op/custom_op_any_format_yxfb.cl
new file mode 100644
index 00000000000..c3b2b6e40ee
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/functional/custom_op/custom_op_any_format_yxfb.cl
@@ -0,0 +1,9 @@
+// Flat elementwise copy. The XML declares input port 0 as YXFB, so the
+// plugin reorders the input to YXFB and this kernel therefore writes YXFB-ordered data.
+// The output is declared ANY, which historically means "inherit the first input's
+// format" -- i.e. YXFB -- so the plugin must reorder YXFB->BFYX for the Result.
+__kernel void custom_kernel_yxfb_copy(__global const INPUT0_TYPE* input,
+ __global OUTPUT0_TYPE* output) {
+ const int i = get_global_id(0);
+ output[i] = input[i] + (OUTPUT0_TYPE)1;
+}
diff --git a/src/plugins/intel_gpu/tests/functional/custom_op/custom_op_two_inputs.cl b/src/plugins/intel_gpu/tests/functional/custom_op/custom_op_two_inputs.cl
new file mode 100644
index 00000000000..344101af90d
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/functional/custom_op/custom_op_two_inputs.cl
@@ -0,0 +1,7 @@
+__kernel void custom_kernel_two_inputs(__global const INPUT0_TYPE* a,
+ __global const INPUT1_TYPE* b,
+ __global OUTPUT0_TYPE* output) {
+ const uint id = get_global_id(0);
+
+ output[id] = a[id] + b[id];
+}
diff --git a/src/plugins/intel_gpu/tests/functional/custom_op/custom_op_two_inputs_fmt.cl b/src/plugins/intel_gpu/tests/functional/custom_op/custom_op_two_inputs_fmt.cl
new file mode 100644
index 00000000000..20d0a7d637f
--- /dev/null
+++ b/src/plugins/intel_gpu/tests/functional/custom_op/custom_op_two_inputs_fmt.cl
@@ -0,0 +1,9 @@
+// Copies port 1 only. Port 0 is declared BFYX and port 1 YXFB while both read the same
+// producer, so the two ports must get their own pre-reorders; if port 1 reused port 0's
+// BFYX reorder the copy would come out permuted.
+__kernel void custom_kernel_second_port_copy(__global const INPUT0_TYPE* input0,
+ __global const INPUT1_TYPE* input1,
+ __global OUTPUT0_TYPE* output) {
+ const int i = get_global_id(0);
+ output[i] = input1[i];
+}
diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/custom_gpu_primitive_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/custom_gpu_primitive_test.cpp
index 2035db9c4f8..db31fdfcf79 100644
--- a/src/plugins/intel_gpu/tests/unit/test_cases/custom_gpu_primitive_test.cpp
+++ b/src/plugins/intel_gpu/tests/unit/test_cases/custom_gpu_primitive_test.cpp
@@ -2,12 +2,16 @@
// SPDX-License-Identifier: Apache-2.0
//
+#include "graph/include/primitive_inst.h"
#include "test_utils.h"
#include <intel_gpu/primitives/input_layout.hpp>
#include <intel_gpu/primitives/eltwise.hpp>
#include <intel_gpu/primitives/reorder.hpp>
#include <intel_gpu/primitives/custom_gpu_primitive.hpp>
+#include <intel_gpu/primitives/crop.hpp>
+#include <intel_gpu/primitives/concatenation.hpp>
+#include <intel_gpu/primitives/activation.hpp>
using namespace cldnn;
using namespace ::tests;
@@ -212,6 +216,56 @@ void add_basic_in2x2x2x2_with_reorder()
}
}
+// custom_gpu_primitive_impl enqueues an OpenCL kernel, so it must not report itself as a
+// CPU impl: that places its own output, and every producer feeding it, in usm_host.
+TEST(custom_gpu_primitive_f32, impl_is_not_cpu_and_producer_stays_in_device_memory) {
+ auto& engine = get_test_engine();
+
+ auto input = engine.allocate_memory({ data_types::f32, format::bfyx, { 1, 1, 4, 4 } });
+
+ std::string kernel_code =
+ R"__krnl(
+ __kernel void copy_kernel(const __global float* input0, __global float* output)
+ {
+ const unsigned idx = get_global_id(0);
+ output[idx] = input0[idx];
+ }
+ )__krnl";
+ std::vector<custom_gpu_primitive::arg_desc> parameters = {
+ { custom_gpu_primitive::arg_input, 0 },
+ { custom_gpu_primitive::arg_output, 0 } };
+ layout output_layout = { data_types::f32, format::bfyx, { 1, 1, 4, 4 } };
+
+ topology topology;
+ topology.add(input_layout("input", input->get_layout()));
+ topology.add(eltwise("producer", { input_info("input"), input_info("input") }, eltwise_mode::sum));
+ topology.add(custom_gpu_primitive(
+ "user_kernel",
+ { input_info("producer") },
+ { kernel_code },
+ "copy_kernel",
+ parameters,
+ "-cl-mad-enable",
+ { output_layout },
+ { output_layout.count() }));
+
+ network network(engine, topology, get_test_default_config(engine));
+ network.set_input_data("input", input);
+ network.execute();
+
+ auto custom_inst = network.get_primitive("user_kernel");
+ ASSERT_NE(custom_inst->get_impl(), nullptr);
+ EXPECT_FALSE(custom_inst->get_impl()->is_cpu());
+ EXPECT_FALSE(custom_inst->get_impl()->requires_lockable_input());
+
+ if (engine.supports_allocation(allocation_type::usm_device)) {
+ auto producer_inst = network.get_primitive("producer");
+ ASSERT_NE(producer_inst->output_memory_ptr(), nullptr);
+ EXPECT_NE(producer_inst->output_memory_ptr()->get_allocation_type(),
+ allocation_type::usm_host);
+ }
+}
+
TEST(custom_gpu_primitive_int32, add_basic_in2x2x2x2) {
add_basic_in2x2x2x2_with_reorder<data_types::i32>();
}
@@ -579,3 +633,303 @@ TEST(custom_gpu_primitive_u8, add_basic_in2x2x2x2) {
TEST(export_import_custom_gpu_primitive_u8, add_basic_in2x2x2x2) {
test_custom_gpu_primitive_u8_add_basic_in2x2x2x2<unsigned char>(true);
}
+
+
+// INPUT0_OFFSET is documented as "the number of elements from the start of the tensor to
+// the first valid element, bypassing the lower padding", with the padding and pitch arrays
+// always ordered as BFYX. Logical b1 f1 y4 x3 with lower padding y=1 x=2 is padded to
+// y5 x5, giving pitches {25,25,5,1} and an offset of 5*1 + 1*2 = 7. Indexing the padding
+// array in the wrong axis order yields 11 instead.
+TEST(custom_gpu_primitive_f32, input_offset_matches_spatial_lower_padding) {
+ auto& engine = get_test_engine();
+
+ auto in_layout = layout{ data_types::f32, format::bfyx, tensor{ 1, 1, 3, 4 },
+ padding({0, 0, 1, 2}, {0, 0, 0, 0}) };
+ auto input = engine.allocate_memory(in_layout);
+
+ std::vector<float> vals(in_layout.get_linear_size());
+ for (size_t i = 0; i < vals.size(); i++)
+ vals[i] = static_cast<float>(i);
+ set_values(input, vals);
+
+ std::string kernel_code =
+ R"__krnl(
+ __kernel void probe_kernel(const __global float* input0, __global float* output)
+ {
+ output[0] = (float)(INPUT0_OFFSET);
+ output[1] = input0[INPUT0_OFFSET];
+ }
+ )__krnl";
+ std::vector<custom_gpu_primitive::arg_desc> parameters = {
+ { custom_gpu_primitive::arg_input, 0 },
+ { custom_gpu_primitive::arg_output, 0 } };
+ layout output_layout = { data_types::f32, format::bfyx, { 1, 1, 2, 1 } };
+
+ topology topology;
+ topology.add(input_layout("input", in_layout));
+ topology.add(custom_gpu_primitive("user_kernel", { input_info("input") }, { kernel_code },
+ "probe_kernel", parameters, "-cl-mad-enable", { output_layout }, { 1 }));
+
+ network network(engine, topology, get_test_default_config(engine));
+ network.set_input_data("input", input);
+ auto outputs = network.execute();
+
+ auto output = outputs.at("user_kernel").get_memory();
+ cldnn::mem_lock<float, mem_lock_type::read> ptr(output, get_test_stream());
+ ASSERT_EQ(ptr[0], 7.f) << "INPUT0_OFFSET does not match the lower padding";
+ ASSERT_EQ(ptr[1], 7.f) << "a kernel honouring INPUT0_OFFSET read the wrong element";
+}
+
+// An in-place crop keeps the parent buffer and expresses the crop as padding on the view.
+// A kernel that honours INPUT0_OFFSET must therefore still read the cropped data, and the
+// crop must remain optimized out. Feature axis first.
+TEST(custom_gpu_primitive_f32, conforming_kernel_reads_in_place_crop_on_feature_axis) {
+ auto& engine = get_test_engine();
+
+ auto input = engine.allocate_memory({ data_types::f32, format::bfyx, { 1, 4, 1, 2 } });
+ set_values(input, { 0.f, 1.f, 10.f, 11.f, 20.f, 21.f, 30.f, 31.f });
+
+ std::string kernel_code =
+ R"__krnl(
+ __kernel void copy_kernel(const __global float* input0, __global float* output)
+ {
+ const unsigned idx = get_global_id(0);
+ output[idx] = input0[INPUT0_OFFSET + idx];
+ }
+ )__krnl";
+ std::vector<custom_gpu_primitive::arg_desc> parameters = {
+ { custom_gpu_primitive::arg_input, 0 },
+ { custom_gpu_primitive::arg_output, 0 } };
+ layout output_layout = { data_types::f32, format::bfyx, { 1, 2, 1, 2 } };
+
+ topology topology;
+ topology.add(input_layout("input", input->get_layout()));
+ // features [2, 4) of the parent tensor
+ topology.add(crop("crop", input_info("input"), tensor(1, 2, 1, 2), tensor(0, 2, 0, 0)));
+ topology.add(custom_gpu_primitive("user_kernel", { input_info("crop") }, { kernel_code },
+ "copy_kernel", parameters, "-cl-mad-enable", { output_layout }, { output_layout.count() }));
+
+ ExecutionConfig config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::optimize_data(true));
+
+ network network(engine, topology, config);
+ network.set_input_data("input", input);
+ auto outputs = network.execute();
+
+ EXPECT_TRUE(network.get_primitive("crop")->can_be_optimized())
+ << "a custom layer input should not block in-place cropping";
+
+ auto output = outputs.at("user_kernel").get_memory();
+ cldnn::mem_lock<float, mem_lock_type::read> output_ptr(output, get_test_stream());
+ std::vector<float> expected = { 20.f, 21.f, 30.f, 31.f };
+ for (size_t i = 0; i < expected.size(); i++)
+ ASSERT_EQ(output_ptr[i], expected[i]) << "element " << i;
+}
+
+// The same on a spatial axis, where the offset covers a non-zero Y padding and so depends
+// on the padding array being read in the documented BFYX order.
+TEST(custom_gpu_primitive_f32, conforming_kernel_reads_in_place_crop_on_spatial_axis) {
+ auto& engine = get_test_engine();
+
+ auto input = engine.allocate_memory({ data_types::f32, format::bfyx, tensor{ 1, 1, 3, 4 } });
+ std::vector<float> vals(12);
+ for (size_t i = 0; i < vals.size(); i++)
+ vals[i] = static_cast<float>(i);
+ set_values(input, vals);
+
+ std::string kernel_code =
+ R"__krnl(
+ __kernel void copy_kernel(const __global float* input0, __global float* output)
+ {
+ const unsigned idx = get_global_id(0);
+ output[idx] = input0[INPUT0_OFFSET + idx];
+ }
+ )__krnl";
+ std::vector<custom_gpu_primitive::arg_desc> parameters = {
+ { custom_gpu_primitive::arg_input, 0 },
+ { custom_gpu_primitive::arg_output, 0 } };
+ layout output_layout = { data_types::f32, format::bfyx, tensor{ 1, 1, 3, 3 } };
+
+ topology topology;
+ topology.add(input_layout("input", input->get_layout()));
+ // rows [1, 4) of the parent tensor
+ topology.add(crop("crop", input_info("input"), tensor(1, 1, 3, 3), tensor(0, 0, 0, 1)));
+ topology.add(custom_gpu_primitive("user_kernel", { input_info("crop") }, { kernel_code },
+ "copy_kernel", parameters, "-cl-mad-enable", { output_layout }, { output_layout.count() }));
+
+ ExecutionConfig config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::optimize_data(true));
+
+ network network(engine, topology, config);
+ network.set_input_data("input", input);
+ auto outputs = network.execute();
+
+ EXPECT_TRUE(network.get_primitive("crop")->can_be_optimized())
+ << "a custom layer input should not block in-place cropping";
+
+ auto output = outputs.at("user_kernel").get_memory();
+ cldnn::mem_lock<float, mem_lock_type::read> output_ptr(output, get_test_stream());
+ for (size_t i = 0; i < 9; i++)
+ ASSERT_EQ(output_ptr[i], static_cast<float>(i + 3)) << "element " << i;
+}
+
+// An in-place concatenation writes offset padding onto its predecessors output layouts,
+// which a kernel would have to honour through OUTPUT0_OFFSET. custom_gpu_primitive is not
+// listed in available_pred, so that does not happen today; this pins the current behaviour.
+TEST(custom_gpu_primitive_f32, custom_layer_producer_blocks_in_place_concat) {
+ auto& engine = get_test_engine();
+
+ auto input = engine.allocate_memory({ data_types::f32, format::bfyx, { 1, 2, 1, 2 } });
+ set_values(input, { 0.f, 1.f, 10.f, 11.f });
+
+ std::string kernel_code =
+ R"__krnl(
+ __kernel void add_kernel(const __global float* input0, __global float* output)
+ {
+ const unsigned idx = get_global_id(0);
+ output[idx] = input0[idx] + ADDEND;
+ }
+ )__krnl";
+ std::vector<custom_gpu_primitive::arg_desc> parameters = {
+ { custom_gpu_primitive::arg_input, 0 },
+ { custom_gpu_primitive::arg_output, 0 } };
+ layout output_layout = { data_types::f32, format::bfyx, { 1, 2, 1, 2 } };
+
+ topology topology;
+ topology.add(input_layout("input", input->get_layout()));
+ topology.add(custom_gpu_primitive("k1", { input_info("input") }, { kernel_code },
+ "add_kernel", parameters, "-cl-mad-enable -DADDEND=100.0f", { output_layout }, { output_layout.count() }));
+ topology.add(custom_gpu_primitive("k2", { input_info("input") }, { kernel_code },
+ "add_kernel", parameters, "-cl-mad-enable -DADDEND=200.0f", { output_layout }, { output_layout.count() }));
+ topology.add(concatenation("concat", { input_info("k1"), input_info("k2") }, 1));
+ // the concat must not be the network output, or it is excluded from fusing for that
+ // reason alone and the test would pass without exercising anything
+ topology.add(activation("act", input_info("concat"), activation_func::abs));
+
+ ExecutionConfig config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::optimize_data(true));
+
+ network network(engine, topology, config);
+ network.set_input_data("input", input);
+ auto outputs = network.execute();
+
+ EXPECT_FALSE(network.get_primitive("concat")->can_be_optimized());
+
+ auto output = outputs.at("act").get_memory();
+ cldnn::mem_lock<float, mem_lock_type::read> output_ptr(output, get_test_stream());
+ std::vector<float> expected = { 100.f, 101.f, 110.f, 111.f, 200.f, 201.f, 210.f, 211.f };
+ for (size_t i = 0; i < expected.size(); i++)
+ ASSERT_EQ(output_ptr[i], expected[i]) << "element " << i;
+}
+
+// Batch axis, completing the b/f/y/x coverage of the INPUT0_OFFSET terms.
+TEST(custom_gpu_primitive_f32, conforming_kernel_reads_in_place_crop_on_batch_axis) {
+ auto& engine = get_test_engine();
+
+ auto input = engine.allocate_memory({ data_types::f32, format::bfyx, { 4, 1, 2, 1 } });
+ set_values(input, { 0.f, 1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f });
+
+ std::string kernel_code =
+ R"__krnl(
+ __kernel void copy_kernel(const __global float* input0, __global float* output)
+ {
+ const unsigned idx = get_global_id(0);
+ output[idx] = input0[INPUT0_OFFSET + idx];
+ }
+ )__krnl";
+ std::vector<custom_gpu_primitive::arg_desc> parameters = {
+ { custom_gpu_primitive::arg_input, 0 },
+ { custom_gpu_primitive::arg_output, 0 } };
+ layout output_layout = { data_types::f32, format::bfyx, { 2, 1, 2, 1 } };
+
+ topology topology;
+ topology.add(input_layout("input", input->get_layout()));
+ // batches [2, 4) of the parent tensor
+ topology.add(crop("crop", input_info("input"), tensor(2, 1, 2, 1), tensor(2, 0, 0, 0)));
+ topology.add(custom_gpu_primitive("user_kernel", { input_info("crop") }, { kernel_code },
+ "copy_kernel", parameters, "-cl-mad-enable", { output_layout }, { output_layout.count() }));
+
+ ExecutionConfig config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::optimize_data(true));
+
+ network network(engine, topology, config);
+ network.set_input_data("input", input);
+ auto outputs = network.execute();
+
+ EXPECT_TRUE(network.get_primitive("crop")->can_be_optimized())
+ << "a custom layer input should not block in-place cropping";
+
+ auto output = outputs.at("user_kernel").get_memory();
+ cldnn::mem_lock<float, mem_lock_type::read> output_ptr(output, get_test_stream());
+ std::vector<float> expected = { 4.f, 5.f, 6.f, 7.f };
+ for (size_t i = 0; i < expected.size(); i++)
+ ASSERT_EQ(output_ptr[i], expected[i]) << "element " << i;
+}
+
+// A feature crop with batch > 1 leaves the cropped region NON-CONTIGUOUS: each batch slice
+// starts at a different offset into the parent. Adding INPUT0_OFFSET to a flat index is not
+// enough here, so this uses the full pitch-based addressing the CustomLayer documentation
+// prescribes, on both the input and the output. This is the case that decides whether the
+// emitted macros are actually sufficient to consume an in-place view.
+TEST(custom_gpu_primitive_f32, documented_pitch_indexing_reads_non_contiguous_in_place_crop) {
+ auto& engine = get_test_engine();
+
+ // b2 f4 y1 x2, value == linear bfyx index
+ auto input = engine.allocate_memory({ data_types::f32, format::bfyx, { 2, 4, 2, 1 } });
+ std::vector<float> vals(16);
+ for (size_t i = 0; i < vals.size(); i++)
+ vals[i] = static_cast<float>(i);
+ set_values(input, vals);
+
+ std::string kernel_code =
+ R"__krnl(
+ __kernel void copy_kernel(const __global float* input0, __global float* output)
+ {
+ const unsigned idx = get_global_id(0);
+ const unsigned x_size = OUTPUT0_DIMS[3];
+ const unsigned y_size = OUTPUT0_DIMS[2];
+ const unsigned f_size = OUTPUT0_DIMS[1];
+
+ const unsigned x = idx % x_size;
+ const unsigned y = (idx / x_size) % y_size;
+ const unsigned f = (idx / (x_size * y_size)) % f_size;
+ const unsigned b = idx / (x_size * y_size * f_size);
+
+ const unsigned in_id = b * INPUT0_PITCHES[0] + f * INPUT0_PITCHES[1] +
+ y * INPUT0_PITCHES[2] + x * INPUT0_PITCHES[3] +
+ INPUT0_OFFSET;
+ const unsigned out_id = b * OUTPUT0_PITCHES[0] + f * OUTPUT0_PITCHES[1] +
+ y * OUTPUT0_PITCHES[2] + x * OUTPUT0_PITCHES[3] +
+ OUTPUT0_OFFSET;
+ output[out_id] = input0[in_id];
+ }
+ )__krnl";
+ std::vector<custom_gpu_primitive::arg_desc> parameters = {
+ { custom_gpu_primitive::arg_input, 0 },
+ { custom_gpu_primitive::arg_output, 0 } };
+ layout output_layout = { data_types::f32, format::bfyx, { 2, 2, 2, 1 } };
+
+ topology topology;
+ topology.add(input_layout("input", input->get_layout()));
+ // features [2, 4) of both batches
+ topology.add(crop("crop", input_info("input"), tensor(2, 2, 2, 1), tensor(0, 2, 0, 0)));
+ topology.add(custom_gpu_primitive("user_kernel", { input_info("crop") }, { kernel_code },
+ "copy_kernel", parameters, "-cl-mad-enable", { output_layout }, { output_layout.count() }));
+
+ ExecutionConfig config = get_test_default_config(engine);
+ config.set_property(ov::intel_gpu::optimize_data(true));
+
+ network network(engine, topology, config);
+ network.set_input_data("input", input);
+ auto outputs = network.execute();
+
+ EXPECT_TRUE(network.get_primitive("crop")->can_be_optimized())
+ << "a custom layer input should not block in-place cropping";
+
+ auto output = outputs.at("user_kernel").get_memory();
+ cldnn::mem_lock<float, mem_lock_type::read> output_ptr(output, get_test_stream());
+ // b0 -> features 2,3 == parent 4,5,6,7 ; b1 -> parent 12,13,14,15
+ std::vector<float> expected = { 4.f, 5.f, 6.f, 7.f, 12.f, 13.f, 14.f, 15.f };
+ for (size_t i = 0; i < expected.size(); i++)
+ ASSERT_EQ(output_ptr[i], expected[i]) << "element " << i;
+}