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] Rewrite group_normalization_ref kernel (#39562)
Joonho Yeomf6f9b3427c14
diff --git a/src/plugins/intel_gpu/src/graph/group_normalization.cpp b/src/plugins/intel_gpu/src/graph/group_normalization.cppindex 3876cd918e8..398359b17a0 100644--- a/src/plugins/intel_gpu/src/graph/group_normalization.cpp+++ b/src/plugins/intel_gpu/src/graph/group_normalization.cpp@@ -10,8 +10,6 @@ namespace cldnn {GPU_DEFINE_PRIMITIVE_TYPE_ID(group_normalization)layout group_normalization_inst::calc_output_layout(group_normalization_node const& node, kernel_impl_params const& impl_param) {- assert(static_cast<bool>(impl_param.desc->output_data_types[0]) == false &&- "Output data type forcing is not supported for group_normalization_node!");auto input_node_layout = impl_param.get_non_padded_input_layout();auto output_type = impl_param.desc->output_data_types[0].value_or(input_node_layout.data_type);diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/group_normalization_ref.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/group_normalization_ref.clindex efad24648a6..8e01c18dfdb 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/group_normalization_ref.cl+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/group_normalization_ref.cl@@ -2,144 +2,153 @@// SPDX-License-Identifier: Apache-2.0//-#include "include/batch_headers/common.cl"#include "include/batch_headers/fetch_data.cl"-#define NUM_CHANNELS_IN_GROUP (INPUT0_FEATURE_NUM / NUM_GROUPS)-#define CHANNEL_SIZE (INPUT0_BATCH_PITCH / INPUT0_FEATURE_NUM)-#define GROUP_SIZE (NUM_CHANNELS_IN_GROUP * CHANNEL_SIZE)--#if MEAN_KERNEL_ENABLED || STANDARD_DEVIATION_KERNEL_ENABLED-inline void FUNC(kahan_summation)(INPUT0_TYPE elem, __private float* compensation, __private float* sum) {- if (isfinite(elem) && isfinite(*sum)) {- float temp = *sum + (elem - *compensation);- *compensation = (temp - *sum) - (elem - *compensation);- *sum = temp;- } else {- *sum += elem;- }-}+#define CHANNELS_PER_GROUP (INPUT0_FEATURE_NUM / NUM_GROUPS)+#define SPATIAL_SIZE (INPUT0_SIZE_W * INPUT0_SIZE_Z * INPUT0_SIZE_Y * INPUT0_SIZE_X)++// Index macros with all six coordinates. Unused coordinates are dropped for the tensor rank.+#if INPUT0_DIMS == 6+ #define INPUT_INDEX(b, f, w, z, y, x) INPUT0_GET_INDEX(b, f, w, z, y, x)+ #define OUT_INDEX(b, f, w, z, y, x) OUTPUT_GET_INDEX(b, f, w, z, y, x)+#elif INPUT0_DIMS == 5+ #define INPUT_INDEX(b, f, w, z, y, x) INPUT0_GET_INDEX(b, f, z, y, x)+ #define OUT_INDEX(b, f, w, z, y, x) OUTPUT_GET_INDEX(b, f, z, y, x)+#else+ #define INPUT_INDEX(b, f, w, z, y, x) INPUT0_GET_INDEX(b, f, y, x)+ #define OUT_INDEX(b, f, w, z, y, x) OUTPUT_GET_INDEX(b, f, y, x)#endif-#if MEAN_KERNEL_ENABLED+#ifdef GROUP_NORM_KERNEL_CALC_STATS-KERNEL (calc_mean_ref)( __global INPUT0_TYPE* input- , __global float* output-#if HAS_FUSED_OPS_DECLS- , FUSED_OPS_DECLS-#endif-)-{- const int batch = get_global_id(0);- if (batch >= INPUT0_BATCH_NUM)- return;- const int group = get_global_id(1);- const int feature_begin = group * NUM_CHANNELS_IN_GROUP;- const int feature_end = group * NUM_CHANNELS_IN_GROUP + NUM_CHANNELS_IN_GROUP;- float variance = 0.f, error = 0.f, mean_value = 0.f;- for (int feature = feature_begin; feature < feature_end; feature++)- {- if (feature >= INPUT0_FEATURE_NUM)- continue;-#if OUTPUT_DIMS > 4- for (int z = 0; z < INPUT0_SIZE_Z; z++)-#endif- for (int y = 0; y < INPUT0_SIZE_Y; y++)- for (int x = 0; x < INPUT0_SIZE_X; x++)- {-#if OUTPUT_DIMS == 5- size_t input_idx = INPUT0_GET_INDEX(batch, feature, z, y, x);-#elif OUTPUT_DIMS == 4- size_t input_idx = INPUT0_GET_INDEX(batch, feature, y, x);-#endif- FUNC_CALL(kahan_summation)(input[input_idx], &error, &mean_value);- }- }- mean_value /= GROUP_SIZE;- output[batch * NUM_GROUPS + group] = mean_value;+// f_begin: group index * CHANNELS_PER_GROUP+// i: linear index in the group with x innermost.+inline uint FUNC(group_element_index)(OPTIONAL_SHAPE_INFO_ARG uint b, uint f_begin, uint i) {+ const uint x = i % INPUT0_SIZE_X;+ i /= INPUT0_SIZE_X;+ const uint y = i % INPUT0_SIZE_Y;+ i /= INPUT0_SIZE_Y;+ const uint z = i % INPUT0_SIZE_Z;+ i /= INPUT0_SIZE_Z;+ const uint w = i % INPUT0_SIZE_W;+ const uint f = f_begin + i / INPUT0_SIZE_W;+ return INPUT_INDEX(b, f, w, z, y, x);}-#elif STANDARD_DEVIATION_KERNEL_ENABLED+// Computes the statistics of each (b, group) for the normalize stage:+// mean_buf[b * NUM_GROUPS + g] = mean of the group+// inv_std_buf[b * NUM_GROUPS + g] = 1 / sqrt(variance + EPSILON)+// A group is CHANNELS_PER_GROUP channels x all spatial elements of batch b.+// Accumulates in f32 with a corrected two-pass algorithm (see below).+// GWS = {LWS * NUM_GROUPS, B, 1}, LWS = {LWS, 1, 1}. One work-group handles one (b, group).+__attribute__((reqd_work_group_size(LWS, 1, 1)))+KERNEL(calc_stats)(+ OPTIONAL_SHAPE_INFO_ARG+ const __global INPUT0_TYPE* input,+ __global float* mean_buf,+ __global float* inv_std_buf+) {+ const uint g = get_group_id(0);+ const uint b = get_global_id(1);+ const uint lid = get_local_id(0);+ const uint f_begin = g * CHANNELS_PER_GROUP;+ const uint n = CHANNELS_PER_GROUP * SPATIAL_SIZE;-KERNEL (calc_standard_deviation_ref)( __global INPUT0_TYPE* input- , __global float* mean- , __global float* output-#if HAS_FUSED_OPS_DECLS- , FUSED_OPS_DECLS-#endif-)-{- const int batch = get_global_id(0);- if (batch >= INPUT0_BATCH_NUM)+ // Only for empty tensors. The condition is uniform in the work-group.+ if (n == 0 || b >= INPUT0_BATCH_NUM)return;- const int group = get_global_id(1);- const int output_idx = batch * NUM_GROUPS + group;- const int feature_begin = group * NUM_CHANNELS_IN_GROUP;- const int feature_end = group * NUM_CHANNELS_IN_GROUP + NUM_CHANNELS_IN_GROUP;- float variance = 0.f, error = 0.f;-- for (int feature = feature_begin; feature < feature_end; feature++)- {- if (feature >= INPUT0_FEATURE_NUM)- continue;-#if OUTPUT_DIMS > 4- for (int z = 0; z < INPUT0_SIZE_Z; z++)-#endif- for (int y = 0; y < INPUT0_SIZE_Y; y++)- for (int x = 0; x < INPUT0_SIZE_X; x++)- {-#if OUTPUT_DIMS == 5- size_t input_idx = INPUT0_GET_INDEX(batch, feature, z, y, x);-#elif OUTPUT_DIMS == 4- size_t input_idx = INPUT0_GET_INDEX(batch, feature, y, x);-#endif- FUNC_CALL(kahan_summation)(pow(input[input_idx] - mean[output_idx], 2), &error, &variance);- }++ // Pass 1: approx_mean = sum(x) / n+ // Kahan summation keeps rounding errors that accumulate in the same direction from biasing the mean.+ float sum = 0.0f;+ float comp = 0.0f;+ for (ulong i = lid; i < n; i += LWS) {+ const float x = convert_float(input[FUNC_CALL(group_element_index)(OPTIONAL_SHAPE_INFO_TENSOR b, f_begin, (uint)i)]);+ // Kahan summation of sum += x. comp keeps the low-order bits lost by each addition.+ const float y = x - comp;+ const float t = sum + y;+ comp = (t - sum) - y;+ sum = t;+ }+ const float approx_mean = work_group_reduce_add(sum) / n;++ // Pass 2: d = x - approx_mean, mean = approx_mean + sum(d) / n, variance = (sum(d^2) - sum(d)^2 / n) / n+ // Corrected two-pass: the second pass also sums the deviations. That sum is zero in exact arithmetic,+ // so it measures the rounding error of approx_mean. It fixes the mean and removes the error from the variance.+ // Kahan summation preserves sum(d) = n * (mean - approx_mean), the correction term of the mean.+ // The deviations share its sign, so a plain f32 sum loses it.+ float d_sum = 0.0f;+ float d_comp = 0.0f;+ float sq_sum = 0.0f;+ for (ulong i = lid; i < n; i += LWS) {+ const float d = convert_float(input[FUNC_CALL(group_element_index)(OPTIONAL_SHAPE_INFO_TENSOR b, f_begin, (uint)i)]) - approx_mean;+ // Kahan summation of d_sum += d. d_comp keeps the low-order bits lost by each addition.+ const float y = d - d_comp;+ const float t = d_sum + y;+ d_comp = (t - d_sum) - y;+ d_sum = t;+ sq_sum = fma(d, d, sq_sum);+ }+ d_sum = work_group_reduce_add(d_sum);+ sq_sum = work_group_reduce_add(sq_sum);+ const float mean = approx_mean + d_sum / n;+ // d_sum * d_sum can overflow while sq_sum is finite, so divide by n first.+ const float variance = fmax((sq_sum - d_sum * (d_sum / n)) / n, 0.0f);++ // Output: mean, inv_std = rsqrt(variance + EPSILON)+ if (lid == 0) {+ mean_buf[b * NUM_GROUPS + g] = mean;+ inv_std_buf[b * NUM_GROUPS + g] = rsqrt(variance + EPSILON);}- variance /= GROUP_SIZE;- float standard_deviation = sqrt(variance + EPSILON);- output[output_idx] = standard_deviation;}-#elif NORMALIZE_KERNEL_ENABLED-KERNEL (normalize_ref)( __global INPUT0_TYPE* input- , __global INPUT0_TYPE* scale_values- , __global INPUT0_TYPE* bias_values- , __global float* mean_values- , __global float* standard_deviation_values- , __global OUTPUT_TYPE* output++#elif defined(GROUP_NORM_KERNEL_NORMALIZE)++// GWS = {W * Z * Y * X, F, B}+KERNEL(normalize)(+ OPTIONAL_SHAPE_INFO_ARG+ const __global INPUT0_TYPE* input,+ const __global INPUT1_TYPE* scale,+ const __global INPUT2_TYPE* bias,+ const __global float* mean_buf,+ const __global float* inv_std_buf,+ __global OUTPUT_TYPE* output#if HAS_FUSED_OPS_DECLS- , FUSED_OPS_DECLS+ , FUSED_OPS_DECLS#endif-)-{- const int batch = get_global_id(0);-#if OUTPUT_DIMS == 4- const int feature = get_global_id(1);-#elif OUTPUT_DIMS == 5- const int feature = get_global_id(1) / OUTPUT_SIZE_Z;- const int z = get_global_id(1) % OUTPUT_SIZE_Z;-#endif- const int y = get_global_id(2) / OUTPUT_SIZE_X;- const int x = get_global_id(2) % OUTPUT_SIZE_X;- const int group = feature / NUM_CHANNELS_IN_GROUP;- float mean = mean_values[batch * NUM_GROUPS + group];- float standard_deviation = standard_deviation_values[batch * NUM_GROUPS + group];-#if OUTPUT_DIMS == 4- size_t output_idx = OUTPUT_GET_INDEX(batch, feature, y, x);-#elif OUTPUT_DIMS == 5- size_t output_idx = OUTPUT_GET_INDEX(batch, feature, z, y, x);-#endif- OUTPUT_TYPE res = ((input[output_idx] - mean) / standard_deviation) * scale_values[feature] + bias_values[feature];+) {+ uint s = get_global_id(0);+ const uint f = get_global_id(1);+ const uint b = get_global_id(2);++ // Only for empty tensors, where GWS is clamped to 1.+ if (s >= SPATIAL_SIZE || f >= INPUT0_FEATURE_NUM || b >= INPUT0_BATCH_NUM)+ return;++ const uint x = s % INPUT0_SIZE_X;+ s /= INPUT0_SIZE_X;+ const uint y = s % INPUT0_SIZE_Y;+ s /= INPUT0_SIZE_Y;+ const uint z = s % INPUT0_SIZE_Z;+ const uint w = s / INPUT0_SIZE_Z;++ const uint bg = b * NUM_GROUPS + f / CHANNELS_PER_GROUP;+ // scale and bias hold C contiguous values. Their layout may be [C] or [1, C, 1, 1], so read them linearly.+ float normalized = (convert_float(input[INPUT_INDEX(b, f, w, z, y, x)]) - mean_buf[bg]) * inv_std_buf[bg];+ normalized = normalized * convert_float(scale[f]) + convert_float(bias[f]);++ const uint output_idx = OUT_INDEX(b, f, w, z, y, x);#if HAS_FUSED_OPSFUSED_OPS;output[output_idx] = FUSED_OPS_RESULT;#else- output[output_idx] = res;+ output[output_idx] = TO_OUTPUT_TYPE(normalized);#endif}#endif-#undef NUM_CHANNELS_IN_GROUP-#undef CHANNEL_SIZE-#undef GROUP_SIZE+#undef CHANNELS_PER_GROUP+#undef SPATIAL_SIZE+#undef INPUT_INDEX+#undef OUT_INDEXdiff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/group_normalization_ref.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/group_normalization_ref.cppindex 385b7fa4342..60fbeea89bb 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/group_normalization_ref.cpp+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/group_normalization_ref.cpp@@ -3,6 +3,12 @@//#include "group_normalization_ref.hpp"+#include <algorithm>+#include <string>+#include <string_view>+#include <vector>++#include "common_utils/dispatch_utils.hpp"#include "common_utils/jitter.hpp"#include "group_normalization_inst.h"#include "intel_gpu/primitives/group_normalization.hpp"@@ -17,63 +23,49 @@ namespace {using namespace ov::intel_gpu::ocl;-void common_jit_constants(JitConstants& jit_constants, const RuntimeParams& params) {- auto desc = params.typed_desc<group_normalization>();- jit_constants.make("EPSILON", static_cast<float>(desc->epsilon));- jit_constants.make("NUM_GROUPS", desc->num_groups);+// Work-group size of calc_stats. One work-group reduces one (batch, group) pair.+// It does not depend on the shape, so the same value is used for static and dynamic kernels.+size_t get_calc_stats_lws(const RuntimeParams& params) {+ const size_t max_wgs = params.get_device_info().max_work_group_size;+ size_t lws = 256;+ while (lws > 1 && lws > max_wgs) {+ lws /= 2;+ }+ return lws;}-class GroupNormalizationGeneratorCalcMeanRef : public KernelGenerator {+class GroupNormalizationGeneratorRefBase : public KernelGenerator {public:- GroupNormalizationGeneratorCalcMeanRef() : KernelGenerator("group_normalization_ref") {}+ explicit GroupNormalizationGeneratorRefBase(std::string_view suffix) : KernelGenerator("group_normalization_ref", suffix) {}protected:[[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {- auto jit_constants = KernelGenerator::get_jit_constants(params);- common_jit_constants(jit_constants, params);- jit_constants.make("MEAN_KERNEL_ENABLED", 1);- return jit_constants;- }-- [[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& params) const override {- Arguments args;-- args.push_back({ArgumentDescriptor::Types::INPUT, 0});- args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 0});-- return args;- }-- [[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {- return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt_params) {- assert(!params.is_dynamic());- auto& wgs = kd.params.workGroups;-- auto desc = params.typed_desc<group_normalization>();- auto max_wgs = params.get_program().get_engine().get_device_info().max_work_group_size;- auto num_groups = static_cast<size_t>(desc->num_groups);- const auto& out_shape = params.output_layouts[0].get_shape();- wgs.global = {out_shape[0], num_groups, 1};- wgs.local = {out_shape[0] * num_groups > max_wgs ? max_wgs / num_groups : out_shape[0], num_groups, 1};- }};+ auto jit = KernelGenerator::get_jit_constants(params);+ auto desc = params.typed_desc<group_normalization>();+ jit.make("EPSILON", static_cast<float>(desc->epsilon));+ jit.make("NUM_GROUPS", desc->num_groups);+ return jit;}};-class GroupNormalizationGeneratorCalcStd : public KernelGenerator {+class GroupNormalizationGeneratorCalcStats : public GroupNormalizationGeneratorRefBase {public:- GroupNormalizationGeneratorCalcStd() : KernelGenerator("group_normalization_ref") {}+ GroupNormalizationGeneratorCalcStats() : GroupNormalizationGeneratorRefBase("calc_stats") {}protected:[[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {- auto jit_constants = KernelGenerator::get_jit_constants(params);- common_jit_constants(jit_constants, params);- jit_constants.make("STANDARD_DEVIATION_KERNEL_ENABLED", 1);- return jit_constants;+ auto jit = GroupNormalizationGeneratorRefBase::get_jit_constants(params);+ jit.make("GROUP_NORM_KERNEL_CALC_STATS", 1);+ jit.make("LWS", get_calc_stats_lws(params));+ return jit;}[[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& params) const override {Arguments args;+ if (params.is_dynamic()) {+ args.push_back({ArgumentDescriptor::Types::SHAPE_INFO, 0});+ }args.push_back({ArgumentDescriptor::Types::INPUT, 0});args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 0});args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 1});@@ -86,33 +78,40 @@ protected:assert(!params.is_dynamic());auto& wgs = kd.params.workGroups;- auto desc = params.typed_desc<group_normalization>();- auto max_wgs = params.get_program().get_engine().get_device_info().max_work_group_size;- auto num_groups = static_cast<size_t>(desc->num_groups);- const auto& out_shape = params.output_layouts[0].get_shape();- wgs.global = {out_shape[0], num_groups, 1};- wgs.local = {out_shape[0] * num_groups > max_wgs ? max_wgs / num_groups : out_shape[0], num_groups, 1};+ const auto& in_l = params.input_layouts[0];+ const auto num_groups = static_cast<size_t>(params.typed_desc<group_normalization>()->num_groups);+ const auto b = extract_channel(ChannelName::BATCH, in_l);+ const auto f = extract_channel(ChannelName::FEATURE, in_l);+ OPENVINO_ASSERT(num_groups > 0 && f % num_groups == 0, "[GPU] GroupNormalization: ", f, " channels are not divisible by ", num_groups, " groups");++ const auto lws = get_calc_stats_lws(params);+ wgs.global = {lws * num_groups, std::max<size_t>(b, 1), 1};+ wgs.local = {lws, 1, 1};}};}};-class GroupNormalizationGeneratorNormalize : public KernelGenerator {+class GroupNormalizationGeneratorNormalize : public GroupNormalizationGeneratorRefBase {public:- GroupNormalizationGeneratorNormalize() : KernelGenerator("group_normalization_ref") {}+ GroupNormalizationGeneratorNormalize() : GroupNormalizationGeneratorRefBase("normalize") {}protected:[[nodiscard]] JitConstants get_jit_constants(const RuntimeParams& params) const override {- auto jit = KernelGenerator::get_jit_constants(params);- common_jit_constants(jit, params);- jit.make("NORMALIZE_KERNEL_ENABLED", 1);- jit.make("INPUT_INDICES_ORDER", "batch, feature, z, y, x");+ auto jit = GroupNormalizationGeneratorRefBase::get_jit_constants(params);+ jit.make("GROUP_NORM_KERNEL_NORMALIZE", 1);if (params.has_fused_primitives()) {- const auto& out_l = params.get_output_layout(0);- auto idx_order =- out_l.get_rank() == 5 ? std::vector<std::string>{"batch", "feature", "z", "y", "x"} : std::vector<std::string>{"batch", "feature", "y", "x"};-- FusedOpsConfiguration conf = {"", idx_order, "res", out_l.data_type};+ const auto rank = params.get_output_layout(0).get_rank();+ std::vector<std::string> idx_order;+ if (rank == 6) {+ idx_order = {"b", "f", "w", "z", "y", "x"};+ } else if (rank == 5) {+ idx_order = {"b", "f", "z", "y", "x"};+ } else {+ idx_order = {"b", "f", "y", "x"};+ }++ FusedOpsConfiguration conf = {"", idx_order, "normalized", ov::element::f32, 1};jit.add(make_fused_ops_jit_constants(params, {conf}));}@@ -122,13 +121,15 @@ protected:[[nodiscard]] Arguments get_arguments_desc(const RuntimeParams& params) const override {Arguments args;+ if (params.is_dynamic()) {+ args.push_back({ArgumentDescriptor::Types::SHAPE_INFO, 0});+ }args.push_back({ArgumentDescriptor::Types::INPUT, 0});args.push_back({ArgumentDescriptor::Types::INPUT, 1});args.push_back({ArgumentDescriptor::Types::INPUT, 2});args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 0});args.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 1});args.push_back({ArgumentDescriptor::Types::OUTPUT, 0});-add_fused_ops_arguments(args, params);return args;@@ -136,23 +137,22 @@ protected:[[nodiscard]] DispatchDataFunc get_dispatch_data_func() const override {return DispatchDataFunc{[](const RuntimeParams& params, KernelData& kd, ImplRuntimeParams* rt_params) {- auto& wgs = kd.params.workGroups;assert(!params.is_dynamic());+ auto& wgs = kd.params.workGroups;const auto& in_l = params.input_layouts[0];const auto& out_l = params.output_layouts[0];- auto b = extract_channel(ChannelName::BATCH, out_l);- auto f = extract_channel(ChannelName::FEATURE, out_l);- auto z = extract_channel(ChannelName::Z, out_l);- auto y = extract_channel(ChannelName::Y, out_l);- auto x = extract_channel(ChannelName::X, out_l);-- wgs.global = {b, f * z, y * x};- std::vector<std::vector<ChannelName>> dims_by_gws = {{ChannelName::BATCH},- {ChannelName::FEATURE, ChannelName::Z},- {ChannelName::X, ChannelName::Y}};-- wgs.local = ov::intel_gpu::get_optimal_lws(wgs.global, params.get_device_info(), in_l.format, out_l.format, dims_by_gws);+ const auto b = extract_channel(ChannelName::BATCH, out_l);+ const auto f = extract_channel(ChannelName::FEATURE, out_l);+ const auto spatial = extract_channel(ChannelName::W, out_l) * extract_channel(ChannelName::Z, out_l) * extract_channel(ChannelName::Y, out_l) *+ extract_channel(ChannelName::X, out_l);++ // get_optimal_lws returns lws that divides gws on every axis, so gws must not be zero.+ wgs.global = {std::max<size_t>(spatial, 1), std::max<size_t>(f, 1), std::max<size_t>(b, 1)};+ std::vector<std::vector<ChannelName>> dims_by_gws = {{ChannelName::X, ChannelName::Y, ChannelName::Z, ChannelName::W},+ {ChannelName::FEATURE},+ {ChannelName::BATCH}};+ wgs.local = get_optimal_lws(wgs.global, params.get_device_info(), in_l.format, out_l.format, dims_by_gws);}};}};@@ -160,14 +160,12 @@ protected:class GroupNormalizationRefImpl : public PrimitiveImplOCL {public:DECLARE_OBJECT_TYPE_SERIALIZATION(ov::intel_gpu::ocl::GroupNormalizationRefImpl)- Stage::Ptr calc_mean = make_stage<GroupNormalizationGeneratorCalcMeanRef>();- Stage::Ptr calc_mean_std = make_stage<GroupNormalizationGeneratorCalcStd>();+ Stage::Ptr calc_stats = make_stage<GroupNormalizationGeneratorCalcStats>();Stage::Ptr normalize = make_stage<GroupNormalizationGeneratorNormalize>();GroupNormalizationRefImpl() : PrimitiveImplOCL(GroupNormalizationRef::get_type_info_static()) {}GroupNormalizationRefImpl(const program_node& node, const RuntimeParams& params) : GroupNormalizationRefImpl() {- add_stage(calc_mean, params);- add_stage(calc_mean_std, params);+ add_stage(calc_stats, params);add_stage(normalize, params);}@@ -178,7 +176,9 @@ public:[[nodiscard]] std::vector<BufferDescriptor> get_internal_buffer_descs(const RuntimeParams& params) const override {auto desc = params.typed_desc<group_normalization>();// Use get_max_shape() for upper bounded dynamic shape. This is not called for non upper bounded dynamic shape.- size_t batch = params.output_layouts[0].get_partial_shape().get_max_shape()[0];+ // Batch is at least 1 because calc_stats runs one batch even when the batch is empty.+ const size_t batch = std::max<size_t>(params.output_layouts[0].get_partial_shape().get_max_shape()[0], 1);+ // mean and 1 / sqrt(variance + epsilon) per (batch, group)auto buf = BufferDescriptor{batch * static_cast<size_t>(desc->num_groups), ov::element::f32};return {buf, buf};}diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/group_normalization_ref.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/group_normalization_ref.hppindex a21226399b8..889a658c65b 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/group_normalization_ref.hpp+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/group_normalization_ref.hpp@@ -4,12 +4,15 @@#pragma once+#include <algorithm>+#include <array>#include <memory>#include <utility>#include "group_normalization_base.hpp"#include "intel_gpu/primitives/activation.hpp"#include "intel_gpu/primitives/eltwise.hpp"+#include "intel_gpu/primitives/reorder.hpp"#include "program_node.h"#include "registry/implementation_manager.hpp"@@ -19,10 +22,10 @@ namespace ov::intel_gpu::ocl {struct GroupNormalizationRef : public GroupNormalizationBase {OV_GPU_PRIMITIVE_IMPL("ocl::group_norm::ref")explicit GroupNormalizationRef(shape_types shape_type, ValidateFunc vf = nullptr) : GroupNormalizationBase(shape_type, std::move(vf)) {}- std::unique_ptr<primitive_impl> create_impl(const program_node& node, const RuntimeParams& params) const override;+ [[nodiscard]] std::unique_ptr<primitive_impl> create_impl(const program_node& node, const RuntimeParams& params) const override;[[nodiscard]] bool validate_impl(const program_node& node) const override {- static constexpr std::array supported_fmts = {format::bfyx, format::bfzyx, format::b_fs_yx_fsv16};-+ // GroupNormalization-12 defines data, scale, bias and output as floating point types.+ // Scale and bias may have a different floating point type from data.static constexpr std::array supported_types = {ov::element::f32,ov::element::f16,@@ -30,15 +33,52 @@ struct GroupNormalizationRef : public GroupNormalizationBase {const auto& in0_layout = node.get_input_layout(0);const auto& out_layout = node.get_output_layout(0);- if (!one_of(in0_layout.format, supported_fmts) || !one_of(out_layout.format, supported_fmts)) {+ const auto& in0_pshape = in0_layout.get_partial_shape();+ if (in0_pshape.rank().is_dynamic() || in0_pshape.size() < 2 || in0_pshape.size() > 6) {+ return false;+ }++ // The kernel picks the number of index arguments from the rank, so the format dimension must match it.+ const size_t fmt_dims = std::max<size_t>(in0_pshape.size(), 4);+ if (!is_supported_format(in0_layout.format, fmt_dims) || !is_supported_format(out_layout.format, fmt_dims)) {return false;}- if (!one_of(in0_layout.data_type, supported_types) || !one_of(out_layout.data_type, supported_types)) {+ // Only data, scale and bias. The dependencies of fused ops follow them and are converted by the fused ops code.+ for (size_t i = 0; i < node.get_primitive()->input_size(); i++) {+ if (!one_of(node.get_input_layout(i).data_type, supported_types)) {+ return false;+ }+ }+ if (!one_of(out_layout.data_type, supported_types)) {return false;}- return fused_ops_are_one_of<eltwise, activation>(node.get_fused_primitives());+ // The kernel computes buffer offsets in 32 bits. Dynamic shapes cannot be checked here and share this limit.+ constexpr size_t max_elements = size_t{1} << 32;+ for (const auto* l : {&in0_layout, &out_layout}) {+ if (l->is_static() && l->get_linear_size() >= max_elements) {+ return false;+ }+ }++ return fused_ops_are_one_of<eltwise, activation, reorder>(node.get_fused_primitives());+ }++private:+ // The kernel indexes through the GET_INDEX macros, so it works for other simple and blocked formats whose+ // dimension matches the rank. But format propagation keeps a node in any format some impl accepts. Accepting+ // formats the opt impls reject would make this ref replace their reorder + opt path, so only the formats of the+ // opt impls (plus rank 6) are accepted.+ static bool is_supported_format(const format& fmt, size_t dims) {+ static constexpr std::array supported_fmts = {+ format::bfyx,+ format::bfzyx,+ format::bfwzyx,+ format::b_fs_yx_fsv16,+ };++ return fmt.dimension() == dims && one_of(fmt, supported_fmts);}};diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/utils/jitter.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/utils/jitter.cppindex 46cc9d02b10..dcf02f72122 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/utils/jitter.cpp+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/utils/jitter.cpp@@ -504,7 +504,7 @@ JitConstants make_indexing_jit_functions(const std::string& name, const layout&const JitTerm f_size{to_code_string(l.feature())};const JitTerm f{"(f)"};if (l.data_padding && simple_format) {- const JitTerm f_pitch{to_code_string(0 /* _tensor.Feature().pitch */)};+ const JitTerm f_pitch{name + "_FEATURE_PITCH"};safe_index_func_val = offset + (f % f_size) * f_pitch;index_func_val = offset + (f * f_pitch);} else if (!l.data_padding && !format::is_multi_blocked(fmt)) {diff --git a/src/plugins/intel_gpu/src/graph/registry/group_normalization_impls.cpp b/src/plugins/intel_gpu/src/graph/registry/group_normalization_impls.cppindex 89d646343f6..4b852dbe184 100644--- a/src/plugins/intel_gpu/src/graph/registry/group_normalization_impls.cpp+++ b/src/plugins/intel_gpu/src/graph/registry/group_normalization_impls.cpp@@ -20,7 +20,7 @@ const std::vector<std::shared_ptr<cldnn::ImplementationManager>>& Registry<groupstatic const std::vector<std::shared_ptr<ImplementationManager>> impls = {OV_GPU_CREATE_INSTANCE_OCL(ocl::GroupNormalizationFsv16Opt, shape_types::any)OV_GPU_CREATE_INSTANCE_OCL(ocl::GroupNormalizationBfyxOpt, shape_types::any)- OV_GPU_CREATE_INSTANCE_OCL(ocl::GroupNormalizationRef, shape_types::static_shape)+ OV_GPU_CREATE_INSTANCE_OCL(ocl::GroupNormalizationRef, shape_types::any)};return impls;diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/group_normalization_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/group_normalization_gpu_test.cppindex b0cdcc81ffd..a271daf678b 100644--- a/src/plugins/intel_gpu/tests/unit/test_cases/group_normalization_gpu_test.cpp+++ b/src/plugins/intel_gpu/tests/unit/test_cases/group_normalization_gpu_test.cpp@@ -16,8 +16,11 @@#include "intel_gpu/primitives/activation.hpp"#include "openvino/reference/group_normalization.hpp"#include "intel_gpu/runtime/compilation_context.hpp"+#include "ocl_v2/group_normalization_ref.hpp"+#include "ocl_v2/primitive_ocl_base.hpp"#include <algorithm>+#include <tuple>using namespace cldnn;@@ -622,3 +625,468 @@ TEST(group_normalization, basic_b_fs_yx_fsv16_fused_eltwise_sum_relu) {ASSERT_NEAR(static_cast<float>(output_mem_lock[i]), expected, 0.05) << "at index " << i;}}++// group_normalization_ref tests.+// The registry tries fsv16_opt and bfyx_opt before ref. Each case gets ref in one of two ways:+// - natural: the input is rejected by both opt impls (bfwzyx, or b_fs_yx_fsv16 with feature lower padding not a+// multiple of 16), so ref is selected. Works for static and dynamic.+// - swap (static only): the impl selected by the network is replaced by the ref impl.+namespace {++// sum_i32: the second eltwise input is i32, a type gn itself does not accept.+enum class gn_fused { none, relu, sum, sum_relu, sum_i32 };+// Input values. large_mean: uniform in [999, 1001]. constant: every value is 1000.1, so the variance is 0.+// large_constant: every value is 99999.9. large_alternating: 99999.8 and 100000.0 alternate, so the variance is+// about 0.01 and is lost if the first-pass mean drifts.+// All make the f32 rounding error of the first-pass mean visible.+enum class gn_dist { uniform, large_mean, constant, large_constant, large_alternating };++struct gn_ref_params {+ std::string name;+ std::vector<std::vector<int64_t>> shapes; // Static: shapes[0]. Dynamic: executed in order, with C fixed.+ int64_t groups;+ format fmt;+ padding in_pad;+ padding out_pad;+ data_types in_dt;+ data_types sb_dt; // scale and bias+ data_types out_dt;+ bool dynamic;+ bool swap;+ bool rank1_sb; // scale and bias of shape [C] instead of [1, C, 1, 1]+ gn_fused fused;+ gn_dist dist;+};++// Values exactly representable in dt, so the f32 reference sees the same input as the kernel.+std::vector<float> gn_ref_values(tests::random_generator& rg, size_t count, data_types dt, float lo, float hi) {+ auto values = rg.generate_random_1d<float>(count, lo, hi);+ for (auto& v : values) {+ if (dt == data_types::f16) {+ v = static_cast<float>(ov::float16(v));+ }+ }+ return values;+}++// Converts any layout (blocked, padded, f16 or f32) to a plain f32 vector.+std::vector<float> gn_ref_read_plain_f32(memory::ptr mem) {+ auto& engine = get_test_engine();+ const auto& l = mem->get_layout();+ topology tp(input_layout("in", l), reorder("out", input_info("in"), format::get_default_format(l.get_rank()), data_types::f32));+ auto config = get_test_default_config(engine);+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));+ network net(engine, tp, config);+ net.set_input_data("in", mem);+ auto out = net.execute().at("out").get_memory();+ cldnn::mem_lock<float, mem_lock_type::read> ptr(out, get_test_stream());+ return std::vector<float>(ptr.begin(), ptr.end());+}++// The gn node can be renamed when a user is fused into it, so look it up by type.+std::shared_ptr<primitive_inst> gn_ref_find_inst(network& net) {+ for (const auto& id : net.get_all_primitive_ids()) {+ if (id != "_optimized_" && net.get_primitive(id)->type() == group_normalization::type_id()) {+ return net.get_primitive(id);+ }+ }+ return nullptr;+}++// Replaces the impl of a static gn with the ref impl.+void gn_ref_swap_impl(network& net, primitive_inst& inst) {+ ov::intel_gpu::ocl::GroupNormalizationRef ref_manager(shape_types::any);+ ASSERT_TRUE(ref_manager.validate(inst.get_node()));+ const auto params = *inst.get_impl_params();+ auto ref_impl = ref_manager.create(inst.get_node(), params);+ ASSERT_NE(ref_impl, nullptr);+ ref_impl->set_kernels(net.get_program()->get_kernels_cache().compile(params, ref_impl->get_kernels_source()));+ inst.set_impl(std::move(ref_impl));+ // The internal buffers of the previous impl have a different size.+ inst.allocate_internal_buffers();+ inst.set_arguments();+}++// The executed impl is ref, and every stage dispatches uniform work-groups within the device limit.+void gn_ref_check_dispatch(primitive_inst& inst) {+ ASSERT_NE(inst.get_impl(), nullptr);+ ASSERT_NE(inst.get_impl()->get_type_info().find("GroupNormalizationRefImpl"), std::string::npos) << inst.get_impl()->get_type_info();+ auto impl = dynamic_cast<ov::intel_gpu::ocl::PrimitiveImplOCL*>(inst.get_impl());+ ASSERT_NE(impl, nullptr);+ const size_t max_wg = inst.get_network().get_engine().get_device_info().max_work_group_size;+ for (size_t s = 0; s < impl->_stages.size(); s++) {+ const auto& wgs = impl->_stages[s]->kd.params.workGroups;+ ASSERT_EQ(wgs.global.size(), 3u);+ ASSERT_EQ(wgs.local.size(), 3u);+ size_t wg_size = 1;+ for (size_t i = 0; i < wgs.global.size(); i++) {+ ASSERT_NE(wgs.local[i], 0u) << "stage " << s << " axis " << i;+ ASSERT_EQ(wgs.global[i] % wgs.local[i], 0u) << "stage " << s << " axis " << i << ": gws=" << wgs.global[i] << " lws=" << wgs.local[i];+ wg_size *= wgs.local[i];+ }+ ASSERT_LE(wg_size, max_wg) << "stage " << s;+ }+}++class group_normalization_ref_gpu_test : public ::testing::TestWithParam<gn_ref_params> {};++TEST_P(group_normalization_ref_gpu_test, accuracy) {+ const auto& p = GetParam();+ auto& engine = get_test_engine();+ const float epsilon = 0.0025f;+ const size_t rank = p.shapes[0].size();+ const int64_t channels = p.shapes[0][1];+ const auto plain_fmt = format::get_default_format(rank);+ const bool has_sum = p.fused == gn_fused::sum || p.fused == gn_fused::sum_relu || p.fused == gn_fused::sum_i32;+ const auto eltw_dt = p.fused == gn_fused::sum_i32 ? data_types::i32 : data_types::f32;+ const bool has_relu = p.fused == gn_fused::relu || p.fused == gn_fused::sum_relu;+ ASSERT_TRUE(!p.dynamic || !p.swap) << "swap works only for static shapes";++ const auto data_pshape = p.dynamic ? ov::PartialShape::dynamic(rank) : ov::PartialShape(p.shapes[0]);+ const layout sb_layout{p.rank1_sb ? ov::PartialShape{channels} : ov::PartialShape{1, channels, 1, 1}, data_types::f32, format::bfyx};++ topology tp;+ tp.add(input_layout{"data", layout{data_pshape, data_types::f32, plain_fmt}});+ tp.add(input_layout{"scale", sb_layout});+ tp.add(input_layout{"bias", sb_layout});+ // gn receives the input in fmt / in_dt / in_pad.+ tp.add(reorder{"data_r", input_info("data"), layout{ov::PartialShape(p.shapes[0]), p.in_dt, p.fmt, p.in_pad}});+ input_info scale_in("scale");+ input_info bias_in("bias");+ if (p.sb_dt != data_types::f32) {+ tp.add(reorder{"scale_r", scale_in, format::bfyx, p.sb_dt});+ tp.add(reorder{"bias_r", bias_in, format::bfyx, p.sb_dt});+ scale_in = input_info("scale_r");+ bias_in = input_info("bias_r");+ }+ group_normalization gn{"gn", input_info("data_r"), scale_in, bias_in, p.groups, epsilon};+ if (p.out_dt != p.in_dt) {+ gn.output_data_types = {optional_data_type{p.out_dt}};+ }+ gn.output_paddings = {p.out_pad};+ tp.add(gn);+ primitive_id last = "gn";+ if (has_sum) {+ tp.add(input_layout{"eltw", layout{data_pshape, eltw_dt, plain_fmt}});+ tp.add(eltwise{"sum", {input_info(last), input_info("eltw")}, eltwise_mode::sum});+ last = "sum";+ }+ if (has_relu) {+ tp.add(activation{"relu", input_info(last), activation_func::relu});+ last = "relu";+ }+ if (p.fused != gn_fused::none) {+ // A network output is not fused into its producer, so the fused chain needs a user.+ tp.add(reorder{"output", input_info(last), plain_fmt, data_types::f32});+ }++ auto config = get_test_default_config(engine);+ // Post-op fusion and the dynamic flow need optimize_data. Ranks other than 4/5 and rank-1 scale need the new shape infer.+ config.set_property(ov::intel_gpu::optimize_data(p.dynamic || p.fused != gn_fused::none));+ if (p.dynamic || p.rank1_sb || rank < 4 || rank > 5) {+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));+ }+ network net(engine, tp, config);++ auto inst = gn_ref_find_inst(net);+ ASSERT_NE(inst, nullptr);+ const auto in_l = inst->get_input_layout(0);+ ASSERT_EQ(in_l.format, p.fmt);+ ASSERT_EQ(in_l.data_type, p.in_dt);+ ASSERT_EQ(in_l.data_padding, p.in_pad);+ ASSERT_EQ(inst->get_node().get_fused_primitives().size(), static_cast<size_t>(has_sum) + static_cast<size_t>(has_relu));+ if (p.swap) {+ ASSERT_NO_FATAL_FAILURE(gn_ref_swap_impl(net, *inst));+ }++ tests::random_generator rg{"group_normalization_ref_gpu_test_" + p.name};+ const auto scale = gn_ref_values(rg, channels, p.sb_dt, -1.0f, 1.0f);+ const auto bias = gn_ref_values(rg, channels, p.sb_dt, -0.5f, 0.5f);+ auto scale_mem = engine.allocate_memory(sb_layout);+ auto bias_mem = engine.allocate_memory(sb_layout);+ set_values(scale_mem, scale);+ set_values(bias_mem, bias);++ for (const auto& dims : p.shapes) {+ const ov::Shape shape(dims.begin(), dims.end());+ const size_t count = ov::shape_size(shape);+ ASSERT_EQ(dims[1], channels);+ std::vector<float> data;+ if (p.dist == gn_dist::large_mean) {+ data = gn_ref_values(rg, count, p.in_dt, 999.0f, 1001.0f);+ } else if (p.dist == gn_dist::constant) {+ data.assign(count, 1000.1f);+ } else if (p.dist == gn_dist::large_constant) {+ data.assign(count, 99999.9f);+ } else if (p.dist == gn_dist::large_alternating) {+ data.resize(count);+ for (size_t i = 0; i < count; i++) {+ data[i] = i % 2 == 0 ? 99999.8f : 100000.0f;+ }+ } else {+ data = gn_ref_values(rg, count, p.in_dt, -1.0f, 1.0f);+ }+ const float eltw_range = eltw_dt == data_types::i32 ? 3.0f : 1.0f;+ auto eltw = rg.generate_random_1d<float>(has_sum ? count : 0, -eltw_range, eltw_range);+ if (eltw_dt == data_types::i32) {+ std::transform(eltw.begin(), eltw.end(), eltw.begin(), [](float v) {+ return std::round(v);+ });+ }++ const layout data_l{shape, data_types::f32, plain_fmt};+ auto data_mem = engine.allocate_memory(data_l);+ set_values(data_mem, data);+ net.set_input_data("data", data_mem);+ net.set_input_data("scale", scale_mem);+ net.set_input_data("bias", bias_mem);+ if (has_sum) {+ auto eltw_mem = engine.allocate_memory(layout{shape, eltw_dt, plain_fmt});+ if (eltw_dt == data_types::i32) {+ set_values(eltw_mem, std::vector<int32_t>(eltw.begin(), eltw.end()));+ } else {+ set_values(eltw_mem, eltw);+ }+ net.set_input_data("eltw", eltw_mem);+ }+ net.execute();+ net.get_stream().finish();+ // The runtime skips a primitive with an empty output and keeps its previous output memory and dispatch.+ // The empty run only has to execute, and the next run has to be correct.+ if (count == 0) {+ continue;+ }+ // Read the gn output itself, which includes the fused ops.+ auto out_mem = inst->output_memory_ptr();++ const auto& out_l = out_mem->get_layout();+ ASSERT_EQ(out_l.format, p.fmt);+ ASSERT_EQ(out_l.data_type, p.out_dt);+ ASSERT_EQ(out_l.data_padding, p.out_pad);+ ASSERT_EQ(out_l.get_shape(), shape);+ ASSERT_NO_FATAL_FAILURE(gn_ref_check_dispatch(*inst));++ std::vector<float> expected(count);+ ov::reference::group_normalization(data.data(), scale.data(), bias.data(), expected.data(), shape, p.groups, epsilon);+ for (size_t i = 0; i < count; i++) {+ if (has_sum) {+ expected[i] += eltw[i];+ }+ if (has_relu) {+ expected[i] = std::max(expected[i], 0.0f);+ }+ }+ const float tolerance = p.out_dt == data_types::f16 ? 0.02f : 2e-4f;++ const auto actual = gn_ref_read_plain_f32(out_mem);+ ASSERT_EQ(actual.size(), count);+ for (size_t i = 0; i < count; i++) {+ ASSERT_NEAR(actual[i], expected[i], tolerance) << "shape " << shape << " i=" << i;+ }+ }+}++const auto dt_f32 = data_types::f32;+const auto dt_f16 = data_types::f16;+// Feature lower padding is not a multiple of 16, so fsv16_opt rejects b_fs_yx_fsv16.+const padding fsv16_odd_pad({0, 1, 1, 2}, {0, 3, 2, 1});++// clang-format off+const std::vector<gn_ref_params> gn_ref_cases = {+ // name, shapes, G, fmt, in_pad, out_pad, in_dt, sb_dt, out_dt, dynamic, swap, rank1_sb, fused, dist+ // Static, swap: formats and inputs that an opt impl accepts.+ {"bfyx_f32", {{2, 32, 5, 7}}, 4, format::bfyx, padding(), padding(), dt_f32, dt_f32, dt_f32, false, true, false, gn_fused::none, gn_dist::uniform},+ {"bfyx_f16_g1_odd_spatial", {{2, 16, 9, 7}}, 1, format::bfyx, padding(), padding(), dt_f16, dt_f16, dt_f16, false, true, false, gn_fused::none, gn_dist::uniform},+ {"bfyx_g_eq_c_n_lt_lws", {{3, 24, 3, 5}}, 24, format::bfyx, padding(), padding(), dt_f32, dt_f16, dt_f32, false, true, false, gn_fused::none, gn_dist::uniform},+ // 1M elements per group: the f32 sum of the first pass has a large rounding error.+ {"bfyx_large_n_large_mean", {{1, 16, 256, 256}}, 1, format::bfyx, padding(), padding(), dt_f32, dt_f32, dt_f32, false, true, false, gn_fused::none, gn_dist::large_mean},+ {"bfyx_large_n_constant", {{1, 16, 256, 256}}, 1, format::bfyx, padding(), padding(), dt_f32, dt_f32, dt_f32, false, true, false, gn_fused::none, gn_dist::constant},+ // 4M elements per group: the plain f32 sum of the deviations also has a large rounding error.+ {"bfyx_4m_large_constant", {{1, 16, 512, 512}}, 1, format::bfyx, padding(), padding(), dt_f32, dt_f32, dt_f32, false, true, false, gn_fused::none, gn_dist::large_constant},+ // 4M elements per group: the plain f32 sum of the first pass drifts, and the variance cancels without the Kahan sum.+ {"bfwzyx_4m_large_alternating", {{1, 16, 1, 1, 512, 512}}, 1, format::bfwzyx, padding(), padding(), dt_f32, dt_f32, dt_f32, false, true, false, gn_fused::none, gn_dist::large_alternating},+ {"bfyx_spatial_pad_1x32x1x1", {{1, 32, 1, 1}}, 8, format::bfyx, padding({0, 0, 1, 2}, {0, 0, 2, 1}), padding(), dt_f32, dt_f32, dt_f32, false, true, false, gn_fused::none, gn_dist::uniform},+ {"bfyx_rank2_feature_pad", {{1, 40}}, 5, format::bfyx, padding({0, 2}, {0, 3}), padding(), dt_f32, dt_f32, dt_f32, false, true, true, gn_fused::none, gn_dist::uniform},+ {"bfzyx_f32_out_pad", {{2, 16, 3, 5, 7}}, 4, format::bfzyx, padding(), padding({0, 0, 1, 0, 1}, {0, 0, 0, 2, 0}), dt_f32, dt_f32, dt_f32, false, true, false, gn_fused::none, gn_dist::uniform},+ {"bfzyx_f16_in_pad_fused_relu", {{1, 32, 4, 3, 5}}, 8, format::bfzyx, padding({0, 0, 1, 1, 0}, {0, 0, 0, 1, 2}), padding(), dt_f16, dt_f32, dt_f16, false, true, false, gn_fused::relu, gn_dist::uniform},+ {"fsv16_f16", {{3, 48, 6, 6}}, 6, format::b_fs_yx_fsv16, padding(), padding(), dt_f16, dt_f16, dt_f16, false, true, false, gn_fused::none, gn_dist::uniform},+ {"bfyx_batch_pad_f16_to_f32", {{3, 24, 5, 5}}, 3, format::bfyx, padding({1, 0, 0, 0}, {2, 0, 0, 0}), padding(), dt_f16, dt_f32, dt_f32, false, true, false, gn_fused::none, gn_dist::uniform},+ {"rank3_bfyx_f16", {{4, 40, 33}}, 8, format::bfyx, padding(), padding(), dt_f16, dt_f16, dt_f16, false, true, true, gn_fused::none, gn_dist::uniform},+ // Static, natural selection.+ {"fsv16_odd_pad_f32", {{1, 64, 4, 4}}, 32, format::b_fs_yx_fsv16, fsv16_odd_pad, padding(), dt_f32, dt_f32, dt_f32, false, false, false, gn_fused::none, gn_dist::uniform},+ {"fsv16_odd_pad_f16_sum_relu", {{1, 64, 4, 4}}, 32, format::b_fs_yx_fsv16, fsv16_odd_pad, padding(), dt_f16, dt_f16, dt_f16, false, false, false, gn_fused::sum_relu, gn_dist::uniform},+ {"rank3_fsv16_feature_pad_f16_to_f32", {{2, 40, 33}}, 8, format::b_fs_yx_fsv16, padding({0, 3, 0, 0}, {0, 1, 0, 0}), padding(), dt_f16, dt_f32, dt_f32, false, false, false, gn_fused::none, gn_dist::uniform},+ {"rank6_f32_rank1_f16_sb_sum_relu", {{2, 24, 3, 4, 5, 6}}, 6, format::bfwzyx, padding(), padding(), dt_f32, dt_f16, dt_f32, false, false, true, gn_fused::sum_relu, gn_dist::uniform},+ // The fused eltwise input is i32. validate must not check the dependencies of fused ops.+ {"rank6_f32_fused_sum_i32", {{2, 24, 2, 2, 2, 2}}, 6, format::bfwzyx, padding(), padding(), dt_f32, dt_f32, dt_f32, false, false, false, gn_fused::sum_i32, gn_dist::uniform},+ // Dynamic, natural selection. Executed once per shape. Dynamic bfyx/bfzyx always go to bfyx_opt.+ {"dyn_fsv16_odd_pad_large_mean", {{2, 64, 8, 8}, {1, 64, 16, 16}, {3, 64, 5, 7}}, 4, format::b_fs_yx_fsv16, fsv16_odd_pad, padding(), dt_f32, dt_f32, dt_f32, true, false, false, gn_fused::none, gn_dist::large_mean},+ // B grows (internal buffers are reallocated), and B * G = 1056 > max_wg in the last run.+ {"dyn_fsv16_odd_pad_f16_sum_relu_b33_g32", {{17, 64, 3, 3}, {4, 64, 5, 5}, {33, 64, 4, 4}}, 32, format::b_fs_yx_fsv16, fsv16_odd_pad, padding(), dt_f16, dt_f16, dt_f16, true, false, false, gn_fused::sum_relu, gn_dist::uniform},+ {"dyn_fsv16_odd_pad_f32_to_f16_g_eq_c", {{2, 16, 3, 3}, {5, 16, 1, 7}}, 16, format::b_fs_yx_fsv16, fsv16_odd_pad, padding(), dt_f32, dt_f16, dt_f16, true, false, false, gn_fused::none, gn_dist::uniform},+ {"dyn_rank3_fsv16_feature_pad_f16_to_f32", {{2, 40, 17}, {3, 40, 9}}, 8, format::b_fs_yx_fsv16, padding({0, 3, 0, 0}, {0, 1, 0, 0}), padding(), dt_f16, dt_f32, dt_f32, true, false, false, gn_fused::none, gn_dist::uniform},+ {"dyn_rank2_fsv16_feature_pad_rank1_sb_relu", {{3, 40}, {7, 40}}, 8, format::b_fs_yx_fsv16, padding({0, 3, 0, 0}, {0, 1, 0, 0}), padding(), dt_f32, dt_f32, dt_f32, true, false, true, gn_fused::relu, gn_dist::uniform},+ // Empty batch in the middle run.+ {"dyn_rank6_f16_empty_batch", {{2, 24, 2, 2, 3, 3}, {0, 24, 2, 2, 3, 3}, {3, 24, 1, 2, 3, 4}}, 6, format::bfwzyx, padding(), padding(), dt_f16, dt_f16, dt_f16, true, false, false, gn_fused::none, gn_dist::uniform},+ {"dyn_rank6_f16_to_f32_g1", {{2, 12, 2, 3, 3, 5}, {3, 12, 1, 2, 3, 4}}, 1, format::bfwzyx, padding(), padding(), dt_f16, dt_f32, dt_f32, true, false, false, gn_fused::none, gn_dist::uniform},+};+// clang-format on++INSTANTIATE_TEST_SUITE_P(group_normalization_ref,+ group_normalization_ref_gpu_test,+ ::testing::ValuesIn(gn_ref_cases),+ [](const ::testing::TestParamInfo<gn_ref_params>& info) {+ return info.param.name;+ });++// Builds a gn node with the given input layout and data types, and returns whether the ref impl accepts it.+bool gn_ref_validate(const ov::PartialShape& shape, format fmt, data_types in_dt, data_types sb_dt, data_types out_dt) {+ auto& engine = get_test_engine();+ const layout in_l{shape, in_dt, fmt};+ const layout sb_l{ov::PartialShape{1, shape[1], 1, 1}, sb_dt, format::bfyx};+ program prog(engine);+ auto& data_node = prog.get_or_create(std::make_shared<input_layout>("data", in_l));+ auto& scale_node = prog.get_or_create(std::make_shared<input_layout>("scale", sb_l));+ auto& bias_node = prog.get_or_create(std::make_shared<input_layout>("bias", sb_l));+ auto gn = std::make_shared<group_normalization>("gn", input_info("data"), input_info("scale"), input_info("bias"), 8, 1e-5);+ gn->output_data_types = {optional_data_type{out_dt}};+ auto& gn_node = prog.get_or_create(gn);+ program_wrapper::add_connection(prog, data_node, gn_node);+ program_wrapper::add_connection(prog, scale_node, gn_node);+ program_wrapper::add_connection(prog, bias_node, gn_node);+ gn_node.recalc_output_layout();+ EXPECT_EQ(gn_node.get_output_layout().format, fmt);+ EXPECT_EQ(gn_node.get_output_layout().data_type, out_dt);++ ov::intel_gpu::ocl::GroupNormalizationRef ref_manager(shape_types::any);+ return ref_manager.validate(gn_node);+}++// The kernel handles blocked formats, but validate accepts only the formats of the opt impls (plus bfwzyx).+// Otherwise format propagation keeps gn in a blocked format and ref replaces the reorder + opt impl path.+TEST(group_normalization_ref, validate_formats) {+ const std::vector<std::tuple<ov::PartialShape, format, bool>> cases = {+ {{2, 32, 4, 4}, format::bfyx, true},+ {{2, 32, 4, 4}, format::b_fs_yx_fsv16, true},+ {{2, 32, 4, 4}, format::bs_fs_yx_bsv32_fsv16, false},+ {{2, 32, 4, 4}, format::b_fs_yx_fsv32, false},+ {{2, 32, 4, 4}, format::byxf, false},+ {{2, 32, 3, 4, 4}, format::bfzyx, true},+ {{2, 32, 3, 4, 4}, format::b_fs_zyx_fsv16, false},+ {{2, 32, 2, 3, 4, 4}, format::bfwzyx, true},+ // The format dimension does not match the rank.+ {{2, 32, 4, 4}, format::bfzyx, false},+ };+ for (const auto& [shape, fmt, expected] : cases) {+ EXPECT_EQ(gn_ref_validate(shape, fmt, data_types::f16, data_types::f16, data_types::f16), expected) << shape << " " << fmt;+ }+}++// GroupNormalization-12 defines data, scale, bias and output as floating point types.+// validate accepts f16 and f32 for each of them, and scale/bias may differ from data.+TEST(group_normalization_ref, validate_data_types) {+ const auto f32 = data_types::f32;+ const auto f16 = data_types::f16;+ const auto i8 = data_types::i8;+ const auto u8 = data_types::u8;+ // in, scale/bias, out, expected+ const std::vector<std::tuple<data_types, data_types, data_types, bool>> cases = {+ {f32, f32, f32, true},+ {f16, f16, f16, true},+ {f16, f32, f16, true},+ {f32, f16, f32, true},+ {f16, f16, f32, true},+ {i8, f16, f16, false},+ {u8, f32, f32, false},+ {f16, i8, f16, false},+ {f32, u8, f32, false},+ {f16, f16, i8, false},+ {f32, f32, u8, false},+ };+ for (const auto& [in_dt, sb_dt, out_dt, expected] : cases) {+ EXPECT_EQ(gn_ref_validate({2, 32, 4, 4}, format::bfyx, in_dt, sb_dt, out_dt), expected) << in_dt << " " << sb_dt << " " << out_dt;+ }+}++} // anonymous namespace++// Static simple-format input whose element count equals its feature count, with padding.+// The jitter emits a special <NAME>_GET_INDEX for this case, which must still honor the padding.+namespace {+struct gn_padded_per_channel_case {+ std::string name;+ std::vector<int64_t> shape;+ int64_t groups;+ padding in_pad;+};++class group_normalization_padded_per_channel_input : public ::testing::TestWithParam<gn_padded_per_channel_case> {};++TEST_P(group_normalization_padded_per_channel_input, bfyx_opt) {+ const auto& c = GetParam();+ auto& engine = get_test_engine();+ const float epsilon = 0.0025f;+ const int64_t channels = c.shape[1];+ const auto plain_fmt = format::get_default_format(c.shape.size());+ const ov::Shape shape(c.shape.begin(), c.shape.end());+ const size_t count = ov::shape_size(shape);+ const layout sb_layout{ov::PartialShape{1, channels, 1, 1}, data_types::f32, format::bfyx};++ topology tp;+ tp.add(input_layout{"data", layout{shape, data_types::f32, plain_fmt}});+ tp.add(input_layout{"scale", sb_layout});+ tp.add(input_layout{"bias", sb_layout});+ tp.add(reorder{"data_r", input_info("data"), layout{shape, data_types::f32, format::bfyx, c.in_pad}});+ tp.add(group_normalization{"gn", input_info("data_r"), input_info("scale"), input_info("bias"), c.groups, epsilon});++ auto config = get_test_default_config(engine);+ config.set_property(ov::intel_gpu::optimize_data(false));+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));+ network net(engine, tp, config);++ auto inst = net.get_primitive("gn");+ ASSERT_EQ(inst->get_input_layout(0).data_padding, c.in_pad);+ const std::string impl = inst->get_impl()->get_type_info();+ ASSERT_NE(impl.find("GroupNormalizationBfyxOptImpl"), std::string::npos) << impl;++ tests::random_generator rg{"gn_padded_per_channel_" + c.name};+ auto data = rg.generate_random_1d<float>(count, -1.0f, 1.0f);+ auto scale = rg.generate_random_1d<float>(channels, -1.0f, 1.0f);+ auto bias = rg.generate_random_1d<float>(channels, -0.5f, 0.5f);+ auto data_mem = engine.allocate_memory(layout{shape, data_types::f32, plain_fmt});+ auto scale_mem = engine.allocate_memory(sb_layout);+ auto bias_mem = engine.allocate_memory(sb_layout);+ set_values(data_mem, data);+ set_values(scale_mem, scale);+ set_values(bias_mem, bias);+ net.set_input_data("data", data_mem);+ net.set_input_data("scale", scale_mem);+ net.set_input_data("bias", bias_mem);+ auto out_mem = net.execute().at("gn").get_memory();+ ASSERT_FALSE(static_cast<bool>(out_mem->get_layout().data_padding));++ std::vector<float> expected(count);+ ov::reference::group_normalization(data.data(), scale.data(), bias.data(), expected.data(), shape, c.groups, epsilon);+ cldnn::mem_lock<float, mem_lock_type::read> actual(out_mem, get_test_stream());+ size_t bad = 0;+ float max_err = 0.0f;+ for (size_t i = 0; i < count; i++) {+ const float err = std::fabs(actual[i] - expected[i]);+ max_err = std::max(max_err, err);+ // Same as err > 2e-4f, but also counts NaN as bad: a comparison with NaN is always false.+ bad += !(err <= 2e-4f);+ }+ EXPECT_EQ(bad, 0u) << "max_err=" << max_err;+}++INSTANTIATE_TEST_SUITE_P(smoke,+ group_normalization_padded_per_channel_input,+ ::testing::Values(gn_padded_per_channel_case{"b1_c32_spatial_pad", {1, 32, 1, 1}, 8, padding({0, 0, 1, 2}, {0, 0, 2, 1})},+ gn_padded_per_channel_case{"b1_c32_feature_pad", {1, 32, 1, 1}, 8, padding({0, 3, 0, 0}, {0, 1, 0, 0})},+ gn_padded_per_channel_case{"b1_c40_rank2_feature_pad", {1, 40}, 5, padding({0, 3}, {0, 1})},+ gn_padded_per_channel_case{"control_b2_c32_spatial_pad", {2, 32, 1, 1}, 8, padding({0, 0, 1, 2}, {0, 0, 2, 1})},+ gn_padded_per_channel_case{"control_b1_c32_no_pad", {1, 32, 1, 1}, 8, padding()}),+ [](const ::testing::TestParamInfo<gn_padded_per_channel_case>& info) {+ return info.param.name;+ });+} // namespace