* 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.
* 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
dnn: fix NMSBoxesBatched class offset for negative coordinates - #30954Fixes#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
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
* 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.
* 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>
* 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
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.
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
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.
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.
INT4 and UINT4 tensors travel unpacked in CV_8S/CV_8U, so QuantizeLinear
only saturated them to the 8-bit range: test_quantizelinear_int4 expects 7
for 40/4+1 and got 11. Clamp the result to [-8, 7] / [0, 15] when the ONNX
output dtype is INT4/UINT4, and enable the four int4 conformance cases
(the DequantizeLinear ones and the uint4 case already passed).
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
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
dnn: share equal constants and merge duplicate nodes in the ONNX importer - #30276
# Summary
The ONNX importer now gives initializers with the same type, shape and bytes a single constant,
and `parseNode()` skips a node that has the same op, attributes and inputs as an earlier one,
reusing that node's outputs instead. Many exported models repeat identical work: RAFT pads the
same correlation pyramid again in each of its 10 refinement iterations, and each iteration's
`pads` constant has a different name, so the Pads only look identical when constants are
compared by value. With this change RAFT runs 5 Pads instead of 41, as ONNX Runtime does.
Custom-domain ops, random ops, nodes with subgraphs and nodes producing graph outputs are never
merged. Neither are `QuantizeLinear`/`DequantizeLinear`: `fuseQDQ()` only folds a DQ into
MatMul/Gemm/Conv while it has a single consumer, so merging them would switch off int8 fusion.
Outputs match ONNX Runtime as closely as before.
| Model | This PR | OpenCV 5.0.0 | ORT 1.30 | vs 5.0.0 | vs ORT 1.30 |
|---|---:|---:|---:|---:|---:|
| RAFT | 392.4 ms | 544.5 ms | 291.3 ms | 1.39× faster | 0.74× |
| NAFNet | 1815.8 ms | 2157.6 ms | 1532.6 ms | 1.19× faster | 0.84× |
| YOLOX | 28.3 ms | 29.8 ms | 15.1 ms | 1.05× faster | 0.53× |
> Benchmarked on AMD Ryzen 9 9950X
### 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
Added flag for bitexact resize in blobFromImage and overloads. - #30131
Current INTER_LINEAR resize allows small deviations up to rounding. It affects inference result for networks that produce coordinates (object detectors, features) and descriptors. The new option allow to get the same result independently on CPU arch and used HALs.
Companion PR for references update: https://github.com/opencv/opencv_extra/pull/1422
### 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
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.
According to the ONNX protobuf specification, boolean tensors may be stored either in raw_data or packed into repeated int32 int32_data as individual 32-bit integers (not a bitmask). Previously, getMatFromTensor only read raw_data, causing assertion failures when parsing ONNX models that serialize boolean initializers into int32_data.
This patch adds int32_data extraction with conversion to CV_Bool, adds specification documentation, removes unreachable duplicate branches for UINT16/UINT32/UINT64, and adds tests in test_onnx_importer using models from opencv_extra.
Test data in opencv_extra under the same branch name as this patch: https://github.com/opencv/opencv_extra/pull/TBD
Addresses #19366.
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
ONNX opset 21 allows INT16 and UINT16 as the quantized type of
QuantizeLinear and DequantizeLinear. The importer already maps them to
CV_16S/CV_16U, but both layers stopped at a CV_Assert that only listed the
8-bit, int32 and fp8 types, so the four conformance cases for these dtypes
were on the parser denylist.
Accept CV_16U/CV_16S in both layers and add the dispatch branches for the
fp32/fp16 scale and activation combinations, mirroring the existing
CV_8U/CV_8S ones. The shared kernels already handle the wider types via
saturate_cast. Remove the four cases from the denylist.
Verified on macOS arm64: before the change the 8 cases
(test_{de}quantizelinear_{u,}int16 x OCV/CPU, OCV/CPU_FP16) fail on the
assertion; after it the whole Test_ONNX_conformance suite passes
(3584 tests) and the quantization unit tests pass (118 tests).
dnn : int8 optimisation - #30289
### Correctness
- **AVX-VNNI 1x1 conv, leftover pixels:** the last `H*W % 8` output pixels read the VNNI-repacked
weights in the wrong order. Fixes the wrong top-1 of MobileNetV2 and DenseNet121 int8 with VNNI.
- **Padded taps in scalar paths:** the depthwise (AVX2) tail and the NEON kxk scalar path skipped
out-of-image taps instead of using the input zero point. The VNNI kxk kernel now never leaves a
tile under 8 pixels.
### Speed
- **First conv:** quantizing the float image is now parallel and vectorized. A float-input conv
with up to 4 channels runs as a 1x1 conv over each pixel's window. First conv 5-6x faster
(ResNet50: 0.88 -> 0.16 ms). `OPENCV_DNN_INT8_CONV_WINDOW_PACKING=0` disables the window packing.
- **AVX-VNNI depthwise conv:** a new kernel transposes input rows into one row per channel and
adds 4 taps for 8 pixels with one `pshufb` + `vpdpbusd`. Depthwise about 2x faster, output
bit-identical.
- **int8 MatMul at batch 1:** uses all threads instead of one. AlexNet int8: 2.75 -> 1.52 ms.
- **Asymmetric padding:** convs with TF "SAME" padding at stride 2 are now fused to int8 instead of
running in float between Dequantize and Quantize. Float convs in EfficientNet-Lite4 and MP hand
pose: 5 -> 0-1.
- **Broadcast int8 Add/Mul:** copies whole contiguous runs in parallel instead of computing an
index per element.
- **int8 Quantize/Dequantize:** AVX2 fast path for signed int8; per-tensor Q/DQ keep the block
layout.
### Tests
- Companion PR : opencv/opencv_extra#1436 (test data).
### Results (ms, i9-14900KS , default threads)
| Model | 5.x before (ms) | this PR (ms) | ONNX Runtime 1.30 (ms) | Speedup vs 5.x | ORT / this PR |
|---|---|---|---|---|---|
| DenseNet121 int8 | 109.4 | 14.7 | 16.1 | 7.43x | 1.09x |
| PP-OCRv3 det int8 | 65.7 | 12.7 | 33.1 | 5.15x | 2.60x |
| SFace int8 | 8.1 | 3.0 | 19.0 | 2.75x | 6.43x |
| EfficientNet-Lite4 int8 | 4.1 | 2.9 | 1.9 | 1.40x | 0.67x |
| EfficientNet-Lite4 qdq | 4.6 | 3.1 | 2.0 | 1.49x | 0.65x |
| MP hand pose int8 | 2.5 | 0.8 | 2.2 | 3.06x | 2.69x |
| PPHumanSeg int8 | 2.6 | 1.9 | 5.6 | 1.41x | 3.02x |
Co-authored with @Prasadayus
### 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
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
dnn: avoid unused quadratic workspace for MLAS attention - #30405
`AttentionLayerImpl` allocates a dense `[batch * heads, sequence, sequence]` probability buffer before calling MLAS FlashAttention, even though that path never uses it. With 12 heads and 8,192 tokens, this is an unused 3 GiB allocation that can make inference fail before the tiled kernel runs.
This patch shares the existing fast-path eligibility check between memory planning and execution. It keeps one-element placeholders for the unused probability and output workspaces, preserving the internal buffer indices used by RoPE. If MLAS declines the call, the generic path allocates the dense buffers it needs. Masked attention and builds without MLAS keep their existing workspace plans. The numerical kernels are unchanged.
I reproduced the allocation with a generated FP32 ONNX Attention model loaded through `readNetFromONNX`, using the 5.x graph engine. For batch 1, 12 heads, head width 16 and 8,192 tokens:
| Measurement | Before | After |
| --- | ---: | ---: |
| Largest `cv::Mat` allocation | 3 GiB | 18 MiB |
| Peak live `cv::Mat` storage | 3,279,180,288 bytes | 51,663,368 bytes |
| Forward with a 512 MiB address-space limit | Allocation failure | Completes |
| Peak RSS without the limit | 65,664 KiB | 65,616 KiB |
The allocation trace goes through `allocateLayerOutputs` and `Mat::fit` before the layer's `forward`. The same failure is resolved at 4,096 and 16,384 tokens; at 16,384 tokens, the largest allocation drops from 12 GiB to 36 MiB. Outputs from the constrained runs match the unrestricted runs byte for byte.
The limit above is Linux `RLIMIT_AS`, which limits virtual address space. RSS barely changes because the unused buffer is not touched. The allocation measurements cover `cv::Mat` storage only.
Validation on Linux x86-64:
- 40 targeted tests pass with MLAS in Release, and the same 40 pass under ASan/UBSan with MLAS and SIMD disabled. The workspace regression test fails against the baseline library.
- 56 ONNX baseline/patch comparisons are byte-identical, covering sequence lengths, 1/6 threads, static and dynamic weights, masks, and RoPE. Four of these force `mlasFlashAttention` to return false after dispatch to exercise fallback from a compact workspace plan.
- Reusing a graph across changing sequence lengths passes 40 comparisons against fresh graphs on each version. A separate layer-level matrix adds 144 byte-identical comparisons.
- The existing Attention perf fixture passes all five cases at 1 and 6 threads with `--perf_verify_sanity=true` and no regression data files. This includes new constant-weight cases at 257, 1,024, and 4,096 tokens. Separate longer pinned timing runs measured approximately +0.5% at 257 tokens and -1.1% at 1,024 tokens; timings vary on this shared host, so this PR makes no speedup claim.
The half-input audit passed six configurations that the graph promotes to FP32. Static, unmasked FP16 constants exposed a separate existing weight-packing issue: the baseline already produces invalid outputs, and ASan reports an out-of-bounds read in unchanged packing code. Those cases are excluded from passing validation. ARM and other platforms still need CI.
This follows the MLAS integration in #29126. #30126 addresses a different source of memory use (weight ownership), but touches the same class. `AttentionOnnxAiLayerImpl` is outside this change.
### 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 incompatible with OpenCV.
- [x] The PR targets the proper branch (`5.x`).
- [x] Related work is referenced above; the reproducer and measurements describe the bug.
- [x] Accuracy and performance tests are included. They generate their inputs and require no new `opencv_extra` data.
- [x] No public API changes or new samples requiring documentation.
Remove Tensorflow Importer - #29474
[PR OpenCV Extra](https://github.com/opencv/opencv_extra/pull/1390)
[PR OpenCV Contrib](https://github.com/opencv/opencv_contrib/pull/4171)
Removed tensorflow importers
### 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