Skip to content

dnn: fix the step bookkeeping of the reduce inner projection - #30108

Merged
abhishek-gola merged 1 commit into
opencv:5.xfrom
officialarghya29:fix/dnn-reduce2-inner-steps
Oct 6, 2026
Merged

abhishek-gola merged 1 commit into
opencv:5.xfrom
officialarghya29:fix/dnn-reduce2-inner-steps

Conversation

@officialarghya29

Copy link
Copy Markdown
Contributor

Pull Request Readiness Checklist

  • I agree to contribute to the project under Apache 2 License.
  • To the best of my knowledge, the proposed patch is not based on code under GPL or another license that is incompatible with OpenCV
  • The PR is proposed to the proper branch (5.x)
  • There is a reference to the original bug report and related work (no pre-existing report; the two conformance cases below were already denied as "Wrong answer", see Problem)
  • There is accuracy test, performance test and test data in opencv_extra repository, if applicable (the conformance data already exists, the new layer test needs no data)
  • The feature is well documented and sample code can be built with the project CMake

Problem

A Reduce* over three or more axes accumulates the wrong elements, except for the first output
slice:

ReduceMean(axes=[0,2,3], keepdims=1) on 3x3x3x3 ONNX Runtime 1.30 before
per-channel means 0.4448 0.4903 -0.5875 ... 0.4446 0.1235 -0.4050 ...

That is exactly the shape of the ONNX conformance case test_mvn_expanded (a
MeanVarianceNormalization decomposed into primitives), which is in the parser denylist with the
comment Issues::Wrong answer; test_mvn_expanded_ver18 is denied without a reason and fails the
same way.

Root cause

ReduceInvoker walks the reduced sub-block with an odometer over every reduced axis but the
innermost one (projected_steps). On a carry the step of the axis that just wrapped is assigned
instead of being accumulated, so the steps of all the axes above it are dropped:

++projected_indices[last_reduced_axis - 1];
current_step += steps_src[reduced_axes[last_reduced_axis - 1]];
for (int j = last_reduced_axis - 1; j > 0; --j) {
    if (projected_indices[j] < shape_src[reduced_axes[j]])
        break;
    projected_indices[j] = 0;
    ++projected_indices[j - 1];
    current_step = steps_src[reduced_axes[j - 1]];   // drops every digit above j - 1
}

With axes=[0,2,3] on a 3x3x3x3 input (steps 27 9 3 1) the projection came out as
0 3 6 27 30 33 27 30 33 where it has to be 0 3 6 27 30 33 54 57 60, i.e. the last three output
slices re-read the elements of the second one. The first slice is never affected, which is why the
incorrect results looked plausible and went unnoticed.

The unprojected-axis loop directly below does the same accounting correctly (it subtracts the step
of the wrapped axis and adds the step of the axis it carries into), which is the form the projected
loop now uses:

    projected_indices[j] -= shape_src[reduced_axes[j]];
    current_step -= shape_src[reduced_axes[j]] * steps_src[reduced_axes[j]];
    ++projected_indices[j - 1];
    current_step += steps_src[reduced_axes[j - 1]];

This also matters for reductions with fewer than three axes indirectly, because the inner
projection drives the outer (unprojected) steps through the same origin/projected_steps
pairing.

Tests

  • Layer_Test_Reduce.NonContiguousAxes (new, test_layers.cpp): Reduce2 with axes=[0,2,3] and
    axes=[0,1,3] on a 3x3x3x3 input, MEAN and SUM, compared against a reference computed in
    the test. Fails on the previous code, passes now.
  • test_mvn_expanded and test_mvn_expanded_ver18 are removed from
    test_onnx_conformance_layer_parser_denylist.inl.hpp; both fail before this change and pass with
    it (maxabs 2.4e-7 against the conformance data). test_mvn (the operator itself, still
    unimplemented) stays denied, with its reason corrected to the real one.

Validation

  • opencv_test_dnn: 5202/5202 with this branch alone (5201 before it), and two fewer skipped
    conformance tests than before.

  • Randomised differential sweep against numpy (scratch/fuzz_reduce.py, 900 combinations of rank
    2-5, random axis sets, keepdims, and MEAN/SUM/MAX/MIN/PROD/L1/L2/SUM_SQUARE):
    0 mismatches. The same sweep on the previous code reports 9 mismatches out of the first 200
    combinations, e.g.

    VALUE shape=(2,3,3,3,1) axes=[0,2,3,4] keepdims=0 op=SUM | maxabs=5.802e+00
    VALUE shape=(3,3,2,1,3) axes=[1,2,3]    keepdims=0 op=PROD | maxabs=9.310e-02
    
  • Not tested: Windows/MSVC, Clang, ARM/RISC-V, CUDA/OpenVINO/OpenCL targets (no access to those
    configurations here). The change is scalar index arithmetic in the CPU fallback path of
    Reduce2, which is also what the backends fall back to.

  • Known, deliberately not addressed here: reducing every axis with keepdims=0 asks for a
    rank-0 output and still fails with output #0 changed during forward(): inferred shape [<scalar>] (the shape check compares MatShape::scalar() from getMemoryShapes with
    MatShape{1} from forward). That is a separate problem in the same layer, left for a follow-up
    so this change stays verifiable on its own; the sweep skips exactly those combinations.

