Skip to content

[Espressif] Lower Fused Quant activations with lookup tables - #25160

Open
rascani wants to merge 3 commits into
mainfrom
codex/espressif-fused-quant-lut
Open

rascani wants to merge 3 commits into
mainfrom
codex/espressif-fused-quant-lut

Conversation

@rascani

@rascani rascani commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Lower sigmoid, tanh, GELU, SiLU, HardSwish, HardSigmoid, ReLU and HardTanh, including ReLU6, to a shared quantized_lut_int8 operator. ESP-NN's logistic evaluation is a generic lookup, so these activations can run directly on int8 tensors.

Export evaluates the FQ operator over all 256 input codes, preserving per-tensor qparams, activation parameters and rounding. Each table is a 256-byte constant Tensor with no scratch allocation or runtime preparation. LowerToEsp accepts static contiguous int8 inputs, and the wrapper checks capacities and the vendor element-count bound.

Unsupported activations use shared Fused Quant decomposition and its core ATen fallbacks. This PR introduces no backend-specific activation decomposition pass; scalar normalization, Edge replacement and constant handling are supplied by the shared-pipeline layer.

Validation: 75 LUT and linear host cases passed at this layer, including exhaustive input-code comparisons, dynamic and partially quantized fallback, mixed convolution/scratch graphs and serialized LUT-call counts. The wrapper retains its existing optimized-S3 table-capacity rejection coverage.

Authored with OpenAI Codex.

@pytorch-bot

pytorch-bot Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/25160

Note: Links to docs will display an error until the docs builds have been completed.

✅ No Failures

As of commit 7263efb with merge base e17e1a9 (image):
💚 Looks good so far! There are no failures yet. 💚

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Nov 17, 2026
@rascani
rascani added this pull request to stack #25158 November 17, 2026 05:13
@rascani

rascani commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

@claude review effort=max

@claude

claude Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Claude finished @rascani's task in 26m 8s —— View job


Request changes: when _lower_lut declines SiLU, HardSwish or HardSigmoid (for example with a dynamic batch dim), they now fall back to ATen ops that have no ExecuTorch kernel, so programs that ran before this PR export cleanly but fail at Method load; the other findings are test-precision and cleanup items.

Detailed review

PR Review: #25160

Summary

The PR lowers eight Fused Quant activations to one esp_nn::quantized_lut_int8 op. That op applies a 256-entry int8 table built at export by running the FQ reference on every input code.

One regression blocks approval: SiLU, HardSwish and HardSigmoid lose their portable fallback. The other findings cover test precision, assertions that can pass without testing anything, and small cleanups.

Scope of this review:

  • A three-reviewer panel covered all 11 changed files, and I re-checked every finding below against the code.
  • The ESP-NN 1.5.0 sources are not in the repo, so I could not check esp_nn_logistic_s8's table indexing, alignment or tail handling.
  • Running Python and pytest needed approval that this job didn't have, so everything here comes from reading the code. Nothing was run.

