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] Broadcast optimization (#36343)
Andrei Fedorov8e80723918da
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl/broadcast.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl/broadcast.cppindex 97e7b45f221..b9d2abb91bc 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl/broadcast.cpp+++ b/src/plugins/intel_gpu/src/graph/impls/ocl/broadcast.cpp@@ -36,6 +36,8 @@ struct broadcast_impl : typed_primitive_impl_ocl<broadcast> {const auto& primitive = impl_param.typed_desc<broadcast>();auto params = get_default_params<kernel_selector::broadcast_params>(impl_param, is_shape_agnostic);+ params.is_explicit_mode = !primitive->axes_mapping.empty();+const auto format = impl_param.get_output_layout().format;size_t max_axes_num = format.dimension();diff --git a/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/broadcast_gpu_opt.cl b/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/broadcast_gpu_opt.clnew file mode 100644index 00000000000..455512dba12--- /dev/null+++ b/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/broadcast_gpu_opt.cl@@ -0,0 +1,151 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "include/fetch_utils.cl"+#include "include/batch_headers/sub_group_block_write.cl"++// Optimized broadcast kernel: each work-group processes one output row (X dimension),+// loading from input and writing to output. Outer dimensions (B, F, W, Z, Y) are+// broadcast via modulo. Per-row address computation (in_row_base, out_row_base)+// replaces ref kernel's per-element get_idx_pos().+//+// This kernel does a pure value-broadcast with no per-element type cast, so it reads+// and writes the same scalar type — only data size matters (any 1/2/4/8-byte type).+// Broadcast-with-convert (input dtype != output dtype) is a distinct case handled by+// the ref kernel via TO_OUTPUT_TYPE; the opt kernel declines it (see Validate()).++#if X_BROADCAST_BLOCK_WRITE+__attribute__((reqd_work_group_size(16, 1, 1)))+__attribute__((intel_reqd_sub_group_size(16)))+#endif+KERNEL(broadcast_gpu_opt)(+ OPTIONAL_SHAPE_INFO_ARG+ const __global INPUT0_TYPE* input,+ __global OUTPUT_TYPE* output+)+{+ const uint row_id = get_global_id(1);+ const uint lid = get_global_id(0);++ // Decode row_id into (b, f, w, z, y) output coordinates+#if OUTPUT_DIMS == 6+ const uint out_y = row_id % OUTPUT_SIZE_Y;+ const uint out_z = (row_id / OUTPUT_SIZE_Y) % OUTPUT_SIZE_Z;+ const uint out_w = (row_id / OUTPUT_SIZE_Y / OUTPUT_SIZE_Z) % OUTPUT_SIZE_W;+ const uint out_f = (row_id / OUTPUT_SIZE_Y / OUTPUT_SIZE_Z / OUTPUT_SIZE_W) % OUTPUT_FEATURE_NUM;+ const uint out_b = row_id / OUTPUT_SIZE_Y / OUTPUT_SIZE_Z / OUTPUT_SIZE_W / OUTPUT_FEATURE_NUM;+#elif OUTPUT_DIMS == 5+ const uint out_y = row_id % OUTPUT_SIZE_Y;+ const uint out_z = (row_id / OUTPUT_SIZE_Y) % OUTPUT_SIZE_Z;+ const uint out_f = (row_id / OUTPUT_SIZE_Y / OUTPUT_SIZE_Z) % OUTPUT_FEATURE_NUM;+ const uint out_b = row_id / OUTPUT_SIZE_Y / OUTPUT_SIZE_Z / OUTPUT_FEATURE_NUM;+ const uint out_w = 0;+#else+ const uint out_y = row_id % OUTPUT_SIZE_Y;+ const uint out_f = (row_id / OUTPUT_SIZE_Y) % OUTPUT_FEATURE_NUM;+ const uint out_b = row_id / OUTPUT_SIZE_Y / OUTPUT_FEATURE_NUM;+ const uint out_z = 0;+ const uint out_w = 0;+#endif++ // Compute input row coordinates (broadcast via modulo for outer dims only)+ const uint in_b = out_b % INPUT0_BATCH_NUM;+ const uint in_f = out_f % INPUT0_FEATURE_NUM;+#if OUTPUT_DIMS >= 5+ const uint in_z = out_z % INPUT0_SIZE_Z;+#else+ const uint in_z = 0;+#endif+#if OUTPUT_DIMS >= 6+ const uint in_w = out_w % INPUT0_SIZE_W;+#else+ const uint in_w = 0;+#endif+ const uint in_y = out_y % INPUT0_SIZE_Y;++ // Base addresses for this row (computed once per row, not per element)+#if OUTPUT_DIMS == 6+ const uint out_row_base = OUTPUT_GET_INDEX(out_b, out_f, out_w, out_z, out_y, 0);+ const uint in_row_base = INPUT0_GET_INDEX(in_b, in_f, in_w, in_z, in_y, 0);+#elif OUTPUT_DIMS == 5+ const uint out_row_base = OUTPUT_GET_INDEX(out_b, out_f, out_z, out_y, 0);+ const uint in_row_base = INPUT0_GET_INDEX(in_b, in_f, in_z, in_y, 0);+#else+ const uint out_row_base = OUTPUT_GET_INDEX(out_b, out_f, out_y, 0);+ const uint in_row_base = INPUT0_GET_INDEX(in_b, in_f, in_y, 0);+#endif++ // Process this row's X dimension; the specific path is selected by the JIT flags below.+ const uint total_wis = get_global_size(0);+ const uint vec_size = OPT_VEC_SIZE;++#if IS_X_BROADCAST+ // X-broadcast: read one scalar, fill consecutive output positions per work-item.+ const OUTPUT_TYPE scalar_val = input[in_row_base];+#if X_BROADCAST_BLOCK_WRITE+ // Subgroup block-write path: the sub-group is pinned to width 16 via+ // intel_reqd_sub_group_size(16) above, so block_write8 (8 elems/lane) emits+ // 128 elements per collective call. Requires OUTPUT_SIZE_X >= 128.+ // For X % 128 != 0, a scalar tail handles the remainder (its stride uses the+ // actual sub-group size). For static X % 128 == 0 the tail compiles away. For+ // dynamic this is a uniform branch (no divergence).+ MAKE_VECTOR_TYPE(OUTPUT_TYPE, 8) out_vec8 = (MAKE_VECTOR_TYPE(OUTPUT_TYPE, 8))(scalar_val);+ const uint x_aligned_end = (OUTPUT_SIZE_X / 128) * 128;+ for (uint x_start = 0; x_start < x_aligned_end; x_start += 128) {+ DT_OUTPUT_BLOCK_WRITE8(output, out_row_base + x_start, out_vec8);+ }+ // Tail: scalar fill, each lane writes one element with stride = sub-group size.+ const uint sg_size = get_max_sub_group_size();+ for (uint x = x_aligned_end + get_sub_group_local_id(); x < OUTPUT_SIZE_X; x += sg_size) {+ output[out_row_base + x] = scalar_val;+ }+#else+ MAKE_VECTOR_TYPE(OUTPUT_TYPE, OPT_VEC_SIZE) out_vec = (MAKE_VECTOR_TYPE(OUTPUT_TYPE, OPT_VEC_SIZE))(scalar_val);+ for (uint x_start = lid * vec_size; x_start < OUTPUT_SIZE_X; x_start += total_wis * vec_size) {+ if (x_start + vec_size <= OUTPUT_SIZE_X) {+ CAT(vstore, OPT_VEC_SIZE)(out_vec, 0, &output[out_row_base + x_start]);+ } else if (x_start < OUTPUT_SIZE_X) {+ for (uint x = x_start; x < OUTPUT_SIZE_X; x++) {+ output[out_row_base + x] = scalar_val;+ }+ }+ }+#endif+#else+ // Runtime X-broadcast detection: if INPUT0_SIZE_X==1 at runtime (only relevant for+ // dynamic shapes — static IS_X_BROADCAST=1 takes the splat fast path above), each+ // output element reads input[0]. For static where INPUT0_SIZE_X is a compile-time+ // literal equal to OUTPUT_SIZE_X, the branch folds away and codegen is unchanged.+ for (uint x_start = lid * vec_size; x_start < OUTPUT_SIZE_X; x_start += total_wis * vec_size) {+ if (x_start + vec_size <= OUTPUT_SIZE_X) {+ MAKE_VECTOR_TYPE(OUTPUT_TYPE, OPT_VEC_SIZE) out_vec;+ if (INPUT0_SIZE_X == 1) {+ const OUTPUT_TYPE scalar_val = input[in_row_base];+ out_vec = (MAKE_VECTOR_TYPE(OUTPUT_TYPE, OPT_VEC_SIZE))(scalar_val);+ } else {+ out_vec = CAT(vload, OPT_VEC_SIZE)(0, &input[in_row_base + x_start]);+ }+#if BATCH_REPEAT > 1+ for (uint br = 0; br < BATCH_REPEAT; br++) {+ CAT(vstore, OPT_VEC_SIZE)(out_vec, 0, &output[out_row_base + br * OUTPUT_BATCH_PITCH + x_start]);+ }+#else+ CAT(vstore, OPT_VEC_SIZE)(out_vec, 0, &output[out_row_base + x_start]);+#endif+ } else if (x_start < OUTPUT_SIZE_X) {+ for (uint x = x_start; x < OUTPUT_SIZE_X; x++) {+ const uint in_x = (INPUT0_SIZE_X == 1) ? 0 : x;+ OUTPUT_TYPE val = input[in_row_base + in_x];+#if BATCH_REPEAT > 1+ for (uint br = 0; br < BATCH_REPEAT; br++) {+ output[out_row_base + br * OUTPUT_BATCH_PITCH + x] = val;+ }+#else+ output[out_row_base + x] = val;+#endif+ }+ }+ }+#endif+}diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/broadcast/broadcast_kernel_base.h b/src/plugins/intel_gpu/src/kernel_selector/kernels/broadcast/broadcast_kernel_base.hindex 4fe668be79c..b89a7ba44b7 100644--- a/src/plugins/intel_gpu/src/kernel_selector/kernels/broadcast/broadcast_kernel_base.h+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/broadcast/broadcast_kernel_base.h@@ -15,6 +15,7 @@ namespace kernel_selector {struct broadcast_params : public base_params {broadcast_params() : base_params(KernelType::BROADCAST) {}std::vector<uint16_t> input_order;+ bool is_explicit_mode = false; // true if primitive uses axes_mapping (explicit), false for numpy mode};////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/broadcast/broadcast_kernel_opt.cpp b/src/plugins/intel_gpu/src/kernel_selector/kernels/broadcast/broadcast_kernel_opt.cppnew file mode 100644index 00000000000..17f63aa5e36--- /dev/null+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/broadcast/broadcast_kernel_opt.cpp@@ -0,0 +1,263 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "broadcast_kernel_opt.h"+#include "kernel_selector_utils.h"++#include <numeric>+#include <vector>++namespace kernel_selector {++static constexpr size_t kOptVecSize = 8;+static constexpr size_t kMinXForOpt = 32;+static constexpr size_t kBatchRepeatInputBytesThreshold = 16 * 1024;+static constexpr size_t kWIsPerRow = 32;++ParamsKey BroadcastKernelOpt::GetSupportedKey() const {+ ParamsKey k;+ // The kernel only needs the data size (no per-element cast), so accept any type.+ // Note: EnableDifferentTypes() is deliberately NOT set, so the params-key rejects+ // input dtype != output dtype — that broadcast-with-convert case stays on the ref kernel.+ k.EnableAllInputDataType();+ k.EnableAllOutputDataType();++ k.EnableInputLayout(DataLayout::bfyx);+ k.EnableInputLayout(DataLayout::bfzyx);+ k.EnableInputLayout(DataLayout::bfwzyx);++ k.EnableOutputLayout(DataLayout::bfyx);+ k.EnableOutputLayout(DataLayout::bfzyx);+ k.EnableOutputLayout(DataLayout::bfwzyx);++ k.EnableTensorOffset();+ k.EnableTensorPitches();+ k.EnableBatching();+ k.EnableDynamicShapesSupport();++ return k;+}++namespace {++// Optimization decisions for the opt kernel. For static shapes these are+// computed from actual sizes; for dynamic shapes only the always-safe baseline+// (plain vstore8 path) is used.+struct OptChoices {+ size_t batch_repeat = 1;+ bool is_x_broadcast = false;+ bool x_broadcast_block_write = false;+ size_t num_rows = 0;+ size_t out_x = 0;+};++OptChoices PickStaticChoices(const broadcast_params& p) {+ const auto& input = p.inputs[0];+ const auto& output = p.outputs[0];++ OptChoices c;+ c.out_x = output.X().v;+ c.is_x_broadcast = (input.X().v == 1) && (output.X().v > 1);++ // Skip batch_repeat for X-broadcast — input is already tiny per row.+ if (!c.is_x_broadcast) {+ const size_t input_bytes = input.LogicalSize() * BytesPerElement(input.GetDType());+ if (input.Batch().v == 1 && output.Batch().v > 1 && input_bytes > kBatchRepeatInputBytesThreshold) {+ c.batch_repeat = output.Batch().v;+ }+ }+ const size_t dispatch_batch = output.Batch().v / c.batch_repeat;+ c.num_rows = output.Y().v * output.Z().v * output.W().v * output.Feature().v * dispatch_batch;+ // Block-write path: handles aligned 128-element chunks plus a scalar tail.+ // Gate requires X >= 128 to make the block-write loop meaningful; smaller X+ // takes the vstore8 splat path which is fine for tiny rows.+ //+ // intel_sub_group_block_write requires a 4-byte-aligned base address; the HW+ // silently rounds a misaligned base down, corrupting output. Two conditions:+ // - output must be contiguous & offset-0 (no padding/buffer offset), and+ // - every row base (row * out_x elements) must be 4-byte aligned. Since row can be+ // any value, this holds for all rows iff one row's byte-width is a multiple of 4:+ // (out_x * BytesPerElement) % 4 == 0. f32/i32/i64 always pass; f16 needs even X;+ // i8/u8 need X % 4 == 0. Otherwise fall back to the vstore8 splat path.+ const bool output_contiguous = !output.PitchesDifferFromLogicalDims() && output.GetFirstElementOffset() == 0;+ const bool row_4byte_aligned = (c.out_x * BytesPerElement(output.GetDType())) % 4 == 0;+ c.x_broadcast_block_write = c.is_x_broadcast && (c.out_x >= 128) && output_contiguous && row_4byte_aligned;+ return c;+}++CommonDispatchData ComputeDispatch(const OptChoices& c) {+ CommonDispatchData dispatchData;+ if (c.x_broadcast_block_write) {+ dispatchData.gws = { 16, c.num_rows, 1 };+ dispatchData.lws = { 16, 1, 1 };+ } else {+ const size_t work_items_per_row = (c.out_x + kOptVecSize - 1) / kOptVecSize;+ const size_t gws_x = std::min(work_items_per_row, kWIsPerRow);+ dispatchData.gws = { gws_x, c.num_rows, 1 };+ dispatchData.lws = { gws_x, 1, 1 };+ }+ return dispatchData;+}++} // namespace++// The X-broadcast block-write path compiles the kernel with intel_reqd_sub_group_size(16)+// and uses DT_OUTPUT_BLOCK_WRITE8, so advertise the sub-group requirements. Without this+// the impl could be selected on a device lacking sub-group support and fail at JIT-compile+// time instead of falling back to the ref kernel.+DeviceFeaturesKey BroadcastKernelOpt::get_required_device_features_key(const Params& params) const {+ auto k = get_common_subgroups_device_features_key(params);+ k.requires_subgroups();+ k.requires_reqd_subgroup_size();+ return k;+}++bool BroadcastKernelOpt::Validate(const Params& params) const {+ const auto& p = static_cast<const broadcast_params&>(params);+ const auto& input = p.inputs[0];+ const auto& output = p.outputs[0];++ if (input.GetLayout() != output.GetLayout())+ return false;++ if (!p.fused_ops.empty())+ return false;++ // This kernel does pure value-broadcast with no type cast. Broadcast-with-convert+ // (input dtype != output dtype) is handled by the ref kernel via TO_OUTPUT_TYPE.+ // The params-key already routes mismatches to ref (this kernel does not enable+ // different_types); this guard makes that invariant explicit.+ if (input.GetDType() != output.GetDType())+ return false;++ // The kernel maps output axis i directly to input axis i (no permutation). Two distinct+ // cases can violate that, so both guards are required:+ // 1. Numpy mode with broadcast_axes set (e.g. {2}) produces a permuted input_order like+ // [1,2,0,3] — caught by the identity check below.+ // 2. Explicit mode (axes_mapping set) leaves broadcast_axes empty, so input_order looks+ // like identity [0,1,2,...], but canonicalize_shapes places the input dim elsewhere —+ // caught by the is_explicit_mode flag.+ if (p.is_explicit_mode)+ return false;++ std::vector<uint16_t> identity_order(p.input_order.size());+ std::iota(identity_order.begin(), identity_order.end(), 0);+ if (p.input_order != identity_order)+ return false;++ if (input.is_dynamic() || output.is_dynamic()) {+ // Dynamic numpy-mode: the kernel processes one output row (X) per work-group and+ // broadcasts outer dims via per-row modulo. It has no Y-blocking, so for a Y-only+ // broadcast the ref kernel is faster. Only opt-in when we can STATICALLY PROVE the+ // beneficial shape, otherwise defer to ref:+ // - Y must be statically known and equal (not a Y-broadcast). If Y is dynamic we+ // cannot rule out a Y-broadcast at compile time -> regression risk -> reject.+ // - X is accepted when it is not statically known (resolved at runtime by the+ // kernel's INPUT0_SIZE_X == 1 branch), or when it either matches or is a 1->N+ // broadcast — the only numpy-valid options. Any other statically known X is a+ // non-row-coherent pattern -> reject.+ const bool y_known = !input.Y().is_dynamic && !output.Y().is_dynamic;+ if (!y_known || input.Y().v != output.Y().v)+ return false;++ const bool x_known = !input.X().is_dynamic && !output.X().is_dynamic;+ return !x_known || input.X().v == output.X().v || input.X().v == 1;+ }++ if (output.X().v < kMinXForOpt)+ return false;++ // X-broadcast splat: input.X==1, output.X>=32.+ bool is_x_broadcast = (input.X().v == 1) && (output.X().v > 1);+ if (is_x_broadcast)+ return true;++ // Standard vectorized path requires X dimensions to match.+ if (input.X().v != output.X().v)+ return false;++ // Don't use opt kernel for Y-only broadcast — ref kernel's Y-blocking is faster+ bool is_y_only_broadcast = (input.Batch().v == output.Batch().v)+ && (input.Feature().v == output.Feature().v)+ && (input.Y().v != output.Y().v);+ if (is_y_only_broadcast)+ return false;++ // Only use opt kernel when batch-repeat gives benefit (large input, batch broadcast)+ // Otherwise ref kernel is faster due to lower per-element overhead+ const size_t input_bytes = input.LogicalSize() * BytesPerElement(input.GetDType());+ const bool has_batch_repeat = (input.Batch().v == 1) && (output.Batch().v > 1)+ && (input_bytes > kBatchRepeatInputBytesThreshold);+ return has_batch_repeat;+}++KernelsPriority BroadcastKernelOpt::GetKernelsPriority(const Params& /*params*/) const {+ return FORCE_PRIORITY_8;+}++void BroadcastKernelOpt::GetUpdateDispatchDataFunc(KernelData& kd) const {+ kd.update_dispatch_data_func = [](const Params& params, KernelData& kd) {+ const auto& prim_params = static_cast<const broadcast_params&>(params);+ // For dynamic shapes, the kernel was JIT-compiled with the safe baseline+ // (BATCH_REPEAT=1, IS_X_BROADCAST=0, X_BROADCAST_BLOCK_WRITE=0). Recompute+ // num_rows from runtime shapes; do not enable size-dependent optimizations.+ OptChoices c;+ const auto& output = prim_params.outputs[0];+ c.out_x = output.X().v;+ c.num_rows = output.Y().v * output.Z().v * output.W().v+ * output.Feature().v * output.Batch().v;+ const auto dispatchData = ComputeDispatch(c);+ OPENVINO_ASSERT(kd.kernels.size() == 1, "[GPU] Invalid kernels size for update dispatch data func");+ kd.kernels[0].params.workGroups.global = dispatchData.gws;+ kd.kernels[0].params.workGroups.local = dispatchData.lws;+ kd.kernels[0].skip_execution = KernelData::SkipKernelExecution(prim_params);+ };+}++KernelsData BroadcastKernelOpt::GetKernelsData(const Params& params) const {+ assert(params.GetType() == KernelType::BROADCAST);++ const auto& prim_params = static_cast<const broadcast_params&>(params);++ if (!Validate(params))+ return {};++ OptChoices choices;+ if (!prim_params.has_dynamic_tensors()) {+ choices = PickStaticChoices(prim_params);+ } else {+ // Safe baseline for dynamic shapes; final num_rows recomputed at dispatch time.+ choices.batch_repeat = 1;+ choices.is_x_broadcast = false;+ choices.x_broadcast_block_write = false;+ choices.num_rows = 1; // placeholder; update_dispatch_data overwrites+ choices.out_x = 1;+ }++ const auto dispatchData = ComputeDispatch(choices);++ KernelData k_data = KernelData::Default<broadcast_params>(params);+ GetUpdateDispatchDataFunc(k_data);++ auto cldnn_jit = MakeBaseParamsJitConstants(prim_params);+ cldnn_jit.AddConstant(MakeJitConstant("OPT_VEC_SIZE", kOptVecSize));+ cldnn_jit.AddConstant(MakeJitConstant("BATCH_REPEAT", choices.batch_repeat));+ cldnn_jit.AddConstant(MakeJitConstant("IS_X_BROADCAST", choices.is_x_broadcast ? 1 : 0));+ cldnn_jit.AddConstant(MakeJitConstant("X_BROADCAST_BLOCK_WRITE", choices.x_broadcast_block_write ? 1 : 0));+ auto entry_point = GetEntryPoint(kernelName, prim_params.layerID, params);+ auto jit = CreateJit(kernelName, cldnn_jit, entry_point);++ auto& kernel = k_data.kernels[0];+ FillCLKernelData(kernel, dispatchData, params.engineInfo, kernelName, jit, entry_point,+ EXE_MODE_DEFAULT,+ false,+ false,+ 1,+ 0,+ 1,+ prim_params.is_shape_agnostic);++ return {k_data};+}+} // namespace kernel_selectordiff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/broadcast/broadcast_kernel_opt.h b/src/plugins/intel_gpu/src/kernel_selector/kernels/broadcast/broadcast_kernel_opt.hnew file mode 100644index 00000000000..d8c99e0328c--- /dev/null+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/broadcast/broadcast_kernel_opt.h@@ -0,0 +1,23 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "broadcast_kernel_base.h"++namespace kernel_selector {+class BroadcastKernelOpt : public BroadcastKernelBase {+public:+ BroadcastKernelOpt() : BroadcastKernelBase("broadcast_gpu_opt") {}++ KernelsData GetKernelsData(const Params& params) const override;+ KernelsPriority GetKernelsPriority(const Params& params) const override;+ ParamsKey GetSupportedKey() const override;+ DeviceFeaturesKey get_required_device_features_key(const Params& params) const override;+ bool Validate(const Params& params) const override;++protected:+ void GetUpdateDispatchDataFunc(KernelData& kd) const override;+};+} // namespace kernel_selectordiff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/broadcast/broadcast_kernel_selector.cpp b/src/plugins/intel_gpu/src/kernel_selector/kernels/broadcast/broadcast_kernel_selector.cppindex 955738bde9e..6bf22278233 100644--- a/src/plugins/intel_gpu/src/kernel_selector/kernels/broadcast/broadcast_kernel_selector.cpp+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/broadcast/broadcast_kernel_selector.cpp@@ -4,9 +4,13 @@#include "broadcast_kernel_selector.h"#include "broadcast_kernel_ref.h"+#include "broadcast_kernel_opt.h"namespace kernel_selector {-broadcast_kernel_selector::broadcast_kernel_selector() { Attach<BroadcastKernelRef>(); }+broadcast_kernel_selector::broadcast_kernel_selector() {+ Attach<BroadcastKernelOpt>();+ Attach<BroadcastKernelRef>();+}KernelsData broadcast_kernel_selector::GetBestKernels(const Params& params) const {return GetNaiveBestKernel(params, KernelType::BROADCAST);diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/broadcast_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/broadcast_gpu_test.cppindex 71b91288c9e..6ddd9258c83 100644--- a/src/plugins/intel_gpu/tests/unit/test_cases/broadcast_gpu_test.cpp+++ b/src/plugins/intel_gpu/tests/unit/test_cases/broadcast_gpu_test.cpp@@ -18,7 +18,8 @@ using namespace ::tests;template<typename T>void start_broadcast_test(format cldnn_format, data_types cldnn_data_type, std::vector<size_t> output_shape,- std::vector<size_t> input_shape, std::vector<size_t> broadcast_axes) {+ std::vector<size_t> input_shape, std::vector<size_t> broadcast_axes,+ const std::string& expected_kernel = "") {size_t input_data_size = accumulate(input_shape.rbegin(), input_shape.rend(), (size_t)1, std::multiplies<size_t>());ASSERT_GE(input_data_size, (size_t)1);std::vector<T> input_data = {};@@ -85,6 +86,20 @@ void start_broadcast_test(format cldnn_format, data_types cldnn_data_type, std::}}}++ // Assert the expected implementation was selected (e.g. "broadcast_gpu_opt" vs+ // "broadcast_gpu_ref"). Correctness alone doesn't prove which kernel ran — a test+ // that silently falls back to ref validates nothing about the opt kernel.+ if (!expected_kernel.empty()) {+ std::string broadcast_kernel;+ for (auto& info : network.get_primitives_info()) {+ if (info.original_id == "broadcast")+ broadcast_kernel = info.kernel_id;+ }+ ASSERT_NE(broadcast_kernel.find(expected_kernel), std::string::npos)+ << "Expected broadcast impl containing '" << expected_kernel+ << "' but got '" << broadcast_kernel << "'";+ }}template<typename inT, typename outT>void start_broadcast_test_dynamic(format input_format,@@ -2411,3 +2426,288 @@ TEST(broadcast_gpu_opt_fp16, bfyx_4x5x1x1_to_4x5x6x1_axis_Y_6) {TEST(broadcast_gpu_opt_fp16, bfyx_4x5x1x1_to_4x5x11x1_axis_Y_11) {run_broadcast_gpu_opt_y_axis({4,5,1,1},{-1,-1,1,1},{4,5,11,1},{1,1,11,1});}++// ===== Tests targeting broadcast_gpu_opt kernel (batch-repeat path) =====+// The opt kernel fires when:+// input.Batch() == 1, output.Batch() > 1, input bytes > 16KB,+// input.X() == output.X(), output.X() >= 32, planar format, no fused ops.+// These tests stress the BATCH_REPEAT loop and OUTPUT_BATCH_PITCH stride math.++// Basic batch broadcast, X divisible by VEC_SIZE=8.+TEST(broadcast_gpu_opt, bfyx_1x16x32x64_to_8x16x32x64_axes_0) {+ start_broadcast_test<float>(format::bfyx, data_types::f32, {8,16,32,64}, {16,32,64}, {0}, "broadcast_gpu_opt");+}++// FP16 path (most common in inference).+TEST(broadcast_gpu_opt, bfyx_fp16_1x16x32x64_to_8x16x32x64_axes_0) {+ start_broadcast_test<ov::float16>(format::bfyx, data_types::f16, {8,16,32,64}, {16,32,64}, {0}, "broadcast_gpu_opt");+}++// X NOT divisible by VEC_SIZE=8 -> exercises scalar tail loop.+TEST(broadcast_gpu_opt, bfyx_1x16x32x70_to_8x16x32x70_axes_0_x_not_aligned) {+ start_broadcast_test<float>(format::bfyx, data_types::f32, {8,16,32,70}, {16,32,70}, {0}, "broadcast_gpu_opt");+}++// X just at threshold (kMinXForOpt = 32).+TEST(broadcast_gpu_opt, bfyx_1x16x16x32_to_4x16x16x32_axes_0_x_min_threshold) {+ start_broadcast_test<float>(format::bfyx, data_types::f32, {4,16,16,32}, {16,16,32}, {0}, "broadcast_gpu_opt");+}++// Non-power-of-2 batch.+TEST(broadcast_gpu_opt, bfyx_1x16x32x64_to_3x16x32x64_axes_0_batch_3) {+ start_broadcast_test<float>(format::bfyx, data_types::f32, {3,16,32,64}, {16,32,64}, {0}, "broadcast_gpu_opt");+}++TEST(broadcast_gpu_opt, bfyx_1x16x32x64_to_17x16x32x64_axes_0_batch_17) {+ start_broadcast_test<float>(format::bfyx, data_types::f32, {17,16,32,64}, {16,32,64}, {0}, "broadcast_gpu_opt");+}++// 5D bfzyx layout.+TEST(broadcast_gpu_opt, bfzyx_1x8x4x32x64_to_4x8x4x32x64_axes_0) {+ start_broadcast_test_5d<float>(format::bfzyx, data_types::f32, {4,8,4,32,64}, {8,4,32,64}, {0});+}++// FP16 5D path.+TEST(broadcast_gpu_opt, bfzyx_fp16_1x8x4x32x64_to_4x8x4x32x64_axes_0) {+ start_broadcast_test_5d<ov::float16>(format::bfzyx, data_types::f16, {4,8,4,32,64}, {8,4,32,64}, {0});+}++// INT8 path (verifies opt kernel handles 1-byte types).+TEST(broadcast_gpu_opt, bfyx_int8_1x16x32x64_to_8x16x32x64_axes_0) {+ start_broadcast_test<int8_t>(format::bfyx, data_types::i8, {8,16,32,64}, {16,32,64}, {0}, "broadcast_gpu_opt");+}++// INT64 path. Input must exceed the 16KB batch-repeat threshold to hit opt:+// 4*16*40 i64 = 20480 bytes > 16384.+TEST(broadcast_gpu_opt, bfyx_int64_1x4x16x40_to_4x4x16x40_axes_0) {+ start_broadcast_test<int64_t>(format::bfyx, data_types::i64, {4,4,16,40}, {4,16,40}, {0}, "broadcast_gpu_opt");+}++// Input just above the 16KB threshold -> opt kernel.+// 4*16*65 fp32 = 16640 bytes > 16384.+TEST(broadcast_gpu_opt, bfyx_1x4x16x65_to_4x4x16x65_axes_0_above_threshold) {+ start_broadcast_test<float>(format::bfyx, data_types::f32, {4,4,16,65}, {4,16,65}, {0}, "broadcast_gpu_opt");+}++// Input just below threshold -> ref kernel (verifies fallback works).+// 4*16*32 fp32 = 8192 bytes < 16384.+TEST(broadcast_gpu_opt, bfyx_1x4x16x32_to_4x4x16x32_axes_0_below_threshold_uses_ref) {+ start_broadcast_test<float>(format::bfyx, data_types::f32, {4,4,16,32}, {4,16,32}, {0}, "broadcast_gpu_ref");+}++// Combined batch+feature broadcast. axes={0,1} -> identity input_order. Input must exceed+// the 16KB batch-repeat threshold to hit opt: 64*128 f32 = 32768 bytes > 16384.+// Input [1,1,64,128] -> Output [4,16,64,128]: batch (1->4) AND feature (1->16) broadcast.+// Feature is handled via in_row_base modulo; opt fires because output.Batch>1, input.Batch==1.+TEST(broadcast_gpu_opt, bfyx_1x1x64x128_to_4x16x64x128_axes_0_1) {+ start_broadcast_test<float>(format::bfyx, data_types::f32, {4,16,64,128}, {64,128}, {0,1}, "broadcast_gpu_opt");+}++// Batch + Y broadcast. broadcast_axes={0,2} yields a permuted input_order [0,2,1,3]+// (NOT identity), so the opt kernel defers to ref. Verifies correctness on the fallback path.+// Input [16,64] (dims F,X) -> Output [4,16,32,64]: batch (axis 0) AND Y (axis 2) broadcast.+TEST(broadcast_gpu_opt, bfyx_16x64_to_4x16x32x64_axes_0_2) {+ start_broadcast_test<float>(format::bfyx, data_types::f32, {4,16,32,64}, {16,64}, {0,2}, "broadcast_gpu_ref");+}++// Guard regression test: broadcast_axes={2} (a middle axis) produces a permuted+// input_order [1,2,0,3] (NOT identity). The opt kernel maps output axis i -> input axis i+// with no permutation, so it must defer to ref here. Verifies the input_order identity+// guard routes this correctly and the result still matches the reference.+// NOTE: the legacy reinterpret (broadcast_axes) helper can only produce identity+// input_order for leading-axis broadcasts ({0}, {0,1}, ...). Trailing/middle-axis+// broadcasts always yield a permuted order and are (correctly) handled by ref. The opt+// kernel's X-broadcast / block-write fast path is exercised via start_x_broadcast_test+// below, which uses the numpy full-shape constructor to build a genuine input.X==1.+TEST(broadcast_gpu_opt, bfyx_axis2_permuted_order_uses_ref) {+ start_broadcast_test<float>(format::bfyx, data_types::f32, {4,16,32,64}, {4,16,64}, {2}, "broadcast_gpu_ref");+}++// Static numpy-mode X-broadcast helper: input has a genuine X==1 that is broadcast to+// output X via the numpy full-shape Broadcast constructor (empty axes_mapping -> empty+// broadcast_axes -> identity input_order). This is the ONLY way to hit the opt kernel's+// IS_X_BROADCAST splat / X_BROADCAST_BLOCK_WRITE paths from a unit test; the legacy+// reinterpret helper cannot construct input.X==1 with identity order.+template<typename T>+void start_x_broadcast_test(data_types dt, const ov::Shape& in_shape, const ov::Shape& out_shape,+ const std::string& expected_kernel) {+ ASSERT_EQ(in_shape.size(), out_shape.size());+ ASSERT_EQ(in_shape.back(), 1u); // X must be 1 to exercise the X-broadcast path++ size_t in_size = accumulate(in_shape.begin(), in_shape.end(), (size_t)1, std::multiplies<size_t>());+ std::vector<T> input_data;+ for (size_t i = 1; i <= in_size; ++i)+ input_data.push_back((T)i);++ size_t out_size = accumulate(out_shape.begin(), out_shape.end(), (size_t)1, std::multiplies<size_t>());+ std::vector<T> ref(out_size);+ ov::reference::broadcast(reinterpret_cast<const char*>(input_data.data()),+ reinterpret_cast<char*>(ref.data()),+ in_shape, out_shape, ov::AxisSet(), sizeof(T));++ auto& engine = get_test_engine();+ auto fmt = format::get_default_format(in_shape.size());+ auto input = engine.allocate_memory({ov::PartialShape(in_shape), dt, fmt});+ set_values(input, input_data);++ topology topology;+ topology.add(input_layout("input", input->get_layout()));+ topology.add(broadcast("broadcast", input_info("input"), out_shape, ov::AxisSet{}, ov::op::BroadcastType::NUMPY));+ topology.add(reorder("output", input_info("broadcast"), fmt, dt));++ network network(engine, topology, get_test_default_config(engine));+ network.set_input_data("input", input);+ auto outputs = network.execute();++ auto output = outputs.at("output").get_memory();+ cldnn::mem_lock<T, mem_lock_type::read> output_ptr(output, get_test_stream());+ for (size_t i = 0; i < out_size; ++i)+ ASSERT_EQ(output_ptr[i], ref[i]);++ std::string broadcast_kernel;+ for (auto& info : network.get_primitives_info()) {+ if (info.original_id == "broadcast")+ broadcast_kernel = info.kernel_id;+ }+ ASSERT_NE(broadcast_kernel.find(expected_kernel), std::string::npos)+ << "Expected broadcast impl containing '" << expected_kernel << "' but got '" << broadcast_kernel << "'";+}++// X-broadcast splat path: input.X==1, output.X in [32,128) -> vstore8 splat (not block-write).+TEST(broadcast_gpu_opt, bfyx_x_broadcast_x64_splat) {+ start_x_broadcast_test<float>(data_types::f32, {1,64,128,1}, {1,64,128,64}, "broadcast_gpu_opt");+}++// X-broadcast block-write path: input.X==1, output.X==256 (>=128, %128==0) -> block_write8, no tail.+TEST(broadcast_gpu_opt, bfyx_x_broadcast_x256_block_write) {+ start_x_broadcast_test<float>(data_types::f32, {1,64,128,1}, {1,64,128,256}, "broadcast_gpu_opt");+}++// X-broadcast block-write + tail: output.X==200 (>=128, %128!=0) -> 1 block of 128 + 72-elem tail.+TEST(broadcast_gpu_opt, bfyx_x_broadcast_x200_block_write_with_tail) {+ start_x_broadcast_test<float>(data_types::f32, {1,64,128,1}, {1,64,128,200}, "broadcast_gpu_opt");+}++// FP16 X-broadcast block-write (verifies block_write_us8 for 2-byte types).+TEST(broadcast_gpu_opt, bfyx_fp16_x_broadcast_x256_block_write) {+ start_x_broadcast_test<ov::float16>(data_types::f16, {1,64,128,1}, {1,64,128,256}, "broadcast_gpu_opt");+}++// FP16 X-broadcast with ODD X=129 (>=128 but row byte-width 129*2=258 not %4). block_write+// would misalign consecutive rows and silently corrupt, so the alignment guard must fall+// back to the vstore8 splat path. Still opt kernel, just not the block-write path.+// (Correctness of the fallback output is the key check here.)+TEST(broadcast_gpu_opt, bfyx_fp16_x_broadcast_x129_odd_falls_back_to_splat) {+ start_x_broadcast_test<ov::float16>(data_types::f16, {1,64,128,1}, {1,64,128,129}, "broadcast_gpu_opt");+}++// INT8 X-broadcast block-write (verifies block_write_uc8 for 1-byte types). X=256, row width+// 256*1=256 %4==0 -> block-write. This is the quantized-model path; distinct 1-byte intrinsic.+TEST(broadcast_gpu_opt, bfyx_int8_x_broadcast_x256_block_write) {+ start_x_broadcast_test<int8_t>(data_types::i8, {1,64,128,1}, {1,64,128,256}, "broadcast_gpu_opt");+}++// INT8 X-broadcast, X=130: row width 130*1=130 %4==2 -> alignment guard fails -> splat fallback.+// i8's alignment condition (X%4==0) differs from f16's (even X); exercises that boundary.+TEST(broadcast_gpu_opt, bfyx_int8_x_broadcast_x130_unaligned_falls_back_to_splat) {+ start_x_broadcast_test<int8_t>(data_types::i8, {1,64,128,1}, {1,64,128,130}, "broadcast_gpu_opt");+}++// FP16 X-broadcast block-write WITH tail: X=192 (>=128, %128=64, even so 192*2=384 %4==0 ->+// block-write eligible). Exercises the 2-byte block-write + scalar-tail combination.+TEST(broadcast_gpu_opt, bfyx_fp16_x_broadcast_x192_block_write_with_tail) {+ start_x_broadcast_test<ov::float16>(data_types::f16, {1,64,128,1}, {1,64,128,192}, "broadcast_gpu_opt");+}++// Dynamic numpy-mode broadcast helper. The input partial shape is passed explicitly so a+// test can mark only some axes dynamic (e.g. batch = -1, Y/X static) — matching how real+// dynamic LLM broadcasts reach the plugin. Numpy mode = empty axes_mapping. The input+// layout is dynamic (so the impl is shape-agnostic), while the target output shape is a+// compile-time constant (so shape inference resolves static F/Y/X, letting the opt kernel's+// Y-static gate admit the case). Exercises the opt kernel's dynamic path: shape-agnostic+// JIT (BATCH_REPEAT=1, runtime INPUT0_SIZE_X==1 branch) + GetUpdateDispatchDataFunc.+// Asserts the impl is dynamic, selects the expected kernel, and produces correct output.+template<typename T>+void start_dynamic_numpy_broadcast_test(data_types dt, const ov::PartialShape& in_pshape,+ const ov::Shape& in_shape, const ov::Shape& out_shape,+ const std::string& expected_kernel) {+ ASSERT_EQ(in_shape.size(), out_shape.size());+ ASSERT_EQ(in_pshape.size(), in_shape.size());++ size_t in_size = accumulate(in_shape.begin(), in_shape.end(), (size_t)1, std::multiplies<size_t>());+ std::vector<T> input_data;+ for (size_t i = 1; i <= in_size; ++i)+ input_data.push_back((T)i);++ size_t out_size = accumulate(out_shape.begin(), out_shape.end(), (size_t)1, std::multiplies<size_t>());+ std::vector<T> ref(out_size);+ ov::reference::broadcast(reinterpret_cast<const char*>(input_data.data()),+ reinterpret_cast<char*>(ref.data()),+ in_shape, out_shape, ov::AxisSet(), sizeof(T));++ auto& engine = get_test_engine();+ const int64_t rank = static_cast<int64_t>(in_shape.size());+ auto fmt = format::get_default_format(rank);++ auto input = engine.allocate_memory({ov::PartialShape(in_shape), dt, fmt});+ set_values(input, input_data);++ topology topology;+ topology.add(input_layout("input", layout(in_pshape, dt, fmt)));+ // Constant (compile-time) target shape so shape inference resolves the static output+ // dims (F/Y/X); the input stays dynamic on its marked axes. This mirrors a real+ // dynamic-batch broadcast where the target shape is known from surrounding constants,+ // and is required for the opt kernel's Y-static gate to admit the case.+ topology.add(broadcast("broadcast", input_info("input"), out_shape, ov::AxisSet{},+ ov::op::BroadcastType::NUMPY));+ topology.add(reorder("output", input_info("broadcast"), fmt, dt));++ ExecutionConfig config = get_test_default_config(engine);+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));++ network network(engine, topology, config);+ network.set_input_data("input", input);++ // Confirm the selected broadcast impl is genuinely a dynamic (shape-agnostic) impl.+ auto inst = network.get_primitive("broadcast");+ auto impl = inst->get_impl();+ ASSERT_TRUE(impl != nullptr);+ ASSERT_TRUE(impl->is_dynamic());++ auto outputs = network.execute();+ auto output = outputs.at("output").get_memory();+ cldnn::mem_lock<T, mem_lock_type::read> output_ptr(output, get_test_stream());+ for (size_t i = 0; i < out_size; ++i)+ ASSERT_EQ(output_ptr[i], ref[i]);++ std::string broadcast_kernel;+ for (auto& info : network.get_primitives_info()) {+ if (info.original_id == "broadcast")+ broadcast_kernel = info.kernel_id;+ }+ ASSERT_NE(broadcast_kernel.find(expected_kernel), std::string::npos)+ << "Expected broadcast impl containing '" << expected_kernel << "' but got '" << broadcast_kernel << "'";+}++// Dynamic batch broadcast: batch is dynamic (-1) but F/Y/X are static, matching a real+// dynamic-batch LLM broadcast. The conservative gate requires Y statically known & equal+// (it is: 128==128), so opt is selected. Runtime batch resolves to 4 at execution.+TEST(broadcast_gpu_opt, dynamic_batch_broadcast_uses_opt) {+ start_dynamic_numpy_broadcast_test<float>(data_types::f32, {-1,64,128,256},+ {1,64,128,256}, {4,64,128,256}, "broadcast_gpu_opt");+}++// Dynamic X-broadcast: batch dynamic, X statically 1 -> opt kernel's INPUT0_SIZE_X==1+// splat branch. Y statically equal so the gate admits it. Verifies runtime X-broadcast.+TEST(broadcast_gpu_opt, dynamic_x_broadcast_uses_opt) {+ start_dynamic_numpy_broadcast_test<float>(data_types::f32, {-1,64,128,1},+ {1,64,128,1}, {4,64,128,64}, "broadcast_gpu_opt");+}++// Dynamic Y is unknown at compile time -> the conservative gate cannot prove Y is not a+// broadcast axis, so opt defers to ref (which has Y-blocking). Guards against a Y-broadcast+// regression on dynamic shapes.+TEST(broadcast_gpu_opt, dynamic_y_unknown_uses_ref) {+ start_dynamic_numpy_broadcast_test<float>(data_types::f32, {-1,64,-1,256},+ {1,64,128,256}, {4,64,128,256}, "broadcast_gpu_ref");+}