Skip to content

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

[CPU] Drop redundant MemoryOutput nodes (#27189)

Maksim Kutakovc7d8e038f266
diff --git a/src/plugins/intel_cpu/src/graph_optimizer.cpp b/src/plugins/intel_cpu/src/graph_optimizer.cpp
index 6b3175e24d9..ab7eb223ba1 100644
--- a/src/plugins/intel_cpu/src/graph_optimizer.cpp
+++ b/src/plugins/intel_cpu/src/graph_optimizer.cpp
@@ -183,6 +183,10 @@ void GraphOptimizer::ApplyCommonGraphOptimizations(Graph &graph) {
MatchSdpaKvCache(graph);
graph.RemoveDroppedNodes();
+ OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "DropRedundantMemoryOutput");
+ DropRedundantMemoryOutput(graph);
+ graph.RemoveDroppedNodes();
+
OV_ITT_SCOPE_NEXT(FIRST_INFERENCE, taskChain, "RemoveDroppedEdges");
graph.RemoveDroppedEdges();
}
@@ -3186,5 +3190,117 @@ void GraphOptimizer::MatchSdpaKvCache(Graph &graph) {
}
}
+void GraphOptimizer::DropRedundantMemoryOutput(Graph &graph) {
+ // When we have a MemoryInput->MemoryOutput pair, that means that the state is immediately populated with the init
+ // subgraph values when the init subgraph exists. In all the other cases the state is simply a read only object.
+ // We can optimize such a case removing the MemoryOutput node and transferring the state values update
+ // responsibility to a special type of the MemoryInput node - MemoryInputSingle
+ auto& graphNodes = graph.GetNodes();
+
+ auto isSuitableMemInput = [](const NodePtr& node) -> bool {
+ if (Type::MemoryInput != node->getType()) {
+ return false;
+ }
+
+ CPU_GRAPH_OPTIMIZER_SCOPE(DropRedundantMemoryOutput_isSuitableMemInput);
+
+ auto memInputBase = std::dynamic_pointer_cast<MemoryNode>(node);
+ OPENVINO_ASSERT(memInputBase,
+ "Unexpectedly wrong dynamic type of node: ",
+ node->getName(),
+ " of type: ",
+ node->getTypeStr());
+
+ auto id = memInputBase->getId();
+
+ NodePtr MemoryOutput = nullptr;
+ auto&& childEdges = node->getChildEdgesAtPort(0);
+ for (auto&& item : childEdges) {
+ auto childNode = item->getChild();
+
+ if (Type::MemoryOutput == childNode->getType()) {
+ auto memOutputBase = std::dynamic_pointer_cast<MemoryNode>(childNode);
+ OPENVINO_ASSERT(memInputBase,
+ "Unexpectedly wrong dynamic type of node: ",
+ node->getName(),
+ " of type: ",
+ node->getTypeStr());
+
+ if (memOutputBase->getId() != id) {
+ return false; // an Assign node from different Variable is attached
+ }
+
+ if (MemoryOutput && MemoryOutput != childNode) {
+ //only one child MemoryOutput is expected
+ return false;
+ }
+ MemoryOutput = childNode;
+ }
+ }
+ return nullptr != MemoryOutput;
+ };
+
+ for (size_t i = 0; i < graphNodes.size(); i++) {
+ auto node = graphNodes[i];
+ if (!isSuitableMemInput(node)) {
+ continue;
+ }
+
+ CPU_GRAPH_OPTIMIZER_SCOPE(DropRedundantMemoryOutput_Node);
+
+ auto memInputNode = std::dynamic_pointer_cast<node::MemoryInputBase>(node);
+ OPENVINO_ASSERT(memInputNode, "MemoryInput node ", node->getName(), " has unexpected dynamic type");
+
+ ov::optional<Shape> inputShape;
+ ov::optional<ov::element::Type> inputPrc;
+
+ if (!node->getParentEdges().empty()) {
+ inputShape = ov::optional<Shape>(node->getInputShapeAtPort(0));
+ inputPrc = ov::optional<ov::element::Type>(node->getOriginalInputPrecisionAtPort(0));
+ }
+
+ //search for the MemoryOutputNode
+ NodePtr memoryOutputNode;
+ for (auto&& edge : node->getChildEdgesAtPort(0)) {
+ auto child = edge->getChild();
+ if (Type::MemoryOutput == child->getType()) {
+ memoryOutputNode = child;
+ break;
+ }
+ }
+ OPENVINO_ASSERT(memoryOutputNode, "Corresponding MemoryOutput has not been found");
+
+ graph.RemoveEdge(memoryOutputNode->getParentEdgeAt(0));
+ // there are no output edges from MemoryOutput nodes
+
+ // now replace the existing MemoryInput with a special type that works without the corresponding MemoryOutput
+ auto memInputSingle = std::make_shared<MemoryInputSingle>(memInputNode->getId(),
+ memInputNode->getName(),
+ memInputNode->getTypeStr(),
+ memInputNode->getOutputShapeAtPort(0),
+ memInputNode->getOriginalOutputPrecisionAtPort(0),
+ graph.getGraphContext(),
+ inputShape,
+ inputPrc);
+
+ graph.AddNode(memInputSingle);
+
+ if (!memInputNode->getParentEdges().empty()) {
+ auto parentEdge = memInputNode->getParentEdgeAt(0);
+ auto parent = parentEdge->getParent();
+ const auto inputNum = parentEdge->getInputNum();
+ graph.RemoveEdge(parentEdge);
+ graph.CreateEdge(parent, memInputSingle, inputNum, 0);
+ }
+
+ for (auto&& edge : memInputNode->getChildEdgesAtPort(0)) {
+ auto child = edge->getChild();
+ const auto outputNum = edge->getOutputNum();
+ graph.RemoveEdge(edge);
+ graph.CreateEdge(memInputSingle, child, 0, outputNum);
+ }
+ }
+}
+
} // namespace intel_cpu
} // namespace ov
diff --git a/src/plugins/intel_cpu/src/graph_optimizer.h b/src/plugins/intel_cpu/src/graph_optimizer.h
index 0a85a253ba8..886296a7c00 100644
--- a/src/plugins/intel_cpu/src/graph_optimizer.h
+++ b/src/plugins/intel_cpu/src/graph_optimizer.h
@@ -52,6 +52,7 @@ private:
void RemoveMemoryInputConvert(Graph &graph);
void RemoveConvertMemoryOutput(Graph &graph);
void MatchSdpaKvCache(Graph &graph);
+ void DropRedundantMemoryOutput(Graph &graph);
bool canBeInplaced(const NodePtr& parentNode, const NodePtr& childNode);
// Method checks that after the sequential execution of Transpose and Reorder nodes,
diff --git a/src/plugins/intel_cpu/src/memory_state.cpp b/src/plugins/intel_cpu/src/memory_state.cpp
index f5f76fe42fe..bf77917497d 100644
--- a/src/plugins/intel_cpu/src/memory_state.cpp
+++ b/src/plugins/intel_cpu/src/memory_state.cpp
@@ -156,6 +156,49 @@ MemoryPtr VariableStateDoubleBuffer::internal_state_mem() const {
return prime_mem();
}
+VariableStateSingleBuffer::VariableStateSingleBuffer(const std::string& name,
+ const MemoryPtr& external_buffer,
+ const MemoryDescPtr& external_desc)
+ : VariableStateBase(name, external_desc) {
+ OPENVINO_ASSERT(external_buffer);
+ m_internal_mem = external_buffer;
+ m_internal_desc = m_internal_mem->getDescPtr();
+ auto&& shape = m_internal_desc->getShape();
+
+ if (shape.isStatic()) {
+ m_internal_mem->nullify();
+ } else {
+ // in the case of the original desc has dynamic shape we create an empty tensor
+ auto new_desc = to_static(m_internal_desc);
+ m_internal_mem->redefineDesc(new_desc);
+ }
+}
+MemoryPtr VariableStateSingleBuffer::input_mem() {
+ return m_internal_mem;
+}
+MemoryPtr VariableStateSingleBuffer::output_mem() {
+ return m_internal_mem;
+}
+MemoryDescPtr VariableStateSingleBuffer::internal_desc() const {
+ return m_internal_desc;
+}
+
+void VariableStateSingleBuffer::reset_impl() {
+ auto new_desc = to_static(m_internal_desc);
+ if (m_internal_mem) {
+ m_internal_mem->redefineDesc(new_desc);
+ m_internal_mem->nullify();
+ }
+}
+
+MemoryPtr VariableStateSingleBuffer::internal_state_mem() const {
+ return m_internal_mem;
+}
+
+void VariableStateSingleBuffer::commit_impl() {
+ // nothing to do
+}
+
VariableStateKVcache::VariableStateKVcache(
const std::string& name,
const MemoryDescPtr& external_desc,
diff --git a/src/plugins/intel_cpu/src/memory_state.h b/src/plugins/intel_cpu/src/memory_state.h
index b4c52903d12..e7493f327e9 100644
--- a/src/plugins/intel_cpu/src/memory_state.h
+++ b/src/plugins/intel_cpu/src/memory_state.h
@@ -94,6 +94,27 @@ private:
size_t buffer_num = 0;
};
+class VariableStateSingleBuffer : public VariableStateBase {
+public:
+ VariableStateSingleBuffer(const std::string& name,
+ const MemoryPtr& external_buffer,
+ const MemoryDescPtr& external_desc);
+
+ MemoryPtr input_mem() override;
+ MemoryPtr output_mem() override;
+ MemoryDescPtr internal_desc() const override;
+
+private:
+ void reset_impl() override;
+ void commit_impl() override;
+
+ MemoryPtr internal_state_mem() const override;
+
+private:
+ MemoryDescPtr m_internal_desc; //mem desc required by the graph internal tensor
+ MemoryPtr m_internal_mem;
+};
+
class VariableStateKVcache : public VariableStateBase {
public:
VariableStateKVcache(const std::string& name,
diff --git a/src/plugins/intel_cpu/src/nodes/memory.cpp b/src/plugins/intel_cpu/src/nodes/memory.cpp
index 756fbc5b578..565597bdcc2 100644
--- a/src/plugins/intel_cpu/src/nodes/memory.cpp
+++ b/src/plugins/intel_cpu/src/nodes/memory.cpp
@@ -377,7 +377,8 @@ bool MemoryInputBase::isSupportedOperation(const std::shared_ptr<const ov::Node>
}
MemoryInputBase::MemoryInputBase(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr ctx)
- : Input(op, ctx), MemoryStateNode(op) {
+ : Input(op, ctx),
+ MemoryStateNode(op) {
std::string errorMessage;
if (!isSupportedOperation(op, errorMessage)) {
OPENVINO_THROW_NOT_IMPLEMENTED(errorMessage);
@@ -385,6 +386,7 @@ MemoryInputBase::MemoryInputBase(const std::shared_ptr<ov::Node>& op, const Grap
if (created()) {
context->getMemoryStatesRegister()->registerInput(this);
}
+ executeHook = &MemoryInputBase::assignState;
}
MemoryInputBase::MemoryInputBase(const std::string id,
@@ -394,8 +396,10 @@ MemoryInputBase::MemoryInputBase(const std::string id,
const ov::element::Type& output_prc,
const GraphContext::CPtr context,
const ov::optional<Shape>& input_shape,
- const ov::optional<ov::element::Type>& input_prc) :
- Input(output_shape, output_prc, name, type, context), MemoryStateNode(id) {
+ const ov::optional<ov::element::Type>& input_prc,
+ MemoryInputBase::mode mode)
+ : Input(output_shape, output_prc, name, type, context),
+ MemoryStateNode(id) {
outputShapes.emplace_back(output_shape);
addOriginalOutputPrecision(output_prc);
if (input_shape) {
@@ -411,6 +415,17 @@ MemoryInputBase::MemoryInputBase(const std::string id,
if (created()) {
context->getMemoryStatesRegister()->registerInput(this);
}
+
+ // this important to prevent identifying it as a const when it's on a const path
+ constant = ConstantType::StrictNoConst;
+
+ if (mode::read_value_assign == mode) {
+ executeHook = &MemoryInputBase::assignState;
+ } else if (mode::single_read_value == mode) {
+ executeHook = &MemoryInputBase::bypassAssignState;
+ } else {
+ THROW_CPU_NODE_ERR("Unexpected MemoryInput mode");
+ }
}
MemoryInputBase::~MemoryInputBase() {
@@ -513,15 +528,26 @@ void MemoryInputBase::assignState(MemStatePtr newState) {
}
void MemoryInputBase::execute(dnnl::stream strm) {
- getOutputNode().assignState(getAssignedState());
+ assert(executeHook && "executeHook is not initialized!");
+ (this->*executeHook)();
runStatic(strm);
}
void MemoryInputBase::executeDynamicImpl(dnnl::stream strm) {
- getOutputNode().assignState(getAssignedState());
+ assert(executeHook && "executeHook is not initialized!");
+ (this->*executeHook)();
runDynamic(strm);
}
+void MemoryInputBase::assignState() {
+ getOutputNode().assignState(getAssignedState());
+}
+
+void MemoryInputBase::bypassAssignState() {
+ // nothing to do
+ return;
+}
+
bool MemoryInput::needInitGraphProcessing() const {
return !getParentEdges().empty() && getAssignedState()->is_reset_state();
}
@@ -828,6 +854,89 @@ void MemoryInputSDPA::resolveInPlaceEdges(Edge::LOOK look) {
}
}
+MemoryInputSingle::MemoryInputSingle(const std::string id,
+ const std::string& name,
+ const std::string& type,
+ const Shape& output_shape,
+ const ov::element::Type& output_prc,
+ const GraphContext::CPtr context,
+ const ov::optional<Shape>& input_shape,
+ const ov::optional<ov::element::Type>& input_prc)
+ : MemoryInput(id,
+ name,
+ type,
+ output_shape,
+ output_prc,
+ context,
+ input_shape,
+ input_prc,
+ MemoryInputBase::mode::single_read_value) {}
+
+MemStatePtr MemoryInputSingle::makeState() const {
+ // assume ov::Tensor is always dense
+ auto original_desc =
+ std::make_shared<CpuBlockedMemoryDesc>(getOriginalOutputPrecisionAtPort(0), outputShapes.at(0));
+
+ auto mem_desc = getBaseMemDescAtOutputPort(0);
+ const auto& eng = getEngine();
+
+ auto state_name = getId();
+
+ // Remove suffix with pair ID. Internal information.
+ auto suffix_idx = state_name.find("/id=");
+ if (suffix_idx != std::string::npos) {
+ state_name = state_name.substr(0, suffix_idx);
+ }
+
+ return std::make_shared<VariableStateSingleBuffer>(state_name,
+ std::make_shared<Memory>(eng, mem_desc),
+ original_desc);
+}
+
+void MemoryInputSingle::runStatic(dnnl::stream strm) {
+ MemoryInput::runStatic(strm);
+ if (needInitGraphProcessing()) {
+ // since there is no corresponding MemoryOutput node, we need to update the state here
+ auto result = getDstMemoryAtPort(0); // only one output port
+ auto stateMem = getAssignedState()->output_mem();
+ CPU_NODE_ASSERT(stateMem, " state memory has nullptr");
+ if (result->getData() != stateMem->getData()) {
+ stateMem->load(*result);
+ }
+ }
+ getAssignedState()->commit(); // since we don't use MemoryOutput, commit must be called to change the reset state
+}
+
+void MemoryInputSingle::runDynamic(dnnl::stream strm) {
+ MemoryInput::runDynamic(strm);
+ if (needInitGraphProcessing()) {
+ // since there is no corresponding MemoryOutput node, we need to update the state here
+ auto result = getDstMemoryAtPort(0); // only one output port
+ auto state = getAssignedState();
+ auto stateMem = state->output_mem();
+ CPU_NODE_ASSERT(stateMem, " state memory has nullptr");
+
+ const auto& newShape = result->getShape();
+ const auto& stateShape = stateMem->getShape();
+
+ if (stateShape.isDynamic() || stateShape.getStaticDims() != newShape.getStaticDims()) {
+ auto extMemDesc = state->internal_desc();
+ auto newExternDesc = extMemDesc->cloneWithNewDims(newShape.getStaticDims());
+ stateMem->redefineDesc(newExternDesc);
+ }
+
+ if (result->getData() != stateMem->getData()) {
+ stateMem->load(*result);
+ }
+ }
+ getAssignedState()->commit(); // since we don't use MemoryOutput, commit must be called to change the reset state
+}
+
+bool MemoryInputSingle::isSupportedOperation(const std::shared_ptr<const ov::Node>& op,
+ std::string& errorMessage) noexcept {
+ return MemoryInput::isSupportedOperation(op, errorMessage);
+}
+
} // namespace node
} // namespace intel_cpu
} // namespace ov
diff --git a/src/plugins/intel_cpu/src/nodes/memory.hpp b/src/plugins/intel_cpu/src/nodes/memory.hpp
index c158d738a36..f503a8d5838 100644
--- a/src/plugins/intel_cpu/src/nodes/memory.hpp
+++ b/src/plugins/intel_cpu/src/nodes/memory.hpp
@@ -120,16 +120,14 @@ protected:
};
class MemoryInputBase : public Input, public MemoryStateNode {
+public:
+ enum class mode {
+ read_value_assign,
+ single_read_value
+ };
+
public:
MemoryInputBase(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr context);
- MemoryInputBase(const std::string id,
- const std::string& name,
- const std::string& type,
- const Shape& output_shape,
- const ov::element::Type& output_prc,
- const GraphContext::CPtr context,
- const ov::optional<Shape>& input_shape,
- const ov::optional<ov::element::Type>& input_prc);
~MemoryInputBase() override;
@@ -152,6 +150,17 @@ public:
MemoryOutputBase& getOutputNode();
void assignState(MemStatePtr newState) override final; // NOLINT
+protected:
+ MemoryInputBase(const std::string id,
+ const std::string& name,
+ const std::string& type,
+ const Shape& output_shape,
+ const ov::element::Type& output_prc,
+ const GraphContext::CPtr context,
+ const ov::optional<Shape>& input_shape,
+ const ov::optional<ov::element::Type>& input_prc,
+ mode mode = mode::read_value_assign);
+
protected:
virtual void runStatic(dnnl::stream strm) = 0;
virtual void runDynamic(dnnl::stream strm) = 0;
@@ -160,12 +169,20 @@ protected:
return state;
}
+private:
+ using executeHookPtr = void (MemoryInputBase::*)(void);
+
+private:
+ void assignState();
+ void bypassAssignState();
+
private:
/**
* @brief keeps reference to output sibling node
*/
MemoryOutputBase* outputNode = nullptr;
MemStatePtr state = nullptr;
+ executeHookPtr executeHook;
};
class MemoryInput : public MemoryInputBase {
@@ -179,16 +196,38 @@ public:
MemStatePtr makeState() const override;
-private:
+protected:
+ bool needInitGraphProcessing() const;
void runStatic(dnnl::stream strm) override;
void runDynamic(dnnl::stream strm) override;
+
+private:
void assignStateHook() override {/*pass*/}
- bool needInitGraphProcessing() const;
private:
ProxyMemoryBlockPtr memBlock = nullptr;
};
+class MemoryInputSingle : public MemoryInput {
+public:
+ MemoryInputSingle(const std::string id,
+ const std::string& name,
+ const std::string& type,
+ const Shape& output_shape,
+ const ov::element::Type& output_prc,
+ const GraphContext::CPtr context,
+ const ov::optional<Shape>& input_shape,
+ const ov::optional<ov::element::Type>& input_prc);
+
+ static bool isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage) noexcept;
+
+ MemStatePtr makeState() const override;
+
+private:
+ void runStatic(dnnl::stream strm) override;
+ void runDynamic(dnnl::stream strm) override;
+};
+
class MemoryInputSDPA : public MemoryInputBase {
public:
MemoryInputSDPA(const std::string id,
diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/common/read_value_assign.cpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/common/read_value_assign.cpp
new file mode 100644
index 00000000000..c6e976b321f
--- /dev/null
+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/common/read_value_assign.cpp
@@ -0,0 +1,182 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "common_test_utils/node_builders/eltwise.hpp"
+#include "common_test_utils/node_builders/constant.hpp"
+#include "shared_test_classes/base/ov_subgraph.hpp"
+#include "utils/cpu_test_utils.hpp"
+
+/* The main purpose of this test set is to test ReadValue->Assign direct connection optimizations, i.e.
+ dropping the MemoryOutput node.
+*/
+
+namespace ov {
+namespace test {
+
+using namespace CPUTestUtils;
+
+// ┌────────┐ ┌────────┐
+// │ Param2 │ │ Param1 │ |---------------|
+// └───┬────┘ └────┬───┘ | |
+// │ |-----------|┌─────────┐ |
+// │ | │ │Constant │ |
+// │ | │ └───┬─────┘ |
+// │ | ┌───┴────┐ │ |
+// │ | │Multiply├─────┘ |
+// │ | └───┬────┘ | <- Optional Init Subgraph
+// │ | │ ┌─────────┐ |
+// │ | │ │Constant │ |
+// │ | │ └───┬─────┘ |
+// │ | ┌───┴────┐ │ |
+// │ | │ Add ├─────┘ |
+// │ | └───┬────┘ |
+// │ | │ |
+// │ |---------------------------|
+// │ │
+// │ │
+// │ │
+// │ ┌─────┴─────┐
+// │ │ ReadValue │
+// │ └─────┬─────┘
+// │ │ \
+// │ ┌──┴──┐ \
+// └────────┤ Add │ \┌────────┐
+// └──┬──┘ │ Assign │
+// │ └────────┘
+// │
+// ┌────┴────┐
+// │ Result1 │
+// └─────────┘
+
+typedef std::tuple<
+ bool, // include init subgraph
+ CPUSpecificParams
+> ReadValueAssignTestParams;
+
+class ReadValueAssignTest : public testing::WithParamInterface<ReadValueAssignTestParams>,
+ virtual public SubgraphBaseTest,
+ public CPUTestsBase {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<ReadValueAssignTestParams> &obj) {
+ bool use_init_subgraph = false;
+ CPUSpecificParams cpu_params;
+ std::tie(use_init_subgraph, cpu_params) = obj.param;
+
+ std::ostringstream results;
+ results << "Init_Graph=" << (use_init_subgraph ? "True" : "False") << "_";
+ results << CPUTestsBase::getTestCaseName(cpu_params);
+ return results.str();
+ }
+
+ void SetUp() override {
+ targetDevice = ov::test::utils::DEVICE_CPU;
+
+ const ov::Shape tensor_shape = {3, 32, 7, 7};
+
+ InputShape param1_shape = {{-1, 32, -1, -1}, {tensor_shape}};
+ InputShape param2_shape = {{-1, -1, -1, -1}, {tensor_shape}};
+
+ bool use_init_subgraph = false;
+ CPUSpecificParams cpu_params;
+ std::tie(use_init_subgraph, cpu_params) = this->GetParam();
+ std::tie(inFmts, outFmts, priority, selectedType) = cpu_params;
+ selectedType = makeSelectedTypeStr(selectedType, net_prc);
+
+ init_input_shapes({param1_shape, param2_shape});
+
+ ov::ParameterVector params;
+ params.push_back(std::make_shared<ov::op::v0::Parameter>(net_prc, inputDynamicShapes[0]));
+ params.push_back(std::make_shared<ov::op::v0::Parameter>(net_prc, inputDynamicShapes[1]));
+ std::shared_ptr<ov::Node> last_node = params.front();
+
+ if (use_init_subgraph) {
+ //build init subgraph
+ auto const1 = utils::make_constant(net_prc, tensor_shape);
+ auto const2 = utils::make_constant(net_prc, tensor_shape);
+ auto multiply = utils::make_eltwise(last_node, const1, utils::EltwiseTypes::MULTIPLY);
+ auto add = utils::make_eltwise(multiply, const2, utils::EltwiseTypes::ADD);
+ last_node = add;
+ }
+
+ const std::string variable_name("variable0");
+ auto variable = std::make_shared<ov::op::util::Variable>(
+ ov::op::util::VariableInfo{inputDynamicShapes[0], net_prc, variable_name});
+
+ auto read = std::make_shared<ov::op::v6::ReadValue>(last_node, variable);
+ auto assign = std::make_shared<ov::op::v6::Assign>(read, variable);
+ auto add = utils::make_eltwise(params[1], read, utils::EltwiseTypes::ADD);
+
+ add->get_rt_info() = getCPUInfo();
+ auto res = std::make_shared<ov::op::v0::Result>(add);
+
+ function =
+ std::make_shared<ov::Model>(ov::ResultVector({res}), ov::SinkVector({assign}), params, "ReadValueAssign");
+ }
+
+protected:
+ const ov::Shape tensor_shape = {3, 32, 7, 7};
+ const ElementType net_prc = element::f32;
+};
+
+TEST_P(ReadValueAssignTest, CompareWithRefs) {
+ compile_model();
+ inferRequest = compiledModel.create_infer_request();
+ ASSERT_TRUE(inferRequest);
+
+ // use the Template plugin as a reference
+
+ auto compiledReferenceModel = core->compile_model(function, ov::test::utils::DEVICE_TEMPLATE);
+ auto inferRequestRef = compiledReferenceModel.create_infer_request();
+ ASSERT_TRUE(inferRequestRef);
+
+ generate_inputs(targetStaticShapes.front());
+ for (const auto& input : inputs) {
+ inferRequest.set_tensor(input.first, input.second);
+ inferRequestRef.set_tensor(input.first, input.second);
+ }
+
+ constexpr int infer_count = 3lu;
+
+ auto&& states = inferRequest.query_state();
+ auto&& refStates = inferRequestRef.query_state();
+
+ for (int i = 0; i < infer_count; ++i) {
+ // set states
+
+ if (i & 0x1) {
+ //reset every odd iteration
+ states.front().reset();
+ refStates.front().reset();
+ } else {
+ // generate and set state tensors every even iteration
+ using ov::test::utils::InputGenerateData;
+
+ auto tensor =
+ ov::test::utils::create_and_fill_tensor(net_prc, tensor_shape, InputGenerateData{0, 10, 1, i});
+ states.front().set_state(tensor);
+ refStates.front().set_state(tensor);
+ }
+
+ inferRequest.infer();
+ inferRequestRef.infer();
+ auto outputs = function->outputs();
+
+ auto result = inferRequest.get_tensor(outputs[0]);
+
+ auto result_ref = inferRequestRef.get_tensor(outputs[0]);
+
+ ov::test::utils::compare(result, result_ref, 1e-4, 1e-4);
+ }
+ CheckNumberOfNodesWithTypes(compiledModel, {"MemoryOutput", "Assign"}, 0);
+}
+
+INSTANTIATE_TEST_SUITE_P(
+ smoke_ReadValue_Assign,
+ ReadValueAssignTest,
+ ::testing::Combine(::testing::Values(true, false),
+ ::testing::Values(CPUSpecificParams{{nchw, nchw}, {nchw}, {""}, "any_type"},
+ CPUSpecificParams{{nhwc, nhwc}, {nhwc}, {""}, "any_type"})),
+ ReadValueAssignTest::getTestCaseName);
+} // namespace test
+} // namespace ov
\ No newline at end of file
diff --git a/src/plugins/template/src/sync_infer_request.cpp b/src/plugins/template/src/sync_infer_request.cpp
index 41881e9839a..418f8f1b717 100644
--- a/src/plugins/template/src/sync_infer_request.cpp
+++ b/src/plugins/template/src/sync_infer_request.cpp
@@ -59,7 +59,7 @@ void collect_variables(const std::shared_ptr<ov::Model>& ov_model,
ov::Tensor tensor = ov::Tensor(variable->get_info().data_type, shape);
variable_context.set_variable_value(variable, std::make_shared<ov::op::util::VariableValue>(tensor));
auto state =
- std::make_shared<ov::template_plugin::VariableState>(variable->get_info().variable_id,
+ std::make_shared<ov::template_plugin::VariableState>(variable->get_info(),
variable_context.get_variable_value(variable));
list_of_variables.emplace_back(state);
}
diff --git a/src/plugins/template/src/variable_state.hpp b/src/plugins/template/src/variable_state.hpp
index 8227a22c0fe..d6f0972f867 100644
--- a/src/plugins/template/src/variable_state.hpp
+++ b/src/plugins/template/src/variable_state.hpp
@@ -4,6 +4,7 @@
#pragma once
+#include "openvino/op/util/variable.hpp"
#include "openvino/runtime/itensor.hpp"
#include "openvino/runtime/ivariable_state.hpp"
#include "openvino/runtime/so_ptr.hpp"
@@ -13,16 +14,35 @@ namespace template_plugin {
class VariableState : public ov::IVariableState {
public:
- VariableState(const std::string& name, const std::shared_ptr<op::util::VariableValue>& variable_value)
- : ov::IVariableState(name),
+ VariableState(const ov::op::util::VariableInfo& variable_info,
+ const std::shared_ptr<op::util::VariableValue>& variable_value)
+ : ov::IVariableState(variable_info.variable_id),
+ m_data_shape(variable_info.data_shape),
+ m_data_type(variable_info.data_type),
m_variable_value(variable_value) {
m_state = get_tensor_impl(variable_value->get_state());
}
void set_state(const ov::SoPtr<ov::ITensor>& state) override {
- OPENVINO_ASSERT(state->get_shape() == m_state->get_shape(), "Wrong tensor shape.");
- OPENVINO_ASSERT(state->get_element_type() == m_state->get_element_type(), "Wrong tensor type.");
- OPENVINO_ASSERT(state->get_byte_size() == m_state->get_byte_size(), "Blob size of tensors are not equal.");
+ OPENVINO_ASSERT(m_data_shape.compatible(state->get_shape()),
+ "Wrong tensor shape: ",
+ state->get_shape(),
+ " is not compatible with expected: ",
+ m_data_shape,
+ " in a variable with ID: ",
+ this->get_name());
+ OPENVINO_ASSERT(m_data_type.compatible(state->get_element_type()),
+ "Wrong tensor type: ",
+ state->get_element_type(),
+ " expected: ",
+ m_data_type,
+ " in a variable with ID: ",
+ this->get_name());
+ m_state->set_shape(state->get_shape());
+ OPENVINO_ASSERT(state->get_byte_size() == m_state->get_byte_size(),
+ "Blob size of tensors are not equal. Variable with ID: ",
+ this->get_name());
std::memcpy(m_state->data(), state->data(), state->get_byte_size());
+ m_variable_value->set_reset(false);
}
void reset() override {
@@ -33,6 +53,8 @@ public:
~VariableState() override = default;
private:
+ PartialShape m_data_shape; // original shape
+ element::Type m_data_type; // original type
std::shared_ptr<op::util::VariableValue> m_variable_value;
};
} // namespace template_plugin
diff --git a/src/tests/functional/plugin/shared/include/subgraph_tests/lora_pattern.hpp b/src/tests/functional/plugin/shared/include/subgraph_tests/lora_pattern.hpp
index 8f9687b7b93..42f70aa9247 100644
--- a/src/tests/functional/plugin/shared/include/subgraph_tests/lora_pattern.hpp
+++ b/src/tests/functional/plugin/shared/include/subgraph_tests/lora_pattern.hpp
@@ -19,5 +19,15 @@ TEST_P(LoraPatternConvolution, empty_tensors) {
run_test_empty_tensors();
}
+TEST_P(LoraPatternMatmul, random_tensors) {
+ targetStaticShapes = {{{{1, 20, K}}, {{N, K}}}};
+ run_test_random_tensors();
+}
+
+TEST_P(LoraPatternConvolution, random_tensors) {
+ targetStaticShapes = {{{1, num_channels, 64, 64}}};
+ run_test_random_tensors();
+}
+
} // namespace test
} // namespace ov
\ No newline at end of file
diff --git a/src/tests/functional/shared_test_classes/include/shared_test_classes/subgraph/lora_pattern.hpp b/src/tests/functional/shared_test_classes/include/shared_test_classes/subgraph/lora_pattern.hpp
index 16764d37dcf..9b38ca059f1 100644
--- a/src/tests/functional/shared_test_classes/include/shared_test_classes/subgraph/lora_pattern.hpp
+++ b/src/tests/functional/shared_test_classes/include/shared_test_classes/subgraph/lora_pattern.hpp
@@ -15,6 +15,7 @@ public:
protected:
void run_test_empty_tensors();
+ void run_test_random_tensors();
protected:
static constexpr auto t4_name = "lora/MatMul.B";
@@ -37,7 +38,7 @@ public:
void SetUp() override;
protected:
- static constexpr size_t num_channels = 320ul;
+ static constexpr size_t num_channels = 64ul;
};
} // namespace test
diff --git a/src/tests/functional/shared_test_classes/src/subgraph/lora_pattern.cpp b/src/tests/functional/shared_test_classes/src/subgraph/lora_pattern.cpp
index 6f74fd09b02..d40872f0756 100644
--- a/src/tests/functional/shared_test_classes/src/subgraph/lora_pattern.cpp
+++ b/src/tests/functional/shared_test_classes/src/subgraph/lora_pattern.cpp
@@ -8,6 +8,7 @@
#include "common_test_utils/node_builders/convolution.hpp"
#include "common_test_utils/ov_tensor_utils.hpp"
#include "shared_test_classes/base/ov_subgraph.hpp"
+#include "template/properties.hpp"
namespace ov {
namespace test {
@@ -37,6 +38,79 @@ void LoraPatternBase::run_test_empty_tensors() {
ov::test::utils::compare(tx_result, tz_result, 1e-4, 1e-4);
}
+void LoraPatternBase::run_test_random_tensors() {
+ compile_model();
+ inferRequest = compiledModel.create_infer_request();
+ ASSERT_TRUE(inferRequest);
+
+ // use the Template plugin as a reference
+
+ auto compiledReferenceModel = core->compile_model(function,
+ ov::test::utils::DEVICE_TEMPLATE,
+ {{ov::template_plugin::disable_transformations(true)}});
+ auto inferRequestRef = compiledReferenceModel.create_infer_request();
+ ASSERT_TRUE(inferRequestRef);
+
+ generate_inputs(targetStaticShapes.front());
+ for (const auto& input : inputs) {
+ inferRequest.set_tensor(input.first, input.second);
+ inferRequestRef.set_tensor(input.first, input.second);
+ }
+
+ constexpr size_t lora_order = 25lu;
+ constexpr int infer_count = 6lu;
+
+ std::unordered_map<std::string, ov::Shape> stateShapes;
+
+ auto&& vars = function->get_variables();
+
+ for (auto&& var : vars) {
+ auto var_info = var->get_info();
+ auto var_shape = var_info.data_shape;
+
+ std::for_each(var_shape.begin(), var_shape.end(), [=](ov::PartialShape::value_type& x) {
+ if (x.is_dynamic()) {
+ x = lora_order;
+ }
+ });
+ stateShapes.insert({var_info.variable_id, var_shape.to_shape()});
+ }
+
+ for (int i = 0; i < infer_count; ++i) {
+ // set states
+
+ auto&& states = inferRequest.query_state();
+ if (!(i & 0x1)) { // every even call
+ // generate and set state tensors
+ for (auto&& item : states) {
+ auto&& refStates = inferRequestRef.query_state();
+ using ov::test::utils::InputGenerateData;
+ const auto& shape = stateShapes.at(item.get_name());
+ auto tensor = ov::test::utils::create_and_fill_tensor(netType, shape, InputGenerateData{0, 10, 1, i});
+ item.set_state(tensor);
+ auto itr = std::find_if(refStates.begin(), refStates.end(), [&](const ov::VariableState& state) {
+ return state.get_name() == item.get_name();
+ });
+ ASSERT_FALSE(itr == refStates.end());
+ itr->set_state(tensor);
+ }
+ }
+
+ inferRequest.infer();
+ inferRequestRef.infer();
+ auto outputs = function->outputs();
+
+ auto tx_result = inferRequest.get_tensor(outputs[0]);
+ auto tz_result = inferRequest.get_tensor(outputs[1]);
+
+ auto tx_result_ref = inferRequestRef.get_tensor(outputs[0]);
+ auto tz_result_ref = inferRequestRef.get_tensor(outputs[1]);
+
+ ov::test::utils::compare(tx_result, tx_result_ref, 1e-4, 1e-4);
+ ov::test::utils::compare(tz_result, tz_result_ref, 1e-4, 1e-4);
+ }
+}
+
void LoraPatternMatmul::SetUp() {
targetDevice = this->GetParam();