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][MoE Performance]Overlap CPU and NPU workloads. (#36398)
intelgaoxiong8bd69db3e7c3
diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.cpp b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.cppindex a81d38b3a07..c307f6bda64 100644--- a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.cpp@@ -4,6 +4,8 @@#include "moe_executor.hpp"+#include <optional>+#include "../compiled_model.hpp" // For CompiledModel::CompiledModelDesc#include "../logging.hpp"#include "moe_infer_utils.hpp"@@ -213,37 +215,27 @@ void MoEExecutor::run(size_t real_idx, size_t idx) {OPENVINO_THROW("MoE: Router scores are required but not available");}- // Parse router scores and populate routing maps- // Note: parse_selected_experts_from_router() clears the maps internally before populating- std::vector<size_t> selected_experts;+ // Dispatch to appropriate inference function.+ // EXPERT_BATCH: parse upfront (single token, routing maps needed for cache lookup).+ // EXPERT_ITERATIVE: parse is fused inside run_expert_iterative, expert-row by row,+ // overlapping with NPU execution to hide the per-layer parse overhead.if (processing_mode == MoEProcessingMode::EXPERT_BATCH) {+ std::vector<size_t> selected_experts;m_profile->batch["Parse Router Output"].record([&]() {selected_experts = ov::npuw::moe::parse_selected_experts_from_router(io.router_scores,num_experts,m_token_to_experts,m_expert_to_tokens);});- } else {- m_profile->iterative["Parse Router Output"].record([&]() {- selected_experts = ov::npuw::moe::parse_selected_experts_from_router(io.router_scores,- num_experts,- m_token_to_experts,- m_expert_to_tokens);- });- }-- if (selected_experts.empty()) {- OPENVINO_THROW("MoE: No experts selected by router");- }-- // Dispatch to appropriate inference function- if (processing_mode == MoEProcessingMode::EXPERT_BATCH) {+ if (selected_experts.empty()) {+ OPENVINO_THROW("MoE: No experts selected by router");+ }m_profile->batch["Total Expert Batch"].record([&]() {run_expert_batch(idx, real_idx, selected_experts);});} else {m_profile->iterative["Total Expert Iterative"].record([&]() {- run_expert_iterative(idx, real_idx, selected_experts);+ run_expert_iterative(idx);});}@@ -331,177 +323,255 @@ void MoEExecutor::run_expert_batch(size_t idx, size_t real_idx, const std::vecto});}-void MoEExecutor::run_expert_iterative(size_t idx, size_t real_idx, const std::vector<size_t>& selected_experts) {- LOG_DEBUG("\n[EXPERT_ITERATIVE] Processing multiple tokens by iterating through experts");+void MoEExecutor::run_expert_iterative(size_t idx) {+ LOG_DEBUG("\n[EXPERT_ITERATIVE] Processing multiple tokens with async inference and overlapping NPU execution");- const auto input_token_count = m_config.input_token_count;const auto& io = m_moe_io[idx];- // Clear output buffer before accumulating expert outputs- if (!m_resources.expert_output_accumulator) {+ // Precondition checks+ if (!m_resources.expert_output_accumulator)OPENVINO_THROW("MoE: Expert output accumulator is null");- }+ if (!io.expert_input)+ OPENVINO_THROW("MoE: Expert input tensor is not set — prologue must bind it before run()");+ if (!m_config.router_scores.compiled.has_value())+ OPENVINO_THROW("MoE: Router scores index not available");+ if (!m_config.expert_input.compiled.has_value())+ OPENVINO_THROW("MoE: Expert input parameter index not available");+ if (m_resources.sorted_chunk_sizes.empty())+ OPENVINO_THROW("MoE: Sorted chunk sizes cannot be empty");++ // Clear output accumulator before accumulating expert outputsstd::memset(m_resources.expert_output_accumulator->data(),0,m_resources.expert_output_accumulator->get_byte_size());- // Get tensor references (constant across all experts)- if (!m_config.router_scores.compiled.has_value()) {- OPENVINO_THROW("MoE: Router scores index not available");- }- if (!m_config.expert_input.compiled.has_value()) {- OPENVINO_THROW("MoE: Expert input parameter index not available");- }-- auto router_source = io.router_scores;auto expert_input_source = io.expert_input;- // Calculate output embedding dimension from any compiled model (all have same output shape)- auto any_compiled_model = m_config.compiled_models.begin()->second;- auto output_shape = any_compiled_model->outputs()[0].get_shape();- size_t embed_dim = (output_shape.size() == 4) ? output_shape[3] : output_shape[1];-- // Process each expert sequentially- for (size_t expert_id : selected_experts) {- LOG_DEBUG("\n Processing Expert[" << expert_id << "]...");-- // Get tokens assigned to this expert- const auto& tokens_for_expert = m_expert_to_tokens.at(expert_id);- const size_t total_tokens = tokens_for_expert.size();-- LOG_DEBUG(" Expert[" << expert_id << "] processing " << total_tokens << " tokens");-- // Precompute expert slot for each token- // This eliminates map lookup + linear search in scatter_expert_outputs hot loop- std::vector<size_t> expert_slots_for_tokens(total_tokens);- for (size_t i = 0; i < total_tokens; ++i) {- size_t token_id = tokens_for_expert[i];- const auto& expert_ids = m_token_to_experts.at(token_id);- auto it = std::find(expert_ids.begin(), expert_ids.end(), expert_id);- if (it == expert_ids.end()) {- OPENVINO_THROW("MoE: Token should have this expert");- }- expert_slots_for_tokens[i] = std::distance(expert_ids.begin(), it);+ // Output embedding dimension+ const auto output_shape = m_config.compiled_models.begin()->second->outputs()[0].get_shape();+ const size_t embed_dim = (output_shape.size() == 4) ? output_shape[3] : output_shape[1];++ // num_tokens and num_experts come from config, validated once during prepare().+ // The router tensor's token dimension is guaranteed to match input_token_count because+ // both are derived from the same compiled model structure at prepare() time.+ const size_t num_tokens = m_config.input_token_count;+ const size_t num_experts = m_config.num_experts;++ // Chunk-size selector+ auto select_chunk = [&](size_t remaining) -> size_t {+ const size_t smallest = m_resources.sorted_chunk_sizes.back();+ const size_t largest = m_resources.sorted_chunk_sizes.front();+ if (remaining <= smallest)+ return smallest;+ if (remaining >= largest)+ return largest;+ for (auto it = m_resources.sorted_chunk_sizes.rbegin(); it != m_resources.sorted_chunk_sizes.rend(); ++it) {+ if (*it >= remaining)+ return *it;}-- // Process tokens in dynamic chunks based on available compiled models- // Priority: use largest possible chunk_size (256 > 128 > 64 > 32)- size_t processed_tokens = 0;- size_t last_chunk_size = 0; // Track last used chunk_size to detect changes- // Note: When switching to a new expert, last_chunk_size resets to 0,- // ensuring weights are unpacked for the first chunk of each expert- while (processed_tokens < total_tokens) {- size_t remaining_tokens = total_tokens - processed_tokens;-- // Chunk selection strategy:- // - remaining_tokens <= smallest chunk → use smallest chunk- // - remaining_tokens >= largest chunk → use largest chunk- // - otherwise → use smallest chunk that is >= remaining_tokens- // Pre-sorted in descending order: [256, 128, 64, 32, 16]- if (m_resources.sorted_chunk_sizes.empty()) {- OPENVINO_THROW("MoE: Sorted chunk sizes cannot be empty");- }-- size_t selected_chunk_size;- size_t smallest_chunk = m_resources.sorted_chunk_sizes.back();- size_t largest_chunk = m_resources.sorted_chunk_sizes.front();-- if (remaining_tokens <= smallest_chunk) {- // Use smallest chunk- selected_chunk_size = smallest_chunk;- } else if (remaining_tokens >= largest_chunk) {- // Use largest chunk- selected_chunk_size = largest_chunk;- } else {- // Find smallest chunk >= remaining_tokens- // Since sorted descending, iterate from end to find first >= remaining_tokens- selected_chunk_size = smallest_chunk; // Default to smallest- for (auto it = m_resources.sorted_chunk_sizes.rbegin(); it != m_resources.sorted_chunk_sizes.rend();- ++it) {- if (*it >= remaining_tokens) {- selected_chunk_size = *it;- break;+ return smallest;+ };++ // Double-buffer request helpers+ size_t global_slot = 0;+ auto get_req = [&](size_t cs, size_t slot) -> RqPtr& {+ return m_resources.chunk_infer_requests.at(cs)[slot & 1];+ };+ // Tracks which expert_id is currently loaded into each (chunk_size, slot) request.+ // Key = cs * 2 + (slot & 1): unique because all chunk_sizes are distinct integers,+ // so cs1 * 2 + b1 == cs2 * 2 + b2 only when cs1 == cs2 and b1 == b2.+ std::map<size_t, size_t> req_expert_state;+ auto do_unpack = [&](size_t cs, size_t slot, RqPtr& req, size_t expert_id) {+ const size_t key = cs * 2 + (slot & 1);+ auto it = req_expert_state.find(key);+ if (it == req_expert_state.end() || it->second != expert_id) {+ m_profile->iterative["Unpack Closure"].record([&]() {+ unpack_single_expert_closure(idx, req, expert_id);+ });+ req_expert_state[key] = expert_id;+ }+ };++ // Expert data ring buffer:+ // 2 slots alternate per non-empty expert. At most one slot is "in-flight" for+ // scatter at any time; the other slot is being filled for the next expert.+ // Safety: expert[k+2] reuses the slot that expert[k] used, and by then expert[k]'s+ // last work item has already been drained (pipeline depth = 1).+ struct ExpertData {+ std::vector<size_t> tokens;+ std::vector<size_t> slots;+ };+ std::array<ExpertData, 2> expert_ring;+ size_t expert_ring_idx = 0; // incremented per non-empty expert++ // In-flight item tracking+ struct InflightItem {+ size_t cs;+ size_t req_slot;+ size_t chunk_start;+ size_t chunk_tokens;+ size_t ring_idx; // expert_ring slot index at launch time+ };+ std::optional<InflightItem> inflight;++ // Drain the in-flight item referenced by `inflight` (wait + scatter).+ // Called both inside the pipeline loop (to drain the previous item while NPU+ // runs the current one) and once after the loop to drain the final item.+ auto do_drain = [&]() {+ NPUW_ASSERT(inflight.has_value() && "do_drain called with no in-flight item");+ auto& req = get_req(inflight->cs, inflight->req_slot);+ m_profile->iterative["NPU Wait"].record([&]() {+ req->wait();+ });+ const auto& data = expert_ring[inflight->ring_idx & 1];+ const auto cm = m_config.compiled_models.at(inflight->cs);+ auto output = req->get_tensor(cm->outputs()[0]);+ m_profile->iterative["Scatter Output"].record([&]() {+ ov::npuw::moe::scatter_expert_outputs(output,+ m_resources.expert_output_accumulator,+ data.tokens,+ inflight->chunk_start,+ inflight->chunk_tokens,+ embed_dim,+ num_tokens,+ data.slots);+ });+ };++ // Per-token counter: how many earlier experts have already selected this token.+ // Gives each token's expert-slot index in O(1) without a full two-pass scan.+ std::vector<size_t> token_slot_count(num_tokens, 0);++ // Parse-ahead buffer: pre-scan the NEXT expert's router row after drain(k-1) but+ // while NPU k is still executing. This hides the O(num_tokens) threshold scan+ // inside the NPU overlap window instead of paying for it on the critical path+ // before item k+1's dispatch.+ //+ // The buffer stores only token IDs that passed the threshold (v > 1e-6).+ // Slot assignment (O(selected) not O(num_tokens)) is still done at the+ // top of the next expert iteration.+ //+ // Timeline with parse-ahead:+ // CPU: [Unpack(k)+Gather(k)] → start(k) → drain(k-1) → [Parse(k+1)] → [Unpack(k+1)+Gather(k+1)] → start(k+1)+ // NPU: [=================NPU(k)==================] [==NPU(k+1)==]+ //+ struct ParseAheadBuffer {+ std::vector<size_t> tokens; // pre-filtered token IDs for next expert+ size_t expert_id = SIZE_MAX; // which expert was pre-scanned (sentinel = none)+ };+ ParseAheadBuffer parse_ahead;++ // Per-expert loop: three phases — Parse, Dispatch, Prefetch.+ auto stream_and_run = [&](auto* data) {+ for (size_t expert_id = 0; expert_id < num_experts; ++expert_id) {+ // -- Parse: determine which tokens this expert processes --+ const size_t ring_slot = expert_ring_idx & 1;+ auto& cur = expert_ring[ring_slot];+ cur.tokens.clear();+ cur.slots.clear();++ const auto* row = data + expert_id * num_tokens;+ // Shared by both the parse-ahead fast path and the full threshold scan below.+ auto fill_token = [&](size_t token_id) {+ cur.tokens.push_back(token_id);+ cur.slots.push_back(token_slot_count[token_id]++);+ };+ m_profile->iterative["Parse Router Row"].record([&]() {+ if (parse_ahead.expert_id == expert_id) {+ // Fast path: token IDs already filtered; only slot updates remain.+ for (size_t token_id : parse_ahead.tokens) {+ fill_token(token_id);+ }+ parse_ahead.expert_id = SIZE_MAX; // consumed+ } else {+ // Full O(num_tokens) threshold scan (first expert, or parse-ahead missed).+ for (size_t token_id = 0; token_id < num_tokens; ++token_id) {+ if (is_nonzero(row[token_id])) {+ fill_token(token_id);+ }}}- }+ });- // Actual tokens to process in this iteration- size_t current_chunk_size = std::min(selected_chunk_size, remaining_tokens);+ if (cur.tokens.empty()) {+ continue; // expert not selected — do not advance ring_idx+ }- LOG_DEBUG(" Processing tokens [" << processed_tokens << ", " << (processed_tokens + current_chunk_size)- << ") with chunk_size=" << selected_chunk_size);+ // -- Dispatch: slice tokens into chunks and pipeline NPU execution --+ size_t processed = 0;+ while (processed < cur.tokens.size()) {+ const size_t cs = select_chunk(cur.tokens.size() - processed);+ const size_t actual = std::min(cs, cur.tokens.size() - processed);+ const size_t s = global_slot & 1;+ auto& req = get_req(cs, s);++ do_unpack(cs, s, req, expert_id);+ {+ const auto cm = m_config.compiled_models.at(cs);+ auto router_dest = req->get_tensor(cm->inputs()[m_config.router_scores.compiled.value()]);+ auto input_dest = req->get_tensor(cm->inputs()[m_config.expert_input.compiled.value()]);+ m_profile->iterative["Gather Router Scores"].record([&]() {+ ov::npuw::moe::gather_router_scores(io.router_scores,+ router_dest,+ expert_id,+ cur.tokens,+ processed,+ actual);+ });+ m_profile->iterative["Gather Expert Input"].record([&]() {+ ov::npuw::moe::gather_expert_inputs(expert_input_source,+ input_dest,+ cur.tokens,+ processed,+ actual);+ });+ }- // Get selected infer request from MoEResources- auto infer_request_it = m_resources.chunk_infer_requests.find(selected_chunk_size);- if (infer_request_it == m_resources.chunk_infer_requests.end()) {- OPENVINO_THROW("MoE: Infer request for chunk_size=", selected_chunk_size, " not found");- }- auto selected_infer_request = infer_request_it->second;-- // Get input/output ports for selected infer request- auto selected_compiled_model = m_config.compiled_models.at(selected_chunk_size);- const auto& selected_router_iport =- selected_compiled_model->inputs()[m_config.router_scores.compiled.value()];- const auto& selected_expert_input_iport =- selected_compiled_model->inputs()[m_config.expert_input.compiled.value()];- const auto& selected_oport = selected_compiled_model->outputs()[0];-- auto selected_router_dest = selected_infer_request->get_tensor(selected_router_iport);- auto selected_expert_input_dest = selected_infer_request->get_tensor(selected_expert_input_iport);- auto selected_expert_output = selected_infer_request->get_tensor(selected_oport);-- // Step 1: Unpack expert weights when chunk_size changes (different infer request)- // This ensures each infer request has correct weights loaded- // Important: last_chunk_size is reset to 0 at the start of each expert loop,- // so the first chunk of a new expert will always trigger unpacking (0 != selected_chunk_size)- if (selected_chunk_size != last_chunk_size) {- m_profile->iterative["Unpack Closure"].record([&]() {- unpack_single_expert_closure(idx, selected_infer_request, expert_id);+ // Start NPU first, then drain previous — this creates the CPU/NPU overlap.+ m_profile->iterative["NPU Start"].record([&]() {+ req->start_async();});- last_chunk_size = selected_chunk_size;- }+ if (inflight) {+ do_drain();+ }- // Step 2: Gather router scores for this chunk- m_profile->iterative["Gather Router Scores"].record([&]() {- ov::npuw::moe::gather_router_scores(router_source,- selected_router_dest,- expert_id,- tokens_for_expert,- processed_tokens,- current_chunk_size);- });+ inflight = InflightItem{cs, s, processed, actual, ring_slot};+ ++global_slot;+ processed += actual;+ }- // Step 3: Gather expert inputs for this chunk- m_profile->iterative["Gather Expert Input"].record([&]() {- ov::npuw::moe::gather_expert_inputs(expert_input_source,- selected_expert_input_dest,- tokens_for_expert,- processed_tokens,- current_chunk_size);- });+ // -- Prefetch: scan next expert's row while the last NPU chunk runs --+ if ((expert_id + 1) < num_experts) {+ const size_t next_id = expert_id + 1;+ const auto* next_row = data + next_id * num_tokens;+ parse_ahead.tokens.clear();+ parse_ahead.expert_id = next_id;+ for (size_t token_id = 0; token_id < num_tokens; ++token_id) {+ if (is_nonzero(next_row[token_id])) {+ parse_ahead.tokens.push_back(token_id);+ }+ }+ }- // Step 4: Execute expert inference- m_profile->iterative["Expert Inference"].record([&]() {- selected_infer_request->infer();- });+ ++expert_ring_idx;+ }+ };- // Step 5: Scatter expert outputs back to global buffer- m_profile->iterative["Scatter Output"].record([&]() {- ov::npuw::moe::scatter_expert_outputs(selected_expert_output,- m_resources.expert_output_accumulator,- tokens_for_expert,- processed_tokens,- current_chunk_size,- embed_dim,- input_token_count,- expert_slots_for_tokens);- });+ const auto elem_type = io.router_scores->get_element_type();+ if (elem_type == ov::element::f32) {+ stream_and_run(io.router_scores->data<float>());+ } else if (elem_type == ov::element::f16) {+ stream_and_run(io.router_scores->data<ov::float16>());+ } else {+ OPENVINO_THROW("MoE: Unsupported router element type for iterative inference");+ }- // Move to next chunk- processed_tokens += current_chunk_size;- }- LOG_DEBUG(" Expert[" << expert_id << "] completed");+ if (!inflight) {+ OPENVINO_THROW("MoE: No experts selected by router");}++ // Drain the last in-flight item+ do_drain();}void MoEExecutor::set_router_scores(size_t idx,diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.hpp b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.hppindex 188cd281229..2d50759591b 100644--- a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.hpp@@ -255,16 +255,17 @@ private:void run_expert_batch(size_t idx, size_t real_idx, const std::vector<size_t>& selected_experts);/**- * @brief Execute expert iterative mode inference+ * @brief Execute expert iterative mode inference.*- * Processing mode: Iterate through experts, each processes multiple tokens- * Uses dynamic chunk sizing and accumulates outputs.+ * Processing mode: Iterate through experts, each processes multiple tokens.+ * CPU gather and NPU inference are overlapped via double-buffering:+ * while NPU executes chunk k, CPU prepares (unpack + gather) chunk k+1.+ * Router row parsing for expert k+1 is also interleaved inside the NPU+ * execution window of expert k.** @param idx Function call index- * @param real_idx Submodel index- * @param selected_experts List of selected expert IDs*/- void run_expert_iterative(size_t idx, size_t real_idx, const std::vector<size_t>& selected_experts);+ void run_expert_iterative(size_t idx);/*** @brief Execute batch experts inference (deprecated)@@ -275,15 +276,6 @@ private:run_expert_batch(idx, real_idx, selected_experts);}- /**- * @brief Execute iterative experts inference (deprecated)- * @deprecated Use run_expert_iterative() instead- */- [[deprecated("Use run_expert_iterative() instead")]]- void run_iterative_experts(size_t idx, size_t real_idx, const std::vector<size_t>& selected_experts) {- run_expert_iterative(idx, real_idx, selected_experts);- }-// === Helper functions ===/**diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_infer_utils.cpp b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_infer_utils.cppindex eb95e325f50..789cdc253a6 100644--- a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_infer_utils.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_infer_utils.cpp@@ -103,16 +103,11 @@ std::vector<size_t> parse_selected_experts_from_router(const ov::SoPtr<ov::ITens// Parse which expert each token selects based on non-zero weightsauto parse_experts = [&](auto* data) {- // For each token, find which experts have non-zero weights- for (size_t token_id = 0; token_id < num_tokens; ++token_id) {- for (size_t expert_id = 0; expert_id < num_experts; ++expert_id) {- // Index calculation for shape [num_experts, 1, token_num, 1]- // data[expert_id, 0, token_id, 0]- size_t idx = expert_id * num_tokens + token_id;-- float value = std::abs(static_cast<float>(data[idx]));- if (value > 1e-6f) {- // This token selected this expert+ // Iterate expert-major: each expert's row is contiguous in memory.+ for (size_t expert_id = 0; expert_id < num_experts; ++expert_id) {+ const auto* row = data + expert_id * num_tokens;+ for (size_t token_id = 0; token_id < num_tokens; ++token_id) {+ if (is_nonzero(row[token_id])) {token_to_experts[token_id].push_back(expert_id);expert_to_tokens[expert_id].push_back(token_id);}@@ -168,9 +163,8 @@ void gather_router_scores(const ov::SoPtr<ov::ITensor>& router_source,const std::vector<size_t>& token_ids,size_t chunk_start,size_t chunk_size) {- auto router_source_shape = router_source->get_shape();+ const auto router_source_shape = router_source->get_shape();- // Calculate expert offset in source tensorsize_t expert_offset;if (router_source_shape.size() == 4) {expert_offset = expert_id * get_router_token_count(router_source_shape);@@ -181,19 +175,18 @@ void gather_router_scores(const ov::SoPtr<ov::ITensor>& router_source,expert_offset = 0; // unreachable, suppress uninitialized warning}- // Gather router scores for chunk tokens- if (router_source->get_element_type() == ov::element::f16) {- const auto* src_base = router_source->data<ov::float16>() + expert_offset;- auto* dst_base = router_dest->data<ov::float16>();+ auto gather = [&](const auto* src_base, auto* dst_base) {+ const size_t* ids = token_ids.data() + chunk_start;for (size_t i = 0; i < chunk_size; ++i) {- dst_base[i] = src_base[token_ids[chunk_start + i]];- }- } else if (router_source->get_element_type() == ov::element::f32) {- const auto* src_base = router_source->data<float>() + expert_offset;- auto* dst_base = router_dest->data<float>();- for (size_t i = 0; i < chunk_size; ++i) {- dst_base[i] = src_base[token_ids[chunk_start + i]];+ dst_base[i] = src_base[ids[i]];}+ };++ const auto elem_type = router_source->get_element_type();+ if (elem_type == ov::element::f16) {+ gather(router_source->data<ov::float16>() + expert_offset, router_dest->data<ov::float16>());+ } else if (elem_type == ov::element::f32) {+ gather(router_source->data<float>() + expert_offset, router_dest->data<float>());} else {NPUW_ASSERT(false && "Unsupported router element type for gathering");}@@ -204,40 +197,24 @@ void gather_expert_inputs(const ov::SoPtr<ov::ITensor>& input_source,const std::vector<size_t>& token_ids,size_t chunk_start,size_t chunk_size) {- auto input_shape = input_source->get_shape();-- // Determine dimensions- size_t hidden_dim;- size_t token_stride;- if (input_shape.size() == 2) {- hidden_dim = input_shape[1];- token_stride = hidden_dim;- } else if (input_shape.size() == 4) {- hidden_dim = input_shape[3];- token_stride = hidden_dim;- } else {- NPUW_ASSERT(false && "Unexpected expert input tensor shape");- }-- // Gather input embeddings for chunk tokens- if (input_source->get_element_type() == ov::element::f16) {- const auto* src_base = input_source->data<ov::float16>();- auto* dst_base = input_dest->data<ov::float16>();- for (size_t i = 0; i < chunk_size; ++i) {- size_t token_id = token_ids[chunk_start + i];- const auto* src_token = src_base + token_id * token_stride;- auto* dst_token = dst_base + i * hidden_dim;- std::memcpy(dst_token, src_token, hidden_dim * sizeof(ov::float16));- }- } else if (input_source->get_element_type() == ov::element::f32) {- const auto* src_base = input_source->data<float>();- auto* dst_base = input_dest->data<float>();- for (size_t i = 0; i < chunk_size; ++i) {- size_t token_id = token_ids[chunk_start + i];- const auto* src_token = src_base + token_id * token_stride;- auto* dst_token = dst_base + i * hidden_dim;- std::memcpy(dst_token, src_token, hidden_dim * sizeof(float));+ const auto input_shape = input_source->get_shape();+ NPUW_ASSERT((input_shape.size() == 2 || input_shape.size() == 4) && "Unexpected expert input tensor shape");+ // hidden_dim is always the last dimension for both supported layouts.+ const size_t hidden_dim = input_shape.back();++ auto gather = [&](const auto* src_base, auto* dst_base) {+ const size_t elem_bytes = hidden_dim * sizeof(*src_base);+ const size_t* ids = token_ids.data() + chunk_start;+ for (size_t i = 0; i < chunk_size; ++i, dst_base += hidden_dim) {+ std::memcpy(dst_base, src_base + ids[i] * hidden_dim, elem_bytes);}+ };++ const auto elem_type = input_source->get_element_type();+ if (elem_type == ov::element::f16) {+ gather(input_source->data<ov::float16>(), input_dest->data<ov::float16>());+ } else if (elem_type == ov::element::f32) {+ gather(input_source->data<float>(), input_dest->data<float>());} else {NPUW_ASSERT(false && "Unsupported expert input element type for gathering");}@@ -251,28 +228,26 @@ void scatter_expert_outputs(const ov::SoPtr<ov::ITensor>& expert_output,size_t embed_dim,size_t input_token_count,const std::vector<size_t>& expert_slots_for_tokens) {- auto elem_type = global_output_buffer->get_element_type();-- for (size_t i = 0; i < chunk_size; ++i) {- size_t original_token_id = token_ids[chunk_start + i];- size_t expert_slot = expert_slots_for_tokens[chunk_start + i];-- // Calculate offsets- size_t src_offset = i * embed_dim;- size_t dst_offset = expert_slot * input_token_count * embed_dim + original_token_id * embed_dim;-- // Scatter output to global buffer- if (elem_type == ov::element::f32) {- const float* src = expert_output->data<float>() + src_offset;- float* dst = global_output_buffer->data<float>() + dst_offset;- std::memcpy(dst, src, embed_dim * sizeof(float));- } else if (elem_type == ov::element::f16) {- const ov::float16* src = expert_output->data<ov::float16>() + src_offset;- ov::float16* dst = global_output_buffer->data<ov::float16>() + dst_offset;- std::memcpy(dst, src, embed_dim * sizeof(ov::float16));- } else {- OPENVINO_THROW("MoE: Unsupported element type for chunk output relayout: ", elem_type);+ // Hoist type dispatch and pointer acquisition outside the loop.+ // slot_stride = number of elements between consecutive expert slots in the output buffer.+ const size_t slot_stride = input_token_count * embed_dim;++ auto scatter = [&](const auto* src_base, auto* dst_base) {+ const size_t elem_bytes = embed_dim * sizeof(*src_base);+ const size_t* ids = token_ids.data() + chunk_start;+ const size_t* slots = expert_slots_for_tokens.data() + chunk_start;+ for (size_t i = 0; i < chunk_size; ++i) {+ std::memcpy(dst_base + slots[i] * slot_stride + ids[i] * embed_dim, src_base + i * embed_dim, elem_bytes);}+ };++ const auto elem_type = global_output_buffer->get_element_type();+ if (elem_type == ov::element::f32) {+ scatter(expert_output->data<float>(), global_output_buffer->data<float>());+ } else if (elem_type == ov::element::f16) {+ scatter(expert_output->data<ov::float16>(), global_output_buffer->data<ov::float16>());+ } else {+ OPENVINO_THROW("MoE: Unsupported element type for chunk output relayout: ", elem_type);}}diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_infer_utils.hpp b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_infer_utils.hppindex f78c0cab8a7..01c4bfb7d1b 100644--- a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_infer_utils.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_infer_utils.hpp@@ -4,6 +4,7 @@#pragma once+#include <cmath>#include <map>#include <vector>@@ -29,6 +30,11 @@ struct MoEProfile {MoEProfile();};+template <typename T>+inline bool is_nonzero(T v) {+ return std::abs(static_cast<float>(v)) > 1e-6f;+}+/*** @brief Slice a single expert's weight from batched weight tensor.*diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_resources.cpp b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_resources.cppindex f3ec48e2bed..0947691bfb9 100644--- a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_resources.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_resources.cpp@@ -42,10 +42,12 @@ void MoEResources::initialize_expert_iterative_mode(}try {- auto infer_request = compiled_model->create_infer_request();- chunk_infer_requests[chunk_size] = std::move(infer_request);+ // Create 2 requests per chunk_size for double-buffering:+ // slot 0 and slot 1 alternate so Unpack+Gather can overlap with NPU inference.+ chunk_infer_requests[chunk_size][0] = compiled_model->create_infer_request();+ chunk_infer_requests[chunk_size][1] = compiled_model->create_infer_request();sorted_chunk_sizes.push_back(chunk_size);- LOG_DEBUG(" Created chunk infer request for chunk_size=" << chunk_size);+ LOG_DEBUG(" Created 2 chunk infer requests (double-buffer) for chunk_size=" << chunk_size);} catch (const std::exception& ex) {OPENVINO_THROW("MoE chunk infer request creation failed for chunk_size=", chunk_size, ": ", ex.what());}diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_resources.hpp b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_resources.hppindex 47cd91e1348..085e3091bb0 100644--- a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_resources.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_resources.hpp@@ -4,7 +4,9 @@#pragma once+#include <array>#include <cstddef>+#include <map>#include <memory>#include <vector>@@ -47,10 +49,11 @@ struct MoEResources {// Used to select optimal chunk size for token batchesstd::vector<size_t> sorted_chunk_sizes;- // Infer requests for different chunk sizes- // Map: chunk_size -> infer_request- // Reused across experts by unpacking different weights- std::map<size_t, ov::SoPtr<ov::IAsyncInferRequest>> chunk_infer_requests;+ // Infer requests for different chunk sizes, double-buffered for pipeline overlap.+ // Map: chunk_size -> [slot0, slot1]+ // Pipeline alternates between slot 0 and slot 1 so that Unpack+Gather for item i+1+ // can run on the CPU while NPU is executing item i.+ std::map<size_t, std::array<ov::SoPtr<ov::IAsyncInferRequest>, 2>> chunk_infer_requests;// Output accumulation buffer// Shape: [num_active_experts, 1, input_token_count, expert_hidden_dim]