How to Strip Unused Operators and Kernels at Compile Time

[中文]

By default, ESP-DL registers all operator modules and links all operator kernels for the target chip. When compile-time operator and kernel stripping (CONFIG_ESPDL_COMPILE_STRIP) is enabled, the build system inspects the models or requirement manifests declared by the project during CMake configuration, generates only the required operator registration entries and kernel selection table rows, and lets the linker discard unreferenced module implementations and assembly symbols via --gc-sections — significantly reducing firmware Flash footprint.

Note

The compile-time stripping specification is currently at the 0.1 preview stage:

  • Module-level stripping (dl_module_includes.inc / dl_module_register.inc) covers all operator modules.

  • Fine-grained kernel-level stripping (table-driven dl_conv_select.inc and future select tables) currently covers Conv / Gemm / MatMul (the conv base layer). Support will gradually expand to additional operators.

How It Works

Compile-time stripping uses a two-phase declarative pipeline:

  1. Declaration phase (each component’s CMakeLists.txt ): Any application or model component includes cmake/strip.cmake after idf_component_register() and calls esp_dl_strip_add(...) to register unencrypted .espdl models and/or .req.yml requirement manifests (for offline-resolved models, encrypted models, or handwritten module/base requirements); file types are detected automatically by extension.

  2. Resolution & finalization phase (automatically run at the end of configuration via esp_dl_strip_finalize ): Once every component’s CMakeLists.txt has finished executing, the build system automatically invokes:

    • esp-dl/spec/resolve.py: resolves all declared .espdl models into canonical .req.yml files.

    • esp-dl/spec/merge.py (invoked by esp-dl/spec/generate.py): strictly validates and computes the union across all .req.yml inputs.

    • esp-dl/spec/generate.py: generates the following artifacts under the esp-dl build directory (typically build/esp-idf/esp-dl/ or build/esp-idf/espressif__esp-dl/):

      • dl_compile_req.yml: the final effective merged requirement manifest for this build (useful for auditing and troubleshooting).

      • dl_module_includes.inc and dl_module_register.inc: header includes and deserialization registrations for only the required operators.

      • dl_conv_select.inc: lookup table rows for only the required convolution kernels.

    During linking, unreferenced C++ operators and assembly kernels in their per-symbol sections are automatically garbage-collected by the linker.

Note

When CONFIG_ESPDL_COMPILE_STRIP=n (the default), the build system generates the full module registry and full kernel selection tables. Any esp_dl_strip_add() declarations in CMakeLists.txt have no stripping effect (declared file paths and extensions are still validated at configure time), making it easy to toggle between full and stripped builds without editing CMake files.

Quick Start (Automatic Stripping from .espdl Models)