Backward Compatibility

  • SiLU, HardSwish and HardSigmoid no longer have a portable fallback (backends/espressif/quantizer/esp_fused_quantizer.py:118-132).
    • Why export keeps them whole: The three new OpQuantizers add aten.silu, aten.hardswish and aten.hardsigmoid to preserved_ops() (frontends/fused_quant/quantizer/quantizer.py:218-219). get_esp_fused_quant_recipe passes that list to both preserve_ops and _core_aten_ops_exception_list (lowering.py:151,158). So export no longer decomposes these ops into sigmoid/mul/clamp.
    • What a rejected node becomes: When _lower_lut returns False (fused_quant_to_esp_pass.py:183-193), DecomposeFusedQuant._get_aten_target (decompose_fused_quant.py:208-238) rewrites the node to exir_ops.edge.aten.silu.default, hardswish.default or hardsigmoid.default. No pass in EspPassManager decomposes these afterwards (esp_pass_manager.py:41-49).
    • No kernel exists for them: No kernel YAML under kernels/ registers silu.out, hardswish.out or hardsigmoid.out. Of these activations, kernels/portable/functions.yaml has only gelu, hardtanh and sigmoid. get_core_aten_quantizers covers only core ATen ops, so that "whatever is left unclaimed decomposes to the portable kernels" (quantizer.py:432-436). These three ops are not core ATen.
    • When it triggers: any _lower_lut rejection under the default allow_cpu_fallback=True:
      • a dynamic batch dim, which test_dynamic_shapes_stay_portable (test_quantization_params.py:330-339) already treats as a supported stays-portable case for add/mul;
      • channels-last example inputs;
      • zero-element tensors.
    • Effect: Before this PR, these ops decomposed into ops that have portable kernels, so such programs ran. Now export succeeds, but Method load fails with a missing aten::hardswish.out or aten::silu.out.
    • Stale claims: For these three ops this contradicts both the PR description ("unsupported configurations retain portable execution") and the docstring at esp_fused_quantizer.py:108-109 ("decomposes the rest for portable execution").
    • Fix: The file already has a pattern for ops without a portable fallback: _lower_linear raises RuntimeError ("Portable linear fallback is not available yet.", fused_quant_to_esp_pass.py:603-610), and lowering.py:134 documents it.
      • Either raise the same way for these three ops, or decompose them to core ATen after DecomposeFusedQuant.
      • Adding a node_filter to the three quantizers would not be enough: preserved_ops() keeps the ATen op whole whether or not the node is annotated.
      • Add a rejection test for each op, for example with a dynamic batch dim.
    • Fix this →

Testing

  • _lower_lut's rejection checks are untested (fused_quant_to_esp_pass.py:183-193).
    • The dynamic-shape, non-contiguous, empty-tensor and _qparams checks have no LUT tests. test_quantization_params.py:309-339 already has a parametrized pattern for this for the binary ops.
    • The only fallback test, test_sigmoid_unsupported_qparams_stay_portable (test_lut.py:228-253), has three gaps:
      • it only reaches the dtype check (float input or float output);
      • it uses sigmoid, which has a portable kernel, so it could not catch the issue above;
      • it never checks that an FQ sigmoid existed before run_passes(). If the quantizer stopped fusing, the post-pass {_SIGMOID: 1} count and the assert_close would still pass without _lower_lut running at all.
    • Fix this →
  • The undersized-table emulator test can't tell which failure it caught (test_lut.py:174-199).
    • Log match is not specific: ET_KERNEL_CHECK logs the whole stringified condition (runtime/core/exec_aten/util/tensor_util.h:377). op_quantized_lut.cpp:30-36 puts every check into one condition, so "table.nbytes()" in log is true whichever clause failed. By contrast, op_quantized_add.cpp:40-51 and op_quantized_mul.cpp:36-49 keep the element-count bound separate from the capacity checks.
    • Wrong failures also pass: pytest.raises(AssertionError) also catches a build failure (tester.py:243).
    • The log can be stale: The firmware dir is reused per worker, target and mode, and emulator.log is only rewritten when the emulator runs. After a build failure, line 199 can read a log left by an earlier run.
    • The path is hard-coded: Line 196 hard-codes esp32s3-optimized and the "main" worker default, copying tester.py:175-179.
    • Fix:
      • Give the table its own ET_KERNEL_CHECK. Because the schema's Tensor table is untyped, that check can also require ScalarType::Char and numel() == 256.
      • Assert on that check's text.
      • Build the path from tester.target.value and tester.kernel_mode.value, and delete emulator.log before the run.
    • Fix this →
  • The serialized-table checks can pass without checking anything (test_lut.py:152-162). The dtype, data_buffer_idx and allocation_info assertions only run for KernelCalls named esp_nn::quantized_lut_int8, and nothing asserts that any call matched. Compare the match count against ops_after_transforms[_ESP_LUT].
  • Only one ESP-NN build is exercised (test_lut.py:166). test_implementation_lut runs only the default S3 optimized build. The tester already supports ANSI emulator runs (test_conv2d.py:336-340). One ANSI case would check the uint8-cast indexing that _lower_lut assumes (fused_quant_to_esp_pass.py:195) against ESP-NN's other logistic implementation.

