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][DOCS] Add src/nodes/README.md, remove duplicated skill sections (#37995)
Vladislav Golubeva5d71979562a
diff --git a/.github/agents-prototype/skills/add-cpu-op/step2-implementation.md b/.github/agents-prototype/skills/add-cpu-op/step2-implementation.mdindex 9722e9bf60a..9a8ffb47531 100644--- a/.github/agents-prototype/skills/add-cpu-op/step2-implementation.md+++ b/.github/agents-prototype/skills/add-cpu-op/step2-implementation.md@@ -87,299 +87,15 @@ automatically picked up by CMake. No CMakeLists.txt edits needed for source file## Step-by-Step Implementation-### 1. Add Type Enum Entry+1. Read [`src/nodes/README.md`](../../../../src/plugins/intel_cpu/src/nodes/README.md) —+ it covers the node lifecycle, factory registration (`Type` enum,+ `cpu_types.cpp` mapping, `nodes_factory.cpp`), shape inference factories,+ dynamic shapes, the node header/source skeleton, and the mandatory+ `OV_SWITCH` type-dispatch pattern.+2. Create/update the files listed in [File Structure](#file-structure) above,+ following that guide's patterns.-In `src/plugins/intel_cpu/src/cpu_types.h`, add the new type to the `Type` enum:--```cpp-enum class Type : uint8_t {- // ... existing entries ...- OpName, // <-- Add alphabetically or near related ops-};-```--### 2. Add String-to-Type Mapping--In `src/plugins/intel_cpu/src/cpu_types.cpp`, add the mapping in TWO places:--**a) In the `type_to_name_tbl` map (op type string → Type enum):**--```cpp-{"OpName", Type::OpName},-```--**b) In the `type_to_str()` switch (Type enum → debug string), add a CASE:**--```cpp-CASE(OpName);-```--> **Note:** The string key in `type_to_name_tbl` must match the op's-> `get_type_name()` return value exactly. Check the core op's `OPENVINO_OP("...")`-> macro to find the correct string.--### 3. Create the Node Header--Create `src/plugins/intel_cpu/src/nodes/<op_name>.h`:--```cpp-// Copyright (C) 2018-2026 Intel Corporation-// SPDX-License-Identifier: Apache-2.0-//--#pragma once--#include <memory>-#include <oneapi/dnnl/dnnl_common.hpp>-#include <string>--#include "graph_context.h"-#include "node.h"-#include "openvino/core/node.hpp"--namespace ov::intel_cpu::node {--class OpName : public Node {-public:- OpName(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr& context);-- static bool isSupportedOperation(const std::shared_ptr<const ov::Node>& op,- std::string& errorMessage) noexcept;- void getSupportedDescriptors() override;- void initSupportedPrimitiveDescriptors() override;- void execute(const dnnl::stream& strm) override;- [[nodiscard]] bool created() const override;- [[nodiscard]] bool needPrepareParams() const override;- void executeDynamicImpl(const dnnl::stream& strm) override;--private:- // Op-specific attributes- // Template helpers for type dispatch-};--} // namespace ov::intel_cpu::node-```--**Key decisions for the header:**--| Question | If yes | If no |-|----------|--------|-------|-| Does the op need ISA-specific or multi-backend paths? | Use the Executor framework (`ExecutorFactory` + `ExecutorPtr`) — see section below | Use direct `execute()` with `OV_SWITCH` type dispatch |-| Does the op need custom shape inference? | Add custom `ShapeInferFactory` | Use `NgraphShapeInferFactory` |-| Does the op need `prepareParams()`? | Override `needPrepareParams` → `true` | Override → `false` |-| Does the op data-dependent output shape? | Override `needShapeInfer()` | Don't override |--### 4. Create the Node Source--Create `src/plugins/intel_cpu/src/nodes/<op_name>.cpp`:--```cpp-// Copyright (C) 2018-2026 Intel Corporation-// SPDX-License-Identifier: Apache-2.0-//--#include "<op_name>.h"--#include <cstddef>-#include <memory>-#include <oneapi/dnnl/dnnl_common.hpp>-#include <string>--#include "cpu_types.h"-#include "graph_context.h"-#include "memory_desc/cpu_memory_desc.h"-#include "node.h"-#include "onednn/iml_type_mapper.h"-#include "openvino/core/except.hpp"-#include "openvino/core/node.hpp"-#include "openvino/core/type.hpp"-#include "openvino/core/type/element_type.hpp"-#include "openvino/op/<op_name>.hpp" // Core op header-#include "openvino/reference/<op_name>.hpp" // Reference implementation-#include "selective_build.h"-#include "shape_inference/shape_inference_cpu.hpp"--namespace ov::intel_cpu::node {--// ═══════════════════════════════════════════════════════════════════-// Constructor-// ═══════════════════════════════════════════════════════════════════-OpName::OpName(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr& context)- : Node(op, context, NgraphShapeInferFactory(op)) {- std::string errorMessage;- if (!isSupportedOperation(op, errorMessage)) {- OPENVINO_THROW_NOT_IMPLEMENTED(errorMessage);- }- // Extract attributes from the core op:- // const auto typed_op = ov::as_type_ptr<const ov::op::vX::OpName>(op);- // m_attribute = typed_op->get_attribute();-}--// ═══════════════════════════════════════════════════════════════════-// Supported Operation Check-// ═══════════════════════════════════════════════════════════════════-bool OpName::isSupportedOperation(const std::shared_ptr<const ov::Node>& op,- std::string& errorMessage) noexcept {- try {- if (!ov::is_type<ov::op::vX::OpName>(op)) {- errorMessage = "Only opsetX OpName operation is supported";- return false;- }- // Add additional checks: shape constraints, attribute values, etc.- } catch (...) {- return false;- }- return true;-}--// ═══════════════════════════════════════════════════════════════════-// Descriptor Setup-// ═══════════════════════════════════════════════════════════════════-void OpName::getSupportedDescriptors() {- // Validation is already done in the core op.- // Add CPU-specific validation here if needed.-}--void OpName::initSupportedPrimitiveDescriptors() {- if (!supportedPrimitiveDescriptors.empty()) {- return;- }-- auto inputPrecision = getOriginalInputPrecisionAtPort(0);- auto outputPrecision = getOriginalOutputPrecisionAtPort(0);-- // Constrain to supported precisions- if (none_of(inputPrecision,- ov::element::f32,- ov::element::bf16, // requires avx512_core_bf16- ov::element::f16,- ov::element::i32)) {- inputPrecision = ov::element::f32;- }-- // Register supported primitive descriptors with layout+precision- addSupportedPrimDesc(- {{LayoutType::ncsp, inputPrecision}}, // inputs- {{LayoutType::ncsp, outputPrecision}}, // outputs- impl_desc_type::ref); // implementation type-}--// ═══════════════════════════════════════════════════════════════════-// Execution-// ═══════════════════════════════════════════════════════════════════-bool OpName::created() const {- return getType() == Type::OpName;-}--bool OpName::needPrepareParams() const {- return false;-}--void OpName::executeDynamicImpl(const dnnl::stream& strm) {- execute(strm);-}--void OpName::execute([[maybe_unused]] const dnnl::stream& strm) {- // Option A: Call the reference implementation directly- // ov::reference::op_name(getSrcDataAtPortAs<const T>(0),- // getDstDataAtPortAs<T>(0),- // ov::Shape{getSrcMemoryAtPort(0)->getStaticDims()},- // /* attributes */);-- // Option B: Use OV_SWITCH for type dispatch- // (see SearchSorted or SegmentMax for pattern)-}--} // namespace ov::intel_cpu::node-```--### 5. Register in Node Factory--In `src/plugins/intel_cpu/src/nodes_factory.cpp`:--**a) Add the include:**--```cpp-#include "nodes/<op_name>.h"-```--**b) Add the registration macro in `NodesFactory::NodesFactory()`:**--```cpp-INTEL_CPU_NODE(OpName, Type::OpName);-```--> **Architecture-specific registration:** If the node is only supported on-> x86-64 (e.g., has JIT kernels), wrap both the include and registration in:-> ```cpp-> #if defined(OPENVINO_ARCH_X86_64)-> INTEL_CPU_NODE(OpName, Type::OpName);-> #endif-> ```--### 6. Shape Inference--**Standard ops** — Use `NgraphShapeInferFactory(op)` in the constructor (default).-This delegates to the core op's `validate_and_infer_types()`.--**Custom shape inference** — When the core shape inference is insufficient or when-output shapes depend on input data at runtime:--Create `src/plugins/intel_cpu/src/shape_inference/custom/<op_name>.hpp`:--```cpp-#pragma once--#include <memory>-#include <utility>--#include "openvino/core/node.hpp"-#include "shape_inference/shape_inference_cpu.hpp"--namespace ov::intel_cpu::node {--class OpNameShapeInferFactory : public ShapeInferFactory {-public:- explicit OpNameShapeInferFactory(std::shared_ptr<ov::Node> op) : m_op(std::move(op)) {}- [[nodiscard]] ShapeInferPtr makeShapeInfer() const override;--private:- std::shared_ptr<ov::Node> m_op;-};--} // namespace ov::intel_cpu::node-```--Then in the node constructor, use `OpNameShapeInferFactory(op)` instead of-`NgraphShapeInferFactory(op)`.--### 7. Dynamic Shapes Support--Dynamic shapes are a **mandatory** requirement for new CPU node implementations.--Key methods to implement:--| Method | Purpose |-|--------|---------|-| `executeDynamicImpl(strm)` | Called during dynamic-shape execution. Usually delegates to `execute(strm)`. |-| `needPrepareParams()` | Return `true` if internal state (e.g., JIT kernel) must be rebuilt when shapes change. |-| `needShapeInfer()` | Override if output shape depends on input **data** (not just input shapes). |-| `createPrimitive()` | Called once after shapes are resolved. Allocate JIT kernels here (with caching). |--**Pattern for data-dependent output shapes** (see `SegmentMax` for reference):--```cpp-bool OpName::needShapeInfer() const {- if (inputShapesModified()) {- return true;- }- // Check if data that affects output shape has changed- // Compare against cached values- return false;-}-```--### 8. Build Verification+### Build Verification```bashcd build@@ -390,38 +106,6 @@ cmake --build . --target openvino_intel_cpu_plugin -j$(nproc) 2>&1 | tail -20Verify no compilation errors before proceeding.-## Type Dispatch Pattern (OV_SWITCH — Mandatory for Conditional Compilation)--See [In-code conditional compilation](../../../../src/plugins/intel_cpu/docs/selective_build.md#in-code-conditional-compilation) for why `OV_SWITCH` is mandatory instead of a manual `if/else`/`switch` chain.--```cpp-namespace {-struct OpNameContext {- OpName& node;-};-} // namespace--template <class T>-struct OpName::OpNameExecute {- void operator()(OpNameContext& ctx) {- ctx.node.executeImpl<T>();- }-};--void OpName::execute([[maybe_unused]] const dnnl::stream& strm) {- auto precision = getParentEdgeAt(0)->getMemory().getDesc().getPrecision();- OpNameContext ctx = {*this};- OV_SWITCH(intel_cpu,- OpNameExecute,- ctx,- precision,- OV_CASE(ov::element::f32, float),- OV_CASE(ov::element::bf16, ov::bfloat16),- OV_CASE(ov::element::f16, ov::float16),- OV_CASE(ov::element::i32, int32_t))-}-```-## Executor Pattern (Standard Architecture for Non-Trivial Ops)The executor framework is the **standard architecture** for any CPU node that isdiff --git a/src/plugins/intel_cpu/src/nodes/README.md b/src/plugins/intel_cpu/src/nodes/README.mdnew file mode 100644index 00000000000..1d00a46467f--- /dev/null+++ b/src/plugins/intel_cpu/src/nodes/README.md@@ -0,0 +1,269 @@+# CPU Plugin Nodes++A *node* is the CPU plugin's executable representation of an OpenVINO operation.+Every node derives from the `Node` base class ([node.h](../node.h)) and is created+by the node factory ([nodes_factory.cpp](../nodes_factory.cpp)) from an+`ov::Node`. This document is the reference for how a CPU node is structured — its+lifecycle methods, factory registration, shape inference, and type dispatch. It is+general background for anyone working on CPU nodes, independent of the op-specific+workflow for adding a *new* op.++## Contents++- [Node lifecycle](#node-lifecycle)+- [Factory registration](#factory-registration)+- [Shape inference factories](#shape-inference-factories)+- [Dynamic shapes](#dynamic-shapes)+- [Type dispatch with OV_SWITCH](#type-dispatch-with-ov_switch)+- [Node header and source skeleton](#node-header-and-source-skeleton)+- [See also](#see-also)++## Node lifecycle++The `Node` base class declares the virtual methods a concrete node overrides. They+are called by the graph in roughly this order — once at compile time+(descriptors), then per inference (params + execute):++| Method | When called | Purpose |+|--------|-------------|---------|+| constructor `OpName(op, context)` | graph build | Validate the op via `isSupportedOperation`, extract attributes, pass a shape-infer factory to the `Node` base. |+| `getSupportedDescriptors()` | compile | Pure virtual. CPU-specific validation / descriptor preparation (often empty when the core op already validated). |+| `initSupportedPrimitiveDescriptors()` | compile | Register the supported `{layout, precision}` combinations per port via `addSupportedPrimDesc`, or build them from an `ExecutorFactory`. |+| `created()` | compile | Pure virtual. Return `getType() == Type::OpName`. |+| `needPrepareParams()` | compile/runtime | Return `true` if internal state (e.g. a JIT kernel) must be rebuilt when shapes change. |+| `createPrimitive()` | after shapes resolved | Allocate primitives/kernels once shapes are known (with caching). |+| `prepareParams()` | per inference (if `needPrepareParams`) | Refresh memory pointers and `update()` the executor. |+| `execute(strm)` | per inference (static) | Pure virtual. Run the computation. |+| `executeDynamicImpl(strm)` | per inference (dynamic) | Run under dynamic shapes; usually delegates to `execute(strm)`. |+| `needShapeInfer()` | per inference | Override if the output shape depends on input **data**, not just input shapes. |++`isSupportedOperation(op, errorMessage)` is a `static noexcept` method used both by+the constructor and by the graph to decide whether the node can handle a given+`ov::Node`. It must never throw.++## Factory registration++A node type is registered in three places so the factory can instantiate it from an+`ov::Node`:++1. **`Type` enum** in [cpu_types.h](../cpu_types.h) — add `OpName`.+2. **String ↔ `Type` mapping** in [cpu_types.cpp](../cpu_types.cpp): add+ `{"OpName", Type::OpName}` to `type_to_name_tbl`, and a `CASE(OpName)` in the+ `NameFromType()` switch. The string key must match the core op's+ `get_type_name()` (the `OPENVINO_OP("...")` macro) exactly.+3. **Factory entry** in [nodes_factory.cpp](../nodes_factory.cpp): include the node+ header and add `INTEL_CPU_NODE(OpName, Type::OpName);`. For nodes that do not+ build on every architecture (e.g. JIT-only), guard both the include and the+ entry with the condition matching the node's actual support — both+ `#if defined(OPENVINO_ARCH_X86_64)` and+ `#if defined(OPENVINO_ARCH_X86) || defined(OPENVINO_ARCH_X86_64)` are in use.++## Shape inference factories++The `Node` constructor takes a shape-inference factory:++- **`NgraphShapeInferFactory(op)`** — the default. Delegates to a per-opset static+ shape-inference implementation registered in `shape_inference.cpp`, falling back+ to the op's generic `validate_and_infer_types()`-based path when no specialized+ implementation is registered. Use it whenever the core/generic shape inference is+ sufficient.+- **Custom `ShapeInferFactory`** — when the core inference is insufficient or the+ output shape depends on runtime data. Implemented under+ [shape_inference/custom/](../shape_inference/custom/) as an+ `OpNameShapeInferFactory : public ShapeInferFactory` whose `makeShapeInfer()`+ returns the op-specific `ShapeInferPtr`.++## Dynamic shapes++Dynamic shapes are mandatory for CPU nodes. The relevant overrides:++- `executeDynamicImpl(strm)` — entry point under dynamic shapes; delegate to+ `execute(strm)` unless the dynamic path differs.+- `needPrepareParams()` — `true` when shape changes require rebuilding kernels.+- `needShapeInfer()` — override only for **data-dependent** output shapes; compare+ the relevant inputs against cached values and return `true` when they changed+ (see `SegmentMax` for an example).+- `createPrimitive()` — allocate the kernel after shapes are resolved.++```cpp+bool OpName::needShapeInfer() const {+ if (inputShapesModified()) {+ return true;+ }+ // Output shape depends on input data: compare against cached values.+ return false;+}+```++## Type dispatch with OV_SWITCH++For nodes that handle multiple element types, **always** dispatch with the+`OV_SWITCH` macro rather than a manual `if/else` or `switch` on the element type.+`OV_SWITCH` lets conditional compilation eliminate unused type specialisations at+compile time, reducing binary size; manual chains defeat it. See+[selective_build.md](../../docs/selective_build.md#in-code-conditional-compilation)+for the macro reference.++```cpp+namespace {+struct OpNameContext {+ OpName& node;+};+} // namespace++template <class T>+struct OpName::OpNameExecute {+ void operator()(OpNameContext& ctx) {+ ctx.node.executeImpl<T>();+ }+};++void OpName::execute([[maybe_unused]] const dnnl::stream& strm) {+ auto precision = getParentEdgeAt(0)->getMemory().getDesc().getPrecision();+ OpNameContext ctx = {*this};+ OV_SWITCH(intel_cpu,+ OpNameExecute,+ ctx,+ precision,+ OV_CASE(ov::element::f32, float),+ OV_CASE(ov::element::bf16, ov::bfloat16),+ OV_CASE(ov::element::f16, ov::float16),+ OV_CASE(ov::element::i32, int32_t))+}+```++## Node header and source skeleton++Files use `snake_case` names and `CamelCase` classes, in the+`ov::intel_cpu::node` namespace. The build uses `file(GLOB_RECURSE)`, so new files+under `src/` are picked up automatically — no CMakeLists edits.++```cpp+// <op_name>.h+#pragma once++#include <memory>+#include <oneapi/dnnl/dnnl_common.hpp>+#include <string>++#include "graph_context.h"+#include "node.h"+#include "openvino/core/node.hpp"++namespace ov::intel_cpu::node {++class OpName : public Node {+public:+ OpName(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr& context);++ static bool isSupportedOperation(const std::shared_ptr<const ov::Node>& op,+ std::string& errorMessage) noexcept;+ void getSupportedDescriptors() override;+ void initSupportedPrimitiveDescriptors() override;+ void execute(const dnnl::stream& strm) override;+ [[nodiscard]] bool created() const override;+ [[nodiscard]] bool needPrepareParams() const override;+ void executeDynamicImpl(const dnnl::stream& strm) override;++private:+ // Op-specific attributes; template helpers for type dispatch.+};++} // namespace ov::intel_cpu::node+```++**Key decisions for the header:**++| Question | If yes | If no |+|----------|--------|-------|+| Does the op need ISA-specific or multi-backend paths? | Use the Executor framework (`ExecutorFactory` + `ExecutorPtr`) — see [Executor Pattern](../../../../../.github/agents-prototype/skills/add-cpu-op/step2-implementation.md#executor-pattern-standard-architecture-for-non-trivial-ops) | Use direct `execute()` with `OV_SWITCH` type dispatch |+| Does the op need custom shape inference? | Add custom `ShapeInferFactory` | Use `NgraphShapeInferFactory` |+| Does the op need `prepareParams()`? | Override `needPrepareParams` → `true` | Override → `false` |+| Does the op have a data-dependent output shape? | Override `needShapeInfer()` | Don't override |++```cpp+// <op_name>.cpp+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "<op_name>.h"++#include "cpu_types.h"+#include "openvino/core/except.hpp"+#include "openvino/op/<op_name>.hpp" // core op+#include "shape_inference/shape_inference_cpu.hpp"++namespace ov::intel_cpu::node {++OpName::OpName(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr& context)+ : Node(op, context, NgraphShapeInferFactory(op)) {+ std::string errorMessage;+ if (!isSupportedOperation(op, errorMessage)) {+ OPENVINO_THROW_NOT_IMPLEMENTED(errorMessage);+ }+ // const auto typed_op = ov::as_type_ptr<const ov::op::vX::OpName>(op);+ // m_attribute = typed_op->get_attribute();+}++bool OpName::isSupportedOperation(const std::shared_ptr<const ov::Node>& op,+ std::string& errorMessage) noexcept {+ try {+ if (!ov::is_type<ov::op::vX::OpName>(op)) {+ errorMessage = "Only opsetX OpName operation is supported";+ return false;+ }+ // Additional checks: shape constraints, attribute values, etc.+ } catch (...) {+ return false;+ }+ return true;+}++void OpName::getSupportedDescriptors() {+ // CPU-specific validation if needed (core op already validated).+}++void OpName::initSupportedPrimitiveDescriptors() {+ if (!supportedPrimitiveDescriptors.empty()) {+ return;+ }+ auto inputPrecision = getOriginalInputPrecisionAtPort(0);+ auto outputPrecision = getOriginalOutputPrecisionAtPort(0);+ if (none_of(inputPrecision, ov::element::f32, ov::element::bf16,+ ov::element::f16, ov::element::i32)) {+ inputPrecision = ov::element::f32;+ }+ addSupportedPrimDesc({{LayoutType::ncsp, inputPrecision}}, // inputs+ {{LayoutType::ncsp, outputPrecision}}, // outputs+ impl_desc_type::ref);+}++bool OpName::created() const {+ return getType() == Type::OpName;+}++bool OpName::needPrepareParams() const {+ return false;+}++void OpName::executeDynamicImpl(const dnnl::stream& strm) {+ execute(strm);+}++void OpName::execute([[maybe_unused]] const dnnl::stream& strm) {+ // Option A: call the reference implementation directly.+ // Option B: dispatch element type with OV_SWITCH (see above).+}++} // namespace ov::intel_cpu::node+```++For nodes more complex than portable C++ (JIT, oneDNN, multi-ISA), the body of+`initSupportedPrimitiveDescriptors`/`prepareParams`/`execute` is driven by the+executor framework, documented separately.++## See also++- [kernels/simd/README.md](kernels/simd/README.md) — SIMD abstraction for kernels.+- [../../docs/selective_build.md](../../docs/selective_build.md#in-code-conditional-compilation) — `OV_SWITCH` / `OV_CPU_INSTANCE_*` and conditional compilation.