For most projects loading unencrypted .espdl models directly, automatic stripping takes only three steps.

  1. Enable compile-time stripping in Kconfig

    Run idf.py menuconfig and enable:

    Component config --->
        ESP-DL --->
            [*] Enable compile-time operator and kernel stripping
    

    Or add the option directly to your project’s sdkconfig.defaults:

    CONFIG_ESPDL_COMPILE_STRIP=y
    
  2. Declare model dependencies in your component’s CMakeLists.txt

    Include cmake/strip.cmake after idf_component_register() and call esp_dl_strip_add(...) (accepts one or more .espdl / .req.yml files in a single call):

    idf_component_register(
        SRCS "app_main.cpp"
        INCLUDE_DIRS "."
    )
    
    # Works with both ESP Component Registry (espressif__esp-dl) and local component (esp-dl)
    idf_build_get_property(build_components BUILD_COMPONENTS)
    if("espressif__esp-dl" IN_LIST build_components)
        idf_component_get_property(espdl_dir espressif__esp-dl COMPONENT_DIR)
    elseif("esp-dl" IN_LIST build_components)
        idf_component_get_property(espdl_dir esp-dl COMPONENT_DIR)
    endif()
    
    include(${espdl_dir}/cmake/strip.cmake)
    esp_dl_strip_add("${CMAKE_CURRENT_LIST_DIR}/models/mobilenet_v2.espdl")
    

    If your project contains multiple models (even across multiple components), call esp_dl_strip_add(...) in each component’s CMakeLists.txt; the build system automatically computes the union of all declarations.

    Note

    Every declared .espdl (and .req.yml) must match the active build target IDF_TARGET. When a .espdl model carries target metadata that does not match IDF_TARGET (or a .req.yml omits IDF_TARGET), spec/resolve.py or spec/generate.py aborts configure with a target mismatch error; legacy .espdl models without embedded target metadata emit a configure-time WARNING and skip the compatibility check. When a project ships per-chip models, guard registrations by IDF_TARGET in CMakeLists.txt:

    idf_build_get_property(target IDF_TARGET)
    if(target STREQUAL "esp32p4" OR target STREQUAL "esp32s31")
        esp_dl_strip_add("${CMAKE_CURRENT_LIST_DIR}/models/model_p4.espdl")
    elseif(target STREQUAL "esp32s3")
        esp_dl_strip_add("${CMAKE_CURRENT_LIST_DIR}/models/model_s3.espdl")
    else()
        esp_dl_strip_add("${CMAKE_CURRENT_LIST_DIR}/models/model_c.espdl")
    endif()
    
  3. Build and verify the stripped result

    Run the standard ESP-IDF build commands:

    idf.py set-target esp32p4
    idf.py build
    

    After building, inspect the results:

    • build/esp-idf/esp-dl/dl_compile_req.yml (or build/esp-idf/espressif__esp-dl/dl_compile_req.yml) to review the effective operator and kernel set.

    • Run idf.py size or idf.py size-components to compare Flash usage before and after enabling stripping.

Advanced Usage

When your project uses encrypted models, loads models from external storage, or needs to manually declare C++ modules (modules) or base-layer kernels (bases), declare a .req.yml file and register it in CMakeLists.txt via esp_dl_strip_add(...). .espdl and .req.yml files can be freely mixed in the same project or even the same esp_dl_strip_add(...) call and are merged automatically.

Generating .req.yml Offline with spec/resolve.py

Offline resolution into .req.yml is recommended in the following scenarios:

  • The .espdl model is encrypted with AES-128 (so plaintext keys do not need to be passed into CMake).

  • The model lives in external storage (such as an SD card, standalone flash partition, or OTA payload) rather than in the source repository.

  • You want the model’s operator/kernel requirements tracked as a human-readable file in version control for code review.

esp-dl/spec/resolve.py resolves .espdl models into canonical .req.yml files:

# 1. Auto-detect supported target chips from unencrypted .espdl model(s)
python3 esp-dl/spec/resolve.py \
    --espdl model_a.espdl model_b.espdl \
    -o my_models.req.yml

# 2. Resolve an AES-128 encrypted .espdl (--key accepts a .key file, 32-char hex, or "0x01, 0x02, ...")
python3 esp-dl/spec/resolve.py \
    --espdl encrypted_model.espdl \
    --key path/to/aes.key \
    -o encrypted_model.req.yml

# 3. Restrict output to specific target chip(s) (comma-separated)
python3 esp-dl/spec/resolve.py \
    --espdl model_a.espdl \
    --target esp32p4,esp32s31 \
    -o p4_model.req.yml

Then register the generated .req.yml in CMakeLists.txt:

include(${espdl_dir}/cmake/strip.cmake)
esp_dl_strip_add("${CMAKE_CURRENT_LIST_DIR}/my_models.req.yml")

Merging Multiple .req.yml Files Offline with spec/merge.py

When multiple encrypted models use different AES keys and are resolved separately, or when you want to combine model manifests with handwritten operator manifests into a single distributable file, use esp-dl/spec/merge.py:

# 1. Merge multiple .req.yml files (defaults to the intersection of supported targets, grouped by ISA)
python3 esp-dl/spec/merge.py \
    model_a.req.yml model_b.req.yml custom_ops.req.yml \
    -o merged.req.yml

# 2. Filter and merge for specific target chip(s)
python3 esp-dl/spec/merge.py \
    model_a.req.yml custom_ops.req.yml \
    --target esp32p4 \
    -o merged_p4.req.yml

Handwriting .req.yml for Direct C++ Module or Base Calls