Code Quality

  • The static-int8 check is duplicated. _lower_lut's check at fused_quant_to_esp_pass.py:183-190 is a verbatim copy of the one in _binary_kernel_args (:97-104). Close variants sit at :218-226, :366-373 and :495-499. A shared predicate would remove this new copy and most of the old ones. Fix this →

Performance

  • Follow-up, not blocking: ReLU/ReLU6/HardTanh after add or linear now run as a separate LUT kernel. That costs one extra pass over the tensor and one extra activation buffer, and test_add.py:75-82 and test_linear.py:62-68 now lock it in.
    • The ESP-NN add, mul and FC calls already accept an activation clamp. The wrappers currently pass the full int8 range (op_quantized_add.cpp:67-68, op_quantized_linear.cpp:74-75).
    • Folding the clamp into the producer is exact only when the activation's input and output qparams are equal. It would therefore also need the quantizer to share them, as _AvgPoolQuantizer does (esp_fused_quantizer.py:95-98).

Specific Comments

  • backends/espressif/README.md:35: "It also accelerates values-only 4-D int8 MaxPool2d" now follows the quantized_lut_int8 sentence, so "It" reads as the LUT op. Use "The operator library also accelerates…".
  • backends/espressif/passes/fused_quant_to_esp_pass.py:195: the comment describes ESP-NN internals. Name the pinned version (1.5.0), so whoever bumps ESP-NN knows to recheck the table layout.
  • backends/espressif/passes/fused_quant_to_esp_pass.py:196: torch.arange(256, dtype=torch.uint8).view(torch.int8) states the uint8 reinterpretation directly instead of relying on int32→int8 wraparound.
  • backends/espressif/ops/operators.py:92: the fake kernel takes its dtype from input, but the reference (:97) returns table's dtype. table.new_empty(input.shape) would match it.
  • backends/espressif/test/ops/test_lut.py:73: EspSigmoidTwoScales subclasses EspSigmoidChain only to reuse its op counts, but two independent sigmoids are not a chain.
  • backends/espressif/test/ops/test_lut.py:203-220: test_lut_covers_all_input_codes repeats the full quantize/export/pass pipeline and the exact comparison that test_dialect_lut already runs for the same 10 cases. Its coverage assertion could move into test_dialect_lut for activation_cases.

Recommendation

Request Changes

The SiLU/HardSwish/HardSigmoid fallback silently produces programs that can't load, for inputs such as a dynamic batch dim that worked before this PR. That breaks the documented portable-fallback contract. The fix is small: raise like _lower_linear does, or decompose to core ATen. Everything else is non-blocking.


  • Load /pr-review skill and gather context
  • Independent three-reviewer panel over all 11 files
  • Consolidate, then fact-check each finding against the code (two reviewer findings dropped as invalid)
  • Run tests: not done, because Python/pytest execution needed approval this job didn't have

@rascani
rascani force-pushed the codex/espressif-fused-quant-lut branch from d6c427c to e4ad26d Compare November 17, 2026 18:09
@github-actions

Copy link
Copy Markdown

This PR needs a release notes: label

If your change should be included in the release notes (i.e. would users of this library care about this change?), please use a label starting with release notes:. This helps us keep track and include your important work in the next release notes.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "release notes: none"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

@rascani

rascani commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

Please review the current revision (e4ad26d5143cc7354c87beca0bcff3217258313f) against this PR's base branch, codex/espressif-fused-quant-depthwise. This PR is part of stack #25158. Re-check any previous findings against the updated code and focus on actionable correctness, quantization/numerical, memory-safety, and test-coverage issues.

@claude

claude Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Claude finished @rascani's task in 39m 7s —— View job


Claude finished @rascani's task ——

The previous fallback blocker is fixed, but HardSwish/HardSigmoid fallbacks now leave unlifted ScalarToTensorPass constants that break serialization of the transformed edge program, so I'm requesting changes; the other findings are minor.

Detailed review of e4ad26d against codex/espressif-fused-quant-depthwise

Summary

