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] Offload MoE expert weights to disk (#36202)
Zaixing Wang36bb72ce88e6
diff --git a/src/common/transformations/src/transformations/op_conversions/convert_fc_to_compressed.cpp b/src/common/transformations/src/transformations/op_conversions/convert_fc_to_compressed.cppindex 096b61bd952..584a748b6b1 100644--- a/src/common/transformations/src/transformations/op_conversions/convert_fc_to_compressed.cpp+++ b/src/common/transformations/src/transformations/op_conversions/convert_fc_to_compressed.cpp@@ -68,7 +68,13 @@ ConvertFullyConnectedToFullyConnectedCompressed::process_compressed_weights(new_OC = OC;new_IC = n_groups * group_size;}- return std::make_shared<v0::Constant>(*constant, new_shape);+ auto new_constant = std::make_shared<v0::Constant>(*constant, new_shape);+ // Propagate plain "otd_bin_offset" entry (used by GPU OTD when WCA is lost)+ auto otd_it = constant->get_rt_info().find("otd_bin_offset");+ if (otd_it != constant->get_rt_info().end()) {+ new_constant->get_rt_info()["otd_bin_offset"] = otd_it->second;+ }+ return new_constant;};auto convert_u4const_to_u8 = [convert_u4zp_to_u8](std::shared_ptr<ov::Node> node) -> std::shared_ptr<ov::Node> {diff --git a/src/inference/include/openvino/runtime/intel_gpu/properties.hpp b/src/inference/include/openvino/runtime/intel_gpu/properties.hppindex 3ac92e47ef6..e947ca59926 100644--- a/src/inference/include/openvino/runtime/intel_gpu/properties.hpp+++ b/src/inference/include/openvino/runtime/intel_gpu/properties.hpp@@ -169,6 +169,16 @@ static constexpr Property<bool> enable_large_allocations{"GPU_ENABLE_LARGE_ALLOC} // namespace hint+/**+ * @brief Percentage (0–100) of model weights to offload to disk.+ * When set to 0 (default), all weights are resident on GPU. A value of N means+ * N% of eligible weights are streamed from host memory on demand via an LRU cache,+ * reducing GPU memory usage at the cost of inference latency.+ * Currently supported for MoE expert weights only.+ * @ingroup ov_runtime_ocl_gpu_prop_cpp_api+ */+static constexpr Property<size_t, PropertyMutability::RW> offload_ratio{"OFFLOAD_RATIO"};+/*** @brief These keys instruct the GPU plugin to use surface/buffer memory type.*/diff --git a/src/plugins/intel_gpu/include/intel_gpu/plugin/program_builder.hpp b/src/plugins/intel_gpu/include/intel_gpu/plugin/program_builder.hppindex 02848734d88..393ee0ded69 100644--- a/src/plugins/intel_gpu/include/intel_gpu/plugin/program_builder.hpp+++ b/src/plugins/intel_gpu/include/intel_gpu/plugin/program_builder.hpp@@ -139,10 +139,11 @@ public:bool use_new_shape_infer() const { return m_config.get_allow_new_shape_infer(); }bool is_inner_program() const { return m_is_inner_program; }- bool is_query_mode() { return queryMode; }+ bool is_query_mode() const { return queryMode; }std::shared_ptr<ov::threading::IStreamsExecutor> get_task_executor() const { return m_task_executor; }std::shared_ptr<cldnn::ICompilationContext> get_compilation_context() const { return m_compilation_context; }+ std::shared_ptr<ov::Model> get_model() const { return m_model; }private:static factories_map_t factories_map;diff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/data.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/data.hppindex b610721e888..c2f2ca4af99 100644--- a/src/plugins/intel_gpu/include/intel_gpu/primitives/data.hpp+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/data.hpp@@ -347,7 +347,8 @@ struct data : public primitive_base<data> {/// @param id This primitive id./// @param mem @ref memory object which contains data./// @note If memory is attached by memory::attach(), the attached buffer should be valid till network build.- data(const primitive_id& id, memory::ptr mem) : primitive_base(id, {}), mem(std::move(mem)) {+ data(const primitive_id& id, memory::ptr mem, bool skip_device_transfer = false)+ : primitive_base(id, {}), mem(std::move(mem)), _skip_device_transfer(skip_device_transfer) {cache_info = std::make_shared<weightless_cache_manager>();}@@ -364,6 +365,14 @@ struct data : public primitive_base<data> {/// @note If memory is attached by memory::attach(), the attached buffer should be valid till network build.memory::ptr mem;+ /// @brief Whether transfer_memory_to_device skips this node (e.g. OTD partial upload).+ bool skip_device_transfer() const { return _skip_device_transfer; }++private:+ bool _skip_device_transfer = false;++public:+std::shared_ptr<weightless_cache_manager> cache_info;size_t hash() const override {diff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_3gemm_fused_compressed.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_3gemm_fused_compressed.hppindex 5caedd8c255..56b6cbfd982 100644--- a/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_3gemm_fused_compressed.hpp+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/moe_3gemm_fused_compressed.hpp@@ -3,20 +3,84 @@//#pragma once+#include <filesystem>#include <vector>+#include <string>#include "ov_ops/moe_compressed.hpp"#include "intel_gpu/runtime/engine.hpp"+#include "intel_gpu/runtime/memory.hpp"#include "primitive.hpp"namespace cldnn {using MOECompressed = ov::op::internal::MOECompressed;+struct moe_weights {+ cldnn::memory::ptr gate_w = nullptr;+ cldnn::memory::ptr gate_s = nullptr;+ cldnn::memory::ptr gate_z = nullptr;+ cldnn::memory::ptr up_w = nullptr;+ cldnn::memory::ptr up_s = nullptr;+ cldnn::memory::ptr up_z = nullptr;+ cldnn::memory::ptr down_w = nullptr;+ cldnn::memory::ptr down_s = nullptr;+ cldnn::memory::ptr down_z = nullptr;+};++/// @brief Lightweight, serializable descriptor for the offload-to-disk (OTD) weight strategy.+/// @details Consolidates the OTD plumbing so the primitive carries a single cohesive field+/// instead of loose members. Empty/zero values mean OTD is disabled (fully resident). This is+/// the only OTD state that participates in blob-cache serialization; the runtime+/// IExpertWeightProvider is rebuilt from it on the impl side.+struct moe_otd_descriptor {+ std::vector<size_t> weight_bin_offsets;+ std::filesystem::path weights_path;+ size_t lru_expert_num = 0;++ bool operator==(const moe_otd_descriptor& rhs) const {+ return weight_bin_offsets == rhs.weight_bin_offsets && weights_path == rhs.weights_path &&+ lru_expert_num == rhs.lru_expert_num;+ }++ void save(BinaryOutputBuffer& ob) const {+ ob << weight_bin_offsets;+ ob << weights_path.string();+ ob << lru_expert_num;+ }++ void load(BinaryInputBuffer& ib) {+ ib >> weight_bin_offsets;+ std::string path_str;+ ib >> path_str;+ weights_path = path_str;+ ib >> lru_expert_num;+ }+};+/// @brief moe compressed primitive/// @details Performs moe compressedstruct moe_3gemm_fused_compressed : public primitive_base<moe_3gemm_fused_compressed> {CLDNN_DECLARE_PRIMITIVE(moe_3gemm_fused_compressed)+ static constexpr size_t serialized_weight_offset_count = 9;++ enum class input_index : size_t {+ hidden_states = 0,+ topk_weights,+ topk_indices,+ weight_0,+ scale_0,+ zp_0,+ weight_1,+ scale_1,+ zp_1,+ weight_2,+ scale_2,+ zp_2,+ count+ };+ static constexpr size_t input_count = static_cast<size_t>(input_index::count);+moe_3gemm_fused_compressed() : primitive_base("", {}) {}// @brief Constructs moe primitive / layer.@@ -67,11 +131,18 @@ struct moe_3gemm_fused_compressed : public primitive_base<moe_3gemm_fused_compre// 21: shared_gate_gate_weight - shared expert gate weight for gating,// shape [hidden_size]//- moe_3gemm_fused_compressed(const primitive_id& id, const std::vector<input_info>& inputs, const MOECompressed::Config& config)+ moe_3gemm_fused_compressed(const primitive_id& id,+ const std::vector<input_info>& inputs,+ const MOECompressed::Config& config,+ const std::vector<size_t>& weight_bin_offsets = {},+ const std::filesystem::path& weights_path = {},+ size_t lru_expert_num = 0): primitive_base(id, inputs, 1, {optional_data_type()}),- _config(config) {}+ _config(config),+ _otd{weight_bin_offsets, weights_path, lru_expert_num} {}MOECompressed::Config _config;+ moe_otd_descriptor _otd;bool operator==(const primitive& rhs) const override {if (!compare_common_params(rhs))@@ -79,17 +150,19 @@ struct moe_3gemm_fused_compressed : public primitive_base<moe_3gemm_fused_compreauto rhs_casted = downcast<const moe_3gemm_fused_compressed>(rhs);- return std::memcmp(&_config, &rhs_casted._config, sizeof(_config)) == 0;+ return std::memcmp(&_config, &rhs_casted._config, sizeof(_config)) == 0 && _otd == rhs_casted._otd;}void save(BinaryOutputBuffer& ob) const override {primitive_base<moe_3gemm_fused_compressed>::save(ob);ob << make_data(&_config, sizeof(_config));+ _otd.save(ob);}void load(BinaryInputBuffer& ib) override {primitive_base<moe_3gemm_fused_compressed>::load(ib);ib >> make_data(&_config, sizeof(_config));+ _otd.load(ib);}};diff --git a/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inl b/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inlindex 3562c00b1af..0cab3a5f5f5 100644--- a/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inl+++ b/src/plugins/intel_gpu/include/intel_gpu/runtime/options.inl@@ -40,6 +40,7 @@ OV_CONFIG_RELEASE_OPTION(ov::hint, model, nullptr, "Shared pointer to the ov::MoOV_CONFIG_RELEASE_OPTION(ov::internal, key_cache_quant_mode, ov::internal::CacheQuantMode::BY_CHANNEL, "AUTO or BY_CHANNEL or BY_TOKEN")OV_CONFIG_RELEASE_OPTION(ov::internal, value_cache_quant_mode, ov::internal::CacheQuantMode::BY_TOKEN, "AUTO or BY_CHANNEL or BY_TOKEN")OV_CONFIG_RELEASE_OPTION(ov::intel_gpu, mem_pool_util_threshold, 0.5, "Minimum utilization threshold (0.0~1.0) for reusable memory in the pool")+OV_CONFIG_RELEASE_OPTION(ov::intel_gpu, offload_ratio, 0, "Percentage (0-100) of model weights to offload to disk. Currently supported for MoE experts only.", [](size_t v) { return v <= 100; })OV_CONFIG_RELEASE_OPTION(ov, enable_weightless, false, "Enable/Disable weightless blob")OV_CONFIG_RELEASE_INTERNAL_OPTION(ov::intel_gpu, shape_predictor_settings, {10, 16 * 1024, 2, 1.1f}, "Preallocation settings")diff --git a/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_quantization.cpp b/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_quantization.cppindex 3ba74a1d6d8..1f0e5ca3d83 100644--- a/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_quantization.cpp+++ b/src/plugins/intel_gpu/src/graph/graph_optimizer/prepare_quantization.cpp@@ -637,6 +637,10 @@ static void optimize_moe_gemm_decompression_parameters(moe_gemm_node& node, progstatic void optimize_moe_3gemm_fused_decompression_parameters(moe_node& node, program& p) {using ov::intel_gpu::ocl::MOE3GemmInputIndex;auto prim = node.get_primitive();+ if (prim->_otd.lru_expert_num > 0) {+ // OTD routed weights are backed by resident-size allocations; reorders would materialize full logical tensors.+ return;+ }const auto& cfg = prim->_config;// Routed-expert scales (gate/up/down); zp at +1 when has_zp.constexpr std::array<size_t, 3> routed_scale_indices{diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/expert_weight_provider.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/expert_weight_provider.hppnew file mode 100644index 00000000000..687cfa5e8ca--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/expert_weight_provider.hpp@@ -0,0 +1,75 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstddef>+#include <cstdint>+#include <optional>+#include <vector>++#include "intel_gpu/primitives/moe_3gemm_fused_compressed.hpp"+#include "intel_gpu/runtime/memory.hpp"+#include "intel_gpu/runtime/stream.hpp"++namespace ov::intel_gpu::ocl::moe {++/// Slot indices produced by a simultaneous acquisition (parallel to the input experts vector).+using ExpertSlotLease = std::vector<size_t>;++/// Lightweight view of routed expert weight/scale/zp triplets for 3 GEMMs.+struct RoutedWeightViews {+ cldnn::memory::ptr weight[3];+ cldnn::memory::ptr scale[3];+ cldnn::memory::ptr zp[3];+};++// Abstraction over "where the weights of a MoE layer's experts live" and how they+// are made addressable on the device for a given set of activated experts.+//+// Two concrete strategies exist today, both expressible through this interface:+// * Fully resident: every expert's weights stay in device memory for the whole+// network lifetime (the ratio=0 path). acquire() is the identity mapping.+// * Offloaded (OTD): expert weights live on disk and are streamed on demand into+// a bounded set of device-resident slots managed by an LRU cache (ratio>0).+// acquire() deduplicates, assigns/streams slots, and returns the slot per expert.+//+// Keeping this behind an interface lets the MoE execution paths be written once,+// independent of the residency strategy, and lets the offload machinery (LRU ++// disk streaming + capacity serialization) be reused by other plugins/back-ends+// by only swapping the device-buffer/stream adapter underneath.+class IExpertWeightProvider {+public:+ virtual ~IExpertWeightProvider() = default;++ // Releases any pinning established by the most recent acquisition.+ virtual void release() = 0;++ // Number of device-resident expert slots. 0 means fully resident (no bound on+ // how many experts can be addressed at once).+ virtual size_t resident_capacity() const = 0;++ // True when expert weights are streamed on demand rather than fully resident.+ virtual bool is_offloaded() const = 0;++ // Fills the RoutedWeightViews with the correct memory pointers for the 3 GEMMs.+ virtual void fill_routed_weight_views(cldnn::moe_weights& weights, RoutedWeightViews& views) = 0;++ // Attempts to simultaneously acquire slots for all requested experts.+ // Returns nullopt if the number of unique experts exceeds resident_capacity()+ // (the caller should fall back to per-expert streaming).+ // The returned lease's slots vector is parallel to the input experts vector.+ virtual std::optional<ExpertSlotLease> try_acquire_simultaneous(const std::vector<uint32_t>& experts, cldnn::stream& stream) = 0;++ // Acquires a single expert slot. Always succeeds (evicts LRU if needed).+ virtual size_t acquire_one(uint32_t expert, cldnn::stream& stream) = 0;++ // Binds device-resident weight buffers. Called once on first execution.+ virtual void bind(cldnn::moe_weights& resident) = 0;++ // Returns true after bind() has been called.+ virtual bool is_bound() const = 0;+};++} // namespace ov::intel_gpu::ocl::moediff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/expert_weight_providers.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/expert_weight_providers.cppnew file mode 100644index 00000000000..165b83715a7--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/expert_weight_providers.cpp@@ -0,0 +1,122 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "expert_weight_providers.hpp"++#include <unordered_map>+#include <utility>++// moe_otd_runtime.hpp is not self-contained: it relies on cldnn graph/runtime+// types (typed_primitive_inst, data_type_traits) being visible at include time.+// primitive_ocl_base.hpp is the established prelude that brings them in.+#include "impls/ocl_v2/primitive_ocl_base.hpp"+#include "moe_otd_runtime.hpp"++namespace ov::intel_gpu::ocl::moe {++std::optional<ExpertSlotLease> ResidentExpertWeightProvider::try_acquire_simultaneous(const std::vector<uint32_t>& experts, cldnn::stream& /*stream*/) {+ // Resident: identity mapping, always succeeds.+ return std::vector<size_t>(experts.begin(), experts.end());+}++size_t ResidentExpertWeightProvider::acquire_one(uint32_t expert, cldnn::stream& /*stream*/) {+ return expert;+}++OffloadExpertWeightProvider::OffloadExpertWeightProvider(size_t capacity,+ const cldnn::MOECompressed::Config& config,+ std::vector<size_t> weight_bin_offsets,+ std::filesystem::path weights_path)+ : _capacity(capacity),+ _config(config),+ _weight_bin_offsets(std::move(weight_bin_offsets)),+ _weights_path(std::move(weights_path)),+ _cache(std::make_shared<LRUCache>(capacity)),+ _weight_reader(_weights_path) {}++void OffloadExpertWeightProvider::bind(cldnn::moe_weights& resident) {+ _resident = &resident;+ _cache->set_initialized();+ _bound = true;+ GPU_DEBUG_TRACE << "MOE OTD bind: resident_slots=" << _capacity << " total_experts=" << _config.num_expert+ << " shared_expert=" << (_config.num_shared_expert > 0 ? 1 : 0) << std::endl;+}++void OffloadExpertWeightProvider::fill_routed_weight_views(cldnn::moe_weights& /*weights*/, RoutedWeightViews& views) {+ // Offloaded: point at the LRU resident buffers (not the original weight inputs).+ OPENVINO_ASSERT(_resident != nullptr, "OffloadExpertWeightProvider: resident buffers not bound");+ views.weight[0] = _resident->gate_w;+ views.scale[0] = _resident->gate_s;+ views.zp[0] = _resident->gate_z;+ views.weight[1] = _resident->up_w;+ views.scale[1] = _resident->up_s;+ views.zp[1] = _resident->up_z;+ views.weight[2] = _resident->down_w;+ views.scale[2] = _resident->down_s;+ views.zp[2] = _resident->down_z;+}++std::optional<ExpertSlotLease> OffloadExpertWeightProvider::try_acquire_simultaneous(const std::vector<uint32_t>& experts, cldnn::stream& stream) {+ // Deduplicate to check capacity+ std::unordered_map<uint32_t, size_t> expert_to_slot;+ expert_to_slot.reserve(experts.size());++ std::vector<size_t> slots(experts.size());+ auto* perf = moe_otd::get_perf_counters();++ for (size_t i = 0; i < experts.size(); i++) {+ const uint32_t expert = experts[i];+ auto it = expert_to_slot.find(expert);+ if (it != expert_to_slot.end()) {+ slots[i] = it->second;+ continue;+ }++ // Check if we would exceed capacity+ if (expert_to_slot.size() >= _capacity) {+ return std::nullopt;+ }++ const auto item = _cache->get_lru_item(expert);+ const auto slot = item.first;++ if (item.second) {+ if (perf)+ perf->gpu_hits.fetch_add(1, std::memory_order_relaxed);+ } else {+ if (perf)+ perf->gpu_misses.fetch_add(1, std::memory_order_relaxed);+ OPENVINO_ASSERT(_resident != nullptr, "OffloadExpertWeightProvider: resident buffers not bound");+ moe_otd::fill_weights_memory(stream, _config, _weight_bin_offsets, _weight_reader, *_resident, {expert}, {slot});+ _cache->set_filled(slot);+ }++ expert_to_slot.emplace(expert, slot);+ slots[i] = slot;+ }++ return slots;+}++size_t OffloadExpertWeightProvider::acquire_one(uint32_t expert, cldnn::stream& stream) {+ auto* perf = moe_otd::get_perf_counters();++ const auto item = _cache->get_lru_item(expert);+ const auto slot = item.first;++ if (item.second) {+ if (perf)+ perf->gpu_hits.fetch_add(1, std::memory_order_relaxed);+ } else {+ if (perf)+ perf->gpu_misses.fetch_add(1, std::memory_order_relaxed);+ OPENVINO_ASSERT(_resident != nullptr, "OffloadExpertWeightProvider: resident buffers not bound");+ moe_otd::fill_weights_memory(stream, _config, _weight_bin_offsets, _weight_reader, *_resident, {expert}, {slot});+ _cache->set_filled(slot);+ }++ return slot;+}++} // namespace ov::intel_gpu::ocl::moediff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/expert_weight_providers.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/expert_weight_providers.hppnew file mode 100644index 00000000000..aaefc3c61a4--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/expert_weight_providers.hpp@@ -0,0 +1,103 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstddef>+#include <cstdint>+#include <filesystem>+#include <memory>+#include <string>+#include <vector>++#include "expert_weight_provider.hpp"+#include "intel_gpu/primitives/moe_3gemm_fused_compressed.hpp"+#include "lru_cache.hpp"+#include "moe_otd_runtime.hpp"++namespace ov::intel_gpu::ocl::moe {++// Identity provider: every expert's weights are already resident in device memory+// for the network lifetime. This is the behaviour of the non-offloaded (ratio=0) path.+class ResidentExpertWeightProvider : public IExpertWeightProvider {+public:+ void release() override {}+ size_t resident_capacity() const override {+ return 0;+ }+ bool is_offloaded() const override {+ return false;+ }+ void bind(cldnn::moe_weights& /*resident*/) override {}+ bool is_bound() const override {+ return true;+ }+ void fill_routed_weight_views(cldnn::moe_weights& weights, RoutedWeightViews& views) override {+ views.weight[0] = weights.gate_w;+ views.scale[0] = weights.gate_s;+ views.zp[0] = weights.gate_z;+ views.weight[1] = weights.up_w;+ views.scale[1] = weights.up_s;+ views.zp[1] = weights.up_z;+ views.weight[2] = weights.down_w;+ views.scale[2] = weights.down_s;+ views.zp[2] = weights.down_z;+ }++ std::optional<ExpertSlotLease> try_acquire_simultaneous(const std::vector<uint32_t>& experts, cldnn::stream& stream) override;+ size_t acquire_one(uint32_t expert, cldnn::stream& stream) override;+};++// Offload (OTD) provider: expert weights live on disk and are streamed on demand+// into a bounded set of device-resident slots managed by an LRU cache.+// The provider deduplicates the requested experts, assigns/streams slots, and+// returns the slot index per requested expert.+//+// The resident device buffers are not owned here; they are bound at runtime via+// bind() because in this back-end they alias the primitive's+// input memory. Loading metadata (config / bin offsets / weights path) is captured+// at construction from graph-build time information.+class OffloadExpertWeightProvider : public IExpertWeightProvider {+public:+ OffloadExpertWeightProvider(size_t capacity,+ const cldnn::MOECompressed::Config& config,+ std::vector<size_t> weight_bin_offsets,+ std::filesystem::path weights_path);++ size_t resident_capacity() const override {+ return _capacity;+ }+ bool is_offloaded() const override {+ return true;+ }++ void release() override {}+ void bind(cldnn::moe_weights& resident) override;+ bool is_bound() const override {+ return _bound;+ }+ void fill_routed_weight_views(cldnn::moe_weights& weights, RoutedWeightViews& views) override;+ std::optional<ExpertSlotLease> try_acquire_simultaneous(const std::vector<uint32_t>& experts, cldnn::stream& stream) override;+ size_t acquire_one(uint32_t expert, cldnn::stream& stream) override;++ LRUCache& cache() {+ return *_cache;+ }++ moe_otd::ParallelWeightReader& weight_reader() {+ return _weight_reader;+ }++private:+ size_t _capacity = 0;+ cldnn::MOECompressed::Config _config{};+ std::vector<size_t> _weight_bin_offsets;+ std::filesystem::path _weights_path;+ std::shared_ptr<LRUCache> _cache;+ moe_otd::ParallelWeightReader _weight_reader;+ cldnn::moe_weights* _resident = nullptr;+ bool _bound = false;+};++} // namespace ov::intel_gpu::ocl::moediff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/lru_cache.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/lru_cache.cppnew file mode 100644index 00000000000..d113397af55--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/lru_cache.cpp@@ -0,0 +1,63 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "lru_cache.hpp"++namespace ov::intel_gpu::ocl::moe {++LRUCache::LRUCache(size_t max_total_experts) : m_max_total_experts(max_total_experts), m_total_experts(0), m_to_filled_lru_expert_no(0) {+ m_filled_list.resize(max_total_experts, false);+}++void LRUCache::move_to_end(std::list<Node>::iterator it) {+ if (std::next(it) == m_list.end())+ return;+ m_list.splice(m_list.end(), m_list, it);+}++void LRUCache::evict_one_unlocked() {+ if (m_list.empty())+ return;++ auto& oldest = m_list.front();++ m_filled_list[oldest.lru_expert_no] = false;+ m_to_filled_lru_expert_no = oldest.lru_expert_no;+ Key key{oldest.expert};+ m_map.erase(key);+ m_list.pop_front();+ --m_total_experts;+}++void LRUCache::evict_one() {+ std::lock_guard<std::mutex> lock(m_mutex);+ evict_one_unlocked();+}++std::pair<size_t, bool> LRUCache::get_lru_item(size_t expert) {+ std::lock_guard<std::mutex> lock(m_mutex);++ Key key{expert};+ auto it = m_map.find(key);+ if (it == m_map.end()) {+ size_t to_filled_no = 0;+ if (m_total_experts >= m_max_total_experts) {+ evict_one_unlocked();+ to_filled_no = m_to_filled_lru_expert_no;+ } else {+ to_filled_no = m_total_experts;+ }+ m_list.push_back(Node{expert, to_filled_no});+ auto new_it = std::prev(m_list.end());+ m_map[key] = new_it;+ ++m_total_experts;+ return {to_filled_no, false};+ } else {+ move_to_end(it->second);+ const bool is_hit = m_filled_list[it->second->lru_expert_no];+ return {it->second->lru_expert_no, is_hit};+ }+}++} // namespace ov::intel_gpu::ocl::moediff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/lru_cache.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/lru_cache.hppnew file mode 100644index 00000000000..554954748d3--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/lru_cache.hpp@@ -0,0 +1,75 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once+#include <list>+#include <mutex>+#include <unordered_map>+#include <utility>+#include <vector>++namespace ov::intel_gpu::ocl::moe {++class LRUCache {+public:+ explicit LRUCache(size_t max_total_experts);++ std::pair<size_t, bool> get_lru_item(size_t expert);++ void evict_one();++ size_t size() const {+ std::lock_guard<std::mutex> lock(m_mutex);+ return m_total_experts;+ }++ void set_filled(size_t lru_expert_no) {+ std::lock_guard<std::mutex> lock(m_mutex);+ if (lru_expert_no >= m_filled_list.size()) {+ return;+ }+ m_filled_list[lru_expert_no] = true;+ }++ bool is_initialized() const {+ return m_initialized;+ }+ void set_initialized() {+ m_initialized = true;+ }++private:+ bool m_initialized = false;+ struct Key {+ size_t expert;+ bool operator==(const Key& other) const noexcept {+ return expert == other.expert;+ }+ };++ struct KeyHash {+ std::size_t operator()(const Key& k) const noexcept {+ return std::hash<size_t>()(k.expert);+ }+ };++ struct Node {+ size_t expert;+ size_t lru_expert_no;+ };++ size_t m_max_total_experts;+ size_t m_total_experts;+ size_t m_to_filled_lru_expert_no;++ std::list<Node> m_list;+ std::vector<bool> m_filled_list;+ std::unordered_map<Key, std::list<Node>::iterator, KeyHash> m_map;+ mutable std::mutex m_mutex;++ void move_to_end(std::list<Node>::iterator it);+ void evict_one_unlocked();+};++} // namespace ov::intel_gpu::ocl::moediff --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 e20f34f9b62..8d4059d629e 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@@ -4,16 +4,33 @@// clang-format off#include "moe_3gemm_gen_micro.hpp"+#include "moe_otd_runtime.hpp"#include "moe_3gemm_swiglu_opt.hpp"+#include "openvino/runtime/shared_buffer.hpp"+#include "lru_cache.hpp"+#include "expert_weight_providers.hpp"// clang-format on+using ov::intel_gpu::ocl::moe::IExpertWeightProvider;+using ov::intel_gpu::ocl::moe::OffloadExpertWeightProvider;+using ov::intel_gpu::ocl::moe::ResidentExpertWeightProvider;+#define DEBUG_MOE_LOG 0#ifdef ENABLE_ONEDNN_FOR_GPU# include <algorithm>+# include <chrono>+# include <cstdint>+# include <fstream># include <initializer_list>+# include <iostream>+# include <limits>+# include <mutex># include <oneapi/dnnl/dnnl.hpp>+# include <oneapi/dnnl/dnnl_ocl.hpp>+# include <sstream># include <string_view>+# include <thread># include <tuple># include <utility>@@ -540,6 +557,12 @@ dnnl::memory convert2dnnl(const memory::ptr& ptr, const std::vector<int64_t>& direturn ptr->get_onednn_memory(dnnl::memory::desc(dnnl::memory::dims(dim), convert_data_type(ptr->get_layout().data_type), tag), offset);}+// Returns the byte count for `element_count` elements of the given layout's data type.+// Handles sub-byte types (u4/i4) that pack two elements per byte.+static int64_t get_bytes_count(int64_t element_count, const cldnn::layout& layout) {+ return static_cast<int64_t>(ov::element::Type(layout.data_type).bitwidth()) * element_count / 8;+}+class moe_3gemm_swiglu_opt_impl : public PrimitiveImplOCL {public:DECLARE_OBJECT_TYPE_SERIALIZATION(ov::intel_gpu::ocl::MoE3GemmSwigluImpl)@@ -618,6 +641,7 @@ public:moe_fusion_weights_base_addr moe_fusion_wei_addr;memory::ptr input_routing_weights;memory::ptr input_router_topk_idx;+ memory::ptr _expert_index_buffer;};std::vector<std::vector<dnnl_weights>> _dnnl_weights;@@ -626,6 +650,292 @@ public:int _shared_intermediate_size;int _gate_up_group_size;int _down_group_size;+ std::shared_ptr<IExpertWeightProvider> _weight_provider;++ // --- OTD helper methods (used when _weight_provider->is_offloaded()) ---++ void set_otd_weight_pointers(typed_primitive_inst<moe_3gemm_fused_compressed>& instance, scratch_buffers& scratch) {+ const auto& w = instance._weights;+ scratch.moe_fusion_wei_addr.weight[0] = w.gate_w;+ scratch.moe_fusion_wei_addr.scale[0] = w.gate_s;+ scratch.moe_fusion_wei_addr.zp[0] = w.gate_z;+ scratch.moe_fusion_wei_addr.weight[1] = w.up_w;+ scratch.moe_fusion_wei_addr.scale[1] = w.up_s;+ scratch.moe_fusion_wei_addr.zp[1] = w.up_z;+ scratch.moe_fusion_wei_addr.weight[2] = w.down_w;+ scratch.moe_fusion_wei_addr.scale[2] = w.down_s;+ scratch.moe_fusion_wei_addr.zp[2] = w.down_z;+ }++ size_t resident_slot_count() const {+ return _weight_provider->resident_capacity();+ }++ // --- Inline composition methods (replace virtual hooks) ---++ void bind_weights_on_first_exec(typed_primitive_inst<moe_3gemm_fused_compressed>& instance) {+ if (!_weight_provider->is_offloaded())+ return;+ if (!_weight_provider->is_bound()) {+ instance._weights.gate_w = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::WEIGHT_0));+ instance._weights.gate_z = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::ZP_0));+ instance._weights.gate_s = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SCALE_0));++ instance._weights.up_w = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::WEIGHT_1));+ instance._weights.up_z = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::ZP_1));+ instance._weights.up_s = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SCALE_1));++ instance._weights.down_w = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::WEIGHT_2));+ instance._weights.down_z = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::ZP_2));+ instance._weights.down_s = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SCALE_2));+ _weight_provider->bind(instance._weights);+ }+ }++ void prepare_weight_pointers(typed_primitive_inst<moe_3gemm_fused_compressed>& instance, scratch_buffers& scratch) {+ if (_weight_provider->is_offloaded()) {+ set_otd_weight_pointers(instance, scratch);+ } else {+ scratch.moe_fusion_wei_addr.weight[0] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::WEIGHT_0));+ scratch.moe_fusion_wei_addr.scale[0] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SCALE_0));+ scratch.moe_fusion_wei_addr.zp[0] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::ZP_0));+ scratch.moe_fusion_wei_addr.weight[1] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::WEIGHT_1));+ scratch.moe_fusion_wei_addr.scale[1] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SCALE_1));+ scratch.moe_fusion_wei_addr.zp[1] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::ZP_1));+ scratch.moe_fusion_wei_addr.weight[2] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::WEIGHT_2));+ scratch.moe_fusion_wei_addr.scale[2] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SCALE_2));+ scratch.moe_fusion_wei_addr.zp[2] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::ZP_2));+ }++ // Shared expert weight pointers (indices 12-21)+ if (instance.dependencies().size() > static_cast<size_t>(MOE3GemmInputIndex::SHARED_GATE_WEIGHT)) {+ scratch.moe_fusion_wei_addr.shared_weight[0] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_GATE_WEIGHT));+ scratch.moe_fusion_wei_addr.shared_scale[0] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_GATE_SCALE));+ scratch.moe_fusion_wei_addr.shared_zp[0] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_GATE_ZP));+ scratch.moe_fusion_wei_addr.shared_weight[1] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_UP_WEIGHT));+ scratch.moe_fusion_wei_addr.shared_scale[1] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_UP_SCALE));+ scratch.moe_fusion_wei_addr.shared_zp[1] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_UP_ZP));+ scratch.moe_fusion_wei_addr.shared_weight[2] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_DOWN_WEIGHT));+ scratch.moe_fusion_wei_addr.shared_scale[2] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_DOWN_SCALE));+ scratch.moe_fusion_wei_addr.shared_zp[2] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_DOWN_ZP));+ scratch.moe_fusion_wei_addr.shared_weight[3] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_GATE_GATE_WEIGHT));+ }+ }++ void on_before_batched_gemv(cldnn::stream& stream,+ typed_primitive_inst<moe_3gemm_fused_compressed>& instance,+ scratch_buffers& scratch,+ size_t topk_count,+ bool& needs_fallback) {+ if (!_weight_provider->is_offloaded()) {+ needs_fallback = false;+ return;+ }+ stream.finish();++ std::vector<uint32_t> expert_ids(topk_count);+ scratch.topk_id->copy_to(stream, expert_ids.data(), 0, 0, topk_count * sizeof(uint32_t), true);++ auto lease = _weight_provider->try_acquire_simultaneous(expert_ids, stream);+ if (!lease) {+ if (auto* perf = moe_otd::get_perf_counters())+ perf->batched_fallbacks.fetch_add(1, std::memory_order_relaxed);+ needs_fallback = true;+ return;+ }++ // Write remapped slot IDs to GPU buffer+ auto& engine = instance.get_network().get_engine();+ const size_t topk_bytes = topk_count * sizeof(uint32_t);+ if (!scratch._expert_index_buffer || scratch._expert_index_buffer->size() < topk_bytes) {+ auto layout = cldnn::layout({1, 1, 1, static_cast<ov::Dimension::value_type>(topk_bytes)}, ov::element::i8, cldnn::format::bfyx);+ scratch._expert_index_buffer = engine.allocate_memory(layout, allocation_type::usm_host, false);+ }+ std::vector<uint32_t> slots_u32(lease->size());+ for (size_t i = 0; i < lease->size(); i++)+ slots_u32[i] = static_cast<uint32_t>((*lease)[i]);+ scratch._expert_index_buffer->copy_from(stream, slots_u32.data(), 0, 0, topk_bytes, true);++ set_otd_weight_pointers(instance, scratch);+ needs_fallback = false;+ }++ void on_before_prefill(cldnn::stream& stream,+ typed_primitive_inst<moe_3gemm_fused_compressed>& instance,+ scratch_buffers& scratch,+ memory::ptr& batch_mem_ptr,+ size_t topk_count,+ bool& needs_fallback) {+ if (!_weight_provider->is_offloaded()) {+ needs_fallback = false;+ return;+ }++ std::vector<uint32_t> expert_ids(topk_count);+ batch_mem_ptr->copy_to(stream, expert_ids.data(), 0, 0, topk_count * sizeof(uint32_t), true);++ auto lease = _weight_provider->try_acquire_simultaneous(expert_ids, stream);+ if (!lease) {+ if (auto* perf = moe_otd::get_perf_counters())+ perf->grouped_fallbacks.fetch_add(1, std::memory_order_relaxed);+ needs_fallback = true;+ return;+ }++ // Write remapped slot IDs to GPU buffer+ auto& engine = instance.get_network().get_engine();+ const size_t topk_bytes = topk_count * sizeof(uint32_t);+ if (!scratch._expert_index_buffer || scratch._expert_index_buffer->size() < topk_bytes) {+ auto layout = cldnn::layout({1, 1, 1, static_cast<ov::Dimension::value_type>(topk_bytes)}, ov::element::i8, cldnn::format::bfyx);+ scratch._expert_index_buffer = engine.allocate_memory(layout, allocation_type::usm_host, false);+ }+ std::vector<uint32_t> slots_u32(lease->size());+ for (size_t i = 0; i < lease->size(); i++)+ slots_u32[i] = static_cast<uint32_t>((*lease)[i]);+ scratch._expert_index_buffer->copy_from(stream, slots_u32.data(), 0, 0, topk_bytes, true);+ batch_mem_ptr = scratch._expert_index_buffer;+ needs_fallback = false;+ }++ bool on_load_expert_weights(size_t expert_no, typed_primitive_inst<moe_3gemm_fused_compressed>& instance, dnnl::stream& dnn_stream) {+ if (!_weight_provider->is_offloaded())+ return false;++ dnn_stream.wait();++ auto& stream = instance.get_network().get_stream();+ auto& dnnl_weights = _dnnl_weights[expert_no];+ auto lru_expert_no = static_cast<int64_t>(_weight_provider->acquire_one(static_cast<uint32_t>(expert_no), stream));+ auto& params = instance._weights;++# define CONVERT_DNNL_OTD(name, i) \+ int64_t wei_offset##i = lru_expert_no * get_bytes_count(dnnl_weights[i].ic * dnnl_weights[i].oc, params.name##_w->get_layout()); \+ int64_t scale_offset##i = \+ lru_expert_no * get_bytes_count(dnnl_weights[i].ic * dnnl_weights[i].oc / dnnl_weights[i].ic_group_size, params.name##_s->get_layout()); \+ int64_t zp_offset##i = \+ lru_expert_no * get_bytes_count(dnnl_weights[i].ic * dnnl_weights[i].oc / dnnl_weights[i].ic_group_size, params.name##_z->get_layout()); \+ dnnl_weights[i].weight = convert2dnnl(params.name##_w, {dnnl_weights[i].ic, dnnl_weights[i].oc}, dnnl::memory::format_tag::ba, wei_offset##i); \+ dnnl_weights[i].scale = convert2dnnl(params.name##_s, \+ {dnnl_weights[i].ic / dnnl_weights[i].ic_group_size, dnnl_weights[i].oc}, \+ dnnl::memory::format_tag::ab, \+ scale_offset##i); \+ dnnl_weights[i].zp = convert2dnnl(params.name##_z, \+ {dnnl_weights[i].ic / dnnl_weights[i].ic_group_size, dnnl_weights[i].oc}, \+ dnnl::memory::format_tag::ab, \+ zp_offset##i);+ CONVERT_DNNL_OTD(gate, 0)+ CONVERT_DNNL_OTD(up, 1)+ CONVERT_DNNL_OTD(down, 2)+# undef CONVERT_DNNL_OTD+ return true;+ }++ int get_num_grouped_experts(int num_total_experts) {+ return _weight_provider->is_offloaded() ? static_cast<int>(resident_slot_count()) : num_total_experts;+ }++ bool build_grouped_mask_otd(cldnn::stream& stream,+ typed_primitive_inst<moe_3gemm_fused_compressed>& instance,+ scratch_buffers& scratch,+ memory::ptr& batch_mem_ptr,+ size_t token_num,+ int max_topk,+ int num_grouped_experts,+ std::vector<int32_t>& tokens_per_expert_cpu,+ std::vector<int32_t>& tokens_lens_per_expert_cpu,+ std::vector<int32_t>& experts_id_cpu,+ std::vector<int32_t>& grouped_offsets_cpu,+ int& num_actually_used_experts,+ const std::vector<cldnn::event::ptr>& events) {+ if (!_weight_provider->is_offloaded())+ return false;++ stream.finish(); // ensure routing kernel has written topk_ids++ size_t topk_count = static_cast<size_t>(token_num) * max_topk;+ std::vector<uint32_t> raw_topk_ids(topk_count);+ batch_mem_ptr->copy_to(stream, raw_topk_ids.data(), 0, 0, topk_count * sizeof(uint32_t), true);++ // Use lease API for capacity-safe simultaneous acquisition.+ // If unique experts exceed resident capacity, returns nullopt → caller falls back.+ auto lease = _weight_provider->try_acquire_simultaneous(raw_topk_ids, stream);+ if (!lease) {+ GPU_DEBUG_TRACE_DETAIL << "exec_prefill_grouped_gemm OTD: unique experts exceed resident_slots=" << resident_slot_count()+ << ", falling back to per-expert onednn loop" << std::endl;+ if (auto* perf = moe_otd::get_perf_counters())+ perf->grouped_fallbacks.fetch_add(1, std::memory_order_relaxed);+ return false; // Caller checks is_offloaded() to distinguish from non-OTD+ }++ // Remap using lease slots+ std::vector<uint32_t> remapped(topk_count);+ for (size_t i = 0; i < topk_count; i++)+ remapped[i] = static_cast<uint32_t>((*lease)[i]);++ // Build per-slot token lists sorted by LRU slot index+ std::vector<std::vector<int32_t>> slot_tokens(num_grouped_experts);+ for (size_t i = 0; i < topk_count; i++) {+ int32_t slot = static_cast<int32_t>(remapped[i]);+ int32_t token_idx = static_cast<int32_t>(i / max_topk);+ slot_tokens[slot].push_back(token_idx);+ }++ // Build grouped_offsets and tokens_per_expert sorted by slot+ int tokens_iter = 0;+ int experts_iter = 0;+ int32_t running_offset = 0;+ for (int s = 0; s < num_grouped_experts; s++) {+ auto n = static_cast<int32_t>(slot_tokens[s].size());+ running_offset += n;+ grouped_offsets_cpu[s] = running_offset;+ if (n > 0) {+ experts_id_cpu[experts_iter] = s;+ tokens_lens_per_expert_cpu[experts_iter] = n;+ ++experts_iter;+ ++num_actually_used_experts;+ for (auto t : slot_tokens[s])+ tokens_per_expert_cpu[tokens_iter++] = t;+ }+ }++ // Upload remapped topk_ids to GPU for scatter_reduce kernel+ auto& engine = instance.get_network().get_engine();+ size_t topk_bytes = topk_count * sizeof(uint32_t);+ if (!scratch._expert_index_buffer || scratch._expert_index_buffer->size() < topk_bytes) {+ auto remap_layout = batch_mem_ptr->get_layout();+ scratch._expert_index_buffer = engine.allocate_memory(remap_layout, allocation_type::usm_host, false);+ }+ scratch._expert_index_buffer->copy_from(stream, remapped.data(), 0, 0, topk_bytes, true);+ batch_mem_ptr = scratch._expert_index_buffer;++ set_otd_weight_pointers(instance, scratch);+ return true;+ }++ void on_after_grouped_gemm(cldnn::stream& stream) {+ if (_weight_provider->is_offloaded())+ stream.get_onednn_stream().wait();+ }++ void on_after_exec_sync(cldnn::stream& stream) {+ if (_weight_provider->is_offloaded())+ stream.finish();+ }++ bool should_pre_zero_output() {+ // OTD may fallback to exec_prefill_onednn which accumulates via index_add+ return !use_grouped_gemm_prefill || _weight_provider->is_offloaded();+ }++ bool should_validate_dnnl_weights() {+ // OTD doesn't validate at init time because weights aren't bound yet+ return !_weight_provider->is_offloaded();+ }++ void on_before_grouped_gather(cldnn::stream& stream) {+ if (_weight_provider->is_offloaded())+ stream.finish();+ }ov::op::internal::MOE::Activation_type _activation_type = ov::op::internal::MOE::Activation_type::SWIGLU;bool _has_shared_expert = false;@@ -685,6 +995,17 @@ public:}GPU_DEBUG_TRACE_DETAIL << "[DEBUG] moe_3gemm_swiglu_opt_impl(): batched_gemv_threshold=" << batched_gemv_threshold << std::endl;+ // Weight provider: select based on OTD configuration.+ auto cur_moe = node.as<moe_3gemm_fused_compressed>().get_primitive();+ if (cur_moe->_otd.lru_expert_num > 0) {+ _weight_provider = std::make_shared<OffloadExpertWeightProvider>(cur_moe->_otd.lru_expert_num,+ cur_moe->_config,+ cur_moe->_otd.weight_bin_offsets,+ cur_moe->_otd.weights_path);+ } else {+ _weight_provider = std::make_shared<ResidentExpertWeightProvider>();+ }+// Don't change the order of stagesadd_stage(gather, params);add_stage(scatter, params);@@ -729,19 +1050,6 @@ public:return;init(cur_moe);- auto get_bytes_count = [](int64_t size, const cldnn::layout& layout) {- ov::element::Type dt = layout.data_type;- switch (layout.data_type) {- case ov::element::u4:- case ov::element::i4:- return size / 2;- break;- default:- return size * static_cast<int64_t>(dt.size());- break;- }- };-_dnnl_weights.resize(cur_moe->_config.num_expert);// Per-GEMM ic_group_size from scale shape; config.group_size can't represent gate/up vs down differing.const auto ic_group_size_from_scale = [](size_t ic, const cldnn::memory::ptr& scale_mem) {@@ -753,67 +1061,72 @@ public:auto& dnnl_weights = _dnnl_weights[j];dnnl_weights.resize(3);dnnl_weights[0].ic = _hidden_size;- dnnl_weights[0].ic_group_size = ic_group_size_from_scale(_hidden_size, moe_fusion_wei_addr.scale[0]);+ dnnl_weights[0].ic_group_size =+ moe_fusion_wei_addr.scale[0] ? ic_group_size_from_scale(_hidden_size, moe_fusion_wei_addr.scale[0]) : _gate_up_group_size;dnnl_weights[0].oc = _intermediate_size;dnnl_weights[1].ic = _hidden_size;- dnnl_weights[1].ic_group_size = ic_group_size_from_scale(_hidden_size, moe_fusion_wei_addr.scale[1]);+ dnnl_weights[1].ic_group_size =+ moe_fusion_wei_addr.scale[1] ? ic_group_size_from_scale(_hidden_size, moe_fusion_wei_addr.scale[1]) : _gate_up_group_size;dnnl_weights[1].oc = _intermediate_size;dnnl_weights[2].ic = _intermediate_size;- dnnl_weights[2].ic_group_size = ic_group_size_from_scale(_intermediate_size, moe_fusion_wei_addr.scale[2]);+ dnnl_weights[2].ic_group_size =+ moe_fusion_wei_addr.scale[2] ? ic_group_size_from_scale(_intermediate_size, moe_fusion_wei_addr.scale[2]) : _down_group_size;dnnl_weights[2].oc = _hidden_size;- for (int i = 0; i < 3; i++) {- // Cross-check ic/ic_group_size against scale shape (drift caused u8 inf bug).- {- const auto& sshape = moe_fusion_wei_addr.scale[i]->get_layout().get_shape();- const size_t scale_num_groups = (sshape.size() >= 3) ? sshape[2] : 1;- OPENVINO_ASSERT(dnnl_weights[i].ic_group_size > 0, "moe_3gemm GEMM ", i, " ic_group_size must be > 0");- OPENVINO_ASSERT(dnnl_weights[i].ic % dnnl_weights[i].ic_group_size == 0,- "moe_3gemm GEMM ",- i,- " ic=",- dnnl_weights[i].ic,- " not divisible by ic_group_size=",- dnnl_weights[i].ic_group_size);- const auto expected_groups = dnnl_weights[i].ic / dnnl_weights[i].ic_group_size;- OPENVINO_ASSERT(static_cast<size_t>(expected_groups) == scale_num_groups,- "moe_3gemm GEMM ",- i,- " ic_group_size=",- dnnl_weights[i].ic_group_size,- " (=> ",- expected_groups,- " groups) disagrees with scale num_groups=",- scale_num_groups,- " (scale shape=",- sshape,- ")");- if (cur_moe->_config.has_zp && moe_fusion_wei_addr.zp[i]) {- const auto& zshape = moe_fusion_wei_addr.zp[i]->get_layout().get_shape();- OPENVINO_ASSERT(zshape == sshape, "moe_3gemm GEMM ", i, " scale shape ", sshape, " does not match zp shape ", zshape);+ if (should_validate_dnnl_weights()) {+ for (int i = 0; i < 3; i++) {+ // Cross-check ic/ic_group_size against scale shape (drift caused u8 inf bug).+ {+ const auto& sshape = moe_fusion_wei_addr.scale[i]->get_layout().get_shape();+ const size_t scale_num_groups = (sshape.size() >= 3) ? sshape[2] : 1;+ OPENVINO_ASSERT(dnnl_weights[i].ic_group_size > 0, "moe_3gemm GEMM ", i, " ic_group_size must be > 0");+ OPENVINO_ASSERT(dnnl_weights[i].ic % dnnl_weights[i].ic_group_size == 0,+ "moe_3gemm GEMM ",+ i,+ " ic=",+ dnnl_weights[i].ic,+ " not divisible by ic_group_size=",+ dnnl_weights[i].ic_group_size);+ const auto expected_groups = dnnl_weights[i].ic / dnnl_weights[i].ic_group_size;+ OPENVINO_ASSERT(static_cast<size_t>(expected_groups) == scale_num_groups,+ "moe_3gemm GEMM ",+ i,+ " ic_group_size=",+ dnnl_weights[i].ic_group_size,+ " (=> ",+ expected_groups,+ " groups) disagrees with scale num_groups=",+ scale_num_groups,+ " (scale shape=",+ sshape,+ ")");+ if (cur_moe->_config.has_zp && moe_fusion_wei_addr.zp[i]) {+ const auto& zshape = moe_fusion_wei_addr.zp[i]->get_layout().get_shape();+ OPENVINO_ASSERT(zshape == sshape, "moe_3gemm GEMM ", i, " scale shape ", sshape, " does not match zp shape ", zshape);+ }+ }+ // weight shape: [ic, oc], type: u4/i8+ int64_t wei_offset = j * get_bytes_count(dnnl_weights[i].ic * dnnl_weights[i].oc, moe_fusion_wei_addr.weight[i]->get_layout());+ dnnl_weights[i].weight =+ convert2dnnl(moe_fusion_wei_addr.weight[i], {dnnl_weights[i].ic, dnnl_weights[i].oc}, dnnl::memory::format_tag::ba, wei_offset);++ // scale shape: [ic / ic_group_size, oc], type: f16+ int64_t scale_offset = j * get_bytes_count(dnnl_weights[i].ic * dnnl_weights[i].oc / dnnl_weights[i].ic_group_size,+ moe_fusion_wei_addr.scale[i]->get_layout());+ dnnl_weights[i].scale = convert2dnnl(moe_fusion_wei_addr.scale[i],+ {dnnl_weights[i].ic / dnnl_weights[i].ic_group_size, dnnl_weights[i].oc},+ dnnl::memory::format_tag::ab,+ scale_offset);++ // zp shape: [ic / ic_group_size, oc], type: u4/i8+ // Skip ZP memory allocation for symmetric quantization (has_zp=false) to save memory+ if (cur_moe->_config.has_zp) {+ int64_t zp_offset = j * get_bytes_count(dnnl_weights[i].ic * dnnl_weights[i].oc / dnnl_weights[i].ic_group_size,+ moe_fusion_wei_addr.zp[i]->get_layout());+ dnnl_weights[i].zp = convert2dnnl(moe_fusion_wei_addr.zp[i],+ {dnnl_weights[i].ic / dnnl_weights[i].ic_group_size, dnnl_weights[i].oc},+ dnnl::memory::format_tag::ab,+ zp_offset);}- }- // weight shape: [ic, oc], type: u4/i8- int64_t wei_offset = j * get_bytes_count(dnnl_weights[i].ic * dnnl_weights[i].oc, moe_fusion_wei_addr.weight[i]->get_layout());- dnnl_weights[i].weight =- convert2dnnl(moe_fusion_wei_addr.weight[i], {dnnl_weights[i].ic, dnnl_weights[i].oc}, dnnl::memory::format_tag::ba, wei_offset);-- // scale shape: [ic / ic_group_size, oc], type: f16- int64_t scale_offset =- j * get_bytes_count(dnnl_weights[i].ic * dnnl_weights[i].oc / dnnl_weights[i].ic_group_size, moe_fusion_wei_addr.scale[i]->get_layout());- dnnl_weights[i].scale = convert2dnnl(moe_fusion_wei_addr.scale[i],- {dnnl_weights[i].ic / dnnl_weights[i].ic_group_size, dnnl_weights[i].oc},- dnnl::memory::format_tag::ab,- scale_offset);-- // zp shape: [ic / ic_group_size, oc], type: u4/i8- // Skip ZP memory allocation for symmetric quantization (has_zp=false) to save memory- if (cur_moe->_config.has_zp) {- int64_t zp_offset =- j * get_bytes_count(dnnl_weights[i].ic * dnnl_weights[i].oc / dnnl_weights[i].ic_group_size, moe_fusion_wei_addr.zp[i]->get_layout());- dnnl_weights[i].zp = convert2dnnl(moe_fusion_wei_addr.zp[i],- {dnnl_weights[i].ic / dnnl_weights[i].ic_group_size, dnnl_weights[i].oc},- dnnl::memory::format_tag::ab,- zp_offset);}}}@@ -823,22 +1136,24 @@ public:if (_shared_gate_proj && _shared_gate_proj->m_batch == batch)return;- if (!addr.shared_weight[0]) {- _has_shared_expert = false;- return;- }+ OPENVINO_ASSERT(addr.shared_weight[0], "MoE shared expert enabled (num_shared_expert > 0) but shared weight buffers are not bound");_shared_intermediate_size = static_cast<int>(addr.shared_weight[0]->get_layout().count() / _hidden_size);auto eng = engine.get_onednn_engine();using t = onednn_matmul::type;+ // Helper: returns true if the memory is a real ZP buffer (not a dynamic placeholder used for symmetric quantization).+ auto is_valid_zp = [](const memory::ptr& m) {+ return m && m->get_layout().data_type != data_types::dynamic;+ };+// 1. Up (Standard Linear)auto up_w_dt = convert_data_type(addr.shared_weight[1]->get_layout().data_type);auto up_w = convert2dnnl(addr.shared_weight[1], {_hidden_size, _shared_intermediate_size}, dnnl::memory::format_tag::ba);auto up_s = addr.shared_scale[1]? convert2dnnl(addr.shared_scale[1], {_hidden_size / _gate_up_group_size, _shared_intermediate_size}, dnnl::memory::format_tag::ab): dnnl::memory();- auto up_z = addr.shared_zp[1]+ auto up_z = is_valid_zp(addr.shared_zp[1])? convert2dnnl(addr.shared_zp[1], {_hidden_size / _gate_up_group_size, _shared_intermediate_size}, dnnl::memory::format_tag::ab): dnnl::memory();_shared_up_proj = std::make_shared<onednn_linear>(onednn_linear::create(eng,@@ -859,7 +1174,7 @@ public:auto gate_s = addr.shared_scale[0]? convert2dnnl(addr.shared_scale[0], {_hidden_size / _gate_up_group_size, _shared_intermediate_size}, dnnl::memory::format_tag::ab): dnnl::memory();- auto gate_z = addr.shared_zp[0]+ auto gate_z = is_valid_zp(addr.shared_zp[0])? convert2dnnl(addr.shared_zp[0], {_hidden_size / _gate_up_group_size, _shared_intermediate_size}, dnnl::memory::format_tag::ab): dnnl::memory();_shared_gate_proj = std::make_shared<onednn_linear>(onednn_linear::create(eng,@@ -897,7 +1212,7 @@ public:auto down_s = addr.shared_scale[2]? convert2dnnl(addr.shared_scale[2], {_shared_intermediate_size / _down_group_size, _hidden_size}, dnnl::memory::format_tag::ab): dnnl::memory();- auto down_z = addr.shared_zp[2]+ auto down_z = is_valid_zp(addr.shared_zp[2])? convert2dnnl(addr.shared_zp[2], {_shared_intermediate_size / _down_group_size, _hidden_size}, dnnl::memory::format_tag::ab): dnnl::memory();_shared_down_proj = std::make_shared<onednn_linear>(onednn_linear::create(eng,@@ -967,6 +1282,7 @@ public:cur_moe->_intermediate_size = _intermediate_size;cur_moe->_gate_up_group_size = _gate_up_group_size;cur_moe->_down_group_size = _down_group_size;+ cur_moe->_weight_provider = _weight_provider; // shared across clones within the same networkcur_moe->use_micro_gemm_prefill = use_micro_gemm_prefill;cur_moe->use_gpu_mask_gen_prefill = use_gpu_mask_gen_prefill;cur_moe->use_grouped_gemm_prefill = use_grouped_gemm_prefill;@@ -1041,6 +1357,7 @@ public:void prepare_internal_buffers(typed_primitive_inst<moe_3gemm_fused_compressed>& instance, scratch_buffers& scratch, size_t token_num) {const auto& intermediates_memories = instance.get_intermediates_memories();auto& engine = instance.get_network().get_engine();+// topk_id / topk_weights are read from inputs (computed by MoERouterFused).scratch.topk_weights = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::TOPK_WEIGHTS));scratch.topk_id = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::TOPK_INDICES));@@ -1063,58 +1380,7 @@ public:}}- // gate- scratch.moe_fusion_wei_addr.weight[0] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::WEIGHT_0));- scratch.moe_fusion_wei_addr.scale[0] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SCALE_0));- scratch.moe_fusion_wei_addr.zp[0] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::ZP_0));-- // up- scratch.moe_fusion_wei_addr.weight[1] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::WEIGHT_1));- scratch.moe_fusion_wei_addr.scale[1] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SCALE_1));- scratch.moe_fusion_wei_addr.zp[1] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::ZP_1));-- // down- scratch.moe_fusion_wei_addr.weight[2] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::WEIGHT_2));- scratch.moe_fusion_wei_addr.scale[2] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SCALE_2));- scratch.moe_fusion_wei_addr.zp[2] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::ZP_2));-- // For symmetric quantization (has_zp=false), ZP inputs are element::dynamic placeholders- // with zero-count layout. Use scale memory as a dummy to avoid null pointer issues.- const auto& config = instance.get_typed_desc<moe_3gemm_fused_compressed>()->_config;- if (!config.has_zp) {- scratch.moe_fusion_wei_addr.zp[0] = scratch.moe_fusion_wei_addr.scale[0];- scratch.moe_fusion_wei_addr.zp[1] = scratch.moe_fusion_wei_addr.scale[1];- scratch.moe_fusion_wei_addr.zp[2] = scratch.moe_fusion_wei_addr.scale[2];- }-- // shared expert- size_t dep_count = instance.dependencies().size();- if (dep_count >= static_cast<size_t>(MOE3GemmInputIndex::SHARED_GATE_GATE_WEIGHT) + 1) {- // Gate- scratch.moe_fusion_wei_addr.shared_weight[0] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_GATE_WEIGHT));- scratch.moe_fusion_wei_addr.shared_scale[0] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_GATE_SCALE));- scratch.moe_fusion_wei_addr.shared_zp[0] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_GATE_ZP));-- // Up- scratch.moe_fusion_wei_addr.shared_weight[1] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_UP_WEIGHT));- scratch.moe_fusion_wei_addr.shared_scale[1] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_UP_SCALE));- scratch.moe_fusion_wei_addr.shared_zp[1] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_UP_ZP));-- // Down- scratch.moe_fusion_wei_addr.shared_weight[2] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_DOWN_WEIGHT));- scratch.moe_fusion_wei_addr.shared_scale[2] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_DOWN_SCALE));- scratch.moe_fusion_wei_addr.shared_zp[2] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_DOWN_ZP));-- // Scalar Gate - f16- scratch.moe_fusion_wei_addr.shared_weight[3] = instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::SHARED_GATE_GATE_WEIGHT));-- // For symmetric quantization, shared expert ZPs are also element::dynamic placeholders- if (!config.has_zp) {- scratch.moe_fusion_wei_addr.shared_zp[0] = scratch.moe_fusion_wei_addr.shared_scale[0];- scratch.moe_fusion_wei_addr.shared_zp[1] = scratch.moe_fusion_wei_addr.shared_scale[1];- scratch.moe_fusion_wei_addr.shared_zp[2] = scratch.moe_fusion_wei_addr.shared_scale[2];- }- }+ prepare_weight_pointers(instance, scratch);}void get_expert_mask_from_gpu(const MOECompressed::Config& config, memory::ptr mem, stream& stream, expert_mask_cpu& expert_mask, size_t actual_token_num) {@@ -1129,12 +1395,8 @@ public:expert_mask.batch.resize(max_expert_num, {});expert_mask.topk.resize(max_expert_num, {});- if (layout.data_padding) {- OPENVINO_THROW("get_expert_mask_from_memory not support padding");- }-- GPU_DEBUG_TRACE_DETAIL << "[DEBUG] get_expert_mask_from_gpu: layout=" << layout.to_short_string() << ", max_expert_num=" << max_expert_num- << ", max_topk=" << max_topk << ", max_tokens=" << max_tokens << std::endl;+ GPU_DEBUG_TRACE_DETAIL << "[DEBUG] get_expert_mask_from_gpu: max_expert_num=" << max_expert_num << ", max_topk=" << max_topk+ << ", max_tokens=" << max_tokens << std::endl;std::vector<int32_t> buf(max_topk * max_tokens);mem->copy_to(stream, buf.data(), 0, 0, buf.size() * sizeof(int32_t), true);@@ -1167,9 +1429,7 @@ public:" should have ",max_topk * max_tokens," tokens, but current is ",- count,- ". layout=",- layout);+ count);}}@@ -1253,6 +1513,8 @@ 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);@@ -1266,6 +1528,21 @@ 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, false);+ return exec_prefill_onednn(events, stream, instance, scratch);+ }+ }+ // OTD hook may have remapped expert IDs into scratch._expert_index_buffer+ if (scratch._expert_index_buffer) {+ batch_mem_ptr = scratch._expert_index_buffer;+ }+// gateconst auto& mlp_gate_wei_mem = scratch.moe_fusion_wei_addr.weight[0];const auto& mlp_gate_scale_mem = scratch.moe_fusion_wei_addr.scale[0];@@ -1383,6 +1660,16 @@ public:auto num_total_experts = static_cast<int>(cur_moe->_config.num_expert);int num_actually_used_experts = 0;+ {+ auto topk_count = token_num * static_cast<size_t>(max_topk);+ bool needs_fallback = false;+ on_before_prefill(stream, instance, scratch, batch_mem_ptr, topk_count, needs_fallback);+ if (needs_fallback) {+ instance.output_memory_ptr(0)->fill(stream, false);+ return exec_prefill_onednn(events, stream, instance, scratch);+ }+ }+// step 1: generate 4 mask data for following kernel execution// input: topk output, [token_len, expert_topk]// output:@@ -1667,11 +1954,42 @@ public:using grouped_kernel_lru = LruCache<int, std::shared_ptr<grouped_onednn_kernel>>;grouped_kernel_lru _grouped_kernels{128};onednn_kernel& get_kernel(int n_token, int expert_no, typed_primitive_inst<moe_3gemm_fused_compressed>& instance) {+ // OTD: all slots have identical shape → cache by n_token only.+ // Non-OTD: cache by (n_token, expert_no) since each expert has fixed weight handles.+ if (_weight_provider->is_offloaded()) {+ if (!_kernels.has(std::make_pair(n_token, 0))) {+ auto kernel = create_kernel(n_token, expert_no, instance);+ _kernels.add(std::make_pair(n_token, 0), kernel);+ if (auto* perf = moe_otd::get_perf_counters())+ perf->created_onednn_kernels.fetch_add(1, std::memory_order_relaxed);+ }+ auto& kernel = *_kernels.get(std::make_pair(n_token, 0));+ // Patch weight memory handles for the current expert's LRU slot.+ // on_load_expert_weights already updated _dnnl_weights[expert_no] with+ // the correct slot offset, so copy those handles to the cached kernel.+ auto& dw = _dnnl_weights[expert_no];+ kernel.gate.weight = dw[0].weight;+ kernel.gate.scale = dw[0].scale;+ kernel.gate.zp = dw[0].zp;+ kernel.up.weight = dw[1].weight;+ kernel.up.scale = dw[1].scale;+ kernel.up.zp = dw[1].zp;+ kernel.down.weight = dw[2].weight;+ kernel.down.scale = dw[2].scale;+ kernel.down.zp = dw[2].zp;+ return kernel;+ }auto key = std::make_pair(n_token, expert_no);- if (_kernels.has(key)) {- return *_kernels.get(key);+ if (!_kernels.has(key)) {+ auto kernel = create_kernel(n_token, expert_no, instance);+ _kernels.add(key, kernel);+ if (auto* perf = moe_otd::get_perf_counters())+ perf->created_onednn_kernels.fetch_add(1, std::memory_order_relaxed);}+ return *_kernels.get(key);+ }+ std::shared_ptr<onednn_kernel> create_kernel(int n_token, int expert_no, typed_primitive_inst<moe_3gemm_fused_compressed>& instance) {auto& cur_net = instance.get_network();auto& stream = cur_net.get_stream();auto& dnn_stream = stream.get_onednn_stream();@@ -1726,8 +2044,7 @@ public:dnnl_weights[2].weight,dnnl_weights[2].scale,dnnl_weights[2].zp);- _kernels.add(key, kernel);- return *_kernels.get(key);+ return kernel;}// Build (and cache) three grouped dnnl::matmul primitives for gate/up/down.@@ -1745,7 +2062,8 @@ public:auto& engine = instance.get_network().get_engine();auto& onednn_engine = engine.get_onednn_engine();- int num_experts = static_cast<int>(config.num_expert);+ // In OTD mode, weight buffer holds only resident_slot_count() slots, not full num_expert.+ int num_experts = get_num_grouped_experts(static_cast<int>(config.num_expert));auto a_dt = convert_data_type(instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::HIDDEN_STATES))->get_layout().data_type);auto gw_dt = convert_data_type(instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::WEIGHT_0))->get_layout().data_type);auto uw_dt = convert_data_type(instance.input_memory_ptr(static_cast<size_t>(MOE3GemmInputIndex::WEIGHT_1))->get_layout().data_type);@@ -1879,6 +2197,8 @@ public:if (can_skip_subgraph) {continue;}++ on_load_expert_weights(expert_no, instance, dnn_stream);auto& dnnl_weights = _dnnl_weights[expert_no];// expert_mask@@ -1910,21 +2230,18 @@ public:convert2dnnl(scratch.x, {static_cast<int64_t>(n_token), dnnl_weights[1].ic}, dnnl::memory::format_tag::ab),convert2dnnl(scratch.up, {static_cast<int64_t>(n_token), _intermediate_size}, dnnl::memory::format_tag::ab),dnnl::memory());-// gatekernel.gate.forward(dnn_stream,n_token,convert2dnnl(scratch.x, {static_cast<int64_t>(n_token), dnnl_weights[0].ic}, dnnl::memory::format_tag::ab),convert2dnnl(scratch.gate, {static_cast<int64_t>(n_token), _intermediate_size}, dnnl::memory::format_tag::ab),convert2dnnl(scratch.up, {static_cast<int64_t>(n_token), _intermediate_size}, dnnl::memory::format_tag::ab));-// downkernel.down.forward(dnn_stream,n_token,convert2dnnl(scratch.gate, {static_cast<int64_t>(n_token), _intermediate_size}, dnnl::memory::format_tag::ab),convert2dnnl(scratch.y, {static_cast<int64_t>(n_token), _hidden_size}, dnnl::memory::format_tag::ab),convert2dnnl(scratch.routing_weights, {static_cast<int64_t>(routing_weights_size)}, dnnl::memory::format_tag::a));-// index_addresult_event = execute_stage({result_event},instance,@@ -1973,24 +2290,45 @@ public:int max_topk = static_cast<int>(config.top_k);int num_actually_used_experts = 0;+ // In OTD mode, the grouped descriptor dimension is resident_slot_count() (LRU slots)+ // rather than the full num_total_experts.+ int num_grouped_experts = get_num_grouped_experts(num_total_experts);+// ----------------------------------------------------------------// Step 1: CPU mask generation (topk_id already flushed by caller)// ----------------------------------------------------------------cldnn::event::ptr ret_event = events.empty() ? nullptr : events[0];- expert_mask_cpu expert_mask;- get_expert_mask_from_gpu(config, batch_mem_ptr, stream, expert_mask, token_num);-// Flat list of source token indices per expert – input for prefill_gatherstd::vector<int32_t> tokens_per_expert_cpu(static_cast<size_t>(token_num) * max_topk, -1);// Compact per-activated-expert metadata reused by scatter_reduce- std::vector<int32_t> tokens_lens_per_expert_cpu(num_total_experts, 0);- std::vector<int32_t> experts_id_cpu(num_total_experts, -1);- // int32_t cumulative end-offsets per expert for OneDNN grouped GEMM- // offsets[e] = sum(n_0..n_e) = exclusive end of expert e in the flat buffer.+ std::vector<int32_t> tokens_lens_per_expert_cpu(num_grouped_experts, 0);+ std::vector<int32_t> experts_id_cpu(num_grouped_experts, -1);+ // int32_t cumulative end-offsets per expert/slot for OneDNN grouped GEMM+ // offsets[e] = sum(n_0..n_e) = exclusive end of expert/slot e in the flat buffer.// This is the s32 format expected by dnnl::memory::desc::grouped().- std::vector<int32_t> grouped_offsets_cpu(num_total_experts, 0);+ std::vector<int32_t> grouped_offsets_cpu(num_grouped_experts, 0);++ if (!build_grouped_mask_otd(stream,+ instance,+ scratch,+ batch_mem_ptr,+ token_num,+ max_topk,+ num_grouped_experts,+ tokens_per_expert_cpu,+ tokens_lens_per_expert_cpu,+ experts_id_cpu,+ grouped_offsets_cpu,+ num_actually_used_experts,+ events)) {+ if (_weight_provider->is_offloaded()) {+ // OTD: unique experts > capacity → explicit fallback to per-expert loop+ return exec_prefill_onednn(events, stream, instance, scratch);+ }+ // Non-OTD path: build mask from original expert IDs+ expert_mask_cpu expert_mask;+ get_expert_mask_from_gpu(config, batch_mem_ptr, stream, expert_mask, token_num);- {int tokens_iter = 0;int experts_iter = 0;int32_t running_offset = 0;@@ -2008,6 +2346,7 @@ public:}}}+int total_gathered_tokens = static_cast<int>(token_num) * max_topk;// Compute actual max tokens assigned to any single expert.@@ -2028,8 +2367,8 @@ public:// So experts_start_offset[k] must equal the start index of expert k+1 in the flat buffer// = exclusive end of expert k = grouped_offsets_cpu[k].{- std::vector<int32_t> expert_start_offsets_per_id(static_cast<size_t>(num_total_experts - 1));- for (int e = 0; e < num_total_experts - 1; ++e)+ std::vector<int32_t> expert_start_offsets_per_id(static_cast<size_t>(num_grouped_experts - 1));+ for (int e = 0; e < num_grouped_experts - 1; ++e)expert_start_offsets_per_id[e] = grouped_offsets_cpu[e]; // end[e] == start[e+1]intermediates_memories[MOE_INTERNAL_BUFFER_TOKEN_START_OFFSET_PER_EXPERT]->copy_from(stream, expert_start_offsets_per_id.data(), 0, 0, expert_start_offsets_per_id.size() * sizeof(int32_t), true);@@ -2062,6 +2401,10 @@ public:{local_threads_count, 1, 1});}+ // In OTD mode, ensure gather OCL kernel completes before OneDNN reads scratch.x.+ // Non-OTD relies on the in-order queue's implicit ordering.+ on_before_grouped_gather(stream);+// ----------------------------------------------------------------// Steps 3-5: OneDNN grouped GEMM – gate, up, SiLU, down// ----------------------------------------------------------------@@ -2155,6 +2498,9 @@ public:gk.down_prim.execute(dnn_stream, args);}+ // Ensure all grouped GEMMs complete before scatter_reduce (OTD sync)+ on_after_grouped_gemm(stream);+// ----------------------------------------------------------------// Step 6: scatter_reduce – weighted accumulate into output// ----------------------------------------------------------------@@ -2189,6 +2535,9 @@ public:const auto& config = cur_moe->_config;auto& cur_net = instance.get_network();auto& stream = cur_net.get_stream();++ OPENVINO_ASSERT(_weight_provider, "expert weight provider not initialized");+cldnn::event::ptr ret_env = nullptr;_has_shared_expert = (config.num_shared_expert > 0);@@ -2204,6 +2553,9 @@ public:auto [hidden_states_mem_ptr, hidden_states_layout] = get_input_info(instance, static_cast<size_t>(MOE3GemmInputIndex::HIDDEN_STATES));size_t token_num = get_seq_len(hidden_states_layout);++ bind_weights_on_first_exec(instance);+scratch_buffers scratch;prepare_internal_buffers(instance, scratch, token_num);kernel_dump_info.clear_entries();@@ -2215,10 +2567,13 @@ public:}auto final_hidden_states_mem_ptr = instance.output_memory_ptr(0);- // only the per-expert onednn loop path accumulates into the output via index_add,- // so it needs the buffer pre-zeroed; micro_gemm and grouped_gemm use scatter_reduce- // which writes atomically and does not require pre-zeroing.- if (!use_micro_gemm_prefill && !use_grouped_gemm_prefill) {+ // Pre-zero output buffer for paths that accumulate into it.+ // The per-expert onednn loop uses index_add (accumulates into output).+ // The grouped_gemm scatter_reduce writes all token positions atomically+ // and does not require pre-zeroing — except in OTD mode where the+ // fallback to exec_prefill_onednn (when unique_experts > lru slots)+ // also accumulates via index_add.+ if (!use_micro_gemm_prefill && should_pre_zero_output()) {final_hidden_states_mem_ptr->fill(stream, false);}// GPU mask gen is only supported for micro_gemm; both grouped_gemm and onednn loop@@ -2241,6 +2596,12 @@ public:ret_env = exec_prefill_micro_gemm(events, instance, scratch, use_gpu_mask_gen);} else if (use_grouped_gemm_prefill) {ret_env = exec_prefill_grouped_gemm(events, stream, instance, scratch);+ // In OTD mode the grouped_gemm path interleaves OCL kernels with OneDNN+ // grouped matmul on the same in-order queue. The framework's event-based+ // scheduling may proceed to subsequent graph nodes before scatter_reduce+ // completes, causing multi-iteration inference to degrade.+ // Flush the queue only in OTD mode to avoid impacting non-OTD perf.+ on_after_exec_sync(stream);} else {ret_env = exec_prefill_onednn(events, stream, instance, scratch);}diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_otd_runtime.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_otd_runtime.cppnew file mode 100644index 00000000000..1a7b449df88--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_otd_runtime.cpp@@ -0,0 +1,235 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "moe_otd_runtime.hpp"++#include <array>+#include <chrono>+#include <cstdlib>+#include <cstring>+#include <limits>++#include "intel_gpu/runtime/debug_configuration.hpp"++namespace ov::intel_gpu::ocl::moe_otd {++void OtdPerfCounters::dump() const {+ const auto hits = gpu_hits.load(std::memory_order_relaxed);+ const auto misses = gpu_misses.load(std::memory_order_relaxed);+ const auto total = hits + misses;+ const auto loads = tensor_load_count.load(std::memory_order_relaxed);+ GPU_DEBUG_INFO << "[OTD_PERF] gpu_hits=" << hits << ", gpu_misses=" << misses << ", gpu_hit_rate=" << (total > 0 ? 100.0 * hits / total : 0.0) << "%"+ << ", tensor_loads=" << loads << ", avg_disk_io_us=" << (loads > 0 ? disk_io_ns.load(std::memory_order_relaxed) / 1000 / loads : 0)+ << ", avg_transpose_us=" << (loads > 0 ? transpose_ns.load(std::memory_order_relaxed) / 1000 / loads : 0)+ << ", avg_gpu_copy_us=" << (loads > 0 ? gpu_copy_ns.load(std::memory_order_relaxed) / 1000 / loads : 0)+ << ", total_disk_io_ms=" << disk_io_ns.load(std::memory_order_relaxed) / 1000000+ << ", total_gpu_copy_ms=" << gpu_copy_ns.load(std::memory_order_relaxed) / 1000000+ << ", batched_fallbacks=" << batched_fallbacks.load(std::memory_order_relaxed)+ << ", grouped_fallbacks=" << grouped_fallbacks.load(std::memory_order_relaxed)+ << ", created_onednn_kernels=" << created_onednn_kernels.load(std::memory_order_relaxed) << std::endl;+}++OtdPerfCounters* get_perf_counters() {+ static bool enabled = std::getenv("MOE_OTD_PERF_LOG") != nullptr;+ if (!enabled)+ return nullptr;++ static OtdPerfCounters counters;+ static bool registered = [] {+ std::atexit([] {+ counters.dump();+ });+ return true;+ }();+ (void)registered;+ return &counters;+}++void maybe_transpose_scale_zp(const cldnn::MOECompressed::Config& config,+ size_t offset_pos,+ const cldnn::layout& layout,+ std::vector<uint8_t>& payload,+ size_t per_expert_size) {+ // Offset positions: 0-2 = weights (no transpose), 3-5 = scales, 6-8 = zero points.+ // Within each group of 3: index % 3 == 2 means "down" variant.+ const bool is_scale = (offset_pos >= 3 && offset_pos <= 5);+ const bool is_zp = (offset_pos >= 6 && offset_pos <= 8);+ if (!is_scale && !is_zp) {+ return;+ }++ const bool is_down = (offset_pos % 3 == 2);+ size_t oc = 0;+ size_t ic = 0;+ if (is_down) {+ oc = static_cast<size_t>(config.hidden_size);+ ic = static_cast<size_t>(config.inter_size);+ } else {+ oc = static_cast<size_t>(config.inter_size);+ ic = static_cast<size_t>(config.hidden_size);+ }++ const size_t group_size = static_cast<size_t>(config.group_size);+ size_t group_count = 1;+ if (group_size != 0 && group_size != std::numeric_limits<size_t>::max()) {+ OPENVINO_ASSERT(ic % group_size == 0, "Invalid group_size for OTD transpose: offset_pos=", offset_pos, ", ic=", ic, ", group_size=", group_size);+ group_count = ic / group_size;+ }++ OPENVINO_ASSERT(oc > 0 && group_count > 0, "Invalid dims for OTD transpose: offset_pos=", offset_pos, ", oc=", oc, ", group_count=", group_count);++ const size_t elem_count = oc * group_count;+ if (is_scale) {+ const size_t elem_size = static_cast<size_t>(cldnn::data_type_traits::size_of(layout.data_type));+ OPENVINO_ASSERT(elem_size > 0, "Invalid scale element size for offset_pos=", offset_pos);+ OPENVINO_ASSERT(elem_count * elem_size == per_expert_size,+ "Unexpected scale payload size for offset_pos=",+ offset_pos,+ ", expected=",+ elem_count * elem_size,+ ", got=",+ per_expert_size);++ std::vector<uint8_t> transposed(per_expert_size, 0);+ for (size_t o = 0; o < oc; o++) {+ for (size_t g = 0; g < group_count; g++) {+ const size_t src_elem_idx = o * group_count + g;+ const size_t dst_elem_idx = g * oc + o;+ std::memcpy(transposed.data() + dst_elem_idx * elem_size, payload.data() + src_elem_idx * elem_size, elem_size);+ }+ }+ payload.swap(transposed);+ return;+ }++ OPENVINO_ASSERT(elem_count % 2 == 0, "Unexpected odd element count for packed zp offset_pos=", offset_pos, ", elem_count=", elem_count);+ OPENVINO_ASSERT(elem_count / 2 == per_expert_size,+ "Unexpected zp payload size for offset_pos=",+ offset_pos,+ ", expected=",+ elem_count / 2,+ ", got=",+ per_expert_size);++ std::vector<uint8_t> unpacked(elem_count, 0);+ for (size_t i = 0; i < per_expert_size; i++) {+ const uint8_t byte = payload[i];+ unpacked[2 * i] = static_cast<uint8_t>(byte & 0x0F);+ unpacked[2 * i + 1] = static_cast<uint8_t>((byte >> 4) & 0x0F);+ }++ std::vector<uint8_t> transposed_unpacked(elem_count, 0);+ for (size_t o = 0; o < oc; o++) {+ for (size_t g = 0; g < group_count; g++) {+ const size_t src_idx = o * group_count + g;+ const size_t dst_idx = g * oc + o;+ transposed_unpacked[dst_idx] = unpacked[src_idx];+ }+ }++ std::vector<uint8_t> repacked(per_expert_size, 0);+ for (size_t i = 0; i < per_expert_size; i++) {+ repacked[i] = static_cast<uint8_t>((transposed_unpacked[2 * i] & 0x0F) | ((transposed_unpacked[2 * i + 1] & 0x0F) << 4));+ }+ payload.swap(repacked);+}++void fill_weights_memory(cldnn::stream& exec_stream,+ const cldnn::MOECompressed::Config& config,+ const std::vector<size_t>& weight_bin_offsets,+ ParallelWeightReader& weight_reader,+ cldnn::moe_weights& wei_mem,+ const std::vector<uint32_t>& experts_list,+ const std::vector<size_t>& lru_experts) {+ struct tensor_fill_plan {+ size_t per_expert_size = 0;+ size_t src_offset = 0;+ size_t dst_offset = 0;+ };++ const auto num_expert = static_cast<size_t>(config.num_expert);++ OPENVINO_ASSERT(weight_bin_offsets.size() == cldnn::moe_3gemm_fused_compressed::serialized_weight_offset_count, "Unexpected number of MOE weight offsets");++ static const std::array<const char*, cldnn::moe_3gemm_fused_compressed::serialized_weight_offset_count> tensor_names = {+ {"gate_w", "up_w", "down_w", "gate_s", "up_s", "down_s", "gate_z", "up_z", "down_z"}};+ const std::array<cldnn::memory_ptr, cldnn::moe_3gemm_fused_compressed::serialized_weight_offset_count> tensors_by_offset = {+ {wei_mem.gate_w, wei_mem.up_w, wei_mem.down_w, wei_mem.gate_s, wei_mem.up_s, wei_mem.down_s, wei_mem.gate_z, wei_mem.up_z, wei_mem.down_z}};++ auto* perf = get_perf_counters();++ const size_t weight_file_size = weight_reader.file_size();++ size_t index = 0;+ for (uint32_t expert : experts_list) {+ auto make_tensor_fill_plan = [&](size_t base_offset, cldnn::memory_ptr mem, size_t expert_no, size_t lru_expert_no, const char* tensor_name) {+ tensor_fill_plan plan;+ if (!mem)+ return plan;+ const auto total_bytes = mem->get_layout().bytes_count();+ OPENVINO_ASSERT(num_expert > 0, "Invalid expert count");+ plan.per_expert_size = total_bytes / num_expert;+ plan.src_offset = base_offset + expert_no * plan.per_expert_size;+ plan.dst_offset = lru_expert_no * plan.per_expert_size;+ OPENVINO_ASSERT(plan.src_offset <= weight_file_size, "Invalid src_offset out of file: ", plan.src_offset, ", file_size=", weight_file_size);+ OPENVINO_ASSERT(plan.per_expert_size <= weight_file_size - plan.src_offset,+ "Read range out of file for tensor ",+ tensor_name,+ ": src_offset=",+ plan.src_offset,+ ", per_expert_size=",+ plan.per_expert_size,+ ", file_size=",+ weight_file_size,+ ", base_offset=",+ base_offset,+ ", expert=",+ expert_no);+ return plan;+ };++ for (size_t offset_pos = 0; offset_pos < static_cast<size_t>(cldnn::moe_3gemm_fused_compressed::serialized_weight_offset_count); offset_pos++) {+ auto plan =+ make_tensor_fill_plan(weight_bin_offsets[offset_pos], tensors_by_offset[offset_pos], expert, lru_experts[index], tensor_names[offset_pos]);+ std::vector<uint8_t> payload;++ if (plan.per_expert_size != 0) {+ payload.resize(plan.per_expert_size);+ if (perf) {+ auto t0 = std::chrono::steady_clock::now();+ weight_reader.read(reinterpret_cast<char*>(payload.data()), plan.per_expert_size, plan.src_offset);+ auto t1 = std::chrono::steady_clock::now();+ perf->disk_io_ns.fetch_add(static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0).count()),+ std::memory_order_relaxed);+ } else {+ weight_reader.read(reinterpret_cast<char*>(payload.data()), plan.per_expert_size, plan.src_offset);+ }+ }++ // Transpose + GPU copy+ auto mem = tensors_by_offset[offset_pos];+ if (mem && plan.per_expert_size != 0) {+ if (perf) {+ auto t0 = std::chrono::steady_clock::now();+ maybe_transpose_scale_zp(config, offset_pos, mem->get_layout(), payload, plan.per_expert_size);+ auto t1 = std::chrono::steady_clock::now();+ mem->copy_from(exec_stream, payload.data(), 0, plan.dst_offset, plan.per_expert_size, true);+ auto t2 = std::chrono::steady_clock::now();+ perf->transpose_ns.fetch_add(static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0).count()),+ std::memory_order_relaxed);+ perf->gpu_copy_ns.fetch_add(static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count()),+ std::memory_order_relaxed);+ perf->tensor_load_count.fetch_add(1, std::memory_order_relaxed);+ } else {+ maybe_transpose_scale_zp(config, offset_pos, mem->get_layout(), payload, plan.per_expert_size);+ mem->copy_from(exec_stream, payload.data(), 0, plan.dst_offset, plan.per_expert_size, true);+ }+ }+ }++ index++;+ }+}++} // namespace ov::intel_gpu::ocl::moe_otddiff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_otd_runtime.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_otd_runtime.hppnew file mode 100644index 00000000000..eea80703288--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_otd_runtime.hpp@@ -0,0 +1,99 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <atomic>+#include <cstdint>+#include <filesystem>+#include <memory>+#include <string>+#include <vector>++#include "intel_gpu/primitives/moe_3gemm_fused_compressed.hpp"+#include "intel_gpu/runtime/stream.hpp"+#include "lru_cache.hpp"+#include "openvino/util/parallel_io.hpp"++namespace ov::intel_gpu::ocl::moe_otd {++// Lightweight perf counters for OTD profiling.+// Enabled by setting MOE_OTD_PERF_LOG=1 environment variable.+// Counters are printed to stderr on process exit.+struct OtdPerfCounters {+ std::atomic<uint64_t> gpu_hits{0};+ std::atomic<uint64_t> gpu_misses{0};+ std::atomic<uint64_t> disk_io_ns{0};+ std::atomic<uint64_t> transpose_ns{0};+ std::atomic<uint64_t> gpu_copy_ns{0};+ std::atomic<uint64_t> tensor_load_count{0};+ std::atomic<uint64_t> batched_fallbacks{0};+ std::atomic<uint64_t> grouped_fallbacks{0};+ std::atomic<uint64_t> created_onednn_kernels{0};++ void dump() const;+};++OtdPerfCounters* get_perf_counters();++class ParallelWeightReader {+public:+ explicit ParallelWeightReader(const std::filesystem::path& weights_path) : _weights_path(weights_path) {}++ ~ParallelWeightReader() {+ if (_opened) {+ ov::util::close_file_handle(_shared_handle);+ }+ }++ ParallelWeightReader(const ParallelWeightReader&) = delete;+ ParallelWeightReader& operator=(const ParallelWeightReader&) = delete;++ const std::filesystem::path& path() const {+ return _weights_path;+ }++ size_t file_size() {+ ensure_open();+ return _file_size;+ }++ void read(char* dst, size_t size, size_t file_offset) {+ ensure_open();+ if (!ov::util::positional_read(_shared_handle, dst, size, file_offset)) {+ OPENVINO_THROW("Failed to read enough bytes from OTD weight file");+ }+ }++private:+ void ensure_open() {+ if (!_opened) {+ std::streamoff file_size = 0;+ ov::util::get_file_handle_and_size(_weights_path, 0, _shared_handle, file_size);+ _file_size = static_cast<size_t>(file_size);+ _opened = true;+ }+ }++ std::filesystem::path _weights_path;+ ov::FileHandle _shared_handle{};+ size_t _file_size = 0;+ bool _opened = false;+};++void maybe_transpose_scale_zp(const cldnn::MOECompressed::Config& config,+ size_t offset_pos,+ const cldnn::layout& layout,+ std::vector<uint8_t>& payload,+ size_t per_expert_size);++void fill_weights_memory(cldnn::stream& exec_stream,+ const cldnn::MOECompressed::Config& config,+ const std::vector<size_t>& weight_bin_offsets,+ ParallelWeightReader& weight_reader,+ cldnn::moe_weights& wei_mem,+ const std::vector<uint32_t>& experts_list,+ const std::vector<size_t>& lru_experts);++} // namespace ov::intel_gpu::ocl::moe_otd\ No newline at end of filediff --git a/src/plugins/intel_gpu/src/graph/include/moe_3gemm_fused_inst.h b/src/plugins/intel_gpu/src/graph/include/moe_3gemm_fused_inst.hindex f3b69f87730..7d6a3e4a4dd 100644--- a/src/plugins/intel_gpu/src/graph/include/moe_3gemm_fused_inst.h+++ b/src/plugins/intel_gpu/src/graph/include/moe_3gemm_fused_inst.h@@ -47,6 +47,7 @@ public:static layout calc_output_layout(const moe_node& /* node */, const kernel_impl_params& impl_param);static std::string to_string(const moe_node& node);typed_primitive_inst(network& network, const moe_node& node);+ cldnn::moe_weights _weights;};using moe_inst = typed_primitive_inst<moe_3gemm_fused_compressed>;diff --git a/src/plugins/intel_gpu/src/graph/network.cpp b/src/plugins/intel_gpu/src/graph/network.cppindex 4f6ce1e95bc..e46efff049b 100644--- a/src/plugins/intel_gpu/src/graph/network.cpp+++ b/src/plugins/intel_gpu/src/graph/network.cpp@@ -18,7 +18,7 @@#include "intel_gpu/runtime/compilation_context.hpp"#include "intel_gpu/runtime/debug_configuration.hpp"#include "intel_gpu/runtime/itt.hpp"-+#include "openvino/util/env_util.hpp"#include "intel_gpu/graph/kernel_impl_params.hpp"#include "intel_gpu/graph/program.hpp"#include "intel_gpu/graph/network.hpp"@@ -1189,7 +1189,9 @@ void network::transfer_memory_to_device(std::shared_ptr<primitive_inst> instance&& users.front()->is_type<reshape>()&& users.front()->is_dynamic())return;-+ if (node.is_type<data>() && node.as<data>().get_primitive()->skip_device_transfer()) {+ return;+ }// Do not transfer memory if a user requires lockable memory.// If memory is used in both gpu and cpu implementations, primitive itself is responsible for correct allocation typeif (node.need_lockable_memory())diff --git a/src/plugins/intel_gpu/src/graph/program.cpp b/src/plugins/intel_gpu/src/graph/program.cppindex 6b8956f3886..d466946d0cf 100644--- a/src/plugins/intel_gpu/src/graph/program.cpp+++ b/src/plugins/intel_gpu/src/graph/program.cpp@@ -1,6 +1,8 @@// Copyright (C) 2018-2026 Intel Corporation// SPDX-License-Identifier: Apache-2.0//+#include <thread>+#include <chrono>#include "intel_gpu/graph/fused_primitive_desc.hpp"#include "registry/implementation_manager.hpp"@@ -502,7 +504,6 @@ void program::build_program(bool is_internal) {{ pre_optimize_graph(is_internal); }run_graph_compilation();{ post_optimize_graph(is_internal); }-#ifdef GPU_DEBUG_CONFIGif (get_config().get_dry_run_path().empty() || is_internal) {#else@@ -724,7 +725,6 @@ void program::transfer_memory_to_device() {// TODO: Do we need finish call here? Maybe call it in network::execute() ?get_stream().finish();};-for (auto& node : processing_order) {if (node->is_shape_infer_dep()) {continue;@@ -732,6 +732,10 @@ void program::transfer_memory_to_device() {if (node->is_type<data>() && !node->need_lockable_memory()) {auto& data_node = node->as<data>();auto data_node_layout = data_node.get_output_layout();+ auto prim = data_node.get_primitive();+ if (prim->skip_device_transfer()) {+ continue;+ }auto& mem = data_node.get_attached_memory();auto mem_layout = mem.get_layout();auto alloc_type = mem.get_allocation_type();diff --git a/src/plugins/intel_gpu/src/plugin/compiled_model.cpp b/src/plugins/intel_gpu/src/plugin/compiled_model.cppindex 191faa6396b..c9bc49a5a7e 100644--- a/src/plugins/intel_gpu/src/plugin/compiled_model.cpp+++ b/src/plugins/intel_gpu/src/plugin/compiled_model.cpp@@ -341,6 +341,7 @@ ov::Any CompiledModel::get_property(const std::string& name) const {ov::PropertyName{ov::hint::dynamic_quantization_group_size.name(), PropertyMutability::RO},ov::PropertyName{ov::hint::activations_scale_factor.name(), PropertyMutability::RO},ov::PropertyName{ov::hint::kv_cache_precision.name(), PropertyMutability::RO},+ ov::PropertyName{ov::intel_gpu::offload_ratio.name(), PropertyMutability::RO},ov::PropertyName{ov::device::id.name(), PropertyMutability::RO},ov::PropertyName{ov::execution_devices.name(), PropertyMutability::RO},ov::PropertyName{ov::runtime_requirements.name(), PropertyMutability::RO},diff --git a/src/plugins/intel_gpu/src/plugin/ops/constant.cpp b/src/plugins/intel_gpu/src/plugin/ops/constant.cppindex 41b5cc225aa..027e70f8ac5 100644--- a/src/plugins/intel_gpu/src/plugin/ops/constant.cpp+++ b/src/plugins/intel_gpu/src/plugin/ops/constant.cpp@@ -26,10 +26,20 @@#include "openvino/op/tensor_iterator.hpp"#include "openvino/op/bucketize.hpp"#include "openvino/op/matmul.hpp"+#include "openvino/op/moe.hpp"#include "openvino/op/util/binary_elementwise_bitwise.hpp"+#include "ov_ops/moe_compressed.hpp"+#include "intel_gpu/primitives/data.hpp"#include "intel_gpu/runtime/debug_configuration.hpp"+#include "moe_offload_constant.hpp"++#include <algorithm>+#include <cctype>+#include <cstdlib>+#include <cstring>+#include <string>namespace ov::intel_gpu {@@ -100,8 +110,13 @@ static void create_data(ProgramBuilder& p, const ov::Shape& const_shape, const sp.primitive_ids[initialconstPrimID] = constPrimID;p.profiling_ids.push_back(initialconstPrimID);} else {+ auto partial_upload = try_prepare_partial_upload(p, op, const_shape, out_dtype, constFormat, constLayout);+cldnn::memory::ptr mem = nullptr;- if (constLayout.bytes_count() > 0) {++ if (partial_upload.enabled) {+ mem = partial_upload.memory;+ } else if (constLayout.bytes_count() > 0) {mem = p.get_engine().allocate_memory(constLayout, false);} else {// In the case of empty const data with {0} shape, it has zero byte.@@ -113,41 +128,46 @@ static void create_data(ProgramBuilder& p, const ov::Shape& const_shape, const sGPU_DEBUG_LOG << "[" << initialconstPrimID << ": constant] layout: "<< constLayout.to_short_string() << ", mem_ptr(" << mem << ", " << mem->size() << " bytes)"<< std::endl;- auto& stream = p.get_engine().get_service_stream();- cldnn::mem_lock<char> lock{mem, stream};- auto buf = lock.data();- auto bufSize = constLayout.bytes_count();-- // If a constant has element type f64 but contains no elements (empty tensor),- // convert it to f32 because the GPU plugin only supports the f32 data type internally.- if (ov::shape_size(const_shape) == 1 &&- out_dtype == cldnn::data_types::f32 &&- op->get_output_element_type(0) == ov::element::f64) {- const auto* f64data = op->get_data_ptr<double>();- auto f32buf = reinterpret_cast<float*>(buf);- f32buf[0] = static_cast<float>(f64data[0]);- } else if (out_dtype == cldnn::data_types::f32 &&- (op->get_output_element_type(0) == ov::element::u16 ||- op->get_output_element_type(0) == ov::element::i16)) {- size_t count = ov::shape_size(const_shape);- auto f32buf = reinterpret_cast<float*>(buf);-- if (op->get_output_element_type(0) == ov::element::u16) {- const auto* u16data = op->get_data_ptr<uint16_t>();- for (size_t i = 0; i < count; i++) {- f32buf[i] = static_cast<float>(u16data[i]);++ if (!partial_upload.enabled) {+ auto& stream = p.get_engine().get_service_stream();+ cldnn::mem_lock<char> lock{mem, stream};+ auto buf = lock.data();+ auto bufSize = constLayout.bytes_count();+ auto upload_count = ov::shape_size(const_shape);++ // If a constant has element type f64 but contains no elements (empty tensor),+ // convert it to f32 because the GPU plugin only supports the f32 data type internally.+ if (upload_count == 1 &&+ out_dtype == cldnn::data_types::f32 &&+ op->get_output_element_type(0) == ov::element::f64) {+ const auto* f64data = op->get_data_ptr<double>();+ auto f32buf = reinterpret_cast<float*>(buf);+ f32buf[0] = static_cast<float>(f64data[0]);+ } else if (out_dtype == cldnn::data_types::f32 &&+ (op->get_output_element_type(0) == ov::element::u16 ||+ op->get_output_element_type(0) == ov::element::i16)) {+ size_t count = upload_count;+ auto f32buf = reinterpret_cast<float*>(buf);++ if (op->get_output_element_type(0) == ov::element::u16) {+ const auto* u16data = op->get_data_ptr<uint16_t>();+ for (size_t i = 0; i < count; i++) {+ f32buf[i] = static_cast<float>(u16data[i]);+ }+ } else {+ const auto* i16data = op->get_data_ptr<int16_t>();+ for (size_t i = 0; i < count; i++) {+ f32buf[i] = static_cast<float>(i16data[i]);+ }}} else {- const auto* i16data = op->get_data_ptr<int16_t>();- for (size_t i = 0; i < count; i++) {- f32buf[i] = static_cast<float>(i16data[i]);- }+ std::memcpy(&buf[0], &data[0], bufSize);}- } else {- std::memcpy(&buf[0], &data[0], bufSize);}ov::wsh::Extension::hint_evict(*op);- p.add_primitive(*op, cldnn::data(initialconstPrimID, mem));+ auto data_prim = cldnn::data(initialconstPrimID, mem, partial_upload.enabled);+ p.add_primitive(*op, data_prim);p.blobMemCache[cache_key] = initialconstPrimID;constPrimID = initialconstPrimID;}diff --git a/src/plugins/intel_gpu/src/plugin/ops/moe.cpp b/src/plugins/intel_gpu/src/plugin/ops/moe.cppindex 500f2be8153..f0fbc1bdbb4 100644--- a/src/plugins/intel_gpu/src/plugin/ops/moe.cpp+++ b/src/plugins/intel_gpu/src/plugin/ops/moe.cpp@@ -7,6 +7,10 @@#include <intel_gpu/primitives/moe_gather.hpp>#include <intel_gpu/primitives/moe_scatter_reduction.hpp>#include <intel_gpu/primitives/swiglu.hpp>++#include <array>+#include <cstdlib>+#include <filesystem>#include <limits>#include "ov_ops/moe_compressed.hpp"@@ -16,10 +20,100 @@#include "intel_gpu/primitives/moe_gemm.hpp"#include "intel_gpu/primitives/moe_mask_gen.hpp"#include "openvino/op/constant.hpp"+#include "openvino/core/model.hpp"+#include "openvino/core/rt_info/weightless_caching_attributes.hpp"+#include "openvino/core/weight_sharing_util.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).+// 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,+ std::vector<size_t>& weight_bin_offsets,+ std::filesystem::path& weights_path,+ size_t& lru_expert_num) {+ using input_idx = cldnn::moe_3gemm_fused_compressed::input_index;+ const auto& config = op->get_config();+ const auto& model = p.get_model();+ 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);+ } else {+ lru_expert_num = 0;+ }+ const bool otd_enabled = lru_expert_num > 0;+ if (otd_enabled) {+ weights_path = std::filesystem::path(p.get_config().get_weights_path());+ OPENVINO_ASSERT(!weights_path.empty(),+ "ov::weights_path property is not set. OTD requires a valid path to the model .bin file. "+ "Please set ov::weights_path when compiling the model.");+ OPENVINO_ASSERT(std::filesystem::exists(weights_path),+ "OTD weights file does not exist: ", weights_path);+ }++ auto get_const_offset = [&](size_t index, size_t /*offset_slot*/) -> size_t {+ auto node = op->input_value(index).get_node_shared_ptr();+ auto const_op = std::dynamic_pointer_cast<ov::op::v0::Constant>(node);+ OPENVINO_ASSERT(const_op != nullptr, "Expected constant input for MOE3GemmFusedCompressed, got: ",+ node->get_type_name(), " name: ", node->get_friendly_name());++ // 1. Direct WeightlessCacheAttribute lookup+ const auto& rt_info = const_op->get_rt_info();+ auto attr_it = rt_info.find(ov::WeightlessCacheAttribute::get_type_info_static());+ if (attr_it != rt_info.end()) {+ return attr_it->second.as<ov::WeightlessCacheAttribute>().bin_offset;+ }++ // 2. Buffer descriptor offset (mmap path)+ auto source_buf = ov::weight_sharing::Extension::get_constant_source_buffer(*const_op);+ if (source_buf) {+ return ov::weight_sharing::Extension::get_constant_id(*const_op);+ }++ // 3. Plain "otd_bin_offset" rt_info entry (survives copy_runtime_info)+ auto otd_it = rt_info.find("otd_bin_offset");+ if (otd_it != rt_info.end()) {+ return static_cast<size_t>(otd_it->second.as<int64_t>());+ }++ OPENVINO_THROW("OTD: Cannot determine bin offset for MOE weight constant. "+ "Constant name: ", const_op->get_friendly_name(),+ ", input_index: ", index,+ ", shape: ", const_op->get_shape(),+ ", type: ", const_op->get_element_type(),+ ", byte_size: ", const_op->get_byte_size());+ };++ const std::array<size_t, cldnn::moe_3gemm_fused_compressed::serialized_weight_offset_count> const_input_idx_by_offset = {+ static_cast<size_t>(input_idx::weight_0),+ static_cast<size_t>(input_idx::weight_1),+ static_cast<size_t>(input_idx::weight_2),+ static_cast<size_t>(input_idx::scale_0),+ static_cast<size_t>(input_idx::scale_1),+ static_cast<size_t>(input_idx::scale_2),+ static_cast<size_t>(input_idx::zp_0),+ static_cast<size_t>(input_idx::zp_1),+ static_cast<size_t>(input_idx::zp_2)+ };++ weight_bin_offsets.assign(cldnn::moe_3gemm_fused_compressed::serialized_weight_offset_count, 0);+ // Serialized offsets are only needed for OTD path (weight-on-demand loading).+ if (otd_enabled) {+ for (size_t i = 0; i < const_input_idx_by_offset.size(); i++) {+ weight_bin_offsets[i] = get_const_offset(const_input_idx_by_offset[i], i);+ }+ }+ return otd_enabled;+}+static void CreateMOECompressedOp(ProgramBuilder& p, const std::shared_ptr<ov::op::internal::MOECompressed>& op) {auto inputs = p.GetInputInfo(op);auto& config = op->get_config();@@ -33,8 +127,14 @@ static void CreateMOECompressedOp(ProgramBuilder& p, const std::shared_ptr<ov::oconst size_t expected_inputs = base_inputs + shared_inputs;validate_inputs_count(op, {expected_inputs});+ // Resolve OTD (offload-to-disk) parameters; no-op when OFFLOAD_RATIO == 0.+ std::vector<size_t> weight_bin_offsets;+ std::filesystem::path weights_path;+ size_t lru_expert_num = 0;+ prepare_moe_otd_params(p, op, weight_bin_offsets, weights_path, lru_expert_num);+const std::string layerName = layer_type_name_ID(op);- const cldnn::moe_3gemm_fused_compressed moe(layerName, input_infos, config);+ const cldnn::moe_3gemm_fused_compressed moe(layerName, input_infos, config, weight_bin_offsets, weights_path, lru_expert_num);p.add_primitive(*op, moe);} else {// Create GEMM2_BIAS_SWIGLU_CLAMP specific primitivesdiff --git a/src/plugins/intel_gpu/src/plugin/ops/moe_offload_constant.cpp b/src/plugins/intel_gpu/src/plugin/ops/moe_offload_constant.cppnew file mode 100644index 00000000000..a538a6eed9b--- /dev/null+++ b/src/plugins/intel_gpu/src/plugin/ops/moe_offload_constant.cpp@@ -0,0 +1,88 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "moe_offload_constant.hpp"++namespace ov::intel_gpu {++// Input indices 3..11 are routed expert weights/scales/zps (WEIGHT_0..ZP_2).+// Input indices 12..21 are shared expert weights (SHARED_GATE_WEIGHT..SHARED_GATE_GATE_WEIGHT).+// See MOE3GemmInputIndex in moe_3gemm_base.hpp for the authoritative enum.+static constexpr size_t ROUTED_INPUT_START = 3;+static constexpr size_t ROUTED_INPUT_END = 11;+static constexpr size_t SHARED_INPUT_START = 12;+static constexpr size_t SHARED_INPUT_END = 21;++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* 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 (idx >= SHARED_INPUT_START && idx <= SHARED_INPUT_END)+ return MoEConstantRole::SharedExpert;+ }+ }+ return MoEConstantRole::NotMoE;+}++bool is_moe_related_constant(const std::shared_ptr<ov::op::v0::Constant>& op) {+ return get_moe_constant_role(op) != MoEConstantRole::NotMoE;+}++PartialUploadLogState& get_partial_upload_log_state() {+ static PartialUploadLogState state;+ return state;+}++PartialUploadDesc try_prepare_partial_upload(ProgramBuilder& p,+ const std::shared_ptr<ov::op::v0::Constant>& op,+ const ov::Shape& const_shape,+ cldnn::data_types out_dtype,+ const cldnn::format& const_format,+ const cldnn::layout& const_layout) {+ PartialUploadDesc desc;++ const size_t otd_ratio = p.get_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;+ 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+ const size_t resident_expert_num = std::max<size_t>(1, const_shape[0] * (100 - otd_ratio) / 100);++ desc.enabled = true;+ desc.upload_shape = const_shape;+ desc.upload_shape[0] = std::min<size_t>(const_shape[0], resident_expert_num);++ auto upload_layout = cldnn::layout(desc.upload_shape, out_dtype, const_format);+ auto upload_mem = p.get_engine().allocate_memory(upload_layout, false);+ // Reinterpret the smaller physical allocation as the full constant layout so the+ // graph sees the expected shape/layout. This is safe because:+ // 1. constant.cpp marks this data node with skip_device_transfer=true (partial_upload.enabled),+ // so no host→device memcpy of the full size occurs.+ // 2. At runtime, OTD loads on-demand into the first `resident_expert_num` slots only.+ // 3. Model cache serialization uses weightless caching (bin_offset metadata) for these+ // constants — it never reads the buffer contents via mem->buffer_ptr(). OTD requires+ // weights_path to be set, which enables weightless caching for all data nodes.+ OPENVINO_ASSERT(upload_layout.bytes_count() <= const_layout.bytes_count(),+ "Partial upload layout (", upload_layout.bytes_count(),+ " bytes) exceeds full constant layout (", const_layout.bytes_count(), " bytes)");+ desc.memory = p.get_engine().reinterpret_buffer(*upload_mem, const_layout);+ desc.upload_bytes = upload_layout.bytes_count();++ get_partial_upload_log_state().log(op->get_friendly_name(),+ desc.upload_shape[0],+ const_shape[0],+ desc.upload_bytes,+ const_layout.bytes_count());+ return desc;+}++} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/plugin/ops/moe_offload_constant.hpp b/src/plugins/intel_gpu/src/plugin/ops/moe_offload_constant.hppnew file mode 100644index 00000000000..20229dd6065--- /dev/null+++ b/src/plugins/intel_gpu/src/plugin/ops/moe_offload_constant.hpp@@ -0,0 +1,85 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <atomic>+#include <cstdint>+#include <memory>+#include <string>++#include "ov_ops/moe_compressed.hpp"+#include "intel_gpu/plugin/program_builder.hpp"+#include "intel_gpu/runtime/debug_configuration.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 };++/// Determines the role of a Constant feeding into MOECompressed.+MoEConstantRole get_moe_constant_role(const std::shared_ptr<ov::op::v0::Constant>& op);++struct PartialUploadDesc {+ bool enabled = false;+ cldnn::memory::ptr memory = nullptr;+ ov::Shape upload_shape{};+ size_t upload_bytes = 0;+};++bool is_moe_related_constant(const std::shared_ptr<ov::op::v0::Constant>& op);++class PartialUploadLogState {+public:+ static constexpr size_t max_detailed_logs = 3;++ void log(const std::string& node_name,+ size_t uploaded_experts,+ size_t total_experts,+ size_t upload_bytes,+ size_t target_bytes) {+ total_upload_bytes.fetch_add(static_cast<uint64_t>(upload_bytes), std::memory_order_relaxed);+ total_target_bytes.fetch_add(static_cast<uint64_t>(target_bytes), std::memory_order_relaxed);++ const size_t total = total_count.fetch_add(1, std::memory_order_relaxed) + 1;+ if (total <= max_detailed_logs) {+ GPU_DEBUG_INFO << "MOE OTD partial constant allocation at compile stage: "+ << node_name << ", experts=" << uploaded_experts+ << "/" << total_experts << ", upload_bytes=" << upload_bytes+ << ", target_bytes=" << target_bytes << std::endl;+ } else if (total == max_detailed_logs + 1) {+ GPU_DEBUG_INFO << "MOE OTD partial constant allocation: suppressing further per-constant logs, "+ << "final summary will be printed at process exit" << std::endl;+ }+ }++ ~PartialUploadLogState() {+ const size_t total = total_count.load(std::memory_order_relaxed);+ if (total > max_detailed_logs) {+ const size_t shown = max_detailed_logs;+ GPU_DEBUG_INFO << "MOE OTD partial constant allocation summary: total=" << total+ << ", shown=" << shown << ", suppressed=" << (total - shown)+ << ", total_upload_bytes=" << total_upload_bytes.load(std::memory_order_relaxed)+ << ", total_target_bytes=" << total_target_bytes.load(std::memory_order_relaxed)+ << std::endl;+ }+ }++private:+ std::atomic<size_t> total_count{0};+ std::atomic<uint64_t> total_upload_bytes{0};+ std::atomic<uint64_t> total_target_bytes{0};+};++PartialUploadLogState& get_partial_upload_log_state();++PartialUploadDesc try_prepare_partial_upload(ProgramBuilder& p,+ const std::shared_ptr<ov::op::v0::Constant>& op,+ const ov::Shape& const_shape,+ cldnn::data_types out_dtype,+ const cldnn::format& const_format,+ const cldnn::layout& const_layout);++} // namespace ov::intel_gpu\ No newline at end of filediff --git a/src/plugins/intel_gpu/src/plugin/plugin.cpp b/src/plugins/intel_gpu/src/plugin/plugin.cppindex 3b3f7391755..3320f62fb7d 100644--- a/src/plugins/intel_gpu/src/plugin/plugin.cpp+++ b/src/plugins/intel_gpu/src/plugin/plugin.cpp@@ -190,7 +190,6 @@ std::shared_ptr<ov::Model> Plugin::clone_and_transform_model(const std::shared_pif (weight_path.extension() != ".bin" && !is_weightless_cache_attributes_set(cloned_model))set_weightless_cache_attributes(cloned_model);}-transform_model(cloned_model, config_copy, context);// Transformations for some reason may drop output tensor names, so here we copy those from the original model@@ -784,6 +783,7 @@ std::vector<ov::PropertyName> Plugin::get_supported_properties() const {ov::PropertyName{ov::cache_encryption_callbacks.name(), PropertyMutability::WO},ov::PropertyName{ov::hint::kv_cache_precision.name(), PropertyMutability::RW},ov::PropertyName{ov::hint::model.name(), PropertyMutability::WO},+ ov::PropertyName{ov::intel_gpu::offload_ratio.name(), PropertyMutability::RW},ov::PropertyName{ov::intel_gpu::config_file.name(), PropertyMutability::RW},};diff --git a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cppindex c626f8c876c..9a098deb653 100644--- a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp+++ b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp@@ -213,6 +213,9 @@#include "openvino/op/matmul.hpp"#include "openvino/op/moe.hpp"#include "openvino/op/reverse_sequence.hpp"+#include "openvino/core/rt_info/weightless_caching_attributes.hpp"+#include "openvino/core/weight_sharing_util.hpp"+#include "ov_ops/moe_compressed.hpp"#include "openvino/op/roll.hpp"#include "openvino/op/shuffle_channels.hpp"#include "openvino/op/transpose.hpp"@@ -489,6 +492,43 @@ void TransformationsPipeline::apply(std::shared_ptr<ov::Model> func) {OV_ITT_SCOPED_TASK(itt::domains::intel_gpu_plugin, "TransformationsPipeline::apply");using const_node_ptr = const std::shared_ptr<const ov::Node>;+ // OTD: Stamp a plain "otd_bin_offset" rt_info entry on each constant that has+ // 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) {+ // First stamp WCA on constants with mmap descriptors but no WCA yet+ for (const auto& op : func->get_ops()) {+ auto const_node = ov::as_type_ptr<ov::op::v0::Constant>(op);+ if (!const_node)+ continue;+ if (const_node->get_rt_info().count(ov::WeightlessCacheAttribute::get_type_info_static()))+ continue;+ auto source_buf = ov::weight_sharing::Extension::get_constant_source_buffer(*const_node);+ if (source_buf) {+ size_t bin_offset = ov::weight_sharing::Extension::get_constant_id(*const_node);+ size_t byte_size = const_node->get_byte_size();+ auto dtype = const_node->get_element_type();+ const_node->get_rt_info()[ov::WeightlessCacheAttribute::get_type_info_static()] =+ ov::WeightlessCacheAttribute(byte_size, bin_offset, dtype);+ }+ }++ // Stamp "otd_bin_offset" as a plain int64_t on every constant with WCA.+ // Plain ov::Any entries survive copy_runtime_info automatically.+ for (const auto& op : func->get_ops()) {+ auto const_node = ov::as_type_ptr<ov::op::v0::Constant>(op);+ if (!const_node)+ continue;+ const auto& rt = const_node->get_rt_info();+ auto it = rt.find(ov::WeightlessCacheAttribute::get_type_info_static());+ if (it != rt.end()) {+ const auto& wca = it->second.as<ov::WeightlessCacheAttribute>();+ const_node->get_rt_info()["otd_bin_offset"] = static_cast<int64_t>(wca.bin_offset);+ }+ }+ }+const auto& defaultPrecisions = ov::pass::low_precision::precision_set::get_int8_support();const ov::element::TypeVector supported_woq_types ={ov::element::u8, ov::element::i8, ov::element::u4, ov::element::i4};diff --git a/src/plugins/intel_gpu/src/runtime/execution_config.cpp b/src/plugins/intel_gpu/src/runtime/execution_config.cppindex a93788e3419..a3861df867a 100644--- a/src/plugins/intel_gpu/src/runtime/execution_config.cpp+++ b/src/plugins/intel_gpu/src/runtime/execution_config.cpp@@ -175,11 +175,11 @@ void ExecutionConfig::apply_rt_info(const IRemoteContext* context, const ov::RTM// WEIGHTS_PATH is used for the weightless cache mechanism which is used only as defined by// ov::util::is_weightless_enabled. Not setting WEIGHTS_PATH will result in not- // using that mechanism.+ // using that mechanism. OTD (MoE offload) also requires the .bin path.if (const auto enable_weightless = ov::util::is_weightless_enabled(get_user_properties()); enable_weightless) {set_property({ov::enable_weightless(*enable_weightless)});}- if (get_enable_weightless()) {+ if (get_enable_weightless() || get_offload_ratio() > 0) {apply_rt_info_property(ov::weights_path, rt_info);}}diff --git a/src/plugins/intel_gpu/tests/unit/CMakeLists.txt b/src/plugins/intel_gpu/tests/unit/CMakeLists.txtindex baf5d8a1c6e..cd8d5d49e79 100644--- a/src/plugins/intel_gpu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_gpu/tests/unit/CMakeLists.txt@@ -32,6 +32,7 @@ file(GLOB_RECURSE SOURCES_MAIN"${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/usm_host_tensor.cpp""${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/common_utils.cpp""${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/simple_math.cpp"+ "${CMAKE_HOME_DIRECTORY}/src/plugins/intel_gpu/src/plugin/ops/moe_offload_constant.cpp")# Those tests have dependency on OpenCL runtimediff --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.cppnew file mode 100644index 00000000000..7780906268b--- /dev/null+++ b/src/plugins/intel_gpu/tests/unit/test_cases/moe_offload_constant_test.cpp@@ -0,0 +1,150 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <gtest/gtest.h>++#include "openvino/op/constant.hpp"+#include "openvino/op/parameter.hpp"+#include "ov_ops/moe_compressed.hpp"+#include "plugin/ops/moe_offload_constant.hpp"++using namespace ov::intel_gpu;++// Helper: build a minimal MOECompressed node with 22 inputs (indices 0..21).+// Inputs 0-2 are Parameters (hidden_states, routing_weights, topk_indices).+// Inputs 3-11 are routed expert Constants (weight/scale/zp × gate/up/down).+// Inputs 12-21 are shared expert Constants.+// Returns the MOECompressed node and the constants at each input position.+struct MoETestGraph {+ std::shared_ptr<ov::op::internal::MOECompressed> moe_node;+ std::vector<std::shared_ptr<ov::op::v0::Constant>> constants; // indices 3..21++ static MoETestGraph build(size_t num_experts = 4, size_t hidden_size = 128, size_t inter_size = 256, size_t group_size = 128) {+ MoETestGraph g;++ const size_t top_k = 2;+ ov::op::internal::MOECompressed::Config config{};+ config.hidden_size = hidden_size;+ config.inter_size = inter_size;+ config.num_expert = num_experts;+ config.num_shared_expert = 1;+ config.top_k = top_k;+ config.group_size = group_size;+ config.has_zp = true;+ config.out_type = ov::element::f16;++ size_t group_num = hidden_size / group_size;+ size_t group_num2 = inter_size / group_size;++ // Build input OutputVector (22 inputs)+ ov::OutputVector inputs;++ // 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});+ 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});+ 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});+ inputs.push_back(topk_idx->output(0));++ // Helper to create a constant with given shape and type+ auto make_const = [](ov::element::Type type, const ov::Shape& shape) {+ return std::make_shared<ov::op::v0::Constant>(type, shape, 0);+ };++ // Inputs 3-11: routed expert weights (gate/up/down × weight/scale/zp)+ // gate_w [E, inter, group_size, group_num]+ g.constants.push_back(make_const(ov::element::u8, {num_experts, inter_size, group_size, group_num})); // 3: w0_weight+ g.constants.push_back(make_const(ov::element::f16, {num_experts, inter_size, group_num, 1})); // 4: w0_scale+ g.constants.push_back(make_const(ov::element::u8, {num_experts, inter_size, group_num, 1})); // 5: w0_zp+ g.constants.push_back(make_const(ov::element::u8, {num_experts, inter_size, group_size, group_num})); // 6: w1_weight+ g.constants.push_back(make_const(ov::element::f16, {num_experts, inter_size, group_num, 1})); // 7: w1_scale+ g.constants.push_back(make_const(ov::element::u8, {num_experts, inter_size, group_num, 1})); // 8: w1_zp+ g.constants.push_back(make_const(ov::element::u8, {num_experts, hidden_size, group_size, group_num2})); // 9: w2_weight+ g.constants.push_back(make_const(ov::element::f16, {num_experts, hidden_size, group_num2, 1})); // 10: w2_scale+ g.constants.push_back(make_const(ov::element::u8, {num_experts, hidden_size, group_num2, 1})); // 11: w2_zp++ // Inputs 12-21: shared expert weights (same structure but num_experts=1 for shared)+ g.constants.push_back(make_const(ov::element::u8, {1, inter_size, group_size, group_num})); // 12: shared_gate_weight+ g.constants.push_back(make_const(ov::element::f16, {1, inter_size, group_num, 1})); // 13: shared_gate_scale+ g.constants.push_back(make_const(ov::element::u8, {1, inter_size, group_num, 1})); // 14: shared_gate_zp+ g.constants.push_back(make_const(ov::element::u8, {1, inter_size, group_size, group_num})); // 15: shared_up_weight+ g.constants.push_back(make_const(ov::element::f16, {1, inter_size, group_num, 1})); // 16: shared_up_scale+ g.constants.push_back(make_const(ov::element::u8, {1, inter_size, group_num, 1})); // 17: shared_up_zp+ g.constants.push_back(make_const(ov::element::u8, {1, hidden_size, group_size, group_num2})); // 18: shared_down_weight+ g.constants.push_back(make_const(ov::element::f16, {1, hidden_size, group_num2, 1})); // 19: shared_down_scale+ g.constants.push_back(make_const(ov::element::u8, {1, hidden_size, group_num2, 1})); // 20: shared_down_zp+ // Input 21 is sometimes shared_gate_gate (for gating the shared expert output)+ g.constants.push_back(make_const(ov::element::f16, {1, hidden_size})); // 21: shared_gate_gate_weight++ for (auto& c : g.constants) {+ inputs.push_back(c->output(0));+ }++ g.moe_node = std::make_shared<ov::op::internal::MOECompressed>(inputs, config);+ return g;+ }+};++// Test that routed expert constants (inputs 3-11) are classified as RoutedExpert+TEST(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";+ }+}++// Test that shared expert constants (inputs 12-21) are classified as SharedExpert+TEST(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";+ }+}++// Test that a constant NOT connected to MOECompressed is NotMoE+TEST(moe_offload_constant, unconnected_constant_is_not_moe) {+ auto c = std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{4, 128}, 0);+ EXPECT_EQ(get_moe_constant_role(c), MoEConstantRole::NotMoE);+}++// Test is_moe_related_constant for both routed and shared+TEST(moe_offload_constant, is_moe_related_covers_both) {+ auto g = MoETestGraph::build();++ // All constants connected to MOECompressed should be "MoE related"+ for (auto& c : g.constants) {+ EXPECT_TRUE(is_moe_related_constant(c));+ }++ // Unconnected constant is not MoE related+ auto unconnected = std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{4, 128}, 0);+ EXPECT_FALSE(is_moe_related_constant(unconnected));+}++// KEY TEST: Shared expert constants must NOT be classified as RoutedExpert+// 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+ for (size_t i = 9; i < g.constants.size(); i++) {+ auto role = get_moe_constant_role(g.constants[i]);+ EXPECT_NE(role, MoEConstantRole::RoutedExpert)+ << "Shared expert constant at input " << (i + 3)+ << " must NOT be classified as RoutedExpert (would be wrongly cropped by partial upload)";+ }+}diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/moe_offload_lru_cache_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/moe_offload_lru_cache_test.cppnew file mode 100644index 00000000000..ae78cac3643--- /dev/null+++ b/src/plugins/intel_gpu/tests/unit/test_cases/moe_offload_lru_cache_test.cpp@@ -0,0 +1,334 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "test_utils/test_utils.h"+#include "intel_gpu/runtime/internal_properties.hpp"+#include "ocl_v2/moe/lru_cache.hpp"++#include <thread>+#include <vector>+#include <set>+#include <atomic>++using namespace cldnn;+using namespace tests;+using ov::intel_gpu::ocl::moe::LRUCache;++// --------------------------------------------------+// Basic construction and initial state+// --------------------------------------------------++TEST(moe_lru_cache, initial_state) {+ LRUCache cache(4);++ ASSERT_EQ(cache.size(), 0U);+ ASSERT_FALSE(cache.is_initialized());+}++// --------------------------------------------------+// get_lru_item: insert (miss) and hit+// --------------------------------------------------++TEST(moe_lru_cache, single_insert_is_miss) {+ LRUCache cache(4);++ auto [slot, hit] = cache.get_lru_item(/*expert=*/0);+ ASSERT_FALSE(hit); // first access is a miss+ ASSERT_EQ(slot, 0U); // first slot assigned+ ASSERT_EQ(cache.size(), 1U);+}++TEST(moe_lru_cache, second_access_without_fill_is_miss) {+ // get_lru_item returns is_hit based on m_filled_list, not just presence+ LRUCache cache(4);++ cache.get_lru_item(0); // insert, slot 0+ auto [slot, hit] = cache.get_lru_item(0); // access again++ ASSERT_EQ(slot, 0U);+ ASSERT_FALSE(hit); // filled_list[0] is still false+}++TEST(moe_lru_cache, access_after_set_filled_is_hit) {+ LRUCache cache(4);++ auto [slot, miss] = cache.get_lru_item(0);+ cache.set_filled(slot);++ auto [slot2, hit] = cache.get_lru_item(0);+ ASSERT_EQ(slot2, slot);+ ASSERT_TRUE(hit);+}++// --------------------------------------------------+// Sequential slot allocation+// --------------------------------------------------++TEST(moe_lru_cache, slots_assigned_sequentially) {+ const size_t cap = 4;+ LRUCache cache(cap);++ for (size_t i = 0; i < cap; ++i) {+ auto [slot, hit] = cache.get_lru_item(/*expert=*/i);+ ASSERT_EQ(slot, i);+ ASSERT_FALSE(hit);+ }+ ASSERT_EQ(cache.size(), cap);+}++// --------------------------------------------------+// Eviction: oldest entry evicted when cache is full+// --------------------------------------------------++TEST(moe_lru_cache, eviction_when_full) {+ LRUCache cache(3);++ // Fill cache: experts 0, 1, 2+ cache.get_lru_item(0); // slot 0+ cache.get_lru_item(1); // slot 1+ cache.get_lru_item(2); // slot 2+ ASSERT_EQ(cache.size(), 3U);++ // Insert expert 3 -> evicts expert 0 (oldest), reuses slot 0+ auto [slot, hit] = cache.get_lru_item(3);+ ASSERT_FALSE(hit);+ ASSERT_EQ(slot, 0U); // expert 0's slot is recycled+ ASSERT_EQ(cache.size(), 3U); // size stays at capacity+}++TEST(moe_lru_cache, evicted_entry_becomes_miss) {+ LRUCache cache(2);++ // Fill: expert 0 (slot 0), expert 1 (slot 1)+ cache.get_lru_item(0);+ cache.set_filled(0);+ cache.get_lru_item(1);+ cache.set_filled(1);++ // Insert expert 2 -> evicts expert 0+ cache.get_lru_item(2);++ // Access expert 0 again -> should be a miss (it was evicted)+ auto [slot, hit] = cache.get_lru_item(0);+ ASSERT_FALSE(hit);+}++// --------------------------------------------------+// LRU ordering: recently accessed items survive eviction+// --------------------------------------------------++TEST(moe_lru_cache, lru_order_refresh_on_access) {+ LRUCache cache(3);++ // Insert experts 0, 1, 2 in order+ cache.get_lru_item(0); // slot 0 (LRU order: 0)+ cache.get_lru_item(1); // slot 1 (LRU order: 0, 1)+ cache.get_lru_item(2); // slot 2 (LRU order: 0, 1, 2)++ // Access expert 0 -> moves to most recent+ // (LRU order: 1, 2, 0)+ cache.get_lru_item(0);++ // Insert expert 3 -> should evict expert 1 (now the oldest)+ auto [slot, hit] = cache.get_lru_item(3);+ ASSERT_FALSE(hit);+ ASSERT_EQ(slot, 1U); // reuses expert 1's slot+}++TEST(moe_lru_cache, double_refresh_changes_eviction_order) {+ LRUCache cache(3);++ // Insert 0, 1, 2+ cache.get_lru_item(0); // slot 0+ cache.get_lru_item(1); // slot 1+ cache.get_lru_item(2); // slot 2++ // Refresh 0, then refresh 1 -> LRU order: 2, 0, 1+ cache.get_lru_item(0);+ cache.get_lru_item(1);++ // Insert 3 -> evicts expert 2 (oldest)+ auto [slot3, hit3] = cache.get_lru_item(3);+ ASSERT_FALSE(hit3);+ ASSERT_EQ(slot3, 2U); // reuses expert 2's slot++ // Insert 4 -> evicts expert 0 (now oldest)+ auto [slot4, hit4] = cache.get_lru_item(4);+ ASSERT_FALSE(hit4);+ ASSERT_EQ(slot4, 0U); // reuses expert 0's slot+}++// --------------------------------------------------+// Multi-layer: (layer, expert) pairs are independent+// --------------------------------------------------++// Since LRU cache is per-layer (each MoE layer has its own cache instance),+// the layer dimension has been removed from the cache key. This test verifies+// that distinct expert ids get independent slots.+TEST(moe_lru_cache, distinct_experts_get_independent_slots) {+ LRUCache cache(4);++ auto [s0, h0] = cache.get_lru_item(/*expert=*/0);+ auto [s1, h1] = cache.get_lru_item(/*expert=*/1);++ ASSERT_FALSE(h0);+ ASSERT_FALSE(h1);+ ASSERT_NE(s0, s1); // different slots for different experts+ ASSERT_EQ(cache.size(), 2U);+}++TEST(moe_lru_cache, same_expert_gets_same_slot) {+ LRUCache cache(4);++ cache.get_lru_item(5);+ cache.set_filled(0);++ auto [s0, h0] = cache.get_lru_item(5);++ ASSERT_TRUE(h0);+ ASSERT_EQ(s0, 0U);+}++// --------------------------------------------------+// set_filled / filled tracking+// --------------------------------------------------++TEST(moe_lru_cache, filled_cleared_on_eviction) {+ LRUCache cache(2);++ // Insert expert 0, mark filled+ auto [s0, miss0] = cache.get_lru_item(0);+ cache.set_filled(s0);++ // Insert expert 1+ cache.get_lru_item(1);++ // Insert expert 2 -> evicts expert 0, reuses slot s0+ auto [s2, h2] = cache.get_lru_item(2);+ ASSERT_EQ(s2, s0); // recycled slot+ ASSERT_FALSE(h2); // filled was cleared during eviction++ // Even after re-inserting to the same slot, accessing it returns not-filled+ auto [s2b, h2b] = cache.get_lru_item(2);+ ASSERT_FALSE(h2b); // not filled until set_filled is called+}++TEST(moe_lru_cache, set_filled_out_of_range_is_safe) {+ LRUCache cache(2);+ // Should not crash+ cache.set_filled(100);+ cache.set_filled(std::numeric_limits<size_t>::max());+}++// --------------------------------------------------+// evict_one: explicit eviction+// --------------------------------------------------++TEST(moe_lru_cache, explicit_evict_reduces_size) {+ LRUCache cache(4);++ cache.get_lru_item(0);+ cache.get_lru_item(1);+ ASSERT_EQ(cache.size(), 2U);++ cache.evict_one();+ ASSERT_EQ(cache.size(), 1U);++ cache.evict_one();+ ASSERT_EQ(cache.size(), 0U);+}++TEST(moe_lru_cache, evict_on_empty_is_safe) {+ LRUCache cache(4);+ // Should not crash+ cache.evict_one();+ ASSERT_EQ(cache.size(), 0U);+}++// --------------------------------------------------+// Capacity = 1 edge case+// --------------------------------------------------++TEST(moe_lru_cache, capacity_one) {+ LRUCache cache(1);++ auto [s0, h0] = cache.get_lru_item(0);+ ASSERT_EQ(s0, 0U);+ ASSERT_FALSE(h0);++ cache.set_filled(s0);++ // Access same -> hit+ auto [s0b, h0b] = cache.get_lru_item(0);+ ASSERT_EQ(s0b, 0U);+ ASSERT_TRUE(h0b);++ // Insert new -> evicts the only entry, reuses slot 0+ auto [s1, h1] = cache.get_lru_item(1);+ ASSERT_EQ(s1, 0U);+ ASSERT_FALSE(h1);+ ASSERT_EQ(cache.size(), 1U);+}++// --------------------------------------------------+// Stress: many inserts and evictions+// --------------------------------------------------++TEST(moe_lru_cache, stress_many_experts) {+ const size_t cap = 8;+ LRUCache cache(cap);++ // Insert 100 unique (layer=0, expert=i) entries into a cache with capacity 8+ for (size_t i = 0; i < 100; ++i) {+ auto [slot, hit] = cache.get_lru_item(i);+ ASSERT_LT(slot, cap);+ if (i < cap) {+ ASSERT_EQ(slot, i);+ }+ }+ ASSERT_EQ(cache.size(), cap);++ // The last `cap` experts should still be in the cache+ for (size_t i = 100 - cap; i < 100; ++i) {+ auto [slot, hit] = cache.get_lru_item(i);+ // They are in cache (though not filled)+ ASSERT_LT(slot, cap);+ }+}++// --------------------------------------------------+// Thread safety: concurrent get_lru_item calls+// --------------------------------------------------++TEST(moe_lru_cache, concurrent_access) {+ const size_t cap = 16;+ LRUCache cache(cap);+ const int num_threads = 4;+ const int ops_per_thread = 200;++ std::vector<std::thread> threads;+ std::atomic<bool> start{false};++ for (int t = 0; t < num_threads; ++t) {+ threads.emplace_back([&, t]() {+ while (!start.load()) {} // spin until all threads are ready+ for (int i = 0; i < ops_per_thread; ++i) {+ size_t expert = t * 32 + i % 32;+ auto [slot, hit] = cache.get_lru_item(expert);+ ASSERT_LT(slot, cap);+ if (!hit) {+ cache.set_filled(slot);+ }+ }+ });+ }++ start.store(true);+ for (auto& th : threads) {+ th.join();+ }++ ASSERT_LE(cache.size(), cap);+}+diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/moe_offload_primitive_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/moe_offload_primitive_test.cppnew file mode 100644index 00000000000..9c57b325b70--- /dev/null+++ b/src/plugins/intel_gpu/tests/unit/test_cases/moe_offload_primitive_test.cpp@@ -0,0 +1,91 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <gtest/gtest.h>++#include "intel_gpu/primitives/moe_3gemm_fused_compressed.hpp"++using cldnn::MOECompressed;++TEST(moe_offload_primitive_test, default_offload_fields) {+ cldnn::moe_3gemm_fused_compressed prim;+ ASSERT_TRUE(prim._otd.weight_bin_offsets.empty());+ ASSERT_TRUE(prim._otd.weights_path.empty());+ ASSERT_EQ(prim._otd.lru_expert_num, 0U);+}++TEST(moe_offload_primitive_test, construct_with_offload_params) {+ MOECompressed::Config config{};+ std::vector<size_t> offsets = {0, 100, 200, 300, 400, 500, 600, 700, 800};+ std::string path = "/path/to/weights.bin";+ size_t lru_num = 16;++ cldnn::moe_3gemm_fused_compressed prim(+ "test_moe",+ {cldnn::input_info("input0"), cldnn::input_info("input1")},+ config,+ offsets,+ path,+ lru_num);++ ASSERT_EQ(prim._otd.weight_bin_offsets.size(), 9U);+ ASSERT_EQ(prim._otd.weight_bin_offsets[0], 0U);+ ASSERT_EQ(prim._otd.weight_bin_offsets[8], 800U);+ ASSERT_EQ(prim._otd.weights_path, path);+ ASSERT_EQ(prim._otd.lru_expert_num, lru_num);+}++TEST(moe_offload_primitive_test, equality_with_offload_fields) {+ MOECompressed::Config config{};+ std::vector<size_t> offsets = {0, 100, 200, 300, 400, 500, 600, 700, 800};++ cldnn::moe_3gemm_fused_compressed prim1(+ "test_moe",+ {cldnn::input_info("input0")},+ config,+ offsets,+ "/path/a.bin",+ 16);++ cldnn::moe_3gemm_fused_compressed prim2(+ "test_moe",+ {cldnn::input_info("input0")},+ config,+ offsets,+ "/path/a.bin",+ 16);++ ASSERT_TRUE(prim1 == prim2);++ // Different weights_path -> not equal+ cldnn::moe_3gemm_fused_compressed prim3(+ "test_moe",+ {cldnn::input_info("input0")},+ config,+ offsets,+ "/path/b.bin",+ 16);+ ASSERT_FALSE(prim1 == prim3);++ // Different lru_expert_num -> not equal+ cldnn::moe_3gemm_fused_compressed prim4(+ "test_moe",+ {cldnn::input_info("input0")},+ config,+ offsets,+ "/path/a.bin",+ 32);+ ASSERT_FALSE(prim1 == prim4);++ // Different offsets -> not equal+ std::vector<size_t> offsets2 = {0, 100, 200, 300, 400, 500, 600, 700, 999};+ cldnn::moe_3gemm_fused_compressed prim5(+ "test_moe",+ {cldnn::input_info("input0")},+ config,+ offsets2,+ "/path/a.bin",+ 16);+ ASSERT_FALSE(prim1 == prim5);+}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.cppnew file mode 100644index 00000000000..73a623c2e50--- /dev/null+++ b/src/plugins/intel_gpu/tests/unit/test_cases/moe_offload_property_test.cpp@@ -0,0 +1,51 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "test_utils/test_utils.h"+#include "intel_gpu/runtime/internal_properties.hpp"++namespace ov::test {++using ::tests::get_test_default_config;+using ::tests::get_test_engine;++TEST(moe_offload_property_test, execution_config_roundtrip) {+ auto config = get_test_default_config(get_test_engine());++ ASSERT_EQ(config.get_offload_ratio(), 0U);++ config.set_property(ov::intel_gpu::offload_ratio(37));++ ASSERT_EQ(config.get_offload_ratio(), 37U);+}++TEST(moe_offload_property_test, default_value_is_zero) {+ auto config = get_test_default_config(get_test_engine());+ ASSERT_EQ(config.get_offload_ratio(), 0U);+}++TEST(moe_offload_property_test, set_and_get_various_values) {+ auto config = get_test_default_config(get_test_engine());++ config.set_property(ov::intel_gpu::offload_ratio(1));+ ASSERT_EQ(config.get_offload_ratio(), 1U);++ config.set_property(ov::intel_gpu::offload_ratio(50));+ ASSERT_EQ(config.get_offload_ratio(), 50U);++ config.set_property(ov::intel_gpu::offload_ratio(100));+ ASSERT_EQ(config.get_offload_ratio(), 100U);+}++TEST(moe_offload_property_test, set_back_to_zero_disables) {+ auto config = get_test_default_config(get_test_engine());++ config.set_property(ov::intel_gpu::offload_ratio(37));+ ASSERT_EQ(config.get_offload_ratio(), 37U);++ config.set_property(ov::intel_gpu::offload_ratio(0));+ ASSERT_EQ(config.get_offload_ratio(), 0U);+}++} // namespace ov::test\ No newline at end of filediff --git a/src/plugins/intel_gpu/tests/unit/test_cases/moe_offload_weight_provider_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/moe_offload_weight_provider_test.cppnew file mode 100644index 00000000000..9765de1ba6d--- /dev/null+++ b/src/plugins/intel_gpu/tests/unit/test_cases/moe_offload_weight_provider_test.cpp@@ -0,0 +1,132 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "test_utils/test_utils.h"+#include "ocl_v2/moe/expert_weight_providers.hpp"++using namespace cldnn;+using namespace tests;+using ov::intel_gpu::ocl::moe::OffloadExpertWeightProvider;+using ov::intel_gpu::ocl::moe::ResidentExpertWeightProvider;++TEST(moe_expert_weight_provider, resident_is_identity) {+ ResidentExpertWeightProvider provider;+ ASSERT_FALSE(provider.is_offloaded());+ ASSERT_EQ(provider.resident_capacity(), 0U);++ // Fully resident: try_acquire_simultaneous returns the expert ids unchanged, including duplicates+ // (no remap, no dedup) - the expert id is already the addressable slot.+ std::vector<uint32_t> experts = {3, 1, 4, 1, 5, 9, 2, 6};+ auto lease = provider.try_acquire_simultaneous(experts, get_test_stream());+ ASSERT_TRUE(lease.has_value());+ ASSERT_EQ(*lease, (std::vector<size_t>{3, 1, 4, 1, 5, 9, 2, 6}));+}++TEST(moe_expert_weight_provider, offload_construction_state) {+ MOECompressed::Config config{};+ std::vector<size_t> offsets = {0, 100, 200, 300, 400, 500, 600, 700, 800};+ OffloadExpertWeightProvider provider(/*capacity=*/16, config, offsets, "/path/to/weights.bin");++ ASSERT_TRUE(provider.is_offloaded());+ ASSERT_EQ(provider.resident_capacity(), 16U);+ // Resident buffers are bound lazily at first execute, not at construction.+ ASSERT_FALSE(provider.is_bound());+ ASSERT_FALSE(provider.cache().is_initialized());+}++TEST(moe_expert_weight_provider, offload_bind_resident_buffers) {+ MOECompressed::Config config{};+ OffloadExpertWeightProvider provider(/*capacity=*/8, config, {}, "/path/to/weights.bin");+ ASSERT_FALSE(provider.is_bound());++ cldnn::moe_weights resident; // null device pointers are fine; only the binding flag matters here+ provider.bind(resident);+ ASSERT_TRUE(provider.is_bound());+ ASSERT_TRUE(provider.cache().is_initialized());++ // Idempotent: a second bind keeps the provider bound.+ provider.bind(resident);+ ASSERT_TRUE(provider.is_bound());+}++TEST(moe_expert_weight_provider, resident_try_acquire_simultaneous_is_identity) {+ ResidentExpertWeightProvider provider;+ std::vector<uint32_t> experts = {3, 7, 3, 1, 7};+ auto lease = provider.try_acquire_simultaneous(experts, get_test_stream());+ ASSERT_TRUE(lease.has_value());+ ASSERT_EQ(*lease, (std::vector<size_t>{3, 7, 3, 1, 7}));+}++TEST(moe_expert_weight_provider, resident_acquire_one_is_identity) {+ ResidentExpertWeightProvider provider;+ ASSERT_EQ(provider.acquire_one(42, get_test_stream()), 42U);+ ASSERT_EQ(provider.acquire_one(0, get_test_stream()), static_cast<size_t>(0));+}++TEST(moe_expert_weight_provider, offload_try_acquire_simultaneous_capacity_overflow) {+ // Capacity=2 means at most 2 unique experts can be acquired simultaneously.+ // Requesting 3 unique experts must return nullopt (capacity overflow).+ MOECompressed::Config config{};+ OffloadExpertWeightProvider provider(/*capacity=*/2, config, {0, 100, 200, 300}, "/nonexistent");++ cldnn::moe_weights resident{};+ provider.bind(resident);++ // Pre-populate the LRU cache so experts 0,1 are hits (no disk I/O needed)+ auto& cache = provider.cache();+ cache.get_lru_item(0);+ cache.set_filled(0);+ cache.get_lru_item(1);+ cache.set_filled(1);++ // 3 unique experts (0, 1, 2) exceeds capacity=2 -> nullopt+ std::vector<uint32_t> experts = {0, 1, 2, 0, 1};+ auto lease = provider.try_acquire_simultaneous(experts, get_test_stream());+ ASSERT_FALSE(lease.has_value());+}++TEST(moe_expert_weight_provider, offload_try_acquire_simultaneous_within_capacity) {+ // Same setup but with only 2 unique experts -> should succeed+ MOECompressed::Config config{};+ OffloadExpertWeightProvider provider(/*capacity=*/2, config, {0, 100, 200, 300}, "/nonexistent");++ cldnn::moe_weights resident{};+ provider.bind(resident);++ // Pre-populate cache+ auto& cache = provider.cache();+ cache.get_lru_item(0);+ cache.set_filled(0);+ cache.get_lru_item(1);+ cache.set_filled(1);++ // 2 unique experts (0, 1) with duplicates -> within capacity=2+ std::vector<uint32_t> experts = {0, 1, 0, 1, 0};+ auto lease = provider.try_acquire_simultaneous(experts, get_test_stream());+ ASSERT_TRUE(lease.has_value());+ // Slots should be valid (cache returned slots for experts 0 and 1)+ ASSERT_EQ(lease->size(), 5U);+ // Duplicates must map to the same slot+ ASSERT_EQ((*lease)[0], (*lease)[2]);+ ASSERT_EQ((*lease)[0], (*lease)[4]);+ ASSERT_EQ((*lease)[1], (*lease)[3]);+}++TEST(moe_expert_weight_provider, offload_acquire_one_basic) {+ // acquire_one always succeeds (evicts LRU if needed)+ MOECompressed::Config config{};+ OffloadExpertWeightProvider provider(/*capacity=*/2, config, {0, 100, 200, 300}, "/nonexistent");++ cldnn::moe_weights resident{};+ provider.bind(resident);++ // Pre-populate cache+ auto& cache = provider.cache();+ auto [slot0, hit0] = cache.get_lru_item(5);+ cache.set_filled(slot0);++ // acquire_one should return a valid slot+ auto slot = provider.acquire_one(5, get_test_stream());+ ASSERT_EQ(slot, slot0);+}