espressif/esp-dl/espdl-operator

Claude Code and agent skill by espressif/esp-dl

Trust tier 2
  • community
LLM review pending
Source check pending

Checking that the SKILL.md file is still in the repository.

End-to-end guide for implementing, testing, and optimizing neural network operators in the ESP-DL framework. Covers C++ module implementation, C reference kernels, SIMD assembly optimization, esp-ppq quantization strategy integration, Docker-based build/test, and inference result alignment between esp-dl and esp-ppq. Use this skill whenever the user wants to add a new operator, implement an operator, optimize an existing operator with SIMD, add quantization support for an operator, or test/vali…

Install

npx vskill@latest install espressif/esp-dl/espdl-operator

SKILL.md

The same SKILL.md was published earlier as espressif/esp-dl/espdl-operator.

ESP-DL Operator Development Skill

This skill guides you through the complete lifecycle of implementing a neural network operator in ESP-DL: from C++ module code, through quantization support in esp-ppq, to Docker-based validation that ensures inference results align between the quantization tool and the on-device runtime.

Workflow Continuity — Read This First

This skill describes a multi-phase pipeline: research → implement → test → optimize → document. The most critical transition is from code modification (Phases 2–5) to testing (Phase 6).

After completing ANY code change — whether it's a new module, a base layer fix, an esp-ppq tweak, or a test config update — immediately proceed to Phase 6 (Docker Build & Test) without stopping to ask the user. The user expects the full implement-then-test cycle to happen as one continuous flow. Pausing after code changes to ask "should I run tests now?" breaks the workflow and forces unnecessary back-and-forth.

The only reasons to pause before testing are:

  • You need information the user hasn't provided (e.g., target chip, Docker image location)
  • A build/compilation error requires the user's input to resolve
  • The user explicitly asked you to stop at a certain phase

When multiple code files need modification, complete ALL code changes first (Phases 2–5 as applicable), then run the full test pipeline once. Don't test after each individual file change.


Project Layout

esp-dl/esp-dl/
├── dl/module/include/dl_module_<op>.hpp # Module layer: interface, shape inference, forward dispatch
├── dl/module/include/dl_module_creator.hpp # Operator registry
├── dl/base/dl_base_<op>.hpp/.cpp # Base layer: C reference impl + ISA dispatch
├── dl/base/isa/tie728/dl_tie728_*.S # TIE728 SIMD (ESP32-S3)
├── dl/base/isa/esp32p4/dl_esp32p4_*.S # ESP32-P4 SIMD (RISC-V PIE)
esp-dl/tools/ops_test/
├── config/op_cfg.toml # Test configurations per operator
├── torch_ops_test.py # PyTorch-based test model builders
├── onnx_ops_test.py # ONNX-based test model builders
├── gen_test_cases.py # Generates quantized .espdl test models
esp-dl/test_apps/esp-dl/ # Test application (builds + runs on hardware)
esp-ppq/esp_ppq/
├── quantization/quantizer/EspdlQuantizer.py # Quantization config per op type
├── parser/espdl/espdl_typedef.py # Op set classifications
├── parser/espdl/export_patterns.py # Export pattern rules (LUT, layout, fusion)
├── IR/base/opdef.py # OpSocket definitions for dispatch
├── executor/op/torch/espdl.py # LUT computation backend

Phase 1: Research & Classify the Operator

Before writing any code, understand what you're building.

1.1 Read the ONNX Specification

Look up the operator at https://onnx.ai/onnx/operators/onnx__<OpName>.html. Understand its inputs, outputs, attributes, broadcasting rules, and edge cases.

1.2 Classify the Operator

The classification determines which templates and patterns to follow:

