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: PA/semi static chunked dispatch (#37896)
Parth Maheshwarif1e29ba0b1cd
diff --git a/src/plugins/intel_npu/src/plugin/npuw/pa_compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/pa_compiled_model.cppindex 3ed56d6ac53..9b13c294c61 100644--- a/src/plugins/intel_npu/src/plugin/npuw/pa_compiled_model.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/pa_compiled_model.cpp@@ -4,32 +4,145 @@#include "pa_compiled_model.hpp"+#include <algorithm>+#include <array>+#include <cstdint>#include <cstdlib>+#include <cstring>+#include <map>+#include <sstream>#include <string>+#include <unordered_set>#include <utility>+#include <vector>#include "intel_npu/config/npuw.hpp"#include "logging.hpp"#include "openvino/runtime/iplugin.hpp"+#include "openvino/runtime/make_tensor.hpp"#include "openvino/runtime/properties.hpp"#include "util.hpp"+namespace {++// The block size the CPU PA executor and the CB pipeline both use. Not read+// off the cache ports: a u8 key cache keeps its scales in the block (dim 40).+constexpr std::size_t kBlockSize = 32u;++constexpr std::array<std::size_t, 3> kChunkSizes = {1024u, 128u, 1u};++// The PA op takes its controls as i32; the lm_head gather index is i64.+template <typename T>+std::vector<T> read_vec(const ov::SoPtr<ov::ITensor>& tensor) {+ const auto* data = tensor->data<T>();+ return {data, data + tensor->get_size()};+}++template <typename T>+ov::SoPtr<ov::ITensor> make_vec_tensor(const std::vector<T>& vals) {+ auto tensor = ov::get_tensor_impl(ov::Tensor(ov::element::from<T>(), ov::Shape{vals.size()}));+ std::copy(vals.begin(), vals.end(), tensor->data<T>());+ return tensor;+}++// The inputs run_chunk can rebase per chunk. A model with any other input+// (embeddings, M-RoPE, per-layer block tables, eviction) runs every dispatch 1:1.+bool is_chunkable_pa_model(const std::shared_ptr<ov::Model>& model) {+ static const std::unordered_set<std::string> supported = {"input_ids",+ "position_ids",+ "past_lens",+ "subsequence_begins",+ "block_indices",+ "block_indices_begins",+ "max_context_len",+ "score_aggregation_window",+ "sampled_tokens_indices"};+ std::unordered_set<std::string> seen;+ for (const auto& input : model->inputs()) {+ const auto& name = input.get_any_name();+ if (ov::npuw::util::is_pa_kv_cache_name(name)) {+ continue;+ }+ if (supported.count(name) == 0) {+ return false;+ }+ seen.insert(name);+ }+ for (const char* required : {"input_ids",+ "position_ids",+ "past_lens",+ "subsequence_begins",+ "block_indices",+ "block_indices_begins",+ "max_context_len",+ "sampled_tokens_indices"}) {+ if (seen.count(required) == 0) {+ return false;+ }+ }+ for (const char* name : {"input_ids", "position_ids"}) {+ const auto& rank = model->input(name).get_partial_shape().rank();+ if (rank.is_dynamic() || rank.get_length() != 1) {+ return false;+ }+ }+ const auto& outputs = model->outputs();+ if (outputs.size() != 1 || outputs.front().get_any_name() != "logits") {+ return false;+ }+ const auto& lshape = outputs.front().get_partial_shape();+ return lshape.rank().is_static() && lshape.rank().get_length() == 3 && lshape[1].is_static() &&+ lshape[2].is_static();+}++std::shared_ptr<ov::Model> derive_pa_semi_static_model(const std::shared_ptr<ov::Model>& base_model,+ std::size_t chunk_size) {+ for (const char* name : {"input_ids", "position_ids"}) {+ const auto& rank = base_model->input(name).get_partial_shape().rank();+ OPENVINO_ASSERT(rank.is_static() && rank.get_length() == 1, "PA: '", name, "' is not a 1-D token stream");+ }+ auto derived = base_model->clone();+ derived->reshape({{"input_ids", ov::PartialShape{static_cast<int64_t>(chunk_size)}},+ {"position_ids", ov::PartialShape{static_cast<int64_t>(chunk_size)}}});+ derived->set_friendly_name(base_model->get_friendly_name() + "_pa_token_" + std::to_string(chunk_size));+ return derived;+}++std::map<std::size_t, ov::SoPtr<ov::ICompiledModel>> compile_pa_semi_static_variants(+ const std::shared_ptr<ov::Model>& base_model,+ const std::shared_ptr<const ov::IPlugin>& plugin,+ const std::string& device,+ const ov::AnyMap& inner_config) {+ std::map<std::size_t, ov::SoPtr<ov::ICompiledModel>> variants;+ for (const auto chunk_size : kChunkSizes) {+ auto derived = derive_pa_semi_static_model(base_model, chunk_size);+ auto compiled = plugin->get_core()->compile_model(derived, device, inner_config);+ OPENVINO_ASSERT(compiled != nullptr,+ "PA semi-static derivation failed to compile chunk_size=",+ chunk_size,+ " on ",+ device);+ LOG_INFO("PA: compiled semi-static variant chunk_size=" << chunk_size << " on " << device);+ variants.emplace(chunk_size, std::move(compiled));+ }++ return variants;+}++} // anonymous namespace+ov::npuw::PACompiledModel::PACompiledModel(const std::shared_ptr<ov::Model>& model,const std::shared_ptr<const ov::IPlugin>& plugin,const ov::AnyMap& properties)- : ov::npuw::ICompiledModel(nullptr, plugin) { // I/O comes from the inner via inputs()/outputs()- // The fallback device is an internal development knob, not a config- // option - an env var keeps it out of user configs (and blob cache keys).- // Only CPU is supported for now: a GPU device would also need the remote- // context forwarded for the pipeline's cache allocation.+ : ov::npuw::ICompiledModel(nullptr, plugin) { // ports are the inner model's, see inputs()+ // An env var, not an option, so it stays out of user configs. GPU would also+ // need the remote context forwarded for the pipeline's cache allocation.const char* device_env = std::getenv("OPENVINO_NPUW_PA_DEVICE");const std::string device = (device_env != nullptr && device_env[0] != '\0') ? device_env : "CPU";OPENVINO_ASSERT(device == "CPU","The PagedAttention fallback device is CPU for now, got OPENVINO_NPUW_PA_DEVICE=",device);- // Sanity: this must be the model the CB pipeline deploys -- PA control- // inputs plus a paged KV cache.bool has_past_lens = false, has_cache = false;for (const auto& input : model->inputs()) {const auto& name = input.get_any_name();@@ -40,14 +153,11 @@ ov::npuw::PACompiledModel::PACompiledModel(const std::shared_ptr<ov::Model>& mod"PACompiledModel expects the continuous-batching PA model ""(past_lens + key_cache/value_cache inputs)");- // The 1:1 part: the model is compiled exactly as received. NPUW_*,- // NPU_USE_NPUW and NPU_* keys are this plugin's configuration and must not- // reach the executing device (which would reject them as unsupported);- // everything else (e.g. KV_CACHE_PRECISION, performance hints) is the- // executing device's business and is forwarded.+ // NPU* keys configure this plugin and DEVICE_ID names an NPU device; the+ // executing device would reject both. Everything else is forwarded.ov::AnyMap inner_config;for (const auto& [key, value] : properties) {- if (ov::npuw::util::starts_with(key, "NPU")) {+ if (ov::npuw::util::starts_with(key, "NPU") || key == ov::device::id.name()) {continue;}inner_config.emplace(key, value);@@ -56,6 +166,13 @@ ov::npuw::PACompiledModel::PACompiledModel(const std::shared_ptr<ov::Model>& modLOG_INFO("PA: compiling the dynamic PA model 1:1 on " << device);m_compiled_model = plugin->get_core()->compile_model(model, device, inner_config);OPENVINO_ASSERT(m_compiled_model != nullptr, "PACompiledModel requires a valid inner compiled model");++ if (is_chunkable_pa_model(model)) {+ m_semi_static_models = compile_pa_semi_static_variants(model, plugin, device, inner_config);+ } else {+ LOG_INFO("PA: model is outside the chunkable flat-token contract; every dispatch runs 1:1");+ }+ LOG_INFO("PA: " << m_semi_static_models.size() << " semi-static variant(s) on " << device);}const std::vector<ov::Output<const ov::Node>>& ov::npuw::PACompiledModel::inputs() const {@@ -75,8 +192,7 @@ std::shared_ptr<const ov::Model> ov::npuw::PACompiledModel::get_runtime_model()}void ov::npuw::PACompiledModel::set_property(const ov::AnyMap& properties) {- // The PA-level options are fixed at compile time; catching them here gives- // a clear error instead of the executing device's "unsupported property".+ // A clear error instead of the executing device's "unsupported property".for (const auto& [key, value] : properties) {if (ov::npuw::util::starts_with(key, "NPU")) {OPENVINO_THROW("PACompiledModel: '", key, "' cannot be changed after the model is compiled");@@ -86,15 +202,12 @@ void ov::npuw::PACompiledModel::set_property(const ov::AnyMap& properties) {}ov::Any ov::npuw::PACompiledModel::get_property(const std::string& name) const {- // The PA-level key is answered here; everything else is the executing- // device's business (notably ov::execution_devices, which the CB pipeline- // queries to pick its block size).+ // Everything but NPUW_PA is the executing device's, including+ // execution_devices, which the CB pipeline reads to pick its block size.if (name == std::string(::intel_npu::NPUW_PA::key())) {return true;}if (name == ov::supported_properties.name()) {- // Keep the property surface self-consistent: the inner device's list- // plus the PA key answered above.auto props = m_compiled_model->get_property(name).as<std::vector<ov::PropertyName>>();props.emplace_back(std::string(::intel_npu::NPUW_PA::key()), ov::PropertyMutability::RO);return props;@@ -106,19 +219,225 @@ std::shared_ptr<ov::ISyncInferRequest> ov::npuw::PACompiledModel::create_sync_inauto self = std::static_pointer_cast<const ov::ICompiledModel>(shared_from_this());auto inner_request = m_compiled_model->create_infer_request();OPENVINO_ASSERT(inner_request != nullptr, "PACompiledModel requires a valid inner infer request");- return std::make_shared<PAInferRequest>(self, std::move(inner_request));+ return std::make_shared<PAInferRequest>(self, std::move(inner_request), m_semi_static_models);}ov::npuw::PAInferRequest::PAInferRequest(const std::shared_ptr<const ov::ICompiledModel>& compiled_model,- ov::SoPtr<ov::IAsyncInferRequest> inner_request)+ ov::SoPtr<ov::IAsyncInferRequest> inner_request,+ const std::map<std::size_t, ov::SoPtr<ov::ICompiledModel>>& variants): ov::ISyncInferRequest(compiled_model),- m_inner_request(std::move(inner_request)) {}+ m_inner_request(std::move(inner_request)) {+ for (const auto& input : get_inputs()) {+ m_inputs_by_name.emplace(input.get_any_name(), input);+ }++ // One request per variant plus a dynamic one for residual chunks.+ const auto make_chunk_request = [](const auto& compiled) {+ ChunkRequest chunk;+ chunk.request = compiled->create_infer_request();+ OPENVINO_ASSERT(chunk.request != nullptr, "PA chunk model requires a valid infer request");+ for (const auto& input : compiled->inputs()) {+ chunk.inputs.emplace(input.get_any_name(), input);+ }+ chunk.logits = compiled->outputs().front();+ return chunk;+ };+ for (const auto& [chunk_size, compiled] : variants) {+ m_chunk_requests.emplace(chunk_size, make_chunk_request(compiled));+ m_chunk_sizes.push_back(chunk_size);+ }+ if (!m_chunk_requests.empty()) {+ m_tail_request = make_chunk_request(m_inner_request->get_compiled_model());+ m_logits_node = get_outputs().front().get_node();+ }+}++ov::npuw::pa::Dispatch ov::npuw::PAInferRequest::parse_dispatch() const {+ const auto get = [&](const char* name) {+ auto it = m_inputs_by_name.find(name);+ OPENVINO_ASSERT(it != m_inputs_by_name.end(), "PA model has no '", name, "' input");+ return m_inner_request->get_tensor(it->second);+ };++ pa::Dispatch d;+ d.past_lens = read_vec<int32_t>(get("past_lens"));+ d.subsequence_begins = read_vec<int32_t>(get("subsequence_begins"));+ const auto mcl_vec = read_vec<int32_t>(get("max_context_len"));+ OPENVINO_ASSERT(!mcl_vec.empty(), "PA dispatch: max_context_len is not set");+ d.max_context_len = mcl_vec.front();++ // Embedding models have no input_ids; M-RoPE position_ids carry the token+ // count in the last dim.+ if (m_inputs_by_name.count("input_ids") > 0) {+ d.input_ids_size = static_cast<int64_t>(get("input_ids")->get_size());+ }+ const auto& pos_shape = get("position_ids")->get_shape();+ OPENVINO_ASSERT(!pos_shape.empty(), "PA dispatch: position_ids has no shape");+ d.position_ids_token_count = static_cast<int64_t>(pos_shape.back());++ // Eviction models carry per-layer block tables instead and run 1:1.+ if (m_inputs_by_name.count("block_indices") > 0) {+ d.has_block_table = true;+ d.block_indices = read_vec<int32_t>(get("block_indices"));+ d.block_indices_begins = read_vec<int32_t>(get("block_indices_begins"));+ }+ if (m_inputs_by_name.count("sampled_tokens_indices") > 0) {+ d.has_sampled_tokens = true;+ d.sampled_tokens_indices = read_vec<int64_t>(get("sampled_tokens_indices"));+ }+ return d;+}++void ov::npuw::PAInferRequest::run_chunk(ChunkRequest& chunk,+ const pa::Dispatch& d,+ int64_t seq,+ int64_t seq_offset,+ int64_t n_chunk_tokens) {+ const auto global_start = d.subsequence_begins[seq] + seq_offset;+ const auto set = [&](const char* name, const ov::SoPtr<ov::ITensor>& tensor) {+ auto it = chunk.inputs.find(name);+ OPENVINO_ASSERT(it != chunk.inputs.end(), "PA chunk model has no '", name, "' input");+ chunk.request->set_tensor(it->second, tensor);+ };+ const auto inner = [&](const char* name) {+ return m_inner_request->get_tensor(m_inputs_by_name.at(name));+ };++ // The caller's tensors outlive this infer, so the chunk can view them.+ const auto slice = [&](const char* name, int64_t start, int64_t n) {+ return ov::npuw::util::view(inner(name), 0, static_cast<std::size_t>(start), static_cast<std::size_t>(n));+ };++ set("input_ids", slice("input_ids", global_start, n_chunk_tokens));+ set("position_ids", slice("position_ids", global_start, n_chunk_tokens));++ // One subsequence, past its first seq_offset tokens, with its full block table.+ set("past_lens", make_vec_tensor<int32_t>({static_cast<int32_t>(d.past_lens[seq] + seq_offset)}));+ set("subsequence_begins", make_vec_tensor<int32_t>({0, static_cast<int32_t>(n_chunk_tokens)}));+ const auto blocks_begin = d.block_indices_begins[seq];+ const auto n_seq_blocks = d.block_indices_begins[seq + 1] - blocks_begin;+ set("block_indices", slice("block_indices", blocks_begin, n_seq_blocks));+ set("block_indices_begins", make_vec_tensor<int32_t>({0, n_seq_blocks}));+ if (m_inputs_by_name.count("score_aggregation_window") > 0) {+ set("score_aggregation_window", slice("score_aggregation_window", seq, 1));+ }++ set("max_context_len", inner("max_context_len"));+ for (const auto& [name, port] : chunk.inputs) {+ if (ov::npuw::util::is_pa_kv_cache_name(name)) {+ chunk.request->set_tensor(port, m_inner_request->get_tensor(m_inputs_by_name.at(name)));+ }+ }++ // Sampled rows in this chunk, with their row in the caller's output.+ std::vector<int64_t> local_sti;+ std::vector<std::size_t> out_rows;+ for (std::size_t i = 0; i < d.sampled_tokens_indices.size(); ++i) {+ const auto g = d.sampled_tokens_indices[i];+ if (g >= global_start && g < global_start + n_chunk_tokens) {+ local_sti.push_back(g - global_start);+ out_rows.push_back(i);+ }+ }+ set("sampled_tokens_indices", make_vec_tensor<int64_t>(local_sti));++ // The logits port is dynamic (one row per sampled token) and NPUW sizes+ // unset outputs from the port, so set an exact-sized tensor.+ const auto& oshape = m_chunked_logits->get_shape();+ const auto out = ov::get_tensor_impl(+ ov::Tensor(m_chunked_logits->get_element_type(), ov::Shape{local_sti.size(), oshape.at(1), oshape.at(2)}));+ chunk.request->set_tensor(chunk.logits, out);++ chunk.request->infer();++ if (out_rows.empty()) {+ return;+ }+ const auto row_bytes = oshape.at(1) * oshape.at(2) * m_chunked_logits->get_element_type().size();+ const auto* src = static_cast<const uint8_t*>(out->data());+ auto* dst = static_cast<uint8_t*>(m_chunked_logits->data());+ for (std::size_t j = 0; j < out_rows.size(); ++j) {+ std::memcpy(dst + out_rows[j] * row_bytes, src + j * row_bytes, row_bytes);+ }+}++void ov::npuw::PAInferRequest::infer_chunked(const pa::Dispatch& d) {+ const auto& logits_port = get_outputs().front();+ const auto& lshape = logits_port.get_partial_shape();+ m_chunked_logits = ov::get_tensor_impl(ov::Tensor(logits_port.get_element_type(),+ ov::Shape{d.sampled_tokens_indices.size(),+ static_cast<std::size_t>(lshape[1].get_length()),+ static_cast<std::size_t>(lshape[2].get_length())}));++ const bool verbose = ov::npuw::get_log_level() >= ov::npuw::LogLevel::Verbose;+ std::ostringstream plan;++ for (int64_t s = 0; s < d.sequences(); ++s) {+ const auto seq_len = d.subsequence_begins[s + 1] - d.subsequence_begins[s];+ int64_t off = 0;+ if (verbose) {+ plan << (s ? "; " : "") << "seq" << s << "=";+ }+ while (off < seq_len) {+ const auto remaining = seq_len - off;+ // Largest variant that fits; the 1-token one only for a single+ // remaining token. Anything else goes to the dynamic model.+ std::size_t pick = 0u;+ for (const auto& [chunk_size, _] : m_chunk_requests) {+ if (static_cast<int64_t>(chunk_size) <= remaining && (chunk_size > 1u || remaining == 1)) {+ pick = chunk_size;+ break;+ }+ }+ auto& chunk = pick ? m_chunk_requests.at(pick) : m_tail_request;+ const auto n = pick ? static_cast<int64_t>(pick) : remaining;+ if (verbose) {+ plan << (off ? "+" : "") << (pick ? "" : "dyn:") << n;+ }+ run_chunk(chunk, d, s, off, n);+ off += n;+ }+ }+ if (verbose) {+ LOG_VERB("PA dispatch #" << m_dispatch_idx << ": chunked " << plan.str());+ }+}++void ov::npuw::PAInferRequest::log_dispatch_io(bool outputs) const {+ if (ov::npuw::get_log_level() < ov::npuw::LogLevel::Verbose) {+ return;+ }+ LOG_VERB("PA dispatch #" << m_dispatch_idx << (outputs ? " outputs:" : " inputs:"));+ LOG_BLOCK();+ for (const auto& port : outputs ? get_outputs() : get_inputs()) {+ const auto& name = port.get_any_name();+ const auto tensor = outputs && m_serve_chunked_logits ? m_chunked_logits : m_inner_request->get_tensor(port);+ LOG_VERB(name << ": " << ov::npuw::util::TensorBrief{tensor});+ }+}void ov::npuw::PAInferRequest::infer() {- m_inner_request->infer();+ log_dispatch_io(/*outputs=*/false);+ const auto dispatch = parse_dispatch();+ pa::validate_dispatch(dispatch, kBlockSize, m_dispatch_idx);+ LOG_VERB("PA dispatch #" << m_dispatch_idx << ": " << dispatch.sequences() << " subsequence(s), "+ << dispatch.tokens() << " token(s), " << dispatch.sampled_tokens_indices.size()+ << " sampled");+ if (pa::variants_serve(dispatch, m_chunk_sizes)) {+ infer_chunked(dispatch);+ m_serve_chunked_logits = true;+ } else {+ m_serve_chunked_logits = false;+ m_inner_request->infer();+ }+ log_dispatch_io(/*outputs=*/true);+ ++m_dispatch_idx;}ov::SoPtr<ov::ITensor> ov::npuw::PAInferRequest::get_tensor(const ov::Output<const ov::Node>& port) const {+ if (m_serve_chunked_logits && port.get_node() == m_logits_node) {+ return m_chunked_logits;+ }return m_inner_request->get_tensor(port);}@@ -128,9 +447,7 @@ void ov::npuw::PAInferRequest::set_tensor(const ov::Output<const ov::Node>& port}void ov::npuw::PAInferRequest::check_tensors() const {- // Tensors live in the inner request, so the base-class check over this- // level's (empty) tensor storage must not run. The inner request performs- // the same element-type/shape validation on its own tensors during infer().+ // Tensors live in the inner request, which checks them itself.}std::vector<ov::SoPtr<ov::IVariableState>> ov::npuw::PAInferRequest::query_state() const {diff --git a/src/plugins/intel_npu/src/plugin/npuw/pa_compiled_model.hpp b/src/plugins/intel_npu/src/plugin/npuw/pa_compiled_model.hppindex 98afc54a7d4..ec4079dae43 100644--- a/src/plugins/intel_npu/src/plugin/npuw/pa_compiled_model.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/pa_compiled_model.hpp@@ -4,28 +4,29 @@#pragma once+#include <cstddef>+#include <functional>+#include <map>#include <memory>+#include <string>+#include <unordered_map>+#include <vector>#include "npuw/compiled_model.hpp"+#include "pa_dispatch.hpp"namespace ov::npuw {-// The front-end for the dynamic, stateless PagedAttention model deployed by-// the GenAI continuous-batching pipeline. The model is compiled 1:1 on the PA-// fallback device (CPU; the internal OPENVINO_NPUW_PA_DEVICE env var exists-// for development), NPU*-prefixed properties are held at this level while-// everything else is forwarded to the executing device.-//-// The exposed ports are the inner compiled model's own ports, so the cache-// geometry the pipeline's KVCacheManager reads off them (element types,-// block shapes) is the device-resolved truth with no copying involved.+// Front-end for the dynamic PagedAttention model the GenAI CB pipeline+// deploys. The model is compiled 1:1 on the PA device (CPU) next to its+// semi-static variants. The ports are the inner model's, so the pipeline reads+// the device-resolved KV cache geometry off them.class PACompiledModel final : public ov::npuw::ICompiledModel {public:PACompiledModel(const std::shared_ptr<ov::Model>& model,const std::shared_ptr<const ov::IPlugin>& plugin,const ov::AnyMap& properties);- // The wrapper adds no I/O of its own -- it exposes the inner model's ports.const std::vector<ov::Output<const ov::Node>>& inputs() const override;const std::vector<ov::Output<const ov::Node>>& outputs() const override;@@ -39,16 +40,20 @@ private:std::shared_ptr<ov::ISyncInferRequest> create_sync_infer_request() const override;ov::SoPtr<ov::ICompiledModel> m_compiled_model;++ // Keyed by chunk size.+ std::map<std::size_t, ov::SoPtr<ov::ICompiledModel>> m_semi_static_models;};-// 1:1 forwarding request. The ports are shared with the inner request (see-// PACompiledModel), so every call delegates without translation, and the-// request holds no state of its own -- it provides exactly the guarantees of-// using the inner request directly.+// Validates each dispatch, then runs it 1:1 or splits every subsequence into+// chunks over the variants, largest first, with a dynamic tail. Chunks fix only+// the token count: the cache is addressed through the caller's block tables,+// so nothing is padded.class PAInferRequest final : public ov::ISyncInferRequest {public:PAInferRequest(const std::shared_ptr<const ov::ICompiledModel>& compiled_model,- ov::SoPtr<ov::IAsyncInferRequest> inner_request);+ ov::SoPtr<ov::IAsyncInferRequest> inner_request,+ const std::map<std::size_t, ov::SoPtr<ov::ICompiledModel>>& variants);void infer() override;@@ -60,7 +65,34 @@ public:std::vector<ov::ProfilingInfo> get_profiling_info() const override;private:+ struct ChunkRequest {+ ov::SoPtr<ov::IAsyncInferRequest> request;+ std::unordered_map<std::string, ov::Output<const ov::Node>> inputs;+ ov::Output<const ov::Node> logits;+ };++ pa::Dispatch parse_dispatch() const;+ void log_dispatch_io(bool outputs) const;++ void infer_chunked(const pa::Dispatch& d);+ void run_chunk(ChunkRequest& chunk, const pa::Dispatch& d, int64_t seq, int64_t seq_offset, int64_t n_chunk_tokens);+ov::SoPtr<ov::IAsyncInferRequest> m_inner_request;++ std::unordered_map<std::string, ov::Output<const ov::Node>> m_inputs_by_name;++ // Largest first. The caller's tensors stay in m_inner_request.+ std::map<std::size_t, ChunkRequest, std::greater<std::size_t>> m_chunk_requests;+ std::vector<std::size_t> m_chunk_sizes;+ ChunkRequest m_tail_request;++ // The chunked path's result, served by get_tensor().+ ov::SoPtr<ov::ITensor> m_chunked_logits;+ bool m_serve_chunked_logits = false;+ const ov::Node* m_logits_node = nullptr;++ // No lock: one request, one user.+ std::size_t m_dispatch_idx = 0u;};} // namespace ov::npuwdiff --git a/src/plugins/intel_npu/src/plugin/npuw/pa_dispatch.cpp b/src/plugins/intel_npu/src/plugin/npuw/pa_dispatch.cppnew file mode 100644index 00000000000..09c0d1a5f37--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/pa_dispatch.cpp@@ -0,0 +1,85 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "pa_dispatch.hpp"++#include <algorithm>++#include "openvino/core/except.hpp"++void ov::npuw::pa::validate_dispatch(const Dispatch& d, std::size_t block_size, std::size_t dispatch_idx) {+ const auto expect = [&](bool cond, const char* what) {+ OPENVINO_ASSERT(cond, "PA dispatch #", dispatch_idx, " violates the PA model expectations: ", what);+ };++ const auto& past = d.past_lens;+ const auto& sub = d.subsequence_begins;+ const auto n_seqs = d.sequences();+ const auto n_tokens = d.tokens();++ // Embedding models have no input_ids; M-RoPE position_ids carry the token+ // count in the last dim.+ if (d.input_ids_size >= 0) {+ expect(d.input_ids_size == n_tokens, "input_ids size != subsequence_begins token count");+ }+ expect(d.position_ids_token_count == n_tokens, "position_ids last dim != subsequence_begins token count");+ expect(static_cast<int64_t>(sub.size()) == n_seqs + 1, "subsequence_begins size != past_lens size + 1");+ expect(sub.front() == 0, "subsequence_begins does not start at 0");+ expect(std::is_sorted(sub.begin(), sub.end()) && std::adjacent_find(sub.begin(), sub.end()) == sub.end(),+ "subsequence_begins is not strictly increasing");++ // Eviction models carry per-layer block tables instead.+ if (d.has_block_table) {+ const auto& bib = d.block_indices_begins;+ expect(static_cast<int64_t>(bib.size()) == n_seqs + 1, "block_indices_begins size != past_lens size + 1");+ expect(bib.front() == 0 && bib.back() == static_cast<int64_t>(d.block_indices.size()) &&+ std::is_sorted(bib.begin(), bib.end()),+ "block_indices_begins is not a prefix-sum over block_indices");+ }++ for (int64_t s = 0; s < n_seqs; ++s) {+ const auto ctx_after = past[s] + (sub[s + 1] - sub[s]);+ expect(past[s] >= 0, "negative past_lens entry");+ expect(d.max_context_len >= ctx_after, "max_context_len < a subsequence's context length");+ if (d.has_block_table && block_size > 0) {+ expect((d.block_indices_begins[s + 1] - d.block_indices_begins[s]) * static_cast<int64_t>(block_size) >=+ ctx_after,+ "block_indices do not cover a subsequence's context");+ }+ }++ // An empty selection is legal (intermediate prefill chunks).+ if (d.has_sampled_tokens) {+ for (auto idx : d.sampled_tokens_indices) {+ expect(idx >= 0 && idx < n_tokens, "sampled_tokens_indices out of token range");+ }+ }+}++bool ov::npuw::pa::variants_serve(const Dispatch& dispatch, const std::vector<std::size_t>& chunk_sizes) {+ if (chunk_sizes.empty() || dispatch.tokens() == 0) {+ return false;+ }++ bool has_one_token_variant = false;+ std::size_t min_multi_token = 0u;+ for (const auto chunk_size : chunk_sizes) {+ has_one_token_variant |= (chunk_size == 1u);+ if (chunk_size > 1u && (min_multi_token == 0u || chunk_size < min_multi_token)) {+ min_multi_token = chunk_size;+ }+ }++ if (dispatch.sequences() == 1 && dispatch.tokens() == 1) {+ return has_one_token_variant;+ }++ for (int64_t s = 0; min_multi_token > 0u && s < dispatch.sequences(); ++s) {+ const auto seq_len = dispatch.subsequence_begins[s + 1] - dispatch.subsequence_begins[s];+ if (seq_len >= static_cast<int64_t>(min_multi_token)) {+ return true;+ }+ }+ return false;+}diff --git a/src/plugins/intel_npu/src/plugin/npuw/pa_dispatch.hpp b/src/plugins/intel_npu/src/plugin/npuw/pa_dispatch.hppnew file mode 100644index 00000000000..4e133ac9d92--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/pa_dispatch.hpp@@ -0,0 +1,44 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstddef>+#include <cstdint>+#include <vector>++namespace ov::npuw::pa {++// Host copies of one dispatch's control tensors, so the checks below are pure+// functions.+struct Dispatch {+ std::vector<int32_t> past_lens;+ std::vector<int32_t> subsequence_begins;+ std::vector<int32_t> block_indices; // meaningful when has_block_table+ std::vector<int32_t> block_indices_begins; // meaningful when has_block_table+ std::vector<int64_t> sampled_tokens_indices; // meaningful when has_sampled_tokens+ int64_t max_context_len = 0;+ int64_t input_ids_size = -1; // -1 when the model has no input_ids input+ int64_t position_ids_token_count = 0; // last dim of position_ids+ bool has_block_table = false;+ bool has_sampled_tokens = false;++ int64_t tokens() const {+ return subsequence_begins.empty() ? int64_t{0} : int64_t{subsequence_begins.back()};+ }+ int64_t sequences() const {+ return static_cast<int64_t>(past_lens.size());+ }+};++// Throws on the first violation of the PA model expectations. A block_size of+// 0 skips the block-table coverage check.+void validate_dispatch(const Dispatch& dispatch, std::size_t block_size, std::size_t dispatch_idx);++// True when the dispatch runs chunked over the variants: some subsequence fills+// a multi-token variant, or it is a single-sequence decode. A decode batch or a+// short prefill stays one 1:1 infer, which chunking would only serialize.+bool variants_serve(const Dispatch& dispatch, const std::vector<std::size_t>& chunk_sizes);++} // namespace ov::npuw::padiff --git a/src/plugins/intel_npu/src/plugin/npuw/util.cpp b/src/plugins/intel_npu/src/plugin/npuw/util.cppindex 0b887da8140..1857f168ae9 100644--- a/src/plugins/intel_npu/src/plugin/npuw/util.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/util.cpp@@ -1081,6 +1081,46 @@ bool ov::npuw::util::is_pa_kv_cache_name(const std::string& input_name) {return ov::npuw::util::starts_with(input_name, "key_cache.") ||ov::npuw::util::starts_with(input_name, "value_cache.");}++std::ostream& ov::npuw::util::operator<<(std::ostream& os, const TensorBrief& brief) {+ const auto& tensor = brief.tensor;+ const auto type = tensor->get_element_type();+ const auto n = tensor->get_size();+ os << type << " " << tensor->get_shape();+ const bool readable =+ type == ov::element::f32 || type == ov::element::f16 || type == ov::element::i32 || type == ov::element::i64;+ if (!readable || n == 0 || n > TensorBrief::kMaxStats) {+ return os;+ }+ const auto value_at = [&](std::size_t i) -> double {+ if (type == ov::element::f32) {+ return tensor->data<float>()[i];+ }+ if (type == ov::element::f16) {+ return static_cast<float>(tensor->data<ov::float16>()[i]);+ }+ if (type == ov::element::i32) {+ return tensor->data<int32_t>()[i];+ }+ return static_cast<double>(tensor->data<int64_t>()[i]);+ };+ if (n <= TensorBrief::kMaxInline) {+ os << " {";+ for (std::size_t i = 0; i < n; ++i) {+ os << (i ? ", " : "") << value_at(i);+ }+ return os << "}";+ }+ auto lo = value_at(0), hi = lo, sum = 0.0;+ for (std::size_t i = 0; i < n; ++i) {+ const auto v = value_at(i);+ lo = std::min(lo, v);+ hi = std::max(hi, v);+ sum += v;+ }+ return os << " min=" << lo << " max=" << hi << " mean=" << sum / static_cast<double>(n);+}+void ov::npuw::util::fill_tensor_bytes(ov::SoPtr<ov::ITensor> tensor, uint8_t fill_val) {auto* tensor_data = reinterpret_cast<uint8_t*>(tensor->data());const size_t byte_size = tensor->get_byte_size();diff --git a/src/plugins/intel_npu/src/plugin/npuw/util.hpp b/src/plugins/intel_npu/src/plugin/npuw/util.hppindex 926dfcf27b6..688a3c65d78 100644--- a/src/plugins/intel_npu/src/plugin/npuw/util.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/util.hpp@@ -6,6 +6,7 @@#include <future>#include <optional>+#include <ostream>#include <random>#include <string>#include <unordered_set>@@ -252,6 +253,15 @@ bool is_swa_kv_cache_name(const std::string& input_name);// by the SDPAToPagedAttention transformation).bool is_pa_kv_cache_name(const std::string& input_name);+// One-line tensor digest for log traces: LOG_VERB("x: " << TensorBrief{t}).+// Tensors past kMaxStats elements, such as KV cache pools, print their shape only.+struct TensorBrief {+ static constexpr std::size_t kMaxInline = 16u;+ static constexpr std::size_t kMaxStats = 1u << 20;+ ov::SoPtr<ov::ITensor> tensor;+};+std::ostream& operator<<(std::ostream& os, const TensorBrief& brief);+// Structure to hold SDPA pattern nodes.// After SplitKVCacheIntoBlocks the single past_key / past_value parameter is// replaced by N block parameters, so both param-node fields are vectors.diff --git a/src/plugins/intel_npu/src/plugin/sources.cmake b/src/plugins/intel_npu/src/plugin/sources.cmakeindex 465480e169b..d20f670ada6 100644--- a/src/plugins/intel_npu/src/plugin/sources.cmake+++ b/src/plugins/intel_npu/src/plugin/sources.cmake@@ -170,6 +170,8 @@ set(NPUW_SOURCES${CMAKE_CURRENT_SOURCE_DIR}/npuw/orc/schema_npuw.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/pa_compiled_model.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/pa_compiled_model.hpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/pa_dispatch.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/pa_dispatch.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/partitioning/online/compiler.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/partitioning/online/compiler.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/partitioning/online/graph.cppdiff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex 700f0318aa7..9ba46393cd0 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -53,6 +53,7 @@ ov_add_test_target(${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/flux2_compiled_model.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/gqa_compiled_model.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/pa_compiled_model.cpp+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/pa_dispatch.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp@@ -195,6 +196,7 @@ target_sources(${TARGET_NAME} PRIVATE${CMAKE_CURRENT_SOURCE_DIR}/npuw/model_builder_lora_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/partitioning_options_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_options_smoke_test.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/pa_dispatch_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/pre_compute_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/resolve_dynamic_quant_storage_types_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/orc.cppdiff --git a/src/plugins/intel_npu/tests/unit/npuw/pa_dispatch_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pa_dispatch_test.cppnew file mode 100644index 00000000000..ea3b943bede--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/pa_dispatch_test.cpp@@ -0,0 +1,213 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Unit tests for the PA dispatch-contract validation (ov::npuw::pa). The+// contract is a pure function over the parsed control tensors, so the tests+// construct Dispatch values directly and assert on the specific violation+// each malformed dispatch must report.++#include "pa_dispatch.hpp"++#include <gtest/gtest.h>++#include <string>++#include "openvino/core/except.hpp"++namespace {++using ov::npuw::pa::Dispatch;+using ov::npuw::pa::validate_dispatch;+using ov::npuw::pa::variants_serve;++// A well-formed two-subsequence dispatch: 4 + 2 scheduled tokens on top of+// 0 / 6 past tokens, a covering block table (block_size 4) and one sampled+// token per subsequence.+Dispatch make_valid_dispatch() {+ Dispatch d;+ d.past_lens = {0, 6};+ d.subsequence_begins = {0, 4, 6};+ d.block_indices = {0, 1, 2};+ d.block_indices_begins = {0, 1, 3};+ d.sampled_tokens_indices = {3, 5};+ d.max_context_len = 8;+ d.input_ids_size = 6;+ d.position_ids_token_count = 6;+ d.has_block_table = true;+ d.has_sampled_tokens = true;+ return d;+}++constexpr std::size_t kBlockSize = 4u;++void expect_violation(const Dispatch& d, const std::string& what, std::size_t block_size = kBlockSize) {+ try {+ validate_dispatch(d, block_size, 0u);+ FAIL() << "expected a dispatch-contract violation: " << what;+ } catch (const ov::Exception& ex) {+ EXPECT_NE(std::string(ex.what()).find(what), std::string::npos) << ex.what();+ }+}++TEST(PADispatchContract, ValidDispatchPasses) {+ EXPECT_NO_THROW(validate_dispatch(make_valid_dispatch(), kBlockSize, 0u));+}++TEST(PADispatchContract, TokenAndSequenceCountsDerive) {+ const auto d = make_valid_dispatch();+ EXPECT_EQ(d.tokens(), 6);+ EXPECT_EQ(d.sequences(), 2);+}++// input_ids is absent on embedding-input models; -1 skips the cross-check.+TEST(PADispatchContract, AbsentInputIdsIsLegal) {+ auto d = make_valid_dispatch();+ d.input_ids_size = -1;+ EXPECT_NO_THROW(validate_dispatch(d, kBlockSize, 0u));+}++TEST(PADispatchContract, InputIdsSizeMismatchRejected) {+ auto d = make_valid_dispatch();+ d.input_ids_size = 5;+ expect_violation(d, "input_ids size != subsequence_begins token count");+}++TEST(PADispatchContract, PositionIdsCountMismatchRejected) {+ auto d = make_valid_dispatch();+ d.position_ids_token_count = 7;+ expect_violation(d, "position_ids last dim != subsequence_begins token count");+}++TEST(PADispatchContract, SubsequenceBeginsSizeMismatchRejected) {+ auto d = make_valid_dispatch();+ d.past_lens = {0}; // now sub.size() != past.size() + 1+ expect_violation(d, "subsequence_begins size != past_lens size + 1");+}++TEST(PADispatchContract, SubsequenceBeginsMustStartAtZero) {+ auto d = make_valid_dispatch();+ d.subsequence_begins = {1, 4, 6};+ expect_violation(d, "subsequence_begins does not start at 0");+}++TEST(PADispatchContract, SubsequenceBeginsMustStrictlyIncrease) {+ auto d = make_valid_dispatch();+ d.subsequence_begins = {0, 4, 4};+ d.input_ids_size = 4;+ d.position_ids_token_count = 4;+ d.sampled_tokens_indices = {3, 3};+ expect_violation(d, "subsequence_begins is not strictly increasing");+}++TEST(PADispatchContract, NegativePastLenRejected) {+ auto d = make_valid_dispatch();+ d.past_lens = {0, -1};+ expect_violation(d, "negative past_lens entry");+}++TEST(PADispatchContract, MaxContextLenMustBoundEveryContext) {+ auto d = make_valid_dispatch();+ d.max_context_len = 7; // subsequence 1 context is 6 past + 2 scheduled = 8+ expect_violation(d, "max_context_len < a subsequence's context length");+}++TEST(PADispatchContract, BlockIndicesBeginsMustBePrefixSum) {+ auto d = make_valid_dispatch();+ d.block_indices_begins = {0, 1, 2}; // back() != block_indices.size()+ expect_violation(d, "block_indices_begins is not a prefix-sum over block_indices");+}++TEST(PADispatchContract, BlocksMustCoverEachContext) {+ auto d = make_valid_dispatch();+ d.block_indices = {0, 1};+ d.block_indices_begins = {0, 1, 2}; // one block (4 slots) for a context of 8+ expect_violation(d, "block_indices do not cover a subsequence's context");+}++// A block_size of 0 means the cache geometry is still dynamic; coverage is+// not checked, everything else still is.+TEST(PADispatchContract, DynamicBlockSizeSkipsCoverageOnly) {+ auto d = make_valid_dispatch();+ d.block_indices = {0};+ d.block_indices_begins = {0, 0, 1};+ EXPECT_NO_THROW(validate_dispatch(d, 0u, 0u));+ d.max_context_len = 7;+ expect_violation(d, "max_context_len < a subsequence's context length", 0u);+}++TEST(PADispatchContract, AbsentBlockTableSkipsBlockChecks) {+ auto d = make_valid_dispatch();+ d.has_block_table = false;+ d.block_indices.clear();+ d.block_indices_begins.clear();+ EXPECT_NO_THROW(validate_dispatch(d, kBlockSize, 0u));+}++// An empty selection is legal (intermediate prefill chunks gather nothing).+TEST(PADispatchContract, EmptySampledTokensIsLegal) {+ auto d = make_valid_dispatch();+ d.sampled_tokens_indices.clear();+ EXPECT_NO_THROW(validate_dispatch(d, kBlockSize, 0u));+}++TEST(PADispatchContract, SampledTokensOutOfRangeRejected) {+ auto d = make_valid_dispatch();+ d.sampled_tokens_indices = {6};+ expect_violation(d, "sampled_tokens_indices out of token range");+}++TEST(PADispatchContract, ViolationNamesTheDispatch) {+ auto d = make_valid_dispatch();+ d.past_lens = {0, -1};+ try {+ validate_dispatch(d, kBlockSize, 7u);+ FAIL() << "expected a dispatch-contract violation";+ } catch (const ov::Exception& ex) {+ EXPECT_NE(std::string(ex.what()).find("PA dispatch #7"), std::string::npos) << ex.what();+ }+}++// A dispatch shaped as N subsequences of the given scheduled lengths; only the+// fields variants_serve reads are populated.+Dispatch make_dispatch_of(const std::vector<int32_t>& seq_lens) {+ Dispatch d;+ d.subsequence_begins = {0};+ for (const auto len : seq_lens) {+ d.past_lens.push_back(0);+ d.subsequence_begins.push_back(d.subsequence_begins.back() + len);+ }+ return d;+}++const std::vector<std::size_t> kChunkSizes = {1024u, 128u, 1u};++TEST(PADispatchRouting, SingleSequenceDecodeServedByTheOneTokenVariant) {+ EXPECT_TRUE(variants_serve(make_dispatch_of({1}), kChunkSizes));+ EXPECT_FALSE(variants_serve(make_dispatch_of({1}), {1024u, 128u}));+}++TEST(PADispatchRouting, DecodeBatchRunsOneToOne) {+ EXPECT_FALSE(variants_serve(make_dispatch_of({1, 1, 1, 1}), kChunkSizes));+}++TEST(PADispatchRouting, ShortPrefillRunsOneToOne) {+ EXPECT_FALSE(variants_serve(make_dispatch_of({32, 32, 32, 32}), kChunkSizes));+ EXPECT_FALSE(variants_serve(make_dispatch_of({127}), kChunkSizes));+}++TEST(PADispatchRouting, LongPrefillIsChunked) {+ EXPECT_TRUE(variants_serve(make_dispatch_of({128}), kChunkSizes));+ EXPECT_TRUE(variants_serve(make_dispatch_of({7638}), kChunkSizes));+}++TEST(PADispatchRouting, MixedDispatchWithOneLongSubsequenceIsChunked) {+ EXPECT_TRUE(variants_serve(make_dispatch_of({1, 1, 200, 1}), kChunkSizes));+}++TEST(PADispatchRouting, NoVariantsOrNoTokensRunOneToOne) {+ EXPECT_FALSE(variants_serve(make_dispatch_of({7638}), {}));+ EXPECT_FALSE(variants_serve(make_dispatch_of({}), kChunkSizes));+}++} // namespace