ggml
[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)
Brought by drakestapleton
ggml / src / ggml-openvino / openvino / pass / fuse_moe_compressed.cpp
| 1 | #include "fuse_moe_compressed.h" |
| 2 | |
| 3 | #include <cstring> |
| 4 | #include <limits> |
| 5 | #include <set> |
| 6 | #include <memory> |
| 7 | #include <openvino/core/graph_util.hpp> |
| 8 | #include <openvino/core/rt_info.hpp> |
| 9 | #include <openvino/op/constant.hpp> |
| 10 | #include <openvino/op/convert.hpp> |
| 11 | #include <openvino/op/gelu.hpp> |
| 12 | #include <openvino/op/multiply.hpp> |
| 13 | #include <openvino/op/reduce_sum.hpp> |
| 14 | #include <openvino/op/reshape.hpp> |
| 15 | #include <openvino/op/slice.hpp> |
| 16 | #include <openvino/op/squeeze.hpp> |
| 17 | #include <openvino/op/subtract.hpp> |
| 18 | #include <openvino/op/swish.hpp> |
| 19 | #include <openvino/op/transpose.hpp> |
| 20 | #include <openvino/op/unsqueeze.hpp> |
| 21 | #include <openvino/pass/constant_folding.hpp> |
| 22 | #include <openvino/pass/pattern/op/optional.hpp> |
| 23 | #include <openvino/pass/pattern/op/wrap_type.hpp> |
| 24 | |
| 25 | #include "../op/gather_matmul.hpp" |
| 26 | #include "../op/moe_compressed.hpp" |
| 27 | |
| 28 | namespace ov { |
| 29 | namespace frontend { |
| 30 | namespace ggml { |
| 31 | namespace pass { |
| 32 | |
| 33 | namespace { |
| 34 | |
| 35 | struct dequant_inputs { |
| 36 | ov::Output<ov::Node> weight; |
| 37 | ov::Output<ov::Node> scale; |
| 38 | ov::Output<ov::Node> zp; |
| 39 | bool has_zp = false; |
| 40 | bool ok = false; |
| 41 | }; |
| 42 | |
| 43 | // Peel the chain built by make_int4_weights/make_int8_weights back to its Constant inputs. |
| 44 | // Grouped weights keep the pre-Reshape rank-4 form [n_expert, n, k/group, group] with scale |
| 45 | // and zp at [n_expert, n, k/group, 1], which is the layout MOECompressed expects. Channel-wise |
| 46 | // weights stay rank-3 with a rank-3 scale and carry no zp. |
| 47 | dequant_inputs unwrap_dequant(const ov::Output<ov::Node> & b) { |
| 48 | dequant_inputs res; |
| 49 | |
| 50 | auto node = b.get_node_shared_ptr(); |
| 51 | while (ov::is_type<ov::op::v0::Convert>(node) || ov::is_type<ov::op::v1::Reshape>(node)) { |
| 52 | node = node->get_input_node_shared_ptr(0); |
| 53 | } |
| 54 | |
| 55 | auto mul = ov::as_type_ptr<ov::op::v1::Multiply>(node); |
| 56 | if (!mul) { |
| 57 | return res; |
| 58 | } |
| 59 | res.scale = mul->input_value(1); |
| 60 | |
| 61 | auto lhs = mul->get_input_node_shared_ptr(0); |
| 62 | if (auto sub = ov::as_type_ptr<ov::op::v1::Subtract>(lhs)) { |
| 63 | // Take the zero point down to its Constant: an integer zp is wrapped in a Convert to f16, |
| 64 | // and the op wants the integer form. A natively quantized expert instead carries an exact |
| 65 | // f16 zp (-min/scale) with no integer behind it, which the MoE kernel does not accept. |
| 66 | auto zp_node = sub->get_input_node_shared_ptr(1); |
| 67 | while (ov::is_type<ov::op::v0::Convert>(zp_node)) { |
| 68 | zp_node = zp_node->get_input_node_shared_ptr(0); |
| 69 | } |
| 70 | res.zp = zp_node->output(0); |
| 71 | res.has_zp = true; |
| 72 | lhs = sub->get_input_node_shared_ptr(0); |
| 73 | } |
| 74 | while (ov::is_type<ov::op::v0::Convert>(lhs)) { |
| 75 | lhs = lhs->get_input_node_shared_ptr(0); |
| 76 | } |
| 77 | if (!ov::is_type<ov::op::v0::Constant>(lhs)) { |
| 78 | return res; |
| 79 | } |
| 80 | |
| 81 | res.weight = lhs->output(0); |
| 82 | res.ok = res.scale.get_partial_shape().is_static() && res.weight.get_partial_shape().is_static(); |
| 83 | return res; |
| 84 | } |
| 85 | |
| 86 | size_t logical_k(const ov::Shape & shape) { |
| 87 | return shape.size() == 4 ? shape[2] * shape[3] : shape.back(); |
| 88 | } |
| 89 | |
| 90 | // Slice a [n_expert, m, ...] compressed weight/scale/zp Constant along axis 1 (m), [begin, end). |
| 91 | // Built by copying raw bytes directly instead of a graph Slice op: CommonOptimizations rewrites |
| 92 | // v8::Slice into v1::StridedSlice for constant folding regardless of disable_constant_folding |
| 93 | // (the rewrite doesn't carry the marking over), and that reference evaluator crashes on |
| 94 | // sub-byte (u4/i4) element types. Each axis-1 "row" (the trailing dims) is confirmed |
| 95 | // byte-aligned here -- weight/scale/zp trailing sizes are always whole groups -- so a |
| 96 | // byte-range memcpy per row is exact for both regular and sub-byte element types. |
| 97 | ov::Output<ov::Node> slice_experts_dim1(const ov::Output<ov::Node> & tensor, int64_t begin, int64_t end) { |
| 98 | auto constant = ov::as_type_ptr<ov::op::v0::Constant>(tensor.get_node_shared_ptr()); |
| 99 | OPENVINO_ASSERT(constant, "slice_experts_dim1 expects a Constant input"); |
| 100 | |
| 101 | const auto & shape = constant->get_shape(); |
| 102 | OPENVINO_ASSERT(shape.size() >= 2, "slice_experts_dim1 expects rank >= 2"); |
| 103 | const auto & type = constant->get_element_type(); |
| 104 | |
| 105 | size_t row_elems = 1; |
| 106 | for (size_t i = 2; i < shape.size(); ++i) { |
| 107 | row_elems *= shape[i]; |
| 108 | } |
| 109 | const size_t row_bits = row_elems * type.bitwidth(); |
| 110 | OPENVINO_ASSERT(row_bits % 8 == 0, "slice_experts_dim1: row is not byte-aligned"); |
| 111 | const size_t row_bytes = row_bits / 8; |
| 112 | |
| 113 | ov::Shape out_shape = shape; |
| 114 | out_shape[1] = static_cast<size_t>(end - begin); |
| 115 | |
| 116 | std::vector<uint8_t> out_data(shape[0] * static_cast<size_t>(end - begin) * row_bytes); |
| 117 | const auto * src = static_cast<const uint8_t *>(constant->get_data_ptr()); |
| 118 | const size_t src_row_bytes = shape[1] * row_bytes; |
| 119 | for (size_t e = 0; e < shape[0]; ++e) { |
| 120 | std::memcpy(out_data.data() + e * static_cast<size_t>(end - begin) * row_bytes, |
| 121 | src + e * src_row_bytes + static_cast<size_t>(begin) * row_bytes, |
| 122 | static_cast<size_t>(end - begin) * row_bytes); |
| 123 | } |
| 124 | |
| 125 | return std::make_shared<ov::op::v0::Constant>(type, out_shape, out_data.data()); |
| 126 | } |
| 127 | |
| 128 | } // namespace |
| 129 | |
| 130 | FuseMoeCompressed::FuseMoeCompressed() { |
| 131 | using namespace ov::pass::pattern; |
| 132 | |
| 133 | // The gate and up projections each get their own Reshape/Transpose of the hidden state and |
| 134 | // their own Reshape of the routing ids, so every branch needs its own sub-pattern. On GPU |
| 135 | // mul_mat_id also converts the activations to f16 before the op and back to f32 after it, |
| 136 | // so those Converts are matched as optional. |
| 137 | auto hidden_gate_m = any_input(); |
| 138 | auto a_gate_reshape_m = wrap_type<ov::op::v1::Reshape>({ hidden_gate_m, any_input() }); |
| 139 | auto a_gate_m = |
| 140 | wrap_type<ov::op::v1::Transpose>({ optional<ov::op::v0::Convert>({ a_gate_reshape_m }), any_input() }); |
| 141 | auto hidden_up_m = any_input(); |
| 142 | auto a_up_m = wrap_type<ov::op::v1::Transpose>( |
| 143 | { optional<ov::op::v0::Convert>({ wrap_type<ov::op::v1::Reshape>({ hidden_up_m, any_input() }) }), |
| 144 | any_input() }); |
| 145 | |
| 146 | auto gate_w_m = any_input(); |
| 147 | auto up_w_m = any_input(); |
| 148 | auto down_w_m = any_input(); |
| 149 | auto ids_gate_m = any_input(); |
| 150 | auto ids_up_m = any_input(); |
| 151 | auto ids_down_m = any_input(); |
| 152 | |
| 153 | auto bgm_gate_m = wrap_type<ov::op::internal::GatherMatmul>({ a_gate_m, gate_w_m, ids_gate_m, any_input() }); |
| 154 | auto gate_u_m = optional<ov::op::v0::Convert>({ wrap_type<ov::op::v0::Unsqueeze>( |
| 155 | { wrap_type<ov::op::v1::Transpose>({ bgm_gate_m, any_input() }), any_input() }) }); |
| 156 | |
| 157 | auto silu_m = wrap_type<ov::op::v4::Swish>({ gate_u_m }); |
| 158 | |
| 159 | auto bgm_up_m = wrap_type<ov::op::internal::GatherMatmul>({ a_up_m, up_w_m, ids_up_m, any_input() }); |
| 160 | auto up_u_m = optional<ov::op::v0::Convert>({ wrap_type<ov::op::v0::Unsqueeze>( |
| 161 | { wrap_type<ov::op::v1::Transpose>({ bgm_up_m, any_input() }), any_input() }) }); |
| 162 | auto swiglu_m = wrap_type<ov::op::v1::Multiply>({ silu_m, up_u_m }); |
| 163 | |
| 164 | auto d_t_m = wrap_type<ov::op::v1::Transpose>( |
| 165 | { optional<ov::op::v0::Convert>({ wrap_type<ov::op::v1::Reshape>({ swiglu_m, any_input() }) }), |
| 166 | any_input() }); |
| 167 | auto bgm_down_m = wrap_type<ov::op::internal::GatherMatmul>({ d_t_m, down_w_m, ids_down_m, any_input() }); |
| 168 | auto down_u_m = optional<ov::op::v0::Convert>({ wrap_type<ov::op::v0::Unsqueeze>( |
| 169 | { wrap_type<ov::op::v1::Transpose>({ bgm_down_m, any_input() }), any_input() }) }); |
| 170 | |
| 171 | auto routing_m = any_input(); |
| 172 | auto weighted_m = wrap_type<ov::op::v1::Multiply>({ down_u_m, routing_m }); |
| 173 | auto root_m = wrap_type<ov::op::v1::ReduceSum>({ weighted_m, any_input() }); |
| 174 | |
| 175 | const auto callback = [=](Matcher & m) { |
| 176 | auto & pm = m.get_pattern_value_map(); |
| 177 | |
| 178 | const auto gate = unwrap_dequant(pm.at(gate_w_m)); |
| 179 | const auto up = unwrap_dequant(pm.at(up_w_m)); |
| 180 | const auto down = unwrap_dequant(pm.at(down_w_m)); |
| 181 | if (!gate.ok || !up.ok || !down.ok) { |
| 182 | return false; |
| 183 | } |
| 184 | |
| 185 | const auto gate_shape = gate.weight.get_shape(); |
| 186 | const auto up_shape = up.weight.get_shape(); |
| 187 | const auto down_shape = down.weight.get_shape(); |
| 188 | if (gate_shape != up_shape || gate_shape.size() < 3 || down_shape.size() < 3) { |
| 189 | return false; |
| 190 | } |
| 191 | |
| 192 | // MOECompressed carries one group_size and one has_zp for all three projections, so a |
| 193 | // model whose down-proj is quantized differently from gate/up cannot be described. This |
| 194 | // happens when ggml requantizes Q5_K/Q6_K experts to channel-wise int8. |
| 195 | if (gate.has_zp != down.has_zp || gate_shape.size() != down_shape.size()) { |
| 196 | return false; |
| 197 | } |
| 198 | |
| 199 | // The kernel only takes an integer zero point (moe_3gemm_swiglu_opt validate_impl). |
| 200 | if (gate.has_zp) { |
| 201 | static const std::set<ov::element::Type> int_zp_types = { ov::element::u4, ov::element::i4, |
| 202 | ov::element::u8, ov::element::i8 }; |
| 203 | if (int_zp_types.count(gate.zp.get_element_type()) == 0 || |
| 204 | int_zp_types.count(down.zp.get_element_type()) == 0) { |
| 205 | return false; |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | // Config holds a single group_size for all three projections. |
| 210 | const auto group_of = [](const dequant_inputs & w) { |
| 211 | const auto s = w.weight.get_shape(); |
| 212 | return s.size() == 4 ? s[3] : logical_k(s); |
| 213 | }; |
| 214 | if (group_of(gate) != group_of(up) || group_of(gate) != group_of(down)) { |
| 215 | return false; |
| 216 | } |
| 217 | |
| 218 | // all three branches must route the same hidden state through the same experts |
| 219 | if (pm.at(hidden_gate_m) != pm.at(hidden_up_m)) { |
| 220 | return false; |
| 221 | } |
| 222 | |
| 223 | auto ids = pm.at(ids_down_m); |
| 224 | const auto ids_pshape = ids.get_partial_shape(); |
| 225 | if (ids_pshape.rank().is_dynamic() || ids_pshape[ids_pshape.rank().get_length() - 1].is_dynamic()) { |
| 226 | return false; |
| 227 | } |
| 228 | const size_t top_k = ids_pshape[ids_pshape.rank().get_length() - 1].get_length(); |
| 229 | |
| 230 | // routing weights arrive as [1, n_tokens, top_k, 1]; the op wants [..., top_k] |
| 231 | auto routing = pm.at(routing_m); |
| 232 | const auto routing_pshape = routing.get_partial_shape(); |
| 233 | if (routing_pshape.rank().is_dynamic() || routing_pshape.rank().get_length() != 4 || |
| 234 | routing_pshape[3] != 1) { |
| 235 | return false; |
| 236 | } |
| 237 | // MOE requires routing weights and ids to have the same shape. Drop the trailing 1 of the |
| 238 | // routing weights and give the ids the leading batch dim, so both become [1, n_tokens, top_k]. |
| 239 | routing = std::make_shared<ov::op::v0::Squeeze>( |
| 240 | routing, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{ 1 }, { 3 })); |
| 241 | if (ids_pshape.rank().get_length() == 2) { |
| 242 | ids = std::make_shared<ov::op::v0::Unsqueeze>( |
| 243 | ids, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{ 1 }, { 0 })); |
| 244 | } |
| 245 | if (routing.get_partial_shape() != ids.get_partial_shape()) { |
| 246 | return false; |
| 247 | } |
| 248 | |
| 249 | const size_t down_k = logical_k(down_shape); |
| 250 | const auto down_scale_shape = down.scale.get_shape(); |
| 251 | const size_t down_groups = down_scale_shape.size() >= 3 ? down_scale_shape[2] : 1; |
| 252 | |
| 253 | ov::op::internal::MOECompressed::Config config; |
| 254 | config.expert_type = ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU; |
| 255 | config.activation_type = ov::op::internal::MOE::Activation_type::SWIGLU; |
| 256 | config.expert_alpha = 0.0f; |
| 257 | config.expert_beta = 1.0f; |
| 258 | config.gate_idx = 0; |
| 259 | config.hidden_size = logical_k(gate_shape); |
| 260 | config.inter_size = gate_shape[1]; |
| 261 | config.num_expert = gate_shape[0]; |
| 262 | config.num_shared_expert = 0; |
| 263 | config.top_k = top_k; |
| 264 | config.group_size = down_groups <= 1 ? std::numeric_limits<size_t>::max() : down_k / down_groups; |
| 265 | config.has_batch_dim = true; |
| 266 | config.has_zp = gate.has_zp; |
| 267 | // dynamic makes the output follow the hidden state, so the plugin can lower this region |
| 268 | // to f16 together with the rest of the graph |
| 269 | config.out_type = ov::element::dynamic; |
| 270 | |
| 271 | auto absent_zp = [] { |
| 272 | auto zp = std::make_shared<ov::op::v0::Constant>(ov::element::dynamic, ov::Shape{ 0 }); |
| 273 | ov::pass::disable_constant_folding(zp); |
| 274 | return zp->output(0); |
| 275 | }; |
| 276 | |
| 277 | // MOE takes its output type from the hidden state. Transpose the activations before the |
| 278 | // f16 Convert that mul_mat_id adds on GPU, so the op stays f32 like the block it replaces |
| 279 | // and the plugin can lower the whole region uniformly. |
| 280 | const auto a_transpose = pm.at(a_gate_m).get_node_shared_ptr(); |
| 281 | ov::Output<ov::Node> hidden = |
| 282 | std::make_shared<ov::op::v1::Transpose>(pm.at(a_gate_reshape_m), a_transpose->input_value(1)); |
| 283 | |
| 284 | const ov::OutputVector args = { |
| 285 | hidden, routing, ids, |
| 286 | gate.weight, gate.scale, gate.has_zp ? gate.zp : absent_zp(), |
| 287 | up.weight, up.scale, up.has_zp ? up.zp : absent_zp(), |
| 288 | down.weight, down.scale, down.has_zp ? down.zp : absent_zp(), |
| 289 | }; |
| 290 | |
| 291 | auto moe = std::make_shared<ov::op::internal::MOECompressed>(args, config); |
| 292 | |
| 293 | // MOE takes its output type from the hidden state, which is f16 on GPU, while the rest of |
| 294 | // the ggml graph works in f32. |
| 295 | ov::Output<ov::Node> result = moe->output(0); |
| 296 | const auto root_type = m.get_match_root()->get_output_element_type(0); |
| 297 | if (result.get_element_type() != root_type) { |
| 298 | result = std::make_shared<ov::op::v0::Convert>(result, root_type); |
| 299 | } |
| 300 | |
| 301 | result.get_node_shared_ptr()->set_friendly_name(m.get_match_root()->get_friendly_name()); |
| 302 | ov::copy_runtime_info(m.get_matched_nodes(), result.get_node_shared_ptr()); |
| 303 | ov::replace_node(m.get_match_root(), result.get_node_shared_ptr()); |
| 304 | register_new_node(moe); |
| 305 | return true; |
| 306 | }; |
| 307 | |
| 308 | register_matcher(std::make_shared<Matcher>(root_m, "ov::frontend::ggml::pass::FuseMoeCompressed"), callback); |
| 309 | } |
| 310 | |
| 311 | FuseMoeCompressedFusedGateUp::FuseMoeCompressedFusedGateUp() { |
| 312 | using namespace ov::pass::pattern; |
| 313 | |
| 314 | // A single GatherMatmul computes the fused gate+up projection; the gate/up split happens |
| 315 | // AFTER the GEMM via two Slice ops on the last (feature) axis (see get_glu_inputs in |
| 316 | // op/glu_geglu.cpp), unlike FuseMoeCompressed's two-separate-GatherMatmul models. |
| 317 | auto hidden_m = any_input(); |
| 318 | auto a_reshape_m = wrap_type<ov::op::v1::Reshape>({ hidden_m, any_input() }); |
| 319 | auto a_m = wrap_type<ov::op::v1::Transpose>({ optional<ov::op::v0::Convert>({ a_reshape_m }), any_input() }); |
| 320 | |
| 321 | auto gate_up_w_m = any_input(); |
| 322 | auto ids_gate_up_m = any_input(); |
| 323 | auto bgm_fused_m = wrap_type<ov::op::internal::GatherMatmul>({ a_m, gate_up_w_m, ids_gate_up_m, any_input() }); |
| 324 | // Two graph shapes reach here. The rank-4 (stateless) graph restores the batch dim with an |
| 325 | // Unsqueeze after the Transpose and may Convert afterwards: |
| 326 | // GatherMatmul -> Transpose -> Unsqueeze -> [Convert] -> Slice |
| 327 | // The rank-3 (stateful) graph never drops to a batch dim at all, so there is no Unsqueeze |
| 328 | // here - it appears later, between the GEGLU and the down Reshape - and the Convert sits on |
| 329 | // the other side of the Transpose: |
| 330 | // GatherMatmul -> Convert -> Transpose -> Slice |
| 331 | // optional<T>({a, b}) matches T(a, b) or bare a, so one pattern covers both. |
| 332 | auto gu_t_m = |
| 333 | wrap_type<ov::op::v1::Transpose>({ optional<ov::op::v0::Convert>({ bgm_fused_m }), any_input() }); |
| 334 | auto gu_u_m = |
| 335 | optional<ov::op::v0::Convert>({ optional<ov::op::v0::Unsqueeze>({ gu_t_m, any_input() }) }); |
| 336 | |
| 337 | auto gate_slice_m = wrap_type<ov::op::v8::Slice>({ gu_u_m, any_input(), any_input(), any_input(), any_input() }); |
| 338 | auto up_slice_m = wrap_type<ov::op::v8::Slice>({ gu_u_m, any_input(), any_input(), any_input(), any_input() }); |
| 339 | auto gelu_m = wrap_type<ov::op::v7::Gelu>({ gate_slice_m }); |
| 340 | auto geglu_m = wrap_type<ov::op::v1::Multiply>({ gelu_m, up_slice_m }); |
| 341 | |
| 342 | // The rank-3 graph inserts the Unsqueeze the gate/up branch lacked right here, before the |
| 343 | // Reshape that feeds the down projection; the rank-4 graph goes straight from the GEGLU |
| 344 | // into the Reshape. |
| 345 | auto d_t_m = wrap_type<ov::op::v1::Transpose>( |
| 346 | { optional<ov::op::v0::Convert>({ wrap_type<ov::op::v1::Reshape>( |
| 347 | { optional<ov::op::v0::Unsqueeze>({ geglu_m, any_input() }), any_input() }) }), |
| 348 | any_input() }); |
| 349 | auto down_w_m = any_input(); |
| 350 | auto ids_down_m = any_input(); |
| 351 | auto bgm_down_m = wrap_type<ov::op::internal::GatherMatmul>({ d_t_m, down_w_m, ids_down_m, any_input() }); |
| 352 | // Same two shapes as the gate/up branch above. |
| 353 | auto down_t_m = |
| 354 | wrap_type<ov::op::v1::Transpose>({ optional<ov::op::v0::Convert>({ bgm_down_m }), any_input() }); |
| 355 | auto down_u_m = |
| 356 | optional<ov::op::v0::Convert>({ optional<ov::op::v0::Unsqueeze>({ down_t_m, any_input() }) }); |
| 357 | |
| 358 | // gemma-4 applies an extra per-expert output scale to the down projection before the |
| 359 | // router-weight multiply (llama-graph.cpp's ffn_down_exps.scale); FuseMoeCompressed's |
| 360 | // Qwen-shaped models have no such scale, so this node is specific to this pattern. |
| 361 | auto down_scale_m = any_input(); |
| 362 | auto down_scaled_m = wrap_type<ov::op::v1::Multiply>({ down_u_m, down_scale_m }); |
| 363 | |
| 364 | auto routing_m = any_input(); |
| 365 | auto weighted_m = wrap_type<ov::op::v1::Multiply>({ down_scaled_m, routing_m }); |
| 366 | auto root_m = wrap_type<ov::op::v1::ReduceSum>({ weighted_m, any_input() }); |
| 367 | |
| 368 | const auto callback = [=](Matcher & m) { |
| 369 | auto & pm = m.get_pattern_value_map(); |
| 370 | |
| 371 | const auto gate_up = unwrap_dequant(pm.at(gate_up_w_m)); |
| 372 | const auto down = unwrap_dequant(pm.at(down_w_m)); |
| 373 | if (!gate_up.ok || !down.ok) { |
| 374 | return false; |
| 375 | } |
| 376 | |
| 377 | // oneDNN's weight-decompression GEMM needs a real zero point, so a symmetric (no zp) |
| 378 | // projection cannot be fused here -- e.g. the GPU-only Q4_0 fallback in |
| 379 | // ggml_openvino_get_extracted_layout for grouped 8-bit expert weights. |
| 380 | if (!gate_up.has_zp || !down.has_zp) { |
| 381 | return false; |
| 382 | } |
| 383 | |
| 384 | const auto gate_up_shape = gate_up.weight.get_shape(); |
| 385 | const auto down_shape = down.weight.get_shape(); |
| 386 | if (gate_up_shape.size() < 3 || down_shape.size() < 3 || gate_up_shape.size() != down_shape.size()) { |
| 387 | return false; |
| 388 | } |
| 389 | |
| 390 | // The op reads the zero point straight off a weight port, so it must already be an |
| 391 | // integer Constant. Requantized experts (GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all) |
| 392 | // are; a native Q4_K expert keeps an exact f16 zp and is left to the unfused path |
| 393 | // rather than rounded here -- rounding would put a live node on that port and the |
| 394 | // expert GEMM would read the wrong zero point. |
| 395 | static const std::set<ov::element::Type> int_types = { ov::element::u4, ov::element::i4, |
| 396 | ov::element::u8, ov::element::i8 }; |
| 397 | if (int_types.count(gate_up.weight.get_element_type()) == 0 || |
| 398 | int_types.count(down.weight.get_element_type()) == 0 || |
| 399 | int_types.count(gate_up.zp.get_element_type()) == 0 || |
| 400 | int_types.count(down.zp.get_element_type()) == 0) { |
| 401 | return false; |
| 402 | } |
| 403 | |
| 404 | const auto group_of = [](const dequant_inputs & w) { |
| 405 | const auto s = w.weight.get_shape(); |
| 406 | return s.size() == 4 ? s[3] : logical_k(s); |
| 407 | }; |
| 408 | if (group_of(gate_up) != group_of(down)) { |
| 409 | return false; |
| 410 | } |
| 411 | |
| 412 | auto gelu_node = ov::as_type_ptr<ov::op::v7::Gelu>(pm.at(gelu_m).get_node_shared_ptr()); |
| 413 | if (!gelu_node || gelu_node->get_approximation_mode() != ov::op::GeluApproximationMode::ERF) { |
| 414 | return false; |
| 415 | } |
| 416 | |
| 417 | // Read the actual gate/up split point from the matched Slice nodes instead of assuming |
| 418 | // inter_size/2, so this stays correct if the model's ffn_dim convention ever changes. |
| 419 | auto gate_slice = ov::as_type_ptr<ov::op::v8::Slice>(pm.at(gate_slice_m).get_node_shared_ptr()); |
| 420 | auto up_slice = ov::as_type_ptr<ov::op::v8::Slice>(pm.at(up_slice_m).get_node_shared_ptr()); |
| 421 | auto gate_end_c = ov::as_type_ptr<ov::op::v0::Constant>(gate_slice->input_value(2).get_node_shared_ptr()); |
| 422 | auto up_begin_c = ov::as_type_ptr<ov::op::v0::Constant>(up_slice->input_value(1).get_node_shared_ptr()); |
| 423 | if (!gate_end_c || !up_begin_c) { |
| 424 | return false; |
| 425 | } |
| 426 | const auto gate_end = gate_end_c->cast_vector<int64_t>().at(0); |
| 427 | const auto up_begin = up_begin_c->cast_vector<int64_t>().at(0); |
| 428 | if (gate_end != up_begin || gate_end <= 0 || gate_end >= static_cast<int64_t>(gate_up_shape[1])) { |
| 429 | return false; |
| 430 | } |
| 431 | const int64_t mid = gate_end; |
| 432 | const int64_t full = static_cast<int64_t>(gate_up_shape[1]); |
| 433 | |
| 434 | auto ids = pm.at(ids_down_m); |
| 435 | const auto ids_pshape = ids.get_partial_shape(); |
| 436 | if (ids_pshape.rank().is_dynamic() || ids_pshape[ids_pshape.rank().get_length() - 1].is_dynamic()) { |
| 437 | return false; |
| 438 | } |
| 439 | const size_t top_k = ids_pshape[ids_pshape.rank().get_length() - 1].get_length(); |
| 440 | |
| 441 | // Routing weights arrive as [1, n_tokens, top_k, 1] on the rank-4 (stateless) graph and |
| 442 | // as [n_tokens, top_k, 1] on the rank-3 (stateful) one, which is the same thing without |
| 443 | // the leading batch dim. Normalise the rank-3 form up to the rank-4 one so everything |
| 444 | // below - and the op's own config - stays in the shape that is already validated on the |
| 445 | // stateless path; the batch dim is taken back off the result at the end. |
| 446 | const auto routing_in = pm.at(routing_m); |
| 447 | const auto routing_pshape = routing_in.get_partial_shape(); |
| 448 | const auto routing_rank = routing_pshape.rank(); |
| 449 | if (routing_rank.is_dynamic() || (routing_rank.get_length() != 4 && routing_rank.get_length() != 3) || |
| 450 | routing_pshape[routing_rank.get_length() - 1] != 1) { |
| 451 | return false; |
| 452 | } |
| 453 | const bool batchless = routing_rank.get_length() == 3; |
| 454 | |
| 455 | // Fold gemma-4's per-expert output scale into the routing weights: the reduction is |
| 456 | // sum_e(routing[e] * scale[e] * down_out[e]), and MOECompressed only takes one |
| 457 | // per-expert weight, so pre-multiply it into routing here (same [.., top_k, 1] shape). |
| 458 | auto down_scale = pm.at(down_scale_m); |
| 459 | if (down_scale.get_partial_shape() != routing_pshape) { |
| 460 | return false; |
| 461 | } |
| 462 | ov::Output<ov::Node> routing = std::make_shared<ov::op::v1::Multiply>(routing_in, down_scale); |
| 463 | if (batchless) { |
| 464 | routing = std::make_shared<ov::op::v0::Unsqueeze>( |
| 465 | routing, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{ 1 }, { 0 })); |
| 466 | } |
| 467 | routing = std::make_shared<ov::op::v0::Squeeze>( |
| 468 | routing, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{ 1 }, { 3 })); |
| 469 | if (ids_pshape.rank().get_length() == 2) { |
| 470 | ids = std::make_shared<ov::op::v0::Unsqueeze>( |
| 471 | ids, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{ 1 }, { 0 })); |
| 472 | } |
| 473 | if (routing.get_partial_shape() != ids.get_partial_shape()) { |
| 474 | return false; |
| 475 | } |
| 476 | |
| 477 | const size_t down_k = logical_k(down_shape); |
| 478 | const auto down_scale_shape = down.scale.get_shape(); |
| 479 | const size_t down_groups = down_scale_shape.size() >= 3 ? down_scale_shape[2] : 1; |
| 480 | |
| 481 | // Split the fused gate_up weight/scale/zp on the output axis. slice_experts_dim1 copies |
| 482 | // raw bytes out of the Constant, so each half stays a Constant -- which is what the op |
| 483 | // needs on its weight ports. |
| 484 | const ov::Output<ov::Node> gate_weight = slice_experts_dim1(gate_up.weight, 0, mid); |
| 485 | const ov::Output<ov::Node> up_weight = slice_experts_dim1(gate_up.weight, mid, full); |
| 486 | const ov::Output<ov::Node> gate_scale = slice_experts_dim1(gate_up.scale, 0, mid); |
| 487 | const ov::Output<ov::Node> up_scale = slice_experts_dim1(gate_up.scale, mid, full); |
| 488 | const ov::Output<ov::Node> gate_zp = slice_experts_dim1(gate_up.zp, 0, mid); |
| 489 | const ov::Output<ov::Node> up_zp = slice_experts_dim1(gate_up.zp, mid, full); |
| 490 | |
| 491 | ov::op::internal::MOECompressed::Config config; |
| 492 | config.expert_type = ov::op::internal::MOE::Expert_type::GEMM3_SWIGLU; |
| 493 | config.activation_type = ov::op::internal::MOE::Activation_type::GEGLU_ERF; |
| 494 | config.expert_alpha = 0.0f; |
| 495 | config.expert_beta = 1.0f; |
| 496 | config.gate_idx = 0; |
| 497 | config.hidden_size = logical_k(gate_up_shape); |
| 498 | config.inter_size = static_cast<size_t>(mid); |
| 499 | config.num_expert = gate_up_shape[0]; |
| 500 | config.num_shared_expert = 0; |
| 501 | config.top_k = top_k; |
| 502 | config.group_size = down_groups <= 1 ? std::numeric_limits<size_t>::max() : down_k / down_groups; |
| 503 | config.has_batch_dim = true; |
| 504 | config.has_zp = true; |
| 505 | config.out_type = ov::element::dynamic; |
| 506 | |
| 507 | // Rebuild the activations Transpose before mul_mat_id's f16 GPU Convert, so the op |
| 508 | // stays f32 like the block it replaces (mirrors FuseMoeCompressed). |
| 509 | const auto a_transpose = pm.at(a_m).get_node_shared_ptr(); |
| 510 | ov::Output<ov::Node> hidden = |
| 511 | std::make_shared<ov::op::v1::Transpose>(pm.at(a_reshape_m), a_transpose->input_value(1)); |
| 512 | |
| 513 | // w0 is the activated (gate) lane and w1 the multiplied (up) lane -- see |
| 514 | // moe_3gemm_swiglu_opt.cpp: "scratch.up = up(x) * silu(gate(x))". |
| 515 | const ov::OutputVector args = { |
| 516 | hidden, routing, ids, |
| 517 | gate_weight, gate_scale, gate_zp, |
| 518 | up_weight, up_scale, up_zp, |
| 519 | down.weight, down.scale, down.zp, |
| 520 | }; |
| 521 | |
| 522 | auto moe = std::make_shared<ov::op::internal::MOECompressed>(args, config); |
| 523 | |
| 524 | ov::Output<ov::Node> result = moe->output(0); |
| 525 | // The op was fed the batched form, so it produces [1, n_tokens, hidden]. On the rank-3 |
| 526 | // graph the ReduceSum being replaced is [n_tokens, hidden], so drop the batch dim again. |
| 527 | if (batchless) { |
| 528 | result = std::make_shared<ov::op::v0::Squeeze>( |
| 529 | result, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{ 1 }, { 0 })); |
| 530 | } |
| 531 | const auto root_type = m.get_match_root()->get_output_element_type(0); |
| 532 | if (result.get_element_type() != root_type) { |
| 533 | result = std::make_shared<ov::op::v0::Convert>(result, root_type); |
| 534 | } |
| 535 | if (result.get_partial_shape() != m.get_match_root()->get_output_partial_shape(0)) { |
| 536 | return false; |
| 537 | } |
| 538 | |
| 539 | result.get_node_shared_ptr()->set_friendly_name(m.get_match_root()->get_friendly_name()); |
| 540 | ov::copy_runtime_info(m.get_matched_nodes(), result.get_node_shared_ptr()); |
| 541 | ov::replace_node(m.get_match_root(), result.get_node_shared_ptr()); |
| 542 | register_new_node(moe); |
| 543 | return true; |
| 544 | }; |
| 545 | |
| 546 | register_matcher( |
| 547 | std::make_shared<Matcher>(root_m, "ov::frontend::ggml::pass::FuseMoeCompressedFusedGateUp"), callback); |
| 548 | } |
| 549 | |
| 550 | } // namespace pass |
| 551 | } // namespace ggml |
| 552 | } // namespace frontend |
| 553 | } // namespace ov |