Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[NPUW]Improve MoE executor and profiling. (#38288)

intelgaoxiongfa2771e5b02e
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.cpp
index 3bd19a1b90a..2ff379294f7 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,7 @@
#include "moe_executor.hpp"
+#include <cstring>
#include <exception>
#include <optional>
@@ -74,6 +75,7 @@ void MoEExecutor::prepare(size_t idx, size_t real_idx, size_t num_sublayers, siz
pool_size);
} else {
m_resources.initialize_expert_iterative_mode(m_config, m_allocator, get_device_name(idx, &desc));
+ m_chunk_stats.init(ov::npuw::profiling_enabled());
}
} else {
LOG_DEBUG("Reusing existing shared MoE config and resources");
@@ -360,11 +362,12 @@ void MoEExecutor::run_expert_iterative(size_t idx) {
if (m_resources.sorted_chunk_sizes.empty())
OPENVINO_THROW("MoE: Sorted chunk sizes cannot be empty");
- // Clear output accumulator before accumulating expert outputs
- std::memset(m_resources.expert_output_accumulator->data(),
- 0,
- m_resources.expert_output_accumulator->get_byte_size());
-
+ // expert_output_accumulator is not cleared up front (profiled as too heavy for a buffer this
+ // size). Routing is expected to be dense — every (token, expert_slot) cell gets memcpy'd
+ // exactly once by scatter_expert_outputs() — but is_nonzero() filters out exactly-zero
+ // mixing scores, which can leave a slot unfilled if a top-k expert's score is 0.0f.
+ // token_slot_count (below) tracks exactly which slots that happens to, so instead we do a
+ // targeted clear of only the missing cells after dispatch — see clear_unfilled_accumulator_slots().
auto expert_input_source = io.expert_input;
// Use the embed_dim already validated against the accumulator buffer during prepare().
@@ -379,11 +382,13 @@ void MoEExecutor::run_expert_iterative(size_t idx) {
"layout may have changed, update embed_dim derivation");
}
- // 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.
+ // num_tokens, num_experts and num_active_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;
+ const size_t num_active_experts = m_config.num_active_experts;
// Chunk-size selector
auto select_chunk = [&](size_t remaining) -> size_t {
@@ -502,7 +507,7 @@ void MoEExecutor::run_expert_iterative(size_t idx) {
// Shared by both the parse-ahead fast path and the full threshold scan below.
auto fill_token = [&](size_t token_id) {
// The accumulator has only K output slots per token.
- if (token_slot_count[token_id] >= m_config.num_active_experts) {
+ if (token_slot_count[token_id] >= num_active_experts) {
OPENVINO_THROW("MoE Iterative experts: nonzero scores exceed the configured top-k for token ",
token_id);
}
@@ -533,8 +538,9 @@ void MoEExecutor::run_expert_iterative(size_t idx) {
// -- 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 remaining = cur.tokens.size() - processed;
+ const size_t cs = select_chunk(remaining);
+ const size_t actual = std::min(cs, remaining);
const size_t s = global_slot & 1;
auto& req = get_req(cs, s);
@@ -564,6 +570,7 @@ void MoEExecutor::run_expert_iterative(size_t idx) {
m_profile->iterative["NPU Start"].record([&]() {
req->start_async();
});
+ m_chunk_stats.record_chunk(cs, actual);
if (inflight) {
do_drain();
}
@@ -602,7 +609,7 @@ void MoEExecutor::run_expert_iterative(size_t idx) {
if (inflight) {
do_drain();
} else {
- // All mixing scores were finite and zero; the accumulator is clear.
+ // All mixing scores were finite and zero; unfilled slot clearing below will zero the accumulator.
LOG_WARN("MoE prefill: all router mixing scores are zero for subgraph["
<< idx << "]; returning zero expert contribution without inference. "
<< "Check router/backend behavior if this is unexpected.");
@@ -622,8 +629,22 @@ void MoEExecutor::run_expert_iterative(size_t idx) {
}
}
}
+ std::memset(m_resources.expert_output_accumulator->data(),
+ 0,
+ m_resources.expert_output_accumulator->get_byte_size());
std::rethrow_exception(original_error);
}
+
+ // Zero any (token, slot) cells that dense routing was expected to fill but didn't (see
+ // comment above token_slot_count's declaration). No-op in the common case where every
+ // token reached num_active_experts.
+ m_profile->iterative["Clear Unfilled Slots"].record([&]() {
+ ov::npuw::moe::clear_unfilled_accumulator_slots(m_resources.expert_output_accumulator,
+ token_slot_count,
+ num_active_experts,
+ embed_dim,
+ num_tokens);
+ });
}
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.hpp
index 2d50759591b..90c55b5f828 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
@@ -205,6 +205,9 @@ private:
std::optional<MoEProfile>
m_profile; // Performance statistics (always collects, reports based on profiling_enabled())
+ // Chunk padding stats, EXPERT_ITERATIVE mode only (see MoEChunkStats)
+ MoEChunkStats m_chunk_stats;
+
// === Weight unpacking methods ===
/**
* @brief Unpack single expert's closure (expert-specific weights)
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.cpp
index 6b157b2d81a..8e30842af5b 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
@@ -4,6 +4,7 @@
#include "moe_infer_utils.hpp"
+#include <cstring>
#include <iomanip>
#include <iostream>
@@ -24,6 +25,39 @@ MoEProfile::MoEProfile() {
batch.report_on_die = ov::npuw::profiling_enabled();
}
+void MoEChunkStats::init(bool active) {
+ enabled = active;
+}
+
+void MoEChunkStats::record_chunk(size_t chunk_size, uint64_t actual_tokens) {
+ if (!enabled) {
+ return;
+ }
+ auto& c = per_chunk_size[chunk_size];
+ c.chunks++;
+ c.tokens += actual_tokens;
+}
+
+void MoEChunkStats::report() const {
+ if (per_chunk_size.empty()) {
+ return;
+ }
+
+ std::cout << "MoE Chunk Efficiency:" << std::endl;
+
+ std::cout << " Per chunk size (padding = capacity - real tokens):" << std::endl;
+ for (auto&& kv : per_chunk_size) {
+ const size_t cs = kv.first;
+ const auto& s = kv.second;
+ const uint64_t capacity = cs * s.chunks;
+ const uint64_t padding = capacity - s.tokens;
+ const double padding_pct =
+ capacity ? (100.0 * static_cast<double>(padding) / static_cast<double>(capacity)) : 0.0;
+ std::cout << " cs=" << cs << " [ chunks=" << s.chunks << ", tokens=" << s.tokens << ", capacity=" << capacity
+ << ", padding=" << padding << " (" << padding_pct << "%) ]" << std::endl;
+ }
+}
+
ov::Tensor slice_expert_weight(const ov::Tensor& batched_weight, size_t expert_id, size_t num_experts) {
// Slice weight tensor from batched (num_experts, ...) to single expert (1, ...)
auto shape = batched_weight.get_shape();
@@ -246,6 +280,32 @@ void scatter_expert_outputs(const ov::SoPtr<ov::ITensor>& expert_output,
}
}
+void clear_unfilled_accumulator_slots(const ov::SoPtr<ov::ITensor>& global_output_buffer,
+ const std::vector<size_t>& token_slot_count,
+ size_t num_active_experts,
+ size_t embed_dim,
+ size_t input_token_count) {
+ const size_t slot_stride = input_token_count * embed_dim;
+
+ auto clear = [&](auto* base) {
+ const size_t elem_bytes = embed_dim * sizeof(*base);
+ for (size_t token_id = 0; token_id < token_slot_count.size(); ++token_id) {
+ for (size_t slot = token_slot_count[token_id]; slot < num_active_experts; ++slot) {
+ std::memset(base + slot * slot_stride + token_id * embed_dim, 0, elem_bytes);
+ }
+ }
+ };
+
+ const auto elem_type = global_output_buffer->get_element_type();
+ if (elem_type == ov::element::f32) {
+ clear(global_output_buffer->data<float>());
+ } else if (elem_type == ov::element::f16) {
+ clear(global_output_buffer->data<ov::float16>());
+ } else {
+ OPENVINO_THROW("MoE: Unsupported element type for accumulator clear: ", elem_type);
+ }
+}
+
// ====================================================================================================
// MoE Request Cache Implementation
// ====================================================================================================
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.hpp
index f5886d67751..7cf09cd2b59 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
@@ -5,6 +5,7 @@
#pragma once
#include <cmath>
+#include <cstdint>
#include <map>
#include <vector>
@@ -31,6 +32,40 @@ struct MoEProfile {
MoEProfile();
};
+/**
+ * @brief Standalone stats for EXPERT_ITERATIVE chunk padding.
+ *
+ * Independent of MoEProfile (which only times named code blocks): tracks
+ * per-chunk-size padding waste (real tokens vs the fixed chunk capacity
+ * actually paid for on the NPU).
+ */
+struct MoEChunkStats {
+ // Accumulated across all chunks dispatched at a given compiled chunk size.
+ struct PerChunkSize {
+ uint64_t chunks = 0; // number of chunks dispatched at this size
+ uint64_t tokens = 0; // real (non-padding) tokens carried by those chunks
+ };
+
+ bool enabled = false;
+ std::map<size_t, PerChunkSize> per_chunk_size; // keyed by chunk size
+
+ // Must be called before any record_*() call.
+ void init(bool active);
+
+ void record_chunk(size_t chunk_size, uint64_t actual_tokens);
+
+ void report() const;
+
+ ~MoEChunkStats() {
+ if (enabled) {
+ try {
+ report();
+ } catch (...) {
+ }
+ }
+ }
+};
+
template <typename T>
inline bool is_nonzero(T v) {
const float value = static_cast<float>(v);
@@ -147,6 +182,26 @@ void scatter_expert_outputs(const ov::SoPtr<ov::ITensor>& expert_output,
size_t input_token_count,
const std::vector<size_t>& expert_slots_for_tokens);
+/**
+ * @brief Zero out only the (token, expert_slot) cells that scatter_expert_outputs() never wrote.
+ *
+ * Cheaper than clearing the whole accumulator up front: with dense top-K routing every
+ * token normally fills all num_active_experts slots, so this is a near-free O(num_tokens)
+ * scan in the common case, touching memory only for the rare token whose is_nonzero()
+ * filtering left a slot unfilled.
+ *
+ * @param global_output_buffer Global output buffer [K, 1, num_tokens, embed_dim]
+ * @param token_slot_count Per-token count of slots actually filled during this call
+ * @param num_active_experts K, the number of expert slots expected per token
+ * @param embed_dim Embedding dimension size
+ * @param input_token_count Total number of input tokens
+ */
+void clear_unfilled_accumulator_slots(const ov::SoPtr<ov::ITensor>& global_output_buffer,
+ const std::vector<size_t>& token_slot_count,
+ size_t num_active_experts,
+ size_t embed_dim,
+ size_t input_token_count);
+
/**
* @brief MoE Request Cache - LRU cache for expert inference requests.
*
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.cpp
index 0947691bfb9..e644e857064 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
@@ -5,6 +5,7 @@
#include "moe_resources.hpp"
#include <algorithm>
+#include <cstring>
#include "../logging.hpp"
#include "openvino/core/except.hpp"
@@ -90,6 +91,7 @@ void MoEResources::initialize_expert_iterative_mode(
auto output_element_type = first_model->outputs()[0].get_element_type();
expert_output_accumulator = allocator(output_element_type, buffer_shape, device);
+ std::memset(expert_output_accumulator->data(), 0, expert_output_accumulator->get_byte_size());
LOG_DEBUG("Allocated iterative mode output buffer: shape=" << buffer_shape << ", type=" << output_element_type
<< ", device=" << device);
diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_transformation.hpp b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_transformation.hpp
index 9920b4783de..3b981146ec2 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_transformation.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_transformation.hpp
@@ -36,7 +36,7 @@ struct ParamIndex {
namespace function {
// Default chunk size variants for dynamic iterative mode chunking
-constexpr std::array<size_t, 5> DEFAULT_ITERATIVE_CHUNKING_VARIANTS = {16, 32, 64, 128, 256};
+constexpr std::array<size_t, 8> DEFAULT_ITERATIVE_CHUNKING_VARIANTS = {16, 32, 64, 128, 192, 256, 384, 512};
// Complete structure analysis result (immutable after analysis)
struct MoEStructureInfo {
diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
index 0964960d1d1..97df62f88b7 100644
--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt
+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
@@ -217,5 +217,6 @@ target_sources(${TARGET_NAME} PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/npuw/host_flash_attention_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/moe_k_tag_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/moe_executor_test.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/moe_infer_utils_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/make_tensor_slice_bounds_test.cpp
)
diff --git a/src/plugins/intel_npu/tests/unit/npuw/moe_infer_utils_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/moe_infer_utils_test.cpp
new file mode 100644
index 00000000000..159363ae3d4
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/npuw/moe_infer_utils_test.cpp
@@ -0,0 +1,119 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "moe/moe_infer_utils.hpp"
+
+#include <algorithm>
+#include <gtest/gtest.h>
+
+#include "openvino/runtime/make_tensor.hpp"
+
+/*
+ * Regression tests for the accumulator-clearing optimization introduced to replace an
+ * unconditional memset of the whole MoE output accumulator (see run_expert_iterative()):
+ * only cells that scatter_expert_outputs() did not write (because a token's real routing
+ * count fell short of num_active_experts, e.g. due to is_nonzero() filtering) get cleared
+ * afterwards. These tests pin the exact behavior clear_unfilled_accumulator_slots() must
+ * preserve: filled cells are left untouched, unfilled cells are zeroed, regardless of
+ * whatever garbage previously occupied the buffer.
+ */
+
+namespace {
+
+using ov::npuw::moe::clear_unfilled_accumulator_slots;
+using ov::npuw::moe::scatter_expert_outputs;
+
+constexpr size_t kNumActiveExperts = 3; // K
+constexpr size_t kNumTokens = 4;
+constexpr size_t kEmbedDim = 2;
+
+ov::SoPtr<ov::ITensor> make_accumulator(float fill_value) {
+ ov::Tensor t(ov::element::f32, ov::Shape{kNumActiveExperts, 1, kNumTokens, kEmbedDim});
+ std::fill_n(t.data<float>(), t.get_size(), fill_value);
+ return ov::get_tensor_impl(t);
+}
+
+} // namespace
+
+TEST(ClearUnfilledAccumulatorSlotsTest, ZeroesOnlySlotsBeyondPerTokenCount) {
+ // Sentinel value simulates stale data left over from a previous call, so any cell that
+ // is NOT correctly zeroed by the function under test is trivially detectable.
+ constexpr float kSentinel = 123.0f;
+ auto acc = make_accumulator(kSentinel);
+
+ // token 0: only 1 of 3 slots filled; token 1: 2 of 3; token 2: all 3 (no gap);
+ // token 3: none filled (worst case, router filtered out every selection).
+ const std::vector<size_t> token_slot_count = {1, 2, 3, 0};
+
+ clear_unfilled_accumulator_slots(acc, token_slot_count, kNumActiveExperts, kEmbedDim, kNumTokens);
+
+ const auto* data = acc->data<float>();
+ const size_t slot_stride = kNumTokens * kEmbedDim;
+ auto cell = [&](size_t slot, size_t token) {
+ return data + slot * slot_stride + token * kEmbedDim;
+ };
+
+ for (size_t token_id = 0; token_id < kNumTokens; ++token_id) {
+ for (size_t slot = 0; slot < kNumActiveExperts; ++slot) {
+ const bool should_be_filled = slot < token_slot_count[token_id];
+ const float expected = should_be_filled ? kSentinel : 0.0f;
+ EXPECT_FLOAT_EQ(cell(slot, token_id)[0], expected) << "token=" << token_id << " slot=" << slot;
+ EXPECT_FLOAT_EQ(cell(slot, token_id)[1], expected) << "token=" << token_id << " slot=" << slot;
+ }
+ }
+}
+
+TEST(ClearUnfilledAccumulatorSlotsTest, NoOpWhenEveryTokenFullyRouted) {
+ constexpr float kSentinel = 7.0f;
+ auto acc = make_accumulator(kSentinel);
+ const std::vector<size_t> token_slot_count(kNumTokens, kNumActiveExperts);
+
+ clear_unfilled_accumulator_slots(acc, token_slot_count, kNumActiveExperts, kEmbedDim, kNumTokens);
+
+ const auto* data = acc->data<float>();
+ for (size_t i = 0; i < acc->get_size(); ++i) {
+ EXPECT_FLOAT_EQ(data[i], kSentinel);
+ }
+}
+
+// End-to-end: scatter a sparse selection (one token skipped by one expert slot) into a
+// buffer pre-filled with garbage, then run the targeted clear — result must match what a
+// full up-front memset(0) followed by the same scatter would have produced.
+TEST(ClearUnfilledAccumulatorSlotsTest, MatchesFullClearThenScatterForSparseRouting) {
+ auto acc = make_accumulator(/*fill_value=*/-1.0f);
+
+ // Only token 1 misses one expert slot (slot 2); every other (token, slot) is scattered.
+ std::vector<size_t> token_slot_count(kNumTokens, 0);
+ auto scatter_one = [&](size_t slot, const std::vector<size_t>& tokens, float value) {
+ ov::Tensor expert_out(ov::element::f32, ov::Shape{tokens.size(), kEmbedDim});
+ std::fill_n(expert_out.data<float>(), expert_out.get_size(), value);
+ std::vector<size_t> slots(tokens.size(), slot);
+ scatter_expert_outputs(ov::get_tensor_impl(expert_out),
+ acc,
+ tokens,
+ /*chunk_start=*/0,
+ /*chunk_size=*/tokens.size(),
+ kEmbedDim,
+ kNumTokens,
+ slots);
+ for (auto token_id : tokens) {
+ token_slot_count[token_id] = std::max(token_slot_count[token_id], slot + 1);
+ }
+ };
+ scatter_one(0, {0, 1, 2, 3}, 1.0f);
+ scatter_one(1, {0, 1, 2, 3}, 2.0f);
+ scatter_one(2, {0, 2, 3}, 3.0f); // token 1 skipped at slot 2
+
+ clear_unfilled_accumulator_slots(acc, token_slot_count, kNumActiveExperts, kEmbedDim, kNumTokens);
+
+ const auto* data = acc->data<float>();
+ const size_t slot_stride = kNumTokens * kEmbedDim;
+ auto value_at = [&](size_t slot, size_t token) {
+ return data[slot * slot_stride + token * kEmbedDim];
+ };
+ EXPECT_FLOAT_EQ(value_at(0, 1), 1.0f);
+ EXPECT_FLOAT_EQ(value_at(1, 1), 2.0f);
+ EXPECT_FLOAT_EQ(value_at(2, 1), 0.0f); // must be zero, not the stale -1.0f sentinel
+ EXPECT_FLOAT_EQ(value_at(2, 0), 3.0f);
+}