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
[GPU] Support OFFLOAD_RATIO=100 and validate MoE resident memory (#38663)
Xiong Yuan500d37e98d27
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_swiglu_opt.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_swiglu_opt.cppindex 4a8f7eac072..a07c75481c9 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_swiglu_opt.cpp+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_swiglu_opt.cpp@@ -1065,9 +1065,9 @@ public:return decode_impl == MoeGemmImpl::grouped_gemm || (prefill_impl == MoeGemmImpl::grouped_gemm && force_gpu_mask_gen_prefill);}- // Single-token decode on the batched GEMV path uses none of the gather/scatter scratch buffers+ // Resident single-token decode on the batched GEMV path uses none of the gather/scatter scratch buffersbool needs_gather_scratch(size_t token_num) const {- return token_num > 1 || decode_impl == MoeGemmImpl::grouped_gemm;+ return token_num > 1 || decode_impl == MoeGemmImpl::grouped_gemm || (token_num == 1 && _weight_provider->is_offloaded());}static bool is_batched_gemv_supported(data_types weight_dt) {@@ -1372,10 +1372,8 @@ public:auto up_mem_dnnl = convert2dnnl(scratch.up, {batch, _shared_intermediate_size}, dnnl::memory::format_tag::ab);auto gate_mem_dnnl = convert2dnnl(scratch.gate, {batch, _shared_intermediate_size}, dnnl::memory::format_tag::ab);- // Reuse routing weights or topk_weights buffer as temp for scalar gate [Batch, 1]- // This buffer is usually [Batch, MaxTopK]. Check if big enough. Batch=1 -> TopK. Batch>1 -> Batch*TopK.- // We only use [Batch, 1] part.- auto scalar_gate_mem = scratch.topk_weights;+ // Routed computation is complete; reuse its scratch without modifying the routing input.+ auto scalar_gate_mem = scratch.routing_weights;auto scalar_gate_dnnl = convert2dnnl(scalar_gate_mem, {batch, 1}, dnnl::memory::format_tag::ab);// 1. Up Proj@@ -1520,7 +1518,7 @@ public:// Per-expert masks feed only the per-expert onednn loop, which the other paths fall back to only with offloaded// experts. Creating them costs two sub-buffers per expert in every layer (~0.4 ms per layer for 256 experts).const bool needs_expert_masks = select_impl(token_num) == MoeGemmImpl::per_expert_onednn || _weight_provider->is_offloaded();- if (token_num > 1 && needs_expert_masks) {+ if (needs_gather_scratch(token_num) && needs_expert_masks) {const auto& config = instance.get_typed_desc<moe_3gemm_fused_compressed>()->_config;int expert_num = static_cast<int>(config.num_expert);scratch.expert_masks.resize(expert_num);@@ -1666,8 +1664,6 @@ public:typed_primitive_inst<moe_3gemm_fused_compressed>& instance,scratch_buffers& scratch,size_t token_num) {- auto& cur_net = instance.get_network();- auto& stream = cur_net.get_stream();auto cur_moe = instance.get_typed_desc<moe_3gemm_fused_compressed>();int max_topk = static_cast<int>(cur_moe->_config.top_k);@@ -1681,16 +1677,6 @@ public:const size_t subgroup_size = instance.get_impl_params()->get_device_info().arch >= gpu_arch::xe2 ? 32 : 16;const size_t max_work_group_size = instance.get_impl_params()->get_device_info().max_work_group_size;- {- const size_t topk_count = token_num * static_cast<size_t>(max_topk);- bool needs_fallback = false;- on_before_batched_gemv(stream, instance, scratch, topk_count, needs_fallback);- if (needs_fallback) {- // Cannot fit all experts simultaneously → fall back to per-expert onednn loop- instance.output_memory_ptr(0)->fill(stream, 0u);- return exec_per_expert_onednn_linear(events, stream, instance, scratch);- }- }// OTD hook may have remapped expert IDs into scratch._expert_index_bufferif (scratch._expert_index_buffer) {batch_mem_ptr = scratch._expert_index_buffer;@@ -2800,8 +2786,12 @@ public:// Batched GEMV: for small token counts (including single token, MTP/speculative decoding),// use optimized GEMV kernels with batch dimension. Avoids gather/scatter overhead.const MoeGemmImpl impl = select_impl(token_num);+ bool batched_fallback = false;if (impl == MoeGemmImpl::batched_gemv) {- return exec_batched_gemv(events, instance, scratch, token_num);+ on_before_batched_gemv(stream, instance, scratch, token_num * config.top_k, batched_fallback);+ if (!batched_fallback) {+ return exec_batched_gemv(events, instance, scratch, token_num);+ }}auto final_hidden_states_mem_ptr = instance.output_memory_ptr(0);@@ -2811,10 +2801,10 @@ public:// and does not require pre-zeroing — except in OTD mode where the// fallback to exec_per_expert_onednn_linear (when unique_experts > lru slots)// also accumulates via index_add.- if (impl != MoeGemmImpl::micro_gemm && should_pre_zero_output()) {+ if (batched_fallback || (impl != MoeGemmImpl::micro_gemm && should_pre_zero_output())) {final_hidden_states_mem_ptr->fill(stream, 0u);}- const bool use_gpu_mask_gen = should_use_gpu_mask_gen(impl, token_num);+ const bool use_gpu_mask_gen = !batched_fallback && should_use_gpu_mask_gen(impl, token_num);if (!use_gpu_mask_gen) {// Wait for input events (topk produced upstream by MoERouterFused)for (const auto& ev : events) {@@ -2827,7 +2817,9 @@ public:GPU_DEBUG_TRACE_DETAIL << "\nMoE3GemmFusedCompressed exec(): token_num=" << token_num << ", max_topk=" << static_cast<int>(config.top_k)<< ", impl=" << static_cast<int>(impl) << std::endl;update_rt_params(instance);- if (impl == MoeGemmImpl::micro_gemm) {+ if (batched_fallback) {+ ret_env = exec_per_expert_onednn_linear(events, stream, instance, scratch);+ } else if (impl == MoeGemmImpl::micro_gemm) {ret_env = exec_prefill_micro_gemm(events, instance, scratch, use_gpu_mask_gen);} else if (impl == MoeGemmImpl::grouped_gemm) {ret_env = use_gpu_mask_gen ? exec_grouped_gemm_gpu_mask_gen(events, stream, instance, scratch)@@ -2862,6 +2854,10 @@ public:}execute_shared_expert(stream.get_onednn_stream(), static_cast<int>(token_num), hidden_states_mem_ptr, final_hidden_states_mem_ptr, scratch);}+ if (batched_fallback) {+ // Include the shared expert and all OneDNN work before returning the completion event.+ on_after_exec_sync(stream);+ }return ret_env;}};diff --git a/src/plugins/intel_gpu/src/plugin/ops/constant.cpp b/src/plugins/intel_gpu/src/plugin/ops/constant.cppindex 84444ceda27..d6b083ce79b 100644--- a/src/plugins/intel_gpu/src/plugin/ops/constant.cpp+++ b/src/plugins/intel_gpu/src/plugin/ops/constant.cpp@@ -165,15 +165,7 @@ static void create_data(ProgramBuilder& p, const ov::Shape& const_shape, const s<< ", layout: " << constLayout.to_short_string() << std::endl;return;}- auto partial_upload = try_prepare_partial_upload(p.get_engine(),- p.get_config(),- op,- const_shape,- out_dtype,- constFormat,- constLayout);--+ auto partial_upload = try_prepare_partial_upload(p.get_engine(), p.get_config(), op, const_shape, out_dtype, constFormat, constLayout);if (partial_upload.enabled) {mem = partial_upload.memory;diff --git a/src/plugins/intel_gpu/src/plugin/ops/moe.cpp b/src/plugins/intel_gpu/src/plugin/ops/moe.cppindex 12b15b7e1f7..796946a0207 100644--- a/src/plugins/intel_gpu/src/plugin/ops/moe.cpp+++ b/src/plugins/intel_gpu/src/plugin/ops/moe.cpp@@ -23,14 +23,15 @@#include "openvino/core/model.hpp"#include "openvino/core/rt_info/weightless_caching_attributes.hpp"#include "openvino/core/weight_sharing_util.hpp"+#include "moe_offload_constant.hpp"namespace ov::intel_gpu {using namespace cldnn;// Resolves OTD (offload-to-disk) parameters for a GEMM3_SWIGLU MOECompressed op.// OFFLOAD_RATIO specifies the percentage of experts offloaded to disk (0-100).-// The number of GPU-resident LRU slots = num_expert * (100 - ratio) / 100.-// ratio=0 means all resident (no OTD); ratio=100 means all on disk (invalid, disabled).+// For ratios 1-100, GPU-resident LRU slots = max(1, num_expert * (100 - ratio) / 100).+// ratio=0 means all resident (no OTD).// Returns true when OTD is enabled (lru_expert_num > 0).static bool prepare_moe_otd_params(ProgramBuilder& p,const std::shared_ptr<ov::op::internal::MOECompressed>& op,@@ -40,11 +41,16 @@ static bool prepare_moe_otd_params(ProgramBuilder& p,using input_idx = cldnn::moe_3gemm_fused_compressed::input_index;const auto& config = op->get_config();const size_t otd_ratio = p.get_config().get_offload_ratio();- // ratio=0 → all resident, no offload- // ratio=100 → all on disk, cannot run → treat as disabled- // otherwise → GPU-resident slots = num_expert * (100 - ratio) / 100- if (otd_ratio > 0 && otd_ratio < 100) {- lru_expert_num = std::max<size_t>(1, static_cast<size_t>(config.num_expert) * (100 - otd_ratio) / 100);+ // ratio=0: all resident, no offload+ // ratios 1-100: GPU-resident slots = max(1, num_expert * (100 - ratio) / 100)+ if (otd_ratio > 0 && otd_ratio <= 100) {+ // Fall back to resident mode if any routed expert constant is not safely offloadable+ // (e.g. shared with non-routed consumers: NotOffloadableRoutedExpert).+ if (is_moe_otd_eligible(op.get())) {+ lru_expert_num = std::max<size_t>(1, static_cast<size_t>(config.num_expert) * (100 - otd_ratio) / 100);+ } else {+ lru_expert_num = 0;+ }} else {lru_expert_num = 0;}diff --git a/src/plugins/intel_gpu/src/plugin/ops/moe_offload_constant.cpp b/src/plugins/intel_gpu/src/plugin/ops/moe_offload_constant.cppindex 39275caf4f4..96400790531 100644--- a/src/plugins/intel_gpu/src/plugin/ops/moe_offload_constant.cpp+++ b/src/plugins/intel_gpu/src/plugin/ops/moe_offload_constant.cpp@@ -4,6 +4,14 @@#include "moe_offload_constant.hpp"+#include <algorithm>+#include <functional>+#include <limits>+#include <unordered_set>+#include <vector>++#include "openvino/op/util/multi_subgraph_base.hpp"+namespace ov::intel_gpu {// Input indices 3..11 are routed expert weights/scales/zps (WEIGHT_0..ZP_2).@@ -14,27 +22,152 @@ static constexpr size_t ROUTED_INPUT_END = 11;static constexpr size_t SHARED_INPUT_START = 12;static constexpr size_t SHARED_INPUT_END = 21;+bool is_otd_capable_moe(const ov::Node* node) {+ if (const auto* moe = ov::as_type<const ov::op::internal::MOECompressed>(node)) {+ return moe->get_config().expert_type == ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU;+ }+ return false;+}+MoEConstantRole get_moe_constant_role(const std::shared_ptr<ov::op::v0::Constant>& op) {- const auto users = op->get_output_target_inputs(0);- for (const auto& input : users) {+ const auto target_inputs = op->get_output_target_inputs(0);+ bool has_moe_consumer = false;+ bool has_non_otd_moe = false;+ bool has_routed = false;+ bool has_shared = false;+ bool has_other_consumer = false;++ for (const auto& input : target_inputs) {const auto* node = input.get_node();- if (ov::is_type<ov::op::internal::MOECompressed>(node)) {- auto idx = input.get_index();- if (idx >= ROUTED_INPUT_START && idx <= ROUTED_INPUT_END) {- return MoEConstantRole::RoutedExpert;+ if (const auto* moe = ov::as_type<const ov::op::internal::MOECompressed>(node)) {+ has_moe_consumer = true;+ if (moe->get_config().expert_type != ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU) {+ has_non_otd_moe = true;+ } else {+ const auto idx = input.get_index();+ if (idx >= ROUTED_INPUT_START && idx <= ROUTED_INPUT_END) {+ has_routed = true;+ } else if (idx >= SHARED_INPUT_START && idx <= SHARED_INPUT_END) {+ has_shared = true;+ } else {+ has_other_consumer = true;+ }}- if (idx >= SHARED_INPUT_START && idx <= SHARED_INPUT_END) {- return MoEConstantRole::SharedExpert;+ } else {+ has_other_consumer = true;+ }+ }++ if (!has_moe_consumer) {+ return MoEConstantRole::NotMoE;+ }+ if (has_non_otd_moe) {+ return MoEConstantRole::NotOffloadableMoE;+ }+ if (has_shared) {+ return MoEConstantRole::AlwaysResidentSharedExpert;+ }+ if (has_routed) {+ if (has_other_consumer) {+ return MoEConstantRole::NotOffloadableRoutedExpert;+ }+ return MoEConstantRole::OffloadableRoutedExpert;+ }+ return MoEConstantRole::NotOffloadableMoE;+}++bool is_moe_otd_eligible(const ov::Node* node) {+ std::vector<const ov::Node*> pending{node};+ std::unordered_set<const ov::Node*> visited;+ while (!pending.empty()) {+ const auto* current = pending.back();+ pending.pop_back();+ if (!visited.insert(current).second)+ continue;+ if (!is_otd_capable_moe(current) || current->get_input_size() <= ROUTED_INPUT_END)+ return false;+ for (size_t index = ROUTED_INPUT_START; index <= ROUTED_INPUT_END; ++index) {+ auto constant = ov::as_type_ptr<ov::op::v0::Constant>(current->input_value(index).get_node_shared_ptr());+ if (!constant || get_moe_constant_role(constant) != MoEConstantRole::OffloadableRoutedExpert)+ return false;+ // Propagate resident fallback across MoEs sharing routed constants.+ for (const auto& consumer : constant->get_output_target_inputs(0)) {+ pending.push_back(consumer.get_node());}}}- return MoEConstantRole::NotMoE;+ return true;+}++bool is_moe_constant_offloadable(const std::shared_ptr<ov::op::v0::Constant>& op) {+ if (get_moe_constant_role(op) != MoEConstantRole::OffloadableRoutedExpert)+ return false;+ const auto consumers = op->get_output_target_inputs(0);+ return std::all_of(consumers.begin(), consumers.end(), [](const ov::Input<ov::Node>& consumer) {+ return is_moe_otd_eligible(consumer.get_node());+ });}bool is_moe_related_constant(const std::shared_ptr<ov::op::v0::Constant>& op) {return get_moe_constant_role(op) != MoEConstantRole::NotMoE;}+uint64_t get_model_resident_constant_bytes(const ov::Model& model, size_t offload_ratio) {+ OPENVINO_ASSERT(offload_ratio <= 100, "OFFLOAD_RATIO must be in the range [0, 100]");++ uint64_t resident_bytes = 0;+ bool has_moe = false;+ std::unordered_set<const ov::Node*> visited;+ std::function<void(const ov::Model&)> collect_resident_bytes = [&](const ov::Model& current_model) {+ for (const auto& node : current_model.get_ops()) {+ has_moe = has_moe || is_otd_capable_moe(node.get());+ if (auto subgraph_op = ov::as_type_ptr<ov::op::util::MultiSubGraphOp>(node)) {+ for (const auto& subgraph : subgraph_op->get_functions())+ collect_resident_bytes(*subgraph);+ }++ auto constant = ov::as_type_ptr<ov::op::v0::Constant>(node);+ if (!constant || !visited.insert(constant.get()).second)+ continue;++ const auto role = get_moe_constant_role(constant);+ if (role == MoEConstantRole::NotMoE)+ continue;++ uint64_t constant_resident_bytes = constant->get_byte_size();+ if (offload_ratio > 0 && is_moe_constant_offloadable(constant)) {+ const auto& shape = constant->get_shape();+ if (shape.empty() || shape[0] == 0)+ continue;++ const size_t resident_experts = std::max<size_t>(1, shape[0] * (100 - offload_ratio) / 100);+ const uint64_t bytes_per_expert =+ constant_resident_bytes / shape[0] + (constant_resident_bytes % shape[0] != 0 ? 1 : 0);+ constant_resident_bytes = bytes_per_expert * resident_experts;+ }++ OPENVINO_ASSERT(constant_resident_bytes <= std::numeric_limits<uint64_t>::max() - resident_bytes, "MoE resident weight size overflows uint64_t");+ resident_bytes += constant_resident_bytes;+ }+ };++ collect_resident_bytes(model);+ return has_moe ? resident_bytes : 0;+}++void validate_model_resident_constant_memory(const ov::Model& model, size_t offload_ratio, uint64_t device_memory_bytes) {+ if (offload_ratio == 0 || device_memory_bytes == 0)+ return;++ const uint64_t resident_bytes = get_model_resident_constant_bytes(model, offload_ratio);+ OPENVINO_ASSERT(resident_bytes <= device_memory_bytes,+ "[GPU] Resident model constants require at least ",+ resident_bytes,+ " bytes, exceeding the device global memory size of ",+ device_memory_bytes,+ " bytes. Increase OFFLOAD_RATIO or use a GPU with more memory.");+}+PartialUploadLogState& get_partial_upload_log_state() {static PartialUploadLogState state;return state;@@ -51,13 +184,13 @@ PartialUploadDesc try_prepare_partial_upload(cldnn::engine& engine,const size_t otd_ratio = config.get_offload_ratio();// Only routed expert weights are partially uploaded; shared experts stay fully resident.- // ratio=0 (all resident) or ratio=100 (all on disk, invalid) → no partial upload.- const bool partial_moe_const_upload = otd_ratio > 0 && otd_ratio < 100 && get_moe_constant_role(op) == MoEConstantRole::RoutedExpert;+ // ratio=0 keeps all experts resident; positive ratios enable partial upload.+ const bool partial_moe_const_upload = otd_ratio > 0 && is_moe_constant_offloadable(op);if (!partial_moe_const_upload || const_layout.bytes_count() == 0 || const_shape.empty() || const_shape[0] == 0) {return desc;}- // otd_ratio is the % on disk; GPU-resident experts = total * (100 - ratio) / 100+ // otd_ratio is the % on disk; GPU-resident experts = max(1, total * (100 - ratio) / 100)const size_t resident_expert_num = std::max<size_t>(1, const_shape[0] * (100 - otd_ratio) / 100);desc.enabled = true;diff --git a/src/plugins/intel_gpu/src/plugin/ops/moe_offload_constant.hpp b/src/plugins/intel_gpu/src/plugin/ops/moe_offload_constant.hppindex 29b5811e3b1..d0a017e5b38 100644--- a/src/plugins/intel_gpu/src/plugin/ops/moe_offload_constant.hpp+++ b/src/plugins/intel_gpu/src/plugin/ops/moe_offload_constant.hpp@@ -5,6 +5,7 @@#pragma once#include <atomic>+#include <cstddef>#include <cstdint>#include <memory>#include <string>@@ -14,12 +15,25 @@#include "intel_gpu/runtime/engine.hpp"#include "intel_gpu/runtime/execution_config.hpp"#include "intel_gpu/runtime/memory.hpp"+#include "openvino/core/model.hpp"#include "openvino/op/constant.hpp"namespace ov::intel_gpu {/// Classifies a Constant's role relative to the MoE fused op.-enum class MoEConstantRole { NotMoE, RoutedExpert, SharedExpert };+enum class MoEConstantRole {+ NotMoE, // Non-MoE constant (e.g. LayerNorm, embeddings, scalars)+ NotOffloadableMoE, // MoE constant whose architecture currently lacks OTD support (e.g. GEMM2_BIAS_SWIGLU_CLAMP)+ NotOffloadableRoutedExpert, // Routed expert constant that cannot be pruned because it is shared with non-routed consumers+ OffloadableRoutedExpert, // Pure routed expert constant eligible for partial upload and offload discounting (GEMM3_SWIGLU)+ AlwaysResidentSharedExpert // Shared expert constant that must remain fully resident (GEMM3_SWIGLU shared inputs)+};++/// Checks if an op is an OTD-capable MOE node (MOECompressed with GEMM3_SWIGLU).+bool is_otd_capable_moe(const ov::Node* node);++bool is_moe_otd_eligible(const ov::Node* node);+bool is_moe_constant_offloadable(const std::shared_ptr<ov::op::v0::Constant>& op);/// Determines the role of a Constant feeding into MOECompressed.MoEConstantRole get_moe_constant_role(const std::shared_ptr<ov::op::v0::Constant>& op);@@ -33,6 +47,9 @@ struct PartialUploadDesc {bool is_moe_related_constant(const std::shared_ptr<ov::op::v0::Constant>& op);+uint64_t get_model_resident_constant_bytes(const ov::Model& model, size_t offload_ratio);+void validate_model_resident_constant_memory(const ov::Model& model, size_t offload_ratio, uint64_t device_memory_bytes);+class PartialUploadLogState {public:static constexpr size_t max_detailed_logs = 3;diff --git a/src/plugins/intel_gpu/src/plugin/plugin.cpp b/src/plugins/intel_gpu/src/plugin/plugin.cppindex b308bf83694..29870a8d087 100644--- a/src/plugins/intel_gpu/src/plugin/plugin.cpp+++ b/src/plugins/intel_gpu/src/plugin/plugin.cpp@@ -22,6 +22,7 @@#include "intel_gpu/graph/serialization/vector_serializer.hpp"#include "intel_gpu/plugin/compiled_model.hpp"#include "intel_gpu/plugin/transformations_pipeline.hpp"+#include "plugin/ops/moe_offload_constant.hpp"#include "intel_gpu/runtime/debug_configuration.hpp"#include "intel_gpu/runtime/device_query.hpp"#include "intel_gpu/runtime/dispatch_probe.hpp"@@ -304,6 +305,13 @@ std::shared_ptr<ov::ICompiledModel> Plugin::compile_model(const std::shared_ptr<auto transformed_model = clone_and_transform_model(model, config, context);config.finalize(context.get(), transformed_model.get());++ if (config.get_offload_ratio() > 0) {+ validate_model_resident_constant_memory(*transformed_model,+ config.get_offload_ratio(),+ context->get_device().get_info().max_global_mem_size);+ }+{OV_ITT_SCOPED_TASK(itt::domains::intel_gpu_plugin, "Plugin::compile_model::CreateCompiledModel");return std::make_shared<CompiledModel>(transformed_model, shared_from_this(), context, config, weight_sharing_context);@@ -330,6 +338,13 @@ std::shared_ptr<ov::ICompiledModel> Plugin::compile_model(const std::shared_ptr<config.finalize(context_impl.get(), transformed_model.get());+ if (config.get_offload_ratio() > 0) {+ validate_model_resident_constant_memory(*transformed_model,+ config.get_offload_ratio(),+ context_impl->get_device().get_info().max_global_mem_size);+ }++return std::make_shared<CompiledModel>(transformed_model, shared_from_this(), context_impl, config, weight_sharing_context);}diff --git a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cppindex 3b5a80aa703..02341478465 100644--- a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp+++ b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp@@ -735,7 +735,7 @@ void TransformationsPipeline::apply(std::shared_ptr<ov::Model> func) {// WeightlessCacheAttribute. Unlike WCA (is_copyable()=false), plain ov::Any values// are automatically propagated by copy_runtime_info through all transformations.// This allows moe.cpp to find bin offsets even when WCA is lost.- if (config.get_offload_ratio() > 0 && config.get_offload_ratio() < 100) {+ if (config.get_offload_ratio() > 0 && config.get_offload_ratio() <= 100) {// First stamp WCA on constants with mmap descriptors but no WCA yetfor (const auto& op : func->get_ops()) {auto const_node = ov::as_type_ptr<ov::op::v0::Constant>(op);diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/moe_3gemm_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/moe_3gemm_gpu_test.cppindex 8456c36d530..7975dc90e00 100644--- a/src/plugins/intel_gpu/tests/unit/test_cases/moe_3gemm_gpu_test.cpp+++ b/src/plugins/intel_gpu/tests/unit/test_cases/moe_3gemm_gpu_test.cpp@@ -4,6 +4,8 @@#include <algorithm>#include <cmath>+#include <filesystem>+#include <fstream>#include <intel_gpu/primitives/data.hpp>#include <intel_gpu/primitives/fully_connected.hpp>#include <intel_gpu/primitives/moe_3gemm_fused_compressed.hpp>@@ -18,10 +20,171 @@#include "../../common/random_generator.hpp"#include "../test_utils/test_utils.h"#include "moe_3gemm_test_data.h"+#include "common_test_utils/common_utils.hpp"using namespace cldnn;using namespace ::tests;+class moe_3gemm_offload_fallback : public ::testing::TestWithParam<std::tuple<size_t, bool, bool>> {+protected:+ std::filesystem::path weights_path;++ void TearDown() override {+ if (!weights_path.empty()) {+ std::error_code error;+ std::filesystem::remove(weights_path, error);+ EXPECT_FALSE(error) << error.message();+ }+ }+};++TEST_P(moe_3gemm_offload_fallback, one_slot_matches_reference) {+ const auto [tokens, is_u4, shared] = GetParam();+ auto& engine = get_test_engine();+ if (!engine.get_device_info().supports_immad) {+ GTEST_SKIP() << "No immad support";+ }+ auto& stream = get_test_stream();+ constexpr size_t hidden = 128;+ constexpr size_t experts = 4;+ constexpr size_t top_k = 2;+ const auto weight_type = is_u4 ? data_types::u4 : data_types::u8;+ topology topo;+ auto input = engine.allocate_memory(layout{ov::Shape{1, tokens, hidden}, data_types::f16, format::bfyx});+ auto routing = engine.allocate_memory(layout{ov::Shape{1, tokens, top_k}, data_types::f16, format::bfyx});+ auto indices = engine.allocate_memory(layout{ov::Shape{1, tokens, top_k}, data_types::i32, format::bfyx});+ topo.add(input_layout("hidden", input->get_layout()));+ topo.add(input_layout("routing", routing->get_layout()));+ topo.add(input_layout("indices", indices->get_layout()));+ std::vector<input_info> inputs{input_info("hidden"), input_info("routing"), input_info("indices")};++ weights_path = std::filesystem::temp_directory_path() / (ov::test::utils::generateTestFilePrefix() + ".bin");+ std::ofstream file(weights_path, std::ios::binary);+ ASSERT_TRUE(file.is_open());+ std::vector<size_t> offsets(9);+ size_t file_offset = 0;+ for (size_t part = 0; part < (shared ? 2U : 1U); ++part) {+ const bool routed = part == 0;+ const size_t count = routed ? experts : 1;+ for (size_t projection = 0; projection < 3; ++projection) {+ for (size_t kind = 0; kind < 3; ++kind) {+ const auto type = kind == 1 ? data_types::f16 : weight_type;+ const ov::Shape shape = kind == 0 ? ov::Shape{count, hidden, 1, hidden}+ : ov::Shape{count, hidden, 1};+ const layout full_layout{shape, type, format::bfyx};+ auto full = engine.allocate_memory(full_layout);+ if (kind == 1) {+ set_values(full, std::vector<ov::float16>(count * hidden, ov::float16(0.01f)));+ } else {+ std::vector<uint8_t> bytes(full_layout.bytes_count(), 0);+ const size_t expert_bytes = bytes.size() / count;+ if (kind == 0) {+ for (size_t e = 0; e < count; ++e) {+ const uint8_t value = static_cast<uint8_t>(routed ? e + projection + 1 : 2);+ std::fill_n(bytes.begin() + e * expert_bytes,+ expert_bytes,+ is_u4 ? static_cast<uint8_t>(value | (value << 4)) : value);+ }+ }+ set_values(full, bytes);+ }+ stream.finish();+ const std::string name = "weight_" + std::to_string(part) + "_" ++ std::to_string(projection) + "_" + std::to_string(kind);+ if (routed) {+ offsets[kind * 3 + projection] = file_offset;+ mem_lock<uint8_t, mem_lock_type::read> bytes(full, stream);+ file.write(reinterpret_cast<const char*>(bytes.data()), full_layout.bytes_count());+ ASSERT_TRUE(file.good());+ file_offset += full_layout.bytes_count();+ auto slot_shape = shape;+ slot_shape[0] = 1;+ auto slot = engine.allocate_memory(layout{slot_shape, type, format::bfyx},+ engine.get_preferred_memory_allocation_type(),+ false);+ ASSERT_EQ(slot->size(), full_layout.bytes_count() / experts);+ topo.add(data(name, engine.reinterpret_buffer(*slot, full_layout), true));+ } else {+ topo.add(data(name, full));+ }+ inputs.emplace_back(name);+ }+ }+ }+ file.close();+ ASSERT_FALSE(file.fail());+ if (shared) {+ auto scalar = engine.allocate_memory(layout{ov::PartialShape{1, hidden}, data_types::f16, format::bfyx});+ set_values(scalar, std::vector<ov::float16>(hidden, ov::float16(0)));+ topo.add(data("shared_scalar", scalar));+ inputs.emplace_back("shared_scalar");+ }++ MOECompressed::Config config{};+ config.hidden_size = hidden;+ config.inter_size = hidden;+ config.num_expert = experts;+ config.top_k = top_k;+ config.group_size = hidden;+ config.num_shared_expert = shared ? 1 : 0;+ config.has_zp = true;+ config.out_type = data_types::f16;+ topo.add(moe_3gemm_fused_compressed("moe", inputs, config, offsets, weights_path, 1));+ auto net_config = get_test_default_config(engine);+ net_config.set_property(ov::intel_gpu::allow_new_shape_infer(true));+ network net(engine, topo, net_config);+ net.set_input_data("hidden", input);+ net.set_input_data("routing", routing);+ net.set_input_data("indices", indices);++ const float scale = static_cast<float>(ov::float16(0.01f));+ for (size_t iteration = 0; iteration < 3; ++iteration) {+ SCOPED_TRACE(iteration);+ const int32_t first_expert = iteration == 1 ? 2 : 0;+ const ov::float16 x(0.1f * static_cast<float>(iteration + 1));+ set_values(input, std::vector<ov::float16>(tokens * hidden, x));+ std::vector<int32_t> ids(tokens * top_k);+ std::vector<ov::float16> routes(tokens * top_k);+ for (size_t t = 0; t < tokens; ++t) {+ ids[t * top_k] = first_expert;+ ids[t * top_k + 1] = first_expert + 1;+ routes[t * top_k] = ov::float16(0.25f);+ routes[t * top_k + 1] = ov::float16(0.75f);+ }+ set_values(indices, ids);+ set_values(routing, routes);+ stream.finish();+ const auto outputs = net.execute();+ auto output = outputs.at("moe").get_memory();+ mem_lock<ov::float16, mem_lock_type::read> result(output, stream);+ auto expert_output = [&](float gate_weight, float up_weight, float down_weight) {+ const float gate = hidden * static_cast<float>(x) * gate_weight * scale;+ const float up = hidden * static_cast<float>(x) * up_weight * scale;+ return hidden * (gate / (1.0f + std::exp(-gate))) * up * down_weight * scale;+ };+ const float e = static_cast<float>(first_expert);+ float expected = 0.25f * expert_output(e + 1, e + 2, e + 3) ++ 0.75f * expert_output(e + 2, e + 3, e + 4);+ if (shared) {+ expected += 0.5f * expert_output(2, 2, 2);+ }+ ASSERT_EQ(output->get_layout().count(), tokens * hidden);+ for (size_t i = 0; i < tokens * hidden; ++i) {+ ASSERT_NEAR(static_cast<float>(result[i]), expected, std::abs(expected) * 0.01f + 0.002f) << i;+ }+ mem_lock<ov::float16, mem_lock_type::read> routing_result(routing, stream);+ for (size_t i = 0; i < routes.size(); ++i) {+ EXPECT_EQ(routing_result[i], routes[i]);+ }+ }+}++INSTANTIATE_TEST_SUITE_P(smoke,+ moe_3gemm_offload_fallback,+ ::testing::Combine(::testing::Values(size_t{1}, size_t{2}, size_t{16}, size_t{33}),+ ::testing::Bool(),+ ::testing::Bool()));+struct Moe3GemmConfig {size_t batch_size;size_t seq_len;diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/moe_offload_constant_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/moe_offload_constant_test.cppindex 37149385d17..ec082cd6b20 100644--- a/src/plugins/intel_gpu/tests/unit/test_cases/moe_offload_constant_test.cpp+++ b/src/plugins/intel_gpu/tests/unit/test_cases/moe_offload_constant_test.cpp@@ -7,6 +7,7 @@#include "test_utils.h"#include "openvino/op/constant.hpp"#include "openvino/op/parameter.hpp"+#include "openvino/op/relu.hpp"#include "intel_gpu/runtime/internal_properties.hpp"#include "ov_ops/moe_compressed.hpp"#include "plugin/ops/moe_offload_constant.hpp"@@ -21,12 +22,18 @@ using namespace ov::intel_gpu;struct MoETestGraph {std::shared_ptr<ov::op::internal::MOECompressed> moe_node;std::vector<std::shared_ptr<ov::op::v0::Constant>> constants; // indices 3..21+ ov::ParameterVector parameters;- static MoETestGraph build(size_t num_experts = 4, size_t hidden_size = 128, size_t inter_size = 256, size_t group_size = 128) {+ static MoETestGraph build(size_t num_experts = 4,+ size_t hidden_size = 128,+ size_t inter_size = 256,+ size_t group_size = 128,+ ov::op::internal::MOE::Expert_type expert_type = ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU) {MoETestGraph g;const size_t top_k = 2;ov::op::internal::MOECompressed::Config config{};+ config.expert_type = expert_type;config.hidden_size = hidden_size;config.inter_size = inter_size;config.num_expert = num_experts;@@ -44,14 +51,17 @@ struct MoETestGraph {// 0: hidden_states [1, 1, hidden_size]auto hidden = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 1, hidden_size});+ g.parameters.push_back(hidden);inputs.push_back(hidden->output(0));// 1: routing_weights [1, 1, top_k]auto routing = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::Shape{1, 1, top_k});+ g.parameters.push_back(routing);inputs.push_back(routing->output(0));// 2: topk_indices [1, 1, top_k]auto topk_idx = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{1, 1, top_k});+ g.parameters.push_back(topk_idx);inputs.push_back(topk_idx->output(0));// Helper to create a constant with given shape and type@@ -93,27 +103,59 @@ struct MoETestGraph {}};-// Test that routed expert constants (inputs 3-11) are classified as RoutedExpert+TEST(moe_offload_constant, validates_resident_weight_budget) {+ auto g = MoETestGraph::build();+ auto result = std::make_shared<ov::op::v0::Result>(g.moe_node);+ ov::Model model(ov::ResultVector{result}, g.parameters);+ const uint64_t resident_bytes = get_model_resident_constant_bytes(model, 1);++ EXPECT_GT(resident_bytes, 0U);+ EXPECT_NO_THROW(validate_model_resident_constant_memory(model, 1, resident_bytes));+ EXPECT_THROW(validate_model_resident_constant_memory(model, 1, resident_bytes - 1), ov::Exception);+ EXPECT_NO_THROW(validate_model_resident_constant_memory(model, 0, 1));+ EXPECT_NO_THROW(validate_model_resident_constant_memory(model, 0, 0));+}++TEST(moe_offload_constant, offload_ratio_reduces_resident_weight_estimate) {+ auto g = MoETestGraph::build();+ auto result = std::make_shared<ov::op::v0::Result>(g.moe_node);+ ov::Model model(ov::ResultVector{result}, g.parameters);++ EXPECT_LT(get_model_resident_constant_bytes(model, 75), get_model_resident_constant_bytes(model, 0));+ EXPECT_LE(get_model_resident_constant_bytes(model, 100), get_model_resident_constant_bytes(model, 75));+ EXPECT_LT(get_model_resident_constant_bytes(model, 100), get_model_resident_constant_bytes(model, 0));+}++TEST(moe_offload_constant, non_moe_model_is_not_subject_to_resident_constant_check) {+ auto constant = std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{4, 128}, 0);+ auto result = std::make_shared<ov::op::v0::Result>(constant);+ ov::Model model(ov::ResultVector{result}, ov::ParameterVector{});++ EXPECT_EQ(get_model_resident_constant_bytes(model, 0), 0U);+ EXPECT_NO_THROW(validate_model_resident_constant_memory(model, 0, 1));+}++// Test that routed expert constants (inputs 3-11) are classified as OffloadableRoutedExpertTEST(moe_offload_constant, routed_expert_classification) {auto g = MoETestGraph::build();// Inputs 3..11 map to g.constants[0..8] (routed experts)for (size_t i = 0; i < 9; i++) {auto role = get_moe_constant_role(g.constants[i]);- EXPECT_EQ(role, MoEConstantRole::RoutedExpert)- << "Constant at MOECompressed input " << (i + 3) << " should be RoutedExpert";+ EXPECT_EQ(role, MoEConstantRole::OffloadableRoutedExpert)+ << "Constant at MOECompressed input " << (i + 3) << " should be OffloadableRoutedExpert";}}-// Test that shared expert constants (inputs 12-21) are classified as SharedExpert+// Test that shared expert constants (inputs 12-21) are classified as AlwaysResidentSharedExpertTEST(moe_offload_constant, shared_expert_classification) {auto g = MoETestGraph::build();// Inputs 12..21 map to g.constants[9..18] (shared experts)for (size_t i = 9; i < g.constants.size(); i++) {auto role = get_moe_constant_role(g.constants[i]);- EXPECT_EQ(role, MoEConstantRole::SharedExpert)- << "Constant at MOECompressed input " << (i + 3) << " should be SharedExpert";+ EXPECT_EQ(role, MoEConstantRole::AlwaysResidentSharedExpert)+ << "Constant at MOECompressed input " << (i + 3) << " should be AlwaysResidentSharedExpert";}}@@ -137,17 +179,17 @@ TEST(moe_offload_constant, is_moe_related_covers_both) {EXPECT_FALSE(is_moe_related_constant(unconnected));}-// KEY TEST: Shared expert constants must NOT be classified as RoutedExpert+// KEY TEST: Shared expert constants must NOT be classified as OffloadableRoutedExpert// This is the regression test for the bug where shared constants were wrongly cropped.TEST(moe_offload_constant, shared_expert_not_cropped_by_partial_upload) {auto g = MoETestGraph::build();- // Shared expert constants (inputs 12-21) must NEVER be RoutedExpert+ // Shared expert constants (inputs 12-21) must NEVER be OffloadableRoutedExpertfor (size_t i = 9; i < g.constants.size(); i++) {auto role = get_moe_constant_role(g.constants[i]);- EXPECT_NE(role, MoEConstantRole::RoutedExpert)+ EXPECT_NE(role, MoEConstantRole::OffloadableRoutedExpert)<< "Shared expert constant at input " << (i + 3)- << " must NOT be classified as RoutedExpert (would be wrongly cropped by partial upload)";+ << " must NOT be classified as OffloadableRoutedExpert (would be wrongly cropped by partial upload)";}}@@ -174,3 +216,125 @@ TEST(moe_offload_constant, partial_upload_uses_preferred_allocation_type) {EXPECT_LT(desc.upload_bytes, layout.bytes_count());EXPECT_EQ(desc.memory->get_allocation_type(), engine.get_preferred_memory_allocation_type());}++TEST(moe_offload_constant, gemm2_moe_is_not_otd_capable_and_not_discounted) {+ auto gemm3_graph = MoETestGraph::build(4, 128, 256, 128, ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU);+ EXPECT_TRUE(is_otd_capable_moe(gemm3_graph.moe_node.get()));++ auto gemm2_graph = MoETestGraph::build(4, 128, 256, 128, ov::op::internal::MOE::Expert_type::GEMM2_BIAS_SWIGLU_CLAMP);+ EXPECT_FALSE(is_otd_capable_moe(gemm2_graph.moe_node.get()));++ // For GEMM2, constants must be classified as NotOffloadableMoE, yet still recognized as MoE related+ for (auto& c : gemm2_graph.constants) {+ EXPECT_EQ(get_moe_constant_role(c), MoEConstantRole::NotOffloadableMoE);+ EXPECT_TRUE(is_moe_related_constant(c));+ }++ // Model with only GEMM2 MOE nodes should not trigger the OTD resident check (returns 0)+ auto result = std::make_shared<ov::op::v0::Result>(gemm2_graph.moe_node);+ ov::Model model(ov::ResultVector{result}, gemm2_graph.parameters);+ EXPECT_EQ(get_model_resident_constant_bytes(model, 50), 0U);++ // Partial upload must be disabled for GEMM2 constants+ auto& engine = tests::get_test_engine();+ auto config = tests::get_test_default_config(engine);+ config.set_property(ov::intel_gpu::offload_ratio(50));+ auto constant = gemm2_graph.constants[0];+ const auto shape = constant->get_output_shape(0);+ const auto layout = cldnn::layout(shape,+ cldnn::element_type_to_data_type(constant->get_output_element_type(0)),+ cldnn::format::get_default_format(shape.size()));+ const auto desc = try_prepare_partial_upload(engine,+ config,+ constant,+ shape,+ layout.data_type,+ layout.format,+ layout);+ EXPECT_FALSE(desc.enabled);+}++TEST(moe_offload_constant, shared_routed_constant_is_not_offloadable) {+ auto g = MoETestGraph::build();+ auto routed_const = g.constants[0];++ // Simulate sharing: attach another non-MoE consumer to the routed constant+ auto dummy_relu = std::make_shared<ov::op::v0::Relu>(routed_const);+ EXPECT_EQ(get_moe_constant_role(routed_const), MoEConstantRole::NotOffloadableRoutedExpert);+ EXPECT_TRUE(is_moe_related_constant(routed_const));++ // Must not be partially uploaded+ auto& engine = tests::get_test_engine();+ auto config = tests::get_test_default_config(engine);+ config.set_property(ov::intel_gpu::offload_ratio(50));+ const auto shape = routed_const->get_output_shape(0);+ const auto layout = cldnn::layout(shape,+ cldnn::element_type_to_data_type(routed_const->get_output_element_type(0)),+ cldnn::format::get_default_format(shape.size()));+ const auto desc = try_prepare_partial_upload(engine,+ config,+ routed_const,+ shape,+ layout.data_type,+ layout.format,+ layout);+ EXPECT_FALSE(desc.enabled);+}++TEST(moe_offload_constant, resident_fallback_keeps_sibling_constants_fully_resident) {+ auto& engine = tests::get_test_engine();+ auto config = tests::get_test_default_config(engine);+ config.set_property(ov::intel_gpu::offload_ratio(75));++ for (bool tensor_weight : {false, true}) {+ SCOPED_TRACE(tensor_weight);+ auto graph = MoETestGraph::build();+ ov::ResultVector results{std::make_shared<ov::op::v0::Result>(graph.moe_node)};+ if (tensor_weight) {+ auto weight = std::make_shared<ov::op::v0::Parameter>(graph.constants[0]->get_element_type(), graph.constants[0]->get_shape());+ graph.moe_node->input(3).replace_source_output(weight);+ graph.parameters.push_back(weight);+ } else {+ auto consumer = std::make_shared<ov::op::v0::Relu>(graph.constants[0]);+ results.push_back(std::make_shared<ov::op::v0::Result>(consumer));+ }+ ov::Model model(results, graph.parameters);+ EXPECT_FALSE(is_moe_otd_eligible(graph.moe_node.get()));+ EXPECT_EQ(get_model_resident_constant_bytes(model, 75), get_model_resident_constant_bytes(model, 0));+ EXPECT_EQ(get_model_resident_constant_bytes(model, 100), get_model_resident_constant_bytes(model, 0));++ for (size_t index = 1; index < 9; ++index) {+ const auto& constant = graph.constants[index];+ EXPECT_FALSE(is_moe_constant_offloadable(constant));+ const auto shape = constant->get_shape();+ const auto layout =+ cldnn::layout(shape, cldnn::element_type_to_data_type(constant->get_element_type()), cldnn::format::get_default_format(shape.size()));+ const auto desc = try_prepare_partial_upload(engine, config, constant, shape, layout.data_type, layout.format, layout);+ EXPECT_FALSE(desc.enabled);+ }+ }+}++TEST(moe_offload_constant, shared_routed_weights_propagate_resident_fallback) {+ auto first = MoETestGraph::build();+ auto second = MoETestGraph::build();+ second.moe_node->input(3).replace_source_output(first.constants[0]);++ EXPECT_TRUE(is_moe_otd_eligible(first.moe_node.get()));+ EXPECT_TRUE(is_moe_otd_eligible(second.moe_node.get()));+ EXPECT_TRUE(is_moe_constant_offloadable(first.constants[0]));++ auto weight = std::make_shared<ov::op::v0::Parameter>(second.constants[3]->get_element_type(), second.constants[3]->get_shape());+ second.moe_node->input(6).replace_source_output(weight);+ second.parameters.push_back(weight);+ auto parameters = first.parameters;+ parameters.insert(parameters.end(), second.parameters.begin(), second.parameters.end());+ ov::Model model(ov::ResultVector{std::make_shared<ov::op::v0::Result>(first.moe_node), std::make_shared<ov::op::v0::Result>(second.moe_node)}, parameters);++ EXPECT_FALSE(is_moe_otd_eligible(first.moe_node.get()));+ EXPECT_FALSE(is_moe_otd_eligible(second.moe_node.get()));+ EXPECT_FALSE(is_moe_constant_offloadable(first.constants[0]));+ EXPECT_FALSE(is_moe_constant_offloadable(first.constants[1]));+ EXPECT_FALSE(is_moe_constant_offloadable(second.constants[1]));+ EXPECT_EQ(get_model_resident_constant_bytes(model, 75), get_model_resident_constant_bytes(model, 0));+}diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/moe_offload_property_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/moe_offload_property_test.cppindex 73a623c2e50..e09820d04f8 100644--- a/src/plugins/intel_gpu/tests/unit/test_cases/moe_offload_property_test.cpp+++ b/src/plugins/intel_gpu/tests/unit/test_cases/moe_offload_property_test.cpp@@ -36,6 +36,7 @@ TEST(moe_offload_property_test, set_and_get_various_values) {config.set_property(ov::intel_gpu::offload_ratio(100));ASSERT_EQ(config.get_offload_ratio(), 100U);+ EXPECT_ANY_THROW(config.set_property(ov::intel_gpu::offload_ratio(101)));}TEST(moe_offload_property_test, set_back_to_zero_disables) {