CategoryExamplesModule PatternBase Pattern
Elementwise binaryAdd, Sub, Mul, Div, Mod, Powdl_module_add.hppdl_base_add.hpp/cpp (elemwiseArgsType)
Elementwise unaryRelu, Sigmoid, Exp, Neg, Sqrtdl_module_relu.hppdl_base_relu.hpp/cpp (ArgsType)
Convolution-likeConv, ConvTranspose, DepthwiseConvdl_module_conv.hppdl_base_conv2d.hpp/cpp
PoolingAveragePool, MaxPool, GlobalAveragePooldl_module_average_pool.hppdl_base_avg_pool2d.hpp/cpp
ReduceReduceSum, ReduceMean, ReduceMaxdl_module_reduce_sum.hppdl_base_reduce.hpp/cpp
Shape manipulationReshape, Transpose, Flatten, Slicedl_module_reshape.hppTypically no base layer needed
Sequence/RNNGRU, LSTMdl_module_gru.hppComplex multi-step base
Activation (LUT)HardSwish, HardSigmoid, Tanhdl_module_lut.hppLUT-based implementation

Read 2-3 reference implementations from the same category. The references directory at references/esp-dl-templates.md has annotated templates for each category.

1.3 Determine Scope

Decide which data types to support: int8, int16, float32.

Default rule: ALL operators MUST implement float32 unless technically impossible. Float32 serves as the high-precision inference path — it preserves full model accuracy without quantization loss and is the baseline for correctness validation. Every operator that can accept float inputs and produce float outputs should support float32, regardless of whether it is "compute-heavy" or "typically run quantized". Conv, ConvTranspose, MatMul, Linear, and all other operators should include float32 support.

When float32 is appropriate (the vast majority of operators):

  • Elementwise ops (Add, Sub, Mul, Relu, Sigmoid, etc.) — always
  • Reduce ops (ReduceSum, ReduceMean, etc.) — always
  • Shape ops (Reshape, Transpose, etc.) — always (dtype-agnostic)
  • Activation/LUT ops (HardSwish, Tanh, etc.) — always (float uses direct computation, not LUT)
  • Conv, ConvTranspose, MatMul, Linear — always (float32 preserves high-precision inference)
  • Pooling ops (AveragePool, MaxPool, etc.) — always
  • Sequence/RNN ops (GRU, LSTM, etc.) — always

The only exceptions where float32 may be omitted:

  • Comparison ops (Greater, Equal, Less) — output is boolean, not a numeric tensor
  • Ops whose output dtype is inherently non-float (e.g., ArgMax returns indices)

If you are unsure whether an operator should support float32, the answer is yes, it should. Only omit float32 when the operator's semantics make float input/output meaningless.

Float32 implementation is generally simpler than quantized: no scale/rescale, no truncation, no exponent handling, and no SIMD optimization needed.


Phase 2: Implement esp-dl Module Layer

Create esp-dl/dl/module/include/dl_module_<op_snake>.hpp where <op_snake> is the snake_case version of the ONNX operator name (e.g., HardSwish → hard_swish).

2.1 Module Class Structure

Every operator module must:

  1. Inherit from `Module` (defined in dl_module_base.hpp)
  2. Implement `get_output_shape()` — compute output shape from input shapes
  3. Implement `forward()` — dispatch to the correct typed forward_template<T>()
  4. Implement `forward_template<T>()` — get tensors from context, prepare args, call base layer
  5. Implement static `deserialize()` — reconstruct from FlatBuffers model
  6. Optionally implement `forward_args()` — for dual-core dispatch support
  7. Optionally implement `print()` — debug info

Key conventions:

  • Use #pragma once as header guard
  • Namespace: dl::module
  • Constructor takes name, inplace, quant_type at minimum
  • Additional ONNX attributes become constructor parameters and class members
  • quant_type dispatches to QUANT_TYPE_SYMM_8BIT, QUANT_TYPE_SYMM_16BIT, QUANT_TYPE_FLOAT32

See references/esp-dl-templates.md for full annotated templates.

2.2 Deserialization

The deserialize() static method reads attributes from FlatBuffers:

cpp
static Module *deserialize(fbs::FbsModel *fbs_model, std::string node_name)
{
Module *op = nullptr;
quant_type_t quant_type;
fbs_model->get_operation_attribute(node_name, "quant_type", quant_type);
// Read operator-specific attributes
int some_attr;
fbs_model->get_operation_attribute(node_name, "some_attr", some_attr);
op = new MyOp(node_name.c_str(), MODULE_NON_INPLACE, quant_type, some_attr);
return op;
}
2.3 Register in Creator

Add the operator to dl_module_creator.hpp in the register_dl_modules() method:

cpp
this->register_module("MyOp", MyOp::deserialize);