@asmorkalov

Copy link
Copy Markdown
Contributor

@abhishek-gola please review.

@asmorkalov asmorkalov added this to the 5.1 milestone Sep 30, 2026
@asmorkalov
asmorkalov requested a balanced review from Copilot October 2, 2026 12:14

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟢 Approval recommended

The focused bookkeeping correction matches the established unprojected-axis logic and is covered by targeted regression and conformance tests.

Review effort: Balanced
Findings: None

What changed in this PR

Fixes incorrect element offsets in DNN Reduce2 reductions spanning three or more axes.

Changes:

  • Corrects projected-axis carry bookkeeping.
  • Adds regression coverage for non-contiguous reductions.
  • Re-enables passing MVN-expanded ONNX conformance tests.
File Description
modules/​dnn/​src/​layers/​reduce2_layer.cpp Corrects offset calculation during odometer carries.
modules/​dnn/​test/​test_layers.cpp Adds SUM and MEAN regression tests.
modules/​dnn/​test/​test_onnx_conformance_layer_parser_denylist.inl.hpp Re-enables fixed conformance cases and updates the MVN reason.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@SavyaSanchi-Sharma

Copy link
Copy Markdown
Contributor
[  FAILED  ] 1 test, listed below:
[  FAILED  ] Test_ONNX_conformance.Layer_Test/test_mvn_expanded_ver18_NGRAPH_CPU, where GetParam() = (test_mvn_expanded_ver18, NGRAPH/CPU)

 1 FAILED TEST
  YOU HAVE 1 DISABLED TEST

please update test_onnx_conformance_layer_filter__openvino.inl.hpp

Comment thread modules/dnn/test/test_layers.cpp Resolved
@SavyaSanchi-Sharma

Copy link
Copy Markdown
Contributor

cc: @abhishek-gola

Reducing over more than two axes walks the reduced sub-block with an odometer
over all of them but the innermost one. When an index carried into the next
axis, the step of that axis was assigned instead of being accumulated, so the
steps of every axis above the one that wrapped were lost and the corresponding
elements were read again and again:

    axes [0, 2, 3] on a 3x3x3x3 input, shape (3,3,3,3), steps (27, 9, 3, 1)
      projected steps: 0 3 6 27 30 33 27 30 33     <- should end in 54 57 60

Only the first output slice happened to be right, because the carry that
introduced the wrong step is the one that moves to the second one.

The same accounting exists for the unprojected axes just below, which
subtracts the step of the wrapped axis and adds the step of the axis it carries
into; the projected loop now does the same. This fixes test_mvn_expanded and
test_mvn_expanded_ver18 (a MeanVarianceNormalization decomposed into
primitives, denied as "Wrong answer" until now) plus any model that reduces
over three or more axes, since the inner projection also feeds the unprojected
axis steps. The OpenVINO backend still answers test_mvn_expanded_ver18
incorrectly, so it is filtered in
test_onnx_conformance_layer_filter__openvino.inl.hpp.

Found by comparing against onnxruntime: 9 of 200 random (rank, shape, axes set,
keepdims, op) combinations were wrong before and none are now; the two
conformance cases above and a new layer test fail without this change.
@officialarghya29
officialarghya29 force-pushed the fix/dnn-reduce2-inner-steps branch from 4f34a7f to 8556b14 Compare October 5, 2026 16:00
@officialarghya29

Copy link
Copy Markdown
Contributor Author

@SavyaSanchi-Sharma thanks for the review. I shortened both comments and added test_mvn_expanded_ver18 with a SKIP to test_onnx_conformance_layer_filter__openvino.inl.hpp, as you suggested, so the OpenVINO conformance run is green again. The update is pushed (8556b14). @SavyaSanchi-Sharma @abhishek-gola could you please take another look when you have a moment? Thanks!

@asmorkalov

Copy link
Copy Markdown
Contributor

@SavyaSanchi-Sharma @abhishek-gola Is it ready for merge?

@abhishek-gola
abhishek-gola merged commit 59a96e4 into opencv:5.x Oct 6, 2026
29 checks passed
@sohailshk sohailshk mentioned this pull request Nov 12, 2026
6 tasks done
abhishek-gola pushed a commit that referenced this pull request Nov 13, 2026
* dnn: fix Reduce over three or more axes

Port of #30108 (5.x, reduce2_layer.cpp) to the 4.x Reduce layer.

ReduceInvoker walks the reduced block with an odometer over every reduced axis but the innermost one. On a carry it assigned the step of the next outer axis (j - 1) instead of removing the offset of the axis that wrapped and adding one step of the next. projected_steps is shared by all output elements, so once an outer reduced axis has three or more elements every output was wrong. Carry the same way as the unprojected axes below. This also makes test_mvn_expanded pass, so it is removed from the parser denylist.

* dnn: parameterize the Reduce multi-axis regression test

Pass each (sizes, axes) case to TEST_P instead of looping inside one TEST.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants