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] MoE offload: stream only the expert weights from the weights file (#39506)
Vladislav Golubevecc720fc5c0d
diff --git a/docs/articles_en/openvino-workflow/running-inference/inference-devices-and-modes/gpu-device.rst b/docs/articles_en/openvino-workflow/running-inference/inference-devices-and-modes/gpu-device.rstindex 1fac71a2f95..dfd2d1a30b7 100644--- a/docs/articles_en/openvino-workflow/running-inference/inference-devices-and-modes/gpu-device.rst+++ b/docs/articles_en/openvino-workflow/running-inference/inference-devices-and-modes/gpu-device.rst@@ -441,6 +441,14 @@ caching or selecting ``ov::CacheMode::OPTIMIZE_SPEED`` is not supported with offincluding when importing a compiled model or loading it from cache.MoE offloading requires a valid weights file and the corresponding constant offsets.+Only the routed expert weights are offloaded. The scales and zero points of all the experts stay+in GPU memory, and so do the slot copies of the cached experts. This costs about 3-5% of the routed+expert weights, but the resident weights shrink as the ratio grows: at ``OFFLOAD_RATIO=90`` the same+amount is roughly 13-16% of the remaining footprint. Take it into account when budgeting GPU memory.++An offloaded MoE layer supports a single stream. Make sure that the number of streams is 1 when using+``ov::intel_gpu::offload_ratio``.+Read-only Properties+++++++++++++++++++++++++++++++++++++++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 b92f87ba9c4..dd8557e9a3a 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@@ -9,6 +9,7 @@#include "openvino/core/graph_util.hpp"#include "openvino/core/rt_info.hpp"+#include "openvino/core/rt_info/weightless_caching_attributes.hpp"#include "openvino/core/type/element_type.hpp"#include "openvino/op/constant.hpp"#include "openvino/op/convert.hpp"@@ -70,11 +71,7 @@ ConvertFullyConnectedToFullyConnectedCompressed::process_compressed_weights(new_IC = n_groups * group_size;}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;- }+ ov::copy_weightless_cache_attr(constant, new_constant);return new_constant;};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 488a4772d23..322b9527b69 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@@ -62,7 +62,8 @@ struct moe_otd_descriptor {struct 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;+ // Only the gate/up/down weights are streamed from the weights file: scales and zero points stay resident+ static constexpr size_t serialized_weight_offset_count = 3;enum class input_index : size_t {hidden_states = 0,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 05c0fb3ea6c..01253f9439d 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@@ -736,10 +736,6 @@ 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.hppindex 687cfa5e8ca..f08b7a6333a 100644--- 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.hpp@@ -25,6 +25,15 @@ struct RoutedWeightViews {cldnn::memory::ptr zp[3];};+// A scale / zero point shared by all the experts (scalar) is used as is, it has no per-expert slices+bool is_per_expert(const cldnn::layout& layout, size_t num_expert);++// Whether the slice of each expert is one contiguous byte range, which the slot copies require+bool has_contiguous_expert_slices(const cldnn::layout& layout, size_t num_expert);++// Layout of the slot buffer of an input with a slice per expert: the same slice, `capacity` times+cldnn::layout get_slot_layout(const cldnn::layout& input, size_t capacity, size_t num_expert);+// 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.//@@ -53,17 +62,19 @@ public:// 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;+ // `inputs` are the primitive inputs, `slots` the slot buffers that a miss loads; a scale / zero point without a slot buffer is+ // shared by all the experts.+ virtual std::optional<ExpertSlotLease> try_acquire_simultaneous(const std::vector<uint32_t>& experts,+ const RoutedWeightViews& inputs,+ const RoutedWeightViews& slots,+ 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;+ virtual size_t acquire_one(uint32_t expert, const RoutedWeightViews& inputs, const RoutedWeightViews& slots, cldnn::stream& stream) = 0;// Binds device-resident weight buffers. Called once on first execution.virtual void bind(cldnn::moe_weights& resident) = 0;diff --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.cppindex 38640ac9677..ca914323b6d 100644--- 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.cpp@@ -15,12 +15,33 @@namespace ov::intel_gpu::ocl::moe {-std::optional<ExpertSlotLease> ResidentExpertWeightProvider::try_acquire_simultaneous(const std::vector<uint32_t>& experts, cldnn::stream& /*stream*/) {+bool is_per_expert(const cldnn::layout& layout, size_t num_expert) {+ return layout.is_static() && layout.count() > 1 && !layout.get_shape().empty() && layout.get_shape()[0] == num_expert;+}++bool has_contiguous_expert_slices(const cldnn::layout& layout, size_t num_expert) {+ return cldnn::format::is_simple_data_format(layout.format) && layout.format.order().front() == 'b' && layout.bytes_count() % num_expert == 0;+}++cldnn::layout get_slot_layout(const cldnn::layout& input, size_t capacity, size_t num_expert) {+ OPENVINO_ASSERT(has_contiguous_expert_slices(input, num_expert), "OTD: expert slices of ", input.to_short_string(), " are not contiguous");+ auto slots_shape = input.get_shape();+ slots_shape[0] = capacity;+ return cldnn::layout(slots_shape, input.data_type, input.format);+}++std::optional<ExpertSlotLease> ResidentExpertWeightProvider::try_acquire_simultaneous(const std::vector<uint32_t>& experts,+ const RoutedWeightViews& /*inputs*/,+ const RoutedWeightViews& /*slots*/,+ 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*/) {+size_t ResidentExpertWeightProvider::acquire_one(uint32_t expert,+ const RoutedWeightViews& /*inputs*/,+ const RoutedWeightViews& /*slots*/,+ cldnn::stream& /*stream*/) {return expert;}@@ -35,29 +56,53 @@ OffloadExpertWeightProvider::OffloadExpertWeightProvider(size_t capacity,_cache(std::make_shared<LRUCache>(capacity)),_weight_reader(_weights_path) {}-void OffloadExpertWeightProvider::bind(cldnn::moe_weights& resident) {- _resident = &resident;+void OffloadExpertWeightProvider::bind(cldnn::moe_weights& /*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;+void OffloadExpertWeightProvider::reset_cache_if_slots_changed(const RoutedWeightViews& slots) {+ std::vector<const void*> handles;+ for (size_t i = 0; i < 3; i++) {+ for (const auto& mem : {slots.weight[i], slots.scale[i], slots.zp[i]}) {+ if (mem) {+ handles.push_back(mem->get_internal_params().mem);+ }+ }+ }+ if (handles != _slot_handles) {+ _slot_handles = std::move(handles);+ _cache = std::make_shared<LRUCache>(_capacity);+ _cache->set_initialized();+ }+}++void OffloadExpertWeightProvider::load(uint32_t expert, size_t slot, const RoutedWeightViews& inputs, const RoutedWeightViews& slots, cldnn::stream& stream) {+ OPENVINO_ASSERT(_weight_bin_offsets.size() == cldnn::moe_3gemm_fused_compressed::serialized_weight_offset_count, "Unexpected number of MOE weight offsets");+ const size_t num_expert = _config.num_expert;+ // The weights are streamed as stored in the weights file, the scales and zero points are copied as converted by the pipeline+ std::vector<moe_otd::SlicedTensor> tensors;+ for (size_t i = 0; i < 3; i++) {+ if (slots.weight[i]) {+ tensors.push_back({slots.weight[i], slots.weight[i]->get_layout().bytes_count() / num_expert, nullptr, _weight_bin_offsets[i]});+ }+ for (const auto& [slot_mem, source] : {std::pair{slots.scale[i], inputs.scale[i]}, std::pair{slots.zp[i], inputs.zp[i]}}) {+ if (slot_mem) {+ tensors.push_back({slot_mem, source->get_layout().bytes_count() / num_expert, source});+ }+ }+ }+ moe_otd::fill_weights_memory(stream, _weight_reader, tensors, expert, slot);}-std::optional<ExpertSlotLease> OffloadExpertWeightProvider::try_acquire_simultaneous(const std::vector<uint32_t>& experts, cldnn::stream& stream) {+std::optional<ExpertSlotLease> OffloadExpertWeightProvider::try_acquire_simultaneous(const std::vector<uint32_t>& experts,+ const RoutedWeightViews& inputs,+ const RoutedWeightViews& slot_buffers,+ cldnn::stream& stream) {+ reset_cache_if_slots_changed(slot_buffers);+// Deduplicate to check capacitystd::unordered_map<uint32_t, size_t> expert_to_slot;expert_to_slot.reserve(experts.size());@@ -89,8 +134,7 @@ std::optional<ExpertSlotLease> OffloadExpertWeightProvider::try_acquire_simultanif (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});+ load(expert, slot, inputs, slot_buffers, stream);_cache->set_filled(slot);}@@ -101,7 +145,8 @@ std::optional<ExpertSlotLease> OffloadExpertWeightProvider::try_acquire_simultanreturn slots;}-size_t OffloadExpertWeightProvider::acquire_one(uint32_t expert, cldnn::stream& stream) {+size_t OffloadExpertWeightProvider::acquire_one(uint32_t expert, const RoutedWeightViews& inputs, const RoutedWeightViews& slots, cldnn::stream& stream) {+ reset_cache_if_slots_changed(slots);auto* perf = moe_otd::get_perf_counters();const auto item = _cache->get_lru_item(expert);@@ -115,8 +160,7 @@ size_t OffloadExpertWeightProvider::acquire_one(uint32_t expert, cldnn::stream&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});+ load(expert, slot, inputs, slots, stream);_cache->set_filled(slot);}diff --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.hppindex aaefc3c61a4..656f8ef6566 100644--- 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.hpp@@ -33,20 +33,12 @@ public: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;+ std::optional<ExpertSlotLease> try_acquire_simultaneous(const std::vector<uint32_t>& experts,+ const RoutedWeightViews& inputs,+ const RoutedWeightViews& slots,+ cldnn::stream& stream) override;+ size_t acquire_one(uint32_t expert, const RoutedWeightViews& inputs, const RoutedWeightViews& slots, cldnn::stream& stream) override;};// Offload (OTD) provider: expert weights live on disk and are streamed on demand@@ -54,9 +46,11 @@ public:// 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+// The resident weight 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+// input memory. The scales and zero points stay fully resident in the primitive inputs; the per-expert ones+// are copied on a miss into slot buffers that the primitive instance owns and passes to every acquisition.+// Loading metadata (config / bin offsets / weights path) is captured// at construction from graph-build time information.class OffloadExpertWeightProvider : public IExpertWeightProvider {public:@@ -77,9 +71,11 @@ public: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;+ std::optional<ExpertSlotLease> try_acquire_simultaneous(const std::vector<uint32_t>& experts,+ const RoutedWeightViews& inputs,+ const RoutedWeightViews& slot_buffers,+ cldnn::stream& stream) override;+ size_t acquire_one(uint32_t expert, const RoutedWeightViews& inputs, const RoutedWeightViews& slots, cldnn::stream& stream) override;LRUCache& cache() {return *_cache;@@ -90,14 +86,19 @@ public:}private:+ // The engine may re-allocate an internal buffer, and then the experts loaded into it are gone+ void reset_cache_if_slots_changed(const RoutedWeightViews& slots);+ void load(uint32_t expert, size_t slot, const RoutedWeightViews& inputs, const RoutedWeightViews& slots, cldnn::stream& stream);+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;+ // Handles of the slot buffers the LRU describes, compared only to detect a re-allocation+ std::vector<const void*> _slot_handles;};} // namespace ov::intel_gpu::ocl::moediff --git a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_base.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_base.hppindex 69c0d418174..e718ea1ac84 100644--- a/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_base.hpp+++ b/src/plugins/intel_gpu/src/graph/impls/ocl_v2/moe/moe_3gemm_base.hpp@@ -25,6 +25,10 @@ namespace ov::intel_gpu::ocl {#define MOE_INTERNAL_BUFFER_ACTUAL_USED_EXPERT_NUM 11 // num_actual_used_experts#define MOE_INTERNAL_BUFFER_GROUPED_OFFSETS 12 // int32_t cumulative end-offsets per expert for OneDNN grouped GEMM#define MOE_INTERNAL_BUFFER_ROW_LUT 13 // gathered row index per (token, topk), inverse of token idx per expert+// Scale / zero point slots of an offloaded layer (gate/up/down), at fixed indices so that they keep the loaded experts+#define MOE_INTERNAL_BUFFER_OTD_SCALE_SLOTS 14+#define MOE_INTERNAL_BUFFER_OTD_ZP_SLOTS 17+#define MOE_INTERNAL_BUFFER_OTD_END 20#define ENABLE_MOE_MICRO_GEMM_POST_PROC_SILU_MUL 1diff --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 f617c627561..d75eee5b04a 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@@ -12,9 +12,13 @@#include "expert_weight_providers.hpp"// clang-format on+using ov::intel_gpu::ocl::moe::get_slot_layout;+using ov::intel_gpu::ocl::moe::has_contiguous_expert_slices;using ov::intel_gpu::ocl::moe::IExpertWeightProvider;+using ov::intel_gpu::ocl::moe::is_per_expert;using ov::intel_gpu::ocl::moe::OffloadExpertWeightProvider;using ov::intel_gpu::ocl::moe::ResidentExpertWeightProvider;+using ov::intel_gpu::ocl::moe::RoutedWeightViews;#define DEBUG_MOE_LOG 0@@ -791,17 +795,56 @@ public:// --- OTD helper methods (used when _weight_provider->is_offloaded()) ---- static void set_otd_weight_pointers(typed_primitive_inst<moe_3gemm_fused_compressed>& instance, scratch_buffers& scratch) {+ static RoutedWeightViews get_routed_inputs(const typed_primitive_inst<moe_3gemm_fused_compressed>& instance) {+ RoutedWeightViews inputs;+ for (size_t i = 0; i < 3; i++) {+ const auto weight_input = static_cast<size_t>(MOE3GemmInputIndex::WEIGHT_0) + 3 * i;+ inputs.weight[i] = instance.input_memory_ptr(weight_input);+ inputs.scale[i] = instance.input_memory_ptr(weight_input + 1);+ inputs.zp[i] = instance.input_memory_ptr(weight_input + 2);+ }+ return inputs;+ }++ // Weights: the partially uploaded constants bound at the first execution. Scales / zero points: the internal slot buffers,+ // none for one shared by all the experts. Read per execution, the engine may re-allocate an internal buffer.+ static RoutedWeightViews get_slot_views(const typed_primitive_inst<moe_3gemm_fused_compressed>& instance) {+ const auto& intermediates = instance.get_intermediates_memories();+ OPENVINO_ASSERT(intermediates.size() >= MOE_INTERNAL_BUFFER_OTD_END, "OTD: the slot buffers of ", instance.id(), " are not allocated");+ const auto num_expert = static_cast<size_t>(instance.get_typed_desc<moe_3gemm_fused_compressed>()->_config.num_expert);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;+ const auto per_expert = [&](size_t input) {+ const auto& mem = instance.input_memory_ptr(input);+ return mem && is_per_expert(mem->get_layout(), num_expert);+ };+ RoutedWeightViews slots;+ slots.weight[0] = w.gate_w;+ slots.weight[1] = w.up_w;+ slots.weight[2] = w.down_w;+ for (size_t i = 0; i < 3; i++) {+ const auto scale_input = static_cast<size_t>(MOE3GemmInputIndex::SCALE_0) + 3 * i;+ if (per_expert(scale_input)) {+ slots.scale[i] = intermediates[MOE_INTERNAL_BUFFER_OTD_SCALE_SLOTS + i];+ }+ if (per_expert(scale_input + 1)) {+ slots.zp[i] = intermediates[MOE_INTERNAL_BUFFER_OTD_ZP_SLOTS + i];+ }+ }+ return slots;+ }++ static void set_otd_weight_pointers(typed_primitive_inst<moe_3gemm_fused_compressed>& instance, scratch_buffers& scratch) {+ OPENVINO_ASSERT(instance._weights.gate_w,+ "MoE offload (OFFLOAD_RATIO) supports a single stream only: the expert slots of ",+ instance.id(),+ " are bound to another network");+ const auto inputs = get_routed_inputs(instance);+ const auto slots = get_slot_views(instance);+ for (size_t i = 0; i < 3; i++) {+ scratch.moe_fusion_wei_addr.weight[i] = slots.weight[i];+ scratch.moe_fusion_wei_addr.scale[i] = slots.scale[i] ? slots.scale[i] : inputs.scale[i];+ scratch.moe_fusion_wei_addr.zp[i] = slots.zp[i] ? slots.zp[i] : inputs.zp[i];+ }}size_t resident_slot_count() const {@@ -874,7 +917,7 @@ public: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);+ auto lease = _weight_provider->try_acquire_simultaneous(expert_ids, get_routed_inputs(instance), get_slot_views(instance), stream);if (!lease) {if (auto* perf = moe_otd::get_perf_counters()) {perf->batched_fallbacks.fetch_add(1, std::memory_order_relaxed);@@ -915,7 +958,7 @@ public: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);+ auto lease = _weight_provider->try_acquire_simultaneous(expert_ids, get_routed_inputs(instance), get_slot_views(instance), stream);if (!lease) {if (auto* perf = moe_otd::get_perf_counters()) {perf->grouped_fallbacks.fetch_add(1, std::memory_order_relaxed);@@ -940,7 +983,10 @@ public:needs_fallback = false;}- bool on_load_expert_weights(size_t expert_no, typed_primitive_inst<moe_3gemm_fused_compressed>& instance, dnnl::stream& dnn_stream) {+ bool on_load_expert_weights(size_t expert_no,+ typed_primitive_inst<moe_3gemm_fused_compressed>& instance,+ const moe_fusion_weights_base_addr& addr,+ dnnl::stream& dnn_stream) {if (!_weight_provider->is_offloaded()) {return false;}@@ -949,25 +995,25 @@ public: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;+ auto lru_expert_no = static_cast<int64_t>(+ _weight_provider->acquire_one(static_cast<uint32_t>(expert_no), get_routed_inputs(instance), get_slot_views(instance), stream));const bool has_zp = instance.get_typed_desc<moe_3gemm_fused_compressed>()->_config.has_zp;-# 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()); \- 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); \- if (has_zp) { \- dnnl_weights[i].zp = convert_zp2dnnl(params.name##_z, dnnl_weights[i].ic / dnnl_weights[i].ic_group_size, dnnl_weights[i].oc, lru_expert_no); \- }- CONVERT_DNNL_OTD(gate, 0)- CONVERT_DNNL_OTD(up, 1)- CONVERT_DNNL_OTD(down, 2)+# define CONVERT_DNNL_OTD(i) \+ int64_t wei_offset##i = lru_expert_no * get_bytes_count(dnnl_weights[i].ic * dnnl_weights[i].oc, addr.weight[i]->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, addr.scale[i]->get_layout()); \+ dnnl_weights[i].weight = convert2dnnl(addr.weight[i], {dnnl_weights[i].ic, dnnl_weights[i].oc}, dnnl::memory::format_tag::ba, wei_offset##i); \+ dnnl_weights[i].scale = convert2dnnl(addr.scale[i], \+ {dnnl_weights[i].ic / dnnl_weights[i].ic_group_size, dnnl_weights[i].oc}, \+ dnnl::memory::format_tag::ab, \+ scale_offset##i); \+ if (has_zp) { \+ dnnl_weights[i].zp = convert_zp2dnnl(addr.zp[i], dnnl_weights[i].ic / dnnl_weights[i].ic_group_size, dnnl_weights[i].oc, lru_expert_no); \+ }+ CONVERT_DNNL_OTD(0)+ CONVERT_DNNL_OTD(1)+ CONVERT_DNNL_OTD(2)# undef CONVERT_DNNL_OTDreturn true;}@@ -1001,7 +1047,7 @@ public:// 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);+ auto lease = _weight_provider->try_acquire_simultaneous(raw_topk_ids, get_routed_inputs(instance), get_slot_views(instance), stream);if (!lease) {GPU_DEBUG_TRACE_DETAIL << "exec_grouped_gemm_cpu_mask_gen OTD: unique experts exceed resident_slots=" << resident_slot_count()<< ", falling back to per-expert onednn loop" << std::endl;@@ -1169,6 +1215,10 @@ public:const auto& weight_dt = params.get_input_layout(static_cast<size_t>(MOE3GemmInputIndex::WEIGHT_0)).data_type;decode_impl = select_decode_impl(params, weight_dt);prefill_impl = select_prefill_impl(config, weight_dt, params.prog->get_engine().get_device_info().arch);+ // The micro-GEMM reads the scales and zero points of every expert, not of the expert slots+ if (prefill_impl == MoeGemmImpl::micro_gemm && node.as<moe_3gemm_fused_compressed>().get_primitive()->_otd.lru_expert_num > 0) {+ prefill_impl = MoeGemmImpl::per_expert_onednn;+ }GPU_DEBUG_TRACE_DETAIL << "[DEBUG] moe_3gemm_swiglu_opt_impl(): prefill_impl=" << static_cast<int>(prefill_impl)<< ", decode_impl=" << static_cast<int>(decode_impl) << std::endl;@@ -1195,6 +1245,26 @@ public:} else {_weight_provider = std::make_shared<ResidentExpertWeightProvider>();}+ // The slot buffers of a dynamic model are laid out at the first inference: check their layouts at compilation+ if (_weight_provider->is_offloaded()) {+ const auto num_expert = static_cast<size_t>(cur_moe->_config.num_expert);+ for (const auto input : {MOE3GemmInputIndex::SCALE_0,+ MOE3GemmInputIndex::ZP_0,+ MOE3GemmInputIndex::SCALE_1,+ MOE3GemmInputIndex::ZP_1,+ MOE3GemmInputIndex::SCALE_2,+ MOE3GemmInputIndex::ZP_2}) {+ const auto& layout = params.get_input_layout(static_cast<size_t>(input));+ OPENVINO_ASSERT(!is_per_expert(layout, num_expert) || has_contiguous_expert_slices(layout, num_expert),+ "MoE offload of ",+ node.id(),+ ": the expert slices of input ",+ static_cast<size_t>(input),+ " (",+ layout.to_short_string(),+ ") are not contiguous");+ }+ }// Don't change the order of stagesadd_stage(gather, params);@@ -1577,6 +1647,29 @@ public:internal_buffers.emplace_back(layout_grouped_offsets, false); // 12: grouped end-offsetsinternal_buffers.emplace_back(layout_token_idx, false); // 13: row_lut}++ if (_weight_provider->is_offloaded()) {+ // The slots keep the loaded experts between the executions, so they have fixed indices whatever the other buffers are+ const layout layout_unused(ov::Shape{1}, ov::element::i32, cldnn::format::bfyx);+ OPENVINO_ASSERT(internal_buffers.size() <= MOE_INTERNAL_BUFFER_OTD_SCALE_SLOTS, "MoE buffers overflow into the reserved OTD slot indices");+ while (internal_buffers.size() < MOE_INTERNAL_BUFFER_OTD_SCALE_SLOTS) {+ internal_buffers.emplace_back(layout_unused, false);+ }+ // Not shareable: the engine must neither pool the slots with other buffers nor free them between the executions+ const auto slots = [&](size_t input) {+ const auto& input_layout = params.input_layouts[input];+ if (!is_per_expert(input_layout, expert_num)) {+ return BufferDescriptor(layout_unused, false, false);+ }+ return BufferDescriptor(get_slot_layout(input_layout, _weight_provider->resident_capacity(), expert_num), false, false);+ };+ for (size_t i = 0; i < 3; i++) {+ internal_buffers.push_back(slots(static_cast<size_t>(MOE3GemmInputIndex::SCALE_0) + 3 * i)); // 14-16: scales+ }+ for (size_t i = 0; i < 3; i++) {+ internal_buffers.push_back(slots(static_cast<size_t>(MOE3GemmInputIndex::ZP_0) + 3 * i)); // 17-19: zero points+ }+ }return internal_buffers;}@@ -2625,7 +2718,7 @@ public:continue;}- on_load_expert_weights(expert_no, instance, dnn_stream);+ on_load_expert_weights(expert_no, instance, scratch.moe_fusion_wei_addr, dnn_stream);auto& dnnl_weights = _dnnl_weights[expert_no];// expert_maskdiff --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.cppindex 0d8432a84a3..520d9738362 100644--- 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.cpp@@ -7,8 +7,6 @@#include <array>#include <chrono>#include <cstdlib>-#include <cstring>-#include <limits>#include "intel_gpu/runtime/debug_configuration.hpp"@@ -21,7 +19,6 @@ void OtdPerfCounters::dump() const {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@@ -47,218 +44,40 @@ OtdPerfCounters* get_perf_counters() {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 = 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;- }-- // ZP handling: u4 (packed 4-bit) requires unpack/transpose/repack;- // u8 (INT8) is 1 byte per element, transposed like scales.- const auto zp_et = ov::element::Type(layout.data_type);- const size_t zp_bitwidth = zp_et.bitwidth();- if (zp_bitwidth >= 8) {- // u8 or larger: transpose like scale (1+ bytes per element)- const size_t byte_per_elem = zp_bitwidth / 8;- OPENVINO_ASSERT(elem_count * byte_per_elem == per_expert_size,- "Unexpected zp payload size for offset_pos=",- offset_pos,- ", expected=",- elem_count * byte_per_elem,- ", 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_idx = o * group_count + g;- const size_t dst_idx = g * oc + o;- std::memcpy(transposed.data() + dst_idx * byte_per_elem, payload.data() + src_idx * byte_per_elem, byte_per_elem);- }- }- payload.swap(transposed);- return;- }-- // u4 packed: 2 elements per byte- 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}};-+void fill_weights_memory(cldnn::stream& exec_stream, ParallelWeightReader& weight_reader, const std::vector<SlicedTensor>& tensors, size_t index, size_t slot) {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);- }- }+ // Sources and slots outlive the device copies+ const bool blocking = exec_stream.get_queue_type() != cldnn::QueueTypes::in_order;+ std::vector<uint8_t> payload;++ for (const auto& tensor : tensors) {+ if (tensor.source) {+ tensor.slots->copy_from(exec_stream, *tensor.source, index * tensor.slice_size, slot * tensor.slice_size, tensor.slice_size, blocking);+ continue;+ }+ const size_t weight_file_size = weight_reader.file_size();+ const size_t src_offset = tensor.file_offset + (index * tensor.slice_size);+ OPENVINO_ASSERT(src_offset <= weight_file_size && tensor.slice_size <= weight_file_size - src_offset,+ "Read range out of file: src_offset=",+ src_offset,+ ", slice_size=",+ tensor.slice_size,+ ", file_size=",+ weight_file_size,+ ", index=",+ index);+ payload.resize(tensor.slice_size);+ const auto t0 = std::chrono::steady_clock::now();+ weight_reader.read(reinterpret_cast<char*>(payload.data()), tensor.slice_size, src_offset);+ const auto t1 = std::chrono::steady_clock::now();+ tensor.slots->copy_from(exec_stream, payload.data(), 0, slot * tensor.slice_size, tensor.slice_size, true);+ if (perf) {+ const auto t2 = 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);+ 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);}-- index++;}}diff --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.hppindex eea80703288..34b55f53aad 100644--- 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.hpp@@ -25,7 +25,6 @@ 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};@@ -82,18 +81,17 @@ private: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);+// A constant sliced along its outer dimension (e.g. one slice per expert) whose slices are loaded on demand into a slot buffer+struct SlicedTensor {+ cldnn::memory::ptr slots; // slice `i` of the buffer holds the slice loaded into slot `i`+ size_t slice_size = 0; // bytes+ cldnn::memory::ptr source; // device-resident tensor with every slice; null: the slices are read from the weights file+ size_t file_offset = 0; // of slice 0 in the weights file, used without `source`+};++/// Loads slice `index` of each tensor into slot `slot` of its slot buffer.+/// Slices are read from the weights file as stored, or copied on the device from `source`. The file reads are complete on return;+/// the device copies are not waited for on an in-order queue, where the kernels that read the slots are enqueued after them.+void fill_weights_memory(cldnn::stream& exec_stream, ParallelWeightReader& weight_reader, const std::vector<SlicedTensor>& tensors, size_t index, size_t slot);} // namespace ov::intel_gpu::ocl::moe_otd\ No newline at end of filediff --git a/src/plugins/intel_gpu/src/plugin/ops/moe.cpp b/src/plugins/intel_gpu/src/plugin/ops/moe.cppindex 30f57875d9f..a0eba931bff 100644--- a/src/plugins/intel_gpu/src/plugin/ops/moe.cpp+++ b/src/plugins/intel_gpu/src/plugin/ops/moe.cpp@@ -21,7 +21,6 @@#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"#include "moe_offload_constant.hpp"@@ -30,8 +29,9 @@ 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).-// For ratios 1-100, GPU-resident LRU slots = max(1, num_expert * (100 - ratio) / 100).-// ratio=0 means all resident (no OTD).+// For ratios 1-100, GPU-resident LRU slots = max(1, num_expert * (100 - ratio) / 100); ratio=0 means all resident (no OTD).+// Only the routed weights are streamed, and only if the graph consumes them exactly as stored in the weights file;+// otherwise the layer stays fully resident. Scales and zero points are always resident.// 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,@@ -39,95 +39,32 @@ static bool prepare_moe_otd_params(ProgramBuilder& p,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 size_t otd_ratio = p.get_config().get_offload_ratio();- // ratio=0: all resident, no offload- // ratios 1-100: GPU-resident slots = max(1, num_expert * (100 - ratio) / 100)- if (otd_ratio > 0 && otd_ratio <= 100) {- // Fall back to resident mode if any routed expert constant is not safely offloadable- // (e.g. shared with non-routed consumers: NotOffloadableRoutedExpert).- if (is_moe_otd_eligible(op.get())) {- lru_expert_num = std::max<size_t>(1, static_cast<size_t>(config.num_expert) * (100 - otd_ratio) / 100);- } else {- lru_expert_num = 0;+ std::string resident_reason;+ lru_expert_num = get_moe_offload_slot_count(*op, p.get_config().get_offload_ratio(), &resident_reason);+ if (lru_expert_num == 0) {+ GPU_DEBUG_IF(p.get_config().get_offload_ratio() > 0) {+ GPU_DEBUG_INFO << "MOE OTD disabled for " << op->get_friendly_name() << ": " << resident_reason << std::endl;}- } else {- lru_expert_num = 0;- }- const bool otd_enabled = lru_expert_num > 0;- if (otd_enabled) {- // Offloaded experts are streamed from the weights file as stored. A per-group u3 zero point is packed there (3 bits per element)- // but is converted to u8 in the graph (oneDNN has no u3 zero point), so its file layout does not match the GPU buffer.- // A scalar zero point is shared by all the experts and is not streamed.- OPENVINO_ASSERT(!config.has_zp || op->get_input_element_type(static_cast<size_t>(input_idx::weight_0)) != ov::element::u3 ||- ov::shape_size(op->get_input_shape(static_cast<size_t>(input_idx::zp_0))) == 1,- "OFFLOAD_RATIO is not supported for u3 weights with per-group zero points");- 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);+ return false;}- 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++) {- // Offsets are ordered as weights, scales, zero points. Symmetric weights have an empty placeholder instead of the zero points.- constexpr size_t first_zp_offset = 6;- if (i >= first_zp_offset && !config.has_zp) {- continue;- }- weight_bin_offsets[i] = get_const_offset(const_input_idx_by_offset[i], i);- }+ OPENVINO_ASSERT(p.get_config().get_num_streams() == 1,+ "[GPU] OFFLOAD_RATIO=",+ p.get_config().get_offload_ratio(),+ " supports a single stream only, but the model is compiled with ",+ p.get_config().get_num_streams(),+ " streams. Set NUM_STREAMS=1 and do not use the THROUGHPUT performance hint.");++ 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.");+ // Without mmap the file offsets are in the IR attributes of the constants+ for (const auto index : {input_idx::weight_0, input_idx::weight_1, input_idx::weight_2}) {+ const auto constant = ov::as_type_ptr<ov::op::v0::Constant>(op->get_input_node_shared_ptr(static_cast<size_t>(index)));+ weight_bin_offsets.push_back(get_weights_file_offset(*constant, weights_path));}- return otd_enabled;+ return true;}static void CreateMOECompressedOp(ProgramBuilder& p, const std::shared_ptr<ov::op::internal::MOECompressed>& op) {diff --git a/src/plugins/intel_gpu/src/plugin/ops/moe_offload_constant.cpp b/src/plugins/intel_gpu/src/plugin/ops/moe_offload_constant.cppindex 1c6ca2bcecf..5ad89193fb3 100644--- a/src/plugins/intel_gpu/src/plugin/ops/moe_offload_constant.cpp+++ b/src/plugins/intel_gpu/src/plugin/ops/moe_offload_constant.cpp@@ -5,11 +5,15 @@#include "moe_offload_constant.hpp"#include <algorithm>+#include <array>+#include <fstream>#include <functional>#include <limits>#include <unordered_set>#include <vector>+#include "intel_gpu/primitives/moe_3gemm_fused_compressed.hpp"+#include "openvino/core/weight_sharing_util.hpp"#include "openvino/op/util/multi_subgraph_base.hpp"namespace ov::intel_gpu {@@ -76,7 +80,81 @@ MoEConstantRole get_moe_constant_role(const std::shared_ptr<ov::op::v0::Constantreturn MoEConstantRole::NotOffloadableMoE;}-bool is_moe_otd_eligible(const ov::Node* node) {+namespace {+using moe_input_index = cldnn::moe_3gemm_fused_compressed::input_index;+constexpr std::array<size_t, 3> routed_weight_inputs = {static_cast<size_t>(moe_input_index::weight_0),+ static_cast<size_t>(moe_input_index::weight_1),+ static_cast<size_t>(moe_input_index::weight_2)};+constexpr std::array<size_t, 6> routed_param_inputs = {static_cast<size_t>(moe_input_index::scale_0),+ static_cast<size_t>(moe_input_index::zp_0),+ static_cast<size_t>(moe_input_index::scale_1),+ static_cast<size_t>(moe_input_index::zp_1),+ static_cast<size_t>(moe_input_index::scale_2),+ static_cast<size_t>(moe_input_index::zp_2)};++bool is_routed_weight_input(size_t index) {+ return std::find(routed_weight_inputs.begin(), routed_weight_inputs.end(), index) != routed_weight_inputs.end();+}++bool is_routed_param_input(size_t index) {+ return std::find(routed_param_inputs.begin(), routed_param_inputs.end(), index) != routed_param_inputs.end();+}++// Offloaded experts are streamed from the weights file as stored, so the graph must consume the file bytes unchanged:+// a constant whose data was converted, transposed or otherwise recomputed by the transformations has no file descriptor+bool is_weights_file_view(const ov::op::v0::Constant& constant, size_t num_expert) {+ if (!ov::weight_sharing::Extension::get_constant_source_buffer(constant)) {+ return false;+ }+ const auto& shape = constant.get_shape();+ // Each expert slice must start on a byte boundary (sub-byte weights)+ return !shape.empty() && shape[0] == num_expert && (ov::shape_size(shape) * constant.get_element_type().bitwidth()) % (8 * num_expert) == 0;+}++// The slots of an offloaded layer copy a scale / zero point per expert, unless it is shared by all the experts (at most one element)+bool is_shared_or_sliced_per_expert(const ov::Output<ov::Node>& input, size_t num_expert) {+ if (input.get_partial_shape().is_dynamic()) {+ return false;+ }+ const auto& shape = input.get_shape();+ const auto count = ov::shape_size(shape);+ return count <= 1 || (shape[0] == num_expert && (count * input.get_element_type().bitwidth()) % (8 * num_expert) == 0);+}++// Why the layer must stay fully resident, nullptr if it can be offloaded. Collects the layers that share its routed weights.+const char* get_resident_reason(const ov::Node* node, std::vector<const ov::Node*>& sharing_layers) {+ const auto* moe = ov::as_type<const ov::op::internal::MOECompressed>(node);+ if (!moe || !is_otd_capable_moe(moe) || moe->get_config().num_expert == 0 || moe->get_input_size() <= routed_param_inputs.back()) {+ return "the expert type is not supported";+ }+ const auto num_expert = static_cast<size_t>(moe->get_config().num_expert);+ for (const auto index : routed_weight_inputs) {+ const auto constant = ov::as_type_ptr<ov::op::v0::Constant>(moe->get_input_node_shared_ptr(index));+ if (!constant || get_moe_constant_role(constant) != MoEConstantRole::OffloadableRoutedExpert) {+ return "the routed weights are not constants used by MoE layers only";+ }+ for (const auto& consumer : constant->get_output_target_inputs(0)) {+ if (!is_routed_weight_input(consumer.get_index())) {+ return "the routed weights are not constants used by MoE layers only";+ }+ sharing_layers.push_back(consumer.get_node());+ }+ if (!is_weights_file_view(*constant, num_expert)) {+ return "the routed weights are not unmodified views of the weights file";+ }+ }+ // Only the routed weights are streamed: the scales and zero points stay resident, with per-expert slot copies+ for (const auto index : routed_param_inputs) {+ if (!is_shared_or_sliced_per_expert(moe->input_value(index), num_expert)) {+ return "a scale or zero point is neither shared by all the experts nor sliced per expert";+ }+ }+ return nullptr;+}+} // namespace++bool is_moe_otd_eligible(const ov::Node* node, std::string* reason) {+ // Layers sharing a routed weight read the same partially uploaded constant: they are offloaded together or not at allstd::vector<const ov::Node*> pending{node};std::unordered_set<const ov::Node*> visited;while (!pending.empty()) {@@ -85,18 +163,11 @@ bool is_moe_otd_eligible(const ov::Node* node) {if (!visited.insert(current).second) {continue;}- if (!is_otd_capable_moe(current) || current->get_input_size() <= ROUTED_INPUT_END) {- return false;- }- for (size_t index = ROUTED_INPUT_START; index <= ROUTED_INPUT_END; ++index) {- auto constant = ov::as_type_ptr<ov::op::v0::Constant>(current->input_value(index).get_node_shared_ptr());- if (!constant || get_moe_constant_role(constant) != MoEConstantRole::OffloadableRoutedExpert) {- return false;- }- // Propagate resident fallback across MoEs sharing routed constants.- for (const auto& consumer : constant->get_output_target_inputs(0)) {- pending.push_back(consumer.get_node());+ if (const auto* why = get_resident_reason(current, pending)) {+ if (reason) {+ *reason = why;}+ return false;}}return true;@@ -108,7 +179,7 @@ bool is_moe_constant_offloadable(const std::shared_ptr<ov::op::v0::Constant>& op}const auto consumers = op->get_output_target_inputs(0);return std::all_of(consumers.begin(), consumers.end(), [](const ov::Input<ov::Node>& consumer) {- return is_moe_otd_eligible(consumer.get_node());+ return is_routed_weight_input(consumer.get_index()) && is_moe_otd_eligible(consumer.get_node());});}@@ -116,6 +187,103 @@ bool is_moe_related_constant(const std::shared_ptr<ov::op::v0::Constant>& op) {return get_moe_constant_role(op) != MoEConstantRole::NotMoE;}+namespace {+// Slot count of the offloaded layers that consume the constant as a routed weight, 0 for any other constant+size_t get_routed_weight_slot_count(const std::shared_ptr<ov::op::v0::Constant>& op, size_t offload_ratio) {+ if (offload_ratio == 0 || !is_moe_constant_offloadable(op)) {+ return 0;+ }+ // Its consumers are offloaded together, with the same number of experts+ const auto* moe = ov::as_type<const ov::op::internal::MOECompressed>(op->get_output_target_inputs(0).begin()->get_node());+ return get_moe_offload_slot_count(*moe, offload_ratio);+}++// Bytes of the slot copies of a per-expert scale / zero point, one set per offloaded layer that consumes it+uint64_t get_routed_param_slot_bytes(const std::shared_ptr<ov::op::v0::Constant>& op, size_t offload_ratio) {+ const auto& shape = op->get_shape();+ if (ov::shape_size(shape) <= 1) {+ return 0;+ }+ uint64_t bytes = 0;+ for (const auto& input : op->get_output_target_inputs(0)) {+ const auto* moe = ov::as_type<const ov::op::internal::MOECompressed>(input.get_node());+ if (!moe || !is_routed_param_input(input.get_index())) {+ continue;+ }+ const auto slot_count = get_moe_offload_slot_count(*moe, offload_ratio);+ if (slot_count > 0 && shape[0] > 0) {+ bytes += op->get_byte_size() / shape[0] * std::min<size_t>(shape[0], slot_count);+ }+ }+ return bytes;+}+} // namespace++size_t get_moe_offload_slot_count(const ov::op::internal::MOECompressed& moe, size_t offload_ratio, std::string* reason) {+ const auto resident = [reason](const char* why) -> size_t {+ if (reason) {+ *reason = why;+ }+ return 0;+ };+ // ratio=0 keeps all experts resident+ if (offload_ratio == 0) {+ return resident("OFFLOAD_RATIO is 0");+ }+ if (!is_moe_otd_eligible(&moe, reason)) {+ return 0;+ }+ // offload_ratio is the % on disk; GPU-resident experts = max(1, total * (100 - ratio) / 100)+ return std::max<size_t>(1, static_cast<size_t>(moe.get_config().num_expert) * (100 - offload_ratio) / 100);+}++size_t get_weights_file_offset(const ov::op::v0::Constant& constant, const std::filesystem::path& weights_path) {+ std::ifstream weights_file(weights_path, std::ios::binary);+ OPENVINO_ASSERT(weights_file.is_open(), "OTD weights file cannot be opened: ", weights_path);+ const auto file_size = static_cast<size_t>(std::filesystem::file_size(weights_path));+ const auto source = ov::weight_sharing::Extension::get_constant_source_buffer(constant);+ const auto byte_size = constant.get_byte_size();+ // With mmap the descriptor offset is relative to the whole file. Without it, it is relative to a buffer read for one constant,+ // whose file range is in the IR attribute.+ auto offset = static_cast<size_t>(ov::weight_sharing::Extension::get_constant_id(constant));+ if (!source || source->size() != file_size) {+ const auto origin = ov::weight_sharing::Extension::get_constant_origin(constant);+ OPENVINO_ASSERT(source && origin && origin->m_size == byte_size,+ "OTD: constant ",+ constant.get_friendly_name(),+ " cannot be located in ",+ weights_path);+ offset = origin->m_offset;+ }+ OPENVINO_ASSERT(offset <= file_size && byte_size <= file_size - offset,+ "OTD: constant ",+ constant.get_friendly_name(),+ " at offset ",+ offset,+ " (",+ byte_size,+ " bytes) is out of ",+ weights_path,+ " (",+ file_size,+ " bytes)");+ // The slices are streamed from this file: compare its first and last bytes with the constant+ const auto* data = static_cast<const char*>(constant.get_data_ptr());+ const size_t sample_size = std::min<size_t>(byte_size, 64);+ for (const size_t sample_offset : {size_t{0}, byte_size - sample_size}) {+ std::array<char, 64> sample{};+ weights_file.seekg(static_cast<std::streamoff>(offset + sample_offset));+ weights_file.read(sample.data(), static_cast<std::streamsize>(sample_size));+ OPENVINO_ASSERT(weights_file && std::equal(sample.begin(), sample.begin() + sample_size, data + sample_offset),+ "OTD: ",+ weights_path,+ " does not contain the data of constant ",+ constant.get_friendly_name(),+ ": ov::weights_path must be the weights file the model was read from");+ }+ return offset;+}+uint64_t get_model_resident_constant_bytes(const ov::Model& model, size_t offload_ratio) {OPENVINO_ASSERT(offload_ratio <= 100, "OFFLOAD_RATIO must be in the range [0, 100]");@@ -142,17 +310,18 @@ uint64_t get_model_resident_constant_bytes(const ov::Model& model, size_t offloa}uint64_t constant_resident_bytes = constant->get_byte_size();- if (offload_ratio > 0 && is_moe_constant_offloadable(constant)) {+ if (const size_t slot_count = get_routed_weight_slot_count(constant, offload_ratio)) {const auto& shape = constant->get_shape();if (shape.empty() || shape[0] == 0) {continue;}- const size_t resident_experts = std::max<size_t>(1, shape[0] * (100 - offload_ratio) / 100);- const uint64_t bytes_per_expert =- constant_resident_bytes / shape[0] + (constant_resident_bytes % shape[0] != 0 ? 1 : 0);+ const size_t resident_experts = std::min<size_t>(shape[0], slot_count);+ const uint64_t bytes_per_expert = (constant_resident_bytes / shape[0]) + (constant_resident_bytes % shape[0] != 0 ? 1 : 0);constant_resident_bytes = bytes_per_expert * resident_experts;}+ // Per-expert scales and zero points stay resident and also have slot copies+ constant_resident_bytes += get_routed_param_slot_bytes(constant, offload_ratio);OPENVINO_ASSERT(constant_resident_bytes <= std::numeric_limits<uint64_t>::max() - resident_bytes, "MoE resident weight size overflows uint64_t");resident_bytes += constant_resident_bytes;@@ -164,7 +333,30 @@ uint64_t get_model_resident_constant_bytes(const ov::Model& model, size_t offloa}void validate_model_resident_constant_memory(const ov::Model& model, size_t offload_ratio, uint64_t device_memory_bytes) {- if (offload_ratio == 0 || device_memory_bytes == 0) {+ if (offload_ratio == 0) {+ return;+ }++ // A model without MoE layers is not affected (OFFLOAD_RATIO may be set for every model of a pipeline), but a MoE model+ // where no layer can be offloaded would silently keep every expert resident+ std::string resident_layer;+ for (const auto& node : model.get_ordered_ops()) {+ const auto moe = ov::as_type_ptr<ov::op::internal::MOECompressed>(node);+ if (!moe || !is_otd_capable_moe(moe.get())) {+ continue;+ }+ std::string reason;+ if (get_moe_offload_slot_count(*moe, offload_ratio, &reason) > 0) {+ resident_layer.clear();+ break;+ }+ if (resident_layer.empty()) {+ resident_layer = moe->get_friendly_name() + ": " + reason;+ }+ }+ OPENVINO_ASSERT(resident_layer.empty(), "[GPU] OFFLOAD_RATIO=", offload_ratio, " has no effect: no MoE layer can be offloaded (", resident_layer, ")");++ if (device_memory_bytes == 0) {return;}@@ -191,17 +383,13 @@ PartialUploadDesc try_prepare_partial_upload(cldnn::engine& engine,const cldnn::layout& const_layout) {PartialUploadDesc desc;- const size_t otd_ratio = config.get_offload_ratio();- // Only routed expert weights are partially uploaded; shared experts stay fully resident.- // ratio=0 keeps all experts resident; positive ratios enable partial upload.- const bool partial_moe_const_upload = otd_ratio > 0 && is_moe_constant_offloadable(op);- if (!partial_moe_const_upload || const_layout.bytes_count() == 0 || const_shape.empty() || const_shape[0] == 0) {+ // Only the routed expert weights of an offloaded layer are partially uploaded:+ // scales, zero points and shared experts stay fully resident.+ const size_t resident_expert_num = get_routed_weight_slot_count(op, config.get_offload_ratio());+ if (resident_expert_num == 0 || const_layout.bytes_count() == 0 || const_shape.empty() || const_shape[0] == 0) {return desc;}- // otd_ratio is the % on disk; GPU-resident experts = max(1, total * (100 - ratio) / 100)- const size_t resident_expert_num = std::max<size_t>(1, const_shape[0] * (100 - otd_ratio) / 100);-desc.enabled = true;desc.upload_shape = const_shape;desc.upload_shape[0] = std::min<size_t>(const_shape[0], resident_expert_num);diff --git a/src/plugins/intel_gpu/src/plugin/ops/moe_offload_constant.hpp b/src/plugins/intel_gpu/src/plugin/ops/moe_offload_constant.hppindex d0a017e5b38..3bb1c50227a 100644--- a/src/plugins/intel_gpu/src/plugin/ops/moe_offload_constant.hpp+++ b/src/plugins/intel_gpu/src/plugin/ops/moe_offload_constant.hpp@@ -7,6 +7,7 @@#include <atomic>#include <cstddef>#include <cstdint>+#include <filesystem>#include <memory>#include <string>@@ -32,12 +33,22 @@ enum class MoEConstantRole {/// Checks if an op is an OTD-capable MOE node (MOECompressed with GEMM3_SWIGLU).bool is_otd_capable_moe(const ov::Node* node);-bool is_moe_otd_eligible(const ov::Node* node);+/// Whether the routed weights of a MoE layer can be streamed from the weights file (if not, why, in `reason`).+/// The layers sharing routed weights with it must be eligible too.+bool is_moe_otd_eligible(const ov::Node* node, std::string* reason = nullptr);+/// Whether the constant is a routed weight of eligible MoE layers only, i.e. partially uploaded when OFFLOAD_RATIO > 0.bool is_moe_constant_offloadable(const std::shared_ptr<ov::op::v0::Constant>& op);/// Determines the role of a Constant feeding into MOECompressed.MoEConstantRole get_moe_constant_role(const std::shared_ptr<ov::op::v0::Constant>& op);+/// Number of device-resident expert slots of an offloaded (OTD) MoE layer, 0 if the layer stays fully resident (and why, in `reason`).+/// Only the routed weights are offloaded, and only if they are unmodified views of the weights file.+size_t get_moe_offload_slot_count(const ov::op::internal::MOECompressed& moe, size_t offload_ratio, std::string* reason = nullptr);++/// Offset of the data of `constant` in `weights_path`. Throws if the constant is not a view of that file.+size_t get_weights_file_offset(const ov::op::v0::Constant& constant, const std::filesystem::path& weights_path);+struct PartialUploadDesc {bool enabled = false;cldnn::memory::ptr memory = nullptr;@@ -48,6 +59,7 @@ struct PartialUploadDesc {bool is_moe_related_constant(const std::shared_ptr<ov::op::v0::Constant>& op);uint64_t get_model_resident_constant_bytes(const ov::Model& model, size_t offload_ratio);+/// Throws if OFFLOAD_RATIO cannot apply to any MoE layer of the model or the resident constants exceed the device memoryvoid validate_model_resident_constant_memory(const ov::Model& model, size_t offload_ratio, uint64_t device_memory_bytes);class PartialUploadLogState {diff --git a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cppindex cae4d2810c1..04812bc1e47 100644--- a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp+++ b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp@@ -248,8 +248,6 @@#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 "ov_ops/grouped_matmul_compressed.hpp"#include "openvino/op/roll.hpp"@@ -1003,46 +1001,6 @@ 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()) != 0U) {- 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, ov::element::u3, ov::element::u2};diff --git a/src/plugins/intel_gpu/tests/functional/shared_tests_instances/skip_tests_config.cpp b/src/plugins/intel_gpu/tests/functional/shared_tests_instances/skip_tests_config.cppindex 740172176fc..bb647c22a19 100644--- a/src/plugins/intel_gpu/tests/functional/shared_tests_instances/skip_tests_config.cpp+++ b/src/plugins/intel_gpu/tests/functional/shared_tests_instances/skip_tests_config.cpp@@ -158,8 +158,6 @@ const std::vector<std::regex>& disabled_test_patterns() {std::regex(R"(.*compile_from_weightless_blob.*)"),// u3 Transpose reference implementation is not upstreamed yet (non-transposed u3 weights fold a Transpose)std::regex(R"(.*MatMulCompressedWeights.*weights_precision=u3_.*transpose_weights=0_.*)"),- // MoE expert offload does not support per-group u3 zero points: the weights file stores them packed, the graph has them as u8- std::regex(R"(.*smoke_MoE3GemmCompressedOffload.*WP=u3_DS=full.*)"),#if defined(_WIN32)// by calc abs_threshold with expected valuediff --git a/src/plugins/intel_gpu/tests/functional/subgraph_tests/dynamic/moe.cpp b/src/plugins/intel_gpu/tests/functional/subgraph_tests/dynamic/moe.cppindex 634bc4f2ce6..ee595c585a7 100644--- a/src/plugins/intel_gpu/tests/functional/subgraph_tests/dynamic/moe.cpp+++ b/src/plugins/intel_gpu/tests/functional/subgraph_tests/dynamic/moe.cpp@@ -7,6 +7,7 @@#include "common_test_utils/file_utils.hpp"#include "common_test_utils/node_builders/moe_builders.hpp"#include "common_test_utils/ov_tensor_utils.hpp"+#include "common_test_utils/test_assertions.hpp"#include "openvino/pass/serialize.hpp"#include "openvino/runtime/intel_gpu/properties.hpp"#include "shared_test_classes/base/ov_subgraph.hpp"@@ -234,28 +235,30 @@ TEST_P(MoECompressedFusionTest, Inference) {run();}-using MoECompressedOffloadParams = std::tuple<size_t, ov::element::Type, ov::test::utils::DecompressionType>;+// offload ratio, weights precision, zero point type, model read with mmap+using MoECompressedOffloadParams = std::tuple<size_t, ov::element::Type, ov::test::utils::DecompressionType, bool>;// The experts are streamed from the weights file on demand, so the model has to be read from a file.class MoECompressedOffloadTest : public testing::WithParamInterface<MoECompressedOffloadParams>, virtual public ov::test::SubgraphBaseTest {public:static std::string getTestCaseName(const testing::TestParamInfo<MoECompressedOffloadParams>& info) {- const auto& [offload_ratio, wp, ds] = info.param;+ const auto& [offload_ratio, wp, ds, mmap] = info.param;std::ostringstream result;- result << "OR=" << offload_ratio << "_WP=" << wp << "_DS=" << ds;+ result << "OR=" << offload_ratio << "_WP=" << wp << "_DS=" << ds << "_mmap=" << mmap;return result.str();}protected:void SetUp() override {- const auto& [offload_ratio, wp, ds] = GetParam();+ const auto& [offload_ratio, wp, ds, mmap] = GetParam();targetDevice = ov::test::utils::DEVICE_GPU;const auto caps = core->get_property(targetDevice, ov::device::capabilities);if (std::find(caps.begin(), caps.end(), ov::intel_gpu::capability::HW_MATMUL) == caps.end()) {GTEST_SKIP() << "MoE pipeline requires a systolic GPU (HW_MATMUL capability)";}inType = outType = inference_precision = ov::element::f16;- abs_threshold = 1e-3;+ // Without a zero point the weights are not centered and the outputs are ~20x larger (up to 0.5), so is the f16 error+ abs_threshold = ds == ov::test::utils::DecompressionType::empty ? 1e-2 : 1e-3;rel_threshold = 0.025;const ov::test::MoePatternParams moe_params{{-1, -1, 256}, 4, 8, 512};// Prefill, then decode steps on the batched GEMV, which falls back to the per-expert loop when the LRU holds@@ -277,7 +280,7 @@ protected:xml_path = file_prefix + ".xml";bin_path = file_prefix + ".bin";ov::pass::Serialize(xml_path, bin_path).run_on_model(function);- function = core->read_model(xml_path);+ function = core->read_model(xml_path, bin_path, {ov::enable_mmap(mmap)});configuration = {ov::hint::inference_precision(ov::element::f16),ov::hint::performance_mode(ov::hint::PerformanceMode::LATENCY),ov::hint::dynamic_quantization_group_size(0),@@ -286,10 +289,38 @@ protected:}void compile_model() override {+ // The experts that are offloaded must not be allocated: compare with the same model fully resident, after compilation and+ // after the first inference (the slot buffers of a dynamic model are allocated then)+ auto resident_configuration = configuration;+ resident_configuration[ov::intel_gpu::offload_ratio.name()] = size_t{0};+ const auto resident_usage = get_compile_and_inference_memory_usage(resident_configuration);+ const auto offloaded_usage = get_compile_and_inference_memory_usage(configuration);+ ASSERT_LT(offloaded_usage.first, resident_usage.first) << "The experts were not offloaded";+ ASSERT_LT(offloaded_usage.second, resident_usage.second) << "The experts were not offloaded";+ov::test::SubgraphBaseTest::compile_model();ov::test::CheckNumberOfNodesWithType(compiledModel, "moe_3gemm_fused_compressed", 1);}+ std::pair<uint64_t, uint64_t> get_compile_and_inference_memory_usage(const ov::AnyMap& config) {+ const auto before = get_memory_usage();+ auto model = core->compile_model(function, targetDevice, config);+ const auto compiled = get_memory_usage() - before;+ auto request = model.create_infer_request();+ request.set_input_tensor(+ ov::test::utils::create_and_fill_tensor_normal_distribution(ov::element::f16, targetStaticShapes.front().front(), 0.0f, 0.05f, 1234));+ request.infer();+ return {compiled, get_memory_usage() - before};+ }++ uint64_t get_memory_usage() {+ uint64_t total = 0;+ for (const auto& [type, bytes] : core->get_property(targetDevice, ov::intel_gpu::memory_statistics)) {+ total += bytes;+ }+ return total;+ }+void generate_inputs(const std::vector<ov::Shape>& target_input_static_shapes) override {inputs.clear();const auto& parameter = function->get_parameters().at(0);@@ -316,22 +347,44 @@ TEST_P(MoECompressedOffloadTest, Inference) {run();}+// An offloaded layer supports a single stream: more streams are rejected at compilation, not at the first inference+TEST_P(MoECompressedOffloadTest, SingleStream) {+ auto explicit_streams = configuration;+ explicit_streams[ov::num_streams.name()] = ov::streams::Num(2);+ OV_EXPECT_THROW(core->compile_model(function, targetDevice, explicit_streams), ov::Exception, testing::HasSubstr("supports a single stream only"));++ auto throughput = configuration;+ throughput[ov::hint::performance_mode.name()] = ov::hint::PerformanceMode::THROUGHPUT;+ OV_EXPECT_THROW(core->compile_model(function, targetDevice, throughput), ov::Exception, testing::HasSubstr("supports a single stream only"));+}+// OFFLOAD_RATIO 50 keeps 4 of the 8 experts resident (= top_k), 75 keeps 2, so every step falls back.-// A scalar zero point is supported for u3 weights only. Per-group u3 zero points are not supported (see skip_tests_config.cpp).+// A scalar zero point is supported for u3 weights onlyINSTANTIATE_TEST_SUITE_P(smoke_MoE3GemmCompressedOffload_u3,MoECompressedOffloadTest,::testing::Combine(::testing::Values(size_t{50}, size_t{75}),::testing::Values(ov::element::u3),::testing::Values(ov::test::utils::DecompressionType::full,ov::test::utils::DecompressionType::scalar,- ov::test::utils::DecompressionType::empty)),+ ov::test::utils::DecompressionType::empty),+ ::testing::Values(true)),MoECompressedOffloadTest::getTestCaseName);INSTANTIATE_TEST_SUITE_P(smoke_MoE3GemmCompressedOffload,MoECompressedOffloadTest,::testing::Combine(::testing::Values(size_t{50}, size_t{75}),::testing::Values(ov::element::u8, ov::element::u4),- ::testing::Values(ov::test::utils::DecompressionType::full, ov::test::utils::DecompressionType::empty)),+ ::testing::Values(ov::test::utils::DecompressionType::full, ov::test::utils::DecompressionType::empty),+ ::testing::Values(true)),+ MoECompressedOffloadTest::getTestCaseName);++// Without mmap every constant is read into its own buffer, with the file offset in its descriptor+INSTANTIATE_TEST_SUITE_P(smoke_MoE3GemmCompressedOffload_no_mmap,+ MoECompressedOffloadTest,+ ::testing::Combine(::testing::Values(size_t{50}),+ ::testing::Values(ov::element::u8, ov::element::u4, ov::element::u3),+ ::testing::Values(ov::test::utils::DecompressionType::full),+ ::testing::Values(false)),MoECompressedOffloadTest::getTestCaseName);// GatherMatmul and fused MoE kernels support only f16 activations, so the MoE pipeline must be applieddiff --git a/src/plugins/intel_gpu/tests/unit/test_cases/moe_3gemm_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/moe_3gemm_gpu_test.cppindex c915179ec0c..b72328847f2 100644--- a/src/plugins/intel_gpu/tests/unit/test_cases/moe_3gemm_gpu_test.cpp+++ b/src/plugins/intel_gpu/tests/unit/test_cases/moe_3gemm_gpu_test.cpp@@ -23,12 +23,19 @@#include "moe_3gemm_fused_inst.h"#include "moe_3gemm_test_data.h"#include "common_test_utils/common_utils.hpp"+#include "common_test_utils/test_assertions.hpp"using namespace cldnn;using namespace ::tests;-class moe_3gemm_offload_fallback : public ::testing::TestWithParam<std::tuple<size_t, bool, bool>> {+// tokens, u4 weights, shared expert, offloaded expert slots (0: resident)+using moe_3gemm_offload_params = std::tuple<size_t, bool, bool, size_t>;++class moe_3gemm_offload_fallback : public ::testing::TestWithParam<moe_3gemm_offload_params> {protected:+ static constexpr size_t hidden = 128;+ static constexpr size_t experts = 4;+ static constexpr size_t top_k = 2;std::filesystem::path weights_path;void TearDown() override {@@ -38,154 +45,206 @@ protected:EXPECT_FALSE(error) << error.message();}}-};-TEST_P(moe_3gemm_offload_fallback, one_slot_matches_reference) {- const auto [tokens, is_u4, shared] = GetParam();- auto& engine = get_test_engine();- if (!engine.get_device_info().supports_immad) {- GTEST_SKIP() << "No immad support";+ // Distinct per expert so that a scale or zero point read for another expert changes the result+ static float routed_scale(size_t expert) {+ return static_cast<float>(ov::float16(0.01f * (1.0f + 0.25f * static_cast<float>(expert))));+ }+ static uint8_t routed_zp(size_t expert) {+ return static_cast<uint8_t>(expert % 2);}- auto& stream = get_test_stream();- constexpr size_t hidden = 128;- constexpr size_t experts = 4;- constexpr size_t top_k = 2;- const auto weight_type = is_u4 ? data_types::u4 : data_types::u8;- topology topo;- auto input = engine.allocate_memory(layout{ov::Shape{1, tokens, hidden}, data_types::f16, format::bfyx});- auto routing = engine.allocate_memory(layout{ov::Shape{1, tokens, top_k}, data_types::f16, format::bfyx});- auto indices = engine.allocate_memory(layout{ov::Shape{1, tokens, top_k}, data_types::i32, format::bfyx});- topo.add(input_layout("hidden", input->get_layout()));- topo.add(input_layout("routing", routing->get_layout()));- topo.add(input_layout("indices", indices->get_layout()));- std::vector<input_info> inputs{input_info("hidden"), input_info("routing"), input_info("indices")};-- weights_path = std::filesystem::temp_directory_path() / (ov::test::utils::generateTestFilePrefix() + ".bin");- std::ofstream file(weights_path, std::ios::binary);- ASSERT_TRUE(file.is_open());- std::vector<size_t> offsets(9);- size_t file_offset = 0;- for (size_t part = 0; part < (shared ? 2U : 1U); ++part) {- const bool routed = part == 0;- const size_t count = routed ? experts : 1;- for (size_t projection = 0; projection < 3; ++projection) {- for (size_t kind = 0; kind < 3; ++kind) {- const auto type = kind == 1 ? data_types::f16 : weight_type;- const ov::Shape shape = kind == 0 ? ov::Shape{count, hidden, 1, hidden}- : ov::Shape{count, hidden, 1};- const layout full_layout{shape, type, format::bfyx};- auto full = engine.allocate_memory(full_layout);- if (kind == 1) {- set_values(full, std::vector<ov::float16>(count * hidden, ov::float16(0.01f)));- } else {- std::vector<uint8_t> bytes(full_layout.bytes_count(), 0);- const size_t expert_bytes = bytes.size() / count;- if (kind == 0) {+ static uint8_t routed_weight(size_t expert, size_t projection) {+ return static_cast<uint8_t>(expert + projection + 1);+ }++ // Only the routed weights are streamed from the weights file (partially uploaded constants), scales and zero points stay resident+ topology build_topology(size_t tokens, bool is_u4, bool shared, size_t capacity) {+ auto& engine = get_test_engine();+ auto& stream = get_test_stream();+ const auto weight_type = is_u4 ? data_types::u4 : data_types::u8;+ topology topo;+ topo.add(input_layout("hidden", layout{ov::Shape{1, tokens, hidden}, data_types::f16, format::bfyx}));+ topo.add(input_layout("routing", layout{ov::Shape{1, tokens, top_k}, data_types::f16, format::bfyx}));+ topo.add(input_layout("indices", layout{ov::Shape{1, tokens, top_k}, data_types::i32, format::bfyx}));+ std::vector<input_info> inputs{input_info("hidden"), input_info("routing"), input_info("indices")};++ weights_path = std::filesystem::temp_directory_path() / (ov::test::utils::generateTestFilePrefix() + ".bin");+ std::ofstream file(weights_path, std::ios::binary);+ OPENVINO_ASSERT(file.is_open());+ std::vector<size_t> offsets(moe_3gemm_fused_compressed::serialized_weight_offset_count);+ size_t file_offset = 0;+ const auto pack = [is_u4](uint8_t value) {+ return is_u4 ? static_cast<uint8_t>(value | (value << 4)) : value;+ };+ for (size_t part = 0; part < (shared ? 2U : 1U); ++part) {+ const bool routed = part == 0;+ const size_t count = routed ? experts : 1;+ for (size_t projection = 0; projection < 3; ++projection) {+ for (size_t kind = 0; kind < 3; ++kind) {+ const auto type = kind == 1 ? data_types::f16 : weight_type;+ const ov::Shape shape = kind == 0 ? ov::Shape{count, hidden, 1, hidden} : ov::Shape{count, hidden, 1};+ const layout full_layout{shape, type, format::bfyx};+ auto full = engine.allocate_memory(full_layout);+ if (kind == 1) {+ std::vector<ov::float16> scales(count * hidden);for (size_t e = 0; e < count; ++e) {- const uint8_t value = static_cast<uint8_t>(routed ? e + projection + 1 : 2);- std::fill_n(bytes.begin() + e * expert_bytes,- expert_bytes,- is_u4 ? static_cast<uint8_t>(value | (value << 4)) : value);+ std::fill_n(scales.begin() + e * hidden, hidden, ov::float16(routed ? routed_scale(e) : 0.01f));}+ set_values(full, scales);+ } else {+ std::vector<uint8_t> bytes(full_layout.bytes_count(), 0);+ const size_t expert_bytes = bytes.size() / count;+ for (size_t e = 0; e < count; ++e) {+ const uint8_t value = kind == 0 ? (routed ? routed_weight(e, projection) : 2) : (routed ? routed_zp(e) : 0);+ std::fill_n(bytes.begin() + e * expert_bytes, expert_bytes, pack(value));+ }+ set_values(full, bytes);}- set_values(full, bytes);- }- stream.finish();- const std::string name = "weight_" + std::to_string(part) + "_" +- std::to_string(projection) + "_" + std::to_string(kind);- if (routed) {- offsets[kind * 3 + projection] = file_offset;- mem_lock<uint8_t, mem_lock_type::read> bytes(full, stream);- file.write(reinterpret_cast<const char*>(bytes.data()), full_layout.bytes_count());- ASSERT_TRUE(file.good());- file_offset += full_layout.bytes_count();- auto slot_shape = shape;- slot_shape[0] = 1;- auto slot = engine.allocate_memory(layout{slot_shape, type, format::bfyx},- engine.get_preferred_memory_allocation_type(),- false);- ASSERT_EQ(slot->size(), full_layout.bytes_count() / experts);- topo.add(data(name, engine.reinterpret_buffer(*slot, full_layout), true));- } else {- topo.add(data(name, full));+ stream.finish();+ const std::string name = "weight_" + std::to_string(part) + "_" + std::to_string(projection) + "_" + std::to_string(kind);+ if (routed && kind == 0 && capacity > 0) {+ offsets[projection] = file_offset;+ mem_lock<uint8_t, mem_lock_type::read> bytes(full, stream);+ file.write(reinterpret_cast<const char*>(bytes.data()), full_layout.bytes_count());+ OPENVINO_ASSERT(file.good());+ file_offset += full_layout.bytes_count();+ auto slot_shape = shape;+ slot_shape[0] = capacity;+ auto slot = engine.allocate_memory(layout{slot_shape, type, format::bfyx}, engine.get_preferred_memory_allocation_type(), false);+ topo.add(data(name, engine.reinterpret_buffer(*slot, full_layout), true));+ } else {+ topo.add(data(name, full));+ }+ inputs.emplace_back(name);}- inputs.emplace_back(name);}}+ file.close();+ OPENVINO_ASSERT(!file.fail());+ if (shared) {+ auto scalar = engine.allocate_memory(layout{ov::PartialShape{1, hidden}, data_types::f16, format::bfyx});+ set_values(scalar, std::vector<ov::float16>(hidden, ov::float16(0)));+ topo.add(data("shared_scalar", scalar));+ inputs.emplace_back("shared_scalar");+ }++ MOECompressed::Config config{};+ config.hidden_size = hidden;+ config.inter_size = hidden;+ config.num_expert = experts;+ config.top_k = top_k;+ config.group_size = hidden;+ config.num_shared_expert = shared ? 1 : 0;+ config.has_zp = true;+ config.out_type = data_types::f16;+ topo.add(moe_3gemm_fused_compressed("moe", inputs, config, offsets, weights_path, capacity));+ return topo;}- file.close();- ASSERT_FALSE(file.fail());- if (shared) {- auto scalar = engine.allocate_memory(layout{ov::PartialShape{1, hidden}, data_types::f16, format::bfyx});- set_values(scalar, std::vector<ov::float16>(hidden, ov::float16(0)));- topo.add(data("shared_scalar", scalar));- inputs.emplace_back("shared_scalar");++ static ExecutionConfig get_config() {+ auto config = get_test_default_config(get_test_engine());+ config.set_property(ov::intel_gpu::allow_new_shape_infer(true));+ return config;}- MOECompressed::Config config{};- config.hidden_size = hidden;- config.inter_size = hidden;- config.num_expert = experts;- config.top_k = top_k;- config.group_size = hidden;- config.num_shared_expert = shared ? 1 : 0;- config.has_zp = true;- config.out_type = data_types::f16;- topo.add(moe_3gemm_fused_compressed("moe", inputs, config, offsets, weights_path, 1));- auto net_config = get_test_default_config(engine);- net_config.set_property(ov::intel_gpu::allow_new_shape_infer(true));- network net(engine, topo, net_config);- net.set_input_data("hidden", input);- net.set_input_data("routing", routing);- net.set_input_data("indices", indices);-- const float scale = static_cast<float>(ov::float16(0.01f));- for (size_t iteration = 0; iteration < 3; ++iteration) {- SCOPED_TRACE(iteration);- const int32_t first_expert = iteration == 1 ? 2 : 0;- const ov::float16 x(0.1f * static_cast<float>(iteration + 1));- set_values(input, std::vector<ov::float16>(tokens * hidden, x));- std::vector<int32_t> ids(tokens * top_k);- std::vector<ov::float16> routes(tokens * top_k);- for (size_t t = 0; t < tokens; ++t) {- ids[t * top_k] = first_expert;- ids[t * top_k + 1] = first_expert + 1;- routes[t * top_k] = ov::float16(0.25f);- routes[t * top_k + 1] = ov::float16(0.75f);- }- set_values(indices, ids);- set_values(routing, routes);- stream.finish();- const auto outputs = net.execute();- auto output = outputs.at("moe").get_memory();- mem_lock<ov::float16, mem_lock_type::read> result(output, stream);- auto expert_output = [&](float gate_weight, float up_weight, float down_weight) {- const float gate = hidden * static_cast<float>(x) * gate_weight * scale;- const float up = hidden * static_cast<float>(x) * up_weight * scale;- return hidden * (gate / (1.0f + std::exp(-gate))) * up * down_weight * scale;- };- const float e = static_cast<float>(first_expert);- float expected = 0.25f * expert_output(e + 1, e + 2, e + 3) +- 0.75f * expert_output(e + 2, e + 3, e + 4);- if (shared) {- expected += 0.5f * expert_output(2, 2, 2);- }- ASSERT_EQ(output->get_layout().count(), tokens * hidden);- for (size_t i = 0; i < tokens * hidden; ++i) {- ASSERT_NEAR(static_cast<float>(result[i]), expected, std::abs(expected) * 0.01f + 0.002f) << i;- }- mem_lock<ov::float16, mem_lock_type::read> routing_result(routing, stream);- for (size_t i = 0; i < routes.size(); ++i) {- EXPECT_EQ(routing_result[i], routes[i]);+ // Runs `iterations` steps with experts {0, 1} or {2, 3}, so the slots are reloaded, and checks the outputs+ static void run_and_check(network& net, size_t tokens, bool shared, size_t iterations) {+ auto& engine = get_test_engine();+ auto& stream = net.get_stream();+ auto input = engine.allocate_memory(layout{ov::Shape{1, tokens, hidden}, data_types::f16, format::bfyx});+ auto routing = engine.allocate_memory(layout{ov::Shape{1, tokens, top_k}, data_types::f16, format::bfyx});+ auto indices = engine.allocate_memory(layout{ov::Shape{1, tokens, top_k}, data_types::i32, format::bfyx});+ net.set_input_data("hidden", input);+ net.set_input_data("routing", routing);+ net.set_input_data("indices", indices);+ for (size_t iteration = 0; iteration < iterations; ++iteration) {+ SCOPED_TRACE(iteration);+ const size_t first_expert = iteration % 2 == 1 ? 2 : 0;+ const ov::float16 x(0.1f * static_cast<float>(iteration % 3 + 1));+ set_values(input, std::vector<ov::float16>(tokens * hidden, x));+ std::vector<int32_t> ids(tokens * top_k);+ std::vector<ov::float16> routes(tokens * top_k);+ for (size_t t = 0; t < tokens; ++t) {+ ids[t * top_k] = static_cast<int32_t>(first_expert);+ ids[t * top_k + 1] = static_cast<int32_t>(first_expert + 1);+ routes[t * top_k] = ov::float16(0.25f);+ routes[t * top_k + 1] = ov::float16(0.75f);+ }+ set_values(indices, ids);+ set_values(routing, routes);+ stream.finish();+ const auto outputs = net.execute();+ auto output = outputs.at("moe").get_memory();+ mem_lock<ov::float16, mem_lock_type::read> result(output, stream);+ auto expert_output = [&](float gate_weight, float up_weight, float down_weight, float scale) {+ const float gate = hidden * static_cast<float>(x) * gate_weight * scale;+ const float up = hidden * static_cast<float>(x) * up_weight * scale;+ return hidden * (gate / (1.0f + std::exp(-gate))) * up * down_weight * scale;+ };+ auto routed_output = [&](size_t e) {+ const auto w = [&](size_t projection) {+ return static_cast<float>(routed_weight(e, projection)) - static_cast<float>(routed_zp(e));+ };+ return expert_output(w(0), w(1), w(2), routed_scale(e));+ };+ float expected = 0.25f * routed_output(first_expert) + 0.75f * routed_output(first_expert + 1);+ if (shared) {+ expected += 0.5f * expert_output(2, 2, 2, static_cast<float>(ov::float16(0.01f)));+ }+ ASSERT_EQ(output->get_layout().count(), tokens * hidden);+ for (size_t i = 0; i < tokens * hidden; ++i) {+ ASSERT_NEAR(static_cast<float>(result[i]), expected, std::abs(expected) * 0.01f + 0.002f) << i;+ }+ mem_lock<ov::float16, mem_lock_type::read> routing_result(routing, stream);+ for (size_t i = 0; i < routes.size(); ++i) {+ EXPECT_EQ(routing_result[i], routes[i]);+ }}}+};++TEST_P(moe_3gemm_offload_fallback, one_slot_matches_reference) {+ const auto [tokens, is_u4, shared, capacity] = GetParam();+ auto& engine = get_test_engine();+ if (!engine.get_device_info().supports_immad) {+ GTEST_SKIP() << "No immad support";+ }+ network net(engine, build_topology(tokens, is_u4, shared, capacity), get_config());+ const auto moe_inst = net.get_primitive("moe");+ std::vector<memory::ptr> constant_inputs;+ for (size_t i = 3; i < moe_inst->dependencies().size(); ++i) {+ constant_inputs.push_back(moe_inst->input_memory_ptr(i));+ }++ run_and_check(net, tokens, shared, 3);++ for (size_t i = 3; i < moe_inst->dependencies().size(); ++i) {+ EXPECT_EQ(moe_inst->input_memory_ptr(i), constant_inputs[i - 3]) << "input " << i << " was replaced";+ }+}++class moe_3gemm_offload_streams : public moe_3gemm_offload_fallback {};++// The expert slots are bound to the first network that executes; another network of the program fails explicitly+TEST_F(moe_3gemm_offload_streams, second_network_is_rejected) {+ auto& engine = get_test_engine();+ if (!engine.get_device_info().supports_immad) {+ GTEST_SKIP() << "No immad support";+ }+ constexpr size_t tokens = 1;+ auto prog = program::build_program(engine, build_topology(tokens, false, false, 2), get_config());+ network first(prog, 0);+ network second(prog, 1);+ run_and_check(first, tokens, false, 2);+ OV_EXPECT_THROW(run_and_check(second, tokens, false, 1), ov::Exception, ::testing::HasSubstr("supports a single stream only"));}INSTANTIATE_TEST_SUITE_P(smoke,moe_3gemm_offload_fallback,::testing::Combine(::testing::Values(size_t{1}, size_t{2}, size_t{16}, size_t{33}),::testing::Bool(),- ::testing::Bool()));+ ::testing::Bool(),+ ::testing::Values(size_t{0}, size_t{1}, size_t{2})));struct Moe3GemmConfig {size_t batch_size;@@ -771,9 +830,9 @@ TEST_P(moe_3gemm_compressed_gpu_random, moe_accuracy_test_random) {input_info("w2_scale"),input_info("w2_zp")};- // Offload: resident slots are refilled from a weights file holding the same tensors in plugin order- // (weights, scales, zero points for gate/up/down). One quantization group per row keeps the file- // layout identical to the device layout.+ // Offload: resident slots are refilled from a weights file holding the routed weights (gate/up/down) in plugin order.+ // Scales and zero points are not streamed: they stay resident and the slot copies are made from them.+ // One quantization group per row keeps the file layout identical to the device layout.std::vector<size_t> weight_bin_offsets;// One file per test process: parallel test runners execute these cases at the same time.auto weights_path = std::filesystem::temp_directory_path() / (ov::test::utils::generateTestFilePrefix() + "_moe_3gemm_otd_weights.bin");@@ -796,12 +855,6 @@ TEST_P(moe_3gemm_compressed_gpu_random, moe_accuracy_test_random) {append(w0_q_packed.data(), w0_q_packed.size());append(w1_q_packed.data(), w1_q_packed.size());append(w2_q_packed.data(), w2_q_packed.size());- append(w0_scale.data(), w0_scale.size() * sizeof(ov::float16));- append(w1_scale.data(), w1_scale.size() * sizeof(ov::float16));- append(w2_scale.data(), w2_scale.size() * sizeof(ov::float16));- append(w0_zp_packed.data(), w0_zp_packed.size());- append(w1_zp_packed.data(), w1_zp_packed.size());- append(w2_zp_packed.data(), w2_zp_packed.size());}topology.add(moe_3gemm_fused_compressed("moe_3gemm_fused_compressed",@@ -827,7 +880,9 @@ TEST_P(moe_3gemm_compressed_gpu_random, moe_accuracy_test_random) {const size_t slot_id_bytes = config.seq_len * config.top_k * sizeof(uint32_t);const bool fits_resident_slots =config.seq_len * config.top_k <= param.lru_expert_num || (param.routed_experts > 0 && param.routed_experts <= param.lru_expert_num);- const bool reads_slot_ids = config.seq_len <= 32 || param.micro_gemm_prefill;+ // An offloaded layer never runs the micro-GEMM prefill (it reads the scales / zero points of every expert, not of the+ // slots): with it requested, the per-expert oneDNN prefill runs and reads no slot ids.+ const bool reads_slot_ids = config.seq_len <= 32;const bool checks_slot_ids = param.lru_expert_num > 0 && fits_resident_slots && reads_slot_ids;// SigmoidBias routing performs all routing math (sigmoid, bias, normalization) in f16 on the kernel side,// while the reference uses f32, leading to slightly larger numerical divergence than Softmax.diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/moe_offload_constant_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/moe_offload_constant_test.cppindex ec082cd6b20..63b0df07114 100644--- a/src/plugins/intel_gpu/tests/unit/test_cases/moe_offload_constant_test.cpp+++ b/src/plugins/intel_gpu/tests/unit/test_cases/moe_offload_constant_test.cpp@@ -4,16 +4,36 @@#include <gtest/gtest.h>+#include <filesystem>+#include <fstream>+#include <numeric>+#include <optional>+#include "test_utils.h"+#include "common_test_utils/test_assertions.hpp"+#include "openvino/core/memory_util.hpp"+#include "openvino/core/rt_info/weightless_caching_attributes.hpp"#include "openvino/op/constant.hpp"#include "openvino/op/parameter.hpp"#include "openvino/op/relu.hpp"+#include "openvino/runtime/shared_buffer.hpp"#include "intel_gpu/runtime/internal_properties.hpp"#include "ov_ops/moe_compressed.hpp"#include "plugin/ops/moe_offload_constant.hpp"using namespace ov::intel_gpu;+// A constant viewing a weights file, as produced by reading a model with mmap+static std::shared_ptr<ov::op::v0::Constant> make_file_backed_const(ov::element::Type type, const ov::Shape& shape) {+ const auto byte_size = ov::util::get_memory_size(type, ov::shape_size(shape));+ auto weights_file = std::make_shared<ov::AlignedBuffer>(byte_size);+ auto view = std::make_shared<ov::SharedBuffer<std::shared_ptr<ov::AlignedBuffer>>>(weights_file->get_ptr<char>(),+ byte_size,+ weights_file,+ ov::create_base_descriptor(1, 0, weights_file));+ return std::make_shared<ov::op::v0::Constant>(type, shape, view);+}+// 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).@@ -28,7 +48,8 @@ struct MoETestGraph {size_t hidden_size = 128,size_t inter_size = 256,size_t group_size = 128,- ov::op::internal::MOE::Expert_type expert_type = ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU) {+ ov::op::internal::MOE::Expert_type expert_type = ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU,+ bool file_backed_weights = true) {MoETestGraph g;const size_t top_k = 2;@@ -68,16 +89,19 @@ struct MoETestGraph {auto make_const = [](ov::element::Type type, const ov::Shape& shape) {return std::make_shared<ov::op::v0::Constant>(type, shape, 0);};+ auto make_weight = [&](ov::element::Type type, const ov::Shape& shape) {+ return file_backed_weights ? make_file_backed_const(type, shape) : make_const(type, shape);+ };// 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_weight(ov::element::u8, {num_experts, inter_size, group_size, group_num})); // 3: w0_weightg.constants.push_back(make_const(ov::element::f16, {num_experts, inter_size, group_num, 1})); // 4: w0_scaleg.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_weight(ov::element::u8, {num_experts, inter_size, group_size, group_num})); // 6: w1_weightg.constants.push_back(make_const(ov::element::f16, {num_experts, inter_size, group_num, 1})); // 7: w1_scaleg.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_weight(ov::element::u8, {num_experts, hidden_size, group_size, group_num2})); // 9: w2_weightg.constants.push_back(make_const(ov::element::f16, {num_experts, hidden_size, group_num2, 1})); // 10: w2_scaleg.constants.push_back(make_const(ov::element::u8, {num_experts, hidden_size, group_num2, 1})); // 11: w2_zp@@ -338,3 +362,174 @@ TEST(moe_offload_constant, shared_routed_weights_propagate_resident_fallback) {EXPECT_FALSE(is_moe_constant_offloadable(second.constants[1]));EXPECT_EQ(get_model_resident_constant_bytes(model, 75), get_model_resident_constant_bytes(model, 0));}++namespace {+PartialUploadDesc prepare_partial_upload(const std::shared_ptr<ov::op::v0::Constant>& constant, size_t offload_ratio) {+ auto& engine = tests::get_test_engine();+ auto config = tests::get_test_default_config(engine);+ config.set_property(ov::intel_gpu::offload_ratio(offload_ratio));+ const auto shape = constant->get_output_shape(0);+ const auto layout =+ cldnn::layout(shape, cldnn::element_type_to_data_type(constant->get_output_element_type(0)), cldnn::format::get_default_format(shape.size()));+ return try_prepare_partial_upload(engine, config, constant, shape, layout.data_type, layout.format, layout);+}+} // namespace++TEST(moe_offload_constant, slot_count_of_file_backed_weights) {+ auto graph = MoETestGraph::build(/*num_experts=*/8);++ EXPECT_EQ(get_moe_offload_slot_count(*graph.moe_node, 0), 0U);+ EXPECT_EQ(get_moe_offload_slot_count(*graph.moe_node, 25), 6U);+ EXPECT_EQ(get_moe_offload_slot_count(*graph.moe_node, 99), 1U);+ EXPECT_EQ(get_moe_offload_slot_count(*graph.moe_node, 100), 1U);+}++// Weights recomputed by the transformations (converted, transposed, ...) have no weights file to be streamed from+TEST(moe_offload_constant, no_offload_of_weights_not_backed_by_file) {+ auto graph = MoETestGraph::build(4, 128, 256, 128, ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU, /*file_backed_weights=*/false);+ ov::Model model(ov::ResultVector{std::make_shared<ov::op::v0::Result>(graph.moe_node)}, graph.parameters);++ EXPECT_EQ(get_moe_offload_slot_count(*graph.moe_node, 50), 0U);+ EXPECT_FALSE(prepare_partial_upload(graph.constants[0], 50).enabled);+ EXPECT_EQ(get_model_resident_constant_bytes(model, 50), get_model_resident_constant_bytes(model, 0));+}++// Only the routed weights are offloaded: scales, zero points and shared experts stay fully resident+TEST(moe_offload_constant, partial_upload_only_for_routed_weights) {+ auto graph = MoETestGraph::build();++ for (size_t i = 0; i < graph.constants.size(); i++) {+ const auto input_index = i + 3;+ const bool is_routed_weight = input_index == 3 || input_index == 6 || input_index == 9;+ EXPECT_EQ(prepare_partial_upload(graph.constants[i], 50).enabled, is_routed_weight) << "MOECompressed input " << input_index;+ }+}++// NNCF int3 models share one scalar zero point among all the layers: only the routed weights are streamed,+// so the resident scales and zero points may have any other consumer+TEST(moe_offload_constant, zero_point_shared_with_other_layers_does_not_block_offload) {+ auto graph = MoETestGraph::build(/*num_experts=*/8);+ auto zp = std::make_shared<ov::op::v0::Constant>(ov::element::u8, ov::Shape{}, 4);+ for (const size_t index : {5, 8, 11}) {+ graph.moe_node->input(index).replace_source_output(zp);+ }+ auto other_layer = std::make_shared<ov::op::v0::Relu>(zp);++ EXPECT_TRUE(is_moe_otd_eligible(graph.moe_node.get()));+ EXPECT_EQ(get_moe_offload_slot_count(*graph.moe_node, 50), 4U);+ EXPECT_TRUE(prepare_partial_upload(graph.constants[0], 50).enabled);+ EXPECT_FALSE(is_moe_constant_offloadable(zp));+}++// The slots copy each expert's slice of a scale / zero point: one shared by the experts but not a scalar cannot be sliced,+// so the layer stays resident at compilation instead of failing at the first inference+TEST(moe_offload_constant, scale_without_expert_slices_keeps_layer_resident) {+ auto graph = MoETestGraph::build();+ graph.moe_node->input(4).replace_source_output(std::make_shared<ov::op::v0::Constant>(ov::element::f16, ov::Shape{1, 256, 1, 1}, 0));+ ov::Model model(ov::ResultVector{std::make_shared<ov::op::v0::Result>(graph.moe_node)}, graph.parameters);++ EXPECT_EQ(get_moe_offload_slot_count(*graph.moe_node, 50), 0U);+ EXPECT_FALSE(prepare_partial_upload(graph.constants[0], 50).enabled);+ EXPECT_EQ(get_model_resident_constant_bytes(model, 50), get_model_resident_constant_bytes(model, 0));+}++// OFFLOAD_RATIO that cannot offload any MoE layer of the model is an error, not a silent full residency+TEST(moe_offload_constant, no_offloadable_moe_layer_is_rejected) {+ auto in_memory = MoETestGraph::build(4, 128, 256, 128, ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU, /*file_backed_weights=*/false);+ ov::Model model(ov::ResultVector{std::make_shared<ov::op::v0::Result>(in_memory.moe_node)}, in_memory.parameters);+ OV_EXPECT_THROW(validate_model_resident_constant_memory(model, 50, 0),+ ov::Exception,+ testing::AllOf(testing::HasSubstr("no MoE layer can be offloaded"), testing::HasSubstr("not unmodified views of the weights file")));+ EXPECT_NO_THROW(validate_model_resident_constant_memory(model, 0, 0));++ // One offloadable layer is enough+ auto file_backed = MoETestGraph::build();+ auto parameters = in_memory.parameters;+ parameters.insert(parameters.end(), file_backed.parameters.begin(), file_backed.parameters.end());+ ov::Model mixed(ov::ResultVector{std::make_shared<ov::op::v0::Result>(in_memory.moe_node), std::make_shared<ov::op::v0::Result>(file_backed.moe_node)},+ parameters);+ EXPECT_NO_THROW(validate_model_resident_constant_memory(mixed, 50, 0));+}++// The slices are streamed from ov::weights_path: it must hold the data of the constant at its offset+TEST(moe_offload_constant, weights_file_offset_is_checked_against_the_file) {+ const auto path = std::filesystem::temp_directory_path() / "moe_offload_constant_weights_file_offset.bin";+ const auto write_file = [&](const std::vector<char>& data) {+ std::ofstream file(path, std::ios::binary);+ file.write(data.data(), static_cast<std::streamsize>(data.size()));+ };+ std::vector<char> file_data(256);+ std::iota(file_data.begin(), file_data.end(), char{0});+ write_file(file_data);++ // Bytes 64..191 of the file, viewed as read with mmap+ constexpr size_t offset = 64, size = 128;+ auto weights_file = std::make_shared<ov::AlignedBuffer>(file_data.size());+ std::copy(file_data.begin(), file_data.end(), weights_file->get_ptr<char>());+ auto view = std::make_shared<ov::SharedBuffer<std::shared_ptr<ov::AlignedBuffer>>>(weights_file->get_ptr<char>() + offset,+ size,+ weights_file,+ ov::create_base_descriptor(1, 0, weights_file));+ const ov::op::v0::Constant constant(ov::element::u8, ov::Shape{size}, view);+ EXPECT_EQ(get_weights_file_offset(constant, path), offset);++ // The same bytes read without mmap into a buffer of their own: the offset is in the IR attribute+ auto region = std::make_shared<ov::AlignedBuffer>(size);+ std::copy_n(file_data.begin() + offset, size, region->get_ptr<char>());+ auto region_view =+ std::make_shared<ov::SharedBuffer<std::shared_ptr<ov::AlignedBuffer>>>(region->get_ptr<char>(), size, region, ov::create_base_descriptor(2, 0, region));+ ov::op::v0::Constant read_constant(ov::element::u8, ov::Shape{size}, region_view);+ OV_EXPECT_THROW(get_weights_file_offset(read_constant, path), ov::Exception, testing::HasSubstr("cannot be located"));+ read_constant.get_rt_info()[ov::WeightlessCacheAttribute::get_type_info_static()] = ov::WeightlessCacheAttribute(size, offset, ov::element::u8);+ EXPECT_EQ(get_weights_file_offset(read_constant, path), offset);++ const ov::op::v0::Constant in_memory(ov::element::u8, ov::Shape{size}, 0);+ OV_EXPECT_THROW(get_weights_file_offset(in_memory, path), ov::Exception, testing::HasSubstr("cannot be located"));++ // Another file of the same size+ write_file(std::vector<char>(file_data.size(), 0));+ OV_EXPECT_THROW(get_weights_file_offset(constant, path), ov::Exception, testing::HasSubstr("does not contain the data of constant"));+ std::filesystem::remove(path);+}++// The estimate keeps the scales and zero points fully resident and adds their slot copies: slots x bytes per expert+TEST(moe_offload_constant, resident_estimate_counts_scale_and_zero_point_slots) {+ for (const bool scalar_zp : {false, true}) {+ SCOPED_TRACE(scalar_zp);+ auto graph = MoETestGraph::build(/*num_experts=*/4);+ if (scalar_zp) {+ auto zp = std::make_shared<ov::op::v0::Constant>(ov::element::u8, ov::Shape{}, 4);+ for (const size_t index : {5, 8, 11}) {+ graph.moe_node->input(index).replace_source_output(zp);+ }+ }+ ov::Model model(ov::ResultVector{std::make_shared<ov::op::v0::Result>(graph.moe_node)}, graph.parameters);+ uint64_t weights = 0;+ uint64_t params = 0;+ for (size_t index = 3; index <= 11; ++index) {+ const auto* constant = ov::as_type<ov::op::v0::Constant>(graph.moe_node->get_input_node_ptr(index));+ ((index % 3 == 0) ? weights : params) += ov::shape_size(constant->get_shape()) > 1 ? constant->get_byte_size() : 0;+ }+ // Ratio 50 keeps 2 of the 4 experts: half of the weights go, half of the per-expert scales and zero points come as slots+ EXPECT_EQ(get_model_resident_constant_bytes(model, 0) - get_model_resident_constant_bytes(model, 50), weights / 2 - params / 2);+ }+}++// Layers sharing a routed weight read the same partially uploaded constant: one that stays resident keeps the other resident too+TEST(moe_offload_constant, layer_sharing_weights_with_a_resident_layer_stays_resident) {+ auto first = MoETestGraph::build();+ auto second = MoETestGraph::build();+ second.moe_node->input(3).replace_source_output(first.constants[0]);+ const auto& up_weight = second.constants[3];+ second.moe_node->input(6).replace_source_output(std::make_shared<ov::op::v0::Constant>(up_weight->get_element_type(), up_weight->get_shape(), 0));++ std::string reason;+ EXPECT_FALSE(is_moe_otd_eligible(first.moe_node.get(), &reason));+ EXPECT_EQ(reason, "the routed weights are not unmodified views of the weights file");+ EXPECT_EQ(get_moe_offload_slot_count(*first.moe_node, 50), 0U);+ EXPECT_EQ(get_moe_offload_slot_count(*second.moe_node, 50), 0U);+ for (const auto& constant : {first.constants[0], first.constants[3], second.constants[6]}) {+ EXPECT_FALSE(is_moe_constant_offloadable(constant));+ EXPECT_FALSE(prepare_partial_upload(constant, 50).enabled);+ }+}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.cppindex 9c57b325b70..fa1d69af4a3 100644--- 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.cpp@@ -17,7 +17,7 @@ TEST(moe_offload_primitive_test, default_offload_fields) {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::vector<size_t> offsets = {0, 100, 800};std::string path = "/path/to/weights.bin";size_t lru_num = 16;@@ -29,16 +29,16 @@ TEST(moe_offload_primitive_test, construct_with_offload_params) {path,lru_num);- ASSERT_EQ(prim._otd.weight_bin_offsets.size(), 9U);+ ASSERT_EQ(prim._otd.weight_bin_offsets.size(), cldnn::moe_3gemm_fused_compressed::serialized_weight_offset_count);ASSERT_EQ(prim._otd.weight_bin_offsets[0], 0U);- ASSERT_EQ(prim._otd.weight_bin_offsets[8], 800U);+ ASSERT_EQ(prim._otd.weight_bin_offsets[2], 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};+ std::vector<size_t> offsets = {0, 100, 200};cldnn::moe_3gemm_fused_compressed prim1("test_moe",@@ -79,7 +79,7 @@ TEST(moe_offload_primitive_test, equality_with_offload_fields) {ASSERT_FALSE(prim1 == prim4);// Different offsets -> not equal- std::vector<size_t> offsets2 = {0, 100, 200, 300, 400, 500, 600, 700, 999};+ std::vector<size_t> offsets2 = {0, 100, 999};cldnn::moe_3gemm_fused_compressed prim5("test_moe",{cldnn::input_info("input0")},diff --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.cppindex 9765de1ba6d..f41a9e55a6c 100644--- 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.cpp@@ -2,13 +2,18 @@// SPDX-License-Identifier: Apache-2.0//-#include "test_utils/test_utils.h"+#include <filesystem>+#include <fstream>+#include "ocl_v2/moe/expert_weight_providers.hpp"+#include "test_utils/test_utils.h"using namespace cldnn;using namespace tests;+using ov::intel_gpu::ocl::moe::get_slot_layout;using ov::intel_gpu::ocl::moe::OffloadExpertWeightProvider;using ov::intel_gpu::ocl::moe::ResidentExpertWeightProvider;+using ov::intel_gpu::ocl::moe::RoutedWeightViews;TEST(moe_expert_weight_provider, resident_is_identity) {ResidentExpertWeightProvider provider;@@ -18,14 +23,14 @@ TEST(moe_expert_weight_provider, resident_is_identity) {// 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());+ 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};+ std::vector<size_t> offsets = {0, 100, 200};OffloadExpertWeightProvider provider(/*capacity=*/16, config, offsets, "/path/to/weights.bin");ASSERT_TRUE(provider.is_offloaded());@@ -53,15 +58,15 @@ TEST(moe_expert_weight_provider, offload_bind_resident_buffers) {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());+ 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));+ 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) {@@ -82,7 +87,7 @@ TEST(moe_expert_weight_provider, offload_try_acquire_simultaneous_capacity_overf// 3 unique experts (0, 1, 2) exceeds capacity=2 -> nulloptstd::vector<uint32_t> experts = {0, 1, 2, 0, 1};- auto lease = provider.try_acquire_simultaneous(experts, get_test_stream());+ auto lease = provider.try_acquire_simultaneous(experts, {}, {}, get_test_stream());ASSERT_FALSE(lease.has_value());}@@ -103,7 +108,7 @@ TEST(moe_expert_weight_provider, offload_try_acquire_simultaneous_within_capacit// 2 unique experts (0, 1) with duplicates -> within capacity=2std::vector<uint32_t> experts = {0, 1, 0, 1, 0};- auto lease = provider.try_acquire_simultaneous(experts, get_test_stream());+ 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);@@ -127,6 +132,78 @@ TEST(moe_expert_weight_provider, offload_acquire_one_basic) {cache.set_filled(slot0);// acquire_one should return a valid slot- auto slot = provider.acquire_one(5, get_test_stream());+ auto slot = provider.acquire_one(5, {}, {}, get_test_stream());ASSERT_EQ(slot, slot0);}++// The weights are streamed from the weights file, the scales and zero points are copied from their resident tensors+TEST(moe_expert_weight_provider, offload_loads_weights_from_file_and_params_from_resident_tensors) {+ auto& engine = get_test_engine();+ auto& stream = get_test_stream();+ constexpr size_t num_expert = 4, capacity = 2, rows = 8, cols = 16, groups = 2;+ constexpr size_t weights_offset = 64, weight_bytes = rows * cols;++ std::vector<uint8_t> file_data(weights_offset + num_expert * weight_bytes, 0xFF);+ for (size_t e = 0; e < num_expert; e++) {+ std::fill_n(file_data.begin() + weights_offset + e * weight_bytes, weight_bytes, static_cast<uint8_t>(e));+ }+ const auto path = std::filesystem::temp_directory_path() / "moe_expert_weight_provider_test.bin";+ {+ std::ofstream file(path, std::ios::binary);+ file.write(reinterpret_cast<const char*>(file_data.data()), static_cast<std::streamsize>(file_data.size()));+ }++ const layout weight_layout{ov::Shape{num_expert, rows, cols}, data_types::u8, format::bfyx};+ const layout weight_slots_layout{ov::Shape{capacity, rows, cols}, data_types::u8, format::bfyx};+ // The partially uploaded weight constant: `capacity` experts, viewed with the full layout+ const auto allocate_weight_slots = [&]() {+ return engine.reinterpret_buffer(*engine.allocate_memory(weight_slots_layout), weight_layout);+ };+ // Scales already reordered by the regular pipeline, with every expert resident+ const layout scales_layout{ov::Shape{num_expert, rows, groups, 1}, data_types::f16, format::byfx};+ auto scales = engine.allocate_memory(scales_layout);+ std::vector<ov::float16> scale_data(num_expert * rows * groups);+ for (size_t i = 0; i < scale_data.size(); i++) {+ scale_data[i] = ov::float16(static_cast<float>(i));+ }+ set_values(scales, scale_data);+ const layout shared_zp_layout{ov::Shape{1}, data_types::u8, format::bfyx};+ auto shared_zp = engine.allocate_memory(shared_zp_layout);++ MOECompressed::Config config{};+ config.num_expert = num_expert;+ {+ OffloadExpertWeightProvider provider(capacity, config, {weights_offset, 0, 0}, path);+ RoutedWeightViews inputs;+ inputs.scale[0] = scales;+ inputs.zp[0] = shared_zp;+ // The scale slots are an internal buffer of the primitive instance; a zero point shared by all the experts has none+ RoutedWeightViews slots;+ slots.weight[0] = allocate_weight_slots();+ slots.scale[0] = engine.allocate_memory(get_slot_layout(scales_layout, capacity, num_expert));++ const uint32_t expert = 3;+ const auto slot = provider.acquire_one(expert, inputs, slots, stream);+ ASSERT_LT(slot, capacity);++ std::vector<uint8_t> loaded_weights(weight_bytes);+ slots.weight[0]->copy_to(stream, loaded_weights.data(), slot * weight_bytes, 0, weight_bytes, true);+ EXPECT_EQ(loaded_weights, std::vector<uint8_t>(weight_bytes, static_cast<uint8_t>(expert)));++ constexpr size_t scale_count = rows * groups;+ std::vector<ov::float16> loaded_scales(scale_count);+ slots.scale[0]->copy_to(stream, loaded_scales.data(), slot * scale_count * sizeof(ov::float16), 0, scale_count * sizeof(ov::float16), true);+ EXPECT_EQ(loaded_scales, std::vector<ov::float16>(scale_data.begin() + expert * scale_count, scale_data.begin() + (expert + 1) * scale_count));+ EXPECT_EQ(provider.acquire_one(expert, inputs, slots, stream), slot);++ // A re-allocated slot buffer has lost the experts, they are loaded again. The old one is kept so that the new one gets other memory.+ const auto old_scale_slots = slots.scale[0];+ slots.scale[0] = engine.allocate_memory(get_slot_layout(scales_layout, capacity, num_expert));+ slots.scale[0]->fill(stream, 0u);+ const auto reloaded_slot = provider.acquire_one(expert, inputs, slots, stream);+ std::fill(loaded_scales.begin(), loaded_scales.end(), ov::float16(0.f));+ slots.scale[0]->copy_to(stream, loaded_scales.data(), reloaded_slot * scale_count * sizeof(ov::float16), 0, scale_count * sizeof(ov::float16), true);+ EXPECT_EQ(loaded_scales, std::vector<ov::float16>(scale_data.begin() + expert * scale_count, scale_data.begin() + (expert + 1) * scale_count));+ }+ std::filesystem::remove(path);+}