If your code constructs C++ modules directly (for example dl::module::Conv, dl::module::Softmax) or invokes base-layer APIs directly (for example dl::base::Conv) without a corresponding .espdl file, write a .req.yml manifest and include it via esp_dl_strip_add(...):

spec_version: "0.1"
targets:
  esp32p4, esp32s31:
    modules:
      # Omitting kernels keeps all legal kernels (Relu has no table-driven kernels)
      Relu:
        register: true
      # Register Conv and keep all legal Conv kernels
      Conv:
        register: true
        kernels: all
      # Keep only a specific 1x1 kernel without registering Gemm in ModuleCreator
      Gemm:
        register: false
        kernels:
          - dl_esp32p4_s8_conv_1x1
    bases:
      # Keep a specific conv base kernel without registering any Module
      conv:
        - dl_esp32p4_s16_conv_3x3

If you simply want all legal kernels and module registration enabled, a compact list shorthand is also supported:

spec_version: "0.1"
targets:
  esp32s3:
    modules:
      - Conv
      - Relu
      - Reshape
    bases:
      conv: all

.req.yml Format Reference

Canonical Example

Canonical .req.yml files emitted by spec/resolve.py and spec/merge.py group chips by ISA compile group (for example, esp32p4 and esp32s31 share identical kernel rules and assembly symbols):

spec_version: "0.1"
targets:
  esp32p4, esp32s31:
    modules:
      Conv:
        register: true
        kernels:
          - dl_esp32p4_s8_conv_1x1_bias_relu
          - dl_esp32p4_s8_dwconv_3x3_pad_bias_relu
      MatMul:
        register: true
        kernels: []
      Relu:
        register: true
        kernels: []
    bases:
      conv:
        - dl_esp32p4_s16_conv_1x1

The 5 Physical ISA Compile Groups

ESP-DL partitions all 9 supported chips into 5 physical ISA compile groups. Chips within the same compile group share identical ISA extensions, kernel sources, kernel symbol names, and kernel selection rules, so they can be combined under a single comma-separated key in targets to share one manifest:

Compile Group (targets key)

Architecture / ISA

Kernel Symbol Prefixes

Matching esp-ppq Export Target

esp32

Xtensa LX6 + MAC16

dl_xtensa_mac16_* + dl_xtensa_* + dl_c_*

c

esp32s2

Xtensa LX7 (no MAC16)

dl_xtensa_* + dl_c_*

c

esp32c2, esp32c3, esp32c5, esp32c6

RISC-V scalar (no PIE)

dl_riscv_* + dl_c_*

c

esp32s3

Xtensa PIE V1 (TIE728)

dl_tie728_* + dl_c_*

esp32s3

esp32p4, esp32s31

RISC-V PIE V2

dl_esp32p4_* + dl_c_*

esp32p4 / esp32s31

Note

  • Why are there 3 model export groups in esp-ppq but 5 compile groups in ESP-DL? When esp-ppq exports a .espdl model, the model binary depends only on rounding mode and weight layout, so all non-PIE chips share the same target="c" model. At ESP-DL compile and link time, however, esp32 (Xtensa + MAC16), esp32s2 (Xtensa without MAC16), and RISC-V scalar chips (esp32c2 / esp32c3 / esp32c5 / esp32c6) have distinct ISA capabilities and scalar kernels. Consequently, running spec/resolve.py on a target="c" model emits separate sections for these 3 scalar compile groups, keeping manifests forward-compatible as ISA-specific kernels evolve.

  • Grouping guideline when handwriting .req.yml: The Kernel Symbol Prefixes column lists the ISA-level symbol families belonging to each compile group; each individual operator only registers the subset it implements (for example, conv currently uses dl_xtensa_mac16_* + dl_c_* on esp32, dl_tie728_* on esp32s3, and dl_esp32p4_* on esp32p4 / esp32s31). Prefer generating manifests via spec/resolve.py so every symbol is guaranteed valid for the target. If an entry lists explicit kernel symbol names (such as dl_esp32p4_* or dl_xtensa_mac16_*), only combine chips belonging to the same compile group under that key and define separate keys for different groups. If an entry only declares modules with kernels: all (or omits kernels), you may freely list chips across multiple groups under one comma-separated key — each chip automatically expands to its own legal kernel set during configuration.

