Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[CPU]Support RoPE for GLM4 (#32682)

Zhang Yi22975422992b
diff --git a/src/common/transformations/src/transformations/common_optimizations/fuse_rotary_positional_embeddings.cpp b/src/common/transformations/src/transformations/common_optimizations/fuse_rotary_positional_embeddings.cpp
index ef6688eccde..3bdb557da20 100644
--- a/src/common/transformations/src/transformations/common_optimizations/fuse_rotary_positional_embeddings.cpp
+++ b/src/common/transformations/src/transformations/common_optimizations/fuse_rotary_positional_embeddings.cpp
@@ -38,6 +38,7 @@
#include "openvino/pass/pattern/matcher.hpp"
#include "openvino/pass/pattern/op/optional.hpp"
#include "openvino/pass/pattern/op/or.hpp"
+#include "openvino/pass/pattern/op/pattern.hpp"
#include "openvino/pass/pattern/op/wrap_type.hpp"
#include "openvino/util/common_util.hpp"
#include "ov_ops/rotary_positional_embeddings.hpp"
@@ -784,7 +785,14 @@ ov::pass::RoPEFusionChatGLMHF::RoPEFusionChatGLMHF() {
auto reshape = pattern::wrap_type<v1::Reshape>({qk_linear, pattern::any_input()},
pattern::shape_matches("[?, head_cnt, 1, head_size]"),
{{"special_zero", false}});
- auto slice_1 = NewGenSlice(reshape, 0, "ndims", 1, 3);
+
+ auto vsplit_out0 = pattern::wrap_type<op::v1::VariadicSplit>(
+ {reshape, 3, pattern::any_input()},
+ pattern::output_index_matches(0) && pattern::shape_matches("[?, head_cnt, 1, ndims]"));
+ auto vsplit_out1 = pattern::wrap_type<op::v1::VariadicSplit>(
+ {reshape, 3, pattern::any_input()},
+ pattern::output_index_matches(1) && pattern::shape_matches("[?, head_cnt, 1, ndims]"));
+ auto slice_1 = NewGenSlice(reshape, 0, "ndims", 1, 3) | vsplit_out0;
auto const_idx =
pattern::wrap_type<ov::opset1::Constant>(pattern::type_matches(ov::element::i32) && const_idx_predicate);
@@ -808,7 +816,7 @@ ov::pass::RoPEFusionChatGLMHF::RoPEFusionChatGLMHF() {
auto multiply_1 = pattern::wrap_type<v1::Multiply>({flatten, repeat_interleave_sin}, {{"auto_broadcast", "numpy"}});
auto add = pattern::wrap_type<v1::Add>({multiply, multiply_1}, {{"auto_broadcast", "numpy"}});
- auto slice_5 = NewGenSlice(reshape, "ndims", INT_MAX, 1, 3);
+ auto slice_5 = NewGenSlice(reshape, "ndims", INT_MAX, 1, 3) | vsplit_out1;
auto result = pattern::wrap_type<v0::Concat>({add, slice_5}, {{"axis", -1}});
matcher_pass_callback callback = [=](ov::pass::pattern::Matcher& m) {
diff --git a/src/plugins/intel_cpu/src/nodes/rope.cpp b/src/plugins/intel_cpu/src/nodes/rope.cpp
index 0758bea8a31..4bbd497d8ce 100644
--- a/src/plugins/intel_cpu/src/nodes/rope.cpp
+++ b/src/plugins/intel_cpu/src/nodes/rope.cpp
@@ -253,7 +253,9 @@ struct RoPE::RoPEExecutorChatGLM : public RoPE::Executor {
jcp.dst_prc = precision_of<T>::value;
jcp.rotary_ndims = config.rotary_ndims;
jcp.interleave = true;
- jcp.mix_cos_sin = true;
+ // if use precomputed rope cache then it's mixed
+ // otherwise rope has separate cos/sin inputs
+ jcp.mix_cos_sin = config.use_rope_cache;
m_rotaryKernel = createJitKernel(jcp, true);
}
@@ -261,7 +263,6 @@ struct RoPE::RoPEExecutorChatGLM : public RoPE::Executor {
const std::vector<MemoryPtr>& inputs,
const std::vector<MemoryPtr>& outputs) override {
ov::intel_cpu::PlainTensor t_src(inputs[0]);
- ov::intel_cpu::PlainTensor t_cos_sin(inputs[1]);
ov::intel_cpu::PlainTensor t_dst(outputs[0]);
// [seq_len, batch_size, (hidden_states_q + hidden_states_k + hidden_states_v)]
@@ -278,27 +279,50 @@ struct RoPE::RoPEExecutorChatGLM : public RoPE::Executor {
auto rotary_dims = m_config.rotary_ndims;
- parallel_for3d(batch_size, head_cnt, seq_len, [&](size_t b, size_t h, size_t p) {
- // src [batch, length, H x S]
- auto* src = t_src.ptr<T>(b, p, h * head_size);
- // [batch_size, length, ndims//2, 2]
- auto* cos_sin = &t_cos_sin.at<float>({b, p, 0, 0}, true);
- auto* dst = t_dst.ptr<T>(b, h, p, 0);
-
- if (m_rotaryKernel) {
- execJitKernel(m_rotaryKernel, src, dst, cos_sin, nullptr);
- } else {
- size_t i = 0;
- for (; i < rotary_dims; i += 2) {
- auto cosv = cos_sin[i];
- auto sinv = cos_sin[i + 1];
- dst[i] = cosv * src[i] - sinv * src[i + 1];
- dst[i + 1] = sinv * src[i] + cosv * src[i + 1];
+ if (m_config.use_rope_cache) {
+ ov::intel_cpu::PlainTensor t_cos_sin(inputs[1]);
+ parallel_for3d(batch_size, head_cnt, seq_len, [&](size_t b, size_t h, size_t p) {
+ // src [batch, length, H x S]
+ auto* src = t_src.ptr<T>(b, p, h * head_size);
+ // [batch_size, length, ndims//2, 2]
+ auto* cos_sin = &t_cos_sin.at<float>({b, p, 0, 0}, true);
+ auto* dst = t_dst.ptr<T>(b, h, p, 0);
+
+ if (m_rotaryKernel) {
+ execJitKernel(m_rotaryKernel, src, dst, cos_sin, nullptr);
+ } else {
+ size_t i = 0;
+ for (; i < rotary_dims; i += 2) {
+ auto cosv = cos_sin[i];
+ auto sinv = cos_sin[i + 1];
+ dst[i] = cosv * src[i] - sinv * src[i + 1];
+ dst[i + 1] = sinv * src[i] + cosv * src[i + 1];
+ }
}
- }
- memcpy(dst + rotary_dims, src + rotary_dims, (head_size - rotary_dims) * sizeof(T));
- });
+ memcpy(dst + rotary_dims, src + rotary_dims, (head_size - rotary_dims) * sizeof(T));
+ });
+ } else {
+ ov::intel_cpu::PlainTensor t_cos(inputs[1]);
+ ov::intel_cpu::PlainTensor t_sin(inputs[2]);
+ parallel_for3d(batch_size, head_cnt, seq_len, [&](size_t b, size_t h, size_t p) {
+ auto* src = t_src.ptr<T>(b, p, h * head_size);
+ auto* dst = t_dst.ptr<T>(b, h, p);
+ // The pattern matching ensures that cos/sin table has shape [-1, 1, 1, -1] so that only b is
+ // variable.
+ const auto* cos = t_cos.ptr<float>(b, 0, 0);
+ const auto* sin = t_sin.ptr<float>(b, 0, 0);
+ if (m_rotaryKernel) {
+ execJitKernel(m_rotaryKernel, src, dst, cos, sin);
+ } else {
+ for (size_t i = 0; i < rotary_dims; i += 2) {
+ dst[i] = cos[i / 2] * src[i] - sin[i / 2] * src[i + 1];
+ dst[i + 1] = sin[i / 2] * src[i] + cos[i / 2] * src[i + 1];
+ }
+ }
+ memcpy(dst + rotary_dims, src + rotary_dims, (head_size - rotary_dims) * sizeof(T));
+ });
+ }
} else {
auto seq_len = t_src.size(0);
auto batch_size = t_src.size(1);
@@ -307,7 +331,7 @@ struct RoPE::RoPEExecutorChatGLM : public RoPE::Executor {
auto head_size = m_config.head_size;
auto rotary_dims = m_config.rotary_ndims;
-
+ ov::intel_cpu::PlainTensor t_cos_sin(inputs[1]);
parallel_for3d(seq_len, batch_size, head_cnt, [&](size_t p, size_t b, size_t h) {
auto* src = t_src.ptr<T>(p, b, h * head_size);
// [length, batch_size, ndims//2, 2]
@@ -425,6 +449,15 @@ void RoPE::initSupportedPrimitiveDescriptors() {
rtPrecision = ov::element::f32;
}
} else if (m_config.is_chatglm) {
+ // in this case layout of cos/sin table must be [-1, 1, 1, -1]
+ if (m_config.support_2d_rope && !m_config.use_rope_cache) {
+ const auto& cos_table_shape = getInputShapeAtPort(1).getDims();
+ const auto& sin_table_shape = getInputShapeAtPort(2).getDims();
+ CPU_NODE_ASSERT(cos_table_shape[1] == 1 && cos_table_shape[2] == 1,
+ "layout of rope's cos table should be [-1, 1, 1, -1]");
+ CPU_NODE_ASSERT(sin_table_shape[1] == 1 && sin_table_shape[2] == 1,
+ "layout of rope's sin table should be [-1, 1, 1, -1]");
+ }
if (rtPrecision == ov::element::f16) {
m_executor = std::make_shared<RoPEExecutorChatGLM<ov::float16>>(m_config);
} else if (rtPrecision == ov::element::bf16) {
diff --git a/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp b/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp
index 5b5863b3577..68464ae719b 100644
--- a/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp
+++ b/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp
@@ -1096,7 +1096,6 @@ void Transformations::PostLpt() {
CPU_REGISTER_PASS_X64(postLPTPassManager, ov::pass::RoPEFusion, true);
CPU_REGISTER_PASS_ARM64(postLPTPassManager, ov::pass::RoPEFusion, true);
CPU_DISABLE_PASS_COMMON(postLPTPassManager, ov::pass::RoPEFusionFlux);
- CPU_DISABLE_PASS_COMMON(postLPTPassManager, ov::pass::RoPEFusionChatGLMHF);
CPU_REGISTER_PASS_X64(postLPTPassManager, CausalMaskPreprocessFusion);
#if defined(OPENVINO_ARCH_X86_64)
diff --git a/src/plugins/intel_cpu/tests/functional/shared_tests_instances/subgraph_tests/rotary_pos_emb.cpp b/src/plugins/intel_cpu/tests/functional/shared_tests_instances/subgraph_tests/rotary_pos_emb.cpp
index 80fc2502008..f35df5056e3 100644
--- a/src/plugins/intel_cpu/tests/functional/shared_tests_instances/subgraph_tests/rotary_pos_emb.cpp
+++ b/src/plugins/intel_cpu/tests/functional/shared_tests_instances/subgraph_tests/rotary_pos_emb.cpp
@@ -79,6 +79,13 @@ INSTANTIATE_TEST_SUITE_P(smoke_RoPETestQwenVL,
::testing::ValuesIn(vit_param)),
RoPETestQwenVL::getTestCaseName);
+INSTANTIATE_TEST_SUITE_P(smoke_RoPETestChatGLM,
+ RoPETestChatGLMHF,
+ ::testing::Combine(::testing::Values(ov::element::f32),
+ ::testing::Values(ov::test::utils::DEVICE_CPU),
+ ::testing::Values(true, false)),
+ RoPETestChatGLMHF::getTestCaseName);
+
INSTANTIATE_TEST_SUITE_P(smoke_RoPETestGPTOSS,
RoPETestGPTOSS,
::testing::Combine(
diff --git a/src/plugins/intel_gpu/tests/functional/shared_tests_instances/subgraph_tests/rotary_pos_emb.cpp b/src/plugins/intel_gpu/tests/functional/shared_tests_instances/subgraph_tests/rotary_pos_emb.cpp
index 2f207d8a111..e86c2cd5487 100644
--- a/src/plugins/intel_gpu/tests/functional/shared_tests_instances/subgraph_tests/rotary_pos_emb.cpp
+++ b/src/plugins/intel_gpu/tests/functional/shared_tests_instances/subgraph_tests/rotary_pos_emb.cpp
@@ -101,7 +101,8 @@ INSTANTIATE_TEST_SUITE_P(smoke_RoPETestChatGLM,
RoPETestChatGLMHF,
::testing::Combine(
::testing::Values(ov::element::f16, ov::element::f32),
- ::testing::Values(ov::test::utils::DEVICE_GPU)),
+ ::testing::Values(ov::test::utils::DEVICE_GPU),
+ ::testing::Values(true, false)),
RoPETestChatGLMHF::getTestCaseName);
INSTANTIATE_TEST_SUITE_P(smoke_RoPETestGPTOSS,
diff --git a/src/tests/functional/plugin/shared/include/shared_test_classes/subgraph/rotary_pos_emb.hpp b/src/tests/functional/plugin/shared/include/shared_test_classes/subgraph/rotary_pos_emb.hpp
index 05969e420ba..52ae1816310 100644
--- a/src/tests/functional/plugin/shared/include/shared_test_classes/subgraph/rotary_pos_emb.hpp
+++ b/src/tests/functional/plugin/shared/include/shared_test_classes/subgraph/rotary_pos_emb.hpp
@@ -12,6 +12,7 @@ namespace test {
using rope_params = std::tuple<ov::element::Type, std::string>;
using rope_params_2 = std::tuple<bool, ov::element::Type, std::string>;
using rope_params_qwenvit = std::tuple<ov::element::Type, std::string, std::string>;
+using rope_params_chatglm = std::tuple<ov::element::Type, std::string, bool>;
class RoPETestFlux : public SubgraphBaseTest, public testing::WithParamInterface<rope_params> {
private:
@@ -183,19 +184,20 @@ public:
static std::string getTestCaseName(const testing::TestParamInfo<rope_params>& obj);
};
-class RoPETestChatGLMHF : public SubgraphBaseTest, public testing::WithParamInterface<rope_params> {
+class RoPETestChatGLMHF : public SubgraphBaseTest, public testing::WithParamInterface<rope_params_chatglm> {
private:
std::shared_ptr<ov::Model> buildROPE_ChatGLMHF(int seq_length,
int num_heads,
int rotary_ndims,
- ov::element::Type element_type);
+ ov::element::Type element_type,
+ bool use_split);
protected:
void generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) override;
void SetUp() override;
public:
- static std::string getTestCaseName(const testing::TestParamInfo<rope_params>& obj);
+ static std::string getTestCaseName(const testing::TestParamInfo<rope_params_chatglm>& obj);
};
class RoPETestGPTOSS : public SubgraphBaseTest, public testing::WithParamInterface<rope_params> {
diff --git a/src/tests/functional/plugin/shared/src/subgraph/rotary_pos_emb.cpp b/src/tests/functional/plugin/shared/src/subgraph/rotary_pos_emb.cpp
index e6dfa4af300..034397eaf81 100644
--- a/src/tests/functional/plugin/shared/src/subgraph/rotary_pos_emb.cpp
+++ b/src/tests/functional/plugin/shared/src/subgraph/rotary_pos_emb.cpp
@@ -1345,7 +1345,8 @@ std::string RoPETestChatGLM2DRoPEStridedSlice::getTestCaseName(const testing::Te
std::shared_ptr<ov::Model> RoPETestChatGLMHF::buildROPE_ChatGLMHF(int seq_length,
int num_heads,
int rotary_ndims,
- ov::element::Type element_type) {
+ ov::element::Type element_type,
+ bool use_split) {
auto input = std::make_shared<ov::opset1::Parameter>(element_type, PartialShape{seq_length, 1, 4096});
auto cos =
std::make_shared<ov::opset1::Parameter>(element_type, PartialShape{seq_length, 1, 1, (rotary_ndims / 2)});
@@ -1353,12 +1354,18 @@ std::shared_ptr<ov::Model> RoPETestChatGLMHF::buildROPE_ChatGLMHF(int seq_length
std::make_shared<ov::opset1::Parameter>(element_type, PartialShape{seq_length, 1, 1, (rotary_ndims / 2)});
auto transpose = makeOP<ov::opset1::Reshape>({input, {-1, num_heads, 1, 128}}, {{"special_zero", false}});
- auto slice_1 = makeOP<ov::opset1::StridedSlice>({transpose, {0, 0, 0, 0}, {0, 0, 0, rotary_ndims}, {1, 1, 1, 1}},
- {{"begin_mask", {1, 1, 1, 0}},
- {"end_mask", {1, 1, 1, 0}},
- {"new_axis_mask", {}},
- {"shrink_axis_mask", {}},
- {"ellipsis_mask", {}}});
+ std::shared_ptr<ov::Node> slice_or_split_1 = nullptr;
+ if (use_split) {
+ slice_or_split_1 = makeOP<ov::opset1::VariadicSplit>({transpose, 3, {rotary_ndims, rotary_ndims}});
+ } else {
+ slice_or_split_1 =
+ makeOP<ov::opset1::StridedSlice>({transpose, {0, 0, 0, 0}, {0, 0, 0, rotary_ndims}, {1, 1, 1, 1}},
+ {{"begin_mask", {1, 1, 1, 0}},
+ {"end_mask", {1, 1, 1, 0}},
+ {"new_axis_mask", {}},
+ {"shrink_axis_mask", {}},
+ {"ellipsis_mask", {}}});
+ }
std::vector<int32_t> rpi_idx(rotary_ndims, 1);
int32_t v = 0;
@@ -1370,8 +1377,8 @@ std::shared_ptr<ov::Model> RoPETestChatGLMHF::buildROPE_ChatGLMHF(int seq_length
auto repeat_interleave_cos = makeOP<ov::opset8::Gather>({cos, repeat_interleave_index, -1}, {{"batch_dims", 0}});
auto repeat_interleave_sin = makeOP<ov::opset8::Gather>({cos, repeat_interleave_index, -1}, {{"batch_dims", 0}});
- auto multiply = makeOP<ov::opset1::Multiply>({slice_1, repeat_interleave_cos}, {{"auto_broadcast", "numpy"}});
- auto slice_2 = makeOP<ov::opset1::StridedSlice>({slice_1, {0, 0, 0, 1}, {0, 0, 0, INT_MAX}, {1, 1, 1, 2}},
+ auto multiply = makeOP<ov::opset1::Multiply>({slice_or_split_1->output(0), repeat_interleave_cos}, {{"auto_broadcast", "numpy"}});
+ auto slice_2 = makeOP<ov::opset1::StridedSlice>({slice_or_split_1->output(0), {0, 0, 0, 1}, {0, 0, 0, INT_MAX}, {1, 1, 1, 2}},
{{"begin_mask", {1, 1, 1, 0}},
{"end_mask", {1, 1, 1, 0}},
{"new_axis_mask", {}},
@@ -1381,7 +1388,7 @@ std::shared_ptr<ov::Model> RoPETestChatGLMHF::buildROPE_ChatGLMHF(int seq_length
auto neg = makeOP<ov::opset1::Multiply>({slice_2, minus_one}, {{"auto_broadcast", "numpy"}});
auto unsqueeze_1 =
makeOP<ov::opset1::Reshape>({neg, {-1, num_heads, 1, (rotary_ndims / 2), 1}}, {{"special_zero", false}});
- auto slice_3 = makeOP<ov::opset1::StridedSlice>({slice_1, {0, 0, 0, 0}, {0, 0, 0, INT_MAX}, {1, 1, 1, 2}},
+ auto slice_3 = makeOP<ov::opset1::StridedSlice>({slice_or_split_1->output(0), {0, 0, 0, 0}, {0, 0, 0, INT_MAX}, {1, 1, 1, 2}},
{{"begin_mask", {1, 1, 1, 0}},
{"end_mask", {1, 1, 1, 0}},
{"new_axis_mask", {}},
@@ -1393,15 +1400,20 @@ std::shared_ptr<ov::Model> RoPETestChatGLMHF::buildROPE_ChatGLMHF(int seq_length
auto flatten = makeOP<ov::opset1::Reshape>({stack, {0, num_heads, 0, rotary_ndims}}, {{"special_zero", true}});
auto multiply_1 = makeOP<ov::opset1::Multiply>({flatten, repeat_interleave_sin}, {{"auto_broadcast", "numpy"}});
auto add = makeOP<ov::opset1::Add>({multiply, multiply_1}, {{"auto_broadcast", "numpy"}});
-
- auto slice_5 =
- makeOP<ov::opset1::StridedSlice>({transpose, {0, 0, 0, rotary_ndims}, {0, 0, 0, INT_MAX}, {1, 1, 1, 1}},
- {{"begin_mask", {1, 1, 1, 0}},
- {"end_mask", {1, 1, 1, 0}},
- {"new_axis_mask", {}},
- {"shrink_axis_mask", {}},
- {"ellipsis_mask", {}}});
- auto concat = makeOP<ov::opset1::Concat>({add, slice_5}, {{"axis", -1}});
+ std::shared_ptr<ov::Node> slice_or_split_5 = nullptr;
+ if (use_split) {
+ slice_or_split_5 = slice_or_split_1;
+ } else {
+ slice_or_split_5 =
+ makeOP<ov::opset1::StridedSlice>({transpose, {0, 0, 0, rotary_ndims}, {0, 0, 0, INT_MAX}, {1, 1, 1, 1}},
+ {{"begin_mask", {1, 1, 1, 0}},
+ {"end_mask", {1, 1, 1, 0}},
+ {"new_axis_mask", {}},
+ {"shrink_axis_mask", {}},
+ {"ellipsis_mask", {}}});
+ }
+ ov::Output<ov::Node> slice_or_split_output_5 = use_split ? slice_or_split_5->output(1) : slice_or_split_5->output(0);
+ auto concat = makeOP<ov::opset1::Concat>({add, slice_or_split_output_5}, {{"axis", -1}});
return std::make_shared<ov::Model>(ov::OutputVector{concat}, ov::ParameterVector{input, cos, sin});
}
@@ -1436,7 +1448,7 @@ void RoPETestChatGLMHF::generate_inputs(const std::vector<ov::Shape>& targetInpu
}
void RoPETestChatGLMHF::SetUp() {
- const auto& [element_type, _targetDevice] = this->GetParam();
+ const auto& [element_type, _targetDevice, use_split] = this->GetParam();
targetDevice = _targetDevice;
const int seq_length = 7;
@@ -1447,13 +1459,13 @@ void RoPETestChatGLMHF::SetUp() {
{{-1, 1, 1, (rotary_ndims / 2)}, {{seq_length, 1, 1, (rotary_ndims / 2)}}},
{{-1, 1, 1, (rotary_ndims / 2)}, {{seq_length, 1, 1, (rotary_ndims / 2)}}}};
init_input_shapes(input_shapes);
- function = buildROPE_ChatGLMHF(-1, num_heads, rotary_ndims, element_type);
+ function = buildROPE_ChatGLMHF(-1, num_heads, rotary_ndims, element_type, use_split);
}
-std::string RoPETestChatGLMHF::getTestCaseName(const testing::TestParamInfo<rope_params>& obj) {
- const auto& [element_type, targetDevice] = obj.param;
+std::string RoPETestChatGLMHF::getTestCaseName(const testing::TestParamInfo<rope_params_chatglm>& obj) {
+ const auto& [element_type, targetDevice, use_split] = obj.param;
std::ostringstream result;
- result << "targetDevice=" << targetDevice << "_element_type=" << element_type.to_string();
+ result << "targetDevice=" << targetDevice << "_element_type=" << element_type.to_string() << "_use_split_" << use_split;
return result.str();
}