Skip to content

[Espressif] Lower Fused Quant depthwise convolution - #25159

Merged
rascani merged 5 commits into
codex/espressif-fused-quant-conv2dfrom
codex/espressif-fused-quant-depthwise
Nov 23, 2026
Merged

rascani merged 5 commits into
codex/espressif-fused-quant-conv2dfrom
codex/espressif-fused-quant-depthwise

Conversation

@rascani

@rascani rascani commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Lower supported Fused Quant depthwise Conv2d calls to ESP-NN, building on #25154 and the scratch bindings in #25157. Support covers static int8 tensors, positive integer channel multipliers, unit dilation, constant per-output-channel symmetric weights, and optional derived int32 bias. Unsupported configurations retain portable convolution.

Export packs constant weights from OHWI to ESP-NN's 1HWO order and allocates an explicit scratch Tensor using the selected chip/kernel query. The wrapper checks capacities and vendor indexing bounds, then uses the vendor dispatcher for SIMD or C execution. Required NHWC boundary copies remain visible in the report.

Review quantization and lowering first, then the schema/reference, wrapper, and shared cases. Tests include hardcoded asymmetric scratch-size expectations across profiles, memory-plan non-overlap, missing-binding fallback, padding bounds, multipliers, batch output alignment, and no-bias paths. S3 sizing-bound checks explicitly select S3. Device checks follow the selected chip, and the undersized-buffer test skips kernels that require no scratch.

Validation: depthwise host tests pass, including chip selection and scratch-query fallback. Five targeted optimized-S3 emulator cases passed: multiplier/stride/padding, unaligned batched output, unpadded stride, no bias, and undersized scratch. Scoped lint passed. Existing vendor depthwise defects remain deferred upstream; other chips have sizing/export coverage only.

Authored with OpenAI Codex.

@rascani
rascani added this pull request to stack #25158 November 17, 2026 04:37
@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/25159

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

❌ 2 New Failures, 5 Pending

As of commit 95a522c with merge base d811540 (image):

NEW FAILURES - The following jobs have failed:

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
@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 review effort=max

@claude

claude Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Claude finished @rascani's task in 29m 17s —— View job


I found no numeric bugs, but I'm requesting changes: the runtime wrapper never checks its redundant channel_multiplier argument, the depthwise tests are weaker than the sibling Conv2d tests, and CI never runs the host-only ones.

PR Review: #25159: [Espressif] Lower Fused Quant depthwise convolution

Summary

The PR lowers Fused Quant depthwise Conv2d (groups == C_in, integer multiplier, unit dilation) to a new esp_nn::quantized_depthwise_conv2d_int8 op, with weights packed at export and scratch planned ahead of time. I found no correctness defects in the weight packing, argument order or reference math. The problems:

  • the tests cover less than the sibling Conv2d tests;
  • CI never runs the host-only tests the PR description relies on for non-S3 chips;
  • the runtime wrapper never checks the redundant channel_multiplier argument;
  • the pass's depthwise branch is driven by a boolean flag.

This was a static review. pytest could not be run here and the ESP-NN v1.5.0 sources were not available, so claims about vendor behavior are marked unverified.

Infrastructure

  • CI never runs the new host-side depthwise tests (test/ops/test_depthwise_conv2d.py:184-329, .ci/scripts/test_espressif.sh:165-166).
    • Default builds set EXECUTORCH_BUILD_ESP_NN_PYBINDS=OFF (setup.py:176, tools/cmake/preset/default.cmake:241). In the generic pytest job (pytest.ini:92), every test gated on s3_queries or get_scratch_queries therefore skips.
    • The only job that builds the bindings runs pytest backends/espressif/test/ops -k implementation. That filter excludes test_dialect_depthwise_conv2d, test_depthwise_scratch_selection, test_public_recipe_depthwise, test_depthwise_without_sizing and test_depthwise_spatial_index_bounds.
    • test_implementation does not check node counts (tester.py:157-158). It compares the device against the graph after the passes run. A regression that silently sends depthwise back to portable would still pass CI.
    • So nothing in CI checks the "host sizing/export coverage" the description cites for P4, S31 and C3. The gap predates this PR (it also affects Conv2d), but this PR is the first to depend on it for every non-S3 profile.
    • Fix: add a host-only step with -k "not implementation" right after the scratch-bindings build. It needs no emulator. Fix this →

