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] Preserve MoE mixing scores and drain failed expert requests (#38123)
Rajath Ravi71a6aed7cffb
diff --git a/src/plugins/intel_npu/docs/moe-runtime-semantics.md b/src/plugins/intel_npu/docs/moe-runtime-semantics.mdnew file mode 100644index 00000000000..78bbc023b1d--- /dev/null+++ b/src/plugins/intel_npu/docs/moe-runtime-semantics.md@@ -0,0 +1,62 @@+# Host-routed MoE runtime semantics++## Design overview++A mixture-of-experts (MoE) layer combines expert outputs using mixing scores+produced by the model's router. There are E available experts and K selected+slots per token. In NPUW's `HOST_ROUTED` path, the host consumes those scores and+dispatches the required expert work to compiled submodels:++1. The model computes routing scores and hidden-state inputs. The router itself+ need not execute on the host.+2. The host identifies nonzero expert contributions and binds the corresponding+ weights, scores and inputs to prepared expert requests.+3. The compiled expert submodels execute on the configured device, such as the NPU.+4. Their score-weighted outputs are combined into the MoE layer's result.++Host routing describes the dispatch mechanism, not the device executing the+expert arithmetic. In particular, **batched expert execution on the NPU is still+host-routed**. In the separate `DEVICE_ROUTED` path, expert selection is performed+inside the compiled graph rather than by this host executor.++### Single-token decode++The host uses `EXPERT_BATCH`: one prepared fixed-K executable contains K expert+slots. It binds the selected experts' weights and mixing scores, then executes+all slots in one inference request. Requests can be cached by their bound expert+selection; changing scores and input/output tensors must still be rebound.+This batching is part of `HOST_ROUTED`, not `DEVICE_ROUTED`.++### Multi-token prefill++The host uses `EXPERT_ITERATIVE`: tokens are grouped by expert and split into+chunks supported by the prepared executables. Double-buffered asynchronous+requests overlap host preparation with device execution. Score-weighted chunk+outputs are placed in an accumulator and combined by the downstream reduction.++The guarantees below apply after expert submodels have been prepared. They do+not expand graph matching, change expert unrolling, or alter LLM configuration+defaults.++## Runtime guarantees++- Mixing scores are coefficients, not a second routing decision. Every finite+ nonzero score is retained, including negative and very small values. An epsilon+ cutoff can change the result when an expert output is large.+- **Any NaN or infinity is an error**, including an entirely NaN routing tensor.+ Both modes validate scores before treating them as zero or nonzero. Invalid+ scores are not converted to zeros, so backend routing failures remain visible.+- If fewer than K coefficients are nonzero during decode, unused slots reuse an+ active expert's weights with a zero score. The request cache is keyed by that+ padded weight selection; scores and input/output tensors are rebound each time.+- An entirely finite, exactly-zero mixture produces zero expert contribution+ without expert inference. Prefill leaves its accumulator cleared. Both modes+ emit an NPUW warning for the affected subgraph when warning logging is enabled,+ so an unexpected all-zero router result can be investigated. This is a+ coefficient-handling guarantee, not a claim that all-zero routing is typical+ of trained models. It does not apply to nonfinite scores.+- If prefill validation or inference fails, both request slots for every chunk+ size are drained before reuse. Cleanup does not replace the original exception+ or scatter partial results.+- Expert weight slices require a valid leading expert dimension and in-range+ expert index. Four-bit expert boundaries must be byte-aligned.\ No newline at end of filediff --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 d8c43002957..3bd19a1b90a 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 <exception>#include <optional>#include "../compiled_model.hpp" // For CompiledModel::CompiledModelDesc@@ -227,9 +228,6 @@ void MoEExecutor::run(size_t real_idx, size_t idx) {m_token_to_experts,m_expert_to_tokens);});- 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);});@@ -249,8 +247,30 @@ void MoEExecutor::run_expert_batch(size_t idx, size_t real_idx, const std::vectoconst auto& io = m_moe_io[idx];// Validate expert count- if (selected_experts.size() != num_active_experts) {- OPENVINO_THROW("MoE Batch experts: number of selected experts does not match num_active_experts");+ if (selected_experts.size() > num_active_experts) {+ OPENVINO_THROW("MoE Batch experts: nonzero scores exceed the configured top-k");+ }+ // Router parsing has already rejected every non-finite score. An empty+ // selection therefore means all mixing coefficients are finite and zero.+ if (selected_experts.empty()) {+ LOG_WARN("MoE decode: all router mixing scores are zero for subgraph["+ << idx << "]; returning zero expert contribution without inference. "+ << "Check router/backend behavior if this is unexpected.");+ for (const auto& output : io.outputs) {+ OPENVINO_ASSERT(output && output->is_continuous(), "MoE: expected a contiguous expert output");+ std::memset(output->data(), 0, output->get_byte_size());+ }+ return;+ }+ // A selected score may be exactly zero. Fill unused compiled slots with an+ // already selected expert, then bind a zero score for those slots. This+ // retains the fixed-K executable without reading any unselected weights.+ std::vector<size_t> padded_experts;+ const auto* bound_experts = &selected_experts;+ if (selected_experts.size() < num_active_experts) {+ padded_experts = selected_experts;+ padded_experts.resize(num_active_experts, selected_experts.front());+ bound_experts = &padded_experts;}// Step 1: Try to find cached request (O(1) lookup) - if cache is enabled@@ -261,7 +281,7 @@ void MoEExecutor::run_expert_batch(size_t idx, size_t real_idx, const std::vectoconst bool cache_enabled = (m_resources.request_cache != nullptr);if (cache_enabled) {- request = m_resources.request_cache->find(idx, selected_experts);+ request = m_resources.request_cache->find(idx, *bound_experts);}if (!request) {@@ -277,12 +297,12 @@ void MoEExecutor::run_expert_batch(size_t idx, size_t real_idx, const std::vecto// Step 2: Configure expert weightsm_profile->batch["Unpack Closure"].record([&]() {- unpack_multiple_experts_closure(idx, request, selected_experts);+ unpack_multiple_experts_closure(idx, request, *bound_experts);});// Step 3: Register to cache for future hits (only if cache enabled)if (cache_enabled) {- m_resources.request_cache->register_request(idx, pool_idx, selected_experts);+ m_resources.request_cache->register_request(idx, pool_idx, *bound_experts);}}@@ -455,7 +475,7 @@ void MoEExecutor::run_expert_iterative(size_t idx) {// 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).+ // The buffer stores only token IDs with nonzero finite mixing scores.// Slot assignment (O(selected) not O(num_tokens)) is still done at the// top of the next expert iteration.//@@ -481,6 +501,11 @@ void MoEExecutor::run_expert_iterative(size_t idx) {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) {+ // The accumulator has only K output slots per token.+ if (token_slot_count[token_id] >= m_config.num_active_experts) {+ OPENVINO_THROW("MoE Iterative experts: nonzero scores exceed the configured top-k for token ",+ token_id);+ }cur.tokens.push_back(token_id);cur.slots.push_back(token_slot_count[token_id]++);};@@ -565,21 +590,40 @@ void MoEExecutor::run_expert_iterative(size_t idx) {}};- 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");- }-- if (!inflight) {- OPENVINO_THROW("MoE: No experts selected by router");+ try {+ 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");+ }+ if (inflight) {+ do_drain();+ } else {+ // All mixing scores were finite and zero; the accumulator is clear.+ 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.");+ }+ } catch (...) {+ const auto original_error = std::current_exception();+ // A later router row can fail validation while a previous chunk is+ // running. A second request may also be in flight if draining the+ // first throws. Finish both slots before buffers/requests can be reused;+ // preserve the original error and never scatter partial results here.+ for (auto& [chunk_size, requests] : m_resources.chunk_infer_requests) {+ for (auto& request : requests) {+ try {+ request->wait();+ } catch (...) {+ // Do not replace the original inference/validation error.+ }+ }+ }+ std::rethrow_exception(original_error);}-- // Drain the last in-flight item- do_drain();}void MoEExecutor::set_router_scores(size_t idx,@@ -624,7 +668,8 @@ void MoEExecutor::set_router_scores(size_t idx,// Set each unrolled router score parameterfor (size_t k = 0; k < num_active_experts; ++k) {- size_t expert_id = selected_experts[k];+ const bool active = k < selected_experts.size();+ size_t expert_id = active ? selected_experts[k] : 0;size_t unrolled_param_idx = unrolled_router_indices[k];const auto& router_iport = desc.compiled_model->inputs()[unrolled_param_idx];@@ -634,11 +679,11 @@ void MoEExecutor::set_router_scores(size_t idx,if (elem_type == ov::element::f16) {auto* src = router_scores_source->data<ov::float16>();auto* dst = router_tensor->data<ov::float16>();- dst[0] = src[expert_id];+ dst[0] = active ? src[expert_id] : ov::float16{0.0f};} else if (elem_type == ov::element::f32) {auto* src = router_scores_source->data<float>();auto* dst = router_tensor->data<float>();- dst[0] = src[expert_id];+ dst[0] = active ? src[expert_id] : 0.0f;} else {OPENVINO_THROW("Unsupported router scores element type: ", elem_type);}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 5ed91032026..6b157b2d81a 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@@ -27,9 +27,8 @@ MoEProfile::MoEProfile() {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();- if (shape.empty() || shape[0] != num_experts) {- NPUW_ASSERT(false && "Expected batched weight with first dimension equal to num_experts");- }+ OPENVINO_ASSERT(num_experts > 0 && !shape.empty() && shape[0] == num_experts && expert_id < num_experts,+ "MoE: invalid expert weight shape or expert index");// Calculate new shape: replace first dimension with 1ov::Shape view_shape = shape;@@ -40,6 +39,8 @@ ov::Tensor slice_expert_weight(const ov::Tensor& batched_weight, size_t expert_i// by wrapping the data pointer at the correct byte offsetauto elem_type = batched_weight.get_element_type();if (elem_type == ov::element::nf4 || elem_type == ov::element::u4 || elem_type == ov::element::i4) {+ OPENVINO_ASSERT(ov::shape_size(view_shape) % 2 == 0,+ "MoE: sub-byte expert weights must have byte-aligned expert boundaries");// Calculate byte-level offset for this expertsize_t total_byte_size = batched_weight.get_byte_size();size_t expert_byte_size = total_byte_size / num_experts;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 01c4bfb7d1b..f5886d67751 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@@ -9,6 +9,7 @@#include <vector>#include "../perf.hpp"+#include "openvino/core/except.hpp"#include "openvino/runtime/iasync_infer_request.hpp"#include "openvino/runtime/so_ptr.hpp"#include "openvino/runtime/tensor.hpp"@@ -32,7 +33,11 @@ struct MoEProfile {template <typename T>inline bool is_nonzero(T v) {- return std::abs(static_cast<float>(v)) > 1e-6f;+ const float value = static_cast<float>(v);+ OPENVINO_ASSERT(std::isfinite(value), "MoE router produced a non-finite mixing score");+ // A magnitude threshold changes the model: a tiny score can multiply a+ // large expert output. Only exactly-zero contributions may be skipped.+ return value != 0.0f;}/**diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex a440b635880..9be62e6123e 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -213,4 +213,5 @@ target_sources(${TARGET_NAME} PRIVATE${CMAKE_CURRENT_SOURCE_DIR}/npuw/sdpa_pattern_matcher_test.cpp${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)diff --git a/src/plugins/intel_npu/tests/unit/npuw/moe_executor_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/moe_executor_test.cppnew file mode 100644index 00000000000..56b4f826676--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/moe_executor_test.cpp@@ -0,0 +1,487 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "moe/moe_executor.hpp"++#include <gtest/gtest.h>++#include <algorithm>+#include <array>+#include <atomic>+#include <chrono>+#include <cmath>+#include <cstring>+#include <functional>+#include <limits>+#include <map>+#include <memory>+#include <mutex>+#include <string>+#include <tuple>+#include <vector>++#include "compiled_model.hpp"+#include "llm_test_helpers.hpp"+#include "openvino/op/ops.hpp"+#include "openvino/runtime/make_tensor.hpp"++namespace {++struct ExecutionLog {+ std::mutex mutex;+ std::vector<const ov::IAsyncInferRequest*> calls;+ std::atomic<size_t> pending{0};+ bool fail_wait = false;+};++// Deliberately prepared expert executables: these tests exercise the existing+// executor contract without requiring topology matching, unrolling or an LLM.+// All request operations used by MoEExecutor are overridden; no base pipeline+// or synchronous request is needed for this deferred, evaluatable fixture.+class EvaluatedRequest final : public ov::IAsyncInferRequest {+public:+ EvaluatedRequest(std::shared_ptr<const ov::ICompiledModel> compiled,+ std::shared_ptr<ov::Model> model,+ std::shared_ptr<ExecutionLog> log)+ : ov::IAsyncInferRequest(nullptr, nullptr, nullptr),+ m_compiled(std::move(compiled)),+ m_model(std::move(model)),+ m_log(std::move(log)) {+ for (const auto& port : m_compiled->inputs())+ allocate(port);+ for (const auto& port : m_compiled->outputs())+ allocate(port);+ }++ void infer() override {+ OPENVINO_ASSERT(!m_pending, "Cannot infer a pending request");+ ov::TensorVector inputs, outputs;+ for (const auto& port : get_inputs())+ inputs.push_back(ov::make_tensor(get_tensor(port)));+ for (const auto& port : get_outputs())+ outputs.push_back(ov::make_tensor(get_tensor(port)));+ OPENVINO_ASSERT(m_model->evaluate(outputs, inputs), "Expert evaluation failed");+ std::lock_guard<std::mutex> lock(m_log->mutex);+ m_log->calls.push_back(this);+ }+ void start_async() override {+ OPENVINO_ASSERT(!m_pending, "Request already pending");+ m_pending = true;+ ++m_log->pending;+ }+ void wait() override {+ if (!m_pending)+ return;+ m_pending = false;+ --m_log->pending;+ if (m_log->fail_wait) {+ m_log->fail_wait = false;+ OPENVINO_THROW("Deferred expert failure");+ }+ infer();+ }+ bool wait_for(const std::chrono::milliseconds&) override {+ wait();+ return true;+ }+ void cancel() override {}+ void set_callback(std::function<void(std::exception_ptr)>) override {}+ ov::SoPtr<ov::ITensor> get_tensor(const ov::Output<const ov::Node>& port) const override {+ return m_tensors.at(port);+ }+ void set_tensor(const ov::Output<const ov::Node>& port, const ov::SoPtr<ov::ITensor>& tensor) override {+ OPENVINO_ASSERT(!m_pending, "Cannot rebind a pending request");+ m_tensors.at(port) = tensor;+ }+ const std::vector<ov::Output<const ov::Node>>& get_inputs() const override {+ return m_compiled->inputs();+ }+ const std::vector<ov::Output<const ov::Node>>& get_outputs() const override {+ return m_compiled->outputs();+ }+ const std::shared_ptr<const ov::ICompiledModel>& get_compiled_model() const override {+ return m_compiled;+ }++private:+ void allocate(const ov::Output<const ov::Node>& port) {+ ov::Tensor tensor(port.get_element_type(), port.get_shape());+ std::memset(tensor.data(), 0, tensor.get_byte_size());+ m_tensors.emplace(port, ov::get_tensor_impl(tensor));+ }+ std::shared_ptr<const ov::ICompiledModel> m_compiled;+ std::shared_ptr<ov::Model> m_model;+ std::shared_ptr<ExecutionLog> m_log;+ std::map<ov::Output<const ov::Node>, ov::SoPtr<ov::ITensor>> m_tensors;+ bool m_pending = false;+};++class EvaluatedModel final : public ov::ICompiledModel {+public:+ EvaluatedModel(const std::shared_ptr<ov::Model>& model, std::shared_ptr<ExecutionLog> log)+ : ov::ICompiledModel(model, std::make_shared<ov::test::npuw::NullPlugin>()),+ m_model(model),+ m_log(std::move(log)) {}+ std::shared_ptr<ov::IAsyncInferRequest> create_infer_request() const override {+ return std::make_shared<EvaluatedRequest>(shared_from_this(), m_model, m_log);+ }+ std::shared_ptr<ov::ISyncInferRequest> create_sync_infer_request() const override {+ OPENVINO_THROW("Only evaluated async requests are used by this fixture");+ }+ std::shared_ptr<const ov::Model> get_runtime_model() const override {+ return m_model;+ }+ void export_model(std::ostream&) const override {}+ void set_property(const ov::AnyMap&) override {}+ ov::Any get_property(const std::string&) const override {+ return {};+ }++private:+ std::shared_ptr<ov::Model> m_model;+ std::shared_ptr<ExecutionLog> m_log;+};++class ExecutorHarness final : public ov::npuw::ISubrequestAccessor {+public:+ static constexpr size_t experts = 4, selected = 2, hidden = 4, chunk = 3;++ ExecutorHarness(size_t tokens, const ov::element::Type& score_type, size_t pool)+ : token_count(tokens),+ scores(score_type, ov::Shape{experts, tokens, 1}),+ weights(ov::element::f32, ov::Shape{experts, 1, hidden}),+ log(std::make_shared<ExecutionLog>()) {+ const bool decode = tokens == 1;+ auto x = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{decode ? 1 : chunk, hidden});+ ov::ParameterVector params{x};+ ov::OutputVector contributions;+ auto state = std::make_shared<ov::npuw::compiled::MoEExperts>();+ state->num_experts = experts;+ state->num_active_experts = selected;+ state->expert_hidden_dim = hidden;+ state->input_token_count = tokens;+ state->_expert_input = {0, 0};+ state->_router_scores = {1, 1};+ for (size_t slot = 0; slot < (decode ? selected : 1); ++slot) {+ auto score = std::make_shared<ov::op::v0::Parameter>(score_type, ov::Shape{1, decode ? 1 : chunk, 1});+ auto weight = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 1, hidden});+ state->_param_mapping[1].push_back(params.size());+ params.push_back(score);+ state->_param_mapping[2].push_back(params.size());+ params.push_back(weight);+ contributions.push_back(+ std::make_shared<ov::op::v1::Multiply>(std::make_shared<ov::op::v1::Multiply>(x, weight),+ std::make_shared<ov::op::v0::Convert>(score, ov::element::f32)));+ }+ ov::Output<ov::Node> output = contributions[0];+ if (decode) {+ output = std::make_shared<ov::op::v1::Add>(output, contributions[1]);+ output = std::make_shared<ov::op::v0::Squeeze>(+ output,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0}));+ }+ auto model = std::make_shared<ov::Model>(ov::OutputVector{output}, params);+ desc.compiled_model = {std::make_shared<EvaluatedModel>(model, log), {}};+ state->_compiled_models[decode ? 0 : chunk] = desc.compiled_model;+ ov::npuw::moe::put_compiled_experts(desc.pipeline.context, state);+ desc.replaced_by = 0;+ desc.param_base = 2;+ desc.closure.get().closure = {weights};+ for (size_t expert = 0; expert < experts; ++expert)+ std::fill_n(weights.data<float>() + expert * hidden, hidden, 1024.0f * static_cast<float>(expert + 1));+ request = {desc.compiled_model->create_infer_request(), {}};+ executor = std::make_unique<ov::npuw::moe::MoEExecutor>(+ *this,+ [this](const ov::element::Type& type, const ov::Shape& shape, const std::string& device) {+ auto result = allocate_mem(type, shape, device);+ accumulator = ov::make_tensor(result);+ return result;+ });+ executor->prepare(0, 0, 1, decode ? pool : 0);+ log->calls.clear(); // Exclude pool warmups.+ }++ void set_score(size_t expert, size_t token, float value) {+ const auto offset = expert * token_count + token;+ if (scores.get_element_type() == ov::element::f32)+ scores.data<float>()[offset] = value;+ else+ scores.data<ov::float16>()[offset] = ov::float16(value);+ }+ float score(size_t expert, size_t token) const {+ const auto offset = expert * token_count + token;+ return scores.get_element_type() == ov::element::f32 ? scores.data<float>()[offset]+ : static_cast<float>(scores.data<ov::float16>()[offset]);+ }+ void bind(float input_value) {+ // New input AND output tensors each time detect stale bindings on cache hits.+ input = ov::Tensor(ov::element::f32, ov::Shape{token_count, hidden});+ output = ov::Tensor(ov::element::f32, ov::Shape{1, hidden});+ std::fill_n(input.data<float>(), input.get_size(), input_value);+ std::fill_n(output.data<float>(), output.get_size(), -100.0f);+ executor->function_prologue_moe_input(0, 0, 0, ov::get_tensor_impl(input));+ executor->function_prologue_moe_input(0, 0, 1, ov::get_tensor_impl(scores));+ executor->function_prologue_moe_output(0, 0, ov::get_tensor_impl(output));+ }+ void check() {+ executor->run(0, 0);+ EXPECT_EQ(log->pending.load(), 0u);+ for (size_t token = 0; token < token_count; ++token) {+ for (size_t h = 0; h < hidden; ++h) {+ float expected = 0;+ for (size_t expert = 0; expert < experts; ++expert)+ expected += input.data<float>()[token * hidden + h] * weights.data<float>()[expert * hidden + h] *+ score(expert, token);+ float actual = output.data<float>()[h];+ if (token_count != 1) {+ actual = 0;+ for (size_t slot = 0; slot < selected; ++slot)+ actual += accumulator.data<float>()[(slot * token_count + token) * hidden + h];+ }+ EXPECT_NEAR(actual, expected, 1e-5f);+ }+ }+ }++ ov::SoPtr<ov::IAsyncInferRequest> get_subrequest(size_t) override {+ return request;+ }+ const void* get_submodel_desc(size_t) override {+ return &desc;+ }+ ov::npuw::util::TensorPtr allocate_mem(const ov::element::Type& type,+ const ov::Shape& shape,+ const std::string&) override {+ return ov::get_tensor_impl(ov::Tensor(type, shape));+ }+ bool is_gather_closure(size_t, size_t) override {+ return false;+ }+ bool unpack_required(size_t, size_t) override {+ return false;+ }+ bool needs_copy_closure(size_t, size_t) override {+ return false;+ }+ std::string subgraph_device(size_t) override {+ return "CPU";+ }++ size_t token_count;+ ov::Tensor scores, weights, input, output, accumulator;+ std::shared_ptr<ExecutionLog> log;+ std::unique_ptr<ov::npuw::moe::MoEExecutor> executor;++private:+ ov::npuw::CompiledModelDescTestAccessor::SubmodelDesc desc;+ ov::SoPtr<ov::IAsyncInferRequest> request;+};++class MoEExecutorRuntimeTest : public ::testing::TestWithParam<std::tuple<bool, size_t, size_t>> {};++TEST_P(MoEExecutorRuntimeTest, PreservesScoresAndBindingsAcrossSelections) {+ const auto [half_scores, tokens, pool] = GetParam();+ ExecutorHarness harness(tokens, half_scores ? ov::element::f16 : ov::element::f32, pool);+ const std::vector<std::array<float, 2>> coefficients{{0.5f, 0.25f},+ {0.0f, 0.5f},+ {-0.5f, 0.25f},+ {0.0f, 0.0f},+ {0.5f, 0.0f},+ {0.5f, 0.25f},+ {0.0f, 0.5f},+ {0x1p-24f, -0x1p-23f}};+ for (size_t iteration = 0; iteration < coefficients.size(); ++iteration) {+ std::memset(harness.scores.data(), 0, harness.scores.get_byte_size());+ for (size_t token = 0; token < tokens; ++token) {+ const size_t a = ((iteration % 2 == 0 ? 0 : 1) + token) % 4;+ const size_t b = ((iteration % 2 == 0 ? 1 : 3) + token) % 4;+ harness.set_score(a, token, coefficients[iteration][0]);+ harness.set_score(b, token, coefficients[iteration][1]);+ }+ harness.bind(static_cast<float>(iteration + 1) / 8.0f);+ const auto before = harness.log->calls.size();+ harness.check();+ if (iteration == 3)+ EXPECT_EQ(harness.log->calls.size(), before);+ else if (tokens == 1)+ EXPECT_EQ(harness.log->calls.size(), before + 1);+ else+ EXPECT_GT(harness.log->calls.size(), before);+ }+ if (tokens == 1 && pool > 0) {+ ASSERT_EQ(harness.log->calls.size(), 7u);+ EXPECT_EQ(harness.log->calls[0], harness.log->calls[2]);+ EXPECT_NE(harness.log->calls[0], harness.log->calls[1]);+ }+}++TEST_P(MoEExecutorRuntimeTest, RejectsNonfiniteScoresInsteadOfReturningZeroAndRemainsReusable) {+ const auto [half_scores, tokens, pool] = GetParam();+ ExecutorHarness harness(tokens, half_scores ? ov::element::f16 : ov::element::f32, pool);+ for (const float invalid : {std::numeric_limits<float>::quiet_NaN(),+ std::numeric_limits<float>::infinity(),+ -std::numeric_limits<float>::infinity()}) {+ SCOPED_TRACE(invalid);+ for (const bool all_nonfinite : {true, false}) {+ SCOPED_TRACE(all_nonfinite);+ std::memset(harness.scores.data(), 0, harness.scores.get_byte_size());+ if (all_nonfinite) {+ for (size_t expert = 0; expert < ExecutorHarness::experts; ++expert) {+ for (size_t token = 0; token < tokens; ++token)+ harness.set_score(expert, token, invalid);+ }+ } else {+ // Prefill can already have work in flight when a later expert's+ // row fails validation; decode must validate before dispatch.+ for (size_t token = 0; token < tokens; ++token) {+ harness.set_score(0, token, 0.5f);+ harness.set_score(1, token, invalid);+ }+ }+ harness.bind(0.5f);+ const auto before = harness.log->calls.size();+ try {+ harness.executor->run(0, 0);+ FAIL() << "Non-finite routing scores must not return a successful zero result";+ } catch (const ov::Exception& error) {+ EXPECT_NE(std::string(error.what()).find("MoE router produced a non-finite mixing score"),+ std::string::npos);+ }+ EXPECT_EQ(harness.log->pending.load(), 0u);+ if (tokens == 1 || all_nonfinite)+ EXPECT_EQ(harness.log->calls.size(), before);+ else+ EXPECT_GT(harness.log->calls.size(), before);++ // A finite all-zero tensor remains a valid, no-inference case.+ const auto after_failure = harness.log->calls.size();+ std::memset(harness.scores.data(), 0, harness.scores.get_byte_size());+ harness.bind(0.25f);+ harness.check();+ EXPECT_EQ(harness.log->calls.size(), after_failure);++ // Reuse the same executor/requests with new bindings and selections.+ for (size_t token = 0; token < tokens; ++token) {+ harness.set_score(2, token, 0.25f);+ harness.set_score(3, token, -0.5f);+ }+ harness.bind(0.75f);+ harness.check();+ EXPECT_GT(harness.log->calls.size(), after_failure);+ }+ }+}++TEST_P(MoEExecutorRuntimeTest, RejectsExcessExpertsPerTokenAndRemainsReusable) {+ const auto [half_scores, tokens, pool] = GetParam();+ ExecutorHarness harness(tokens, half_scores ? ov::element::f16 : ov::element::f32, pool);+ std::vector<size_t> invalid_tokens{0};+ if (tokens > 1)+ invalid_tokens.push_back(tokens - 1);++ // Expert 2 exercises parse-ahead; leaving its row empty and using expert 3+ // exercises the full scan. Both must reject before dispatching that expert.+ for (const size_t extra_expert : {size_t{2}, size_t{3}}) {+ SCOPED_TRACE(extra_expert);+ for (const float extra_score : {0.25f, 0x1p-24f, -0x1p-24f}) {+ SCOPED_TRACE(extra_score);+ for (const size_t invalid_token : invalid_tokens) {+ SCOPED_TRACE(invalid_token);+ std::memset(harness.scores.data(), 0, harness.scores.get_byte_size());+ for (size_t token = 0; token < tokens; ++token) {+ harness.set_score(0, token, 0.5f);+ harness.set_score(1, token, 0.25f);+ }+ // Only one token violates K, including with an f16-representable+ // tiny coefficient that must not be hidden by a threshold.+ harness.set_score(extra_expert, invalid_token, extra_score);+ harness.bind(0.5f);+ const auto before = harness.log->calls.size();+ try {+ harness.executor->run(0, 0);+ FAIL() << "A token with more than K nonzero scores must be rejected";+ } catch (const ov::Exception& error) {+ EXPECT_NE(std::string(error.what()).find("nonzero scores exceed the configured top-k"),+ std::string::npos);+ }+ EXPECT_EQ(harness.log->pending.load(), 0u);+ if (tokens == 1) {+ EXPECT_EQ(harness.log->calls.size(), before);+ } else {+ // Both valid experts dispatched all chunks; cleanup waits for+ // the final pending chunk, but no excess expert was launched.+ const auto chunks = (tokens + ExecutorHarness::chunk - 1) / ExecutorHarness::chunk;+ EXPECT_EQ(harness.log->calls.size(), before + ExecutorHarness::selected * chunks);+ }++ const auto after_failure = harness.log->calls.size();+ std::memset(harness.scores.data(), 0, harness.scores.get_byte_size());+ harness.bind(0.25f);+ harness.check();+ EXPECT_EQ(harness.log->calls.size(), after_failure);++ // Reuse with new bindings and exactly K experts per token. Across+ // the prefill batch, the union may legally contain all E experts.+ for (size_t token = 0; token < tokens; ++token) {+ harness.set_score(token % ExecutorHarness::experts, token, 0.25f);+ harness.set_score((token + 2) % ExecutorHarness::experts, token, -0.5f);+ }+ harness.bind(0.75f);+ harness.check();+ EXPECT_GT(harness.log->calls.size(), after_failure);+ }+ }+ }+}++INSTANTIATE_TEST_SUITE_P(ScoreTypesAndModes,+ MoEExecutorRuntimeTest,+ ::testing::Combine(::testing::Bool(),+ ::testing::Values(size_t{1}, size_t{7}),+ ::testing::Values(size_t{0}, size_t{2})));++TEST(MoEExecutorCleanupTest, DrainsDeferredRequestsAndRemainsReusableAfterFailures) {+ for (const auto type : {ov::element::f32, ov::element::f16}) {+ for (const bool inference_failure : {false, true}) {+ ExecutorHarness harness(7, type, 0);+ std::memset(harness.scores.data(), 0, harness.scores.get_byte_size());+ for (size_t token = 0; token < 7; ++token) {+ harness.set_score(0, token, 0.5f);+ harness.set_score(1, token, inference_failure ? 0.25f : std::numeric_limits<float>::quiet_NaN());+ }+ harness.bind(0.5f);+ harness.log->fail_wait = inference_failure;+ EXPECT_THROW(harness.executor->run(0, 0), ov::Exception);+ EXPECT_EQ(harness.log->pending.load(), 0u);+ for (size_t token = 0; token < 7; ++token)+ harness.set_score(1, token, 0.25f);+ harness.bind(0.25f);+ harness.check();+ }+ }+}++TEST(MoEExecutorUtilitiesTest, OnlyExactZeroIsInactiveAndNonfiniteScoresFail) {+ for (const float value : {0.0f, -0.0f})+ EXPECT_FALSE(ov::npuw::moe::is_nonzero(value));+ for (const float value : {1e-9f, -1e-10f, 0.5f})+ EXPECT_TRUE(ov::npuw::moe::is_nonzero(value));+ for (const float value : {std::numeric_limits<float>::infinity(),+ -std::numeric_limits<float>::infinity(),+ std::numeric_limits<float>::quiet_NaN()}) {+ EXPECT_THROW(ov::npuw::moe::is_nonzero(value), ov::Exception);+ EXPECT_THROW(ov::npuw::moe::is_nonzero(ov::float16(value)), ov::Exception);+ }+}++TEST(MoEExecutorUtilitiesTest, ValidatesExpertSlicesAndPackedBoundaries) {+ ov::Tensor aligned(ov::element::i4, ov::Shape{4, 2, 4});+ EXPECT_EQ(ov::npuw::moe::slice_expert_weight(aligned, 3, 4).get_shape(), (ov::Shape{1, 2, 4}));+ EXPECT_THROW(ov::npuw::moe::slice_expert_weight(aligned, 4, 4), ov::Exception);+ EXPECT_THROW(ov::npuw::moe::slice_expert_weight(aligned, 0, 0), ov::Exception);+ ov::Tensor unaligned(ov::element::i4, ov::Shape{4, 3, 1});+ EXPECT_THROW(ov::npuw::moe::slice_expert_weight(unaligned, 1, 4), ov::Exception);+}++} // namespace