This PR lowers static int8 Fused Quant sigmoid, tanh, GELU, SiLU, HardSwish, HardSigmoid, ReLU and HardTanh to a new esp_nn::quantized_lut_int8 op, using a 256-byte table computed at export time. When no LUT applies, it decomposes SiLU, HardSwish and HardSigmoid to portable kernels. One confirmed regression blocks approval: when HardSwish or HardSigmoid fall back, the transformed edge program keeps unlifted tensor constants and can no longer be serialized (see Backward Compatibility). The other findings are minor.

Re-check of the previous review:

  • Fixed: the SiLU/HardSwish/HardSigmoid fallback blocker, the undersized-table emulator test, the serialized-table check that could pass vacuously, and the README wording.
  • Still open, under Testing: coverage of the rejection checks (now partially covered) and the single ESP-NN build being exercised.
  • Still open, non-blocking, not re-raised:
    • the static-int8 check duplicated between lower_to_esp.py:97-104 and :188-195;
    • the ReLU-after-add/linear performance follow-up;
    • the optional dtype hardening for the table in op_quantized_lut.cpp.

I did not run pytest (Python execution needs approval in this job) or the emulator tests. The ESP-NN 1.5.0 sources are fetched at build time and were not in the checkout.

Code Quality

  • The eager quantized_lut_int8 returns a view of table for 0-dim inputs (minor, confirmed by reading the code).

    • Indexing with a 0-dim integer tensor is a select, so table[input.to(torch.int64) & 255] (backends/espressif/ops/operators.py:97) returns a view that aliases the table constant.
    • The op's schema does not allow its output to alias an input.
    • The scalar case (backends/espressif/test/ops/test_lut.py:132) takes this path.
    • Fix: use torch.take(table, input.to(torch.int64) & 255), which always returns a new tensor.

    Fix this →

Testing

  • The uint8 table order is only checked on one ESP-NN build (minor, still open from the previous review).

    • _lower_lut stores the table in uint8-cast order (backends/espressif/passes/lower_to_esp.py:200-201).
    • The only test that would catch a mismatch with esp_nn_logistic_s8 is test_implementation_lut. It runs only when ESPRESSIF_BUILD_DIR is set, and only on the default ESP32-S3 OPTIMIZED build (backends/espressif/test/tester.py:109-110). The PR description doesn't say it was run.
    • I couldn't confirm that the ANSI and RISC-V variants of esp_nn_logistic_s8 index the table the same way. If one doesn't, every lookup on that build reads the entry 128 positions away.
    • Please confirm the emulator run passes, and add an ANSI case following backends/espressif/test/ops/test_conv2d.py:380.

    Fix this →

  • No test reaches the qparams rejection in _lower_lut (minor, partially fixed from the previous review).

    • Every fallback test is rejected earlier, by the dtype/static-shape check at backends/espressif/passes/lower_to_esp.py:188-196:
      • both test_sigmoid_unsupported_qparams_stay_portable cases make one edge float;
      • the other fallback tests use a dynamic batch or a float edge.
    • So :197-198 never returns False in the tests, and the test name claims coverage it doesn't have.
    • Fix: add a case with int8 edges whose qparams _qparams rejects (for example narrow-range or per-channel), and rename the float-edge test.

    Fix this →

API Design

  • Narrow-range int8 qparams silently skip the LUT (minor, confirmed by reading the code).

    • _lower_lut goes through _qparams (backends/espressif/passes/lower_to_esp.py:197). _qparams returns None unless (quant_min, quant_max) == (-128, 127) (:157-158).
    • _qparams is shared with the binary kernels. For LUT ops the check is unnecessary: the table is built by running the FQ op on all 256 codes (:201-206), so it already applies the clamp the output qparams specify.
    • backends/espressif/README.md:30-32 promises LUT support for "constant per-tensor input and output qparams" and states no range condition.
    • Consequences:
      • a custom quantizer with, say, quant_min=-127 falls back to portable kernels without notice;
      • get_esp_fused_quant_recipe(allow_cpu_fallback=False) rejects a configuration the README documents as supported.
    • Fix: drop the full-range requirement for LUT ops, or document it in the README.

    Fix this →

