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] sdpa_micro: saturate the folded attention mask to avoid NaN in fully masked rows (#39148)
Chon Ming Lee66e07dbdda5a
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_micro.cl b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_micro.clindex 8b1f964856c..2e500d026c8 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_micro.cl+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa_micro.cl@@ -640,13 +640,18 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARGfloat scale = native_recip(iscale);#endif#endif+ // Upper bound for a folded additive attention mask. exp2(scale * log2(e) * -MICRO_MASK_SAT) must still+ // flush to exactly 0 for small custom scales (holds for scale >= ~2e-35), while 2 * MICRO_MASK_SAT plus+ // any score stays far below FLT_MAX, so a fully masked row stays finite instead of becoming NaN.+#define MICRO_MASK_SAT 1.0e37f+#define sat_mask(x) clamp((x), -MICRO_MASK_SAT, MICRO_MASK_SAT)const float log2_e = 1.442695f;#if !defined(HAS_SINK_INPUT)#define LOG_2_E_MUL_SCALE 1scale *= log2_e;#endif#ifdef STATIC_SCALAR_ATTN_MASK_VALUE- float masked_scale = iscale * STATIC_SCALAR_ATTN_MASK_VALUE;+ float masked_scale = sat_mask(iscale * STATIC_SCALAR_ATTN_MASK_VALUE);#endif#ifdef HAS_SINK_INPUT#if IS_GQA_SINGLE_TOKEN@@ -1155,6 +1160,7 @@ KERNEL(micro_sdpa)(OPTIONAL_SHAPE_INFO_ARG#ifdef LOG_2_E_MUL_SCALE#define unscale(x) ((x)*iscale)tile_elementwise(mask_tile_float, unscale);+ tile_elementwise_s(mask_tile_float, sat_mask);#else#define scale(x) ((x)* scale)tile_elementwise(S_tile, scale);diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/sdpa_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/sdpa_gpu_test.cppindex 54ca68430f1..960031903b2 100644--- a/src/plugins/intel_gpu/tests/unit/test_cases/sdpa_gpu_test.cpp+++ b/src/plugins/intel_gpu/tests/unit/test_cases/sdpa_gpu_test.cpp@@ -737,6 +737,218 @@ INSTANTIATE_TEST_SUITE_P(sdpa_micro_prefetch_k_test::PrintToStringParamName);+enum class masked_row_check {+ mean_v, // the fill overflows once folded: uniform weights, i.e. the mean of all V rows+ softmax, // finite fill: softmax over all keys, the fill cancels out+ hull, // only finiteness and the convex hull of V+};++struct sdpa_mask_fill_params {+ data_types dt;+ float fill;+ bool use_micro;+ bool scalar_mask;+ masked_row_check masked_rows;+ float scale = 0.0f; // 0: default 1/sqrt(head_size)+};++class sdpa_mask_fill_test : public ::testing::TestWithParam<sdpa_mask_fill_params> {+public:+ static std::string PrintToStringParamName(const testing::TestParamInfo<sdpa_mask_fill_params>& info) {+ const auto& p = info.param;+ std::string fill;+ if (std::isinf(p.fill))+ fill = "neg_inf";+ else if (std::isnan(p.fill))+ fill = "nan";+ else+ fill = std::to_string(static_cast<int>(std::log10(-p.fill) * 100));+ return std::string(p.dt == data_types::bf16 ? "bf16" : "f16") + "_fill_" + fill + (p.use_micro ? "_micro" : "_opt") ++ (p.scalar_mask ? "_scalar_mask" : "_tensor_mask") + (p.scale != 0.0f ? "_custom_scale" : "");+ }++protected:+ template <typename T>+ void run(const sdpa_mask_fill_params& p) {+ auto& engine = get_test_engine();+ const auto& device_info = engine.get_device_info();+ if (p.use_micro && (!device_info.supports_immad || device_info.arch < cldnn::gpu_arch::xe_hpg))+ GTEST_SKIP() << "sdpa_micro requires a device with systolic (immad) support";++ const size_t heads = 2, seq_q = 48, seq_kv = 64, head_size = 256;+ const size_t valid_q = 32;+ const size_t valid_kv = 40;+ const ov::Shape q_shape{1, heads, seq_q, head_size};+ const ov::Shape kv_shape{1, heads, seq_kv, head_size};+ const ov::Shape mask_shape{1, 1, seq_q, seq_kv};++ const layout q_layout(q_shape, p.dt, format::bfyx);+ const layout kv_layout(kv_shape, p.dt, format::bfyx);+ const layout mask_layout(mask_shape, p.dt, format::bfyx);+ auto q_mem = engine.allocate_memory(q_layout);+ auto k_mem = engine.allocate_memory(kv_layout);+ auto v_mem = engine.allocate_memory(kv_layout);+ auto mask_mem = engine.allocate_memory(mask_layout);++ tests::random_generator rg;+ rg.set_seed(GET_SUITE_NAME);+ const auto q = rg.generate_random_1d<T>(ov::shape_size(q_shape), -1.0f, 1.0f);+ const auto k = rg.generate_random_1d<T>(ov::shape_size(kv_shape), -1.0f, 1.0f);+ const auto v = rg.generate_random_1d<T>(ov::shape_size(kv_shape), -1.0f, 1.0f);+ std::vector<T> mask(ov::shape_size(mask_shape));+ for (size_t i = 0; i < seq_q; ++i)+ for (size_t j = 0; j < seq_kv; ++j)+ mask[i * seq_kv + j] = (i >= valid_q || j >= valid_kv) ? T(p.fill) : T(0.0f);+ set_values(q_mem, q);+ set_values(k_mem, k);+ set_values(v_mem, v);+ set_values(mask_mem, mask);++ topology topo;+ topo.add(input_layout("q", q_layout));+ topo.add(input_layout("k", kv_layout));+ topo.add(input_layout("v", kv_layout));+ topo.add(input_layout("mask", mask_layout));+ auto sdpa_prim = scaled_dot_product_attention("sdpa",+ {input_info("q"), input_info("k"), input_info("v"), input_info("mask")},+ false, -1, {0, 1, 2, 3}, {0, 1, 2, 3}, {0, 1, 2, 3}, {0, 1, 2, 3}, {}, false);+ if (p.scalar_mask)+ sdpa_prim.attn_mask_val = p.fill;+ if (p.scale != 0.0f)+ sdpa_prim.scale_val = p.scale;+ topo.add(sdpa_prim);+ topo.add(reorder("result", input_info("sdpa"), format::bfyx, data_types::f32));++ ExecutionConfig config = get_test_default_config(engine);+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));+ config.set_property(ov::intel_gpu::enable_sdpa_micro(p.use_micro));+ auto network = get_network(engine, topo, config, get_test_stream_ptr(), false);+ network->set_input_data("q", q_mem);+ network->set_input_data("k", k_mem);+ network->set_input_data("v", v_mem);+ network->set_input_data("mask", mask_mem);+ auto output = network->execute().at("result").get_memory();++ // Make sure the kernel under test actually ran (the node description carries the entry point).+ std::string sdpa_info;+ for (const auto& info : network->get_primitives_info()) {+ if (info.type_id == "scaled_dot_product_attention")+ sdpa_info = network->get_primitive_info(info.original_id);+ }+ ASSERT_FALSE(sdpa_info.empty());+ if (p.use_micro) {+ ASSERT_NE(sdpa_info.find("sdpa_micro"), std::string::npos) << "sdpa_micro was not selected:\n" << sdpa_info;+ } else {+ ASSERT_EQ(sdpa_info.find("sdpa_micro"), std::string::npos) << "sdpa_micro was selected:\n" << sdpa_info;+ }++ cldnn::mem_lock<float, mem_lock_type::read> out(output, get_test_stream());+ ASSERT_EQ(out.size(), ov::shape_size(q_shape));++ const double scale = p.scale != 0.0f ? static_cast<double>(p.scale) : 1.0 / std::sqrt(static_cast<double>(head_size));+ const double tol = p.dt == data_types::bf16 ? 2e-2 : 4e-3;+ // Double reference on the rounded inputs: softmax(q.k * scale + mask) . V over the keys [0, keys_end),+ // or the plain mean of those V rows if uniform is set.+ auto check_row = [&](size_t h, size_t i, const float* o, size_t keys_end, bool uniform) {+ std::vector<double> s(keys_end, 0.0);+ if (!uniform) {+ double s_max = -std::numeric_limits<double>::infinity();+ for (size_t j = 0; j < keys_end; ++j) {+ double acc = 0.0;+ for (size_t d = 0; d < head_size; ++d)+ acc += static_cast<double>(q[(h * seq_q + i) * head_size + d]) * static_cast<double>(k[(h * seq_kv + j) * head_size + d]);+ const double m = p.scalar_mask ? static_cast<double>(p.fill) : static_cast<double>(static_cast<float>(mask[i * seq_kv + j]));+ s[j] = acc * scale + m;+ s_max = std::max(s_max, s[j]);+ }+ for (auto& x : s)+ x -= s_max;+ }+ double sum = 0.0;+ for (auto& x : s) {+ x = std::exp(x);+ sum += x;+ }+ for (size_t d = 0; d < head_size; ++d) {+ double ref = 0.0;+ for (size_t j = 0; j < keys_end; ++j)+ ref += s[j] / sum * static_cast<double>(v[(h * seq_kv + j) * head_size + d]);+ ASSERT_TRUE(std::isfinite(o[d])) << "non-finite output in row h=" << h << " q=" << i << " d=" << d;+ ASSERT_NEAR(o[d], ref, tol) << "h=" << h << " q=" << i << " d=" << d;+ }+ };+ size_t checked_rows = 0, checked_masked_rows = 0;+ for (size_t h = 0; h < heads; ++h) {+ for (size_t i = 0; i < seq_q; ++i) {+ const float* o = &out[(h * seq_q + i) * head_size];+ const bool fully_masked = p.scalar_mask || i >= valid_q;+ if (!fully_masked) {+ // Masked keys contribute exactly zero.+ ASSERT_NO_FATAL_FAILURE(check_row(h, i, o, valid_kv, false));+ ++checked_rows;+ continue;+ }+ if (p.masked_rows == masked_row_check::hull) {+ // Any softmax output is a convex combination of the V rows.+ for (size_t d = 0; d < head_size; ++d) {+ ASSERT_TRUE(std::isfinite(o[d])) << "non-finite output in fully masked row h=" << h << " q=" << i << " d=" << d;+ float lo = std::numeric_limits<float>::max(), hi = std::numeric_limits<float>::lowest();+ for (size_t j = 0; j < seq_kv; ++j) {+ const float vv = static_cast<float>(v[(h * seq_kv + j) * head_size + d]);+ lo = std::min(lo, vv);+ hi = std::max(hi, vv);+ }+ ASSERT_GE(o[d], lo - tol) << "h=" << h << " q=" << i << " d=" << d;+ ASSERT_LE(o[d], hi + tol) << "h=" << h << " q=" << i << " d=" << d;+ }+ } else {+ ASSERT_NO_FATAL_FAILURE(check_row(h, i, o, seq_kv, p.masked_rows == masked_row_check::mean_v));+ }+ ++checked_masked_rows;+ }+ }+ ASSERT_EQ(checked_rows, p.scalar_mask ? 0 : heads * valid_q);+ ASSERT_EQ(checked_masked_rows, heads * seq_q - checked_rows);+ }+};++TEST_P(sdpa_mask_fill_test, fully_masked_rows_stay_finite) {+ const auto p = GetParam();+ if (p.dt == data_types::bf16)+ run<ov::bfloat16>(p);+ else+ run<ov::float16>(p);+}++constexpr float torch_mask_fill = -2.381976325057654e38f;+constexpr float bf16_lowest = -3.3895313892515355e38f;+constexpr float neg_inf = -std::numeric_limits<float>::infinity();+constexpr float quiet_nan = std::numeric_limits<float>::quiet_NaN();++INSTANTIATE_TEST_SUITE_P(smoke_sdpa_mask_fill,+ sdpa_mask_fill_test,+ ::testing::Values(+ // bf16: the fill survives the conversion and overflows once folded (original NaN report)+ sdpa_mask_fill_params{data_types::bf16, torch_mask_fill, true, false, masked_row_check::mean_v},+ sdpa_mask_fill_params{data_types::bf16, bf16_lowest, true, false, masked_row_check::mean_v},+ sdpa_mask_fill_params{data_types::bf16, neg_inf, true, false, masked_row_check::mean_v},+ sdpa_mask_fill_params{data_types::bf16, -1e4f, true, false, masked_row_check::softmax}, // control: never overflowed+ sdpa_mask_fill_params{data_types::bf16, torch_mask_fill, true, true, masked_row_check::mean_v},+ // small custom scale: the folded mask stays finite, so nothing is saturated here+ sdpa_mask_fill_params{data_types::bf16, -1e4f, true, false, masked_row_check::mean_v, 1e-30f},+ sdpa_mask_fill_params{data_types::bf16, torch_mask_fill, true, false, masked_row_check::mean_v, 1e-30f},+ sdpa_mask_fill_params{data_types::bf16, quiet_nan, true, false, masked_row_check::mean_v},+ sdpa_mask_fill_params{data_types::bf16, torch_mask_fill, false, false, masked_row_check::hull},+ sdpa_mask_fill_params{data_types::bf16, neg_inf, false, false, masked_row_check::hull},+ sdpa_mask_fill_params{data_types::bf16, torch_mask_fill, false, true, masked_row_check::hull},+ // f16: f32 fills saturate to -65504 on conversion; only an explicit -inf mask overflows+ sdpa_mask_fill_params{data_types::f16, -65504.0f, true, false, masked_row_check::softmax},+ sdpa_mask_fill_params{data_types::f16, neg_inf, true, false, masked_row_check::mean_v},+ sdpa_mask_fill_params{data_types::f16, -65504.0f, true, true, masked_row_check::softmax},+ sdpa_mask_fill_params{data_types::f16, -65504.0f, false, false, masked_row_check::hull},+ sdpa_mask_fill_params{data_types::f16, neg_inf, false, false, masked_row_check::hull}),+ sdpa_mask_fill_test::PrintToStringParamName);+// use_onednn_sdpa is a debug-caps-only option.#ifdef ENABLE_DEBUG_CAPSstruct onednn_sdpa_test_params {