Testing

  • test_depthwise_scratch_selection cannot catch argument-mapping bugs (test_depthwise_conv2d.py:234-269).
    • The expected value comes from calling the same query with hand-written dims. The s8_padded case is symmetric in every way that matters: C == O == 16, M = 1, stride = padding = (1, 1), and a padded-input size that does not change if W and H are swapped.
    • So passing channels instead of outputs in filter_dims, a wrong multiplier, or swapped W/H or stride/padding order would all still pass.
    • The sibling test_public_recipe_conv2d (test_conv2d.py:237-274) hard-codes the bytes per target and also covers EspTarget.ESP32, which is missing here.
    • This matters more than it did for Conv2d. The new depthwise bound (fused_quant_to_esp_pass.py:494-503) is derived by hand. A vendor size above it raises RuntimeError at :529 instead of falling back, even with allow_cpu_fallback=True. Each non-S3 profile is checked against only this one shape. I could not confirm whether any real shape exceeds the bound.
    • Fix: use an asymmetric case such as multiplier_3 or stride_padding with hard-coded bytes per target, and run all of test_cases through test_dialect for each target. Fix this →
  • test_depthwise_without_sizing skips the case it simulates (test_depthwise_conv2d.py:295).
    • It requests the s3_queries fixture, so its "binding" case is skipped exactly when the bindings really are missing.
    • Every other depthwise lowering test is gated the same way. A default install without pybinds therefore runs no depthwise lowering or fallback test at all.
    • That default path is the one the quantizer change affects: depthwise now always gets an int32 bias and then falls back to portable.
    • test_convolution_falls_back_without_sizing (test_conv2d.py:278-287) avoids this by looking up queries only inside its "query" branch. Fix this →
  • The scratch/IO overlap check was dropped (test_depthwise_conv2d.py:210-222). test_dialect_conv2d asserts that the planned scratch does not overlap the kernel's input or output (test_conv2d.py:212-225); the depthwise copy of that test does not. This is the assertion that protects planned scratch, because the kernel reads scratch while it writes out. Fix this →
  • The emulator cases miss the common SIMD configurations (test_depthwise_conv2d.py:102-180).
    • The only stride > 1 case, stride_padding, uses C=5 with a 3×2 kernel. No case covers 16 channels, 3×3, stride 2 (MobileNet's downsampling block), padded or unpadded.
    • The only batch > 1 case, batches_unaligned, uses C=4 and M=4. Its per-batch output offset is 240 B, which is 16-byte aligned. So the M=1 C%8 and C%16 paths never see out + batch * output_bytes (op_quantized_depthwise_conv2d.cpp:141) at an unaligned address.
    • no_bias only runs with C=8.
    • Fix: add the strided C=16 cases, a batch-2 case with C=8 or 16, M=1 and odd oh*ow, and a no-bias case with C=16. Fix this →
  • Negative cases are missing. Fix this →
    • test_convolution_int32_bias (test_fused_quant_quantizer.py:212) only gained positive cases. No test checks that a grouped conv that is not depthwise, e.g. Conv2d(4, 4, 1, groups=2), stays without int32 bias under the new groups in (1, shape[1]) rule (esp_fused_quantizer.py:59).
    • test_depthwise_spatial_index_bounds (:308-329) only uses stride 1 and padding 0. That leaves the pad > 32768 clause (pass :490, C++ :75) untested, although it is reachable, e.g. with padding 32769 and stride 65535.

Code Quality

  • The runtime wrapper trusts channel_multiplier (ops/op_quantized_depthwise_conv2d.cpp:80).
    • The wrapper computes outputs = channels * channel_multiplier. The sibling wrapper takes it from out.size(3) (op_quantized_conv2d.cpp:53), and the delegate computes the multiplier as output.shape[1] / input.shape[1] (espnn_runtime/src/int8_interpreter.cpp:557,592).
    • Nothing checks out.size(3) == outputs, weight.size(0) == 1 or weight.size(3) == outputs. The byte-capacity checks keep writes in bounds, but a program whose multiplier disagrees with its tensors passes every check and silently writes the wrong layout. For example, channel_multiplier=1 with out shaped for M=2 writes C channels per pixel into the first half of out.
    • The PR description says the wrapper checks "vendor indexing bounds", but output_h/output_w are never checked against (in + 2p − k)/s + 1. The sibling wrapper has the same gap. I could not verify whether the padded S3 SIMD kernels clip their windows.
    • Fix: add the equality checks. Better still, remove the argument from the schema and compute the multiplier the way the delegate does, since the tensor shapes fully determine it. Fix this →
  • A boolean flag now drives _conv2d_kernel_args (passes/fused_quant_to_esp_pass.py:433-554).
    • The depthwise flag switches the groups checks (:436, :463-464), the size-query kwargs through a conditional ** splat (:526), the weight permute (:530-532), and the op args through a conditional * splat (:548).
    • The ordinary-conv bound and its comment (:474-486) are computed, then overwritten for depthwise (:494).
    • outputs // channels is computed twice, the depthwise=False default is never used, and outputs % channels (:464) cannot be non-zero once groups == channels.
    • _lower_conv2d sets depthwise = groups != 1 (:579). Ordinary grouped convs are therefore labeled depthwise and fetch the depthwise query, and only the shape checks deep in the helper (:463-464) reject them.
    • Fix: decide groups == channels in one place, compute the multiplier once, use if/else for the two bounds, and build each op's args explicitly. Alternatively, split out a depthwise args builder that shares the validation. Fix this →
  • The reference copies the linear requantize code (ops/operators.py:331-342, copied from :208-219). The bias add, per-channel requantize, stack, offset and clamp are copied verbatim. The sibling quantized_conv2d_int8 reuses quantized_linear_int8 instead. Fix this →
  • Low confidence: depthwise int32 biases may clamp (quantizer/esp_fused_quantizer.py:59, :29-32, :88).
    • The bias scale is s_in · s_w[c] with no adjustment, and the quantized bias is clamped to about ±2³¹. Each depthwise channel has only kH·kW weights, so near-dead channels (e.g. after BN folding in MobileNet-style models) get eps-sized weight scales. Their bias then saturates silently: with s_in = 0.01 and s_w ≈ 1.2e-7, any |bias| > ~2.6 clamps.
    • Before this PR, depthwise convs that fall back to portable (dilation, int16 limits, no pybinds) kept an exact float bias. They now get the clamped int32 value as well.
    • Consider adjusting weight scales the way TFLite does, or at least warning when the bias saturates. I have not measured this on a real model.

Specific Comments

  • README.md:45: "within the vendor's dimension and indexing bounds" is vague. State the limits users will hit: C·M ≤ 65535, C ≤ 65520, padding ≤ 32768, and (out − 1)·stride − pad ≤ 32767. Exceeding any of them silently falls back to portable.
  • quantizer/esp_fused_quantizer.py:105-107: the docstring reflow leaves a short line mid-sentence ("Conv2d, and depthwise Conv2d biases use").
  • ops/op_quantized_depthwise_conv2d.cpp:75-76,97: the literals 32768, 32767 and 65535 sit next to std::numeric_limits<uint16_t>::max() at :68. Use std::numeric_limits<int16_t>/<uint16_t>. The reason for the int16 window-origin limit is only written down in the Python comment (pass :488).
  • test/ops/test_depthwise_conv2d.py:99: groups=8 is hard-coded and silently tied to the default channels=8; use self.conv.groups.
  • test/ops/test_depthwise_conv2d.py:356: the Conv2d wrapper logs the same "scratch.nbytes()" check text (op_quantized_conv2d.cpp:134) to the same operator-library-{worker}-esp32s3-optimized/emulator.log. If the firmware build fails, pytest.raises(AssertionError) is satisfied and a stale log can satisfy the string check, e.g. under -k undersized. Match something unique to the depthwise kernel.

Recommendation

Request Changes

None of the findings is a numeric bug. Two things should land with the new op:

  • the channel_multiplier consistency checks in the wrapper, or removing the argument;
  • depthwise tests at parity with the sibling Conv2d tests: hard-coded per-target scratch bytes on an asymmetric shape, the scratch/IO overlap assertion, and a fallback test that is not gated on pybinds.

The CI -k implementation filter predates this PR, but until it changes, none of the host-only coverage the PR description cites runs in CI.

@rascani

rascani commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

Please review the current revision (2d8d88646a1118218dec4a77daf2f3126dfcb7d1) against this PR's base branch, codex/espressif-fused-quant-conv2d. 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 30m 46s —— View job


Most of the previous review's test and CI findings are fixed, but I'm still requesting changes. The wrapper still never checks channel_multiplier against the tensor shapes, and very wide depthwise convs abort export instead of falling back to portable.

PR Review: #25159: [Espressif] Lower Fused Quant depthwise convolution (re-review of 2d8d886)

Summary

The PR lowers Fused Quant depthwise Conv2d (groups == C_in, integer channel multiplier, unit dilation) to a new esp_nn::quantized_depthwise_conv2d_int8 op. Weights are packed to 1HWO at export and scratch is planned ahead of time. I found no numeric defects in the reference op, the argument order between pass, schema and wrapper, or the OHWI→1HWO packing.

Status of the previous review's findings:

  • Fixed:
    • CI now runs the host-only tests (.ci/scripts/test_espressif.sh:165-166).
    • The scratch vs. input/output overlap assertion is back.
    • The missing-binding fallback test no longer skips when the bindings are missing.
    • Scratch bytes are hard-coded per target, now including ESP32.
    • A test covers the padding > 32768 rejection.
    • New emulator cases cover unaligned batched output, unpadded stride-2 with C=16, and no bias with C=16.
    • The undersized-scratch test now checks for the depthwise kernel's own log text.
  • Still open (below):
    • the wrapper's unchecked channel_multiplier;
    • the stride-2, padding-1, C=16 case;
    • scratch-size tests that cannot catch argument-order bugs;
    • the quantizer negative case;
    • the low-confidence bias-saturation note.
  • Unchanged and not repeated here, since they are outside this review's focus: the depthwise flag in _conv2d_kernel_args, the duplicated requantize code in operators.py, and the earlier wording and literal-constant nits.

New this round: the wide-depthwise export crash, and a question about the deferred vendor defects.

This was a static review. Running Python and fetching the ESP-NN v1.5.0 sources were both blocked here, so claims about vendor behavior are marked unverified.

Code Quality

  • The wrapper still never checks channel_multiplier (ops/op_quantized_depthwise_conv2d.cpp:80; checks at :95-106).

    • It computes outputs = channels * channel_multiplier. The sibling takes it from out.size(3) (op_quantized_conv2d.cpp:53).
    • Nothing checks any of these:
      • out.size(3) == outputs
      • weight.size(0) == 1 and weight.size(3) == outputs
      • out.size(0) == batches
      • output_h/output_w equal (in + 2p − k)/s + 1
    • The byte-capacity checks keep writes in bounds. But a program whose arguments disagree with its tensors passes every check and silently writes the wrong layout. Example: channel_multiplier=1 with out shaped for M=2 writes C channels per pixel into the first half of out.
    • Unverified: S3's padded 3×3 path sizes its padded copy in scratch from the input dims and padding, but loops over the output dims. An inflated output_h/output_w would then read past that copy. The description's claim that the wrapper "checks vendor indexing bounds" should cover this case.
    • Fix: add the equality checks, or drop channel_multiplier from the schema and derive it as out.size(3) / channels with a divisibility check. The op is new, so the schema is still cheap to change. Fix this →
  • Very wide depthwise convs abort export instead of falling back (passes/lower_to_esp.py:528-535).

    • Cause: the binding's check_conv_arithmetic (scratch/bindings.cpp:72-73) bounds the filter as (kw·aligned_C + 15)·kh·outputs. That is the ordinary-conv layout, and for depthwise it grows with C². The pass's own depthwise bound (:502-511) grows only linearly in C. A shape can therefore pass the pass's checks and then make the binding throw ValueError("scratch query intermediates exceed the int32 range").
    • Nothing catches that error: _lower_conv2d only catches AttributeError, and LowerToEsp.call (:656-658) catches nothing.
    • Trigger: Conv2d(4800, 4800, 7, padding=3, groups=4800) on a (1, 4800, 7, 7) input. The pass's bound is about 8.8M, but the binding's sum is about 2.27e9, which is above INT32_MAX. The cutoff is roughly 4.7K channels for a 7×7 kernel and 10.9K for 3×3.
    • Consequence: export fails even with allow_cpu_fallback=True, although the PR says unsupported configurations retain portable convolution. Such shapes are unusual on ESP32, but the fix is small.
    • Fix: move the size query and its bound check above _weighted_constants, and return None on ValueError. That way a rejected shape also leaves no multiplier/shift constants behind. The same change covers the ordinary-conv path, whose Python bound is about half the binding's. The alternative is a depthwise filter term in the binding, in [Espressif] Bind ESP-NN scratch-size queries by target #25157. Fix this →
  • Question: which vendor depthwise defects are deferred, and are the affected shapes excluded from lowering? (passes/lower_to_esp.py:495-511)

    • The description says "Existing vendor depthwise defects remain deferred upstream". The only guard aimed at a specific defect is the int16 window-origin check (:496-501).
    • A known defect may produce wrong output or overrun scratch on a shape this PR lowers. In that case the pass should return None for that shape, or the README should list it. Today such a shape reaches esp_nn_depthwise_conv_s8.
    • Please link the upstream issues so reviewers can check that the affected shapes are excluded.
  • Low confidence, carried over: depthwise int32 biases may saturate (quantizer/esp_fused_quantizer.py:29-32, :59, :86-88).

    • This code is unchanged. The bias scale is s_in · s_w[c], and the quantized bias is clamped to about ±2³¹.
    • A depthwise channel has only kh·kw weights. Near-dead channels, e.g. after BN folding, therefore get weight scales near the observer eps (≈1.2e-7). With s_in = 0.01, any |bias| above about 2.6 is clamped.
    • Depthwise convs that fall back to portable now carry the clamped value as well. Before this PR they kept the exact float bias.
    • Consider raising the weight scale in this case, as TFLite does, or at least warning when a bias saturates. I have not measured this on a real model.

Testing

  • The standard MobileNet downsampling layer is missing from the test cases (test/ops/test_depthwise_conv2d.py:103-195).
    • No case combines C % 16 == 0, a 3×3 kernel, multiplier 1, stride 2 and padding 1. stride_s8_unpadded has stride 2 with padding 0, and s8_padded has padding 1 with stride 1.
    • This stride-2 downsampling layer appears several times in every MobileNet-class model and runs on the S3 SIMD path. The gap matters more given the deferred vendor defects.
    • Add e.g. EspDepthwiseConv2d(16, stride=2, padding=1) on (1, 16, 8, 8). Fix this →
  • The scratch-size tests may not catch argument-order bugs, and the other chips are sized for only one shape (test_depthwise_conv2d.py:270-297).
    • The only non-zero expectation is 728 bytes on S3, for multiplier_stride_padding. That equals 2·(kh·kw·C·M + H·W·C) + 32 = 2·(96 + 252) + 32.
    • That formula looks like S3's ch_mult % 4 sizing branch. As far as I recall, that branch ignores stride, padding and output dims and is symmetric in width and height, but I could not check this against the v1.5.0 source. If it is that branch, swapping width and height, or the stride and padding order, in the size_query(...) call (lower_to_esp.py:528-535) would still pass.
    • Every P4, S31, ESP32 and C3 expectation is 0, and those chips lower only this one shape, because test_dialect_depthwise_conv2d runs only on the default S3 profile. Every P4/S31 depthwise size that test_scratch.py checks is 0 too.
    • So the pass's hand-derived bound (lower_to_esp.py:502-511) is never compared with a non-zero P4/S31 depthwise size. A vendor size above that bound raises RuntimeError at :536-537, even with CPU fallback enabled.
    • Fix: pin the scratch bytes for an M=1, C=16, 3×3 unpadded case with stride (2, 1) on a non-square input, and lower every test_cases entry for each profile. Both checks run on the host. Fix this →
  • No negative case for the new bias rule (test/test_fused_quant_quantizer.py:212-219).
    • Still open. Every parametrized case is a positive one. Nothing checks that a grouped conv that is not depthwise, such as Conv2d(4, 6, 1, groups=2), gets no int32 bias under groups in (1, shape[1]) (esp_fused_quantizer.py:59).
    • groups_fallback (test_conv2d.py:167) likely would not catch that regression, because the portable path tolerates an int32 bias. Fix this →

Recommendation

Request Changes

The last review asked for the wrapper's shape checks, or for dropping channel_multiplier from the schema, and neither has happened. The wide-depthwise export crash is a small fix in the same area. Please also answer the question about the deferred vendor defects. Before relying on this path for MobileNet-class models, add the stride-2, padding-1, C=16 case to the emulator run.

@rascani

rascani commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

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

The scratch size-query fallback from #25154 is preserved for depthwise, with a regression using an actual rejected vendor scratch bound that verifies numerical fallback and serialization. Please re-check the earlier finding that a size-query ValueError aborted export. Focused depthwise checks and 969 combined host tests at the stack tip passed with rebuilt sizing bindings. Runtime wrappers retain the agreed bounds-checking contract, with semantic eligibility checked during AOT lowering.

@claude

claude Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Claude encountered an error after 25m 58s —— View job


The earlier size-query ValueError export abort is fixed, but I'm requesting changes for one small memory-safety gap: the depthwise wrapper's int32 guard ignores how far out reaches into the input, which the sibling wrapper and the sizing binding both bound.

PR Review: #25159: [Espressif] Lower Fused Quant depthwise convolution (re-review of 93fce0f)

Summary

The PR lowers Fused Quant depthwise Conv2d to a new esp_nn::quantized_depthwise_conv2d_int8 op, with weights packed to 1HWO and scratch planned at export. One wrapper bound is missing and some test gaps remain.

Status of the previous review's findings:

  • Fixed: a size-query ValueError aborted export.
    • The size query and _weighted_constants now run inside try/except ValueError (passes/lower_to_esp.py:524-539). Nothing is added to the graph before that block.
    • The new test_depthwise_falls_back_when_sizing_rejects_bounds does reach that path. For its shape the pass's own bound is about 8.8 MB, but the binding's total is about 2.27e9, so the binding raises.
  • Dropped, per the agreed contract: the semantic checks on channel_multiplier and the output shape. The bounds-checking part of that finding is narrowed and moved under Security.
  • Still open (below): the vendor-defects question, the stride-2/padding-1/C=16 case, the scratch-size test that cannot catch argument-order bugs, and the negative test for the bias rule.
  • Unchanged, not repeated (low confidence or outside the requested focus):
    • the int32-bias saturation note;
    • the depthwise flag in _conv2d_kernel_args, whose not depthwise and groups != 1 clause at :446 is now dead because the only caller sets depthwise = groups != 1;
    • the duplicated requantize tail in operators.py;
    • the earlier wording and literal-constant nits.

This was a static review. Python and the ESP-NN v1.5.0 sources were not available here, so claims about vendor behavior are marked unverified.

Security

  • The wrapper's int32 guard ignores how far out reaches into the input (ops/op_quantized_depthwise_conv2d.cpp:72-93).
    • padded_h/padded_w (:85-88) use only the input size, padding, kernel and stride. Apart from the int16 window-origin check at :76, nothing ties out.size(1) or out.size(2) to the input.

    • The two other guards on the same vendor arithmetic both account for the output:

      • the sibling wrapper uses max(height + padding, (output_h - 1) * stride + kernel_h) (op_quantized_conv2d.cpp:83-86);
      • the sizing binding uses max(input, output * stride) + 2 * pad + filter (scratch/bindings.cpp:61-65).
    • Trigger: a program the pass would not emit (hand-built, corrupted, or produced by some other tool) with input (1, 3, 3, 16), a 3×3 kernel, padding 0, stride (130, 128) and out of shape (1, 126, 128, 16).

      • Every wrapper check passes. The wrapper's own bound comes to about 2.5 MB.
      • For the same dimensions, check_conv_arithmetic computes 16383 · 16387 · 16 ≈ 4.3e9 and raises, so sizing at export would reject this shape.
    • Unverified consequence:

      • On S3, the unpadded 3×3, C % 16 path pads the input to out * stride + k - 1 along each axis.
      • That size overflows int32 and wraps to a value small enough to pass required <= scratch.nbytes() (:127-131), so the padding copy then writes far past the end of scratch.
      • The padded path (padding == 1) sizes its copy from the input instead, so an oversized out makes it read past that copy.
    • Fix: add (out.size(axis + 1) - 1) * stride[axis] + weight.size(axis + 1) <= input.size(axis + 1) + 2 * padding[axis] to the loop at :72-79.

      • This keeps every window the kernel reads inside the padded input, and the existing bound then covers the vendor's padded copy.
      • Every program the pass emits already satisfies it (lower_to_esp.py:475-481). It is a bounds check within the agreed contract, not a semantic one.

      Fix this →

Code Quality

  • Question, still unanswered from the last round: which "existing vendor depthwise defects" are deferred, and are the affected shapes kept out of lowering?
    • No code, README or test in backends/espressif names them. The only guard aimed at a vendor limitation is the int16 window-origin check (lower_to_esp.py:497-503).
    • P4 and S31 have no runtime coverage, so a defect on those chips would only show up as wrong output on device.
    • Please link the upstream issues, or list the affected shapes and return None for them in _conv2d_kernel_args.

Testing

  • The common S3 strided path is missing, and the scratch-size test cannot catch argument-order bugs (test/ops/test_depthwise_conv2d.py:103-195, :270-297).

    • No case combines M=1, C % 16 == 0, a 3×3 kernel, stride 2 and padding 1. stride_s8_unpadded uses padding 0 and s8_padded uses stride 1. That combination is the downsampling layer of MobileNet-class models, and it runs the padded SIMD path.

    • The only non-zero expected size, 728 bytes on S3, equals 2·(3·2·4·4 + 7·9·4) + 32, a plain product of sizes.

      • That suggests the vendor sizes this multiplier-4 case without using stride, padding or output dims (unverified).
      • If so, swapping width and height, or the stride and padding order, in the pass's size_query(...) call (lower_to_esp.py:525-532) would still give 728.
      • The other five profiles expect 0, so they cannot catch an argument-order bug either.
    • Fix:

      • Add EspDepthwiseConv2d(16, stride=2, padding=1) on (1, 16, 8, 8).
      • Add an unpadded case with asymmetric stride, e.g. EspDepthwiseConv2d(16, stride=(2, 1)) on (1, 16, 7, 9), and hard-code its scratch bytes per target in test_depthwise_scratch_selection. S3 sizes that path's right/bottom padding per axis from out * stride (unverified), so the expected size would depend on argument order.
      • The ESP32-S3 (optimized) CI job runs every test_cases entry on the emulator, so both cases would also be checked numerically on the device.

      Fix this →

  • test_depthwise_falls_back_when_sizing_rejects_bounds does not show that lowering reached the size query (:339-353).

    • The test calls the binding directly, then only checks that the model falls back.
    • Suppose a later change lets the pass's own bound or an eligibility check reject this shape first. The test would still pass, but the except ValueError path at lower_to_esp.py:538 would no longer be covered.
    • Fix: use monkeypatch to wrap s3_queries.depthwise_conv2d_scratch_size in a spy that records the call and re-raises, then assert it raised exactly once. Fix this →
  • No negative case for the new bias rule (test/test_fused_quant_quantizer.py:212-214).

    • All three parameter sets expect an int32 bias.
    • Nothing checks that Conv2d(4, 4, 1, groups=2), where 1 < groups < C_in, keeps a non-int32 bias under groups in (1, shape[1]) (esp_fused_quantizer.py:59).

    Fix this →

Recommendation

Request Changes

The blocker is the one-line window check in the wrapper. It closes a heap-overflow path that the sibling wrapper and the binding already guard, and it stays within the agreed bounds-only contract. The test additions are small and can land with it. Please also answer the vendor-defects question.

@rascani
rascani force-pushed the codex/espressif-fused-quant-depthwise branch from 93fce0f to 00056dc 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-depthwise branch 2 times, most recently from 47ee335 to 366d92f 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
Lower static int8 depthwise Conv2d through ESP-NN with positive channel
multipliers, unit dilation, per-output-channel symmetric weights, and
derived int32 bias. Reuse convolution parameter preparation and target-
selected scratch queries, packing constant weights from OHWI to 1HWO at
export. Unsupported configurations retain portable convolution.

Pass planned scratch explicitly to the depthwise operator. The wrapper
checks buffer capacities and vendor indexing bounds before setting the
scratch pointer and executing each batch. Recognize depthwise layout
boundaries in strict export.

Validated 214 Python tests across focused and regression runs, all 27
ESP32-S3 emulator cases, and lintrunner. Shared model cases cover vendor
SIMD and C dispatch, channel multipliers, rectangular kernels, batches,
float users, shared bias, repeated inference, and portable fallback.
Native checks also cover undersized scratch and ANSI zero-byte scratch.

Authored with OpenAI Codex.
Exercise a valid depthwise convolution that passes lowering's bounds but is rejected by the sizing binding's more conservative arithmetic guard. Verify portable numerical behavior and serialization through the common scratch-rejection fallback.

Validated 45 host depthwise and convolution-fallback tests with freshly built sizing bindings.

Authored with OpenAI Codex.
Reject output windows that extend beyond the padded input before passing dimensions to ESP-NN. This prevents inconsistent operator arguments from overflowing vendor scratch-size arithmetic or reading beyond padded storage.

The ESP32-S3 emulator rejects independently corrupted height and width strides at the new kernel check. Three normal padded, strided, and channel-multiplier cases continue to pass.

Authored with OpenAI Codex.
Keep S3 sizing-bound tests explicitly on S3 while device validation follows the selected target. Skip the undersized-scratch check for kernels that need no scratch and locate the invalid-window diagnostic in the selected chip and kernel-mode directory.

Authored with OpenAI Codex.
Require compute coverage for the supported depthwise recipe while checking its reported layout copies and serialized program. Keep strict rejection of unsupported dilation.

Authored with OpenAI Codex.

This branch was previously deployed

1 inactive deployment
cadence — 95a522c4 Deployed Nov 23, 2026 by rascani via hifi-op-test / hifi4 #40393
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