Backward Compatibility

  • HardSwish/HardSigmoid fallbacks leave the transformed edge program unserializable (major, confirmed by reading the code).

    • Cause:
      • DecomposeActivations emits aten.add.Tensor(x, 3) and aten.div.Tensor(y, 6) with Python scalars.
      • ScalarToTensorPass (backends/espressif/passes/esp_pass_manager.py:52) turns those scalars into get_attr tensor constants.
      • to_edge and to_edge_transform_and_lower lift such constants right after this pass (exir/program/_program.py:881-882, :1406-1409).
      • The ESP recipe instead runs EspPassManager in the EDGE_PROGRAM_MANAGER_TRANSFORM stage (backends/espressif/lowering.py:149,164). That stage calls EdgeProgramManager.transform (export/stages.py:841-844), which never lifts them.
    • Consequence: exir/serde/export_serialize.py:735-737 raises SerializeError: getattr nodes containing tensors should not appear in the graph when anything serializes the transformed program. That program is session.get_edge_program_manager().exported_program(), or the result of edge.transform(EspPassManager()). Affected callers:
      • executorch.exir.serde.serialize.serialize/save;
      • an ETRecord built from that manager with generate_etrecord (devtools/etrecord/_etrecord.py:346).
    • Trigger:
      • Any HardSwish or HardSigmoid that does not get a LUT, i.e. one with a dynamic batch or a float edge. These are exactly the graphs in test_dynamic_activation_falls_back_to_portable and test_partially_quantized_activation_falls_back_to_portable.
      • Before this PR, the quantizer did not preserve these ops, so to_edge decomposed them and lifted the scalars, and these programs serialized.
      • SiLU has no scalar operands, so it is not affected.
      • .pte emission still works because the emitter fetches get_attr tensors (exir/emit/_emitter.py:1832-1834), so tests that only build a .pte don't notice.
    • Fix:
      • Preferred: have DecomposeActivations emit exir_ops.edge targets directly via aten_to_edge, as _get_aten_target in backends/transforms/fused_quant/decompose_fused_quant.py already does. Register scalar operands with add_constant(..., InputKind.CONSTANT_TENSOR), as _lower_lut does.
      • This also removes ScalarToTensorPass and OpReplacePass. Both are whole-graph ExportPass retraces that now run on every ESP program, even when nothing falls back.
      • Alternatively, lift the constants before EspPassManager returns.
      • Either way, assert that serialize(edge.exported_program()) succeeds in _check_portable_activation (backends/espressif/test/ops/test_lut.py:281).

    Fix this →

Recommendation

Request Changes

The serialization regression is the only blocker. Fixing it means either emitting Edge ops with registered constants or lifting the constants, plus one test assertion. Everything else is non-blocking.

@rascani
rascani force-pushed the codex/espressif-fused-quant-lut branch from 871d2f6 to ffed2db Compare November 18, 2026 20:52
@rascani
rascani requested a review from JakeStevens November 18, 2026 21:29
@rascani
rascani marked this pull request as ready for review November 18, 2026 21:29
@rascani
rascani force-pushed the codex/espressif-fused-quant-lut branch 2 times, most recently from 5ad1cc5 to 2beeec1 Compare November 18, 2026 23:56
@rascani
rascani removed this pull request from stack #25158 November 18, 2026 23:59
@rascani
rascani added this pull request to stack #25261 November 19, 2026 00:01
@JakeStevens

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Claude finished @JakeStevens's task in 4m 38s —— View job


The previous blockers are fixed and this review found no new correctness problems, but I'm asking for changes because the optimized-ESP-NN emulator jobs, the only CI that checks the new LUT kernel against ESP-NN, are failing on the current head and nobody has confirmed they're unrelated; the rest is minor coverage and API polish.

Detailed review of a23c338 against codex/espressif-fused-quant-depthwise

PR Review: #25160

Summary

The PR lowers static int8 Fused Quant sigmoid, tanh, GELU, SiLU, HardSwish, HardSigmoid, ReLU and HardTanh to esp_nn::quantized_lut_int8. The 256-entry table is built at export by evaluating the FQ op on every input code.

