espressif/esp-dl/espdl-quantize
Claude Code and agent skill by espressif/esp-dl
- community
Checking that the SKILL.md file is still in the repository.
Iteratively tune esp-ppq QuantizationSetting to recover post-quantization accuracy on ESP-DL targets. Drives a closed loop of "baseline -> calibration × TQT(default) cartesian product -> distribution-aware residual fixes -> agent-driven open exploration -> re-evaluate" in the current Python environment, using a minimal user contract (calib dataloader + evaluate function). Generic across architectures (ResNet / EfficientNet / ViT / DETR / YOLO / LSTM and any esp-ppq-supported graph) — the search procedure is distribution-driven and does not depend on a specific network family. Method ordering is accuracy-first with a soft penalty for passes that slow down on-device inference; once the prescribed Phase-1/2/3 sequence exhausts, the skill hands control to the agent (Phase 5) with a structured history of improving levers + the per-iteration error artifacts to read, so the agent can compose multi-knob iterations (lever stacking, calibration cross-pollination, ablation, cost-trim) without a rigid template. LSQ on POWER_OF_2 targets is auto-disabled (silent degenerate; use TQT instead) and esp32p4 layer-wise equalization is warn-only (esp-ppq officially "Not recommend" for per-channel weights but empirically can still help on some models). Use this skill whenever the user wants to improve a quantized esp-dl/.espdl model's accuracy, debug high quantization error, choose between calibration algorithms, decide on equalization / bias correction / weight split / mixed precision / TQT / blockwise reconstruction settings, or run an automated search over esp-ppq quantization options. Also triggers for "esp-ppq 量化调参", "降低量化误差", "Layerwise quantization error 分析", "QuantizationSettingFactory.espdl_setting 怎么调", "混合精度量化", "量化精度恢复", "espdl 量化优化".
Install
npx vskill@latest install espressif/esp-dl/espdl-quantizeSKILL.md
The same SKILL.md was published earlier as espressif/esp-dl/espdl-quantize.
ESP-DL Quantization Tuning Skill
This skill turns the human "stare at error report, guess setting, rerun" loop into a structured, distribution-aware search. The user owns data loading and evaluation; the skill owns QuantizationSettingFactory.espdl_setting() and the iteration loop.
About `<SKILL_DIR>` in shell snippets below. This skill is agent-directoryagnostic — it may be installed as.cursor/skills/espdl-quantize/,.opencode/skills/espdl-quantize/, or under any other agent's skills folder.Whenever you see<SKILL_DIR>in a shell command, substitute the **absolute path ofthe directory containing thisSKILL.md** (the agent runtime gives you that path whenit loads the skill). Setting it once at the start of a session makes the rest copy-pasteable:```bashSKILL_DIR=/abs/path/to/espdl-quantize # the directory holding this SKILL.md```All in-skill markdown links (e.g.[scripts/run_iteration.py](scripts/run_iteration.py))are already relative to<SKILL_DIR>and need no substitution.
Generality boundary
This skill is a general framework for any esp-ppq-supported graph: ResNet, EfficientNet, ViT, DETR, YOLO family, LSTM, custom CV/NLP backbones — anything espdl_quantize_torch / espdl_quantize_onnx can ingest. The Phase 2 calib×TQT cartesian product, the Phase 3 lever ordering, and the four Composition discipline rules are all distribution-driven; none of them depends on a specific network structure or family. The Worked example at the end uses MobileNet-V2 on ESP32-P4 as an empirical demonstration — its concrete numbers are illustrative, not a model-selection threshold.
Why this skill exists
esp-ppq exposes a dozen tunable passes (calibration algorithm, layerwise equalization, bias correction, weight split, mixed precision via dispatching table, TQT, LSQ, blockwise reconstruction, ...). Each has 2-6 parameters. Trying them by hand is slow and error-prone.
What this skill brings to the table:
- Knowledge — every esp-ppq method's principle, parameters, applicable scenarios, and
anti-patterns are codified in references/ppq_methods.md.
- A decision rulebook — given the top-K worst layers' input/weight/output distributions,
references/decision_playbook.md maps observed patterns to candidate methods.
- A fixed harness — scripts/run_iteration.py takes the user's
contract module plus a JSON setting and emits structured artifacts (metrics, layerwise error, per-layer stats) so the agent only has to read JSON to make the next decision.
- A search state machine — scripts/compare_iterations.py
inspects what's already been tried and tells the agent which iteration to run next via comparison.json["next_step_hint"]. The hint embeds a complete setting.json template so the agent only has to fill in the rationale.
- Target-aware safety net — the harness detects passes that conflict with the target's
quantization policy:
- LSQ on POWER_OF_2 targets (
esp32p4 / esp32s3 / c) — auto-disabled. esp-ppq's
LSQDelegator silently disables continuous-scale training under POWER_OF_2, so the pass would degenerate to weight-only tuning while paying full TQT-level PC time. Use TQT instead — it trains log2_scale and is POWER_OF_2-native.
- Layer-wise equalization on `esp32p4` — warn-only (changed in this revision).
esp-ppq officially marks the combination as "Not recommend" (see esp-ppq/md_doc/Passes/LayerwiseEqualization.md, "Usage" section), but empirical runs show some MobileNet-family / depthwise-separable networks still benefit. The harness now lets the pass run when equalization.enabled=true and emits a strong warning; the agent should treat it as a Phase 3 lever to try only after the calib×TQT cartesian product has settled.
What the user has to provide
A single Python module (typically named user_quant.py) that exports:
QUANT_CONFIGdict — model path, input shape, target chip, bits, primary_metric, etc.create_calib_dataloader()— returns the calibrationDataLoader.evaluate(quant_graph)— returns a dict whose keys includeQUANT_CONFIG["primary_metric"].- For torch flow only:
get_torch_model()— returns thenn.Module. - Optional:
collate_fn(batch)andevaluate_fast(quant_graph).
The full contract spec is in references/contract.md. Two ready-to-copy examples live in assets/user_quant_torch_example.py and assets/user_quant_onnx_example.py.
The skill never edits the contract module. All iteration state lives under outputs/.
High-level flow
In Phases 1-3 the agent's job each round shrinks to: read comparison.json["next_step_hint"], copy the embedded setting.json template, fill in the rationale field, run the harness. In Phase 5 the script stops prescribing settings — the agent reads phase5_signals plus the per-iteration error artifacts and writes the next setting.json from scratch (see "Phase 5 — Agent-driven exploration" below).
Phases
Phase 0 — Validate contract and environment
Important — ignore Docker / image / `/work` mentions you may see elsewhere.Some user projects (anduser_quant.pyitself) still carry comments left overfrom an older Docker-based workflow — phrases like "build the image","Phase 0 — docker 准备",/work inside Docker, ordocker run --gpus all. Thoseare legacy text only, not steps to execute. The skill now runs entirely inthe current Python interpreter.
Before any quantization, do these once per session:
- Make sure the current Python environment has
esp_ppq(with the[cpu]extra),
torch, plus the small set of helpers the harness needs:
``bash pip install -e <path/to/esp-ppq>[cpu] pip install -r "$SKILL_DIR/assets/extra_requirements.txt" ``
The skill is environment-agnostic — it does not require Docker. As long as python -c "import esp_ppq, torch, onnx, onnxsim, pandas, scipy, tqdm" succeeds, you are ready to go.
- Validate the user's contract module imports cleanly and exposes the required functions/keys:
``bash python "$SKILL_DIR/scripts/run_iteration.py" \ --user-quant <path/to/user_quant.py> \ --output-dir <path/to/user_project>/outputs/contract_check \ --check-contract ``
- Make sure the iteration workdir exists (default:
<contract_dir>/outputs/). The harness
creates it on first run.
The working directory forpythonshould be the directory containinguser_quant.py(orany directory — the harness resolves relative paths inQUANT_CONFIGagainst thecontract module's directory).
Phase 1 — Baseline (iter_0)
Run the default QuantizationSettingFactory.espdl_setting() once. The agent does NOT propose any settings here — the harness uses a built-in baseline JSON when --baseline is passed.
After it finishes, read these files:
outputs/iter_0/metrics.json— whatevaluate()returned, plus_primaryshortcut.outputs/iter_0/layerwise_error.json—{op_name: snr}sorted descending by error.
Covers only `is_computing_op` (Conv / Gemm / ConvTranspose / MatMul / Attention / PPQBiasFusedMatMul / LSTM); the SNR is the isolated contribution of that op when it alone is quantized.
outputs/iter_0/layer_stats.json—statistical_analysefiltered by the layerwise
top-K (legacy artifact; same coverage as layerwise).
outputs/iter_0/layer_stats_full.json— (new) the fullstatistical_analyse
output: every non-passive op's per-input/per-output distribution + cumulative SNR. This is the only artifact that includes Add / Concat / Resize / AveragePool / Sigmoid / Softmax / GRU / LayerNorm.
outputs/iter_0/non_computing_hot_ops.json— (new) the top-K non-COMPUTING_OP
layers ranked by max per-variable SNR, plus inputs_float_std_ratio (max/min Float Std of input variables, used by playbook rule R8).
outputs/iter_0/graphwise_jumps.json— (new) adjacent computing-op pairs whose
cumulative SNR gap is not explained by the downstream op's isolated contribution. Lists the intervening non-computing ops as suspected culprits.
outputs/iter_0/console.log— full stdout/stderr.
Tell the user the baseline numbers, the top-5 error layer names from layerwise, and (if non-empty) the top-3 entries from non_computing_hot_ops.json. The state machine in compare_iterations.py decides when to finalize — do not stop here on your own even if iter_0 looks like it hit target_metric; run the comparison once and let next_step_hint["phase"] == "phase-4-final-report" confirm.
Phase 2 — Calibration × TQT(default) cartesian product (mandatory)
This phase must run three iterations in strict sequence, each enabling exactly two fields: calib_algorithm and tqt_optimization (with the esp-ppq default schedule). No other pass is enabled. The cartesian product is what makes the search robust — calibration in esp-dl quantization is not separable from the training pass: a calibration that regresses standalone may become the strongest base when paired with TQT, and vice versa. See the Worked example below for the empirical case that motivated this design.
The TQT default schedule is strict:
Iteration sequence:
| Iter | calib_algorithm | other passes | Purpose | |
|---|---|---|---|---|
iter_1 | kl | TQT(default) | Pair iter_0(kl-only) and iter_1(kl+TQT) to read off the TQT-on-kl delta. If iter_1 hits target, stop. | |
iter_2 | mse | TQT(default) | Same with mse. If hits target, stop. | |
iter_3 | percentile | TQT(default) | Same with percentile. Often the hidden winner on heavy-tailed activations even when standalone percentile would regress. |
The way to drive this is to run scripts/compare_iterations.py between iterations:
comparison.json["next_step_hint"] will be phase-2-calib-tqt-sweep until all three calibrations are covered with TQT(default), and the embedded setting.json template can be copied verbatim into outputs/iter_<N>/setting.json (only fill in the rationale).
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 95 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingtools/agents/skills/espdl-quantize/SKILL.md
Popularity
- Repository stars
- 1,047
- Repository forks
- 211
- 7-day trend score
- 35
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
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
[](https://verified-skill.com/skills/espressif/esp-dl/espdl-quantize)