interplane.Get Omega
Read in your language

ggml

[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)

Brought by drakestapleton

branch master Branches Tags History

ggml / src / ggml-openvino / openvino / op / mul_mat_id.cpp

254 lines · 13027 bytes Raw Blame History
1#include "../node_context.h"
2#include "../op_table.h"
3#include "../utils.h"
4#include "gather_matmul.hpp"
5#include "ggml-openvino/ggml-openvino-extra.h"
6
7#include <cstdint>
8#include <cstring>
9#include <limits>
10#include <memory>
11#include <openvino/op/bitwise_and.hpp>
12#include <openvino/op/bitwise_right_shift.hpp>
13#include <openvino/op/broadcast.hpp>
14#include <openvino/op/concat.hpp>
15#include <openvino/op/constant.hpp>
16#include <openvino/op/convert.hpp>
17#include <openvino/op/gather.hpp>
18#include <openvino/op/matmul.hpp>
19#include <openvino/op/multiply.hpp>
20#include <openvino/op/reshape.hpp>
21#include <openvino/op/shape_of.hpp>
22#include <openvino/op/slice.hpp>
23#include <openvino/op/transpose.hpp>
24#include <openvino/op/unsqueeze.hpp>
25#include <vector>
26
27namespace ov {
28namespace frontend {
29namespace ggml {
30namespace op {
31
32namespace {
33
34std::shared_ptr<ov::op::v0::Constant> const_i64(const std::vector<int64_t> & values) {
35 return ov::op::v0::Constant::create(ov::element::i64, ov::Shape{values.size()}, values);
36}
37
38ov::Output<ov::Node> slice_axis(const ov::Output<ov::Node> & input, int64_t axis, int64_t begin, int64_t end) {
39 return std::make_shared<ov::op::v8::Slice>(input, const_i64({begin}), const_i64({end}), const_i64({1}),
40 const_i64({axis}));
41}
42
43// GGML tensors are rank 4, but stateful models drop the leading size-1 batch dim, so
44// activations and ids arrive one rank lower. Pick the trailing dims by actual rank.
45std::vector<int> trailing_dims(const ov::Output<ov::Node> & input, int count) {
46 const auto rank = input.get_partial_shape().rank();
47 FRONT_END_OP_CONVERSION_CHECK(rank.is_static(), "Expected static rank for MUL_MAT_ID input");
48 const int rank_len = static_cast<int>(rank.get_length());
49 FRONT_END_OP_CONVERSION_CHECK(rank_len >= count, "MUL_MAT_ID input rank is too low");
50
51 std::vector<int> dims;
52 for (int i = rank_len - count; i < rank_len; ++i) {
53 dims.push_back(i);
54 }
55 return dims;
56}
57
58ov::Output<ov::Node> static_shape_dims_or_shapeof(const ov::Output<ov::Node> & input,
59 const std::vector<int> & dims) {
60 const auto & partial_shape = input.get_partial_shape();
61 if (partial_shape.is_static()) {
62 std::vector<int64_t> values;
63 values.reserve(dims.size());
64 for (const int64_t dim : dims) {
65 values.push_back(partial_shape[dim].get_length());
66 }
67 return const_i64(values);
68 }
69
70 auto shape = std::make_shared<ov::op::v3::ShapeOf>(input, ov::element::i64);
71 return get_dimensions(shape, dims);
72}
73
74ov::Output<ov::Node> translate_mul_mat_id_mxfp4_packed(const NodeContext & context,
75 ov::Output<ov::Node> expert_weights,
76 ov::Output<ov::Node> activations,
77 ov::Output<ov::Node> ids) {
78 auto packed_shape = expert_weights.get_partial_shape().to_shape();
79 FRONT_END_OP_CONVERSION_CHECK(packed_shape.size() == 5 && packed_shape[4] == 17,
80 "Expected packed MXFP4 expert weights with shape [1, n_expert, m, k_blocks, 17]");
81
82 const int64_t n_expert = static_cast<int64_t>(packed_shape[1]);
83 const int64_t rows = static_cast<int64_t>(packed_shape[2]);
84 const int64_t k_blocks = static_cast<int64_t>(packed_shape[3]);
85 const int64_t qk = 32;
86 const int64_t cols = k_blocks * qk;
87
88 auto packed_shape_4d = const_i64({n_expert, rows, k_blocks, 17});
89 expert_weights = std::make_shared<ov::op::v1::Reshape>(expert_weights, packed_shape_4d, false);
90
91 auto activations_shape_4d = std::make_shared<ov::op::v3::ShapeOf>(activations, ov::element::i64);
92 auto ids_shape_4d = std::make_shared<ov::op::v3::ShapeOf>(ids, ov::element::i64);
93 auto activations_shape_3d = get_dimensions(activations_shape_4d, {1, 2, 3});
94 auto ids_shape_2d = get_dimensions(ids_shape_4d, {2, 3});
95
96 activations = std::make_shared<ov::op::v1::Reshape>(activations, activations_shape_3d, false);
97 ids = std::make_shared<ov::op::v1::Reshape>(ids, ids_shape_2d, false);
98 if (ids.get_element_type() != ov::element::i32 && ids.get_element_type() != ov::element::i64) {
99 ids = std::make_shared<ov::op::v0::Convert>(ids, ov::element::i32);
100 }
101
102 auto gather_axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {0});
103
104 static const std::vector<float> f4e2m1_lut = {0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f,
105 -0.0f, -0.5f, -1.0f, -1.5f, -2.0f, -3.0f, -4.0f, -6.0f};
106 std::vector<float> e8m0_lut(256);
107 for (size_t i = 0; i < e8m0_lut.size(); ++i) {
108 uint32_t bits = static_cast<uint32_t>(i) << 23;
109 memcpy(&e8m0_lut[i], &bits, sizeof(float));
110 }
111 e8m0_lut[0] = std::numeric_limits<float>::min() / 2.0f;
112 e8m0_lut[255] = std::numeric_limits<float>::quiet_NaN();
113
114 auto f4_lut = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{f4e2m1_lut.size()}, f4e2m1_lut);
115 auto scale_lut = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{e8m0_lut.size()}, e8m0_lut);
116
117 auto selected_packed_weights = std::make_shared<ov::op::v8::Gather>(expert_weights, ids, gather_axis);
118 auto scale_byte = slice_axis(selected_packed_weights, 4, 0, 1);
119 auto qs = slice_axis(selected_packed_weights, 4, 1, 17);
120 auto low = std::make_shared<ov::op::v13::BitwiseAnd>(
121 qs, ov::op::v0::Constant::create(ov::element::u8, ov::Shape{}, {0x0F}), ov::op::AutoBroadcastType::NUMPY);
122 auto high_shift = std::make_shared<ov::op::v15::BitwiseRightShift>(
123 qs, ov::op::v0::Constant::create(ov::element::u8, ov::Shape{}, {4}), ov::op::AutoBroadcastType::NUMPY);
124 auto nibbles = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{low, high_shift}, 4);
125 auto nibble_indices = std::make_shared<ov::op::v0::Convert>(nibbles, ov::element::i32);
126 auto weights_f32 = std::make_shared<ov::op::v8::Gather>(f4_lut, nibble_indices, gather_axis);
127
128 auto scale_indices = std::make_shared<ov::op::v0::Convert>(scale_byte, ov::element::i32);
129 auto scales_f32 = std::make_shared<ov::op::v8::Gather>(scale_lut, scale_indices, gather_axis);
130 ov::Output<ov::Node> selected_weights = std::make_shared<ov::op::v1::Multiply>(weights_f32, scales_f32,
131 ov::op::AutoBroadcastType::NUMPY);
132
133 auto ids_shape = std::make_shared<ov::op::v3::ShapeOf>(ids, ov::element::i64);
134 auto selected_weights_target_dims = std::make_shared<ov::op::v0::Concat>(
135 ov::OutputVector{get_dimensions(ids_shape, {0, 1}), const_i64({rows, cols})}, 0);
136 selected_weights = std::make_shared<ov::op::v1::Reshape>(selected_weights, selected_weights_target_dims, false);
137
138 auto activations_shape = std::make_shared<ov::op::v3::ShapeOf>(activations, ov::element::i64);
139 ov::Output<ov::Node> acts_target_dims = std::make_shared<ov::op::v0::Concat>(
140 ov::OutputVector{
141 get_dimensions(activations_shape, {0}),
142 get_dimensions(ids_shape, {1}),
143 get_dimensions(activations_shape, {2}),
144 },
145 0);
146 ov::Output<ov::Node> acts_broadcasted =
147 std::make_shared<ov::op::v3::Broadcast>(activations, acts_target_dims, ov::op::BroadcastType::BIDIRECTIONAL);
148
149 auto activations_expanded = std::make_shared<ov::op::v0::Unsqueeze>(acts_broadcasted, const_i64({2}));
150 ov::Output<ov::Node> result =
151 std::make_shared<ov::op::v0::MatMul>(activations_expanded, selected_weights, false, true);
152
153 auto batch_dim = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});
154 auto row_dim = ov::op::v0::Constant::create(ov::element::i64, {1}, {rows});
155 auto result_target_dims = std::make_shared<ov::op::v0::Concat>(
156 ov::OutputVector{batch_dim, get_dimensions(ids_shape, {0, 1}), row_dim}, 0);
157 result = std::make_shared<ov::op::v1::Reshape>(result, result_target_dims, false);
158
159 const auto output_type = context.get_output_type();
160 if (result.get_element_type() != output_type) {
161 result = std::make_shared<ov::op::v0::Convert>(result, output_type);
162 }
163 return result;
164}
165
166} // namespace
167
168OutputVector translate_mul_mat_id(const NodeContext & context) {
169 num_inputs_check(context, 3, 3);
170
171 auto expert_weights = process_view_input_new(context, 0);
172 auto activations = process_view_input_new(context, 1);
173 auto ids = process_view_input_new(context, 2);
174
175 if (activations.get_partial_shape().rank() == 3) {
176 activations = std::make_shared<ov::op::v0::Unsqueeze>(activations, const_i64({0}));
177 }
178 if (ids.get_partial_shape().rank() == 3) {
179 ids = std::make_shared<ov::op::v0::Unsqueeze>(ids, const_i64({0}));
180 }
181
182 if (expert_weights.get_element_type() == ov::element::u8 && expert_weights.get_partial_shape().rank().is_static() &&
183 expert_weights.get_partial_shape().rank().get_length() == 5) {
184 return rename_outputs_with_suffix({translate_mul_mat_id_mxfp4_packed(context, expert_weights, activations, ids)},
185 context.get_name());
186 }
187
188 // General (non-packed) path: dense F32/F16/BF16 weights, or the f16 dequantization chain for
189 // quantized MoE experts (see extract_quantized_weights / make_int4_weights / make_int8_weights in
190 // ggml-quants.cpp). Routed through ov::op::internal::GatherMatmul instead of a naive
191 // Gather+Broadcast+MatMul, so the selected expert's full weight matrix is never materialized per
192 // token. The CPU plugin's ConvertGatherMatmulToGatherMatmulCompressed pass (run during
193 // compile_model) fuses the dequantization chain feeding GatherMatmul's B input into a
194 // GatherMatmulCompressed node automatically, as long as MarkDequantization has marked the chain --
195 // see translate_session.cpp's apply_transformations for the MarkDequantization registration.
196 //
197 // OpenVINO sees GGML tensors in reversed dimension order:
198 // activations: [1, n_tokens, n_used_or_1, k]
199 // ids: [1, 1, n_tokens, n_used]
200 // expert_weights is either [1, n_expert, m, k] (4D, e.g. non-quantized weights without a
201 // pre-built extra) or already [n_expert, m, k] (3D, weights routed through
202 // process_weight_tensor) -- GatherMatmul's B input expects the latter.
203 auto expert_weights_rank = expert_weights.get_partial_shape().rank();
204 FRONT_END_OP_CONVERSION_CHECK(expert_weights_rank.is_static(),
205 "Expected static rank for MUL_MAT_ID expert weights");
206 if (expert_weights_rank.get_length() == 4) {
207 auto expert_weights_shape_3d = static_shape_dims_or_shapeof(expert_weights, {1, 2, 3});
208 expert_weights = std::make_shared<ov::op::v1::Reshape>(expert_weights, expert_weights_shape_3d, false);
209 }
210
211 auto activations_shape_3d = static_shape_dims_or_shapeof(activations, trailing_dims(activations, 3));
212 auto ids_shape_2d = static_shape_dims_or_shapeof(ids, trailing_dims(ids, 2));
213
214 activations = std::make_shared<ov::op::v1::Reshape>(activations, activations_shape_3d, false);
215 ids = std::make_shared<ov::op::v1::Reshape>(ids, ids_shape_2d, false);
216
217 if (ids.get_element_type() != ov::element::i32 && ids.get_element_type() != ov::element::i64) {
218 ids = std::make_shared<ov::op::v0::Convert>(ids, ov::element::i32);
219 }
220
221 const auto output_type = context.get_output_type();
222 const auto activations_type = ggml_openvino_is_gpu() ? ov::element::f16 : ov::element::f32;
223 if (activations.get_element_type() != activations_type) {
224 activations = std::make_shared<ov::op::v0::Convert>(activations, activations_type);
225 }
226
227 // GatherMatmul's A input is [n_used_or_1, n_tokens, k]; activations_3d is
228 // [n_tokens, n_used_or_1, k].
229 auto activations_transpose_order = const_i64({1, 0, 2});
230 ov::Output<ov::Node> activations_for_gather =
231 std::make_shared<ov::op::v1::Transpose>(activations, activations_transpose_order);
232
233 ov::Output<ov::Node> result = std::make_shared<ov::op::internal::GatherMatmul>(activations_for_gather, expert_weights, ids);
234
235 // result is [n_used, n_tokens, m]; GGML expects [1, n_tokens, n_used, m], except on the
236 // stateful path where the leading batch dim is dropped.
237 auto result_transpose_order = const_i64({1, 0, 2});
238 result = std::make_shared<ov::op::v1::Transpose>(result, result_transpose_order);
239 if (!context.is_stateful()) {
240 auto unsqueeze_axes = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});
241 result = std::make_shared<ov::op::v0::Unsqueeze>(result, unsqueeze_axes);
242 }
243
244 if (result.get_element_type() != output_type) {
245 result = std::make_shared<ov::op::v0::Convert>(result, output_type);
246 }
247
248 return rename_outputs_with_suffix({result}, context.get_name());
249}
250
251} // namespace op
252} // namespace ggml
253} // namespace frontend
254} // namespace ov