Commit Graph

2455 Commits

Author SHA1 Message Date
Abhishek Gola
085c194218 Merge pull request #31279 from ish1416/fix-flatten-axis-stale-4x
FlattenLayerImpl::finalize previously overwrote _startAxis and _endAxis in place with normalize_axis(..., numAxes) for the rank of the first input. Because end_axis defaults to -1 (and axis can also be negative), this permanently replaced relative negative axes with positive indices bound to the first input rank.

Reusing the same Flatten layer with an input of a different rank then failed in two ways:

Increasing rank (e.g., default axis=1, end_axis=-1: 3D [2, 3, 4] followed by 4D [2, 3, 4, 5]): silently flattened only axes [1, 2] and returned shape [2, 12, 5] instead of [2, 60].
Decreasing rank (e.g., 4D [2, 3, 4, 5] followed by 3D [2, 3, 4]): threw an assertion error in normalize_axis because the stale _endAxis = 3 was out of range for a 3D input.
Fix
Keep _startAxis and _endAxis unmodified in FlattenLayerImpl::finalize, while still validating the normalized axis range (0 <= startAxis <= endAxis < numAxes).
All backends already handle raw axis attributes cleanly: getMemoryShapes, initCann, and initNgraph normalize _startAxis and _endAxis into local variables, and forward, forward_ocl, and initCUDA operate directly on the output shapes.
2026-12-01 19:21:27 +05:30
Sohail Shaikh
94a5d75358 dnn: fix int8 depthwise 3x3 convolution with dilation and small heights (#31229)
* dnn: fix int8 depthwise 3x3 convolution with dilation and small heights

The first output column of each row read the input samples at 0 and dilation_w instead of dilation_w - pad_left and 2*dilation_w - pad_left, and with a small height only the top taps were skipped, so the bottom taps read the row below the input. Same change as in the float kernels, applied to the int8 kernels; adds an accuracy test against a direct computation.

* dnn: test int8 depthwise edge cases through the AVX2/LASX vector loop

The test widths 20 and 33 left fewer than 32 outputs, so only the scalar
code of the AVX2 and LASX kernels was run. Use widths 20, 40 and 71 so
that the 32-output vector loop (stride 1, and stride 2 with dilation_w 1)
and the scalar tail both run for the edge configurations.
2026-12-01 15:48:46 +05:30
Ishita Singh
ac7d331a79 dnn: keep Flatten axis attributes unchanged in finalize
FlattenLayerImpl::finalize previously overwrote _startAxis and _endAxis
with normalize_axis(..., numAxes) for the rank of the first input.
Since end_axis defaults to -1 (and axis can also be negative), this
replaced relative negative indices with positive indices bound to the
first input rank.

Reusing the same Flatten layer on an input of a different rank then:
- flattened the wrong range of dimensions when rank increased (e.g.
  [2, 3, 4, 5] flattened to [2, 12, 5] instead of [2, 60] for default
  axis=1, end_axis=-1), or
- triggered an assertion failure in normalize_axis when rank decreased
  (e.g. stale end_axis=3 on a 3D input).

getMemoryShapes, initCann, and initNgraph already normalize _startAxis
and _endAxis locally, and forward/forward_ocl/initCUDA use the output
shapes directly. Keep _startAxis and _endAxis unchanged in finalize
while still validating the normalized axis range.
2026-12-01 13:49:15 +05:30
Ishita Singh
b1e9563dd6 dnn: keep the GatherElements axis attribute unchanged in finalize
GatherElementsLayerImpl::finalize previously normalized the axis attribute
by overwriting this->axis with normalize_axis(axis, data.dims).
When the layer was created with a negative axis (such as -1, supported by
the ONNX GatherElements specification), this replaced the relative index
with a positive index fixed to the rank of the first input.

Subsequent evaluations on an input of different rank on the same layer then:
- evaluated GatherElements along the wrong axis (e.g. axis 1 instead of axis 2
  when moving from a 2D tensor to a 3D tensor), leading to silent data corruption, or
- triggered an assertion failure in normalize_axis (e.g. axis 2 on a 2D tensor
  when moving from a 3D tensor to a 2D tensor).

Fix this by keeping this->axis unmodified and storing the normalized axis
separately for execution. Add regression tests covering both decreasing and
increasing rank on the same GatherElements layer instance.
2026-11-30 19:25:45 +05:30
Ishita Singh
e55e631516 dnn: keep the TopK axis attribute unchanged in finalize
TopKLayerImpl::finalize previously normalized the axis attribute by
overwriting this->axis with normalize_axis(axis, input_shape.size()).
When the layer was created with a negative axis (such as the default -1),
this replaced the relative index with a positive index fixed to the rank
of the first input.

Subsequent runs on an input of different rank then either:
- evaluated TopK along the wrong axis (e.g. axis 1 instead of axis 2
  when moving from a 2D tensor to a 3D tensor), or
- triggered an out-of-range assertion in getMemoryShapes (e.g. axis 2
  on a 2D tensor when moving from a 3D tensor to a 2D tensor).

Fix this by keeping this->axis unmodified and storing the normalized axis
separately for execution. Add unit tests for both increasing and decreasing
rank inputs on the same TopK layer instance.
2026-11-30 16:14:05 +05:30
Dmitry Kurtaev
1972259d2b Fix RotatedRest NMS bug 2026-11-29 20:41:14 +03:00
Shiven Solanki
d53f83e34a dnn: fix Einsum index for uppercase subscript letters 2026-11-25 17:11:00 +08:00
Abhishek Gola
572449ce97 Merge pull request #30923 from pctablet505/fix-dnn-cuda-gemm-square-transpose
dnn: avoid transposing square Gemm weights in-place in initCUDA 🤖🤖🤖
2026-11-24 19:25:26 +05:30
Abhishek Gola
93bb48ad50 Merge pull request #30961 from kazisufiyan-k2/python-typing-dnn-layerid
python: fix LayerId typing alias referencing missing cv2.dnn.DictValue
2026-11-20 08:30:15 +05:30
Abhishek Gola
a2506f124a Merge pull request #30948 from pctablet505/fix-dnn-cpu-norm-variance
dnn: fix CPU MVN, LayerNorm, InstanceNorm and GroupNorm outputs for inputs with a large mean 🤖🤖🤖
2026-11-19 21:39:55 +05:30
Rahul Kumar
9cef898938 dnn: repack the convolution after a reshape or a fusion change 🤖🤖🤖 (#30866)
* dnn: repack the convolution when SAME padding changes after a reshape

* dnn: rebuild the packed convolution in every finalize()

forward() packs fastConvImpl with the pads and the Winograd choice that
finalize() computes, and with weightsMat, into which fuseLayers() may
still fold BatchNorm. finalize() kept the pack whenever the Winograd
choice was unchanged, so a SAME convolution kept the old padding after a
reshape, and a convolution kept BatchNorm folded in after
enableFusion(false). Reset it in every finalize(), as convolutionOp is.

Also print the target as int in the test message (-Wsign-promo).

* dnn: drop the OpenCL case from the reshape test

The OpenCL path never uses fastConvImpl, so the case passed on 4.x too.
2026-11-19 19:16:03 +05:30
Kazi Sufiyan
2603b839cb python: fix LayerId typing alias referencing missing cv2.dnn.DictValue
The generated cv2/typing/__init__.py defined LayerId as cv2.dnn.DictValue.
This line runs on every "import cv2", so if cv2.dnn.DictValue is not
available the whole import fails with AttributeError.

Net::Impl::getLayerId(DictValue&) accepts only an integer layer index or
a string layer name and asserts for anything else, so describe LayerId
as Union[int, str]. This also removes the runtime dependency on cv2.dnn
from the typing module.

Add a test that checks the generated cv2.typing.LayerId alias.
2026-11-19 08:58:07 +00:00
Muhammad Usman Mateen
19672eb03f Merge pull request #30842 from usmanmateen/fix/onnx-avgpool-count-include-pad
dnn: read count_include_pad in the ONNX AveragePool importer 🤖🤖🤖 - #30842

Fixes #30834

`parseAveragePool` in the 4.x ONNX importer chose `ave_pool_padded_area` from the model's `producer_name` only (`framework_name == "pytorch"`) and ignored the node's `count_include_pad` attribute. PyTorch models with `nn.AvgPool2d(..., padding=p, count_include_pad=False)` (PoolFormer, timm Inception-v4 and Inception-ResNet-v2) therefore divided border windows by the full kernel area, and non-PyTorch models with `count_include_pad=1` left the padding out.

The importer now reads `count_include_pad` and falls back to the old producer-based default when the attribute is missing, the same way the 5.x importer does. Models without the attribute behave as before.

Tests: `test_averagepool_2d_pads_count_include_pad` and `test_averagepool_2d_precomputed_pads_count_include_pad` come off the `opencv_all` conformance denylist. Without the importer change they fail on OCV/CPU, OCV/OCL and OCV/OCL_FP16 (normInf 1.568 and 12.16), and with it they pass. Their test data is already in `opencv_extra`.

`Test_ONNX_layers.AveragePooling_exclude_pad` covers the reported case: a PyTorch-exported `nn.AvgPool2d(3, stride=1, padding=1, count_include_pad=False)`, where the explicit `count_include_pad=0` has to override the PyTorch default. The model is in opencv/opencv_extra#1466. Without the importer change the test fails on OCV/CPU, OCV/OCL and OCV/OCL_FP16 (normInf 0.3855), and with it the test passes.

Tested on Ubuntu 24.04 (WSL2), x86-64, GCC 15.2.0, Release, `WITH_OPENCL=ON`, OpenCL through PoCL on the CPU. With and without the patch, I ran the `opencv_test_dnn` tests matching `*averagepool*:*AvePool*:*AveragePool*:*Pooling*:*pool*:Test_ONNX_conformance.*:Test_ONNX_layers.*`. Both runs passed the same 4137 tests, and the only difference is that the six re-enabled cases run (and pass) instead of being skipped. The repro from the issue prints all ones after the fix, matching PyTorch.

### 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-19 08:44:27 +03:00
pctablet505
5fe3daad9c dnn: fix CPU normalization outputs for inputs with a large mean
MVN, LayerNormalization, InstanceNormalization and GroupNormalization took
the variance of each row as E[x^2] - E[x]^2 in float. When the mean is large
against the spread the two terms cancel: from about 1000 standard deviations
the variance comes out as 0 and the outputs are scaled by 1/sqrt(eps).

Keep the one-pass result for ordinary rows. When mean^2 > 64 * var, measure
the row again from d = x - mean, summed in double: mean += E[d],
var = E[d^2] - E[d]^2.
2026-11-18 20:54:52 +05:30
pctablet505
6b961342ca 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:32 +05:30
Mohammad Sohail Shaikh
d73b2f9c87 dnn: fix Reduce over three or more axes (#30781)
* 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.
2026-11-13 17:21:33 +05:30
Muhammad Usman Mateen
efe734517f dnn: compute LogSoftmax without taking the log of softmax 🤖🤖🤖 (#30545)
* 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. See #30544.

* 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 softmax kernel already has the row maximum and the sum of exp(x - max), so the log path now writes (x - max) - log(sum) directly. Subtracting max first keeps rows of large, close values exact, as in test_logsoftmax_large_number.

Fixes #30544

* dnn: pass the LogSoftmax flag to softmax() instead of a separate function

Address review: softmax() takes a logSoftmax flag with a default of false, and logSoftmax() calls it with true.

* dnn: run the LogSoftmax underflow test on the OpenCL targets

The test now runs for every target of the OpenCV backend, and uses the default FP16 thresholds for the FP16 targets.

* dnn: compute LogSoftmax in the OpenCL kernels without taking the log of softmax

With LOG_SOFTMAX, the kernels kept exp(x - max) and returned log(exp(x - max) / sum), which is -inf once exp underflows. They now keep x - max, add up exp(x - max), and return x - max - log(sum), like the CPU path. This covers the generic kernels in softmax.cl and the subgroup kernels in softmax_loss.cl.
2026-11-13 15:42:48 +05:30
Mohammad Sohail Shaikh
55ff746075 Merge pull request #30728 from sohailshk/fix/dnn-matmul-broadcast-packedb (#30728)
dnn: fix packed-B offsets for broadcast batched MatMul

When the constant B of a MatMul has more than one batch slice but fewer than the output batch (B broadcasts over A's leading dims), updatePackedBOffsets derived the packed slice stride from the output batch, so every slice after the first read the wrong packed data. matmul_layer.cpp now passes fastGemmPackBSize(N, K, opt), the size of one packed slice, as the stride.
2026-11-10 08:43:16 +05:30
Kumataro
173a1cf711 dnn, features2d, imgproc: fix build warnings with GCC 15 / C++20
- dnn: suppress false-positive std::vector::insert warning in ONNX GRU parser
- features2d: simplify indexChange initialization in BRISK kernel generation
- imgproc: fix implicit conversion warnings with INTER_TAB_SIZE in SIMD remap and warp tests
2026-11-08 10:48:56 +09:00
Nathan Keys
50cfa93293 dnn(torch): validate nn.Padding dimension and pad bounds
Validate the one-based Padding dimension before converting it to an
array index, and reject the minimum integer pad before negating it.
Add a serialized Torch7 regression test for valid and invalid bounds.

Signed-off-by: Nathan Keys <professor.moody@pm.me>
2026-10-28 22:02:46 -05:00
Stefan Neumüller
ffbf6e6bcc dnn: use pow not std::pow in OpenCL kernels
5622958189 replaced pow() with std::pow() in three OpenCL C kernel
files. OpenCL C is a C99-derived language and has no std namespace, so
these kernels fail to compile at runtime on the GPU (e.g.
CL_BUILD_PROGRAM_FAILURE: use of undeclared identifier 'std') and dnn
silently falls back to CPU for the affected activations, LRN and fused
conv layers. Revert to the plain built-in pow() in the kernels.
2026-10-21 11:39:52 +00:00
Alexander Smorkalov
1e71c2b43a Merge pull request #30425 from tushar152006:fix-onnx-reduce-axes-parsing
DNN/ONNX: fix axes parsing and guard dynamic inputs in parseReduce
2026-10-21 10:30:55 +03:00
m00dy
69c37f364d Merge pull request #30261 from professor-moody:fix/dnn-tflite-tensor-buffer-bounds
dnn: validate TFLite tensor buffer bounds 🤖🤖🤖 - #30261

OpenCV Extra: https://github.com/opencv/opencv_extra/pull/1430

### What this changes

`TFLiteImporter::parseTensor` now checks the buffer index and required tensor bytes before constructing a `Mat` over model data. It rejects negative or overflowing shapes and unsupported sparse tensors. Absent or empty data remains a runtime tensor.

### Why

A TFLite model controls tensor shape, type, and buffer index. On 4.x at `802cf95aa3d42816995695bf68a86b3532f12760`, a tensor can claim more bytes than its selected buffer contains. The `tfliteShortBuffer` model included in this PR caused a stock Release SIGSEGV in three observed runs. The new check rejects it before the `Mat` wraps short data.

Associated upstream issue: none. Related DNN parser work includes #29371 and the closed, unmerged #29336; neither fixes this shape-to-buffer check.

### Tests and reproduction

This PR includes 15 small inline control and malformed TFLite models, importer tests, and `modules/dnn/test/generate_tflite_tensor_bounds_models.py`. The generator uses OpenCV's in-tree TFLite schema and `flatc` 25.12.19. The focused tests need no `opencv_extra` download.

To reproduce with the bytes in this PR, copy `modules/dnn/test/test_tflite_importer.cpp` and `modules/dnn/test/tflite_tensor_bounds_models.inc` from this PR into an otherwise unmodified 4.x checkout at the commit above. Build `opencv_test_dnn`, then run `./build/bin/opencv_test_dnn --gtest_filter=Test_TFLite_Importer.ShortInt32Buffer`. Apply the full PR and run `./build/bin/opencv_test_dnn --gtest_filter='Test_TFLite_Importer.*'`.

On Linux, an earlier tree that combined this patch with a separate ONNX importer fix passed all 15 focused TFLite tests and the 245-test `*Test_TFLite.*:*Test_ONNX_layers.*` filter in Release and GCC ASan builds. The compiled source and test files in this PR are byte-identical to that tree; only a generator comment changed afterwards, and rerunning the generator reproduced the include byte-for-byte. This branch has not been built on its own. Clang, MSVC, MinGW, and 5.x runtime tests have not run.

I used an AI coding tool to help prepare this change and will answer reviewer questions and address requested fixes within a day, following OpenCV's AI usage guideline. A separate reproducer archive is available on request; no files are attached to this PR.

### 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
- [ ] 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
      The test models are inline in this PR; no opencv_extra change is proposed.
- [ ] The feature is well documented and sample code can be built with the project CMake
2026-10-21 10:21:50 +03:00
Tushar Burla
2cf429b882 DNN/ONNX: fix axes parsing and guard dynamic inputs in parseReduce 2026-10-21 02:43:10 +05:30
Alexander Smorkalov
b29dda362e Merge pull request #30337 from velonica0:okriscv/dnn-convblock-rvv-vla-4.x
dnn: RVV: vectorize convBlock_F32 at any VLEN with one LMUL=1 kernel
2026-10-19 13:27:41 +03:00
Abhishek Gola
f093da6500 Merge pull request #30262 from professor-moody/fix/dnn-onnx-concat-rank-bounds
dnn: bound ONNX Concat axes and padding ranks 🤖🤖🤖
2026-10-19 13:21:41 +05:30
velonica0
7294629fd6 dnn: RVV: vectorize convBlock_F32 at any VLEN with one LMUL=1 kernel 2026-10-15 23:28:28 -07:00
NIKHIL
cf475c2e2e Merge pull request #30243 from Nikhi00718:fix/dnn-blob-rect-no-resize
dnn: fix blobRectsToImageRects when the image is not resized - #30243

### 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. No existing report covers this case; reproduction is below. Related: #26085, #30042.
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable. Accuracy test added; no test data needed.
- [ ] The feature is well documented and sample code can be built with the project CMake. Not applicable to this bug fix.

### Problem

`Image2BlobParams::blobRectToImageRect()` and `blobRectsToImageRects()` return `Rect(0, 0, 0, 0)` for every rect when `Image2BlobParams::size` equals the image size, in all three padding modes. With `size` left empty (the default, which `blobFromImageWithParams()` treats as "keep the image size"), the mapping divides by zero and returns `INT_MIN` coordinates. Running a 640x640 detector on 640x640 frames is enough to hit the first case.

```python
import cv2 as cv

p = cv.dnn.Image2BlobParams()
p.size = (640, 640)
p.paddingmode = cv.dnn.DNN_PMODE_LETTERBOX
print(p.blobRectToImageRect((10, 20, 30, 40), (640, 640)))
# (0, 0, 0, 0), expected (10, 20, 30, 40)

p.size = (0, 0)
print(p.blobRectToImageRect((10, 20, 30, 40), (640, 480)))
# (-2147483648, -2147483648, -2147483648, -2147483648), expected (10, 20, 30, 40)
```

Observed with the `opencv-python` 5.0.0 wheel and with a 4.x build at `802cf95aa3`. The function is identical on 4.x and has been since it was added in #24539 (4.9.0).

### Cause

`blobFromImagesWithParams()` replaces an empty `size` with the image size and applies no resize, crop or padding when the two sizes match. `blobRectsToImageRects()` only handles the `size != imgSize` branch: when the sizes match, the output keeps the zero rects created by `rImg.resize()`, and an empty `size` goes into the resize formulas as a zero divisor.

### Change

`blobRectsToImageRects()` now follows the same two rules as `blobFromImagesWithParams()`: an empty `size` means the image size, and when the sizes match, blob and image coordinates are the same, so the input rects are returned. The resize, crop-center and letterbox mappings are unchanged.

The new test covers both cases for all three padding modes. It also checks that the blob built with the same parameters is pixel-identical to the image, which is what makes returning the input rects correct here.

#30042 (5.x feature PR) contains an equivalent pass-through for the equal-size case as part of a larger Model API change; this is the standalone fix for 4.x, including the empty-size case.

### Testing

Built `opencv_test_dnn` and the Python bindings from this branch (head `d90164465c`, base 4.x `802cf95aa3`) on Ubuntu 26.04 (WSL2), GCC 15.2, Ninja, `BUILD_LIST=dnn,python3,ts`.

- `opencv_test_dnn --gtest_filter=blobRectToImageRect*`: 4 passed. On base `802cf95aa3` the new `blobRectToImageRect.no_resize` fails in all six mode/size combinations (`[0 x 0 from (0, 0)]` for equal sizes, `INT_MIN` for empty size); the blob pixel-identity assertion passes there too.
- `opencv_test_dnn --gtest_filter='blob*:*Image2Blob*:*imagesFromBlob*'`: 11 passed.
- `modules/dnn/misc/python/test/test_dnn.py`: 10 passed, including all `blob*` tests; 6 model tests failed only because their opencv_extra files are not present locally (`dnn/googlenet_0.png`, `dnn/opencv_face_detector.prototxt`, ...).
- The Python reproducer above prints `(10, 20, 30, 40)` for both cases with this branch.
- No compiler warnings in the touched files; `git diff --check` clean.
- Full `opencv_test_dnn` was not run (needs opencv_extra test data).
2026-10-15 08:15:11 +03:00
professor-moody
cb607b5c68 dnn: load Concat bounds models from opencv_extra 2026-10-13 08:11:59 -05:00
professor-moody
9005fe35f0 dnn: bound folded ONNX Concat axes and padding ranks
Validate the normalized axis against every constant input rank before
folding Concat and QLinearConcat. Assert equal input ranks before the
ConcatLayer padding loop reads each dimension.

Add self-contained importer regressions and an in-tree model generator.
2026-10-12 11:03:37 -05:00
Pratham Kumar
8602d9d964 Merge pull request #29831 from pratham-mcw:nchw_nchw_opt
dnn: fix eltwise layer memory traversal pattern causing Windows-ARM64 slowdown - #29831

## Problem
- `EltwiseInvoker::operator()` (backs the `Eltwise` layer's SUM/PROD/DIV ops) ran slower on Windows-ARM64 than x64.

## Root cause
- The loop tiled the output into fixed-size blocks and looped over the **channel axis inside each block**.
- In NCHW layout, consecutive channels of the same sample sit far apart in memory (`planeSize * 4` bytes apart).
- So each block jumped between ~256 memory locations per tensor — roughly **768 concurrent strided streams** across the three tensors involved.
- Hardware prefetchers can only track a small, fixed number of streams and Windows-ARM64's prefetcher falls over on this pattern.

## Fix
- Walk the output buffer contiguously and track the current (sample, channel) plane from the offset and clamp each block so it never crosses into the next channel.
- This removes the inner channel loop entirely: one channel finishes before the next starts, so every tensor is read/written sequentially instead of jumping around.
- No behavior change, only the traversal order is different.

## Performance Benchmarks:
<img width="1479" height="208" alt="image" src="https://github.com/user-attachments/assets/0f878757-d988-4564-b166-96d80834c77e" />
2026-09-01 14:26:36 +03:00
Satya Mallick
3e990c4ec2 DNN: allow smaller GatherElements dimensions outside axis 2026-08-30 11:30:40 +05:30
Pratham Kumar
d223a5ba93 Merge pull request #29716 from pratham-mcw:lstm_unroll_opt
Optimize fastGEMM1T NEON: extend 4-wide to 8-wide outer loop unrolling - #29716

**PR Description:**

- This PR extends the NEON fastGEMM1T optimization by adding an 8-wide outer loop before the existing 4-wide loop. The 8-wide block processes 8 output neurons per iteration instead of 4, reducing the total number of outer loop iterations by half and sharing the vector load cost across 8 output accumulator registers instead of 4.

- On x86, the AVX2 path processes 8 floats per instruction (256-bit registers) and AVX-512 processes 16 floats per instruction (512-bit registers). On ARM, NEON is 128-bit, only 4 floats per instruction. Intel's wider registers naturally cover more outputs per inner step. This patch brings ARM NEON closer to Intel parity through wider outer loop unrolling.

**Performance results:**
<img width="1236" height="478" alt="image" src="https://github.com/user-attachments/assets/c933e64c-2200-450e-9887-3fd0cbdd5b8e" />


Notes:
- The existing 4-wide loop is retained to handle remainders when nvecs is not a multiple of 8
- No existing tests modified
- Follows the same pattern as the existing 4-wide NEON path.

- [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
2026-08-22 09:10:25 +03:00
Anton Karpov
f625c00f5a dnn: fix the parameter names documented for memset
The four memset overloads in cuda4dnn document their first parameter as
src while it is called dest, and the directions are the wrong way round:
the output buffer is marked [in] and the 8-bit fill value is marked [out].

The prose above two of them already says dest, only the tags disagree.
2026-08-05 15:48:52 +03:00
Alexander Smorkalov
f7dd7df170 Merge pull request #29531 from asmorkalov:as/openvino_ci_fail
Disable test test that sporadically fails with OpenVINO on CI #29531

### 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-07-17 13:32:48 +03:00
Alexander Smorkalov
e978c193cf pre: OpenCV 4.14.0 (version++) 2026-07-09 12:35:42 +03:00
yyyisyyy11
b887e2fd3e Merge pull request #29018 from yyyisyyy11:project4_Lunhan_Yan
dnn: add DynamicQuantizeLinear ONNX layer support #29018

### 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 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 target platform(s)
- [x] There is an accuracy test
- [ ] There is a performance test

### Description

Implements the ONNX `DynamicQuantizeLinear` operator (opset 11) for the OpenCV DNN module.

**What it does:**

- Adds `QuantizeDynamicLayer` and `DequantizeDynamicLayer` layer classes
- Registers layers and adds ONNX importer dispatch for `DynamicQuantizeLinear`
- Computes scale and zero-point at runtime from activation min/max
- Quantizes FP32 input to int8 (stored as uint8 - 128, matching OpenCV convention)

**Framework limitation & workaround:**
Due to the single-dtype-per-layer constraint in `LayerData::dtype` (see #29017), the float32 scale output cannot be passed through the CV_8S blob pipeline directly. As a workaround, the scale is encoded as 4 raw bytes in a CV_8S `{1,4}` blob using `memcpy`, and decoded by the downstream `DequantizeDynamic` layer.

**Testing:**

- Custom accuracy tests reproduce all 3 ONNX conformance test cases: `test_dynamicquantizelinear`, `test_dynamicquantizelinear_max_adjusted`, `test_dynamicquantizelinear_min_adjusted`
- Each test verifies: quantized values, scale, zero point, and round-trip dequantize accuracy
- All existing quantization regression tests pass (42/42)

**Conformance tests:**
The 6 conformance tests for `DynamicQuantizeLinear` remain in the parser denylist (they were already denylisted before this PR) because the framework cannot produce mixed-type outputs. The custom tests provide equivalent coverage.

### Files changed

- `modules/dnn/include/opencv2/dnn/all_layers.hpp` — layer class declarations
- `modules/dnn/src/init.cpp` — layer registration
- `modules/dnn/src/onnx/onnx_importer.cpp` — ONNX import dispatch
- `modules/dnn/src/int8layers/quantization_utils.cpp` — layer implementations
- `modules/dnn/test/test_onnx_importer.cpp` — custom accuracy tests
2026-07-09 11:07:12 +03:00
Uwez Khan
b4164a4bc4 bound einsum subscript index before reading input shape 2026-07-01 18:19:00 +05:30
Alexander Smorkalov
5b83b0c440 Merge pull request #29405 from Teddy-Yangjiale:rvv-dnn-conv-4x
dnn: add RVV LMUL=1 kernel for convBlock_F32 (ConvolutionLayer, rv64gcv)
2026-06-29 18:08:55 +03:00
Teddy-Yangjiale
c831290769 dnn: add RVV LMUL=1 kernel for convBlock_F32 (ConvolutionLayer, rv64gcv) 2026-06-29 00:47:44 +08:00
Alexander Smorkalov
edd89cfca5 Merge pull request #29371 from uwezkhan:tflite-pad-resize-bounds
check parameter tensor length in tflite parsePadding and parseResize
2026-06-28 14:19:17 +03:00
uwezkhan
69d2303531 Merge pull request #29345 from uwezkhan:onnx-tile-bounds
bound tile axis and repeats length in onnx parseTile #29345

OpenCV Extra: https://github.com/opencv/opencv_extra/pull/1385

parseTile sizes repeats_vec from the input-0 rank, then fills it from fields of the model that are never checked against that size. In the tile-1 path the axis taken from the third input indexes repeats_vec directly, and in the tile>1 path the loop writes one entry per element of the repeats tensor. A crafted ONNX with an out-of-range axis, or a repeats tensor longer than the input rank, writes past repeats_vec while loading the model through readNetFromONNX.

The fix runs axis through normalize_axis, the same helper the squeeze and concat paths in this file already use, so a negative or oversized axis is rejected before the write, and it checks the repeats length equals the input rank before the loop. Keeping both bounds in the parser puts the check next to the write instead of trusting the model to be well formed. Before, a repeats tensor shorter than the rank was silently accepted; after, it is rejected, which matches the ONNX rule that repeats carries one entry per input dimension.

- [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
- [ ] 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
- [ ] The feature is well documented and sample code can be built with the project CMake
2026-06-26 12:39:04 +03:00
Tõnu Samuel
b64a215e71 Merge pull request #29377 from tonuonu:perf-dnn-activation-simd
dnn: SIMD for transcendental activation layers (15 functors) 🧑‍💻🤖 #2937

# dnn: SIMD for transcendental activation layers (15 functors) 🧑‍💻🤖

### Summary

Many `BaseDefaultFunctor`-based activation functors fall back to the scalar `BaseDefaultFunctor::apply`
— one `libm` call per element. This PR adds vectorized `apply()` overrides (universal intrinsics,
matching the existing `MishFunctor`/`GeluFunctor`/`SigmoidFunctor` pattern, each with a scalar tail) to
the **15 transcendental activations** that have a clean SIMD path:

| functor | uses | | functor | uses |
|---|---|---|---|---|
| TanH | `v_exp` (1−2/(e²ˣ+1)) | | Asinh | `v_log`,`v_sqrt` (sign·log(\|x\|+√(x²+1))) |
| Log | `v_log` | | Acosh | `v_log`,`v_sqrt` |
| Erf | `v_erf` | | Atanh | `v_log` |
| Exp | `v_exp` | | Softplus | `v_exp`,`v_log` |
| Sin | `v_sin` | | BNLL | `v_exp`,`v_log` (max(x,0)+log1p(e^−\|x\|)) |
| Cos | `v_cos` | | GeluApproximation | `v_exp` (tanh) |
| Tan | `v_sin`/`v_cos` | | Sinh / Cosh | `v_exp` |

Functors compile at the baseline SIMD width (SSE on x86, NEON on ARM — same as the existing SIMD
functors). `Sqrt`/`Floor`/`Ceil`/`Round`/`Abs`/etc. are intentionally **not** included — those are
single cheap ops the compiler already auto-vectorizes (measured `Sqrt` at 0.95×). `Asin`/`Acos`/`Atan`
are omitted (no `v_atan`/`v_asin`/`v_acos` intrinsic).

### Performance

Real `opencv_perf_dnn` `Layer_Activation` (added here), 8×256×128×100 = 26.2 M-elem CV_32F blob, A/B
vs the scalar fallback, median speedup:

| functor | M4 clang/NEON | A76 gcc/NEON | Threadripper gcc | Xeon W-2235 gcc | functor | M4 | A76 | TR | Xeon |
|---|---|---|---|---|---|---|---|---|---|
| TanH | 9.1× | 2.3× | 7.3× | 7.3× | Sinh | 3.3× | 3.2× | 5.2× | 5.0× |
| Cos | 8.8× | 3.0× | 3.3× | 3.0× | Acosh | 3.2× | 2.9× | 2.7× | 2.6× |
| Log | 7.8× | 3.0× | 2.5× | 2.4× | Cosh | 2.8× | 3.2× | 2.6× | 2.5× |
| Sin | 7.8× | 3.0× | 3.4× | 2.9× | Exp | 2.4× | 2.5× | 1.4× | 1.5× |
| GeluApprox | 7.6× | 2.4× | 6.6× | 5.8× | BNLL | 4.2× | 2.0× | 1.6× | 1.4× |
| Atanh | 7.0× | 3.6× | 6.0× | 5.2× | Softplus | 2.0× | 2.0× | 3.3× | 2.7× |
| Tan | 6.8× | 3.6× | 6.6× | 6.0× | Erf | 4.2× | 2.4× | 3.9× | 3.5× |
| Asinh | 3.9× | 2.4× | 5.8× | 5.7× | | | | | |

Every functor is a win on every tested out-of-order core (worst case 1.4×). On the **in-order
Cortex-A55** (a55-tuned build) all 15 measure 0.985–0.99× — neutral, within noise: the SIMD
polynomials are dependency-chain-bound, which an in-order pipeline can neither accelerate nor (here)
slow down. So: meaningful wins on out-of-order ARM + x86, no regression on in-order ARM.

### Accuracy

Uses the `v_exp`/`v_log`/`v_erf`/`v_sin`/`v_cos` polynomials OpenCV already ships and relies on (Gelu
via `v_erf`, Mish/Sigmoid via `v_exp`). Verified vs scalar `libm` on 320 K random elements per functor
with domain-correct inputs (Acosh x≥1, Atanh |x|<1, …): **max abs error ≤ 3e-5** (most ≤ 2e-6), zero
elements exceeding rel>1e-3 & abs>1e-4. ONNX conformance and the layer accuracy tests exercise these ops.

### 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 a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch (4.x)
- [ ] There is a reference to the original bug report and related work — N/A (perf improvement)
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable — perf test added (`Layer_Activation`, `SANITY_CHECK_NOTHING`); accuracy covered by existing ONNX conformance/layer tests
- [ ] The feature is well documented and sample code can be built with the project CMake — N/A (internal optimization, no new API)
2026-06-26 11:06:53 +03:00
Uwez Khan
6678e48c12 check parameter tensor length in tflite parsePadding and parseResize
guard the parsePadding NHWC swap on paddings.total()==8 and require the parseResize size tensor to hold height and width, matching the existing parseStridedSlice check
2026-06-23 16:46:41 +05:30
Alexander Smorkalov
2adeab8504 Merge pull request #29314 from uwezkhan:onnx-tensor-payload-size
validate onnx tensor payload size in getMatFromTensor
2026-06-23 13:18:24 +03:00
Pratham Kumar
df0c9d7950 Merge pull request #29316 from pratham-mcw:dnn-arm64-neon-blobfromimages
dnn: optimize blobFromImages using NEON intrinsics on ARM64 #29316

- This PR optimizes the HWC-to-NCHW conversion in blobFromImages() by adding NEON implementation.
- On x64, the MSVC compiler automatically vectorizes the existing scalar implementation, resulting in significantly better performance.
- On Windows ARM64, MSVC does not auto-vectorize this stride-3 access pattern, leading to a noticeable performance gap compared to x64.
- Added CV_NEON macro guard to ensure SIMD optimization is enabled on ARM64 architecture, leaving behavior on other platforms completely unchanged.

**Performance Improvements**

- This optimization significantly improves the performance of HWC-to-NCHW conversion on Windows ARM64.

<img width="823" height="254" alt="image" src="https://github.com/user-attachments/assets/84b22deb-22da-4607-8009-3405c2529b80" />

- [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
2026-06-23 09:25:30 +03:00
Alexander Smorkalov
10f4847bf6 Merge pull request #29321 from uwezkhan:tflite-kernel-scale-count
check tflite kernel scale count against output channels
2026-06-22 11:29:08 +03:00
uwezkhan
4e56cf9ac8 check begin and size lengths match in tensorflow parseSlice 2026-06-17 14:05:39 +05:30
uwezkhan
414a0379d8 check tflite kernel scale count against output channels 2026-06-16 22:19:58 +05:30
uwezkhan
57081ac946 validate onnx tensor payload size in getMatFromTensor
Reject initializers whose declared shape claims more elements than the tensor payload (raw_data or a typed *_data field) actually holds, before the Mat copy/convert reads them.
2026-06-16 15:55:31 +05:30