Fixed since the last review:

  • the 0-dim output aliasing the table (now torch.take, plus a test);
  • the HardSwish/HardSigmoid fallback serialization (test_lut.py:294 now round-trips through serialize/deserialize);
  • the undersized-table check, which now has its own ET_KERNEL_CHECK.

Still open: the narrow-range qparams gate, the missing ANSI emulator case, and the untested qparams-rejection branch.

New: a quantizer-test gap.

What I couldn't check:

  • I couldn't read the CI logs from this job.
  • The ESP-NN sources aren't in the checkout, so I couldn't check esp_nn_logistic_s8's table indexing.
  • I didn't run pytest or the emulator.

Testing

  • The failing optimized-emulator jobs may be caused by this PR (major until the author rules it out).

    • Dr. CI shows ESP32-S3, ESP32-P4 and ESP32-S31 (optimized) failing on a23c338.
    • Those are the only jobs that run test_implementation_lut (backends/espressif/test/ops/test_lut.py:189-194) and test_implementation_lut_undersized_table against real ESP-NN.
    • The host tests can't catch a table-order mismatch. The Python reference (ops/operators.py:106, take(table, input & 255)) and the table construction (passes/lower_to_esp.py:201-202, int8 codes in uint8-cast order) share the same assumption.
    • If the optimized esp_nn_logistic_s8 indexed lut[x + 128] instead, every lowered activation would be silently wrong on device, and only these jobs would show it.
    • Please confirm whether these failures are related. Also add one ANSI case (EspTester(..., kernel_mode=EspKernelMode.ANSI), as in test_conv2d.py) so both ESP-NN implementations are checked. This was flagged in the previous review and is still open.
    • All three reviewers raised the indexing concern independently.

    Fix this →

  • No test reaches the qparams rejection in _lower_lut (minor, still open).

    • test_sigmoid_unsupported_qparams_stay_portable (test_lut.py:259-264) only sets one edge to float, so _lower_lut rejects it at the dtype check (lower_to_esp.py:189-197). The _qparams is None branch at :199 never runs, which makes the test name misleading.
    • The dynamic-shape and partial-quantization fallback tests (:320, :352) only cover silu, hardswish and hardsigmoid. Nothing tests a dynamic-batch fallback for sigmoid, tanh, GELU (either approximate mode), relu or hard_tanh.
    • Fix: add a case with int8 edges whose qparams _qparams rejects (narrow range or per-channel), rename the float-edge test, and widen the dynamic fallback parametrization to all _LUT_OPS.

    Fix this →

  • The new quantizer test checks the wrong op (minor).

    • test_sigmoid_output_qparams_are_calibrated (backends/espressif/test/test_fused_quant_quantizer.py:39) covers sigmoid, which the core quantizers already handled.
    • The three OpQuantizers this PR adds (quantizer/esp_fused_quantizer.py:118-132, hardswish, hardsigmoid and silu) get no direct check of int8, (-128, 127) and calibrated scale.
    • If they were annotated with the wrong config, the only symptom would be a missed lowering in test_lut.py, not a failing quantizer test.
    • Fix: parametrize the test over the three new ops.

API Design

  • Narrow-range int8 qparams silently skip the LUT (minor, still open; two reviewers raised it).

    • _lower_lut calls _qparams (lower_to_esp.py:199), which returns None unless (quant_min, quant_max) == (-128, 127) (:159-160).
    • That restriction matters for the binary kernels, but not here: the table comes from running the FQ op itself, so any output clamp is already in it.
    • Effect: a symmetric [-127, 127] config falls back to portable without any warning, and allow_cpu_fallback=False rejects it.
    • backends/espressif/README.md doesn't mention this requirement.
    • Fix: accept any valid int8 range for LUT ops, or document the requirement.

    Fix this →

Recommendation

Request Changes

The blocker is confirming that the failing optimized-emulator jobs aren't caused by this PR. They are the only check of the table order against ESP-NN, and a wrong order would make every lowered activation silently wrong on device. The other findings are non-blocking. The ReLU-into-producer folding and the duplicated static-int8 check from earlier reviews are still open but not re-raised.


  • Load /pr-review skill
  • Gather diff against codex/espressif-fused-quant-depthwise
  • Independent three-reviewer panel
  • Consolidate and fact-check (dropped: per-node table duplication, since the emitter deduplicates constant buffers; _lower_lut not catching the _qparams ValueError, which matches the binary lowering; kernel dtype checks, which were already flagged as optional)
  • Run tests and the emulator: not done, because they need approval and an ESP build this job doesn't have; the CI logs weren't accessible