Field Semantics and Validation Rules

spec/merge.py (and spec/generate.py during build configuration) enforce the following strict validation rules:

Field / Syntax

Semantics & Validation Rules

spec_version

Required. For example "0.1". Validates compatibility between the manifest and the current ESP-DL toolchain specification: during the 0.x preview stage, both major and minor versions must match; from 1.x onward, major version must match and manifest minor version must not exceed the toolchain version.

targets

Explicit chip target mapping. Keys must be concrete chip names or comma-separated chip lists (e.g., esp32p4, esp32s31); wildcard all is not allowed. See The 5 Physical ISA Compile Groups above for exact grouping details.

modules.<Op>.register

Boolean (true / false); defaults to true when omitted. When merging multiple .req.yml files, values combine with logical OR (if any source requests registration, the module is registered). Non-boolean values (such as the string "false") raise an error.

modules.<Op>.kernels

  • Omitted / all / null: expands to all legal kernels for this module on the target chip.

  • Explicit empty list []: requests 0 table-driven kernels (for example, modules without kernel selection tables such as Relu, or S8/S16 MatMul using the native_kn native path).

  • List of kernel names: keeps only the listed kernels; misspelled or unsupported kernel names for the target chip fail immediately at configure time.

Unknown key check

Module entries accept only register and kernels. Any typo or unrecognized key causes configuration to fail immediately, preventing silent fallback to the full table.

bases.<base>

Directly appends kernels to a table-driven base layer (currently conv) without registering any Module. Accepts all, null, [], or an explicit kernel list.

CMake API Reference

The registration API is defined in ${espdl_dir}/cmake/strip.cmake and must be called after idf_component_register():

CMake Function

Description

esp_dl_strip_add(<f1> [f2 ...])

Registers one or more unencrypted .espdl models and/or .req.yml (.yaml) manifests; automatically dispatches by file extension and merges all declarations at configure time.

Troubleshooting & FAQ

  1. Configure error after enabling CONFIG_ESPDL_COMPILE_STRIP=y: no esp_dl_strip_add() declarations were registered

    • Cause: Stripping is enabled, but no component in the project called esp_dl_strip_add().

    • Fix: Include cmake/strip.cmake in your application or model component’s CMakeLists.txt and call esp_dl_strip_add(...). If you do not need stripping, set CONFIG_ESPDL_COMPILE_STRIP=n.

  2. Runtime error: Do not support <Op>, please implement and register it first.

    • Cause: Model deserialization encountered an operator not registered in the generated dl_module_register.inc.

    • Fix: Inspect build/esp-idf/<esp-dl>/dl_compile_req.yml to check whether a .espdl model was omitted or whether a handwritten .req.yml set register: false for that operator.

  3. Runtime error: no Conv kernel for packed key 0x....

    • Cause: Executing Conv / Gemm / MatMul requested a kernel key not present in the generated dl_conv_select.inc.

    • Fix:

      • If you invoke dl::base::Conv or handwritten C++ dl::module::Conv directly (without a corresponding .espdl), add the required bases.conv or modules.Conv entries to a .req.yml file and register it with esp_dl_strip_add(...).

      • If a model was replaced or re-quantized, re-run idf.py build (CMake automatically reconfigures when a declared .espdl changes; if you use an offline .req.yml, re-run spec/resolve.py and, if applicable, spec/merge.py).

  4. Is it an error if MatMul or other operators show kernels: [] in the generated .req.yml ?

    • No. kernels: [] is expected in two cases:

      • The operator has no table-driven kernel selection table (e.g., Relu, Softmax, Reshape).

      • An S8/S16 MatMul node uses the input1_layout=native_kn native path instead of the quantized Conv 1x1 lookup table, so no Conv kernels need to be pulled in.

  5. Warning when resolving legacy .espdl files: WARNING: ... model has no 'targets'/'target' metadata

    • Older .espdl exports may not contain target metadata. This warning only skips static target-compatibility validation and does not affect operator/kernel extraction. Re-export the model with a newer esp-ppq version, or pass --target explicitly when invoking spec/resolve.py offline.