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
[CPU] Support independent PagedSelectiveSSM state precision (#37660)
Nesterov Alexander42f805803eb9
diff --git a/src/common/transformations/tests/common_optimizations/convert_pagedattn_inputs.cpp b/src/common/transformations/tests/common_optimizations/convert_pagedattn_inputs.cppindex fda7af40509..625b95846b5 100644--- a/src/common/transformations/tests/common_optimizations/convert_pagedattn_inputs.cpp+++ b/src/common/transformations/tests/common_optimizations/convert_pagedattn_inputs.cpp@@ -597,9 +597,81 @@ TEST_F(ConvertPagedAttnInputsStateTableTest, ConvertPagedSelectiveSSMPrecision)local_manager.register_pass<ov::pass::ConvertPagedAttnInputs>(cacheConfig, update_paged_attention_shape_func);local_manager.run_passes(local_model);+ for (size_t input = 0; input < 5; ++input) {+ EXPECT_EQ(paged_ssm->get_input_element_type(input), element::f16);+ }// Verify no Convert node between Parameter and PagedSelectiveSSMEXPECT_TRUE(ov::is_type<v0::Parameter>(paged_ssm->get_input_node_shared_ptr(5)));EXPECT_EQ(selective_ssm_state_table->get_element_type(), ov::element::f16);+ EXPECT_EQ(paged_ssm->get_output_element_type(0), element::f16);+}++TEST_F(ConvertPagedAttnInputsStateTableTest, ConvertPagedSelectiveSSMIndependentStatePrecision) {+ auto A = std::make_shared<v0::Parameter>(element::f32, PartialShape{4});+ auto dt = std::make_shared<v0::Parameter>(element::f32, PartialShape{-1, 4});+ auto B = std::make_shared<v0::Parameter>(element::f32, PartialShape{-1, 2, 16});+ auto x = std::make_shared<v0::Parameter>(element::f32, PartialShape{-1, 4, 8});+ auto C = std::make_shared<v0::Parameter>(element::f32, PartialShape{-1, 2, 16});+ auto selective_ssm_state_table = std::make_shared<v0::Parameter>(element::dynamic, PartialShape{-1, 4, 8, 16});+ selective_ssm_state_table->set_friendly_name("selective_ssm_state_table.0");+ for (const auto& parameter : {A, dt, B, x, C, selective_ssm_state_table}) {+ enable_keep_const_precision(parameter);+ }+ auto subsequence_begins = std::make_shared<v0::Parameter>(element::i32, PartialShape{-1});+ auto block_indices = std::make_shared<v0::Parameter>(element::i32, PartialShape{-1});+ auto block_indices_begins = std::make_shared<v0::Parameter>(element::i32, PartialShape{-1});+ auto num_processed_tokens = std::make_shared<v0::Parameter>(element::i32, PartialShape{-1});+ auto cache_interval = std::make_shared<v0::Parameter>(element::i32, PartialShape{-1});++ auto paged_ssm = std::make_shared<op::internal::PagedSelectiveSSM>(A,+ dt,+ B,+ x,+ C,+ selective_ssm_state_table,+ subsequence_begins,+ block_indices,+ block_indices_begins,+ num_processed_tokens,+ cache_interval);+ auto local_model = std::make_shared<Model>(OutputVector{paged_ssm},+ ParameterVector{A,+ dt,+ B,+ x,+ C,+ selective_ssm_state_table,+ subsequence_begins,+ block_indices,+ block_indices_begins,+ num_processed_tokens,+ cache_interval});++ ov::pass::ConvertPagedAttnInputs::KVCacheConfig cacheConfig;+ cacheConfig.inferencePrecision = ov::element::f16;++ ov::pass::Manager local_manager;++ precisions_map fp_convert_precision_map = {{ov::element::f64, ov::element::f32},+ {ov::element::f32, ov::element::f16}};+ type_to_fuse_map empty_fuse_map = {};+ local_manager.register_pass<ov::pass::ConvertPrecision>(fp_convert_precision_map,+ empty_fuse_map,+ /*keep_precision_sensitive_in_fp32*/ true,+ /*convert_input_output_precision*/ false,+ /*store_original_precision_as_rt_attribute*/ true);++ auto update_paged_attention_shape_func =+ [](const ov::element::Type&, const bool, const size_t, int64_t&, int64_t&) {};+ local_manager.register_pass<ov::pass::ConvertPagedAttnInputs>(cacheConfig, update_paged_attention_shape_func);+ local_manager.run_passes(local_model);++ for (size_t input = 0; input < 5; ++input) {+ EXPECT_EQ(paged_ssm->get_input_element_type(input), element::f32);+ }+ EXPECT_TRUE(ov::is_type<v0::Parameter>(paged_ssm->get_input_node_shared_ptr(5)));+ EXPECT_EQ(selective_ssm_state_table->get_element_type(), ov::element::f16);+ EXPECT_EQ(paged_ssm->get_output_element_type(0), element::f32);}} // namespacediff --git a/src/core/src/op/paged_selective_ssm.cpp b/src/core/src/op/paged_selective_ssm.cppindex 5a1c845cae0..a2ede7aa7ed 100644--- a/src/core/src/op/paged_selective_ssm.cpp+++ b/src/core/src/op/paged_selective_ssm.cpp@@ -49,18 +49,22 @@ void PagedSelectiveSSM::validate_and_infer_types() {ov::element::Type common_float_type = get_input_element_type(0);bool float_types_merge = true;- for (size_t input = 1; input < 6; ++input) {+ for (size_t input = 1; input < 5; ++input) {float_types_merge &=ov::element::Type::merge(common_float_type, common_float_type, get_input_element_type(input));}NODE_VALIDATION_CHECK(this,float_types_merge,- "PagedSelectiveSSM expects inputs A, dt, B, x, C and recurrent_state_table to have the "- "same element type.");+ "PagedSelectiveSSM expects inputs A, dt, B, x, and C to have the same element type.");NODE_VALIDATION_CHECK(this,common_float_type.is_dynamic() || common_float_type == ov::element::f32 ||common_float_type == ov::element::f16 || common_float_type == ov::element::bf16,"PagedSelectiveSSM data inputs must have f32, f16, or bf16 element type.");+ const auto& state_type = get_input_element_type(5);+ NODE_VALIDATION_CHECK(this,+ state_type.is_dynamic() || state_type == ov::element::f32 || state_type == ov::element::f16 ||+ state_type == ov::element::bf16,+ "PagedSelectiveSSM recurrent_state_table must have f32, f16, or bf16 element type.");ov::element::Type common_index_type = get_input_element_type(6);bool index_types_merge = true;diff --git a/src/core/tests/type_prop/paged_selective_ssm.cpp b/src/core/tests/type_prop/paged_selective_ssm.cppindex b22e59b6296..18d366b990c 100644--- a/src/core/tests/type_prop/paged_selective_ssm.cpp+++ b/src/core/tests/type_prop/paged_selective_ssm.cpp@@ -13,6 +13,7 @@ namespace ov::test {namespace {std::shared_ptr<op::internal::PagedSelectiveSSM> make_paged_selective_ssm(const element::Type& et,+ const element::Type& state_et,const element::Type& ind_et,const PartialShape& A,const PartialShape& dt,@@ -25,7 +26,7 @@ std::shared_ptr<op::internal::PagedSelectiveSSM> make_paged_selective_ssm(constauto B_p = std::make_shared<op::v0::Parameter>(et, B);auto x_p = std::make_shared<op::v0::Parameter>(et, x);auto C_p = std::make_shared<op::v0::Parameter>(et, C);- auto state_p = std::make_shared<op::v0::Parameter>(et, state);+ auto state_p = std::make_shared<op::v0::Parameter>(state_et, state);auto subseq = std::make_shared<op::v0::Parameter>(ind_et, PartialShape{-1});auto block_idx = std::make_shared<op::v0::Parameter>(ind_et, PartialShape{-1});auto block_idx_begins = std::make_shared<op::v0::Parameter>(ind_et, PartialShape{-1});@@ -45,6 +46,17 @@ std::shared_ptr<op::internal::PagedSelectiveSSM> make_paged_selective_ssm(constcache_interval});}+std::shared_ptr<op::internal::PagedSelectiveSSM> make_paged_selective_ssm(const element::Type& et,+ const element::Type& ind_et,+ const PartialShape& A,+ const PartialShape& dt,+ const PartialShape& B,+ const PartialShape& x,+ const PartialShape& C,+ const PartialShape& state) {+ return make_paged_selective_ssm(et, et, ind_et, A, dt, B, x, C, state);+}+} // namespaceTEST(type_prop, paged_selective_ssm_static_f32) {@@ -75,32 +87,44 @@ TEST(type_prop, paged_selective_ssm_partial_shape_infer) {EXPECT_EQ(op->get_output_partial_shape(0), PartialShape(Shape{6, 4, 8}));}-TEST(type_prop, paged_selective_ssm_state_type_must_match) {- auto A_p = std::make_shared<op::v0::Parameter>(element::f16, Shape{4});- auto dt_p = std::make_shared<op::v0::Parameter>(element::f16, Shape{6, 4});- auto B_p = std::make_shared<op::v0::Parameter>(element::f16, Shape{6, 2, 16});- auto x_p = std::make_shared<op::v0::Parameter>(element::f16, Shape{6, 4, 8});- auto C_p = std::make_shared<op::v0::Parameter>(element::f16, Shape{6, 2, 16});- auto state_p = std::make_shared<op::v0::Parameter>(element::bf16, Shape{3, 4, 8, 16});- auto subseq = std::make_shared<op::v0::Parameter>(element::i64, PartialShape{-1});- auto block_idx = std::make_shared<op::v0::Parameter>(element::i64, PartialShape{-1});- auto block_idx_begins = std::make_shared<op::v0::Parameter>(element::i64, PartialShape{-1});- auto processed = std::make_shared<op::v0::Parameter>(element::i64, PartialShape{-1});- auto cache_interval = std::make_shared<op::v0::Parameter>(element::i64, PartialShape{-1});-- OV_EXPECT_THROW(std::ignore = std::make_shared<op::internal::PagedSelectiveSSM>(OutputVector{A_p,- dt_p,- B_p,- x_p,- C_p,- state_p,- subseq,- block_idx,- block_idx_begins,- processed,- cache_interval}),- NodeValidationFailure,- testing::HasSubstr("recurrent_state_table to have the same element type."));+TEST(type_prop, paged_selective_ssm_state_type_is_independent) {+ const auto check_types =+ [](const element::Type& data_type, const element::Type& state_type, const element::Type& index_type) {+ const auto op = make_paged_selective_ssm(data_type,+ state_type,+ index_type,+ Shape{4},+ Shape{6, 4},+ Shape{6, 2, 16},+ Shape{6, 4, 8},+ Shape{6, 2, 16},+ Shape{3, 4, 8, 16});+ EXPECT_EQ(op->get_output_element_type(0), data_type);+ };++ check_types(element::f16, element::bf16, element::i64);+ check_types(element::f32, element::f16, element::i32);+ check_types(element::f16, element::f32, element::i32);+ check_types(element::f32, element::dynamic, element::i32);+}++TEST(type_prop, paged_selective_ssm_merges_dynamic_computation_input_type) {+ auto A = std::make_shared<op::v0::Parameter>(element::dynamic, Shape{4});+ auto dt = std::make_shared<op::v0::Parameter>(element::f32, Shape{6, 4});+ auto B = std::make_shared<op::v0::Parameter>(element::f32, Shape{6, 2, 16});+ auto x = std::make_shared<op::v0::Parameter>(element::f32, Shape{6, 4, 8});+ auto C = std::make_shared<op::v0::Parameter>(element::f32, Shape{6, 2, 16});+ auto state = std::make_shared<op::v0::Parameter>(element::f16, Shape{3, 4, 8, 16});+ auto subseq = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{-1});+ auto block_idx = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{-1});+ auto block_idx_begins = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{-1});+ auto processed = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{-1});+ auto cache_interval = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{-1});++ const auto op = std::make_shared<op::internal::PagedSelectiveSSM>(+ OutputVector{A, dt, B, x, C, state, subseq, block_idx, block_idx_begins, processed, cache_interval});++ EXPECT_EQ(op->get_output_element_type(0), element::f32);}TEST(type_prop, paged_selective_ssm_bad_index_type) {@@ -512,8 +536,7 @@ TEST(type_prop, paged_selective_ssm_type_mismatch) {std::ignore = std::make_shared<op::internal::PagedSelectiveSSM>(OutputVector{A, dt, B, x, C, state, subseq, block_idx, block_idx_begins, processed, cache_interval}),NodeValidationFailure,- testing::HasSubstr("PagedSelectiveSSM expects inputs A, dt, B, x, C and recurrent_state_table to have the same "- "element type."));+ testing::HasSubstr("PagedSelectiveSSM expects inputs A, dt, B, x, and C to have the same element type."));}TEST(type_prop, paged_selective_ssm_state_float_type_invalid) {@@ -533,7 +556,7 @@ TEST(type_prop, paged_selective_ssm_state_float_type_invalid) {std::ignore = std::make_shared<op::internal::PagedSelectiveSSM>(OutputVector{A, dt, B, x, C, state, subseq, block_idx, block_idx_begins, processed, cache_interval}),NodeValidationFailure,- testing::HasSubstr("recurrent_state_table to have the same element type."));+ testing::HasSubstr("PagedSelectiveSSM recurrent_state_table must have f32, f16, or bf16 element type."));}TEST(type_prop, paged_selective_ssm_index_type_mixed) {diff --git a/src/plugins/intel_cpu/src/nodes/executors/common/paged_selective_ssm_executor.cpp b/src/plugins/intel_cpu/src/nodes/executors/common/paged_selective_ssm_executor.cppindex c5e4e7e1f97..1af3a32a2e1 100644--- a/src/plugins/intel_cpu/src/nodes/executors/common/paged_selective_ssm_executor.cpp+++ b/src/plugins/intel_cpu/src/nodes/executors/common/paged_selective_ssm_executor.cpp@@ -47,7 +47,6 @@ bool PagedSelectiveSSMExecutor::supports(const PagedSelectiveSSMConfig& config)ARG_PAGED_SSM_B,ARG_PAGED_SSM_X,ARG_PAGED_SSM_C,- ARG_PAGED_SSM_STATE,ARG_PAGED_SSM_OUT,};if (!std::all_of(data_args.begin(), data_args.end(), [&](const auto arg) {@@ -55,6 +54,9 @@ bool PagedSelectiveSSMExecutor::supports(const PagedSelectiveSSMConfig& config)})) {return false;}+ if (!is_supported_data_precision(config.descs.at(ARG_PAGED_SSM_STATE)->getPrecision())) {+ return false;+ }const auto index_precision = config.descs.at(ARG_PAGED_SSM_SUBSEQUENCE_BEGINS)->getPrecision();if (!is_supported_index_precision(index_precision)) {@@ -90,7 +92,7 @@ bool PagedSelectiveSSMExecutor::update_scratchpad(const MemoryArgs& memory) {const auto& B_dims = B_shape.getStaticDims();const auto& state_dims = state_shape.getStaticDims();const auto& subsequence_dims = subsequence_shape.getStaticDims();- const auto precision = memory.at(ARG_PAGED_SSM_X)->getDescPtr()->getPrecision();+ const auto data_precision = memory.at(ARG_PAGED_SSM_X)->getDescPtr()->getPrecision();OPENVINO_ASSERT(x_dims.size() == 3 && B_dims.size() == 3 && state_dims.size() == 4 &&subsequence_dims.size() == 1 && subsequence_dims[0] >= 1);const auto head_dim = x_dims[2];@@ -106,7 +108,7 @@ bool PagedSelectiveSSMExecutor::update_scratchpad(const MemoryArgs& memory) {const auto projection_elements =node::kernel::checked_size_product({B_dims[0], B_dims[1], B_dims[2]}, "B/C projection");const auto projection_scratch_elements =- precision == ov::element::f32+ data_precision == ov::element::f32? size_t{0}: node::kernel::checked_size_product({size_t{2}, projection_elements}, "B/C projection scratch");const auto metadata_scratch_elements = state_dims[0];@@ -149,7 +151,8 @@ void PagedSelectiveSSMExecutor::execute(const MemoryArgs& memory) {const auto& interval_dims = memory.at(ARG_PAGED_SSM_CACHE_INTERVAL)->getStaticDims();OPENVINO_ASSERT(B_dims.size() == 3 && x_dims.size() == 3 && state_dims.size() == 4);OPENVINO_ASSERT(subsequence_dims.size() == 1 && subsequence_dims[0] >= 1 && block_indices_dims.size() == 1);- const auto precision = memory.at(ARG_PAGED_SSM_X)->getDescPtr()->getPrecision();+ const auto data_precision = memory.at(ARG_PAGED_SSM_X)->getDescPtr()->getPrecision();+ const auto state_precision = memory.at(ARG_PAGED_SSM_STATE)->getDescPtr()->getPrecision();const auto projection_elements =node::kernel::checked_size_product({B_dims[0], B_dims[1], B_dims[2]}, "B/C projection");const auto sequence_count = subsequence_dims[0] - 1;@@ -160,7 +163,7 @@ void PagedSelectiveSSMExecutor::execute(const MemoryArgs& memory) {const auto expected_state_scratch_elements =node::kernel::checked_size_product({thread_count, expected_scratch_head_dim, state_dims[3]}, "state scratch");const auto expected_projection_scratch_elements =- precision == ov::element::f32+ data_precision == ov::element::f32? size_t{0}: node::kernel::checked_size_product({size_t{2}, projection_elements}, "B/C projection scratch");const auto expected_metadata_scratch_elements = state_dims[0];@@ -191,19 +194,19 @@ void PagedSelectiveSSMExecutor::execute(const MemoryArgs& memory) {reinterpret_cast<int32_t*>(state_scratch + m_state_scratch_elements + m_projection_scratch_elements);const float* converted_B = nullptr;const float* converted_C = nullptr;- if (precision != ov::element::f32) {+ if (data_precision != ov::element::f32) {auto* projection_scratch = state_scratch + m_state_scratch_elements;converted_B = projection_scratch;converted_C = projection_scratch + projection_elements;if (projection_elements > 0) {cpu_parallel_convert(memory.at(ARG_PAGED_SSM_B)->getData(),projection_scratch,- precision,+ data_precision,ov::element::f32,projection_elements);cpu_parallel_convert(memory.at(ARG_PAGED_SSM_C)->getData(),projection_scratch + projection_elements,- precision,+ data_precision,ov::element::f32,projection_elements);}@@ -221,7 +224,8 @@ void PagedSelectiveSSMExecutor::execute(const MemoryArgs& memory) {memory.at(ARG_PAGED_SSM_CACHE_INTERVAL)->getData(),memory.at(ARG_PAGED_SSM_OUT)->getData(),shape,- precision,+ data_precision,+ state_precision,memory.at(ARG_PAGED_SSM_SUBSEQUENCE_BEGINS)->getDescPtr()->getPrecision(),state_scratch,m_scratch_head_dim,diff --git a/src/plugins/intel_cpu/src/nodes/kernels/selective_ssm.cpp b/src/plugins/intel_cpu/src/nodes/kernels/selective_ssm.cppindex 2e030da74d5..6f1e7e25518 100644--- a/src/plugins/intel_cpu/src/nodes/kernels/selective_ssm.cpp+++ b/src/plugins/intel_cpu/src/nodes/kernels/selective_ssm.cpp@@ -340,13 +340,13 @@ void validate_paged_metadata(const PagedMetadata& metadata,}}-template <typename DataT, typename ProjectionT>+template <typename DataT, typename StateT, typename ProjectionT>void paged_selective_ssm_typed(const DataT* A,const DataT* dt,const ProjectionT* B,const DataT* x,const ProjectionT* C,- DataT* recurrent_state_table,+ StateT* recurrent_state_table,const PagedMetadata& metadata,DataT* output,const PagedSelectiveSSMShape& shape,@@ -471,7 +471,7 @@ void dispatch_selective_projection(const void* A,}}-template <typename DataT>+template <typename DataT, typename StateT>void dispatch_paged_projection(const void* A,const void* dt,const void* B,@@ -492,7 +492,7 @@ void dispatch_paged_projection(const void* A,B_data,static_cast<const DataT*>(x),C_data,- static_cast<DataT*>(recurrent_state_table),+ static_cast<StateT*>(recurrent_state_table),metadata,static_cast<DataT*>(output),shape,@@ -507,6 +507,58 @@ void dispatch_paged_projection(const void* A,}}+struct PagedSelectiveSSMCallArgs {+ const void* A;+ const void* dt;+ const void* B;+ const void* x;+ const void* C;+ void* recurrent_state_table;+ const PagedMetadata& metadata;+ void* output;+ const PagedSelectiveSSMShape& shape;+ float* state_scratch;+ size_t scratch_head_dim;+ const CpuParallelPtr& cpu_parallel;+ const float* converted_B;+ const float* converted_C;+};++template <typename DataT, typename StateT>+void dispatch_paged_typed(const PagedSelectiveSSMCallArgs& args) {+ dispatch_paged_projection<DataT, StateT>(args.A,+ args.dt,+ args.B,+ args.x,+ args.C,+ args.recurrent_state_table,+ args.metadata,+ args.output,+ args.shape,+ args.state_scratch,+ args.scratch_head_dim,+ args.cpu_parallel,+ args.converted_B,+ args.converted_C);+}++template <typename DataT>+void dispatch_paged_state_type(const PagedSelectiveSSMCallArgs& args, const ov::element::Type& state_precision) {+ switch (state_precision) {+ case ov::element::f32:+ dispatch_paged_typed<DataT, float>(args);+ return;+ case ov::element::f16:+ dispatch_paged_typed<DataT, ov::float16>(args);+ return;+ case ov::element::bf16:+ dispatch_paged_typed<DataT, ov::bfloat16>(args);+ return;+ default:+ OPENVINO_THROW("PagedSelectiveSSM supports only f32/f16/bf16 state, got ", state_precision, ".");+ }+}+} // namespacesize_t checked_size_product(std::initializer_list<size_t> dimensions, const char* tensor_name) {@@ -609,7 +661,8 @@ void paged_selective_ssm(const void* A,const void* cache_interval,void* output,const PagedSelectiveSSMShape& shape,- const ov::element::Type& precision,+ const ov::element::Type& data_precision,+ const ov::element::Type& state_precision,const ov::element::Type& index_precision,float* state_scratch,size_t scratch_head_dim,@@ -630,31 +683,33 @@ void paged_selective_ssm(const void* A,if (metadata_validation_scratch != nullptr) {validate_paged_metadata(metadata, shape, metadata_validation_scratch);}-#define OV_CPU_PAGED_SSM_CALL(DataT) \- dispatch_paged_projection<DataT>(A, \- dt, \- B, \- x, \- C, \- recurrent_state_table, \- metadata, \- output, \- shape, \- state_scratch, \- scratch_head_dim, \- cpu_parallel, \- converted_B, \- converted_C)- if (precision == ov::element::f32) {- OV_CPU_PAGED_SSM_CALL(float);- } else if (precision == ov::element::f16) {- OV_CPU_PAGED_SSM_CALL(ov::float16);- } else if (precision == ov::element::bf16) {- OV_CPU_PAGED_SSM_CALL(ov::bfloat16);- } else {- OPENVINO_THROW("PagedSelectiveSSM supports only f32/f16/bf16, got ", precision, ".");+ const PagedSelectiveSSMCallArgs args{A,+ dt,+ B,+ x,+ C,+ recurrent_state_table,+ metadata,+ output,+ shape,+ state_scratch,+ scratch_head_dim,+ cpu_parallel,+ converted_B,+ converted_C};+ switch (data_precision) {+ case ov::element::f32:+ dispatch_paged_state_type<float>(args, state_precision);+ return;+ case ov::element::f16:+ dispatch_paged_state_type<ov::float16>(args, state_precision);+ return;+ case ov::element::bf16:+ dispatch_paged_state_type<ov::bfloat16>(args, state_precision);+ return;+ default:+ OPENVINO_THROW("PagedSelectiveSSM supports only f32/f16/bf16 data, got ", data_precision, ".");}-#undef OV_CPU_PAGED_SSM_CALL}} // namespace ov::intel_cpu::node::kerneldiff --git a/src/plugins/intel_cpu/src/nodes/kernels/selective_ssm.hpp b/src/plugins/intel_cpu/src/nodes/kernels/selective_ssm.hppindex 964f7c313f9..3b6706ebc64 100644--- a/src/plugins/intel_cpu/src/nodes/kernels/selective_ssm.hpp+++ b/src/plugins/intel_cpu/src/nodes/kernels/selective_ssm.hpp@@ -67,7 +67,8 @@ void paged_selective_ssm(const void* A,const void* cache_interval,void* output,const PagedSelectiveSSMShape& shape,- const ov::element::Type& precision,+ const ov::element::Type& data_precision,+ const ov::element::Type& state_precision,const ov::element::Type& index_precision,float* state_scratch,size_t scratch_head_dim,diff --git a/src/plugins/intel_cpu/src/nodes/paged_selective_ssm.cpp b/src/plugins/intel_cpu/src/nodes/paged_selective_ssm.cppindex 6b0ce309563..66928a54475 100644--- a/src/plugins/intel_cpu/src/nodes/paged_selective_ssm.cpp+++ b/src/plugins/intel_cpu/src/nodes/paged_selective_ssm.cpp@@ -35,21 +35,27 @@ namespace ov::intel_cpu::node {namespace {using InputPortBinding = std::pair<int, size_t>;+constexpr auto output_port = output_port_index(PagedSelectiveSSMOutputPort::Output);constexpr std::array input_port_bindings{- InputPortBinding{ARG_PAGED_SSM_A, 0},- InputPortBinding{ARG_PAGED_SSM_DT, 1},- InputPortBinding{ARG_PAGED_SSM_B, 2},- InputPortBinding{ARG_PAGED_SSM_X, 3},- InputPortBinding{ARG_PAGED_SSM_C, 4},- InputPortBinding{ARG_PAGED_SSM_STATE, 5},- InputPortBinding{ARG_PAGED_SSM_SUBSEQUENCE_BEGINS, 6},- InputPortBinding{ARG_PAGED_SSM_BLOCK_INDICES, 7},- InputPortBinding{ARG_PAGED_SSM_BLOCK_INDICES_BEGINS, 8},- InputPortBinding{ARG_PAGED_SSM_NUM_PROCESSED_TOKENS, 9},- InputPortBinding{ARG_PAGED_SSM_CACHE_INTERVAL, 10},+ InputPortBinding{ARG_PAGED_SSM_A, input_port_index(PagedSelectiveSSMInputPort::A)},+ InputPortBinding{ARG_PAGED_SSM_DT, input_port_index(PagedSelectiveSSMInputPort::TimeStep)},+ InputPortBinding{ARG_PAGED_SSM_B, input_port_index(PagedSelectiveSSMInputPort::InputProjection)},+ InputPortBinding{ARG_PAGED_SSM_X, input_port_index(PagedSelectiveSSMInputPort::Input)},+ InputPortBinding{ARG_PAGED_SSM_C, input_port_index(PagedSelectiveSSMInputPort::OutputProjection)},+ InputPortBinding{ARG_PAGED_SSM_STATE, input_port_index(PagedSelectiveSSMInputPort::State)},+ InputPortBinding{ARG_PAGED_SSM_SUBSEQUENCE_BEGINS, input_port_index(PagedSelectiveSSMInputPort::SubsequenceBegins)},+ InputPortBinding{ARG_PAGED_SSM_BLOCK_INDICES, input_port_index(PagedSelectiveSSMInputPort::BlockIndices)},+ InputPortBinding{ARG_PAGED_SSM_BLOCK_INDICES_BEGINS,+ input_port_index(PagedSelectiveSSMInputPort::BlockIndicesBegins)},+ InputPortBinding{ARG_PAGED_SSM_NUM_PROCESSED_TOKENS,+ input_port_index(PagedSelectiveSSMInputPort::NumProcessedTokens)},+ InputPortBinding{ARG_PAGED_SSM_CACHE_INTERVAL, input_port_index(PagedSelectiveSSMInputPort::CacheInterval)},};+static_assert(input_port_bindings.size() == paged_ssm_input_count);+static_assert(paged_ssm_output_count == 1);+} // namespacePagedSelectiveSSM::PagedSelectiveSSM(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr& context)@@ -61,33 +67,51 @@ PagedSelectiveSSM::PagedSelectiveSSM(const std::shared_ptr<ov::Node>& op, const}void PagedSelectiveSSM::initSupportedPrimitiveDescriptors() {- const auto data_precision = getOriginalInputPrecisionAtPort(0);+ const auto data_precision = getOriginalInputPrecisionAtPort(input_port_index(PagedSelectiveSSMInputPort::Input));OPENVINO_ASSERT(any_of(data_precision, ov::element::f32, ov::element::f16, ov::element::bf16),"PagedSelectiveSSM supports only f32/f16/bf16 data, got ",data_precision,".");- for (size_t port = 1; port <= 5; ++port) {- OPENVINO_ASSERT(getOriginalInputPrecisionAtPort(port) == data_precision,- "PagedSelectiveSSM requires one data precision on ports 0..5.");+ std::array<ov::element::Type, paged_ssm_input_count> input_precisions;+ for (size_t port = 0; port < paged_ssm_input_count; ++port) {+ input_precisions[port] = getOriginalInputPrecisionAtPort(port);+ }++ // BF16 precision enforcement preserves constant A in f32 while lowering the activation path. The executor uses+ // one DataT, selected by x, so regular CPU reorders convert the remaining computation inputs to that precision.+ for (const auto port : paged_ssm_computation_ports) {+ const auto port_index = input_port_index(port);+ OPENVINO_ASSERT(any_of(input_precisions[port_index], ov::element::f32, ov::element::f16, ov::element::bf16),+ "PagedSelectiveSSM supports only f32/f16/bf16 computation inputs, got ",+ input_precisions[port_index],+ " at port ",+ port_index,+ ".");+ input_precisions[port_index] = data_precision;}- const auto index_precision = getOriginalInputPrecisionAtPort(6);+ const auto state_precision = input_precisions[input_port_index(PagedSelectiveSSMInputPort::State)];+ OPENVINO_ASSERT(any_of(state_precision, ov::element::f32, ov::element::f16, ov::element::bf16),+ "PagedSelectiveSSM supports only f32/f16/bf16 state, got ",+ state_precision,+ ".");+ const auto index_precision = input_precisions[input_port_index(PagedSelectiveSSMInputPort::SubsequenceBegins)];OPENVINO_ASSERT(any_of(index_precision, ov::element::i32, ov::element::i64),"PagedSelectiveSSM supports only i32/i64 metadata, got ",index_precision,".");- for (size_t port = 7; port <= 10; ++port) {- OPENVINO_ASSERT(getOriginalInputPrecisionAtPort(port) == index_precision,- "PagedSelectiveSSM requires one metadata precision on ports 6..10.");+ for (const auto port : paged_ssm_metadata_ports) {+ OPENVINO_ASSERT(input_precisions[input_port_index(port)] == index_precision,+ "PagedSelectiveSSM requires all metadata inputs to have one precision.");}const auto& creators_map = BlockedDescCreator::getCommonCreators();MemoryDescArgs descs;for (const auto& [arg_id, port_id] : input_port_bindings) {descs[arg_id] = creators_map.at(LayoutType::ncsp)- ->createSharedDesc(getOriginalInputPrecisionAtPort(port_id), getInputShapeAtPort(port_id));+ ->createSharedDesc(input_precisions[port_id], getInputShapeAtPort(port_id));}- descs[ARG_PAGED_SSM_OUT] = creators_map.at(LayoutType::ncsp)- ->createSharedDesc(getOriginalOutputPrecisionAtPort(0), getOutputShapeAtPort(0));+ descs[ARG_PAGED_SSM_OUT] =+ creators_map.at(LayoutType::ncsp)->createSharedDesc(data_precision, getOutputShapeAtPort(output_port));auto execution_context = std::make_shared<ExecutorContext>(context, getImplPriority(), privateWeightCache);m_factory = std::make_shared<ExecutorFactory<PagedSelectiveSSMAttrs>>(m_attrs, execution_context, descs);@@ -110,7 +134,7 @@ void PagedSelectiveSSM::bindMemoryArguments() {for (const auto& [arg_id, port_id] : input_port_bindings) {m_memory[arg_id] = getSrcMemoryAtPort(port_id);}- m_memory[ARG_PAGED_SSM_OUT] = getDstMemoryAtPort(0);+ m_memory[ARG_PAGED_SSM_OUT] = getDstMemoryAtPort(output_port);}void PagedSelectiveSSM::createPrimitive() {diff --git a/src/plugins/intel_cpu/src/nodes/paged_selective_ssm.h b/src/plugins/intel_cpu/src/nodes/paged_selective_ssm.hindex dfb55922056..84d75eb35ef 100644--- a/src/plugins/intel_cpu/src/nodes/paged_selective_ssm.h+++ b/src/plugins/intel_cpu/src/nodes/paged_selective_ssm.h@@ -4,6 +4,9 @@#pragma once+#include <array>+#include <cstddef>+#include <cstdint>#include <memory>#include <oneapi/dnnl/dnnl_common.hpp>#include <string>@@ -16,7 +19,57 @@#include "nodes/executors/paged_selective_ssm_config.hpp"#include "openvino/core/node.hpp"-namespace ov::intel_cpu::node {+namespace ov::intel_cpu {++enum class PagedSelectiveSSMInputPort : uint8_t {+ A,+ TimeStep,+ InputProjection,+ Input,+ OutputProjection,+ State,+ SubsequenceBegins,+ BlockIndices,+ BlockIndicesBegins,+ NumProcessedTokens,+ CacheInterval,+ Count,+};++constexpr size_t input_port_index(PagedSelectiveSSMInputPort port) noexcept {+ return static_cast<size_t>(port);+}++inline constexpr size_t paged_ssm_input_count = input_port_index(PagedSelectiveSSMInputPort::Count);++enum class PagedSelectiveSSMOutputPort : uint8_t {+ Output,+ Count,+};++constexpr size_t output_port_index(PagedSelectiveSSMOutputPort port) noexcept {+ return static_cast<size_t>(port);+}++inline constexpr size_t paged_ssm_output_count = output_port_index(PagedSelectiveSSMOutputPort::Count);++inline constexpr std::array paged_ssm_computation_ports{+ PagedSelectiveSSMInputPort::A,+ PagedSelectiveSSMInputPort::TimeStep,+ PagedSelectiveSSMInputPort::InputProjection,+ PagedSelectiveSSMInputPort::Input,+ PagedSelectiveSSMInputPort::OutputProjection,+};++inline constexpr std::array paged_ssm_metadata_ports{+ PagedSelectiveSSMInputPort::SubsequenceBegins,+ PagedSelectiveSSMInputPort::BlockIndices,+ PagedSelectiveSSMInputPort::BlockIndicesBegins,+ PagedSelectiveSSMInputPort::NumProcessedTokens,+ PagedSelectiveSSMInputPort::CacheInterval,+};++namespace node {class PagedSelectiveSSM : public Node {public:@@ -27,7 +80,7 @@ public:return getType() == Type::PagedSelectiveSSM;}bool isExecutable() const override {- return !isInputTensorAtPortEmpty(3);+ return !isInputTensorAtPortEmpty(input_port_index(PagedSelectiveSSMInputPort::Input));}void createPrimitive() override;@@ -47,4 +100,5 @@ private:MemoryArgs m_memory;};-} // namespace ov::intel_cpu::node+} // namespace node+} // namespace ov::intel_cpudiff --git a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/paged_selective_ssm.cpp b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/paged_selective_ssm.cppindex 3e2d3336941..b4fc78a0549 100644--- a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/paged_selective_ssm.cpp+++ b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/paged_selective_ssm.cpp@@ -14,24 +14,52 @@#include "common_test_utils/ov_tensor_utils.hpp"#include "openvino/core/type/bfloat16.hpp"#include "openvino/core/type/float16.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/matmul.hpp"#include "openvino/op/paged_selective_ssm.hpp"#include "openvino/op/parameter.hpp"#include "openvino/op/result.hpp"#include "openvino/runtime/core.hpp"+#include "openvino/runtime/exec_model_info.hpp"#include "openvino/runtime/remote_context.hpp"#include "openvino/runtime/remote_tensor.hpp"#include "openvino/runtime/tensor.hpp"#include "transformations/rt_info/keep_const_precision.hpp"+#include "utils/precision_support.h"namespace {+enum class InputPort : size_t {+ A,+ TimeStep,+ InputProjection,+ Input,+ OutputProjection,+ State,+ SubsequenceBegins,+ BlockIndices,+ BlockIndicesBegins,+ NumProcessedTokens,+ CacheInterval,+ Count,+};++constexpr size_t input_port_index(InputPort port) noexcept {+ return static_cast<size_t>(port);+}++constexpr bool is_float_port(InputPort port) noexcept {+ return port <= InputPort::State;+}++inline constexpr size_t input_count = input_port_index(InputPort::Count);-template <typename T, typename IndexT>-void run_reference(const std::vector<T>& A,- const std::vector<T>& dt,- const std::vector<T>& B,- const std::vector<T>& x,- const std::vector<T>& C,- std::vector<T>& recurrent_state_table,+template <typename DataT, typename StateT, typename IndexT>+void run_reference(const std::vector<DataT>& A,+ const std::vector<DataT>& dt,+ const std::vector<DataT>& B,+ const std::vector<DataT>& x,+ const std::vector<DataT>& C,+ std::vector<StateT>& recurrent_state_table,const std::vector<IndexT>& subsequence_begins,const std::vector<IndexT>& block_indices,const std::vector<IndexT>& block_indices_begins,@@ -41,7 +69,7 @@ void run_reference(const std::vector<T>& A,size_t num_groups,size_t head_dim,size_t state_size,- std::vector<T>& output) {+ std::vector<DataT>& output) {const size_t tokens = x.size() / (num_heads * head_dim);const size_t heads_per_group = num_heads / num_groups;const size_t num_sequences = subsequence_begins.size() - 1;@@ -79,8 +107,7 @@ void run_reference(const std::vector<T>& A,const auto projection_base = (token * num_groups + group) * state_size;std::vector<float> input_projection(state_size);for (size_t state_index = 0; state_index < state_size; ++state_index) {- input_projection[state_index] =- delta * static_cast<float>(B[projection_base + state_index]);+ input_projection[state_index] = delta * static_cast<float>(B[projection_base + state_index]);}for (size_t position = 0; position < head_dim; ++position) {@@ -96,7 +123,7 @@ void run_reference(const std::vector<T>& A,reduction += static_cast<double>(state[state_base + state_index]) *static_cast<float>(C[projection_base + state_index]);}- output[(token * num_heads + head) * head_dim + position] = static_cast<T>(reduction);+ output[(token * num_heads + head) * head_dim + position] = static_cast<DataT>(reduction);}if (interval > 0) {@@ -110,12 +137,11 @@ void run_reference(const std::vector<T>& A,if (is_boundary || is_last) {const auto write_slot = 1 + (cached_tokens - 1) / positive_interval;OPENVINO_ASSERT(logical_block_begin + write_slot < logical_block_end);- const auto write_block =- static_cast<size_t>(block_indices[logical_block_begin + write_slot]);+ const auto write_block = static_cast<size_t>(block_indices[logical_block_begin + write_slot]);for (size_t position = 0; position < head_dim; ++position) {for (size_t state_index = 0; state_index < state_size; ++state_index) {recurrent_state_table[state_off(write_block, head, position, state_index)] =- static_cast<T>(state[position * state_size + state_index]);+ static_cast<StateT>(state[position * state_size + state_index]);}}}@@ -131,12 +157,15 @@ std::vector<T> tensor_to_vector(const ov::Tensor& tensor) {return std::vector<T>(ptr, ptr + tensor.get_size());}-ov::Tensor make_index_tensor(const std::vector<int32_t>& values, const ov::element::Type& index_type) {+template <typename T>+ov::Tensor make_index_tensor(const std::vector<T>& values, const ov::element::Type& index_type) {ov::Tensor tensor(index_type, ov::Shape{values.size()});if (index_type == ov::element::i32) {- std::copy(values.begin(), values.end(), tensor.data<int32_t>());+ std::transform(values.begin(), values.end(), tensor.data<int32_t>(), [](T value) {+ return static_cast<int32_t>(value);+ });} else {- std::transform(values.begin(), values.end(), tensor.data<int64_t>(), [](int32_t value) {+ std::transform(values.begin(), values.end(), tensor.data<int64_t>(), [](T value) {return static_cast<int64_t>(value);});}@@ -150,18 +179,20 @@ ov::Tensor make_f32_tensor(const ov::Shape& shape, const std::vector<float>& valreturn tensor;}-std::shared_ptr<ov::Model> make_paged_validation_model() {+std::shared_ptr<ov::Model> make_paged_validation_model(size_t token_count = 1,+ size_t physical_block_count = 2,+ const ov::element::Type& index_type = ov::element::i32) {auto A = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1});- auto dt = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 1});- auto B = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 1, 1});- auto x = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 1, 1});- auto C = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 1, 1});- auto state = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{2, 1, 1, 1});- auto subsequences = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{2});- auto blocks = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{2});- auto block_begins = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{2});- auto processed = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{1});- auto intervals = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{1});+ auto dt = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{token_count, 1});+ auto B = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{token_count, 1, 1});+ auto x = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{token_count, 1, 1});+ auto C = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{token_count, 1, 1});+ auto state = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{physical_block_count, 1, 1, 1});+ auto subsequences = std::make_shared<ov::op::v0::Parameter>(index_type, ov::Shape{2});+ auto blocks = std::make_shared<ov::op::v0::Parameter>(index_type, ov::Shape{physical_block_count});+ auto block_begins = std::make_shared<ov::op::v0::Parameter>(index_type, ov::Shape{2});+ auto processed = std::make_shared<ov::op::v0::Parameter>(index_type, ov::Shape{1});+ auto intervals = std::make_shared<ov::op::v0::Parameter>(index_type, ov::Shape{1});const ov::ParameterVectorparameters{A, dt, B, x, C, state, subsequences, blocks, block_begins, processed, intervals};const auto ssm = std::make_shared<ov::op::internal::PagedSelectiveSSM>(A,@@ -178,29 +209,33 @@ std::shared_ptr<ov::Model> make_paged_validation_model() {return std::make_shared<ov::Model>(ssm->outputs(), parameters);}-template <typename T, typename IndexT>+template <typename DataT, typename StateT, typename IndexT>std::vector<ov::Tensor> calculate_typed_refs(const std::map<std::shared_ptr<ov::Node>, ov::Tensor>& host_inputs,const std::shared_ptr<ov::Model>& function,size_t num_heads,size_t num_groups,size_t head_dim,size_t state_size,- const ov::element::Type& data_type) {+ const ov::element::Type& data_type,+ const ov::element::Type& state_type) {const auto& params = function->get_parameters();+ const auto tensor_for = [&](InputPort port) -> const ov::Tensor& {+ return host_inputs.at(params.at(input_port_index(port)));+ };- auto A = tensor_to_vector<T>(host_inputs.at(params[0]));- auto dt = tensor_to_vector<T>(host_inputs.at(params[1]));- auto B = tensor_to_vector<T>(host_inputs.at(params[2]));- auto x = tensor_to_vector<T>(host_inputs.at(params[3]));- auto C = tensor_to_vector<T>(host_inputs.at(params[4]));- auto state = tensor_to_vector<T>(host_inputs.at(params[5]));- auto subsequence_begins = tensor_to_vector<IndexT>(host_inputs.at(params[6]));- auto block_indices = tensor_to_vector<IndexT>(host_inputs.at(params[7]));- auto block_indices_begins = tensor_to_vector<IndexT>(host_inputs.at(params[8]));- auto num_processed_tokens = tensor_to_vector<IndexT>(host_inputs.at(params[9]));- auto cache_interval = tensor_to_vector<IndexT>(host_inputs.at(params[10]));-- std::vector<T> ref_output;+ auto A = tensor_to_vector<DataT>(tensor_for(InputPort::A));+ auto dt = tensor_to_vector<DataT>(tensor_for(InputPort::TimeStep));+ auto B = tensor_to_vector<DataT>(tensor_for(InputPort::InputProjection));+ auto x = tensor_to_vector<DataT>(tensor_for(InputPort::Input));+ auto C = tensor_to_vector<DataT>(tensor_for(InputPort::OutputProjection));+ auto state = tensor_to_vector<StateT>(tensor_for(InputPort::State));+ auto subsequence_begins = tensor_to_vector<IndexT>(tensor_for(InputPort::SubsequenceBegins));+ auto block_indices = tensor_to_vector<IndexT>(tensor_for(InputPort::BlockIndices));+ auto block_indices_begins = tensor_to_vector<IndexT>(tensor_for(InputPort::BlockIndicesBegins));+ auto num_processed_tokens = tensor_to_vector<IndexT>(tensor_for(InputPort::NumProcessedTokens));+ auto cache_interval = tensor_to_vector<IndexT>(tensor_for(InputPort::CacheInterval));++ std::vector<DataT> ref_output;run_reference(A,dt,B,@@ -218,31 +253,89 @@ std::vector<ov::Tensor> calculate_typed_refs(const std::map<std::shared_ptr<ov::state_size,ref_output);- ov::Tensor output_tensor(data_type, host_inputs.at(params[3]).get_shape());- std::copy(ref_output.begin(), ref_output.end(), output_tensor.data<T>());+ ov::Tensor output_tensor(data_type, tensor_for(InputPort::Input).get_shape());+ std::copy(ref_output.begin(), ref_output.end(), output_tensor.data<DataT>());- ov::Tensor state_tensor(data_type, host_inputs.at(params[5]).get_shape());- std::copy(state.begin(), state.end(), state_tensor.data<T>());+ ov::Tensor state_tensor(state_type, tensor_for(InputPort::State).get_shape());+ std::copy(state.begin(), state.end(), state_tensor.data<StateT>());return {output_tensor, state_tensor};}-template <typename T>-std::vector<ov::Tensor> calculate_data_typed_refs(- const std::map<std::shared_ptr<ov::Node>, ov::Tensor>& host_inputs,- const std::shared_ptr<ov::Model>& function,- size_t num_heads,- size_t num_groups,- size_t head_dim,- size_t state_size,- const ov::element::Type& data_type,- const ov::element::Type& index_type) {+template <typename DataT, typename StateT>+std::vector<ov::Tensor> calculate_state_typed_refs(const std::map<std::shared_ptr<ov::Node>, ov::Tensor>& host_inputs,+ const std::shared_ptr<ov::Model>& function,+ size_t num_heads,+ size_t num_groups,+ size_t head_dim,+ size_t state_size,+ const ov::element::Type& data_type,+ const ov::element::Type& state_type,+ const ov::element::Type& index_type) {if (index_type == ov::element::i64) {- return calculate_typed_refs<T, int64_t>(- host_inputs, function, num_heads, num_groups, head_dim, state_size, data_type);+ return calculate_typed_refs<DataT, StateT, int64_t>(host_inputs,+ function,+ num_heads,+ num_groups,+ head_dim,+ state_size,+ data_type,+ state_type);}- return calculate_typed_refs<T, int32_t>(- host_inputs, function, num_heads, num_groups, head_dim, state_size, data_type);+ return calculate_typed_refs<DataT, StateT, int32_t>(host_inputs,+ function,+ num_heads,+ num_groups,+ head_dim,+ state_size,+ data_type,+ state_type);+}++template <typename DataT>+std::vector<ov::Tensor> calculate_data_typed_refs(const std::map<std::shared_ptr<ov::Node>, ov::Tensor>& host_inputs,+ const std::shared_ptr<ov::Model>& function,+ size_t num_heads,+ size_t num_groups,+ size_t head_dim,+ size_t state_size,+ const ov::element::Type& data_type,+ const ov::element::Type& state_type,+ const ov::element::Type& index_type) {+ if (state_type == ov::element::f32) {+ return calculate_state_typed_refs<DataT, float>(host_inputs,+ function,+ num_heads,+ num_groups,+ head_dim,+ state_size,+ data_type,+ state_type,+ index_type);+ }+ if (state_type == ov::element::f16) {+ return calculate_state_typed_refs<DataT, ov::float16>(host_inputs,+ function,+ num_heads,+ num_groups,+ head_dim,+ state_size,+ data_type,+ state_type,+ index_type);+ }+ if (state_type == ov::element::bf16) {+ return calculate_state_typed_refs<DataT, ov::bfloat16>(host_inputs,+ function,+ num_heads,+ num_groups,+ head_dim,+ state_size,+ data_type,+ state_type,+ index_type);+ }+ OPENVINO_THROW("Unsupported PagedSelectiveSSM state precision ", state_type, ".");}int32_t count_logical_blocks(const std::vector<int32_t>& sequence_lengths,@@ -284,6 +377,7 @@ std::string PagedSelectiveSSMLayerTest::getTestCaseName(num_processed_tokens,cache_intervals,element_type,+ state_type,index_type,target_device] = obj.param;std::ostringstream result;@@ -314,6 +408,7 @@ std::string PagedSelectiveSSMLayerTest::getTestCaseName(}}result << "_Type=" << element_type;+ result << "_StateType=" << state_type;result << "_IndexType=" << index_type;result << "_Target=" << target_device;return result.str();@@ -328,21 +423,17 @@ void PagedSelectiveSSMLayerTest::SetUp() {num_processed_tokens,cache_intervals,data_type,+ state_type,index_type,device] = GetParam();- if (device.find("CPU") != std::string::npos) {- // Skip BF16/F16 tests if not support- if ((data_type == ov::element::bf16) && !with_cpu_x86_avx512_core_amx_bf16()) {- GTEST_SKIP();- }- if ((data_type == ov::element::f16) && !with_cpu_x86_avx512_core_fp16()) {- GTEST_SKIP();- }- }targetDevice = device;this->data_type = data_type;- configuration[ov::hint::inference_precision.name()] = data_type;+ this->state_type = state_type;+ if (!ov::intel_cpu::hasHardwareSupport(state_type)) {+ GTEST_SKIP() << "CPU precision policy does not preserve " << state_type << " state storage on this system.";+ }+ configuration[ov::hint::inference_precision.name()] = state_type;OPENVINO_ASSERT(!seq_lengths.empty());OPENVINO_ASSERT(seq_lengths.size() == num_processed_tokens.size());OPENVINO_ASSERT(seq_lengths.size() == cache_intervals.size());@@ -421,8 +512,13 @@ void PagedSelectiveSSMLayerTest::SetUp() {auto p_B = std::make_shared<ov::op::v0::Parameter>(data_type, ov::PartialShape{-1, num_groups, state_size});auto p_x = std::make_shared<ov::op::v0::Parameter>(data_type, ov::PartialShape{-1, num_heads, head_dim});auto p_C = std::make_shared<ov::op::v0::Parameter>(data_type, ov::PartialShape{-1, num_groups, state_size});+ // Keep the source model valid. ConvertPagedAttnInputs applies the requested state storage precision inside the+ // CPU pipeline while computation parameters retain data_type through keep_const_precision.auto p_state =std::make_shared<ov::op::v0::Parameter>(data_type, ov::PartialShape{-1, num_heads, head_dim, state_size});+ for (const auto& parameter : {p_A, p_dt, p_B, p_x, p_C, p_state}) {+ ov::enable_keep_const_precision(parameter);+ }auto p_subseq = std::make_shared<ov::op::v0::Parameter>(index_type, ov::PartialShape{-1});auto p_blocks = std::make_shared<ov::op::v0::Parameter>(index_type, ov::PartialShape{-1});auto p_block_begins = std::make_shared<ov::op::v0::Parameter>(index_type, ov::PartialShape{-1});@@ -466,12 +562,17 @@ void PagedSelectiveSSMLayerTest::generate_inputs(const std::vector<ov::Shape>& tnum_processed_tokens_param,cache_intervals,element_type,+ state_type,index_type,device] = GetParam();- const auto num_sequences = static_cast<int32_t>(targetInputStaticShapes[9][0]);- OPENVINO_ASSERT(targetInputStaticShapes[6][0] == static_cast<size_t>(num_sequences + 1));- OPENVINO_ASSERT(targetInputStaticShapes[8][0] == static_cast<size_t>(num_sequences + 1));- OPENVINO_ASSERT(targetInputStaticShapes[10][0] == static_cast<size_t>(num_sequences));+ const auto shape_for = [&](InputPort port) -> const ov::Shape& {+ return targetInputStaticShapes.at(input_port_index(port));+ };+ OPENVINO_ASSERT(targetInputStaticShapes.size() == input_count);+ const auto num_sequences = static_cast<int32_t>(shape_for(InputPort::NumProcessedTokens).front());+ OPENVINO_ASSERT(shape_for(InputPort::SubsequenceBegins).front() == static_cast<size_t>(num_sequences + 1));+ OPENVINO_ASSERT(shape_for(InputPort::BlockIndicesBegins).front() == static_cast<size_t>(num_sequences + 1));+ OPENVINO_ASSERT(shape_for(InputPort::CacheInterval).front() == static_cast<size_t>(num_sequences));const bool use_alternate_metadata = static_cast<size_t>(num_sequences) != seq_lengths.size();auto active_seq_lengths = seq_lengths;auto active_processed_tokens = num_processed_tokens_param;@@ -530,44 +631,48 @@ void PagedSelectiveSSMLayerTest::generate_inputs(const std::vector<ov::Shape>& tremote_context = compiledModel.get_context();}- for (size_t i = 0; i < params.size(); i++) {- const auto& param = params[i];- const auto& shape = targetInputStaticShapes[i];+ for (size_t input_index = 0; input_index < params.size(); ++input_index) {+ const auto port = static_cast<InputPort>(input_index);+ const auto& param = params[input_index];+ const auto& shape = targetInputStaticShapes[input_index];ov::Tensor tensor;- if (i == 0) {+ if (port == InputPort::A) {tensor = ov::test::utils::create_and_fill_tensor_real_distribution(param->get_element_type(),- shape,- -0.5f,- 0.2f,- 1);- } else if (i == 1) {+ shape,+ -0.5f,+ 0.2f,+ 1);+ } else if (port == InputPort::TimeStep) {tensor = ov::test::utils::create_and_fill_tensor_real_distribution(param->get_element_type(),- shape,- 0.0f,- 0.5f,- 1);- } else if (i <= 5) {- tensor = ov::test::utils::create_and_fill_tensor(param->get_element_type(),+ shape,+ 0.0f,+ 0.5f,+ 1);+ } else if (is_float_port(port)) {+ const auto tensor_type = port == InputPort::State ? state_type : param->get_element_type();+ tensor = ov::test::utils::create_and_fill_tensor(tensor_type,shape,ov::test::utils::InputGenerateData(-0.5f, 1.0f, 1000, 1));- } else if (i == 6) {+ } else if (port == InputPort::SubsequenceBegins) {tensor = make_index_tensor(subsequence_begins, index_type);- } else if (i == 7) {+ } else if (port == InputPort::BlockIndices) {tensor = make_index_tensor(block_indices, index_type);- } else if (i == 8) {+ } else if (port == InputPort::BlockIndicesBegins) {tensor = make_index_tensor(block_indices_begins, index_type);- } else if (i == 9) {+ } else if (port == InputPort::NumProcessedTokens) {tensor = make_index_tensor(num_processed_tokens, index_type);- } else if (i == 10) {+ } else if (port == InputPort::CacheInterval) {tensor = make_index_tensor(cache_interval, index_type);+ } else {+ OPENVINO_THROW("Unexpected PagedSelectiveSSM input port ", input_index, ".");}// The operation updates the state input in place, so the oracle needs an independent pre-inference snapshot.ov::Tensor host_tensor(tensor.get_element_type(), tensor.get_shape());tensor.copy_to(host_tensor);host_inputs[param] = host_tensor;- if (use_remote_tensors && i <= 5) {+ if (use_remote_tensors && is_float_port(port)) {auto remote_tensor = remote_context.create_tensor(param->get_element_type(), shape);remote_tensor.copy_from(tensor);inputs[param] = remote_tensor;@@ -586,25 +691,47 @@ std::vector<ov::Tensor> PagedSelectiveSSMLayerTest::calculate_refs() {num_processed_tokens,cache_intervals,element_type,+ state_type,index_type,device] = GetParam();if (element_type == ov::element::f16) {- return calculate_data_typed_refs<ov::float16>(- host_inputs, function, num_heads, num_groups, head_dim, state_size, element_type, index_type);+ return calculate_data_typed_refs<ov::float16>(host_inputs,+ function,+ num_heads,+ num_groups,+ head_dim,+ state_size,+ element_type,+ state_type,+ index_type);}if (element_type == ov::element::bf16) {- return calculate_data_typed_refs<ov::bfloat16>(- host_inputs, function, num_heads, num_groups, head_dim, state_size, element_type, index_type);+ return calculate_data_typed_refs<ov::bfloat16>(host_inputs,+ function,+ num_heads,+ num_groups,+ head_dim,+ state_size,+ element_type,+ state_type,+ index_type);}- return calculate_data_typed_refs<float>(- host_inputs, function, num_heads, num_groups, head_dim, state_size, element_type, index_type);+ return calculate_data_typed_refs<float>(host_inputs,+ function,+ num_heads,+ num_groups,+ head_dim,+ state_size,+ element_type,+ state_type,+ index_type);}std::vector<ov::Tensor> PagedSelectiveSSMLayerTest::get_plugin_outputs() {auto outputs = SubgraphBaseTest::get_plugin_outputs();- const auto& state_param = function->get_parameters().at(5);+ const auto& state_param = function->get_parameters().at(input_port_index(InputPort::State));const auto actual_state_tensor = inferRequest.get_tensor(state_param);ov::Tensor host_state_tensor(actual_state_tensor.get_element_type(), actual_state_tensor.get_shape());actual_state_tensor.copy_to(host_state_tensor);@@ -616,10 +743,10 @@ std::vector<ov::Tensor> PagedSelectiveSSMLayerTest::get_plugin_outputs() {void PagedSelectiveSSMLayerTest::compare(const std::vector<ov::Tensor>& expected,const std::vector<ov::Tensor>& actual) {ASSERT_EQ(expected.size(), actual.size());- if (data_type == ov::element::bf16) {+ if (data_type == ov::element::bf16 || state_type == ov::element::bf16) {abs_threshold = 1e-3f;rel_threshold = 1e-2f;- } else if (data_type == ov::element::f16) {+ } else if (data_type == ov::element::f16 || state_type == ov::element::f16) {abs_threshold = 5e-4f;rel_threshold = 1e-5f;} else {@@ -638,6 +765,33 @@ TEST_P(PagedSelectiveSSMLayerTest, Inference) {CheckNumberOfNodesWithType(runtime_model, {"Loop"}, 0);}+TEST(PagedSelectiveSSMFunctionalTest, AlignsComputationPrecisionAfterCpuLowering) {+ if (!ov::intel_cpu::hasHardwareSupport(ov::element::bf16)) {+ GTEST_SKIP() << "CPU does not support bf16 inference.";+ }++ auto model = make_paged_validation_model();+ const auto a_parameter = model->get_parameters().at(input_port_index(InputPort::A));+ const auto a_constant = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1}, {-0.2F});+ a_parameter->output(0).replace(a_constant->output(0));+ model->remove_parameter(a_parameter);+ const auto result = model->get_results().front();+ const auto weights = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 1}, {1.F});+ const auto matmul = std::make_shared<ov::op::v0::MatMul>(result->input_value(0), weights, false, false);+ result->input(0).replace_source_output(matmul);++ ov::Core core;+ const auto compiled_model = core.compile_model(model, "CPU", ov::hint::inference_precision(ov::element::bf16));+ const auto runtime_model = compiled_model.get_runtime_model();+ CheckNumberOfNodesWithType(runtime_model, {"PagedSelectiveSSM"}, 1);+ for (const auto& node : runtime_model->get_ops()) {+ const auto& rt_info = node->get_rt_info();+ if (rt_info.at(ov::exec_model_info::LAYER_TYPE).as<std::string>() == "PagedSelectiveSSM") {+ EXPECT_EQ(rt_info.at(ov::exec_model_info::RUNTIME_PRECISION).as<ov::element::Type>(), ov::element::bf16);+ }+ }+}+TEST(PagedSelectiveSSMFunctionalTest, RejectsMalformedMetadataBeforeExecution) {struct MetadataCase {const char* name;@@ -658,21 +812,25 @@ TEST(PagedSelectiveSSMFunctionalTest, RejectsMalformedMetadataBeforeExecution) {};ov::Core core;- auto compiled_model = core.compile_model(make_paged_validation_model(), "CPU");+ auto compiled_model =+ core.compile_model(make_paged_validation_model(), "CPU", ov::hint::inference_precision(ov::element::f32));for (const auto& test_case : cases) {SCOPED_TRACE(test_case.name);auto request = compiled_model.create_infer_request();- request.set_input_tensor(0, make_f32_tensor({1}, {-0.2F}));- request.set_input_tensor(1, make_f32_tensor({1, 1}, {0.1F}));- request.set_input_tensor(2, make_f32_tensor({1, 1, 1}, {0.2F}));- request.set_input_tensor(3, make_f32_tensor({1, 1, 1}, {0.3F}));- request.set_input_tensor(4, make_f32_tensor({1, 1, 1}, {0.4F}));- request.set_input_tensor(5, make_f32_tensor({2, 1, 1, 1}, {0.F, 0.F}));- request.set_input_tensor(6, make_index_tensor(test_case.subsequences, ov::element::i32));- request.set_input_tensor(7, make_index_tensor(test_case.blocks, ov::element::i32));- request.set_input_tensor(8, make_index_tensor(test_case.block_begins, ov::element::i32));- request.set_input_tensor(9, make_index_tensor(test_case.processed, ov::element::i32));- request.set_input_tensor(10, make_index_tensor(test_case.intervals, ov::element::i32));+ const auto set_input = [&](InputPort port, const ov::Tensor& tensor) {+ request.set_input_tensor(input_port_index(port), tensor);+ };+ set_input(InputPort::A, make_f32_tensor({1}, {-0.2F}));+ set_input(InputPort::TimeStep, make_f32_tensor({1, 1}, {0.1F}));+ set_input(InputPort::InputProjection, make_f32_tensor({1, 1, 1}, {0.2F}));+ set_input(InputPort::Input, make_f32_tensor({1, 1, 1}, {0.3F}));+ set_input(InputPort::OutputProjection, make_f32_tensor({1, 1, 1}, {0.4F}));+ set_input(InputPort::State, make_f32_tensor({2, 1, 1, 1}, {0.F, 0.F}));+ set_input(InputPort::SubsequenceBegins, make_index_tensor(test_case.subsequences, ov::element::i32));+ set_input(InputPort::BlockIndices, make_index_tensor(test_case.blocks, ov::element::i32));+ set_input(InputPort::BlockIndicesBegins, make_index_tensor(test_case.block_begins, ov::element::i32));+ set_input(InputPort::NumProcessedTokens, make_index_tensor(test_case.processed, ov::element::i32));+ set_input(InputPort::CacheInterval, make_index_tensor(test_case.intervals, ov::element::i32));EXPECT_THROW(request.infer(), ov::Exception);}}diff --git a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/paged_selective_ssm.hpp b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/paged_selective_ssm.hppindex 3a34a8777fc..a6863a68f3c 100644--- a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/paged_selective_ssm.hpp+++ b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/classes/paged_selective_ssm.hpp@@ -24,9 +24,10 @@ using PagedSelectiveSSMLayerParams = std::tuple<int32_t,std::vector<int32_t>,ov::element::Type,ov::element::Type,+ ov::element::Type,std::string>; // num_heads, num_groups, head_dim, state_size,// seq_lengths, num_processed_tokens, cache_intervals,- // element_type, index_type, target_device+ // data_type, state_type, index_type, target_deviceclass PagedSelectiveSSMLayerTest : public testing::WithParamInterface<PagedSelectiveSSMLayerParams>,virtual public ov::test::SubgraphBaseTest {@@ -43,6 +44,7 @@ protected:private:std::map<std::shared_ptr<ov::Node>, ov::Tensor> host_inputs;ov::element::Type data_type;+ ov::element::Type state_type;};} // namespace ov::testdiff --git a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/common/paged_selective_ssm.cpp b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/common/paged_selective_ssm.cppindex 7312411cf5a..a0998a1b6a7 100644--- a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/common/paged_selective_ssm.cpp+++ b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/common/paged_selective_ssm.cpp@@ -7,26 +7,32 @@namespace ov::test {std::vector<PagedSelectiveSSMLayerParams> paged_selective_ssm_test_cases = {- {4, 2, 5, 3, {3}, {0}, {2}, ov::element::f32, ov::element::i32, "CPU"},- {4, 2, 5, 3, {3}, {4}, {2}, ov::element::f32, ov::element::i32, "CPU"},- {4, 2, 5, 3, {4}, {1}, {3}, ov::element::f32, ov::element::i32, "CPU"},- {4, 2, 5, 3, {1}, {4}, {2}, ov::element::f32, ov::element::i32, "CPU"},- {4, 2, 5, 3, {1}, {3}, {2}, ov::element::f32, ov::element::i32, "CPU"},- {4, 2, 5, 3, {0, 2, 1}, {7, 1, 0}, {2, 2, 4}, ov::element::f32, ov::element::i32, "CPU"},- {4, 2, 5, 3, {0, 0}, {0, 7}, {2, -3}, ov::element::f32, ov::element::i32, "CPU"},- {4, 1, 3, 4, {3, 2}, {5, 9}, {0, -3}, ov::element::f32, ov::element::i32, "CPU"},- {3, 3, 1, 1, {4}, {0}, {1}, ov::element::f32, ov::element::i64, "CPU"},- {4, 2, 5, 3, {1}, {0}, {2}, ov::element::f32, ov::element::i64, "CPU"},- {64, 1, 64, 128, {1}, {0}, {1}, ov::element::f32, ov::element::i32, "CPU"},- {96, 8, 80, 80, {5}, {0}, {2}, ov::element::f32, ov::element::i64, "CPU"},- {4, 2, 5, 3, {1}, {0}, {2}, ov::element::f16, ov::element::i32, "CPU"},- {4, 2, 5, 3, {3, 1}, {1, 4}, {3, 2}, ov::element::f16, ov::element::i32, "CPU"},- {4, 2, 5, 3, {1}, {0}, {2}, ov::element::f16, ov::element::i64, "CPU"},- {4, 2, 5, 3, {3, 1}, {1, 4}, {3, 2}, ov::element::f16, ov::element::i64, "CPU"},- {4, 2, 5, 3, {1}, {0}, {2}, ov::element::bf16, ov::element::i32, "CPU"},- {4, 2, 5, 3, {3, 1}, {1, 4}, {3, 2}, ov::element::bf16, ov::element::i32, "CPU"},- {4, 2, 5, 3, {1}, {0}, {2}, ov::element::bf16, ov::element::i64, "CPU"},- {4, 2, 5, 3, {3, 1}, {1, 4}, {3, 2}, ov::element::bf16, ov::element::i64, "CPU"},+ {4, 2, 5, 3, {3}, {0}, {2}, ov::element::f32, ov::element::f32, ov::element::i32, "CPU"},+ {4, 2, 5, 3, {3}, {4}, {2}, ov::element::f32, ov::element::f32, ov::element::i32, "CPU"},+ {4, 2, 5, 3, {4}, {1}, {3}, ov::element::f32, ov::element::f32, ov::element::i32, "CPU"},+ {4, 2, 5, 3, {1}, {4}, {2}, ov::element::f32, ov::element::f32, ov::element::i32, "CPU"},+ {4, 2, 5, 3, {1}, {3}, {2}, ov::element::f32, ov::element::f32, ov::element::i32, "CPU"},+ {4, 2, 5, 3, {0, 2, 1}, {7, 1, 0}, {2, 2, 4}, ov::element::f32, ov::element::f32, ov::element::i32, "CPU"},+ {4, 2, 5, 3, {0, 0}, {0, 7}, {2, -3}, ov::element::f32, ov::element::f32, ov::element::i32, "CPU"},+ {4, 1, 3, 4, {3, 2}, {5, 9}, {0, -3}, ov::element::f32, ov::element::f32, ov::element::i32, "CPU"},+ {3, 3, 1, 1, {4}, {0}, {1}, ov::element::f32, ov::element::f32, ov::element::i64, "CPU"},+ {4, 2, 5, 3, {1}, {0}, {2}, ov::element::f32, ov::element::f32, ov::element::i64, "CPU"},+ {64, 1, 64, 128, {1}, {0}, {1}, ov::element::f32, ov::element::f32, ov::element::i32, "CPU"},+ {96, 8, 80, 80, {5}, {0}, {2}, ov::element::f32, ov::element::f32, ov::element::i64, "CPU"},+ {4, 2, 5, 3, {1}, {0}, {2}, ov::element::f16, ov::element::f16, ov::element::i32, "CPU"},+ {4, 2, 5, 3, {3, 1}, {1, 4}, {3, 2}, ov::element::f16, ov::element::f16, ov::element::i32, "CPU"},+ {4, 2, 5, 3, {1}, {0}, {2}, ov::element::f16, ov::element::f16, ov::element::i64, "CPU"},+ {4, 2, 5, 3, {3, 1}, {1, 4}, {3, 2}, ov::element::f16, ov::element::f16, ov::element::i64, "CPU"},+ {4, 2, 5, 3, {1}, {0}, {2}, ov::element::bf16, ov::element::bf16, ov::element::i32, "CPU"},+ {4, 2, 5, 3, {3, 1}, {1, 4}, {3, 2}, ov::element::bf16, ov::element::bf16, ov::element::i32, "CPU"},+ {4, 2, 5, 3, {1}, {0}, {2}, ov::element::bf16, ov::element::bf16, ov::element::i64, "CPU"},+ {4, 2, 5, 3, {3, 1}, {1, 4}, {3, 2}, ov::element::bf16, ov::element::bf16, ov::element::i64, "CPU"},+ {4, 2, 5, 3, {3, 1}, {1, 4}, {3, 2}, ov::element::f32, ov::element::f16, ov::element::i32, "CPU"},+ {64, 1, 64, 128, {1}, {0}, {1}, ov::element::f32, ov::element::bf16, ov::element::i64, "CPU"},+ {4, 2, 5, 3, {3, 1}, {1, 4}, {3, 2}, ov::element::f16, ov::element::f32, ov::element::i32, "CPU"},+ {4, 2, 5, 3, {3, 1}, {1, 4}, {3, 2}, ov::element::f16, ov::element::bf16, ov::element::i64, "CPU"},+ {4, 2, 5, 3, {3, 1}, {1, 4}, {3, 2}, ov::element::bf16, ov::element::f16, ov::element::i32, "CPU"},+ {4, 2, 5, 3, {3, 1}, {1, 4}, {3, 2}, ov::element::bf16, ov::element::f32, ov::element::i64, "CPU"},};INSTANTIATE_TEST_SUITE_P(smoke_PagedSelectiveSSM,