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][HFA]Support mixed data types. (#37327)
intelgaoxiongba728f685d55
diff --git a/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.cpp b/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.cppindex 6f32a588889..4d42da3fe02 100644--- a/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.cpp@@ -347,6 +347,13 @@ void ensure_hfa_requests(ov::npuw::v1::subgraphs::InferContext& ctx, RuntimeStatconst auto tile_input = hfa->_compiled_tile_model->inputs()[input_idx];const auto final_tile_input = hfa->_compiled_final_tile_model->inputs()[input_idx];+ // Regular tile KV inputs (f16) differ from final tile KV inputs (f32).+ // Skip sharing for mismatched dtypes — those ports will be set per-tile+ // in process_tile at runtime.+ if (tile_input.get_element_type() != final_tile_input.get_element_type()) {+ continue;+ }+auto main_tensor = state.base_request->get_tensor(final_tile_input);state.hfa_requests.infer_requests[HFARequestSet::REGULAR_TILE]->set_tensor(tile_input, main_tensor);@@ -977,6 +984,12 @@ ov::npuw::v1::subgraphs::RuntimeBehaviorFactory make_runtime_factory() {tile_length)) {request->set_tensor(model->inputs()[tile_in.k], k_source);} else if (hfa_desc->_can_use_tensor_view) {+ OPENVINO_ASSERT(k_tile_buffer->get_element_type() == k_source->get_element_type(),+ "HFA K tile dtype mismatch: source=",+ k_source->get_element_type(),+ " tile_buffer=",+ k_tile_buffer->get_element_type(),+ ". Tile model was not constructed with the correct KV dtype.");request->set_tensor(model->inputs()[tile_in.k],ov::npuw::util::view(k_source, K_SEQ_DIM, kv_offset, tile_length));} else {@@ -990,6 +1003,12 @@ ov::npuw::v1::subgraphs::RuntimeBehaviorFactory make_runtime_factory() {tile_length)) {request->set_tensor(model->inputs()[tile_in.v], v_source);} else if (hfa_desc->_can_use_tensor_view) {+ OPENVINO_ASSERT(v_tile_buffer->get_element_type() == v_source->get_element_type(),+ "HFA V tile dtype mismatch: source=",+ v_source->get_element_type(),+ " tile_buffer=",+ v_tile_buffer->get_element_type(),+ ". Tile model was not constructed with the correct KV dtype.");request->set_tensor(model->inputs()[tile_in.v],ov::npuw::util::view(v_source, V_SEQ_DIM, kv_offset, tile_length));} else {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 026a4b9c521..87228370eaa 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@@ -58,8 +58,17 @@ struct FlashAttentionResults {// ============================================================================// Helper function: Create input parameters for HFA tile model// ============================================================================+// state_dtype : element type for past_acc / past_max / past_d (internal HFA state;+// typically f16 to match KV-block storage dtype).+// kv_tile_dtype: element type for k_tile / v_tile (the KV slice fed into each tile).+// May differ from state_dtype — e.g. f32 for the final tile that+// receives the freshly-computed present-KV from the upstream graph,+// vs f16 for regular tiles that read stored KV blocks.+// ============================================================================static HFATileInputs create_hfa_tile_inputs(const ov::Shape& q_shape,- const ov::element::Type& input_dtype,+ const ov::element::Type& state_dtype,+ const ov::element::Type& kv_tile_dtype,+ const ov::element::Type& q_dtype,const ov::element::Type& mask_dtype,int64_t tile_size,size_t kv_num_heads,@@ -77,22 +86,25 @@ static HFATileInputs create_hfa_tile_inputs(const ov::Shape& q_shape,param->output(0).get_tensor().set_names({name});};+ // State tensors (acc / max / d) use state_dtype so they stay consistent between+ // the regular tile output and the next tile's input without any conversion.// past_acc: [batch, num_heads, seq_len, head_dim]inputs.past_acc =- std::make_shared<ov::op::v0::Parameter>(input_dtype, ov::Shape{batch, num_heads, seq_len, head_dim});+ std::make_shared<ov::op::v0::Parameter>(state_dtype, ov::Shape{batch, num_heads, seq_len, head_dim});set_param_name(inputs.past_acc, HFATileInputId::PAST_ACC);// past_max: [batch, num_heads, seq_len, 1]- inputs.past_max = std::make_shared<ov::op::v0::Parameter>(input_dtype, ov::Shape{batch, num_heads, seq_len, 1});+ inputs.past_max = std::make_shared<ov::op::v0::Parameter>(state_dtype, ov::Shape{batch, num_heads, seq_len, 1});set_param_name(inputs.past_max, HFATileInputId::PAST_MAX);// past_d: [batch, num_heads, seq_len, 1]- inputs.past_d = std::make_shared<ov::op::v0::Parameter>(input_dtype, ov::Shape{batch, num_heads, seq_len, 1});+ inputs.past_d = std::make_shared<ov::op::v0::Parameter>(state_dtype, ov::Shape{batch, num_heads, seq_len, 1});set_param_name(inputs.past_d, HFATileInputId::PAST_D);+ // KV tile tensors use kv_tile_dtype (may differ from state_dtype).// k_tile: [batch, kv_num_heads, tile_size, head_dim]inputs.k_tile = std::make_shared<ov::op::v0::Parameter>(- input_dtype,+ kv_tile_dtype,ov::Shape{batch, kv_num_heads, static_cast<size_t>(tile_size), head_dim});set_param_name(inputs.k_tile, HFATileInputId::K_TILE);@@ -100,17 +112,18 @@ static HFATileInputs create_hfa_tile_inputs(const ov::Shape& q_shape,// [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,+ kv_tile_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,+ kv_tile_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]- inputs.q = std::make_shared<ov::op::v0::Parameter>(input_dtype, ov::Shape{batch, num_heads, seq_len, head_dim});+ // Q may run at a different precision from KV cache (e.g. f32 vs f16); use q_dtype.+ inputs.q = std::make_shared<ov::op::v0::Parameter>(q_dtype, ov::Shape{batch, num_heads, seq_len, head_dim});set_param_name(inputs.q, HFATileInputId::Q);// mask_tile: [batch, 1, seq_len, tile_size] - use mask's original dtype@@ -594,10 +607,17 @@ static ov::ResultVector create_regular_tile_outputs_fused(const FlashAttentionRe// Helper function: Create individual tile model (regular or final)// ============================================================================// Parameters:-// is_final_tile: If true, creates final tile with division/transpose/reshape-// output_dtype: Output data type (only used when is_final_tile=true)+// state_dtype : element type for past_acc / past_max / past_d state tensors+// (shared between regular and final tile — typically f16).+// kv_tile_dtype : element type for k_tile / v_tile.+// Regular tiles: f16 (KV-block storage dtype).+// Final tile: f32 (present-KV output dtype from upstream graph).+// is_final_tile : If true, creates final tile with division/transpose/reshape.+// output_dtype : Output data type (only used when is_final_tile=true).static std::shared_ptr<ov::Model> create_hfa_tile_model(const ov::Shape& q_shape,- const ov::element::Type& input_dtype,+ const ov::element::Type& state_dtype,+ const ov::element::Type& kv_tile_dtype,+ const ov::element::Type& q_dtype,const ov::element::Type& mask_dtype,int64_t tile_size,size_t kv_num_heads,@@ -607,7 +627,8 @@ static std::shared_ptr<ov::Model> create_hfa_tile_model(const ov::Shape& q_shapebool 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+ << ", kv_num_heads=" << kv_num_heads << ", state_dtype=" << state_dtype+ << ", kv_tile_dtype=" << kv_tile_dtype << ", mask_dtype=" << mask_dtype<< (is_final_tile ? ", output_dtype=" + output_dtype.get_type_name() : "")<< ", fused_flash_attention=" << fused_flash_attention);@@ -621,10 +642,17 @@ static std::shared_ptr<ov::Model> create_hfa_tile_model(const ov::Shape& q_shapeNPUW_ASSERT(num_heads % kv_num_heads == 0 && "Q heads must be divisible by KV heads");auto compute_dtype = ov::element::f32;- LOG_DEBUG("Using compute_dtype=f32 for all operations to match mask type");+ LOG_DEBUG("Using compute_dtype=f32 for all operations");// Create input parameters- auto inputs = create_hfa_tile_inputs(q_shape, input_dtype, mask_dtype, tile_size, kv_num_heads, v_transposed);+ auto inputs = create_hfa_tile_inputs(q_shape,+ state_dtype,+ kv_tile_dtype,+ q_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 if@@ -710,21 +738,23 @@ static std::shared_ptr<ov::Model> create_hfa_tile_model(const ov::Shape& q_shapehead_dim,fused_flash_attention);model_name = "HFA_Final_Tile";- LOG_DEBUG("HFA FINAL tile model created: inputs=" << input_dtype << ", compute=" << compute_dtype- << ", output=" << output_dtype);+ LOG_DEBUG("HFA FINAL tile model created: state=" << state_dtype << ", kv_tile=" << kv_tile_dtype << ", compute="+ << compute_dtype << ", output=" << output_dtype);} else {// === REGULAR TILE: Output intermediate states (acc, max, d) ===+ // State outputs use state_dtype so they can be directly reused as the next+ // tile's state inputs without any type conversion.if (fused_flash_attention) {LOG_DEBUG("Using fused flash attention implementation - outputs acc, max, d from separate nodes");- model_results = create_regular_tile_outputs_fused(results, input_dtype);+ model_results = create_regular_tile_outputs_fused(results, state_dtype);} else {LOG_DEBUG("Using host flash attention implementation - outputs acc, max, d from the same node");- model_results = create_regular_tile_outputs(results, input_dtype);+ model_results = create_regular_tile_outputs(results, state_dtype);}model_name = "HFA_Tile";- LOG_DEBUG("HFA tile model created: inputs=" << input_dtype << ", compute=" << compute_dtype- << ", outputs=" << input_dtype);+ LOG_DEBUG("HFA tile model created: state=" << state_dtype << ", kv_tile=" << kv_tile_dtype+ << ", compute=" << compute_dtype << ", state_out=" << state_dtype);}// Create model parameters@@ -979,7 +1009,22 @@ std::optional<HostFlashAttention> HostFlashAttention::from(const std::shared_ptr}auto q_shape_static = q_shape.to_shape();- auto dtype = q_input->get_output_element_type(0);+ // KV cache and Q may have different element types (e.g. f16 KV vs f32 Q).+ // block_kv_dtype: skip any Convert(f16→f32) that sits between the block Parameter+ // and the Concat; the Concat output may be upcast to f32 (Gemma-4) but the block+ // manager allocates tensors at the underlying storage dtype (f16).+ auto first_kv_node = skip_convert_nodes(k_concat->get_input_node_shared_ptr(0));+ const ov::element::Type block_kv_dtype = first_kv_node->get_output_element_type(0);++ // present_kv_dtype: dtype of the freshly-computed present-KV tensors that the+ // upstream NPU subgraph passes at runtime (typically f32).+ // The last input of k_concat is the present key; skip any Convert to get its+ // declared parameter dtype.+ auto present_kv_node = skip_convert_nodes(k_concat->get_input_node_shared_ptr(k_concat->get_input_size() - 1));+ const ov::element::Type present_kv_dtype = present_kv_node->get_output_element_type(0);++ const ov::element::Type q_dtype = q_input->get_output_element_type(0);+ LOG_DEBUG("HFA dtypes: block_kv=" << block_kv_dtype << ", present_kv=" << present_kv_dtype << ", q=" << q_dtype);// Validate Q shape and extract query_size (seq_len dimension)if (q_shape_static.size() != 4) {@@ -1053,9 +1098,18 @@ std::optional<HostFlashAttention> HostFlashAttention::from(const std::shared_ptr// 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);+ // Regular tile: state and KV-tile both use block_kv_dtype (f16).+ // past_acc/max/d: f16 k_tile/v_tile: f16 (from KV blocks)+ // Final tile: state still uses block_kv_dtype (f16) for zero-copy with regular+ // tile outputs; KV-tile uses present_kv_dtype (f32) matching the upstream graph.+ // past_acc/max/d: f16 k_tile/v_tile: f32 (present-KV from upstream)+ LOG_INFO("Creating HFA tile models: tile_size=" << query_size << ", v_transposed=" << v_transposed+ << ", block_kv=" << block_kv_dtype+ << ", present_kv=" << present_kv_dtype << ", q=" << q_dtype);auto tile_model = create_hfa_tile_model(q_shape_static,- dtype,+ block_kv_dtype, // state_dtype+ block_kv_dtype, // kv_tile_dtype (past blocks)+ q_dtype,mask_dtype,query_size,kv_num_heads,@@ -1069,7 +1123,9 @@ std::optional<HostFlashAttention> HostFlashAttention::from(const std::shared_ptr}auto final_tile_model = create_hfa_tile_model(q_shape_static,- dtype,+ block_kv_dtype, // state_dtype (consistent with regular tile)+ present_kv_dtype, // kv_tile_dtype (present-KV, f32)+ q_dtype,mask_dtype,query_size,kv_num_heads,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 aec51d3a2d6..f005b12fe7f 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@@ -11,6 +11,7 @@#include "openvino/op/add.hpp"#include "openvino/op/concat.hpp"+#include "openvino/op/convert.hpp"#include "openvino/op/matmul.hpp"#include "openvino/op/parameter.hpp"#include "openvino/op/result.hpp"@@ -81,6 +82,132 @@ std::shared_ptr<ov::Model> build_sdpa_model(size_t query_size = QUERY_SIZE,return model;}+// Build a model where Q is f32 but K/V cache are f16 (Gemma-4 style mixed precision).+std::shared_ptr<ov::Model> build_sdpa_model_mixed_dtype(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 size_t context_size = past_len + query_size;+ const Shape kv_shape = {BATCH, num_heads, past_len, head_dim};+ const Shape new_kv_shape = {BATCH, num_heads, query_size, head_dim};+ const Shape q_shape_s = {BATCH, num_heads, query_size, head_dim};+ const Shape mask_shape = {BATCH, 1, query_size, context_size};++ ParameterVector params;+ ResultVector results;+ auto make_param = [&](const std::string& name, const Shape& shape, element::Type dtype) {+ auto p = std::make_shared<op::v0::Parameter>(dtype, shape);+ p->set_friendly_name(name);+ p->output(0).get_tensor().set_names({name});+ params.push_back(p);+ return p;+ };++ // Q is f32 (compute precision), KV cache stored as f16 (storage precision),+ // present-KV from the upstream NPU subgraph is f32.+ // This mirrors the real Gemma-4 pattern:+ // Convert(f16 past_block) ─┐+ // f32 present_kv ┴→ Concat(f32) → MatMul+ auto query = make_param("query.0", q_shape_s, element::f32);+ auto past_key = make_param("past_key_values.0.key", kv_shape, element::f16);+ auto past_val = make_param("past_key_values.0.value", kv_shape, element::f16);+ auto new_key = make_param("new_key.0", new_kv_shape, element::f32);+ auto new_val = make_param("new_value.0", new_kv_shape, element::f32);+ auto mask = make_param("mask.0", mask_shape, element::f32);++ // Upcast stored f16 KV blocks before Concat (matches block_kv_dtype derivation).+ auto past_key_f32 = std::make_shared<op::v0::Convert>(past_key, element::f32);+ auto past_val_f32 = std::make_shared<op::v0::Convert>(past_val, element::f32);++ auto key_concat = std::make_shared<op::v0::Concat>(OutputVector{past_key_f32, new_key}, 2);+ key_concat->set_friendly_name("concat_key.0");+ auto val_concat = std::make_shared<op::v0::Concat>(OutputVector{past_val_f32, new_val}, 2);+ val_concat->set_friendly_name("concat_value.0");++ // Q@K and softmax@V — both sides already f32, no extra Convert needed.+ 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");+ auto matmul2 = std::make_shared<op::v0::MatMul>(softmax->output(0), val_concat);+ 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_mixed_dtype");+ model->validate_nodes_and_infer_types();+ return model;+}++} // namespace++// ============================================================================+// MixedDtype suite — Q=f32, KV=f16. The tile model must declare the Q+// parameter as f32 and KV/state parameters as f16, matching runtime tensors.+// ============================================================================++TEST(HostFlashAttentionMixedDtypeTest, FromReturnsValue) {+ EXPECT_TRUE(ov::npuw::function::HostFlashAttention::from(build_sdpa_model_mixed_dtype(), true).has_value());+}++// Helper: get element type of a model input by HFATileInputId name+static ov::element::Type get_input_dtype(const std::shared_ptr<ov::Model>& model, const std::string& name) {+ for (const auto& in : model->inputs()) {+ if (in.get_names().count(name))+ return in.get_element_type();+ }+ throw std::runtime_error("input '" + name + "' not found in model");+}++// Q parameter must be f32 (matching query_tensor dtype at runtime)+TEST(HostFlashAttentionMixedDtypeTest, Fused_QParamIsF32) {+ auto result = ov::npuw::function::HostFlashAttention::from(build_sdpa_model_mixed_dtype(), true);+ ASSERT_TRUE(result.has_value());+ EXPECT_EQ(get_input_dtype(result->_tile_model, "Q"), ov::element::f32)+ << "Q tile parameter must match query tensor dtype (f32)";+ EXPECT_EQ(get_input_dtype(result->_final_tile_model, "Q"), ov::element::f32);+}++// KV tile parameters: regular tile = f16 (KV block storage), final tile = f32 (present-KV).+// This is the core invariant of the mixed-dtype fix.+TEST(HostFlashAttentionMixedDtypeTest, Fused_KVTileParamsAreF16) {+ auto result = ov::npuw::function::HostFlashAttention::from(build_sdpa_model_mixed_dtype(), true);+ ASSERT_TRUE(result.has_value());+ // Regular tile reads stored KV blocks → f16.+ EXPECT_EQ(get_input_dtype(result->_tile_model, "K_TILE"), ov::element::f16)+ << "K_TILE parameter must match KV cache dtype (f16)";+ EXPECT_EQ(get_input_dtype(result->_tile_model, "V_TILE"), ov::element::f16)+ << "V_TILE parameter must match KV cache dtype (f16)";+ // Final tile receives present-KV from upstream NPU subgraph → f32.+ EXPECT_EQ(get_input_dtype(result->_final_tile_model, "K_TILE"), ov::element::f32)+ << "Final tile K_TILE must match present-KV dtype (f32)";+ EXPECT_EQ(get_input_dtype(result->_final_tile_model, "V_TILE"), ov::element::f32)+ << "Final tile V_TILE must match present-KV dtype (f32)";+}++// State parameters: both tile models use f16 so regular-tile outputs feed final-tile+// inputs without conversion.+TEST(HostFlashAttentionMixedDtypeTest, Fused_StateParamsAreF16) {+ auto result = ov::npuw::function::HostFlashAttention::from(build_sdpa_model_mixed_dtype(), true);+ ASSERT_TRUE(result.has_value());+ for (const auto& tile_model : {result->_tile_model, result->_final_tile_model}) {+ EXPECT_EQ(get_input_dtype(tile_model, "PAST_ACC"), ov::element::f16);+ EXPECT_EQ(get_input_dtype(tile_model, "PAST_MAX"), ov::element::f16);+ EXPECT_EQ(get_input_dtype(tile_model, "PAST_D"), ov::element::f16);+ }+}++namespace {+void expect_input_name(const std::shared_ptr<ov::Model>& model,size_t idx,const std::string& expected_name,