Commit Graph

266 Commits

Author SHA1 Message Date
Shiven Solanki
b946499f3b dnn: keep the Hardmax axis attribute unchanged in forward 2026-11-29 23:00:07 +08:00
abhishek-gola
7aae1af9bd dnn: avoid unsafe fork fallback in NonZero death test 2026-11-29 12:13:08 +05:30
Tushar Burla
da45186698 dnn(onnx): add ONNX TensorScatter operator (opset 24)
- Implement TensorScatterLayer supporting linear and circular modes along specified axis

- Register TensorScatter in LayerFactory and ONNX importer

- Copy contiguous slice blocks per outer row with std::memcpy, bounded chunking, and nstripes tuning

- Un-denylist 3 official ONNX conformance tests and shield OpenVINO backend

- Add dedicated unit tests for circular wrapping, default indices, int64 bounds, zero-work domains, and chunk scheduling
2026-11-28 14:43:23 +05:30
Abhishek Gola
2b33bdac61 dnn: return all false in IsInf when both detect flags are 0 (#31171)
Problem
IsInf threw "Unsupported mode" when detect_positive and detect_negative were both 0. ONNX expects an all-false output in that case.

Fix
Fill the output with zeros in that branch instead of calling CV_Error.
2026-11-27 13:22:49 +05:30
Shiven Solanki
84f7fe9044 dnn: fix last row and column in bilinear tf_crop_and_resize 2026-11-27 12:21:35 +08:00
Shiven Solanki
ffcc3c5179 dnn: return all false in IsInf when both detect flags are 0 2026-11-26 20:19:11 +08:00
pbkx
a06a29dc41 dnn: fix NonZero output for grouped parallel ranges (#31009)
Incorrect prefix offsets can be generated when different partitions are used for counting and emission, leading to some coordinates being overwritten or not written at all. Despite this, the output shape remains correct.

Each logical stripe is counted independently. We have added a parameterized test for dense and sparse inputs. It covers three different counting partitions and tests that all coordinates are correctly generated in row-major order. The test also verifies that the output shape and type are correct, that output memory was reused and that input data was preserved.
2026-11-26 13:27:19 +05:30
Varun Jaiswal
a1b14ca7fe Merge pull request #30423 from varun-jaiswal17/dnn-fastgemm-threads
fastGemm optimizations and add flashattention without MLAS

fastGemm cuts every product into fixed tiles (60 × 320 on AVX/AVX2, from #23897) and runs one tile per parallel task. Transformer layers have few rows, so they make fewer tasks than there are threads. On a 32-thread CPU, a 50 × 3072 projection gives 10 tasks, and one attention MatMul of DeiT-Tiny (3 heads × 197 × 64 × 197) gives 12.
2026-11-26 13:00:18 +05:30
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
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
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
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
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
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
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
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
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
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
Tushar Burla
1ae9196360 Merge pull request #30576 from tushar152006:feat-dnn-onnx-compress
dnn(onnx): add support for ONNX Compress operator - #30576

### Description

This PR adds support for the ONNX `Compress` operator (opset 9-24) to the OpenCV DNN dynamic engine:
- Implements `CompressLayer` in `modules/dnn/src/layers/compress_layer.cpp` supporting dynamic output shapes (`dynamicOutputShapes() { return true; }`).
- Implements full ONNX `Compress` semantics:
  - Slices along a specified axis when the `axis` attribute is provided (supports negative axis indexing via `normalize_axis`).
  - Flattens the input tensor to 1D before compression when the `axis` attribute is omitted.
  - Discards elements exceeding condition length when condition length is shorter than target axis dimension (`std::min(dimAxis, condTotal)`).
  - Handles all-false condition ($K=0$) cleanly with early return after fitting the valid empty output shape (`[..., 0, ...]`).
  - Enforces continuous tensor invariants with `CV_Assert(data.isContinuous())` and validates `condition` as `CV_Bool` per ONNX spec.
  - Slicing optimized via OpenCV native `parallel_for_` flattening multi-dimensional iteration domains to 1D (`totalSlices = outer * K`).
- Un-denylists and passes all 4 official ONNX conformance tests in `test_onnx_conformance_layer_parser_denylist.inl.hpp`.
- Marks `Compress` conformance tests with `SKIP;` in `test_onnx_conformance_layer_filter__openvino.inl.hpp` to ensure OpenVINO CI remains green.
- Adds focused Google Test unit tests in `modules/dnn/test/test_layers.cpp` verifying empty output behavior on all-false condition both with and without `axis`.

### Test Results
All 4 ONNX conformance tests + 2 all-false unit tests pass locally:
```text
[==========] Running 6 tests from 2 test cases.
[----------] Global test environment set-up.
[----------] 2 tests from Test_Compress
[ RUN      ] Test_Compress.AllFalse_WithAxis
[       OK ] Test_Compress.AllFalse_WithAxis (29 ms)
[ RUN      ] Test_Compress.AllFalse_WithoutAxis
[       OK ] Test_Compress.AllFalse_WithoutAxis (0 ms)
[----------] 2 tests from Test_Compress (30 ms total)

[----------] 4 tests from Test_ONNX_conformance
[ RUN      ] Test_ONNX_conformance.Layer_Test/test_compress_0_OCV_CPU
[       OK ] Test_ONNX_conformance.Layer_Test/test_compress_0_OCV_CPU (901 ms)
[ RUN      ] Test_ONNX_conformance.Layer_Test/test_compress_1_OCV_CPU
[       OK ] Test_ONNX_conformance.Layer_Test/test_compress_1_OCV_CPU (465 ms)
[ RUN      ] Test_ONNX_conformance.Layer_Test/test_compress_default_axis_OCV_CPU
[       OK ] Test_ONNX_conformance.Layer_Test/test_compress_default_axis_OCV_CPU (456 ms)
[ RUN      ] Test_ONNX_conformance.Layer_Test/test_compress_negative_axis_OCV_CPU
[       OK ] Test_ONNX_conformance.Layer_Test/test_compress_negative_axis_OCV_CPU (559 ms)
[----------] 4 tests from Test_ONNX_conformance (2383 ms total)

[----------] Global test environment tear-down
[==========] 6 tests from 2 test cases ran. (2413 ms total)
[  PASSED  ] 6 tests.
```

### Checklist
- [x] I have read the [OpenCV contribution guidelines](https://github.com/opencv/opencv/wiki/How_to_contribute).
- [x] My code follows the OpenCV coding style guidelines.
- [x] I have tested my changes locally and all relevant unit tests pass.
- [x] No unrelated files or whitespace changes are included.
2026-10-30 09:11:02 +03:00
Prasad Ayush Kumar
36836bb4cc Merge pull request #30313 from Prasadayus:dnn-block-layout-optimization
DNN: Optimize block layout handling and fold Mul/Add into BatchNorm - #30313

Requires: https://github.com/opencv/opencv_extra/pull/1439

### PR Changes

- AveragePool runs on plain NCHW input without conversion to block layout; with an avgpool HAL hook registered, block layout is kept as before.
- NaryEltwise with a scalar constant operand runs in block layout.
- BatchNorm absorbs following Mul/Add by scalar or per-channel constants into its scale and bias; ChainFuser marks a [C,1,1] / [1,C,1,1] constant per channel once it proves the input is 4D.
- Global average/max pooling reduces block input directly.
- An elementwise op feeding a conversion to plain now runs after it, on C channels instead of C0 lanes.
- Slice2 on the channel axis keeps block layout for C0-aligned or runtime bounds.

### Performance

Measured on i9-14900KS, default threads (32).

| Model       | 5.x        | After PR   | ORT  (1.30)     | OpenCV before vs after | After PR vs ORT |
|-------------|-----------:|-----------:|-----------:|-----------------------:|----------------:|
| RAFT        | 965.67 ms  | 691.03 ms  | 604.26 ms  | 1.40x                  | 0.87x           |
| DenseNet121 | 14.14 ms   | 9.84 ms    | 12.05 ms   | 1.44x                  | 1.22x           |
| XFeat       | 5.80 ms    | 5.63 ms    | 2.95 ms    | 1.03x                  | 0.52x           |
| NAFNet      | 1304.50 ms | 1195.67 ms | 1407.77 ms | 1.09x                  | 1.18x           |
| RealESRGAN  | 422.57 ms  | 403.93 ms  | 534.29 ms  | 1.05x                  | 1.32x           |
| PPOCRv3_det | 14.25 ms   | 14.15 ms   | 16.32 ms   | 1.01x                  | 1.15x           |

### 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
      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-10-29 08:41:09 +03:00
uwezkhan
3e93353b5b Merge pull request #30530 from uwezkhan:sce-weights-shape-check
dnn: check weights and soft labels shape in SoftmaxCrossEntropyLoss 🤖🤖🤖 - #30530

`SoftmaxCrossEntropyLossImpl::forward` reads the optional `weights` input as a float array of `C` class weights (`weightBase[y]`, and `wData[c]` on the probability-label path) but never checks its length or type. The probability-label path also reads `labels` with the scores layout (n, c, s) without checking that the labels have the scores shape. Both tensors come straight from the ONNX model, so a short weights initializer or a `[1, C]` labels tensor against `[2, C]` scores reads past the buffer.

Before: weights of shape `[1]` with `C = 64` and labels `C - 1` gives an ASan heap-buffer-overflow READ in `reduceSCEPerSample`. Probability labels `[1, 64]` against scores `[2, 64]` give a READ of size 16 in the forward lambda.
After: both cases throw from `forward`. Weights are checked against `C` and converted to `CV_32F`, which `NegativeLogLikelihoodLoss` already does. Valid models are unchanged, and all 104 `test_sce_*` / `test_nllloss_*` conformance cases pass on OCV/CPU.
Tradeoff: one extra `convertTo` of a `C`-element vector per forward call. In exchange, `float16`/`double` weights are now read with their real values instead of being reinterpreted as float.

A regression test was added to `test_layers.cpp`. It fails under ASan without the fix and passes with it.


### 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
      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-10-28 21:30:37 +03:00
Uwez Khan
abd21b8d54 dnn: validate boxes shape and follow TF extrapolation in CropAndResize
Check the [1, 1, N, 7] boxes layout in getMemoryShapes so the output size and the box loop agree on every backend. Emit the extrapolation value for samples outside [0, H - 1] x [0, W - 1] and sample the box center for 1-pixel crops, on both the CPU and CUDA paths.
2026-10-25 22:54:51 +05:30
Lazizbek Ergashev
f365616a02 Merge pull request #30503 from lazerg/fix:issue-30501-gathernd-empty-indices
dnn: fix GatherND division by zero on empty indices - #30503

GatherND divided by zero in `forward_impl` when the indices tensor is empty, which kills the process with SIGFPE on x86-64 (seen with `LightGlueMatcher` when nothing matches). The layer now returns early when the output is empty.

Fixes #30501

### 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-10-25 10:11:04 +03:00
sanjayk9
f62288c4a1 Merge pull request #30297 from sanjayk9:dnn-matmul-nobias-gemm
dnn: skip MatMul's zero-fill when there is no bias - #30297

Without a bias, MatMul pre-zeroed the whole output with a single-threaded memset and then still passed beta = 1 into the gemm, forcing every kernel to read and multiply-add against that zeroed buffer. Passing beta = 0 instead removes the memset and lets MLAS/fastGemmThin write the product directly. Measured 31-50% faster on a small, write-heavy, no-bias shape (512x32x512, 8 threads); `MatMul.matmul/41` and the new `MatMul.matmul_dynamicB/41` cover the constant-B and dynamic-B paths.

### 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
      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-10-23 11:42:16 +03:00
xieofxie
83f8d6e6c6 Merge pull request #30332 from xieofxie:hualxie/enable-mlas-windows-arm64
dnn: enable vendored MLAS on Windows ARM64 with MSVC - #30332

Close https://github.com/opencv/opencv/issues/30330
After https://github.com/opencv/opencv/pull/30331

### Summary

Enable OpenCV DNN’s vendored MLAS implementation on Windows ARM64 using Microsoft’s C++ compiler (`cl.exe`).

This change builds on the separate MLAS target architecture detection fix.

MLAS is currently disabled on all Windows targets. Enabling ARM64 requires more than removing that restriction: the GNU-style `.S` sources cannot be used by the MSVC toolchain, and the vendored Windows sources lack the SGEMV kernel used by the single-row fast path.

This change:

- Adds the Windows ARM64 SGEMV kernel from the same ONNX Runtime revision as the existing vendored sources.
- Preprocesses the native SGEMM and SGEMV `.asm` files with `cl.exe`, then assembles them with `armasm64`.
- Includes the generated assembly objects in `opencv_dnn`, with configuration-specific output paths.
- Enables MLAS only for Microsoft `cl.exe` targeting ARM64. Other Windows toolchains and targets remain disabled.
- Adds GEMM and SDPA accuracy coverage and documents the Windows build requirements.

The implementation uses the existing upstream `MlasHGemmSupported` probe. No additional HGEMM or FP16 workaround is introduced.

### Validation

On Windows ARM64, based on upstream commit `3074f64`:

- Release and Debug DNN builds linked successfully.
- MLAS and both NEON assembly kernels were enabled.
- All **116 selected tests passed in each configuration**, covering GEMM, single-row GEMV through FlashAttention, transposition, odd-sized tails, and accumulation across FlashAttention blocks.
- CMake guard checks confirmed unsupported Windows compiler/target combinations remain disabled.

A complete Python wheel has not been rebuilt, and performance benchmarks have not been run.

### Related work

- [[opencv/opencv#29343](https://github.com/opencv/opencv/pull/29343)](https://github.com/opencv/opencv/pull/29343): temporary blanket Windows disable; this PR enables only the supported MSVC ARM64 configuration.
- [[opencv/opencv#29885](https://github.com/opencv/opencv/issues/29885)](https://github.com/opencv/opencv/issues/29885): related Windows x86/x64 and clang-cl problems, outside this PR’s scope.
- [[opencv/opencv#29362](https://github.com/opencv/opencv/pull/29362)](https://github.com/opencv/opencv/pull/29362): existing HGEMM capability-probe fix, retained unchanged.

### 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-10-22 14:39:57 +03:00
Savya Sanchi Sharma
38a2f1556a Merge pull request #29807 from SavyaSanchi-Sharma:cudnnjit_p2
dnn(cuda): move the CUDA backend to UMat device buffers - #29807

This PR is in continuation with  #29658 and #30259 
### 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-10-19 13:06:41 +03:00
Abhishek Gola
eacc7a59ed Merge pull request #30277 from sanjayk9/dnn-attention-mlas-qkv
dnn: speed up Attention on CPU with MLAS; support 4D input (SAM3 decoder)
2026-10-19 13:07:06 +05:30
Savya Sanchi Sharma
d1f25babff Merge pull request #30309 from SavyaSanchi-Sharma:opti/lstm
dnn: speed up LSTM2 (gate math, input projection, recurrence) - #30309

Speeds up the ONNX LSTM layer (`LSTM2`) in `recurrent2_layers.cpp`:
- Default sigmoid/tanh gates are computed on raw rows with the dispatched activation kernels. Peephole, clip and custom activations keep the old path.
- The input projection runs before the per-direction loop, so the GEMM uses all threads. It goes through MLAS when available.
- Batch 1 (hidden size >= 128): hidden units are split across threads, with one `parallel_for_` per timestep.
- Batch > 1: one packed GEMM per step replaces one GEMV per row.

Ryzen 9 9950X, default threads, 5.x vs this PR:

| Model | 5.x, ms | PR, ms | x-factor |
|---|:-:|:-:|:-:|
| `DNNTestNetwork.CRNN` | 2.693 | 1.562 | 1.72 |
| CRNN EN 2021sep | 2.498 | 1.472 | 1.70 |
| crnn.onnx | 2.650 | 1.434 | 1.85 |
| LSTM2 bidirectional, batch 1, in 512, hidden 256, 24 steps (CRNN layer 1) | 0.710 | 0.212 | 3.36 
### 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-10-19 09:41:52 +03:00
sanjay
2c6130dc03 Merge 5.x: keep unconditional bias push, keep QKV grouping 2026-10-15 13:09:49 +05:30
sanjay
fa0d4a06a1 dnn: group a fused Attention's tokens the way its QKV reshape does
The fusion read only num_heads and head_dim from the QKV Reshape target,
so a graph reshaping Q/K/V to [B, T*S, H, D] fused the same way as one
reshaping to [B*T, S, H, D], and the fused layer computed the second for
both, giving a wrong result for the first.

The fusion now records the first two target entries, the batch and the
sequence length the attention runs over, each as a constant times a
product of input dims, or as inferred. It reads constants and chains of
Shape, Gather, Mul, Unsqueeze, Squeeze and Cast (as in the SAM3 decoder).
If an entry is computed some other way, or Q, K and V disagree, the block
is left unfused. The layer evaluates the record against the input shape
and runs over that grouping, which is a view of the same contiguous
tokens. Without a record, as for the ONNX Attention op, the input must be
3D.
2026-10-14 21:13:31 +05:30
Abhishek Gola
94a2431d7b Merge pull request #30103 from officialarghya29/fix/dnn-matmul-rank1-a-gemm
dnn: accept a rank-1 A in the MatMul -> Gemm rewrite
2026-10-14 14:16:27 +05:30
sanjay
d8baaa6e82 dnn: size the Attention output from the V width
The output has v_hidden values per token, but getMemoryShapes() sized it
from the input width, so a V wider than the input wrote past the output
buffer. Size it from v_hidden for both output ranks, and test V widths
below, equal to and above the input width.
2026-10-14 14:01:50 +05:30
sanjay
d5c8ad61fe dnn: faster transformer inference on CPU; accept rank > 3 Attention input
- Attention Q/K/V projection: pack each (Q/K/V, head) weight slice with
  MLAS and run all per-head GEMMs in one multithreaded
  mlasSgemmPackedBatch() call; the fastGemm loop stays as the fallback.
- MLAS: split each operation into 4 tiles per thread on hybrid CPUs.
- forward(): hand the private output Mats to the caller instead of
  copying them again.
- Attention: accept [..., S, C] input (SAM3 decoder).
2026-10-13 20:34:55 +05:30
Abhishek Gola
3b3a414c9c Merge pull request #30101 from officialarghya29/fix/dnn-gru-output-direction-seqlen
dnn: honour the GRU output selection, direction=reverse, sequence_lens and clip
2026-10-08 13:43:10 +05:30
Arghya Bose
27a035e866 dnn: address review feedback on the GRU fixes
- Move the activation clip clamp and holdFinishedRows into
  recurrent_activations.hpp and call them from both GRU and RNN; drop the
  redundant useClip flag, since clip > 0 is the switch.
- Select the GRU outputs positionally, matching getMemoryShapes(), instead
  of guessing Y / Y_h from their shape and keeping the old single-output
  may-be-Y_h policy.
- Reject direction=reverse together with two-direction weights instead of
  silently running both sweeps backwards, and drop the unreachable assert.
- Collapse the four inlined GRU references into one shared helper and drop
  the stale sentence from the SingleOutputIsSequenceY comment.
- Drop the hand-made hPrev allocation: hInternal.copyTo() already sizes and
  types it.
- Gate the GRU reference on the input timestep rather than the loop
  position, so reverse + sequence_lens skips the padding instead of the
  valid steps, and cover that combination with a test.
2026-10-07 20:38:16 +05:30
Abhishek Gola
99eb7ceb88 Merge pull request #30107 from officialarghya29/fix/dnn-global-pooling-nd
dnn: support global pooling for inputs with more than two spatial dimensions
2026-10-07 12:58:58 +05:30
Arghya Bose
6fa9357d32 dnn: support global pooling for inputs with more than two spatial dimensions
GlobalAveragePool and GlobalMaxPool accept N x C x D1 x ... x Dn inputs, but
the layer only worked for at most two spatial dimensions: the parameter
vectors derived from the layer params hold one pad/stride entry per recognized
dimension (kernel_d/h/w), so a 5-D input hit
"CV_CheckLE(addedDims, pads_begin.size())" in getMemoryShapes and the model
could not be loaded at all.

The quantized pooling layer shares the same parameters, so it silently read
past the pad/stride vectors and produced garbage output shapes (and read
garbage kernels) in the same situation.

Fix by giving the paddings (0) and the strides (1) as many entries as the
global kernel has spatial dimensions, both in the shape computation and in
finalize. The extra entries are inserted at the front so that the parameters
stay trailing-aligned with the spatial dimensions, and a check rejects inputs
with more spatial dimensions than the layer can describe instead of reading
the per-dimension flags out of bounds.
2026-10-06 18:30:09 +05:30
Abhishek Gola
33d76d5ade Merge pull request #30091 from abhishek-gola:core-shape-einsum
Add squeeze/unsqueeze/flatten/reshape for N-D arrays - #30091

### 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-10-06 12:44:51 +03:00