Commit Graph

2423 Commits

Author SHA1 Message Date
Shiven Solanki
4fe077ab3e Merge pull request #31142 from sshivensolanki:dnn-dft-opset20-axis
dnn: use the opset 20 default axis -2 for ONNX DFT - #31142

Fixes #31141

### Problem
Opset 20 made the `DFT` axis an optional input with default `-2`, but the importer leaves the layer on its opset 17 default `axis = 1`. So opset 20 `DFT` without an axis input transforms the wrong dim for 4-D and larger inputs.

### Fix
In `parseDFT`, set `axis = -2` when the model's opset is 20 or newer and no `axis` attribute is present (same pattern as `parseRoiAlign`).

### Tests
Added `Test_ONNX_layers.DFT_opset20_default_axis` to `test_onnx_importer.cpp`, using a `[1, 3, 4, 2]` model from opencv_extra. It fails without the fix and passes with it. The full `opencv_test_dnn` passes (9540 tests) on macOS arm64.

### Pull Request Readiness Checklist

See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request

- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
      Patch to opencv_extra has the same branch name.
- [ ] The feature is well documented and sample code can be built with the project CMake
2026-11-25 12:34:14 +03:00
Alexander Smorkalov
e8d7aa4a2f Merge pull request #31131 from sshivensolanki:dnn-einsum-uppercase-letters
dnn: fix Einsum index for uppercase subscript letters
2026-11-25 11:12:59 +03:00
Alexander Smorkalov
b8d77c769a Merge pull request #31120 from sshivensolanki/dnn-det-empty-matrix
dnn: fix Det output for 0x0 matrices
2026-11-25 09:17:41 +03:00
Alexander Smorkalov
d1abca9a89 Merge pull request #31123 from sshivensolanki:dnn-maxunpool-kernel-hw
dnn: fix MaxUnpool kernel and stride order in the ONNX importer
2026-11-24 18:08:21 +03:00
uwezkhan
7b07609d66 dnn: reject negative position ids in RotaryEmbedding gather 🤖🤖🤖 (#30511)
* dnn: reject negative position ids in RotaryEmbedding gather

* dnn: check RotaryEmbedding cache width, rotary dim and position_ids shape/type

* dnn: check RotaryEmbedding input types in getTypes, exact cache width and 4d num_heads
2026-11-24 19:22:42 +05:30
Shiven Solanki
3e3f338dde Merge pull request #31061 from sshivensolanki/dnn-trilu-tall-matrix
dnn: fix Trilu for inputs with more rows than columns

Problem
Trilu only loops over the first min(h, w) rows, so when the input has more rows than columns, the remaining rows keep their input values instead of being masked.

Fix
Loop over all h rows in forward() and remove the unused m. The existing cmin < w && num_zeros > 0 check already keeps the memset inside each row, so no other change is needed.
2026-11-24 18:50:41 +05:30
Shiven Solanki
45fed1fec6 dnn: fix Einsum index for uppercase subscript letters 2026-11-24 20:54:28 +08:00
Shiven Solanki
f9efe61f9a dnn: fix MaxUnpool kernel and stride order in the ONNX importer 2026-11-24 18:17:54 +08:00
Shiven Solanki
5dcb95b793 dnn: fix Det output for 0x0 matrices 2026-11-24 17:44:57 +08:00
Laiba Irfan
3351889ecd dnn: support allowzero attribute in ONNX Reshape (#30854)
* dnn: support allowzero attribute in ONNX Reshape

* dnn: skip reshape allowzero test for OpenVINO, specify opset range

* dnn: add Reshape2 allowzero tests for 2D legacy and block-layout paths
2026-11-24 13:41:12 +05:30
Rahul Kumar
7a3dd65ae1 dnn: fix com.microsoft Attention with a mask_index or without a bias, and Add(mask, scores) fusion 🤖🤖🤖 (#30930)
* dnn: fix masked Attention ONNX import and commutative mask-Add fusion

ONNXImporter2::parseAttention required every input after X to be constant before populating params.blobs, leaving blobs empty for dynamic masks, pushing constant masks into blobs[2], and failing on omitted or trailing empty optional inputs. AttentionLayerImpl also read bias from blobs.back() instead of blobs[1], and ModelFusionAttention::isMaskAdd hardcoded inputs[1] so Add(mask, scores) bound Attention's mask to the removed score node. Fold constant weight and bias into blobs[0..1], keep any 4th mask input on layer->inputs[1], and match score_arg in isMaskAdd.

* dnn(onnx): lower the Attention int32 mask_index with addKeyPaddingMaskBias

mask_index is an int32 0/1 padding mask, not an additive bias. Turn it
into the additive mask the layer applies, the same way
parseMultiHeadAttention does, saving and restoring node_inputs and
node_outputs around the helper.

The test loads its models from opencv_extra (same branch name) with
testONNXModels() instead of building them and the reference in code;
the first three cases now use the spec's int32 [B, S] mask.

* dnn: keep AttentionLayerImpl's blob access as on 5.x

parseAttention now always gives the layer exactly two blobs, the weight
and the bias, and the fusion passes do the same, so blobs.front() and
blobs.back() already pick them. The blobs[0]/blobs[1] change is not
needed.
2026-11-24 13:38:53 +05:30
Shiven Solanki
9c6d1ababb dnn: return an empty shape in Shape when start > end (#31011)
* dnn: return an empty shape in Shape when start > end

* dnn: apply the Shape start > end rule to the CUDA backend

* dnn: skip test_shape_start_greater_than_end in the OpenVINO filter

Problem
ShapeLayerImpl::getShapeRange asserts start_ <= end_, so Shape with start > end throws. The ONNX spec says the result should be an empty shape.

Fix
After clamping, set end_ = std::max(end_, start_) so the range has length 0. This
2026-11-24 13:36:58 +05:30
Shiven Solanki
5014b24db5 dnn: keep CV_64S precision in Resize2 nearest mode (#31036)
* dnn: keep CV_64S precision in Resize2 nearest mode

Fixes #31035

* dnn: use ptr<>() in Resize2 int64 test to fix Debug assert on 4D Mat
2026-11-24 13:04:50 +05:30
Alexander Smorkalov
ed4ee4d5b2 Merge pull request #31097 from sshivensolanki:dnn-cumsum-empty-axis
dnn: fix CumSum crash when the scan axis has length 0
2026-11-24 10:02:45 +03:00
Abhishek Gola
1056624e1c dnn: fix CumProd crash when the scan axis has length 0 (#31063)
* dnn: fix CumProd crash when the scan axis has length 0

* dnn: use Mat::empty() for the CumProd empty-input check

Return early from forwardImpl() when the input has no elements. The output already has the right empty shape. The check comes after normalize_axis(), so an out-of-range axis is still reported.
2026-11-24 10:45:03 +05:30
Abhishek Gola
eb30136494 Merge pull request #30924 from pctablet505/fix-dnn-cuda-gemm-square-transpose-5x
dnn: avoid transposing square Gemm weights in-place in initCUDA (5.x) 🤖🤖🤖
2026-11-24 09:44:47 +05:30
Shiven Solanki
150a25256c dnn: fix CumSum crash when the scan axis has length 0 2026-11-23 22:25:12 +08:00
Shiven Solanki
7f57e38b02 dnn: use Mat::empty() for the CumProd empty-input check 2026-11-23 18:58:12 +08:00
Abhishek Gola
d2c6f944cf Merge pull request #31034 from sshivensolanki/dnn-cast-uint32-uint64
dnn: support UINT32 and UINT64 targets in Cast

Map ONNX UINT32 (12) and UINT64 (13) to CV_32U and CV_64U in mapToCvDepth.
Add CV_32U and CV_64U cases to truncateFloatToInt, so float inputs truncate toward zero as ONNX requires, instead of being rounded by convertTo.
Allow CV_32U and CV_64U in the outputType parameter.
2026-11-23 09:27:12 +05:30
Abhishek Gola
e4ec28617f Merge pull request #31039 from ish1416/dnn-reduce-support-unsigned
dnn: support CV_32U and CV_64U in Reduce layers

Fix
In modules/dnn/src/layers/reduce2_layer.cpp: Add CV_32U and CV_64U to getTypes validation.
In modules/dnn/src/layers/reduce_layer.cpp: Add CV_32U and CV_64U to getTypes and typeDispatch (opDispatch<uint32_t> and opDispatch<uint64_t>).
In modules/dnn/test/test_int.cpp: Extend Test_Reduce_Int to include CV_32U and CV_64U.
In modules/dnn/test/test_layers.cpp: Add Layer_Test_Reduce_Unsigned parameterized test checking MAX, MIN, and SUM on CV_32U and CV_64U with values greater than 2^31 to verify unsigned comparison logic.
2026-11-23 09:26:18 +05:30
Shiven Solanki
36596cbeca dnn: fix CumProd crash when the scan axis has length 0 2026-11-23 08:50:36 +08:00
Abhishek Gola
2ce6479ab8 Merge pull request #31047 from sshivensolanki/dnn-range-zero-delta
dnn: reject zero delta in Range layer

Check that delta is not zero in getRangeParams() before rangeSize() is called: CV_CheckNE for the float branch and CV_CheckTrue(idelta != 0, ...) for the integer branch, since CV_CheckNE has no int64_t overload. Both forward() and getMemoryShapes() go through getRangeParams(), so both are covered.
2026-11-22 21:31:16 +05:30
Ishita Singh
4bd226ed15 dnn: support CV_32U and CV_64U in Reduce layers 2026-11-22 20:35:00 +05:30
Shiven Solanki
7e2201571d Merge pull request #31025 from sshivensolanki/dnn-onehot-uint32-bool
dnn: support CV_32U, CV_64U and CV_Bool values in OneHot

Add the missing case labels, calling the existing runKernel<uint32_t>, runKernel<uint64_t> and runKernel<bool>.
tensorToScalar could not read CV_64U tensors. It now reads them as uint64_t and writes the result without going through int64_t, so values above INT64_MAX are not cut down. The output conversion moved into a small storeScalar template, called with double, int64_t or uint64_t; the results for the other input types are unchanged.
2026-11-22 18:35:51 +05:30
Tushar Burla
f3a7576b57 dnn(onnx): add support for ONNX Col2Im operator
- Implement Col2ImLayer supporting static/dynamic output shape inference and spatial summation
- Enforce CV_32F data input and int32/int64 shape inputs in getTypes() and forward()
- Require 1-D rank and CV_64S value range-checking (rejecting > INT_MAX) for image_shape and block_shape
- Support multi-dimensional spatial blocks, dilations, pads, and strides
- Parse image and block shapes using OpenCV tensorToIntVec()
- Parallelize across batch and channels using a single parallel_for_ with batch*channel <= INT_MAX guard
- Guard wide-coordinate offsets and domain arithmetic against signed overflow
- Add unit and parameterized tests in test_layers for shape inference, type validation, empty inputs, oversized shapes, malformed ranks, coordinate bounds, malformed attributes, and 4-D spatial values
- Add Col2Im performance benchmark baseline in modules/dnn/perf/perf_col2im.cpp
- Skip Col2Im conformance tests in OpenVINO filter
- Un-denylist all 5 official ONNX conformance tests

# Conflicts:
#	modules/dnn/test/test_layers.cpp

# Conflicts:
#	modules/dnn/test/test_layers.cpp
2026-11-22 11:32:10 +05:30
Shiven Solanki
45833cc1aa dnn: reject zero delta in Range layer 2026-11-22 10:58:26 +08:00
Shiven Solanki
ad55604af8 dnn: support UINT32 and UINT64 targets in Cast 2026-11-21 19:52:12 +08:00
Shiven Solanki
c8ac3039be dnn: support CV_32U and CV_64U outputs in EyeLike 2026-11-21 18:03:13 +08:00
Shiven Solanki
fe06ceaca5 dnn: support CV_32U and CV_64U in Clip default bounds 2026-11-21 12:07:01 +08:00
Abhishek Gola
c7a8a7afbd Merge pull request #31004 from sshivensolanki/dnn-tensortoscalar-int8-uint16
dnn: read CV_8S and CV_16U correctly in tensorToScalar
2026-11-21 09:20:43 +05:30
Shiven Solanki
7410814bf7 dnn: read CV_8S and CV_16U correctly in tensorToScalar 2026-11-20 17:25:31 +08:00
Shiven Solanki
e9b03f5d0a dnn: support CV_64S and CV_Bool in Hardmax forward 2026-11-20 15:55:33 +08:00
wzy712
0946969810 dnn: add ONNX ReverseSequence layer (#30591)
* dnn: add ONNX ReverseSequence layer

- new ReverseSequenceLayer: byte-wise block copy, works for any CV type and rank >= 2
- getTypes(): accept CV_16S as well, grouped by signed/unsigned/float families
- tests: CV_16S rank-2 / rank-3 block copy, both axis layouts, int32 sequence_lens,
  out-of-range sequence_lens must throw

# Conflicts:
#	modules/dnn/test/test_layers.cpp

* dnn: simplify ReverseSequence layer and tests

Parallelize over (batch, time) pairs, take byte strides from X.step, validate sequence_lens up front and drop the redundant type whitelist. Rework the layer test to check an independent reference implementation.

* dnn: reuse tensorToIntVec in ReverseSequence layer

Read sequence_lens through the shared helper and check its element count, so lengths are narrowed once. Compare the layer test against an index-based reference instead of duplicating the layer's stride computation.

* dnn: state supported opsets and skip ReverseSequence for OpenVINO

Drop the future-opsets claim in the layer header and mark the two conformance cases as skipped for the OpenVINO backend, following the Compress operator.

* dnn: add ReverseSequence to the ONNX importer dispatcher

Register an explicit parseReverseSequence() handler instead of relying on the generic custom-layer path. Drop the constant-only layer tests and fold the sequence_lens length check into the out-of-range test.
2026-11-20 08:41:11 +05:30
Ishita Singh
81cf43c1d8 dnn: handle min > max in Clip layer and enable ONNX conformance test (#30891)
* dnn: handle min > max in Clip layer and enable ONNX conformance test

Under the ONNX specification, the Clip operator is defined mathematically as
y = min(max(x, min), max). When min > max, the operation clamps identically
to max for all input values.

Previously, ClipLayerImpl asserted minValue <= maxValue in its constructor
and actualMin <= actualMax in forward, causing assertion failures on valid
ONNX models with min > max. Additionally, the adjacency graph fusion interpreter
checked a < min first, returning min instead of max.

This commit:
1. Removes the min <= max assertions in ClipLayerImpl constructor and forward,
   allowing ONNX-conforming evaluation where min > max clamps to max.
2. Updates FusionEltwiseOp::CLAMP in AdjacencyGraph interpreter to use
   std::min(std::max(a, n.scalar), n.scalar2), matching the ONNX evaluation order.
3. Removes test_clip_min_greater_than_max from the layer parser denylist.
4. Adds unit tests covering static and dynamic min > max clipping.

* dnn: filter test_clip_min_greater_than_max for OpenVINO backend

* dnn(test): address review comments on Clip min > max tests and fusion coverage
2026-11-20 08:22:26 +05:30
Shiven Solanki
e207b496e4 Merge pull request #30954 from sshivensolanki/dnn-nms-batched-negative-coords
dnn: fix NMSBoxesBatched class offset for negative coordinates - #30954

Fixes #30953

### Problem

`NMSBoxesBatched` shifts each class by `class_id * (max_coord + 1)`, which only separates the classes when all coordinates are non-negative. With boxes that start at negative coordinates, the shifted classes can still overlap, and a box gets suppressed by a box of a different class.

### Fix

Also track the smallest top-left coordinate, `min_coord`, and shift by `class_id * (max_coord - min_coord + 1)`, which is the full coordinate range plus one. `min_coord` starts at `0`, so the shift is unchanged when all coordinates are non-negative, and existing results stay the same.

### Tests

Added `BatchedNMS.NegativeCoordinates`: two boxes of different classes that only touch at one corner, one of them at negative coordinates. Before the fix only 1 box is kept; after the fix both are kept. The full `opencv_test_dnn` passes.

### Pull Request Readiness Checklist

See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request

- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
      Patch to opencv_extra has the same branch name.
- [x] The feature is well documented and sample code can be built with the project CMake
2026-11-19 10:45:26 +03:00
pctablet505
f400b8e220 dnn: avoid transposing square Gemm weights in-place in initCUDA
GemmLayerImpl::initCUDA() called cv::transpose(B, B) on a shallow view of blobs[0]. When B is square (K == N) and transB is false, cv::transpose reuses the buffer in-place, mutating blobs[0] on the first forward() and transposing it back on a subsequent batch-size reshape. Transpose into a separate Mat before constructing InnerProductOp.
2026-11-18 19:56:37 +05:30
Shiven Solanki
6158022f07 dnn: fix Hardmax max index when no element exceeds lowest()
Start the search from the first element of each slice instead of numeric_limits<T>::lowest() at index 0, so slices where every value equals the lowest value (e.g. all-zero uint8, all -inf float) get their 1 in the right place. Fixes #30903
2026-11-18 15:31:22 +08:00
Abhishek Gola
80db42de85 Merge pull request #30887 from abhishek-gola/fix/sphinx-docs-warnings
Fix Sphinx documentation warning sources
2026-11-18 08:49:36 +05:30
Alexander Smorkalov
e04069c2b7 Merge pull request #30709 from peters:dnn/cuda102-reduce
dnn: fix CUDA 10.2 build of N-D reduce kernels 🤖🤖🤖
2026-11-17 12:05:34 +03:00
Abhishek gola
315ddafc6c Fix Sphinx API targets, navigation and documentation warnings 2026-11-16 20:13:32 +05:30
Muhammad Usman Mateen
d87ac83e05 dnn: compute LogSoftmax without taking the log of softmax (5.x) 🤖🤖🤖 (#30816)
* dnn: test LogSoftmax far below the maximum

LogSoftmax must give x - max - log(sum(exp(x - max))) for values about 104 or more below the row maximum, where exp underflows in float32. Covers a short row and one long enough for the SIMD loops, on the CPU and OpenCL targets. Port of the test from #30545.

* dnn: compute LogSoftmax without taking the log of softmax

logSoftmax() took the log of the softmax output, so elements whose exp(x - max) underflows came out as -inf. The dispatched softmax kernel already has the row maximum and the sum of exp((x - max) * scale), so softmax() takes a logSoftmax flag and the log path writes (x - max) * scale - log(sum) directly.

The OpenCL kernels had the same problem with LOG_SOFTMAX: they now keep x - max, add up exp(x - max) and return x - max - log(sum). This covers the generic kernels in softmax.cl and the subgroup kernels in softmax_loss.cl.

Port of #30545 to 5.x.
2026-11-15 12:50:26 +05:30
Kaustubh Arora
998f72949d dnn: keep INT4/UINT4 QuantizeLinear off the AVX2 per-tensor fast path (#30616)
* dnn: keep INT4/UINT4 QuantizeLinear off the AVX2 per-tensor fast path

The x86 AVX2 path for per-tensor float to int8/uint8 returns before the
4-bit saturation added in #30596, so INT4/UINT4 outputs were still
clamped to the 8-bit range there. Skip it for 4-bit output and add a
per-tensor INT4/UINT4 test that reaches that path on x86.

* dnn: clamp INT4/UINT4 inside the AVX2 per-tensor QuantizeLinear path

Pass the output range into the AVX2 kernel instead of skipping it, so
per-tensor INT4/UINT4 keeps the vectorized, parallel path; the kernel
already clamps in float before converting. The post-pass from #30596
is only reached by the generic path now. Widen the regression test to
35 elements so it covers the 8-lane loop and the scalar tail on x86.

* dnn: drop the PR reference from the INT4 QuantizeLinear test comment

---------

Co-authored-by: Kaustubh Arora <arorakaustubh681@gmail.com>
2026-11-13 16:06:37 +05:30
uwezkhan
dfbf43df29 dnn: check weight, bias and past_state in CausalConvWithState 🤖🤖🤖 (#30628)
* dnn: check weight, bias and past_state in CausalConvWithState

Check the ONNX shapes of weight [C, 1, k], bias [C] and past_state [B, C, k - 1] against the input in getMemoryShapes, and require them to be float in forward, since the kernel indexes all three by input channel and reads them as float.

* dnn: check CausalConvWithState input types before fp16 conversion, require rank-1 bias
2026-11-09 12:23:45 +05:30
Peter Rekdal Khan-Sunde
bdb7f63d7d dnn: fix CUDA 10.2 build of N-D reduce kernels
CUDA builds below CUDA 11 are configured with --std=c++11, where
std::conditional_t is unavailable. Use std::conditional<>::type so the
N-D reduce kernels compile with CUDA 10.2. No behavior change.
2026-11-07 09:55:10 +01:00
Savya Sanchi Sharma
0f51622bac Merge pull request #30439 from SavyaSanchi-Sharma:layers
dnn(cuda): transformer layer coverage and CUDA Graph replay on the new engine - #30439

  Follow-up to #30415 (ResNet layer coverage and cuDNN JIT conv/pooling on the new engine). Adds CUDA support on the new DNN engine
  for the layers transformer models need, and brings the CUDA path to parity with ONNX Runtime.
**Companion PR** opencv/opencv_extra#1448

  **Changes**
  - CUDA execs for Attention, Cast, ConstantOfShape, Expand, Gather, Not, Reduce, Shape, Slice, Softmax, Tile, Transpose, Concat,
  Gelu, LayerNormalization, MatMul, Split, Squeeze, Unsqueeze and the element-wise activations.
  - A graph with static shapes is recorded as one CUDA Graph on the second `forward()` and replayed from then on.
  - The cuDNN JIT convolution reads NCHW buffers in place; NHWC staging is kept only for FP16 grouped convolutions.
  - TF32 for cuBLAS GEMMs (`OPENCV_DNN_CUDA_ALLOW_TF32`), FP32 accumulation for FP16 GEMMs
  (`OPENCV_DNN_CUDA_FP16_HALF_ACCUMULATE`), and fused MatMul/Gemm post-ops.
  - Batch-broadcast MatMul and Shape are safe to capture in a CUDA Graph; the unused pointer-array `cublas::gemmBatched` is
  removed.
  - Tests: `forward()` runs three times on batch-broadcast MatMul and Shape models; `MatMul_init_bcast` runs on CUDA again;
  `AttentionSharedShapeReshape` uses the FP16 default tolerance on CUDA FP16.
  - Perf: new CUDA-only `*_CUDA_pinned` tests pin the input shapes.

  **Performance** (ms, median of 50, FP32 with TF32, RTX PRO 6000 Blackwell, idle GPU)

| Model | CPU | CUDA (cuDNN JIT) | CUDA (full cuDNN) | ORT 1.31 CUDA EP |
  |---|---|---|---|---|
  | ResNet-50 | 8.02 | 0.80 | 0.80 | 0.88 |
  | ResNet-18 | 3.27 | 0.44 | 0.44 | 0.48 |
  | MobileNetV2 | 1.99 | 0.28 | 0.27 | 0.40 |
  | DenseNet-121 | 17.42 | 1.48 | 1.58 | 1.58 |
  | EfficientNet-Lite4 | 5.03 | 0.53 | 0.54 | 0.73 |
  | ViT-B/32 | 11.06 | 1.02 | 1.02 | 0.95 |
  | ViT-Base/16 | 24.38 | 1.16 | 1.17 | 1.13 |
  | DeiT-Tiny | 4.58 | 0.65 | 0.65 | 0.68 |
  | MobileViT-XS | 6.93 | 0.72 | 0.72 | 0.77 |
  | YOLOv3 | 47.21 | 2.60 | 2.59 | 2.72 |
  | YOLOv4 | 109.38 | 3.58 | 3.61 | 4.18 |
  | YOLOv4-tiny | 7.31 | 0.64 | 0.64 | 0.66 |
  | BEiT-Base | 25.30 | 1.24 | 1.24 | 1.19 |
  | BERT | 10.00 | 0.97 | 0.97 | 0.99 |
  | SigLIP | 41.14 | 2.09 | 2.09 | 2.44 
### Pull Request Readiness Checklist

See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request

- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [ ] The PR is proposed to the proper branch
- [ ] There is a reference to the original bug report and related work
- [ ] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
      Patch to opencv_extra has the same branch name.
- [ ] The feature is well documented and sample code can be built with the project CMake
2026-11-03 10:29:32 +03:00
Tushar Burla
ee27ba2059 dnn(onnx): enable ONNX AveragePool with dilations conformance tests
- Accept plural attribute names (kernel_shape, strides, dilations, pads) in AveragePoolLayer
- Un-denylist 6 official ONNX AveragePool dilation conformance tests in parser denylist
- Conformance tests verified on CPU: 2D and 3D dilated average pooling passing (6/6)
2026-11-02 18:42:08 +05:30
Abhishek Gola
3abf366a38 Merge pull request #30596 from Kaustubh1235/dnn-quantize-int4
dnn: saturate QuantizeLinear INT4/UINT4 output to the 4-bit range
2026-10-31 12:57:54 +05:30
Abhishek Gola
b45d4bdd89 Merge pull request #30268 from omrope79/dnn-vision-perf
dnn: fast-path optimizations for LayerScale folding, strided/9-tap Conv, and block-layout Split
2026-10-31 12:56:41 +05:30
Arghya Bose
490dc83542 Merge pull request #30105 from officialarghya29:fix/dnn-resize-scales-downsample
dnn: derive the Resize scales from the given scales, not from the shapes - #30105

### Pull Request Readiness Checklist

- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch (5.x)
- [x] There is a reference to the original bug report and related work (no pre-existing report; found by differential testing against ONNX Runtime, see *Problem*)
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable (companion PR: opencv/opencv_extra#1455)
- [x] The feature is well documented and sample code can be built with the project CMake

---

### Problem

`Resize` resamples with a step of `in/out` when the target size comes from the `scales` input,
but ONNX defines the step along an axis as `1/scale`. The two agree only while `in*scale` is an
integer, which is not the common case. A `1x2x4x5` input with `scales=[1,1,0.5,0.5]` produces a
`1x2x2x2` output, so the step along `W` is `2` (as `1/0.5`) and not `2.5` (as `5/2`):

| `Resize(nearest=False, mode=linear, coordinate_transformation_mode=half_pixel)` | ONNX Runtime 1.30 | before |
|---|---|---|
| `1x2x4x5` input, `scales=0.5`, first output row | `0.49208999 -0.11570000` | `0.28683999 -0.48815000` |

The error is not restricted to downscaling. Any non-integral `in*scale` is affected, e.g. a
7-wide input with `scale=1.5` (output 10) was sampled at `0.7` instead of `2/3`. `cubic`,
`pytorch_half_pixel`, `half_pixel_symmetric`, `tf_half_pixel_for_nn` and `asymmetric` are all
affected; the antialias filter support is stretched the same way, producing a `2.5`-pixel-wide
filter where `1/scale` asks for `2`.

### Root cause

A constant `scales` input is folded into the `zoom_factor_x`/`zoom_factor_y` layer parameters by
`ONNXImporter2::parseResize2` (`ninputs` is set to 1). `Resize2LayerImpl::forward` therefore never
saw the tensor and took the step from `updateOutSizeAndScale`, which derives it from the shapes:

```cpp
if (sizes.empty() && !scales.empty() && halfPixelCenters)      // never true for folded scales
    scaleHeight = 1.f / scales[hIdx];
...
scaleHeight = float(inpShape[2]) / outHeight;                  // in/out instead of 1/scale
```

The antialias branch had the same problem for its filter support, which it also read from
`scales` (empty in the folded case) or fell back to `outShape/inpShape`.

### Solution

The scales are resolved once, from the `scales` input or from the folded `zoom_factor_*`, and both
the step and the antialias filter use that value:

```cpp
if (sizes.empty() && !alignCorners && onnxScaleH > 0 && onnxScaleW > 0 &&
    coordTransModeE != CoordTransMode::TF_CROP_AND_RESIZE)
{
    scaleHeight = 1.f / onnxScaleH;
    scaleWidth  = 1.f / onnxScaleW;
}
```

`align_corners` keeps the step `updateOutSizeAndScale()` derives from the shapes, `(in - 1) / (out - 1)`
with the integer output length, which is what the operator definition and onnxruntime use:

| `Resize(align_corners, mode=linear)` | ONNX Runtime 1.29 | this PR |
|---|---|---|
| `1x1x2x4`, `scales=0.6`, output `1x1x1x2` | `1 4` | `1 4` |
| `1x1x2x4`, `scales=0.6`, output `1x1x3x3`, `mode=cubic` | `1 2.5 4 7 8.5 10 13 14.5 16` | same |

Two stored conformance references still carry the value produced by the ONNX reference
implementation while it divided by the unrounded `input * scale` ([onnx/onnx#8495](https://github.com/onnx/onnx/issues/8495)).
They are regenerated from onnxruntime 1.29 in opencv/opencv_extra#1455, which is what
`test_resize_downsample_scales_{linear,cubic}_align_corners` then compares against.

`tf_crop_and_resize` ignores the step entirely (its grid comes from the roi) and is untouched.

### Tests

Three accuracy tests in `modules/dnn/test/test_layers.cpp`, all on the folded-scale path with an
input whose `in*scale` is not integral, and each fails on the previous code:

| test | covers |
|---|---|
| `Layer_Test_Resize.downscale_uses_given_scales` | step = `1/scale` for `half_pixel`, bilinear |
| `Layer_Test_Resize.antialias_downscale_uses_given_scales` | antialias filter of support `1/scale` |
| `Layer_Test_Resize.align_corners_downscale` | step = `(in - 1) / (out - 1)` and exact corners |

The references are built from the operator definition: `src = (dst + 0.5)/scale - 0.5` for
`half_pixel`, the ONNX antialias triangle filter for the second, and `src = dst * (in - 1)/(out - 1)`
for `align_corners`.

### Validation

- `opencv_test_dnn`: 5204/5204, no regressions.
- `Test_ONNX_conformance.Layer_Test/test_resize_*`: 40/40 with opencv/opencv_extra#1455 applied,
  including the antialias and `half_pixel_symmetric` cases that were already green.
- Differential sweep against ONNX Runtime 1.29/1.30 CPU: the failing `Resize` configurations
  (`linear`/`cubic`, 6 coordinate transformation modes, `antialias`, `cubic_coeff_a` and
  `exclude_outside` combinations) now agree; every other case in the sweep is unchanged.
- Not tested: Windows/MSVC, Clang, ARM/RISC-V, CUDA/OpenVINO/OpenCL targets (no access to those
  configurations here). The patch only changes which scale the CPU kernels are given; the
  `scaleWidth`/`scaleHeight` members are not consumed by the CUDA/CANN node builders, which keep
  using `outHeight`/`outWidth` and the coordinate mode flags.
2026-10-30 15:08:42 +03:00
Abhishek Gola
fe97300989 dnn: keep an unaligned channel Split on the plain tensor, use cv::max in the test relu helper
Signed-off-by: Abhishek Gola <abhishek.gola@bigvisionllc.com>
2026-10-30 14:02:18 +05:30