← Back to Pull requests

[GPU] Fix for ScaledAttn functional layer tests on PTL #38600

Merged
nshchego merged 9 files (207 lines) on Oct 14, 2026 06:46 UTC
View on GitHub
nshchego nshchego commented on Oct 05, 2026 10:46 UTC
Author

Details:


- sdpa_opt.cl/sdpa_ref.cl: scale input was read with the wrong buffer type (INPUT3_TYPE instead of the always-correct INPUT4_TYPE), since a placeholder attn_mask input always occupies slot 3 when scale is used.
sdpa/sdpa_utils.hpp: a placeholder (dummy) attention-mask was mis-detected as a real mask because shape canonicalization pads it to rank 4 before the rank()>1 check runs; added an element-count check.
sdpa/sdpa_opt.cpp: the actual segfault — execute()'s stage-selection condition (is_prefill) didn't match the constructor's stage-creation condition (is_prefill || unaligned_head_size), so for static shapes with decode length 1 + unaligned head size, it looked up a kernel stage that was never created, crashing in dynamic_cast.

- In the Q-loading remainder path, int valid_workers = K_HEAD_SIZE - k_sgidSUBGROUP_SIZE could go negative when extra subgroups (sized for a larger V_HEAD_SIZE) exceed what's needed for K_HEAD_SIZE. Comparing the unsigned sglid against that negative int made the guard true for all lanes, corrupting slm_query.
-
In load_attn_mask()'s boundary-padding branch, the float literal NAN was assigned into an INPUT3_TYPE intermediate (ushort for bf16 mask tensors). The implicit float→ushort conversion doesn't preserve NaN's bit pattern, so after being decoded back as bf16 it became a large finite garbage value instead of NaN. This broke the masking of out-of-range key positions (e.g., the trailing partition when SOURCE_SEQ_LEN isn't a multiple of the partition size), poisoning the softmax max and collapsing entire output rows to all-zero — exactly matching the Actual: 0, Expected: <value> failures, only for bf16 + prefill + mismatched K/V head size + real runtime mask.

Tickets:


-
196455

AI Assistance:


-
AI assistance used: yes*

Diff: 207 lines (+123 / -84) across 9 files Reviewer: v-Golubev Review duration: 12719m
All Vouch review confidence checks passed
Residual risk 0.04 = Change Risk (0.47) × (1 − Review Confidence (0.92)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.47 · 207 lines diff across 9 files
0.47
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.92 · 5 substantive comment(s)
0.92
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
91%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.319
Real PR Conversation Timeline
18 items
v-Golubev v-Golubev commented on code on Oct 08, 2026 10:19 UTC
Code Review
src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_opt.hpp:1
@@ -24,11 +24,16 @@ inline size_t get_target_seq_len_block_size() {
     return block_size;
 }
 
-inline size_t get_sg_number_scale_factor(const device_info& info, size_t head_size, size_t kernel_type) {
+inline size_t get_sg_number_scale_factor(const device_info& info, size_t head_size, size_t kernel_type, size_t k_head_size = 0) {

Can we remove the default value for k_head_size, here and in get_seq_len_partition_size? It hides the callers which were not updated, and as far as I see, PA is already affected. get_jit_constants_base is shared with PagedAttentionSDPAOptGeneratorMultiToken, so for PA the JIT now gets desc->k_head_size, while paged_attention_opt.cpp still calls these helpers without it (get_partitioning_size, the multi-token dispatch func, sdpa_opt_seq_len_partition_size). As a result, for PA prefill with different K/V head sizes (e.g. 192/128), the kernel is compiled with SG_SCALE_FACTOR=1, but dispatched with LWS and partition size calculated for scale factor 2. With a required parameter, this would be a compilation error. Could you please double check?

v-Golubev v-Golubev commented on code on Oct 08, 2026 10:19 UTC
Code Review
src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_utils.hpp:1
@@ -42,11 +42,22 @@ inline bool sdpa_has_runtime_attn_mask_input(const cldnn::kernel_impl_params& pa
         return false;
     }
 
-    const auto& attn_mask_pshape =
-        params.get_input_layout(cldnn::scaled_dot_product_attention::ScaledDotProductAttentionInputIdx::ATTN_MASK).get_partial_shape();
+    const auto& attn_mask_layout = params.get_input_layout(cldnn::scaled_dot_product_attention::ScaledDotProductAttentionInputIdx::ATTN_MASK);
+    const auto& attn_mask_pshape = attn_mask_layout.get_partial_shape();
+
+    if (!attn_mask_pshape.rank().is_static()) {
+        return true;
+    }
 
     // Keep scalar and 1D placeholders out of the real attention-mask path.
-    return !attn_mask_pshape.rank().is_static() || attn_mask_pshape.rank().get_length() > 1;
+    // Note: such placeholders may get padded up to rank 4 (all dims equal to 1) by shape
+    // canonicalization performed elsewhere in the pipeline, so the original rank check alone
+    // is not sufficient - also treat a statically-known single-element tensor as a placeholder.
+    if (attn_mask_pshape.rank().get_length() <= 1) {
+        return false;
+    }
+
+    return !attn_mask_pshape.is_static() || attn_mask_layout.count() != 1;

As far as I see, the root cause is in SDPABase::static_canonicalize_shapes: the attention mask input is extended to rank 4 even if it is a placeholder. But the placeholder is just an empty input, so it must remain scalar. Let's skip it in the canonicalization instead: then the original rank check here keeps working, and we don't need this heuristic. Please note: with the current approach, a real static mask with [1,1,1,1] shape would be silently ignored. What do you think?

v-Golubev v-Golubev commented on code on Oct 08, 2026 10:20 UTC
Code Review
src/plugins/intel_gpu/include/intel_gpu/runtime/utils.hpp:1
@@ -137,10 +137,15 @@ template <typename derived_type, typename base_type, std::enable_if_t<std::is_ba
 inline derived_type& downcast(base_type& base) {
     try {
         return dynamic_cast<derived_type&>(base);
-    } catch (std::bad_cast& /* ex */) {
-        throw std::runtime_error("Unable to cast reference from base to derived type");
+    } catch (std::bad_cast&) {
+        OPENVINO_THROW("Unable to cast reference from base (",
+                        typeid(base_type).name(),
+                        ") actual dynamic type (",
+                        typeid(base).name(),
+                        ") to derived (",
+                        typeid(derived_type).name(),
+                        ") type");
     }
-    throw std::runtime_error("downcast failed with unhandled exception");

Why was this line removed?

nshchego nshchego commented on code on Oct 10, 2026 08:11 UTC
Code Review
src/plugins/intel_gpu/include/intel_gpu/runtime/utils.hpp:1
@@ -137,10 +137,15 @@ template <typename derived_type, typename base_type, std::enable_if_t<std::is_ba
 inline derived_type& downcast(base_type& base) {
     try {
         return dynamic_cast<derived_type&>(base);
-    } catch (std::bad_cast& /* ex */) {
-        throw std::runtime_error("Unable to cast reference from base to derived type");
+    } catch (std::bad_cast&) {
+        OPENVINO_THROW("Unable to cast reference from base (",
+                        typeid(base_type).name(),
+                        ") actual dynamic type (",
+                        typeid(base).name(),
+                        ") to derived (",
+                        typeid(derived_type).name(),
+                        ") type");
     }
-    throw std::runtime_error("downcast failed with unhandled exception");

That statement was unreachable dead code, because dynamic_cast throws only std::bad_cast, which is caught by the catch block. I can revert it back if you have real concern about that.

nshchego nshchego commented on code on Oct 11, 2026 20:11 UTC
Code Review
src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_opt.hpp:1
@@ -24,11 +24,16 @@ inline size_t get_target_seq_len_block_size() {
     return block_size;
 }
 
-inline size_t get_sg_number_scale_factor(const device_info& info, size_t head_size, size_t kernel_type) {
+inline size_t get_sg_number_scale_factor(const device_info& info, size_t head_size, size_t kernel_type, size_t k_head_size = 0) {

You are right, modified.

nshchego nshchego commented on code on Oct 11, 2026 20:12 UTC
Code Review
src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_utils.hpp:1
@@ -42,11 +42,22 @@ inline bool sdpa_has_runtime_attn_mask_input(const cldnn::kernel_impl_params& pa
         return false;
     }
 
-    const auto& attn_mask_pshape =
-        params.get_input_layout(cldnn::scaled_dot_product_attention::ScaledDotProductAttentionInputIdx::ATTN_MASK).get_partial_shape();
+    const auto& attn_mask_layout = params.get_input_layout(cldnn::scaled_dot_product_attention::ScaledDotProductAttentionInputIdx::ATTN_MASK);
+    const auto& attn_mask_pshape = attn_mask_layout.get_partial_shape();
+
+    if (!attn_mask_pshape.rank().is_static()) {
+        return true;
+    }
 
     // Keep scalar and 1D placeholders out of the real attention-mask path.
-    return !attn_mask_pshape.rank().is_static() || attn_mask_pshape.rank().get_length() > 1;
+    // Note: such placeholders may get padded up to rank 4 (all dims equal to 1) by shape
+    // canonicalization performed elsewhere in the pipeline, so the original rank check alone
+    // is not sufficient - also treat a statically-known single-element tensor as a placeholder.
+    if (attn_mask_pshape.rank().get_length() <= 1) {
+        return false;
+    }
+
+    return !attn_mask_pshape.is_static() || attn_mask_layout.count() != 1;

Modified

v-Golubev v-Golubev commented on code on Oct 12, 2026 18:41 UTC
Code Review
src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/paged_attention_opt.cpp:1
@@ -207,10 +207,10 @@ size_t get_max_context_len(const kernel_impl_params& params) {
     return paged_attention_max_len;
 }
 
-size_t get_partitioning_size(const kernel_impl_params& params, size_t head_size, PagedAttentionStage stage) {
+size_t get_partitioning_size(const kernel_impl_params& params, size_t head_size, PagedAttentionStage stage, size_t k_head_size = 0) {

Please remove default parameter

v-Golubev v-Golubev commented on code on Oct 12, 2026 18:41 UTC
Code Review
src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_utils.hpp:1
@@ -42,11 +42,20 @@ inline bool sdpa_has_runtime_attn_mask_input(const cldnn::kernel_impl_params& pa
         return false;
     }
 
-    const auto& attn_mask_pshape =
-        params.get_input_layout(cldnn::scaled_dot_product_attention::ScaledDotProductAttentionInputIdx::ATTN_MASK).get_partial_shape();
+    const auto& attn_mask_layout = params.get_input_layout(cldnn::scaled_dot_product_attention::ScaledDotProductAttentionInputIdx::ATTN_MASK);
+    const auto& attn_mask_pshape = attn_mask_layout.get_partial_shape();
 
-    // Keep scalar and 1D placeholders out of the real attention-mask path.
-    return !attn_mask_pshape.rank().is_static() || attn_mask_pshape.rank().get_length() > 1;
+    if (!attn_mask_pshape.rank().is_static()) {
+        return true;
+    }
+
+    // Per SDPA specification, the attention mask is either empty (a placeholder, e.g. when only a scalar
+    // attn_mask_val is provided or no mask is used at all) or has rank 2 or more. Shape canonicalization
+    // (SDPABase::static_canonicalize_shapes) keeps such a placeholder's shape at rank 0 instead of padding
+    // it up to rank 4, so a plain rank check is sufficient here.
+    // Note: with this approach, a real static mask with shape [1,1,1,1] would be silently ignored, since it

Minor: this note carries over the caveat about the old single-element heuristic, but it doesn't apply to the rank check below anymore: a static mask with shape [1,1,1,1] has rank 4, so rank().get_length() > 1 is true and it's still detected as a real mask. The actually indistinguishable case is a genuinely scalar (rank-0) real mask, not a [1,1,1,1] one.

v-Golubev v-Golubev commented on code on Oct 12, 2026 18:45 UTC
Code Review
src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_opt.cpp:1
@@ -259,7 +259,7 @@ DispatchDataFunc SDPAOptGeneratorSingleToken::get_dispatch_data_func() const {
 
             const size_t head_size_u = ensure_positive_dim(head_size, "head_size", "SDPA: invalid non-positive ", " in static dispatch");
 
-            const size_t sg_num_scale = get_sg_number_scale_factor(params.get_device_info(), head_size_u, SDPAStage::SINGLE_TOKEN);
+            const size_t sg_num_scale = get_sg_number_scale_factor(params.get_device_info(), head_size_u, SDPAStage::SINGLE_TOKEN, 0);

Even after the refactoring, k_head_size is derived independently here and in get_jit_constants_base, and still passed around as a magic 0 elsewhere meaning "not applicable for this stage". Let's add a single SDPABase::get_effective_head_sizes(params) (paged-attention just returns desc->k_head_size/v_head_size; the SDPA branch reuses this exact get_head_size + int4-override logic, already identical in both places today) and call it everywhere instead of re-deriving the pair per call site. What do you think?

nshchego nshchego commented on code on Oct 13, 2026 08:31 UTC
Code Review
src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/paged_attention_opt.cpp:1
@@ -207,10 +207,10 @@ size_t get_max_context_len(const kernel_impl_params& params) {
     return paged_attention_max_len;
 }
 
-size_t get_partitioning_size(const kernel_impl_params& params, size_t head_size, PagedAttentionStage stage) {
+size_t get_partitioning_size(const kernel_impl_params& params, size_t head_size, PagedAttentionStage stage, size_t k_head_size = 0) {

Removed

nshchego nshchego commented on code on Oct 13, 2026 08:32 UTC
Code Review
src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_utils.hpp:1
@@ -42,11 +42,20 @@ inline bool sdpa_has_runtime_attn_mask_input(const cldnn::kernel_impl_params& pa
         return false;
     }
 
-    const auto& attn_mask_pshape =
-        params.get_input_layout(cldnn::scaled_dot_product_attention::ScaledDotProductAttentionInputIdx::ATTN_MASK).get_partial_shape();
+    const auto& attn_mask_layout = params.get_input_layout(cldnn::scaled_dot_product_attention::ScaledDotProductAttentionInputIdx::ATTN_MASK);
+    const auto& attn_mask_pshape = attn_mask_layout.get_partial_shape();
 
-    // Keep scalar and 1D placeholders out of the real attention-mask path.
-    return !attn_mask_pshape.rank().is_static() || attn_mask_pshape.rank().get_length() > 1;
+    if (!attn_mask_pshape.rank().is_static()) {
+        return true;
+    }
+
+    // Per SDPA specification, the attention mask is either empty (a placeholder, e.g. when only a scalar
+    // attn_mask_val is provided or no mask is used at all) or has rank 2 or more. Shape canonicalization
+    // (SDPABase::static_canonicalize_shapes) keeps such a placeholder's shape at rank 0 instead of padding
+    // it up to rank 4, so a plain rank check is sufficient here.
+    // Note: with this approach, a real static mask with shape [1,1,1,1] would be silently ignored, since it

Removed

nshchego nshchego commented on code on Oct 13, 2026 08:33 UTC
Code Review
src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_opt.cpp:1
@@ -259,7 +259,7 @@ DispatchDataFunc SDPAOptGeneratorSingleToken::get_dispatch_data_func() const {
 
             const size_t head_size_u = ensure_positive_dim(head_size, "head_size", "SDPA: invalid non-positive ", " in static dispatch");
 
-            const size_t sg_num_scale = get_sg_number_scale_factor(params.get_device_info(), head_size_u, SDPAStage::SINGLE_TOKEN);
+            const size_t sg_num_scale = get_sg_number_scale_factor(params.get_device_info(), head_size_u, SDPAStage::SINGLE_TOKEN, 0);

Modified

v-Golubev v-Golubev commented on code on Oct 13, 2026 18:48 UTC
Code Review
src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_opt.hpp:1
@@ -24,11 +24,16 @@ inline size_t get_target_seq_len_block_size() {
     return block_size;
 }
 
-inline size_t get_sg_number_scale_factor(const device_info& info, size_t head_size, size_t kernel_type) {
+inline size_t get_sg_number_scale_factor(const device_info& info, size_t head_size, size_t kernel_type, size_t k_head_size) {
     constexpr size_t subgroup_size = 16;
     const size_t optimal_scale_factor = 2;
     if (kernel_type == SDPAStage::MULTI_TOKENS) {
-        if (head_size % subgroup_size == 0 && head_size * optimal_scale_factor <= info.max_work_group_size) {
+        // The doubled-subgroup query-loading scheme (SG_SCALE_FACTOR == 2) in the multi-token
+        // kernel assumes the work-group is sized off a single head size. When K/V head sizes
+        // differ, the per-subgroup head-index/seq-half assignment logic is not guaranteed to
+        // produce correct coverage, so keep the safe (non-scaled) path in that case.
+        bool head_sizes_match = (k_head_size == 0) || (k_head_size == head_size);

Should we remove k_head_size == 0 after the refactoring? It looks like 0 is not a special value anymore

v-Golubev v-Golubev commented on code on Oct 13, 2026 18:48 UTC
Code Review
src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_base.cpp:1
@@ -87,6 +87,36 @@ bool SDPABase::is_int4_kv_cache(const kernel_impl_params& params) {
     return data_type_traits::is_i4_u4(kv_cache_dt);
 }
 
+// Returns {k_head_size, v_head_size} as actually used by SDPA-family OCL kernels (SDPAOpt/SDPAMicro
+// and PagedAttentionOpt share this via SDPABase). For PagedAttention these are simply the descriptor
+// fields; for SDPA they are derived from the K/V input layouts (honoring transpose orders), with the
+// int4 KV-cache override (physical K/V layouts are packed to half size; use the logical, un-halved
+// head size taken from the query layout instead).
+std::pair<int64_t, int64_t> SDPABase::get_effective_head_sizes(const kernel_impl_params& params) {
+    if (params.is_type<paged_attention>()) {
+        const auto desc = params.typed_desc<paged_attention>();
+        return {static_cast<int64_t>(desc->k_head_size), static_cast<int64_t>(desc->v_head_size)};
+    }
+

Let's assert that result is not nullptr

v-Golubev v-Golubev approved these changes on Oct 13, 2026 18:50 UTC
Approved Reviewer

Only minor comments left

nshchego nshchego commented on code on Oct 14, 2026 13:29 UTC
Code Review
src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_gen_opt.hpp:1
@@ -24,11 +24,16 @@ inline size_t get_target_seq_len_block_size() {
     return block_size;
 }
 
-inline size_t get_sg_number_scale_factor(const device_info& info, size_t head_size, size_t kernel_type) {
+inline size_t get_sg_number_scale_factor(const device_info& info, size_t head_size, size_t kernel_type, size_t k_head_size) {
     constexpr size_t subgroup_size = 16;
     const size_t optimal_scale_factor = 2;
     if (kernel_type == SDPAStage::MULTI_TOKENS) {
-        if (head_size % subgroup_size == 0 && head_size * optimal_scale_factor <= info.max_work_group_size) {
+        // The doubled-subgroup query-loading scheme (SG_SCALE_FACTOR == 2) in the multi-token
+        // kernel assumes the work-group is sized off a single head size. When K/V head sizes
+        // differ, the per-subgroup head-index/seq-half assignment logic is not guaranteed to
+        // produce correct coverage, so keep the safe (non-scaled) path in that case.
+        bool head_sizes_match = (k_head_size == 0) || (k_head_size == head_size);

PR #38853

nshchego nshchego commented on code on Oct 14, 2026 13:41 UTC
Code Review
src/plugins/intel_gpu/src/graph/impls/ocl_v2/sdpa/sdpa_base.cpp:1
@@ -87,6 +87,36 @@ bool SDPABase::is_int4_kv_cache(const kernel_impl_params& params) {
     return data_type_traits::is_i4_u4(kv_cache_dt);
 }
 
+// Returns {k_head_size, v_head_size} as actually used by SDPA-family OCL kernels (SDPAOpt/SDPAMicro
+// and PagedAttentionOpt share this via SDPABase). For PagedAttention these are simply the descriptor
+// fields; for SDPA they are derived from the K/V input layouts (honoring transpose orders), with the
+// int4 KV-cache override (physical K/V layouts are packed to half size; use the logical, un-halved
+// head size taken from the query layout instead).
+std::pair<int64_t, int64_t> SDPABase::get_effective_head_sizes(const kernel_impl_params& params) {
+    if (params.is_type<paged_attention>()) {
+        const auto desc = params.typed_desc<paged_attention>();
+        return {static_cast<int64_t>(desc->k_head_size), static_cast<int64_t>(desc->v_head_size)};
+    }
+

params.typed_desc uses static cast - it does not return nullptr

Reviewers
Assignees
nshchego nshchego
Labels
risk: low confidence: 91.9% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 46.7% (MEDIUM) · Higher = larger blast radius
46.7%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 91.9% · Lower = rushed or shallow review
91.9%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 3.8% · Safe to merge
3.8%