Also add the #include "dl_module_<op_snake>.hpp" at the top of the creator header.

→ Continue to Phase 3 if a base layer is needed, or skip to Phase 4 (esp-ppq) if this is a shape-only op. After all code phases are done, proceed directly to Phase 6 for testing.


Phase 3: Implement esp-dl Base Layer (C Reference)

The base layer provides the actual computation kernel. Create:

  • esp-dl/dl/base/dl_base_<op_snake>.hpp — declarations
  • esp-dl/dl/base/dl_base_<op_snake>.cpp — C reference implementation
3.1 Architecture
Module::forward_template<T>()
→ prepares ArgsType / elemwiseArgsType
→ calls base::<op_function>(args)
→ selects ISA-optimized or C reference impl
→ executes the kernel

For elementwise binary ops, use elemwiseArgsType<T> and the elemwise_loop_*d() helpers. For unary ops, use ArgsType<T> and the activation_shell() helper. For other ops, define a custom args struct.

3.2 ISA Dispatch Pattern

In the .cpp file, the implementation selection follows this pattern:

cpp
#if CONFIG_PIE_V2_BOOST
impl_func = dl_esp32p4_s8_<op>_11c; // P4 SIMD
#elif CONFIG_PIE_V1_BOOST
impl_func = dl_tie728_s8_<op>_11c; // S3 SIMD
#else
impl_func = c_impl_<op>; // C reference (always present)
#endif

The C reference implementation is the fallback and must always exist. SIMD implementations are added as a later optimization step.

3.3 Float32 Implementation Differences

Float32 kernels are fundamentally simpler than int8/int16 quantized kernels because there is no quantization overhead. Here are the key differences:

Aspectint8 / int16 (quantized)float32
Arithmetictool::truncate<int32_t>(result) — clamp to type rangeDirect arithmetic, no truncation
Scale/RescaleUses args->mul_shift, input_scale, output_rescaleIgnores these fields (exponent=0, scale=1.0)
SIMD dispatchISA-specific implementations (TIE728, ESP32-P4)C reference only — no SIMD needed
Template specializationGeneric template handles quantization mathExplicit template<> specialization for float

Two patterns for float implementation:

Pattern A — Base layer with float specialization (recommended for binary/complex ops): The base layer .cpp provides a template<> ... <float> specialization that does direct arithmetic. The module calls the same base::op(args) function for all types. This pattern keeps the module layer clean and uniform. See dl_base_add.cpp for example.

Pattern B — Module-level inline implementation (acceptable for simple unary ops): Some simple unary ops (like ReLU) implement float32 directly in the module's forward() method without calling the base layer. This avoids creating a base-layer float overload for trivial operations. The float path is a simple loop over elements.

cpp
// Pattern B example: float implemented directly in forward()
void forward(ModelContext *context, runtime_mode_t mode)
{
if (quant_type == QUANT_TYPE_SYMM_8BIT) {
forward_template<int8_t>(context, mode);
} else if (quant_type == QUANT_TYPE_SYMM_16BIT) {
forward_template<int16_t>(context, mode);
} else if (quant_type == QUANT_TYPE_FLOAT32) {
TensorBase *input = context->get_tensor(m_inputs_index[0]);
TensorBase *output = context->get_tensor(m_outputs_index[0]);
float *input_ptr = (float *)input->get_element_ptr();
float *output_ptr = (float *)output->get_element_ptr();
for (size_t i = 0; i < input->size; i++) {
output_ptr[i] = /* direct float operation on input_ptr[i] */;
}
}
}

Use Pattern A when the operation has multiple broadcast variants, multi-dimensional looping, or dual-core dispatch. Use Pattern B only for straightforward element-by-element operations with a single input.

See references/esp-dl-templates.md for complete float32 template examples.

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewNot runA model review is scheduled for the next rescan.

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
956
Repository forks
189
7-day trend score
34

Stars and forks are for the whole GitHub repository, not this skill alone. Refreshed 20 Mar 2026, 8 months ago.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/espressif/esp-dl/espdl-operator/badge)](https://verified-skill.com/skills/espressif/esp-dl/espdl-operator)

Something wrong with this skill or its page? Tell us.