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
[NPUW]Handle flash sdpa without pre-transposed V tensor correctly. (#37246)
intelgaoxiong859ae97fbb67
diff --git a/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.cpp b/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.cppindex e8897d43d3e..cfda2390c76 100644--- a/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.cpp@@ -62,7 +62,8 @@ static HFATileInputs create_hfa_tile_inputs(const ov::Shape& q_shape,const ov::element::Type& input_dtype,const ov::element::Type& mask_dtype,int64_t tile_size,- size_t kv_num_heads) {+ size_t kv_num_heads,+ bool v_transposed = true) {auto batch = q_shape[0];auto num_heads = q_shape[1];auto seq_len = q_shape[2];@@ -95,10 +96,17 @@ static HFATileInputs create_hfa_tile_inputs(const ov::Shape& q_shape,ov::Shape{batch, kv_num_heads, static_cast<size_t>(tile_size), head_dim});set_param_name(inputs.k_tile, HFATileInputId::K_TILE);- // v_tile: [batch, kv_num_heads, head_dim, tile_size]- inputs.v_tile = std::make_shared<ov::op::v0::Parameter>(- input_dtype,- ov::Shape{batch, kv_num_heads, head_dim, static_cast<size_t>(tile_size)});+ // v_tile: [batch, kv_num_heads, head_dim, tile_size] when V is pre-transposed by OptimizeValueTensors,+ // [batch, kv_num_heads, tile_size, head_dim] when V is in normal (non-transposed) layout.+ if (v_transposed) {+ inputs.v_tile = std::make_shared<ov::op::v0::Parameter>(+ input_dtype,+ ov::Shape{batch, kv_num_heads, head_dim, static_cast<size_t>(tile_size)});+ } else {+ inputs.v_tile = std::make_shared<ov::op::v0::Parameter>(+ input_dtype,+ ov::Shape{batch, kv_num_heads, static_cast<size_t>(tile_size), head_dim});+ }set_param_name(inputs.v_tile, HFATileInputId::V_TILE);// q: [batch, num_heads, seq_len, head_dim]@@ -162,7 +170,8 @@ static FlashAttentionResults execute_fused_flash_attention(const HFATileF32Nodesconst std::shared_ptr<ov::Node>& k_input,const std::shared_ptr<ov::Node>& v_input,bool is_last_tile = false,- bool is_first_tile = false) {+ bool is_first_tile = false,+ bool v_transposed = true) {ov::intel_npu::op::FlashAttentionTile::Config config;config.is_head = is_first_tile;config.is_tail = is_last_tile;@@ -171,13 +180,24 @@ static FlashAttentionResults execute_fused_flash_attention(const HFATileF32Nodesauto rank = v_shape.rank().get_length();if (rank != 4)OPENVINO_THROW("v_input rank must be 4 for flash attention");- std::vector<int64_t> transpose_v_order({0, 1, 3, 2});- auto transpose_order = std::make_shared<ov::op::v0::Constant>(ov::element::i64,- ov::Shape{static_cast<size_t>(rank)},- transpose_v_order);- auto v_transpose = std::make_shared<ov::op::v1::Transpose>(v_input, transpose_order);- v_transpose->set_friendly_name("v_input_transposed");+ // When V is pre-transposed by OptimizeValueTensors, the tile parameter is [B,H,head_dim,tile_size];+ // we transpose it back to [B,H,tile_size,head_dim] before feeding FlashAttentionTile (which expects+ // normal [B,H,seq_len,head_dim] layout). When V was NOT transposed, the tile parameter already+ // holds normal layout [B,H,tile_size,head_dim] and no transpose is needed.+ std::shared_ptr<ov::Node> v_for_attn;+ if (v_transposed) {+ std::vector<int64_t> transpose_v_order({0, 1, 3, 2});+ auto transpose_order = std::make_shared<ov::op::v0::Constant>(ov::element::i64,+ ov::Shape{static_cast<size_t>(rank)},+ transpose_v_order);+ auto v_transpose = std::make_shared<ov::op::v1::Transpose>(v_input, transpose_order);+ v_transpose->set_friendly_name("v_input_transposed");+ v_for_attn = v_transpose;+ } else {+ // V is already in [B,H,tile_size,head_dim] — pass directly.+ v_for_attn = v_input;+ }auto squeeze = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{-1});@@ -192,7 +212,7 @@ static FlashAttentionResults execute_fused_flash_attention(const HFATileF32Nodes// Use mask for final tile to ensure proper masking of the last KV blockflash_attn_tile = std::make_shared<ov::intel_npu::op::FlashAttentionTile>(q_input,k_input,- v_transpose,+ v_for_attn,f32_nodes.past_acc_f32,past_max_squeezed,past_sum_squeezed,@@ -201,7 +221,7 @@ static FlashAttentionResults execute_fused_flash_attention(const HFATileF32Nodes} else {flash_attn_tile = std::make_shared<ov::intel_npu::op::FlashAttentionTile>(q_input,k_input,- v_transpose,+ v_for_attn,f32_nodes.past_acc_f32,past_max_squeezed,past_sum_squeezed,@@ -580,6 +600,7 @@ static std::shared_ptr<ov::Model> create_hfa_tile_model(const ov::Shape& q_shapesize_t kv_num_heads,bool is_final_tile = false,bool fused_flash_attention = false,+ bool v_transposed = true,const ov::element::Type& output_dtype = ov::element::f16) {LOG_DEBUG("Creating HFA " << (is_final_tile ? "FINAL " : "") << "tile model with tile_size=" << tile_size<< ", kv_num_heads=" << kv_num_heads << ", mask_dtype=" << mask_dtype@@ -599,7 +620,7 @@ static std::shared_ptr<ov::Model> create_hfa_tile_model(const ov::Shape& q_shapeLOG_DEBUG("Using compute_dtype=f32 for all operations to match mask type");// Create input parameters- auto inputs = create_hfa_tile_inputs(q_shape, input_dtype, mask_dtype, tile_size, kv_num_heads);+ auto inputs = create_hfa_tile_inputs(q_shape, input_dtype, mask_dtype, tile_size, kv_num_heads, v_transposed);// Convert all inputs to f32.// For the fused operation only the final tile uses a mask (regular tiles skip mask for performance)@@ -642,7 +663,9 @@ static std::shared_ptr<ov::Model> create_hfa_tile_model(const ov::Shape& q_shapef32_nodes.q_f32,f32_nodes.k_tile_f32,f32_nodes.v_tile_f32,- is_final_tile);+ is_final_tile,+ false, // is_first_tile+ v_transposed);} else {// Broadcast K and V tiles from kv_num_heads to num_headsauto [k_broadcast, v_broadcast] = broadcast_kv_tiles(f32_nodes.k_tile_f32,@@ -1021,14 +1044,18 @@ std::optional<HostFlashAttention> HostFlashAttention::from(const std::shared_ptr// ========================================================================// Step 5: Create tile models using query_size as tile_size// ========================================================================- LOG_INFO("Creating HFA tile models with tile_size=" << query_size);+ // V tensors are pre-transposed (stored as [B,H,head_dim,seq]) only when OptimizeValueTensors+ // succeeded, which is reflected by the V-concat axis being 3 instead of the default 2.+ const bool v_transposed = (v_seq_dim == 3);+ LOG_INFO("Creating HFA tile models with tile_size=" << query_size << ", v_transposed=" << v_transposed);auto tile_model = create_hfa_tile_model(q_shape_static,dtype,mask_dtype,query_size,kv_num_heads,false,- fused_flash_attention);+ fused_flash_attention,+ v_transposed);if (!tile_model) {LOG_WARN("Failed to create HFA tile model");return std::nullopt;@@ -1041,6 +1068,7 @@ std::optional<HostFlashAttention> HostFlashAttention::from(const std::shared_ptrkv_num_heads,true,fused_flash_attention,+ v_transposed,output_dtype);if (!final_tile_model) {LOG_WARN("Failed to create HFA final tile model");diff --git a/src/plugins/intel_npu/tests/unit/npuw/host_flash_attention_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/host_flash_attention_test.cppindex 94d5d046d19..1a93f0832a1 100644--- a/src/plugins/intel_npu/tests/unit/npuw/host_flash_attention_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/host_flash_attention_test.cpp@@ -211,17 +211,81 @@ TEST(HostFlashAttentionFromTest, Fused_ContextSizeIsCorrect) {EXPECT_EQ(result->_context_size, QUERY_SIZE + PAST_LEN);}+namespace {+// ============================================================================+// Build a model where V is pre-transposed (axis=3), simulating a model that+// has been processed by OptimizeValueTensors. V parameters are stored as+// [B, H, head_dim, seq] and the V-Concat is along axis 3.// ============================================================================-// Input / output shape checks+std::shared_ptr<ov::Model> build_sdpa_model_transposed_v(size_t query_size = QUERY_SIZE,+ size_t past_len = PAST_LEN,+ size_t num_heads = NUM_HEADS,+ size_t head_dim = HEAD_DIM) {+ using namespace ov;+ const Shape past_k_shape = {BATCH, num_heads, past_len, head_dim}; // K: normal layout+ const Shape new_k_shape = {BATCH, num_heads, query_size, head_dim};+ const Shape past_v_shape = {BATCH, num_heads, head_dim, past_len}; // V: pre-transposed+ const Shape new_v_shape = {BATCH, num_heads, head_dim, query_size};+ const Shape q_shape = {BATCH, num_heads, query_size, head_dim};+ const Shape mask_shape = {BATCH, 1, query_size, past_len + query_size};++ ParameterVector params;+ ResultVector results;+ auto make_param = [&](const std::string& name, const Shape& shape) {+ auto p = std::make_shared<op::v0::Parameter>(element::f32, shape);+ p->set_friendly_name(name);+ p->output(0).get_tensor().set_names({name});+ params.push_back(p);+ return p;+ };++ auto query = make_param("query.0", q_shape);+ auto past_key = make_param("past_key_values.0.key", past_k_shape);+ auto past_val = make_param("past_key_values.0.value", past_v_shape);+ auto new_key = make_param("new_key.0", new_k_shape);+ auto new_val = make_param("new_value.0", new_v_shape);+ auto mask = make_param("mask.0", mask_shape);++ auto key_concat = std::make_shared<op::v0::Concat>(OutputVector{past_key, new_key}, 2);+ key_concat->set_friendly_name("concat_key.0");+ // axis=3: concat along the last dim, which is the sequence dimension in transposed V layout+ auto val_concat = std::make_shared<op::v0::Concat>(OutputVector{past_val, new_val}, 3);+ val_concat->set_friendly_name("concat_value.0");++ auto qk = std::make_shared<op::v0::MatMul>(query, key_concat, false, true);+ qk->set_friendly_name("matmul1.0");+ auto add = std::make_shared<op::v1::Add>(qk->output(0), mask->output(0));+ add->set_friendly_name("add.0");+ auto softmax = std::make_shared<op::v8::Softmax>(add->output(0), 3);+ softmax->set_friendly_name("softmax.0");+ // transpose_b=true: softmax[B,H,q,k] x V[B,H,head_dim,k]^T -> [B,H,q,head_dim]+ auto matmul2 = std::make_shared<op::v0::MatMul>(softmax->output(0), val_concat->output(0), false, true);+ matmul2->set_friendly_name("matmul2.0");++ auto make_result = [&](const Output<Node>& out, const std::string& name) {+ results.push_back(std::make_shared<op::v0::Result>(out));+ results.back()->set_friendly_name(name);+ };+ make_result(key_concat->output(0), "present.0.key");+ make_result(val_concat->output(0), "present.0.value");+ make_result(matmul2->output(0), "attn_out.0");++ auto model = std::make_shared<Model>(results, params, "sdpa_model_transposed_v");+ model->validate_nodes_and_infer_types();+ return model;+}++} // namespace++// ============================================================================+// Input / output shape checks — V NOT transposed (axis=2, the default)// Expected shapes (BATCH=1, NUM_HEADS=8, HEAD_DIM=64, QUERY_SIZE=16):-// past_acc [1, 8, 16, 64] past_max [1, 8, 16, 1] past_d [1, 8, 16, 1]-// k_tile [1, 8, 16, 64] v_tile [1, 8, 64, 16] (V stored pre-transposed)-// q [1, 8, 16, 64] mask_tile [1, 1, 16, 16]-// regular tile outputs: acc [1,8,16,64] maxx [1,8,16,1] d [1,8,16,1]-// final tile output: [1, QUERY_SIZE, NUM_HEADS*HEAD_DIM] = [1, 16, 512]+// past_acc [1,8,16,64] past_max [1,8,16,1] past_d [1,8,16,1]+// k_tile [1,8,16,64] v_tile [1,8,16,64] (normal [B,H,tile,head_dim])+// q [1,8,16,64] mask_tile [1,1,16,16]// ============================================================================-// Fused path — regular tile (6 inputs, no mask)+// Fused path — regular tile (6 inputs, no mask); v_tile in normal layoutTEST(HostFlashAttentionFromTest, Fused_RegularTileInputShapes) {auto result = ov::npuw::function::HostFlashAttention::from(build_sdpa_model(), true);ASSERT_TRUE(result.has_value());@@ -231,13 +295,13 @@ TEST(HostFlashAttentionFromTest, Fused_RegularTileInputShapes) {{BATCH, NUM_HEADS, QUERY_SIZE, 1}, // past_max{BATCH, NUM_HEADS, QUERY_SIZE, 1}, // past_d{BATCH, NUM_HEADS, QUERY_SIZE, HEAD_DIM}, // k_tile [B, kv_heads, tile, head_dim]- {BATCH, NUM_HEADS, HEAD_DIM, QUERY_SIZE}, // v_tile [B, kv_heads, head_dim, tile]+ {BATCH, NUM_HEADS, QUERY_SIZE, HEAD_DIM}, // v_tile [B, kv_heads, tile, head_dim] (normal){BATCH, NUM_HEADS, QUERY_SIZE, HEAD_DIM}, // q};check_input_shapes(result->_tile_model, expected_inputs, "fused regular tile");}-// Fused path — final tile (7 inputs, with mask)+// Fused path — final tile (7 inputs, with mask); v_tile in normal layoutTEST(HostFlashAttentionFromTest, Fused_FinalTileInputShapes) {auto result = ov::npuw::function::HostFlashAttention::from(build_sdpa_model(), true);ASSERT_TRUE(result.has_value());@@ -247,14 +311,14 @@ TEST(HostFlashAttentionFromTest, Fused_FinalTileInputShapes) {{BATCH, NUM_HEADS, QUERY_SIZE, 1}, // past_max{BATCH, NUM_HEADS, QUERY_SIZE, 1}, // past_d{BATCH, NUM_HEADS, QUERY_SIZE, HEAD_DIM}, // k_tile- {BATCH, NUM_HEADS, HEAD_DIM, QUERY_SIZE}, // v_tile+ {BATCH, NUM_HEADS, QUERY_SIZE, HEAD_DIM}, // v_tile (normal){BATCH, NUM_HEADS, QUERY_SIZE, HEAD_DIM}, // q{BATCH, 1, QUERY_SIZE, QUERY_SIZE}, // mask_tile [B, 1, seq, tile]};check_input_shapes(result->_final_tile_model, expected_inputs, "fused final tile");}-// Non-fused path — regular tile (7 inputs, with mask)+// Non-fused path — regular tile (7 inputs, with mask); v_tile in normal layoutTEST(HostFlashAttentionFromTest, NonFused_RegularTileInputShapes) {auto result = ov::npuw::function::HostFlashAttention::from(build_sdpa_model(), false);ASSERT_TRUE(result.has_value());@@ -263,10 +327,10 @@ TEST(HostFlashAttentionFromTest, NonFused_RegularTileInputShapes) {{BATCH, NUM_HEADS, QUERY_SIZE, HEAD_DIM}, // past_acc{BATCH, NUM_HEADS, QUERY_SIZE, 1}, // past_max{BATCH, NUM_HEADS, QUERY_SIZE, 1}, // past_d- {BATCH, NUM_HEADS, QUERY_SIZE, HEAD_DIM}, // k_tile [B, kv_heads, tile, head_dim]- {BATCH, NUM_HEADS, HEAD_DIM, QUERY_SIZE}, // v_tile [B, kv_heads, head_dim, tile]+ {BATCH, NUM_HEADS, QUERY_SIZE, HEAD_DIM}, // k_tile+ {BATCH, NUM_HEADS, QUERY_SIZE, HEAD_DIM}, // v_tile (normal){BATCH, NUM_HEADS, QUERY_SIZE, HEAD_DIM}, // q- {BATCH, 1, QUERY_SIZE, QUERY_SIZE}, // mask_tile [B, 1, seq, tile]+ {BATCH, 1, QUERY_SIZE, QUERY_SIZE}, // mask_tile};check_input_shapes(result->_tile_model, expected_inputs, "non-fused regular tile");}@@ -306,3 +370,85 @@ TEST(HostFlashAttentionFromTest, NonFused_FinalTileOutputShape) {ASSERT_TRUE(result.has_value());check_output_shapes(result->_final_tile_model, {{BATCH, QUERY_SIZE, NUM_HEADS * HEAD_DIM}}, "non-fused final tile");}++// ============================================================================+// TransposedV suite — V pre-transposed (axis=3), simulating OptimizeValueTensors.+// v_tile must be [B, H, head_dim, tile_size] (transposed storage layout).+// ============================================================================++// Sanity: the transposed-V model is parseable+TEST(HostFlashAttentionTransposedVTest, FromReturnsValue) {+ EXPECT_TRUE(ov::npuw::function::HostFlashAttention::from(build_sdpa_model_transposed_v(), true).has_value());+}++// v_seq_dim == 3 -> _v_seq_dim field stored correctly+TEST(HostFlashAttentionTransposedVTest, VSeqDimIsThree) {+ auto result = ov::npuw::function::HostFlashAttention::from(build_sdpa_model_transposed_v(), true);+ ASSERT_TRUE(result.has_value());+ EXPECT_EQ(result->_v_seq_dim, 3u);+}++// Contrast: non-transposed model has _v_seq_dim == 2+TEST(HostFlashAttentionFromTest, VSeqDimIsTwoForNormalModel) {+ auto result = ov::npuw::function::HostFlashAttention::from(build_sdpa_model(), true);+ ASSERT_TRUE(result.has_value());+ EXPECT_EQ(result->_v_seq_dim, 2u);+}++// Fused regular tile: v_tile in transposed layout [B, H, head_dim, tile]+TEST(HostFlashAttentionTransposedVTest, Fused_RegularTileVTileIsTransposed) {+ auto result = ov::npuw::function::HostFlashAttention::from(build_sdpa_model_transposed_v(), true);+ ASSERT_TRUE(result.has_value());+ const std::vector<ov::Shape> expected = {+ {BATCH, NUM_HEADS, QUERY_SIZE, HEAD_DIM}, // past_acc+ {BATCH, NUM_HEADS, QUERY_SIZE, 1}, // past_max+ {BATCH, NUM_HEADS, QUERY_SIZE, 1}, // past_d+ {BATCH, NUM_HEADS, QUERY_SIZE, HEAD_DIM}, // k_tile+ {BATCH, NUM_HEADS, HEAD_DIM, QUERY_SIZE}, // v_tile [B,H,head_dim,tile] — pre-transposed+ {BATCH, NUM_HEADS, QUERY_SIZE, HEAD_DIM}, // q+ };+ check_input_shapes(result->_tile_model, expected, "transposed-V fused regular tile");+}++// Fused final tile: v_tile in transposed layout [B, H, head_dim, tile]+TEST(HostFlashAttentionTransposedVTest, Fused_FinalTileVTileIsTransposed) {+ auto result = ov::npuw::function::HostFlashAttention::from(build_sdpa_model_transposed_v(), true);+ ASSERT_TRUE(result.has_value());+ const std::vector<ov::Shape> expected = {+ {BATCH, NUM_HEADS, QUERY_SIZE, HEAD_DIM}, // past_acc+ {BATCH, NUM_HEADS, QUERY_SIZE, 1}, // past_max+ {BATCH, NUM_HEADS, QUERY_SIZE, 1}, // past_d+ {BATCH, NUM_HEADS, QUERY_SIZE, HEAD_DIM}, // k_tile+ {BATCH, NUM_HEADS, HEAD_DIM, QUERY_SIZE}, // v_tile [B,H,head_dim,tile] — pre-transposed+ {BATCH, NUM_HEADS, QUERY_SIZE, HEAD_DIM}, // q+ {BATCH, 1, QUERY_SIZE, QUERY_SIZE}, // mask_tile+ };+ check_input_shapes(result->_final_tile_model, expected, "transposed-V fused final tile");+}++// Output shapes are independent of V layout+TEST(HostFlashAttentionTransposedVTest, Fused_FinalTileOutputShape) {+ auto result = ov::npuw::function::HostFlashAttention::from(build_sdpa_model_transposed_v(), true);+ ASSERT_TRUE(result.has_value());+ check_output_shapes(result->_final_tile_model,+ {{BATCH, QUERY_SIZE, NUM_HEADS * HEAD_DIM}},+ "transposed-V fused final tile");+}++TEST(HostFlashAttentionTransposedVTest, Fused_RegularTileOutputShapes) {+ auto result = ov::npuw::function::HostFlashAttention::from(build_sdpa_model_transposed_v(), true);+ ASSERT_TRUE(result.has_value());+ const std::vector<ov::Shape> expected = {+ {BATCH, NUM_HEADS, QUERY_SIZE, HEAD_DIM},+ {BATCH, NUM_HEADS, QUERY_SIZE, 1},+ {BATCH, NUM_HEADS, QUERY_SIZE, 1},+ };+ check_output_shapes(result->_tile_model, expected, "transposed-V fused regular tile");+}++// Context size is derived from the transposed concat (axis=3, dim=3 of output)+TEST(HostFlashAttentionTransposedVTest, ContextSizeIsCorrect) {+ auto result = ov::npuw::function::HostFlashAttention::from(build_sdpa_model_transposed_v(), true);+ ASSERT_TRUE(result.has_value());+ EXPECT_EQ(result->_context_size, QUERY_SIZE + PAST_LEN);+}