Lower sigmoid, tanh, GELU, SiLU, HardSwish, HardSigmoid, ReLU, and HardTanh (including ReLU6) to quantized_lut_int8. ESP-NN's logistic evaluation applies a generic 256-entry int8 lookup table, so the same kernel handles these elementwise activations.

Evaluate each original FQ operator over every int8 input code at export, preserving its activation parameters, calibrated per-tensor qparams, and rounding. Store the table as a constant Tensor argument without scratch allocation. The native wrapper checks input, output, and table capacities and the vendor's element-count bound. Preserve SiLU, HardSwish, and HardSigmoid through local configurations of the existing shared OpQuantizer.

Validation passed 249 Python tests, 24 S3 emulator tests, and scoped lint. Shared cases cover every int8 code, both GELU modes, custom clamp bounds, mixed float users, chains, saturation, serialization, and undersized-table rejection. Add and linear also exercise ReLU through the lookup operator.

Authored with OpenAI Codex.
Return independent storage for scalar LUT outputs and lift constants introduced by activation decomposition before returning the transformed Edge program. This preserves the operator aliasing contract and makes HardSwish and HardSigmoid fallback graphs serializable.

Validation: 69 LUT and pass-manager Python tests passed. The new scalar-alias and Edge-serialization regressions failed before these fixes. Scoped lint passed. Authored with OpenAI Codex.
@rascani

rascani commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

@claude re-review

@claude

claude Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Claude finished @rascani's task in 4m 21s —— View job


This re-review of faa344e found no new correctness defects, but the ESP32 emulator jobs are the only check that the table order matches real ESP-NN and they are still queued on this head, so approval should wait for them; the other findings are minor and were mostly raised before.

Detailed review of faa344e

PR Review: #25160

Summary

The PR lowers static per-tensor int8 Fused Quant sigmoid, tanh, GELU, SiLU, HardSwish, HardSigmoid, ReLU and HardTanh to esp_nn::quantized_lut_int8. Its 256-entry table is built at export by evaluating the FQ op on every input code.

Status of earlier findings:

  • Fixed: the scalar output aliasing the table, the fallback serialization (lift_constant_tensor_pass now runs in esp_pass_manager.py:71 on the base branch), and the undersized-table check, which now has its own ET_KERNEL_CHECK.
  • Still open: the ANSI emulator case, the untested qparams-rejection branch, the narrow-range qparams gate, and the quantizer test only covering sigmoid. These are listed below.
  • Not re-raised (non-blocking): folding ReLU into the add/linear clamp, and the duplicated static-int8 check.

What I could not check:

  • The ESP-NN 1.5.x sources are not in the checkout, so I couldn't check esp_nn_logistic_s8's signature or how it indexes the table.
  • I did not run pytest or the emulator.
  • The ESP32 emulator jobs on this head were still queued while I reviewed.

Testing

  • The table order is only checked against the PR's own Python reference (major until the emulator jobs pass; all three reviewers raised it).

    • _lower_lut builds the table in uint8-cast order (backends/espressif/passes/lower_to_esp.py:203).
    • The eager reference reads it with torch.take(table, input & 255) (backends/espressif/ops/operators.py:106). The atol=0 host tests therefore agree with the lowering by construction.
    • If ESP-NN indexes lut[x + 128], or esp_nn_logistic_s8 has a different signature, every lowered activation would be wrong on device and all host tests would still pass.
    • Only test_implementation_lut would catch this. It skips unless ESPRESSIF_BUILD_DIR is set, and it runs only the default OPTIMIZED build (test/tester.py:108). test_lut.py has no ANSI case, unlike test_conv2d.py.
    • Please confirm the Test ESP32 Emulators jobs pass on faa344e, and add one EspKernelMode.ANSI case.

    Fix this →

  • Several _lower_lut rejection branches are untested, and one test name claims coverage it doesn't have (minor, confirmed, still open).

    • test_sigmoid_unsupported_qparams_stay_portable (test_lut.py:264) only makes one edge float. _lower_lut therefore rejects it at the dtype check (lower_to_esp.py:189-197), and the _qparams is None branch at :199 never runs.
    • No test covers per-channel or narrow-range int8 qparams, zero-element tensors, or non-contiguous (e.g. channels_last) inputs.
    • The dynamic-shape fallback test covers only silu, hardswish and hardsigmoid.
    • Fix: add an int8 case whose qparams _qparams rejects, rename the float-edge test, and widen the dynamic fallback parametrization to all of _LUT_OPS.

    Fix this →

  • The quantizer test does not cover the three new OpQuantizers (minor, still open).

    • test_sigmoid_output_qparams_are_calibrated (test/test_fused_quant_quantizer.py:39) tests sigmoid, which the core quantizers already handled.
    • The hardswish, hardsigmoid and silu entries added at quantizer/esp_fused_quantizer.py:118-132 have no direct check.
    • Fix: parametrize the test over those three ops.

API Design

  • Narrow-range int8 qparams silently skip the LUT (minor, confirmed, still open; raised again by a reviewer this round).

    • _lower_lut calls _qparams (lower_to_esp.py:199), which returns None unless (quant_min, quant_max) == (-128, 127) (:159-160).
    • The LUT doesn't need that restriction, because the table is the FQ op itself evaluated on every code and already includes the output clamp.
    • Consequences:
      • a [-127, 127] config, or a ReLU/HardSigmoid with a [0, 127] output spec, falls back without notice;
      • allow_cpu_fallback=False rejects these configs;
      • the README doesn't mention the requirement.
    • Fix: accept any valid int8 range for LUT ops, or document the restriction.

    Fix this →

Code Quality

  • The table's shape can follow the scale's shape (minor, low confidence: found by reading the code, not reproduced).
    • is_per_tensor() accepts an all-ones scale of any rank (exir/dialects/fused_quant/ops.py:106-112).
    • If the reference op broadcasts codes (shape [256]) against a [1, 1, 1, 1] scale, the table becomes [1, 1, 1, 256] instead of [256].
    • The runtime is unaffected, since it checks only nbytes(), but the serialized table would not be 1-D and the (256,) assertion in test_dialect_lut would fail.
    • Fix: add .reshape(256) after node.target(*args, **kwargs) (lower_to_esp.py:207).
  • The kernel checks byte capacity only (minor; all three reviewers raised it, and it was flagged as optional earlier).
    • op_quantized_lut.cpp:30-37 does not check that input, out and table are Char, or that out.numel() == input.numel().
    • Because the schema's Tensor table is untyped, table.scalar_type() == Char && table.numel() == 256 would make the existing nbytes() >= 256 check exact.
    • numel >= 0 (:33) is always true.

Recommendation

Needs Discussion

No confirmed defects remain. Approval depends on the Test ESP32 Emulators jobs passing on faa344e: they are the only check of the table order against ESP-NN, and a wrong order would make every lowered activation silently wrong on device. The rest is non-blocking.


  • Load /pr-review skill
  • Gather diff and CI status (ESP32 emulator jobs were queued on this head)
  • Independent three-reviewer panel
  • Consolidate, re-check previous findings, fact-check (dropped: the claim that the commit message describes constant lifting missing from the diff, because the base already lifts in esp_pass_manager.py; the claim that non-constant hard_tanh bounds could crash, because they are floats; _qparams raising ValueError, which matches the binary lowerings)
  • Run tests and the emulator: not done, because they need approval and an ESP build this job doesn't have

Exercise narrow int8 input and output ranges through portable fallback and
serialization, and distinguish these from partially quantized sigmoid calls.
Verify calibrated output grids for sigmoid, SiLU, HardSwish, and HardSigmoid.

Authored with Codex.

This branch was previously deployed

1 inactive deployment
cadence — 7263efbd Deployed Nov 23, 2026 by rascani via hifi1s-op-test / hifi1s #40464
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants