From f7ca3a382a311db3a14f956698bb2520bd2d96de Mon Sep 17 00:00:00 2001 From: Prasad Ayush Kumar <129419372+Prasadayus@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:22:12 +0530 Subject: [PATCH] Merge pull request #30416 from Prasadayus:dnn-int8-layer-support support dynamic int8 ConvInteger and MatMulInteger - #30416 Requires: https://github.com/opencv/opencv_extra/pull/1446 Models quantized with ONNX Runtime's dynamic quantization use DynamicQuantizeLinear followed by ConvInteger or MatMulInteger. 5.x has no importer for either op, so none of these models load. ### Models this enables The int8 ONNX files of these models load and run with this PR: - Segmentation: [SAM 3 tracker](https://huggingface.co/onnx-community/sam3-tracker-ONNX), [SAM 2.1 hiera-tiny](https://huggingface.co/onnx-community/sam2.1-hiera-tiny-ONNX), [SegFormer-B3 ADE20K](https://huggingface.co/onnx-community/segformer-b3-finetuned-ade-512-512-ONNX) - Detection: [Grounding DINO tiny](https://huggingface.co/onnx-community/grounding-dino-tiny-ONNX), [OWLv2 base](https://huggingface.co/onnx-community/owlv2-base-patch16-ensemble-ONNX), [RT-DETR R18vd](https://huggingface.co/onnx-community/rtdetr_r18vd), [RF-DETR base](https://huggingface.co/onnx-community/rfdetr_base-ONNX), [YOLO26n](https://huggingface.co/onnx-community/yolo26n-ONNX) - Depth and features: [Depth Anything V2 small](https://huggingface.co/onnx-community/depth-anything-v2-small), [DINOv2 small](https://huggingface.co/onnx-community/dinov2-small), [ViT-B/16](https://huggingface.co/onnx-community/vit-base-patch16-224-ONNX) - Text: [TrOCR base printed](https://huggingface.co/onnx-community/trocr-base-printed-ONNX), [BERT base uncased](https://huggingface.co/Xenova/bert-base-uncased) ### Changes - **ConvInteger** ([opset 10](https://onnx.ai/onnx/operators/onnx__ConvInteger.html)): imported as `Conv2Int8` in a new int32-output mode. The int8 conv kernels (AVX-VNNI, AVX2, NEON, RVV and the scalar path) can now store the int32 accumulators instead of requantizing. Weights and zero points stay inputs, so constant and runtime weights both work. The first commit also fixes the NEON 1x1 fast path, which ignored padding and assumed at least 8 output positions; those cases now take the general path. - **MatMulInteger** ([opset 10](https://onnx.ai/onnx/operators/onnx__MatMulInteger.html)): imported as `MatMulInt8` in a new int32-output mode, backed by a dedicated int8 GEMM in `int8layers/matmul_int8_kernels` (dispatched for AVX2, AVX_VNNI and NEON_DOTPROD, with a universal-intrinsics baseline). A constant B is packed once, and zero points are applied as a correction term so the inner loop is a plain int8 dot product. B can be N-D with broadcast batch dimensions; b_zero_point can be a scalar, one value per column, or per batch and column. A per-row a_zero_point is rejected, as in ONNX Runtime. - ONNX conformance tests `test_basic_convinteger`, `test_convinteger_with_padding`, `test_convinteger_without_padding` and `test_matmulinteger` are enabled (skipped for the OpenVINO backend). ### 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 --- cmake/OpenCVCompilerOptimizations.cmake | 2 +- modules/dnn/CMakeLists.txt | 3 +- .../dnn/include/opencv2/dnn/all_layers.hpp | 10 + modules/dnn/perf/perf_layer.cpp | 35 ++ modules/dnn/src/graph_fusion_qdq.cpp | 4 +- .../dnn/src/graph_fusion_transpose_matmul.cpp | 2 + modules/dnn/src/init.cpp | 1 + .../conv2_int8_kernels.dispatch.cpp | 9 +- .../dnn/src/int8layers/conv2_int8_kernels.hpp | 2 +- .../int8layers/conv2_int8_kernels.simd.hpp | 329 +++++++++++++----- .../dnn/src/int8layers/conv2_int8_layer.cpp | 240 ++++++++++++- .../dnn/src/int8layers/convolution_layer.cpp | 8 +- .../matmul_int8_kernels.dispatch.cpp | 28 ++ .../src/int8layers/matmul_int8_kernels.hpp | 26 ++ .../int8layers/matmul_int8_kernels.simd.hpp | 174 +++++++++ .../dnn/src/int8layers/matmul_int8_layer.cpp | 245 ++++++++++++- .../dnn/src/layers/cpu_kernels/fast_gemm.hpp | 48 +++ modules/dnn/src/layers/matmul_layer.cpp | 48 --- modules/dnn/src/onnx/onnx_importer2.cpp | 24 ++ ...conformance_layer_filter__openvino.inl.hpp | 8 +- ..._conformance_layer_parser_denylist.inl.hpp | 4 - modules/dnn/test/test_onnx_importer.cpp | 63 ++++ 22 files changed, 1160 insertions(+), 153 deletions(-) create mode 100644 modules/dnn/src/int8layers/matmul_int8_kernels.dispatch.cpp create mode 100644 modules/dnn/src/int8layers/matmul_int8_kernels.hpp create mode 100644 modules/dnn/src/int8layers/matmul_int8_kernels.simd.hpp diff --git a/cmake/OpenCVCompilerOptimizations.cmake b/cmake/OpenCVCompilerOptimizations.cmake index 5a9b2db590..10ac3ac852 100644 --- a/cmake/OpenCVCompilerOptimizations.cmake +++ b/cmake/OpenCVCompilerOptimizations.cmake @@ -339,7 +339,7 @@ if(X86 OR X86_64) if(NOT DEFINED CPU_DISPATCH) if(X86_64) - set(CPU_DISPATCH "SSE4_1;SSE4_2;AVX;FP16;AVX2;AVX_VNNI;AVX512_SKX" CACHE STRING "${HELP_CPU_DISPATCH}") + set(CPU_DISPATCH "SSE4_1;SSE4_2;AVX;FP16;AVX2;AVX_VNNI;AVX512_SKX;AVX512_CLX" CACHE STRING "${HELP_CPU_DISPATCH}") else() set(CPU_DISPATCH "SSE4_1;SSE4_2;AVX;FP16" CACHE STRING "${HELP_CPU_DISPATCH}") endif() diff --git a/modules/dnn/CMakeLists.txt b/modules/dnn/CMakeLists.txt index 5c1c311fb4..66d9d08617 100644 --- a/modules/dnn/CMakeLists.txt +++ b/modules/dnn/CMakeLists.txt @@ -13,7 +13,8 @@ ocv_add_dispatched_file_force_all("layers/cpu_kernels/fast_gemm_kernels" AVX AVX ocv_add_dispatched_file("layers/cpu_kernels/conv2_depthwise" AVX AVX2 NEON NEON_FP16) ocv_add_dispatched_file("layers/cpu_kernels/conv2_kernels" AVX AVX2 NEON NEON_FP16) ocv_add_dispatched_file("layers/cpu_kernels/conv2_deconv" AVX AVX2 NEON) -ocv_add_dispatched_file("int8layers/conv2_int8_kernels" AVX2 RVV AVX_VNNI) +ocv_add_dispatched_file("int8layers/conv2_int8_kernels" AVX2 RVV AVX_VNNI AVX512_CLX) +ocv_add_dispatched_file("int8layers/matmul_int8_kernels" AVX2 AVX_VNNI AVX512_CLX NEON_DOTPROD) ocv_add_dispatched_file("layers/cpu_kernels/activation_kernels" AVX AVX2 NEON NEON_FP16) ocv_add_dispatched_file_force_all("layers/cpu_kernels/gridsample_kernels" AVX AVX2 NEON RVV LASX) diff --git a/modules/dnn/include/opencv2/dnn/all_layers.hpp b/modules/dnn/include/opencv2/dnn/all_layers.hpp index f5e50e4921..f45a6c9752 100644 --- a/modules/dnn/include/opencv2/dnn/all_layers.hpp +++ b/modules/dnn/include/opencv2/dnn/all_layers.hpp @@ -420,6 +420,7 @@ CV__DNN_INLINE_NS_BEGIN float input_sc, output_sc; bool per_channel; bool float_input = false; + bool int32_output = false; // ONNX ConvInteger: int32 sums, zero points are inputs std::vector strides, dilations, pads; int ngroups; @@ -1924,6 +1925,15 @@ CV__DNN_INLINE_NS_BEGIN float input_sc, output_sc; int output_type; bool per_channel; + //! ONNX MatMulInteger (opset 10) mode: int32 output, B and both zero points are inputs + bool int32_output = false; + + /** @brief Creates the ONNX MatMulInteger form of the layer. + * @param params layer parameters; "int32_output" must be true, because the requantizing + * int8 form is built only from MatMulInt8Params, by the QDQ fusion + * @return the MatMulInteger layer: Y = (A - a_zero_point) * (B - b_zero_point) in int32 + */ + static Ptr create(const LayerParams& params); static Ptr create(const MatMulInt8Params& params); }; diff --git a/modules/dnn/perf/perf_layer.cpp b/modules/dnn/perf/perf_layer.cpp index 14f2010777..ac3532c0ed 100644 --- a/modules/dnn/perf/perf_layer.cpp +++ b/modules/dnn/perf/perf_layer.cpp @@ -1475,4 +1475,39 @@ PERF_TEST_P_(Layer_Activation, Atanh) { test_activation("Atanh", -0.95f, 0 INSTANTIATE_TEST_CASE_P(/**/, Layer_Activation, testing::Values(std::make_tuple(DNN_BACKEND_OPENCV, DNN_TARGET_CPU))); +struct Layer_DynamicInt8 : public TestBaseWithParam > +{ + void test_model(const std::string& name, const std::vector& inp_shape) + { + std::string model = findDataFile("dnn/onnx/models/" + name + ".onnx", true); + Net net = readNetFromONNX(model, ENGINE_OPENCV); + net.setPreferableBackend(get<0>(GetParam())); + net.setPreferableTarget(get<1>(GetParam())); + + Mat inp(inp_shape, CV_32F); + randu(inp, -1.f, 1.f); + net.setInput(inp); + net.forward(); + + TEST_CYCLE() + { + net.forward(); + } + + SANITY_CHECK_NOTHING(); + } +}; + +PERF_TEST_P_(Layer_DynamicInt8, ConvInteger) +{ + test_model("convinteger_dynamic_block", {1, 3, 256, 256}); +} + +PERF_TEST_P_(Layer_DynamicInt8, MatMulInteger) +{ + test_model("matmulinteger_dynamic_block", {1, 256, 256}); +} + +INSTANTIATE_TEST_CASE_P(/**/, Layer_DynamicInt8, testing::Values(std::make_tuple(DNN_BACKEND_OPENCV, DNN_TARGET_CPU))); + } // namespace diff --git a/modules/dnn/src/graph_fusion_qdq.cpp b/modules/dnn/src/graph_fusion_qdq.cpp index ad5c61c674..fc85728038 100644 --- a/modules/dnn/src/graph_fusion_qdq.cpp +++ b/modules/dnn/src/graph_fusion_qdq.cpp @@ -60,7 +60,7 @@ struct ModelFusionQDQ static bool getInt8OutputParams(Layer* layer, float& sc, int& zp) { if (auto* p = dynamic_cast(layer)) - { sc = p->output_sc; zp = p->output_zp; return true; } + { sc = p->output_sc; zp = p->output_zp; return !p->int32_output; } if (auto* p = dynamic_cast(layer)) { sc = p->output_sc; zp = p->output_zp; return true; } if (auto* p = dynamic_cast(layer)) @@ -1258,7 +1258,7 @@ struct ModelFusionQDQ { if (newprog[j].empty()) continue; Conv2Int8Layer* conv = dynamic_cast(newprog[j].get()); - if (!conv || conv->inputs.empty() || conv->float_input) + if (!conv || conv->inputs.empty() || conv->float_input || conv->int32_output) continue; Arg conv_in0 = conv->inputs[0]; diff --git a/modules/dnn/src/graph_fusion_transpose_matmul.cpp b/modules/dnn/src/graph_fusion_transpose_matmul.cpp index 12ec3f207c..370648ca79 100644 --- a/modules/dnn/src/graph_fusion_transpose_matmul.cpp +++ b/modules/dnn/src/graph_fusion_transpose_matmul.cpp @@ -73,6 +73,8 @@ struct ModelFusionTransposeMatMul MatMulLayer* mm = dynamic_cast(layer.get()); if (!mm) continue; + // MatMulInt8Layer does not read trans_a/trans_b + if (dynamic_cast(layer.get())) continue; if (layer->inputs.size() != 2) continue; diff --git a/modules/dnn/src/init.cpp b/modules/dnn/src/init.cpp index d0afde7778..9261ff6d5f 100644 --- a/modules/dnn/src/init.cpp +++ b/modules/dnn/src/init.cpp @@ -295,6 +295,7 @@ void initializeLayerFactory() CV_DNN_REGISTER_LAYER_CLASS(PoolingInt8, PoolingLayerInt8); CV_DNN_REGISTER_LAYER_CLASS(EltwiseInt8, EltwiseLayerInt8); CV_DNN_REGISTER_LAYER_CLASS(Conv2Int8, Conv2Int8Layer); + CV_DNN_REGISTER_LAYER_CLASS(MatMulInt8, MatMulInt8Layer); CV_DNN_REGISTER_LAYER_CLASS(Pool2Int8, Pool2Int8Layer); CV_DNN_REGISTER_LAYER_CLASS(Eltwise2Int8, Eltwise2Int8Layer); CV_DNN_REGISTER_LAYER_CLASS(BatchNormInt8, BatchNormLayerInt8); diff --git a/modules/dnn/src/int8layers/conv2_int8_kernels.dispatch.cpp b/modules/dnn/src/int8layers/conv2_int8_kernels.dispatch.cpp index 6f2396bb6d..8588bd413c 100644 --- a/modules/dnn/src/int8layers/conv2_int8_kernels.dispatch.cpp +++ b/modules/dnn/src/int8layers/conv2_int8_kernels.dispatch.cpp @@ -23,11 +23,11 @@ void convInt8Block(const void* inp_, const void* residual_, const float* multiplier, int inp_zp, int out_zp, const int8_t* activLUT, - bool inputIsU8) + bool inputIsU8, bool int32Out) { CV_CPU_DISPATCH(convInt8Block, (inp_, residual_, out_, cs, weights_, weightsVNNI_, bias, biasVNNI_, multiplier, inp_zp, out_zp, - activLUT, inputIsU8), + activLUT, inputIsU8, int32Out), CV_CPU_DISPATCH_MODES_ALL); } @@ -36,10 +36,13 @@ void fastConvVNNI( const int8_t* weights, size_t wstep, const int* bias, int blockSize, int vecsize, int vecsize_aligned, int outZp, const float* multiplier, bool initOutput, bool finalOutput ) { + CV_CPU_CALL_AVX512_CLX(fastConvVNNI, (weights, wstep, bias, rowbuf, output, outShape, + blockSize, vecsize, vecsize_aligned, outZp, + multiplier, initOutput, finalOutput)); CV_CPU_CALL_AVX_VNNI(fastConvVNNI, (weights, wstep, bias, rowbuf, output, outShape, blockSize, vecsize, vecsize_aligned, outZp, multiplier, initOutput, finalOutput)); - CV_Error(Error::StsNotImplemented, "DNN/INT8: AVX-VNNI convolution kernel is not available"); + CV_Error(Error::StsNotImplemented, "DNN/INT8: VNNI convolution kernel is not available"); } } diff --git a/modules/dnn/src/int8layers/conv2_int8_kernels.hpp b/modules/dnn/src/int8layers/conv2_int8_kernels.hpp index cb4a060c5a..bbce24ea86 100644 --- a/modules/dnn/src/int8layers/conv2_int8_kernels.hpp +++ b/modules/dnn/src/int8layers/conv2_int8_kernels.hpp @@ -25,7 +25,7 @@ void convInt8Block(const void* inp_, const void* residual_, const float* multiplier, int inp_zp, int out_zp, const int8_t* activLUT, - bool inputIsU8); + bool inputIsU8, bool int32Out); // AVX-VNNI kernel of the legacy int8 convolution layer. Built only when CMake found // a toolchain that can encode AVX-VNNI, so ask CV_CPU_HAS_SUPPORT_AVX_VNNI before diff --git a/modules/dnn/src/int8layers/conv2_int8_kernels.simd.hpp b/modules/dnn/src/int8layers/conv2_int8_kernels.simd.hpp index 494e21c70c..8982a8bea2 100644 --- a/modules/dnn/src/int8layers/conv2_int8_kernels.simd.hpp +++ b/modules/dnn/src/int8layers/conv2_int8_kernels.simd.hpp @@ -6,6 +6,7 @@ #include "opencv2/core/hal/intrin.hpp" #include "../layers/conv2_common.hpp" +#include #if CV_AVX2 && (defined(__x86_64__) || defined(_M_X64)) #include #endif @@ -22,10 +23,10 @@ void convInt8Block(const void* inp_, const void* residual_, const float* multiplier, int inp_zp, int out_zp, const int8_t* activLUT, - bool inputIsU8); + bool inputIsU8, bool int32Out); -// AVX-VNNI kernel of the legacy int8 convolution layer (im2col + GEMM). -// Only the AVX_VNNI build of this file defines it. +// VNNI kernel of the legacy int8 convolution layer (im2col + GEMM). +// Only the AVX_VNNI and AVX512_CLX builds of this file define it. void fastConvVNNI( const int8_t* weights, size_t wstep, const int* bias, const uint8_t* rowbuf, int* output, const int* outShape, int blockSize, int vecsize, int vecsize_aligned, int outZp, @@ -33,10 +34,18 @@ void fastConvVNNI( const int8_t* weights, size_t wstep, const int* bias, #if !defined(CV_CPU_OPTIMIZATION_DECLARATIONS_ONLY) +// kernel output element: requantized int8, or the raw int32 sums of ONNX ConvInteger +template using ConvInt8Out = std::conditional_t; + #if CV_NEON && defined(CV_NEON_DOT) && CV_NEON_DOT #include -#define CONV_NEON_STORE(j) { \ +#define CONV_NEON_STORE32(j) { \ + vst1q_s32(outptr + (p + (j)) * K0, s##j##_lo); \ + vst1q_s32(outptr + (p + (j)) * K0 + 4, s##j##_hi); \ +} + +#define CONV_NEON_STORE(j) if constexpr (INT32_OUT) CONV_NEON_STORE32(j) else { \ float32x4_t facc_lo = vfmaq_f32(vzp, vcvtq_f32_s32(s##j##_lo), vmult_lo); \ float32x4_t facc_hi = vfmaq_f32(vzp, vcvtq_f32_s32(s##j##_hi), vmult_hi); \ if (resptr) { \ @@ -84,6 +93,7 @@ void fastConvVNNI( const int8_t* weights, size_t wstep, const int* bias, } \ } +template static void convInt8BlockNEON(const void* inp_, const void* residual_, void* out_, const ConvState& cs, const void* weightsVNNI_, @@ -92,9 +102,9 @@ static void convInt8BlockNEON(const void* inp_, const void* residual_, const int8_t* activLUT, bool inputIsU8) { - constexpr int C0 = 8, K0 = 8; - constexpr int C0shift = 3; - constexpr int SPAT_BLOCK_SIZE = 8; + static constexpr int C0 = 8, K0 = 8; + static constexpr int C0shift = 3; + static constexpr int SPAT_BLOCK_SIZE = 8; constexpr int MAX_CONV_DIMS = ConvState::MAX_CONV_DIMS; CV_Assert(cs.inpshape.layout == DATA_LAYOUT_BLOCK); @@ -125,18 +135,20 @@ static void convInt8BlockNEON(const void* inp_, const void* residual_, const int8_t* inp = (const int8_t*)inp_; const int8_t* residual = (const int8_t*)residual_; - int8_t* out = (int8_t*)out_; + typedef ConvInt8Out out_t; + out_t* out = (out_t*)out_; const int8_t* wdata = (const int8_t*)weightsVNNI_; const int* ofsZYX = cs.coordtab.data(); size_t outtotal = outshape.total(); - if ((Kg % K0) != 0) memset(out, 0, outtotal); + if ((Kg % K0) != 0) memset(out, 0, outtotal * sizeof(out_t)); const int8x16_t v_xor = inputIsU8 ? vdupq_n_s8((int8_t)0x80) : vdupq_n_s8(0); int Sz = cs.strides[0], Sy = cs.strides[1], Sx = cs.strides[2]; - if (ksize_ == 1 && Sx == 1 && Sy == 1 && Sz == 1) { + if (ksize_ == 1 && Sx == 1 && Sy == 1 && Sz == 1 && !cs.hasPadding() && + planeblocks_ >= SPAT_BLOCK_SIZE) { int total_spatial = planeblocks_; int iplanesize = total_spatial * C0; int cblocks_g = (Cg + C0 - 1) / C0; @@ -189,7 +201,7 @@ static void convInt8BlockNEON(const void* inp_, const void* residual_, if (k_base >= K) continue; int k1 = k_base >> C0shift; - int8_t* outptr = out + (size_t)(n * K1 + k1) * planesize; + out_t* outptr = out + (size_t)(n * K1 + k1) * planesize; const int8_t* resptr = residual ? residual + (size_t)(n * K1 + k1) * planesize : nullptr; const int8_t* wbaseptr = wdata + (size_t)(g * Kblk + kblk) * C1Max * C0 * K0; @@ -198,6 +210,8 @@ static void convInt8BlockNEON(const void* inp_, const void* residual_, float32x4_t vmult_lo = vld1q_f32(multiplier + k_base); float32x4_t vmult_hi = vld1q_f32(multiplier + k_base + 4); float32x4_t vzp = vdupq_n_f32((float)out_zp); + // only the int8 store reads these + CV_UNUSED(resptr); CV_UNUSED(vmult_lo); CV_UNUSED(vmult_hi); CV_UNUSED(vzp); int p = p_start; for (; p <= p_end - SPAT_BLOCK_SIZE; p += SPAT_BLOCK_SIZE) { @@ -332,7 +346,7 @@ static void convInt8BlockNEON(const void* inp_, const void* residual_, const int8_t* wbaseptr = wdata + (size_t)(g * Kblk + kblk) * ksize * C1Max * C0 * K0; int k1 = k_base >> C0shift; - int8_t* outptr = out + (size_t)(n * K1 + k1) * planesize; + out_t* outptr = out + (size_t)(n * K1 + k1) * planesize; const int8_t* resptr = residual ? residual + (size_t)(n * K1 + k1) * planesize : nullptr; int32x4_t vbias_lo = vld1q_s32(bias + k_base); @@ -340,6 +354,8 @@ static void convInt8BlockNEON(const void* inp_, const void* residual_, float32x4_t vmult_lo = vld1q_f32(multiplier + k_base); float32x4_t vmult_hi = vld1q_f32(multiplier + k_base + 4); float32x4_t vzp = vdupq_n_f32((float)out_zp); + // only the int8 store reads these + CV_UNUSED(vmult_lo); CV_UNUSED(vmult_hi); CV_UNUSED(vzp); int H_l = H, W_l = W; int Di_l = Di, Hi_l = Hi, Wi_l = Wi; @@ -511,8 +527,12 @@ static void convInt8BlockNEON(const void* inp_, const void* residual_, } } } - int8_t* optr = outptr + p * K0; + out_t* optr = outptr + p * K0; const int8_t* rptr = resptr ? resptr + p * K0 : nullptr; + if constexpr (INT32_OUT) { + memcpy(optr, acc, sizeof(acc)); + continue; + } for (int k0 = 0; k0 < K0; k0++) { float val = (float)acc[k0] * multiplier[k_base + k0] + (float)out_zp; if (rptr) { @@ -535,6 +555,7 @@ static void convInt8BlockNEON(const void* inp_, const void* residual_, }); } #undef CONV_NEON_STORE +#undef CONV_NEON_STORE32 #endif // CV_NEON && CV_NEON_DOT #if CV_RVV @@ -577,6 +598,8 @@ struct ConvInt8RVV_M1 vint16mf2_t x16 = __riscv_vncvt_x_x_w_i16mf2(x, vl); __riscv_vse8_v_i8mf4(dst, __riscv_vncvt_x_x_w_i8mf4(x16, vl), vl); } + static inline void store32(int32_t* p, vi32 x, size_t vl) + { __riscv_vse32_v_i32m1(p, x, vl); } }; struct ConvInt8RVV_M2 @@ -610,6 +633,8 @@ struct ConvInt8RVV_M2 vint16m1_t x16 = __riscv_vncvt_x_x_w_i16m1(x, vl); __riscv_vse8_v_i8mf2(dst, __riscv_vncvt_x_x_w_i8mf2(x16, vl), vl); } + static inline void store32(int32_t* p, vi32 x, size_t vl) + { __riscv_vse32_v_i32m2(p, x, vl); } }; // vfcvt.x.f.v uses the current FP rounding mode; Linux default is RNE, @@ -626,7 +651,9 @@ struct ConvInt8RVV_M2 acc##j = RVV::vwmacc(acc##j, (int16_t)(int8_t)((uint8_t)ipj[7] ^ xor_val), w7, vl); \ } -#define CONV_RVV_STORE(j) { \ +#define CONV_RVV_STORE32(j) { RVV::store32(outptr + (size_t)(p + (j)) * K0, acc##j, vl); } + +#define CONV_RVV_STORE(j) if constexpr (INT32_OUT) CONV_RVV_STORE32(j) else { \ typename RVV::vf32 facc = RVV::fmadd(RVV::tofloat(acc##j, vl), vmult, vzp, vl); \ int8_t* optrj = outptr + (size_t)(p + (j)) * K0; \ if (resptr) { \ @@ -656,7 +683,7 @@ struct ConvInt8RVV_M2 } \ } -template +template static void convInt8BlockRVV(const void* inp_, const void* residual_, void* out_, const ConvState& cs, const void* weights_, @@ -665,9 +692,9 @@ static void convInt8BlockRVV(const void* inp_, const void* residual_, const int8_t* activLUT, bool inputIsU8) { - constexpr int C0 = 8, K0 = 8; - constexpr int C0shift = 3; - constexpr int SPAT_BLOCK_SIZE = 8; + static constexpr int C0 = 8, K0 = 8; + static constexpr int C0shift = 3; + static constexpr int SPAT_BLOCK_SIZE = 8; constexpr int MAX_CONV_DIMS = ConvState::MAX_CONV_DIMS; CV_Assert(cs.inpshape.layout == DATA_LAYOUT_BLOCK); @@ -702,13 +729,14 @@ static void convInt8BlockRVV(const void* inp_, const void* residual_, const int8_t* inp = (const int8_t*)inp_; const int8_t* residual = (const int8_t*)residual_; - int8_t* out = (int8_t*)out_; + typedef ConvInt8Out out_t; + out_t* out = (out_t*)out_; const int8_t* wdata = (const int8_t*)weights_; const int* ofsZYX = cs.coordtab.data(); size_t outtotal = outshape.total(); if ((Kg % K0) != 0) - memset(out, 0, outtotal); + memset(out, 0, outtotal * sizeof(out_t)); int total_blocks = N * ngroups * Kblk; @@ -749,7 +777,7 @@ static void convInt8BlockRVV(const void* inp_, const void* residual_, const int8_t* wbaseptr = wdata + (size_t)(g * Kblk + kblk) * ksize * C1Max * C0 * K0; int k1 = k_base >> C0shift; - int8_t* outptr = out + (size_t)(n * K1 + k1) * planesize; + out_t* outptr = out + (size_t)(n * K1 + k1) * planesize; const int8_t* resptr = residual ? residual + (size_t)(n * K1 + k1) * planesize : nullptr; int D_l = D, H_l = H, W_l = W; @@ -779,6 +807,8 @@ static void convInt8BlockRVV(const void* inp_, const void* residual_, typename RVV::vi32 vbias = RVV::vle32(biasbuf, vl); typename RVV::vf32 vmult = RVV::vle32f(multbuf, vl); typename RVV::vf32 vzp = RVV::vfmv((float)out_zp, vl); + // only the int8 store reads these + CV_UNUSED(vmult); CV_UNUSED(vzp); int p = 0; for (; p < planeblocks_l; p += SPAT_BLOCK_SIZE) { @@ -903,8 +933,12 @@ static void convInt8BlockRVV(const void* inp_, const void* residual_, } } - int8_t* optr = outptr + p * K0; + out_t* optr = outptr + p * K0; const int8_t* rptr = resptr ? resptr + p * K0 : nullptr; + if constexpr (INT32_OUT) { + memcpy(optr, acc, sizeof(acc)); + continue; + } for (int k0 = 0; k0 < K0; k0++) { float val = (float)acc[k0] * multbuf[k0] + (float)out_zp; if (rptr) { @@ -929,9 +963,25 @@ static void convInt8BlockRVV(const void* inp_, const void* residual_, #undef CONV_RVV_MAC #undef CONV_RVV_STORE +#undef CONV_RVV_STORE32 #endif // CV_RVV +#if CV_AVX2 && (defined(__x86_64__) || defined(_M_X64)) +// stores the first n of the 8 int32 lanes +static inline void storeInt32x8(int32_t* dst, __m256i v, int n) +{ + if (n == 8) { + _mm256_storeu_si256((__m256i*)dst, v); + } else { + alignas(32) int32_t buf[8]; + _mm256_store_si256((__m256i*)buf, v); + memcpy(dst, buf, n * sizeof(int32_t)); + } +} +#endif + // INT8 depthwise convolution kernel (ngroups==K==C, Kg==Cg==1). +template static void convInt8BlockDepthwise(const void* inp_, const void* residual_, void* out_, const ConvState& cs, const void* weights_, @@ -975,7 +1025,8 @@ static void convInt8BlockDepthwise(const void* inp_, const void* residual_, const int8_t* inp = (const int8_t*)inp_; const int8_t* residual = (const int8_t*)residual_; - int8_t* out = (int8_t*)out_; + typedef ConvInt8Out out_t; + out_t* out = (out_t*)out_; const int8_t* wdata = (const int8_t*)weights_; const int* ofsZYX = cs.coordtab.data(); @@ -1014,7 +1065,7 @@ static void convInt8BlockDepthwise(const void* inp_, const void* residual_, int p_task_end = std::min(p_task_start + TILE, planeblocks); const int8_t* inpbaseptr = inp + (size_t)(n * C1 + k1) * iplanesize; - int8_t* outbase = out + (size_t)(n * K1 + k1) * planesize; + out_t* outbase = out + (size_t)(n * K1 + k1) * planesize; const int8_t* resbase = residual ? residual + (size_t)(n * K1 + k1) * planesize : nullptr; @@ -1155,7 +1206,8 @@ static void convInt8BlockDepthwise(const void* inp_, const void* residual_, } } - #define DW_STORE(j) { \ + #define DW_STORE32(j) { storeInt32x8(outbase + (p + (j)) * K0, s##j, n_g); } + #define DW_STORE(j) if constexpr (INT32_OUT) DW_STORE32(j) else { \ __m256 facc = _mm256_add_ps( \ _mm256_mul_ps(_mm256_cvtepi32_ps(s##j), vmult), vzp); \ int8_t* optr = outbase + (p + (j)) * K0; \ @@ -1195,6 +1247,7 @@ static void convInt8BlockDepthwise(const void* inp_, const void* residual_, DW_STORE(0); DW_STORE(1); DW_STORE(2); DW_STORE(3); DW_STORE(4); DW_STORE(5); DW_STORE(6); DW_STORE(7); #undef DW_STORE + #undef DW_STORE32 } for (; p < p_task_end; p++) { int zj = p / (H * W); @@ -1222,9 +1275,13 @@ static void convInt8BlockDepthwise(const void* inp_, const void* residual_, _mm_loadl_epi64((const __m128i*)(wbuf + i*K0))); acc = _mm256_add_epi32(acc, _mm256_mullo_epi32(inp32, w32)); } + if constexpr (INT32_OUT) { + storeInt32x8(outbase + p * K0, acc, n_g); + continue; + } __m256 facc = _mm256_add_ps( _mm256_mul_ps(_mm256_cvtepi32_ps(acc), vmult), vzp); - int8_t* optr = outbase + p * K0; + out_t* optr = outbase + p * K0; const int8_t* rptr = resbase ? resbase + p * K0 : nullptr; if (rptr) { facc = _mm256_add_ps(facc, _mm256_sub_ps(_mm256_cvtepi32_ps( @@ -1270,7 +1327,7 @@ static void convInt8BlockDepthwise(const void* inp_, const void* residual_, int yi_base = yj * Sy - padY; int xi_base = xj * Sx - padX; - int8_t* optr = outbase + p * K0; + out_t* optr = outbase + p * K0; const int8_t* rptr = resbase ? resbase + p * K0 : nullptr; for (int g = g_start; g < g_end; g++) { @@ -1310,6 +1367,10 @@ static void convInt8BlockDepthwise(const void* inp_, const void* residual_, } } + if constexpr (INT32_OUT) { + optr[j] = acc; + continue; + } float val = (float)acc * multiplier[g] + (float)out_zp; if (rptr) val += (float)((int)rptr[j] - out_zp); int ival = cvRound(val); @@ -1328,14 +1389,16 @@ static void convInt8BlockDepthwise(const void* inp_, const void* residual_, }); } -#if CV_AVX_VNNI +#if CV_AVX_VNNI || CV_AVX_512VNNI -//////////////////////////// AVX-VNNI kernels //////////////////////////// +//////////////////////////// VNNI kernels //////////////////////////// // +// The same 256-bit code serves AVX-VNNI and AVX-512 VNNI, whose VL form runs VPDPBUSD on ymm. // VPDPBUSD multiplies unsigned activations by signed weights, so these kernels // consume the uint8 input directly and use the VNNI-reordered weights/bias // (weightsVNNI_/biasVNNI_) prepared by the layer. +template static void convInt8BlockVNNI_kxk(const void* inp_, const void* residual_, void* out_, const ConvState& cs, const void* weightsVNNI_, @@ -1345,7 +1408,7 @@ static void convInt8BlockVNNI_kxk(const void* inp_, const void* residual_, bool inputIsU8) { constexpr int C0 = 8, K0 = 8; - constexpr int SPAT_BLOCK_SIZE = 8; + static constexpr int SPAT_BLOCK_SIZE = 8; constexpr int MAX_CONV_DIMS = ConvState::MAX_CONV_DIMS; CV_Assert(cs.inpshape.layout == DATA_LAYOUT_BLOCK); @@ -1380,12 +1443,13 @@ static void convInt8BlockVNNI_kxk(const void* inp_, const void* residual_, const int8_t* inp = (const int8_t*)inp_; const int8_t* residual = (const int8_t*)residual_; - int8_t* out = (int8_t*)out_; + typedef ConvInt8Out out_t; + out_t* out = (out_t*)out_; const int8_t* wdata = (const int8_t*)weightsVNNI_; const int* ofsZYX = cs.coordtab.data(); size_t outtotal = outshape.total(); - if ((Kg % K0) != 0) memset(out, 0, outtotal); + if ((Kg % K0) != 0) memset(out, 0, outtotal * sizeof(out_t)); int nkb = N * ngroups * Kblk; int nthreads = std::max(1, cv::getNumThreads()); @@ -1436,7 +1500,7 @@ static void convInt8BlockVNNI_kxk(const void* inp_, const void* residual_, const int8_t* wbaseptr = wdata + (size_t)(g * Kblk + kblk) * ksize * C1Max * C0 * K0; int k1 = k_base >> C0shift; - int8_t* outptr = out + (size_t)(n * K1 + k1) * planesize; + out_t* outptr = out + (size_t)(n * K1 + k1) * planesize; const int8_t* resptr = residual ? residual + (size_t)(n * K1 + k1) * planesize : nullptr; const int k_valid = std::min(K0, K - k_base); @@ -1586,8 +1650,19 @@ static void convInt8BlockVNNI_kxk(const void* inp_, const void* residual_, __m256 vmult = _mm256_load_ps(multbuf); __m256 vzp = _mm256_set1_ps((float)out_zp); + // only the int8 store reads these + CV_UNUSED(vmult); CV_UNUSED(vzp); - #define CONV_VNNI_STORE(j) { \ + #define CONV_VNNI_STORE32(j) { \ + if (!cs.depthwise) { \ + _mm256_storeu_si256((__m256i*)(outptr + (p + (j)) * K0), s##j); \ + } else { \ + alignas(32) int32_t tmp32[K0]; \ + _mm256_store_si256((__m256i*)tmp32, s##j); \ + outptr[(p + (j)) * K0 + k0_off_dw] = tmp32[k0_off_dw]; \ + } \ + } + #define CONV_VNNI_STORE(j) if constexpr (INT32_OUT) CONV_VNNI_STORE32(j) else { \ __m256 facc = _mm256_add_ps( \ _mm256_mul_ps(_mm256_cvtepi32_ps(s##j), vmult), vzp); \ if (resptr) { \ @@ -1629,6 +1704,7 @@ static void convInt8BlockVNNI_kxk(const void* inp_, const void* residual_, CONV_VNNI_STORE(4); CONV_VNNI_STORE(5); CONV_VNNI_STORE(6); CONV_VNNI_STORE(7); #undef CONV_VNNI_STORE + #undef CONV_VNNI_STORE32 } // Scalar tail @@ -1666,10 +1742,15 @@ static void convInt8BlockVNNI_kxk(const void* inp_, const void* residual_, } } } - int8_t* optr = outptr + p * K0; + out_t* optr = outptr + p * K0; const int8_t* rptr = resptr ? resptr + p * K0 : nullptr; int k0_lo = cs.depthwise ? k0_off_dw : 0; int k0_hi = cs.depthwise ? k0_off_dw + 1 : K0; + if constexpr (INT32_OUT) { + for (int k0 = k0_lo; k0 < k0_hi; k0++) + optr[k0] = acc[k0]; + continue; + } for (int k0 = k0_lo; k0 < k0_hi; k0++) { float val = (float)acc[k0] * multbuf[k0] + (float)out_zp; if (rptr) val += (float)((int)rptr[k0] - out_zp); @@ -1689,6 +1770,7 @@ static void convInt8BlockVNNI_kxk(const void* inp_, const void* residual_, }); } +template static void convInt8BlockVNNI_1x1(const void* inp_, const void* residual_, void* out_, const ConvState& cs, const void* weightsVNNI_, @@ -1698,7 +1780,7 @@ static void convInt8BlockVNNI_1x1(const void* inp_, const void* residual_, bool inputIsU8) { constexpr int C0 = 8, K0 = 8; - constexpr int SPAT_BLOCK_SIZE = 8; + static constexpr int SPAT_BLOCK_SIZE = 8; const MatShape& inpshape = cs.inpshape; const MatShape& outshape = cs.outshape; @@ -1728,14 +1810,15 @@ static void convInt8BlockVNNI_1x1(const void* inp_, const void* residual_, const int8_t* inp = (const int8_t*)inp_; const int8_t* residual = (const int8_t*)residual_; - int8_t* out = (int8_t*)out_; + typedef ConvInt8Out out_t; + out_t* out = (out_t*)out_; const int8_t* wdata = (const int8_t*)weightsVNNI_; int iplanesize = Pi * C0; int planesize = P * K0; if ((Kg % K0) != 0) - memset(out, 0, outshape.total()); + memset(out, 0, outshape.total() * sizeof(out_t)); constexpr int SB_TILE = 8; int nthreads = std::max(1, cv::getNumThreads()); @@ -1772,7 +1855,7 @@ static void convInt8BlockVNNI_1x1(const void* inp_, const void* residual_, const int8_t* wbaseptr = wdata + (size_t)(g * Kblk + kblk) * C1Max * C0 * K0; int k1 = k_base >> C0shift; - int8_t* outptr = out + (size_t)(n * K1 + k1) * planesize; + out_t* outptr = out + (size_t)(n * K1 + k1) * planesize; const int8_t* resptr = residual ? residual + (size_t)(n * K1 + k1) * planesize : nullptr; const int k_valid = std::min(K0, K - k_base); @@ -1820,8 +1903,13 @@ static void convInt8BlockVNNI_1x1(const void* inp_, const void* residual_, __m256 vmult = _mm256_load_ps(multbuf); __m256 vzp = _mm256_set1_ps((float)out_zp); + // only the int8 store reads these + CV_UNUSED(vmult); CV_UNUSED(vzp); - #define CONV_1x1_STORE(j) { \ + #define CONV_1x1_STORE32(j) { \ + _mm256_storeu_si256((__m256i*)(outptr + (p + (j)) * K0), s##j); \ + } + #define CONV_1x1_STORE(j) if constexpr (INT32_OUT) CONV_1x1_STORE32(j) else { \ __m256 facc = _mm256_add_ps( \ _mm256_mul_ps(_mm256_cvtepi32_ps(s##j), vmult), vzp); \ if (resptr) { \ @@ -1854,6 +1942,7 @@ static void convInt8BlockVNNI_1x1(const void* inp_, const void* residual_, CONV_1x1_STORE(4); CONV_1x1_STORE(5); CONV_1x1_STORE(6); CONV_1x1_STORE(7); #undef CONV_1x1_STORE + #undef CONV_1x1_STORE32 } for (; p < p_end; p++) { @@ -1871,8 +1960,12 @@ static void convInt8BlockVNNI_1x1(const void* inp_, const void* residual_, alignas(32) int32_t acc[K0]; _mm256_store_si256((__m256i*)acc, s); - int8_t* optr = outptr + (size_t)p * K0; + out_t* optr = outptr + (size_t)p * K0; const int8_t* rptr = resptr ? resptr + (size_t)p * K0 : nullptr; + if constexpr (INT32_OUT) { + memcpy(optr, acc, sizeof(acc)); + continue; + } for (int k0 = 0; k0 < K0; k0++) { float val = (float)acc[k0] * multbuf[k0] + (float)out_zp; if (rptr) { @@ -1895,12 +1988,36 @@ static void convInt8BlockVNNI_1x1(const void* inp_, const void* residual_, }); } +// 8 vectors of 8 pixels per channel into 8 vectors of 8 channels per pixel +static inline void transpose8x8Int32(__m256i r0, __m256i r1, __m256i r2, __m256i r3, + __m256i r4, __m256i r5, __m256i r6, __m256i r7, + __m256i* dst) +{ + __m256i t0 = _mm256_unpacklo_epi32(r0, r1), t1 = _mm256_unpackhi_epi32(r0, r1); + __m256i t2 = _mm256_unpacklo_epi32(r2, r3), t3 = _mm256_unpackhi_epi32(r2, r3); + __m256i t4 = _mm256_unpacklo_epi32(r4, r5), t5 = _mm256_unpackhi_epi32(r4, r5); + __m256i t6 = _mm256_unpacklo_epi32(r6, r7), t7 = _mm256_unpackhi_epi32(r6, r7); + __m256i u0 = _mm256_unpacklo_epi64(t0, t2), u1 = _mm256_unpackhi_epi64(t0, t2); + __m256i u2 = _mm256_unpacklo_epi64(t1, t3), u3 = _mm256_unpackhi_epi64(t1, t3); + __m256i u4 = _mm256_unpacklo_epi64(t4, t6), u5 = _mm256_unpackhi_epi64(t4, t6); + __m256i u6 = _mm256_unpacklo_epi64(t5, t7), u7 = _mm256_unpackhi_epi64(t5, t7); + dst[0] = _mm256_permute2x128_si256(u0, u4, 0x20); + dst[1] = _mm256_permute2x128_si256(u1, u5, 0x20); + dst[2] = _mm256_permute2x128_si256(u2, u6, 0x20); + dst[3] = _mm256_permute2x128_si256(u3, u7, 0x20); + dst[4] = _mm256_permute2x128_si256(u0, u4, 0x31); + dst[5] = _mm256_permute2x128_si256(u1, u5, 0x31); + dst[6] = _mm256_permute2x128_si256(u2, u6, 0x31); + dst[7] = _mm256_permute2x128_si256(u3, u7, 0x31); +} + +template static bool convInt8BlockDepthwiseVNNI(const void* inp_, void* out_, const ConvState& cs, const void* weights_, const int* bias, const float* multiplier, int inp_zp, int out_zp, const int8_t* activLUT, bool inputIsU8) { - constexpr int C0 = 8, K0 = 8; + static constexpr int C0 = 8, K0 = 8; const MatShape& inpshape = cs.inpshape; const MatShape& outshape = cs.outshape; if (cs.nspatialdims != 2 || inpshape.dims != 5 || outshape.dims != 5) @@ -1930,7 +2047,8 @@ static bool convInt8BlockDepthwiseVNNI(const void* inp_, void* out_, const ConvS const int maxRows = (band - 1) * sy + (kh - 1) * dy + 1; const int8_t* inp = (const int8_t*)inp_; - int8_t* out = (int8_t*)out_; + typedef ConvInt8Out out_t; + out_t* out = (out_t*)out_; const int8_t* wdata = (const int8_t*)weights_; const int* ofsZYX = cs.coordtab.data(); @@ -2020,7 +2138,7 @@ static bool convInt8BlockDepthwiseVNNI(const void* inp_, void* out_, const ConvS for (int oy = oy0; oy < oy1; oy++) { const uint8_t* rbase = planar + (size_t)(oy - oy0) * sy * C0 * Wp; - int8_t* orow = out + ((size_t)(n * K1 + k1) * Ho + oy) * Wo * K0; + out_t* orow = out + ((size_t)(n * K1 + k1) * Ho + oy) * Wo * K0; for (int ox0 = 0; ox0 < Wo; ox0 += 8) { __m256i s0 = _mm256_set1_epi32(biasv[0]), s1 = _mm256_set1_epi32(biasv[1]); __m256i s2 = _mm256_set1_epi32(biasv[2]), s3 = _mm256_set1_epi32(biasv[3]); @@ -2044,6 +2162,16 @@ static bool convInt8BlockDepthwiseVNNI(const void* inp_, void* out_, const ConvS } } + if constexpr (INT32_OUT) { + __m256i px[8]; + transpose8x8Int32(s0, s1, s2, s3, s4, s5, s6, s7, px); + out_t* optr = orow + (size_t)ox0 * K0; + const int npix = std::min(8, Wo - ox0); + for (int j = 0; j < npix; j++) + storeInt32x8(optr + j * K0, px[j], n_g); + continue; + } + #define DWV_Q(c) _mm256_cvtps_epi32(_mm256_add_ps(_mm256_mul_ps( \ _mm256_cvtepi32_ps(s##c), _mm256_set1_ps(multv[c])), vzp)) __m256i p01 = _mm256_packs_epi32(DWV_Q(0), DWV_Q(1)); @@ -2060,7 +2188,7 @@ static bool convInt8BlockDepthwiseVNNI(const void* inp_, void* out_, const ConvS __m256i px03 = _mm256_permute2x128_si256(lo, hi, 0x20); __m256i px47 = _mm256_permute2x128_si256(lo, hi, 0x31); - int8_t* optr = orow + (size_t)ox0 * K0; + out_t* optr = orow + (size_t)ox0 * K0; const int npix = std::min(8, Wo - ox0); if (npix == 8 && n_g == K0 && !activLUT) { _mm256_storeu_si256((__m256i*)optr, px03); @@ -2070,7 +2198,7 @@ static bool convInt8BlockDepthwiseVNNI(const void* inp_, void* out_, const ConvS _mm256_store_si256((__m256i*)tmp, px03); _mm256_store_si256((__m256i*)(tmp + 32), px47); for (int j = 0; j < npix; j++) { - int8_t* o = optr + j * K0; + out_t* o = optr + j * K0; const int8_t* tj = tmp + j * K0; if (!activLUT) memcpy(o, tj, n_g); @@ -2089,6 +2217,7 @@ static bool convInt8BlockDepthwiseVNNI(const void* inp_, void* out_, const ConvS return true; } +template static void convInt8BlockVNNI(const void* inp_, const void* residual_, void* out_, const ConvState& cs, const void* weightsVNNI_, @@ -2099,16 +2228,16 @@ static void convInt8BlockVNNI(const void* inp_, const void* residual_, { if (cs.wshape[2] == 1 && !cs.hasPadding() && cs.strides[0] == 1 && cs.strides[1] == 1 && cs.strides[2] == 1) { - convInt8BlockVNNI_1x1(inp_, residual_, out_, cs, weightsVNNI_, - biasVNNI, multiplier, inp_zp, out_zp, activLUT, inputIsU8); + convInt8BlockVNNI_1x1(inp_, residual_, out_, cs, weightsVNNI_, biasVNNI, + multiplier, inp_zp, out_zp, activLUT, inputIsU8); return; } - convInt8BlockVNNI_kxk(inp_, residual_, out_, cs, weightsVNNI_, - biasVNNI, multiplier, inp_zp, out_zp, activLUT, inputIsU8); + convInt8BlockVNNI_kxk(inp_, residual_, out_, cs, weightsVNNI_, biasVNNI, + multiplier, inp_zp, out_zp, activLUT, inputIsU8); } -// Legacy int8 convolution (im2col + GEMM) AVX-VNNI kernel, used by -// int8layers/convolution_layer.cpp. It lives here so that every AVX-VNNI int8 +// Legacy int8 convolution (im2col + GEMM) VNNI kernel, used by +// int8layers/convolution_layer.cpp. It lives here so that every VNNI int8 // code path shares a single dispatched translation unit. enum { FASCONV_BASE_VECSZ = 4 }; @@ -2333,46 +2462,50 @@ void fastConvVNNI( const int8_t* weights, size_t wstep, const int* bias, _mm256_zeroupper(); } -#endif // CV_AVX_VNNI +#endif // CV_AVX_VNNI || CV_AVX_512VNNI -void convInt8Block(const void* inp_, const void* residual_, - void* out_, const ConvState& cs, - const void* weights_, - const void* weightsVNNI_, - const int* bias, const int* biasVNNI_, - const float* multiplier, - int inp_zp, int out_zp, - const int8_t* activLUT, - bool inputIsU8) +template +static void convInt8BlockImpl(const void* inp_, const void* residual_, + void* out_, const ConvState& cs, + const void* weights_, + const void* weightsVNNI_, + const int* bias, const int* biasVNNI_, + const float* multiplier, + int inp_zp, int out_zp, + const int8_t* activLUT, + bool inputIsU8) { // Depthwise convolution has a dedicated kernel. if (cs.depthwise) { const int* dw_bias = biasVNNI_ ? biasVNNI_ : bias; -#if CV_AVX_VNNI - if (!residual_ && convInt8BlockDepthwiseVNNI(inp_, out_, cs, weights_, dw_bias, multiplier, - inp_zp, out_zp, activLUT, inputIsU8)) +#if CV_AVX_VNNI || CV_AVX_512VNNI + if (!residual_ && convInt8BlockDepthwiseVNNI(inp_, out_, cs, weights_, dw_bias, + multiplier, inp_zp, out_zp, + activLUT, inputIsU8)) return; #endif - convInt8BlockDepthwise(inp_, residual_, out_, cs, weights_, - dw_bias, multiplier, inp_zp, out_zp, activLUT, inputIsU8); + convInt8BlockDepthwise(inp_, residual_, out_, cs, weights_, + dw_bias, multiplier, inp_zp, out_zp, + activLUT, inputIsU8); return; } -#if CV_AVX_VNNI +#if CV_AVX_VNNI || CV_AVX_512VNNI bool useVNNI = weightsVNNI_ && biasVNNI_; if (useVNNI && cs.hasPadding()) { const MatShape& os = cs.outshape; useVNNI = os.total() / ((size_t)os[0] * os[1] * os.back()) >= 8; } if (useVNNI) { - convInt8BlockVNNI(inp_, residual_, out_, cs, weightsVNNI_, - biasVNNI_, multiplier, inp_zp, out_zp, activLUT, inputIsU8); + convInt8BlockVNNI(inp_, residual_, out_, cs, weightsVNNI_, + biasVNNI_, multiplier, inp_zp, out_zp, + activLUT, inputIsU8); return; } #endif #if CV_NEON && defined(CV_NEON_DOT) && CV_NEON_DOT if (weightsVNNI_) { - convInt8BlockNEON(inp_, residual_, out_, cs, weightsVNNI_, - bias, multiplier, inp_zp, out_zp, activLUT, inputIsU8); + convInt8BlockNEON(inp_, residual_, out_, cs, weightsVNNI_, + bias, multiplier, inp_zp, out_zp, activLUT, inputIsU8); return; } #endif @@ -2381,13 +2514,15 @@ void convInt8Block(const void* inp_, const void* residual_, // vl=8 over the K0 output channels; pick the narrowest register group // that provides 8 lanes at the runtime VLEN (no VLEN hardcoded). if (__riscv_vsetvlmax_e32m1() >= 8) { - convInt8BlockRVV(inp_, residual_, out_, cs, weights_, - bias, multiplier, inp_zp, out_zp, activLUT, inputIsU8); + convInt8BlockRVV(inp_, residual_, out_, cs, weights_, + bias, multiplier, inp_zp, out_zp, + activLUT, inputIsU8); return; } if (__riscv_vsetvlmax_e32m2() >= 8) { - convInt8BlockRVV(inp_, residual_, out_, cs, weights_, - bias, multiplier, inp_zp, out_zp, activLUT, inputIsU8); + convInt8BlockRVV(inp_, residual_, out_, cs, weights_, + bias, multiplier, inp_zp, out_zp, + activLUT, inputIsU8); return; } } @@ -2433,13 +2568,14 @@ void convInt8Block(const void* inp_, const void* residual_, const int8_t* inp = (const int8_t*)inp_; const int8_t* residual = (const int8_t*)residual_; - int8_t* out = (int8_t*)out_; + typedef ConvInt8Out out_t; + out_t* out = (out_t*)out_; const int8_t* wdata = (const int8_t*)weights_; const int* ofsZYX = cs.coordtab.data(); size_t outtotal = outshape.total(); if ((Kg % K0) != 0) { - memset(out, 0, outtotal); + memset(out, 0, outtotal * sizeof(out_t)); } int total_blocks = N * ngroups * Kblk; @@ -2489,7 +2625,7 @@ void convInt8Block(const void* inp_, const void* residual_, const int8_t* wbaseptr = wdata + (size_t)(g * Kblk + kblk) * ksize * C1Max * C0 * K0; int k1 = k_base >> C0shift; - int8_t* outptr = out + (size_t)(n * K1 + k1) * planesize; + out_t* outptr = out + (size_t)(n * K1 + k1) * planesize; const int8_t* resptr = residual ? residual + (size_t)(n * K1 + k1) * planesize : nullptr; int D_l = D, H_l = H, W_l = W; @@ -2617,6 +2753,15 @@ void convInt8Block(const void* inp_, const void* residual_, } } + if constexpr (INT32_OUT) { + __m256i* optr = (__m256i*)(outptr + p * K0); + _mm256_storeu_si256(optr + 0, s0); _mm256_storeu_si256(optr + 1, s1); + _mm256_storeu_si256(optr + 2, s2); _mm256_storeu_si256(optr + 3, s3); + _mm256_storeu_si256(optr + 4, s4); _mm256_storeu_si256(optr + 5, s5); + _mm256_storeu_si256(optr + 6, s6); _mm256_storeu_si256(optr + 7, s7); + continue; + } + // Store accumulators _mm256_store_si256((__m256i*)(sumbuf + 0*K0), s0); _mm256_store_si256((__m256i*)(sumbuf + 1*K0), s1); @@ -2651,7 +2796,7 @@ void convInt8Block(const void* inp_, const void* residual_, __m128i packed8 = inputIsU8 ? _mm_packus_epi16(packed16, packed16) : _mm_packs_epi16(packed16, packed16); - int8_t* optr = outptr + (p + j) * K0; + out_t* optr = outptr + (p + j) * K0; if (activLUT) { alignas(16) int8_t tmp8[16]; _mm_store_si128((__m128i*)tmp8, packed8); @@ -2705,8 +2850,12 @@ void convInt8Block(const void* inp_, const void* residual_, } } - int8_t* optr = outptr + p * K0; + out_t* optr = outptr + p * K0; const int8_t* rptr = resptr ? resptr + p * K0 : nullptr; + if constexpr (INT32_OUT) { + memcpy(optr, acc, sizeof(acc)); + continue; + } for (int k0 = 0; k0 < K0; k0++) { float val = (float)acc[k0] * multbuf[k0] + (float)out_zp; if (rptr) { @@ -2729,6 +2878,24 @@ void convInt8Block(const void* inp_, const void* residual_, }); } +void convInt8Block(const void* inp_, const void* residual_, + void* out_, const ConvState& cs, + const void* weights_, + const void* weightsVNNI_, + const int* bias, const int* biasVNNI_, + const float* multiplier, + int inp_zp, int out_zp, + const int8_t* activLUT, + bool inputIsU8, bool int32Out) +{ + if (int32Out) + convInt8BlockImpl(inp_, residual_, out_, cs, weights_, weightsVNNI_, bias, + biasVNNI_, multiplier, inp_zp, out_zp, activLUT, inputIsU8); + else + convInt8BlockImpl(inp_, residual_, out_, cs, weights_, weightsVNNI_, bias, + biasVNNI_, multiplier, inp_zp, out_zp, activLUT, inputIsU8); +} + #endif // !CV_CPU_OPTIMIZATION_DECLARATIONS_ONLY CV_CPU_OPTIMIZATION_NAMESPACE_END diff --git a/modules/dnn/src/int8layers/conv2_int8_layer.cpp b/modules/dnn/src/int8layers/conv2_int8_layer.cpp index 6d7a07704b..4d0003b998 100644 --- a/modules/dnn/src/int8layers/conv2_int8_layer.cpp +++ b/modules/dnn/src/int8layers/conv2_int8_layer.cpp @@ -184,6 +184,94 @@ static void repackWeightsForVNNI(const Mat& wpack, int ngroups, int Kg, int Cg, }); } +// w - w_zero_point as int32 [K, Cg*ksize]; false when a value does not fit int8 +template +static bool shiftConvWeights(const Mat& w, const Mat& wzp, Mat& dst) +{ + int K = w.size[0]; + int len = (int)(w.total() / K); + dst.create(K, len, CV_32S); + parallel_for_(Range(0, K), [&](const Range& range) { + for (int k = range.start; k < range.end; k++) { + int zp = wzp.empty() ? 0 : (int)wzp.ptr()[wzp.total() == 1 ? 0 : k]; + const T* s = w.ptr() + (size_t)k * len; + int* d = dst.ptr(k); + for (int i = 0; i < len; i++) + d[i] = (int)s[i] - zp; + } + }); + double minVal = 0, maxVal = 0; + minMaxIdx(dst, &minVal, &maxVal); + return minVal >= -128 && maxVal <= 127; +} + +// ConvInteger on block layout for the weights or groups the int8 kernels cannot take +template +static void convIntegerScalar(const Mat& inp, const Mat& wshift, int x_zp, + const ConvState& cs, Mat& out) +{ + const MatShape& ishape = cs.inpshape; + const MatShape& oshape = cs.outshape; + int ndims = oshape.dims; + int N = oshape[0], K = oshape.channels(), C = ishape.channels(); + int C0 = ishape.back(), K0 = oshape.back(); + int K1 = (K + K0 - 1) / K0, C1 = (C + C0 - 1) / C0; + int D = ndims >= 6 ? oshape[ndims-4] : 1, H = ndims >= 5 ? oshape[ndims-3] : 1; + int W = oshape[ndims-2]; + int Di = ndims >= 6 ? ishape[ndims-4] : 1, Hi = ndims >= 5 ? ishape[ndims-3] : 1; + int Wi = ishape[ndims-2]; + int Kg = K / cs.ngroups, Cg = C / cs.ngroups; + int kD = cs.kshape[0], kH = cs.kshape[1], kW = cs.kshape[2]; + int sD = cs.strides[0], sH = cs.strides[1], sW = cs.strides[2]; + int dD = cs.dilations[0], dH = cs.dilations[1], dW = cs.dilations[2]; + int padZ = cs.pads[0], padY = cs.pads[1], padX = cs.pads[2]; + size_t iplane = (size_t)Di * Hi * Wi * C0, oplane = (size_t)D * H * W * K0; + const T* src = inp.ptr(); + int32_t* dst = out.ptr(); + if (K % K0 != 0) + out.setTo(Scalar::all(0)); + + parallel_for_(Range(0, N * K * D * H), [&](const Range& range) { + AutoBuffer accbuf(W); + int* acc = accbuf.data(); + for (int row = range.start; row < range.end; row++) { + int oy = row % H, t = row / H; + int oz = t % D; + t /= D; + int k = t % K, n = t / K, g = k / Kg; + std::fill(acc, acc + W, 0); + const int* wk = wshift.ptr(k); + for (int c = 0; c < Cg; c++) { + int ci = g * Cg + c; + const T* sc = src + (n * C1 + ci / C0) * iplane + ci % C0; + for (int kz = 0; kz < kD; kz++) { + int iz = oz * sD - padZ + kz * dD; + if ((unsigned)iz >= (unsigned)Di) + continue; + for (int ky = 0; ky < kH; ky++) { + int iy = oy * sH - padY + ky * dH; + if ((unsigned)iy >= (unsigned)Hi) + continue; + const T* srow = sc + ((size_t)iz * Hi + iy) * Wi * C0; + for (int kx = 0; kx < kW; kx++) { + int wv = wk[((c * kD + kz) * kH + ky) * kW + kx]; + int x0 = kx * dW - padX; + int ox0 = x0 < 0 ? (sW - 1 - x0) / sW : 0; + int ox1 = Wi - 1 - x0 < 0 ? 0 : std::min(W, (Wi - 1 - x0) / sW + 1); + for (int ox = ox0; ox < ox1; ox++) + acc[ox] += ((int)srow[(ox * sW + x0) * C0] - x_zp) * wv; + } + } + } + } + int32_t* drow = dst + (n * K1 + k / K0) * oplane + + ((size_t)oz * H + oy) * W * K0 + k % K0; + for (int ox = 0; ox < W; ox++) + drow[ox * K0] = acc[ox]; + } + }); +} + class Conv2Int8LayerImpl CV_FINAL : public Conv2Int8Layer { public: @@ -212,6 +300,11 @@ public: bool addResidual; bool inputIsU8; + Mat wsum; // int32 mode: per-channel sum of the folded int8 weights + Mat wshift; // int32 mode: w - w_zp as int32 when the int8 kernels cannot take it + Mat biasDynVNNI, biasDynBase, unitMultiplier; + MatShape prevWshape; + Conv2Int8LayerImpl(const LayerParams& params) { setParamsFrom(params); @@ -228,6 +321,7 @@ public: output_zp = params.get("zeropoints", 0); per_channel = params.get("per_channel", true); inputIsU8 = params.get("input_is_u8", false); + int32_output = params.get("int32_output", false); addResidual = false; @@ -272,7 +366,14 @@ public: std::vector& internals) const CV_OVERRIDE { int outtype; - if (float_input) + if (int32_output) { + CV_CheckGE(inputs.size(), (size_t)2, "DNN/ConvInteger: x and w are required"); + CV_CheckType(inputs[0], inputs[0] == CV_8U || inputs[0] == CV_8S, + "DNN/ConvInteger: x must be uint8 or int8"); + CV_CheckType(inputs[1], inputs[1] == CV_8U || inputs[1] == CV_8S, + "DNN/ConvInteger: w must be uint8 or int8"); + outtype = CV_32S; + } else if (float_input) outtype = inputIsU8 ? CV_8UC1 : CV_8SC1; else outtype = !inputs.empty() ? inputs[0] : CV_8SC1; @@ -296,7 +397,9 @@ public: int C0 = getNetImpl(this)->defaultC0; inpshape = inpshape.toLayout(DATA_LAYOUT_BLOCK, C0); } - outshapes.assign(1, convInferShape(inpshape, wshape0, emptyKernelShape, + CV_Assert(!int32_output || ninputs >= 2); + const MatShape& wshape = int32_output ? inpshapes[1] : wshape0; + outshapes.assign(1, convInferShape(inpshape, wshape, emptyKernelShape, ngroups, strides, dilations, pads, auto_pad, ceil_mode)); tempshapes.clear(); @@ -336,6 +439,8 @@ public: bool setActivation(const Ptr& layer) CV_OVERRIDE { + if (int32_output) + return false; Ptr activ_int8 = layer.dynamicCast(); if (!activ_int8.empty()) { activ = activ_int8; @@ -521,10 +626,139 @@ public: }); } + void setWeightsInteger(const Mat& w, const Mat& wzp, int C0) + { + CV_CheckType(w.type(), w.type() == CV_8UC1 || w.type() == CV_8SC1, + "DNN/ConvInteger: w must be uint8 or int8"); + CV_Assert(w.isContinuous() && w.dims >= 3); + int K = w.size[0]; + if (!wzp.empty()) { + CV_CheckTypeEQ(wzp.type(), w.type(), + "DNN/ConvInteger: w_zero_point must have the type of w"); + CV_Check(wzp.total(), wzp.total() == 1 || wzp.total() == (size_t)K, + "DNN/ConvInteger: w_zero_point must be scalar or per output channel"); + } + wshape0 = w.shape(); + Mat shifted; + bool fits = w.type() == CV_8UC1 ? shiftConvWeights(w, wzp, shifted) + : shiftConvWeights(w, wzp, shifted); + int Kg = K / ngroups, Cg = wshape0[1]; + if (!fits || !(ngroups == 1 || Kg % C0 == 0 || (Kg == 1 && Cg == 1))) { + wshift = shifted; + weights.release(); + weightsVNNI.release(); + return; + } + wshift.release(); + Mat w8; + shifted.reshape(1, wshape0).convertTo(w8, CV_8S); + repackConvWeightsInt8(w8, weights, ngroups, C0); + repackWeightsForVNNI(weights, ngroups, Kg, Cg, Mat::zeros(1, K, CV_32S), + weightsVNNI, biasVNNI); + + // the kernels load 8 channels at a time + int Kpad = alignSize(K, C0); + wsum = Mat::zeros(1, Kpad, CV_32S); + biasDynVNNI = Mat::zeros(1, Kpad, CV_32S); + biasDynBase = Mat::zeros(1, Kpad, CV_32S); + unitMultiplier = Mat::ones(1, Kpad, CV_32F); + for (int k = 0; k < K; k++) + wsum.at(k) = -biasVNNI.at(k) / 128; + } + + // ONNX ConvInteger: https://onnx.ai/onnx/operators/onnx__ConvInteger.html, opset 10 (its only + // version); x_zero_point is a scalar, w_zero_point a scalar or one value per output channel + void forwardInt32(InputArrayOfArrays input_arrs, OutputArrayOfArrays output_arrs) + { + auto* netimpl_ = getNetImpl(this); + int ninputs = (int)input_arrs.total(); + CV_Assert(ninputs >= 2 && !float_input && !addResidual); + + const Mat& inp = input_arrs.getMat(0); + MatShape inpshape = inp.shape(); + CV_Assert(inpshape.layout == DATA_LAYOUT_BLOCK); + CV_CheckType(inp.type(), inp.type() == CV_8UC1 || inp.type() == CV_8SC1, + "DNN/ConvInteger: x must be uint8 or int8"); + const bool isU8 = inp.type() == CV_8UC1; + int C0 = inpshape.back(); + + int zp = 0; + Mat zpm = ninputs > 2 ? input_arrs.getMat(2) : Mat(); + if (!zpm.empty()) { + CV_CheckEQ(zpm.total(), (size_t)1, "DNN/ConvInteger: x_zero_point must be a scalar"); + CV_CheckTypeEQ(zpm.type(), inp.type(), + "DNN/ConvInteger: x_zero_point must have the type of x"); + zp = isU8 ? (int)zpm.ptr()[0] : (int)zpm.ptr()[0]; + } + + bool dynamicWeights = !netimpl_->isConstArg(inputs[1]) || + (ninputs > 3 && !netimpl_->isConstArg(inputs[3])); + if (dynamicWeights || (weights.empty() && wshift.empty())) + setWeightsInteger(input_arrs.getMat(1), ninputs > 3 ? input_arrs.getMat(3) : Mat(), C0); + + std::vector emptyKernelShape; + MatShape outshape = convInferShape(inpshape, wshape0, emptyKernelShape, + ngroups, strides, dilations, + pads, auto_pad, ceil_mode); + int outkind = output_arrs.kind(); + Mat out; + if (outkind == _InputArray::STD_VECTOR_MAT) { + std::vector& outs = output_arrs.getMatVecRef(); + outs.resize(1); + outs[0].fit(outshape, CV_32S); + out = outs[0]; + } else { + std::vector& outs = output_arrs.getUMatVecRef(); + outs.resize(1); + outs[0].fit(outshape, CV_32S); + out.fit(outshape, CV_32S); + } + + if (inpshape != prevInpshape || wshape0 != prevWshape) { + cs.initConv(inpshape, wshape0, outshape, ngroups, + strides, dilations, pads, auto_pad, ceil_mode, + FAST_ACTIV_NONE, nullptr, {}); + if (cs.depthwise) + cs.wshape = getWpackShapeInt8(wshape0, ngroups, C0); + prevInpshape = inpshape; + prevWshape = wshape0; + } + + if (!weights.empty()) { + // the VNNI and depthwise kernels read s8 as x+128, the others read u8 as x-128 + const int zpVNNI = isU8 ? zp : zp + 128, zpBase = isU8 ? zp - 128 : zp; + const int* ws = wsum.ptr(); + int* bV = biasDynVNNI.ptr(); + int* bB = biasDynBase.ptr(); + for (int k = 0; k < wshape0[0]; k++) { + bV[k] = -zpVNNI * ws[k]; + bB[k] = -zpBase * ws[k]; + } + convInt8Block(inp.data, nullptr, out.data, cs, weights.data, weightsVNNI.data, + bB, bV, unitMultiplier.ptr(), zp, 0, nullptr, isU8, true); + } else if (isU8) { + convIntegerScalar(inp, wshift, zp, cs, out); + } else { + convIntegerScalar(inp, wshift, zp, cs, out); + } + + if (dynamicWeights) { + weights.release(); + weightsVNNI.release(); + wshift.release(); + } + if (outkind == _InputArray::STD_VECTOR_UMAT) + out.copyTo(output_arrs.getUMatVecRef()[0]); + } + void forward(InputArrayOfArrays input_arrs, OutputArrayOfArrays output_arrs, OutputArrayOfArrays) CV_OVERRIDE { + if (int32_output) { + forwardInt32(input_arrs, output_arrs); + return; + } int ninputs = (int)input_arrs.total(); CV_Assert(ninputs >= 1); @@ -642,7 +876,7 @@ public: effectiveBiasVNNI, outMultiplier.ptr(), input_zp, output_zp, - lutptr, inputIsU8); + lutptr, inputIsU8, false); if (outkind == _InputArray::STD_VECTOR_UMAT) { std::vector& outs = output_arrs.getUMatVecRef(); diff --git a/modules/dnn/src/int8layers/convolution_layer.cpp b/modules/dnn/src/int8layers/convolution_layer.cpp index f91fee272f..e6b57f6de3 100644 --- a/modules/dnn/src/int8layers/convolution_layer.cpp +++ b/modules/dnn/src/int8layers/convolution_layer.cpp @@ -805,7 +805,8 @@ public: p.useAVX2 = checkHardwareSupport(CPU_AVX2) && isConv2D; p.useAVX512 = CV_CPU_HAS_SUPPORT_AVX512_SKX && isConv2D; - p.useVNNI = p.useAVX2 && CV_CPU_HAS_SUPPORT_AVX_VNNI && input.type() == CV_8UC1; + p.useVNNI = p.useAVX2 && input.type() == CV_8UC1 && + (CV_CPU_HAS_SUPPORT_AVX_VNNI || CV_CPU_HAS_SUPPORT_AVX512_CLX); p.useLASX = checkHardwareSupport(CPU_LASX) && isConv2D; p.useRVV = checkHardwareSupport(CPU_RVV) && isConv2D; @@ -1586,8 +1587,9 @@ public: Mat outputInt32 = outputInt32Buf_; if (inputs[0].type() == CV_8U) { - // AVX-VNNI path: pass uint8 input directly, skip u8→s8 conversion. - if (CV_CPU_HAS_SUPPORT_AVX_VNNI && inputs[0].dims == 4) { + // AVX-VNNI / AVX-512 VNNI path: pass uint8 input directly, skip u8→s8 conversion. + if ((CV_CPU_HAS_SUPPORT_AVX_VNNI || CV_CPU_HAS_SUPPORT_AVX512_CLX) && + inputs[0].dims == 4) { if (biasvecVNNI.empty() && !biasvec.empty()) { int outCn = weightsMat.rows; biasvecVNNI.resize(biasvec.size()); diff --git a/modules/dnn/src/int8layers/matmul_int8_kernels.dispatch.cpp b/modules/dnn/src/int8layers/matmul_int8_kernels.dispatch.cpp new file mode 100644 index 0000000000..e9675b5bf6 --- /dev/null +++ b/modules/dnn/src/int8layers/matmul_int8_kernels.dispatch.cpp @@ -0,0 +1,28 @@ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// Copyright (C) 2026, BigVision LLC, all rights reserved. +// Third party copyrights are property of their respective owners. + +#include "../precomp.hpp" +#include "matmul_int8_kernels.hpp" + +#include "matmul_int8_kernels.simd.hpp" +#include "int8layers/matmul_int8_kernels.simd_declarations.hpp" + +namespace cv +{ +namespace dnn +{ + +void matMulInt8Int32(const uchar* A, size_t lda, const int8_t* packedB, const int* colsum, + const int* corr, const int* rowterm, int* Y, size_t ldy, + int M, int N, int K, int a_zp, bool aIsU8) +{ + CV_CPU_DISPATCH(matMulInt8Int32, (A, lda, packedB, colsum, corr, rowterm, Y, ldy, + M, N, K, a_zp, aIsU8), + CV_CPU_DISPATCH_MODES_ALL); +} + +} +} diff --git a/modules/dnn/src/int8layers/matmul_int8_kernels.hpp b/modules/dnn/src/int8layers/matmul_int8_kernels.hpp new file mode 100644 index 0000000000..68c2d2937a --- /dev/null +++ b/modules/dnn/src/int8layers/matmul_int8_kernels.hpp @@ -0,0 +1,26 @@ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// Copyright (C) 2026, BigVision LLC, all rights reserved. +// Third party copyrights are property of their respective owners. + +#ifndef __OPENCV_DNN_INT8LAYERS_MATMUL_INT8_KERNELS_HPP__ +#define __OPENCV_DNN_INT8LAYERS_MATMUL_INT8_KERNELS_HPP__ + +namespace cv +{ +namespace dnn +{ + +enum { MATMUL_INT8_NR = 16, MATMUL_INT8_KR = 4 }; + +// Y[r,n] = sum_k (A[r,k] - a_zp) * B[k,n] + corr[n] * rowterm[r] in int32, corr may be null; +// packedB is int8 B as [N/NR][K/KR][NR][KR] rounded up and zero-padded; colsum and corr pad N alike +void matMulInt8Int32(const uchar* A, size_t lda, const int8_t* packedB, const int* colsum, + const int* corr, const int* rowterm, int* Y, size_t ldy, + int M, int N, int K, int a_zp, bool aIsU8); + +} +} + +#endif diff --git a/modules/dnn/src/int8layers/matmul_int8_kernels.simd.hpp b/modules/dnn/src/int8layers/matmul_int8_kernels.simd.hpp new file mode 100644 index 0000000000..0f24790326 --- /dev/null +++ b/modules/dnn/src/int8layers/matmul_int8_kernels.simd.hpp @@ -0,0 +1,174 @@ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// Copyright (C) 2026, BigVision LLC, all rights reserved. +// Third party copyrights are property of their respective owners. + +#include "opencv2/core/hal/intrin.hpp" + +namespace cv { +namespace dnn { +CV_CPU_OPTIMIZATION_NAMESPACE_BEGIN + +void matMulInt8Int32(const uchar* A, size_t lda, const int8_t* packedB, const int* colsum, + const int* corr, const int* rowterm, int* Y, size_t ldy, + int M, int N, int K, int a_zp, bool aIsU8); + +#if !defined(CV_CPU_OPTIMIZATION_DECLARATIONS_ONLY) + +static constexpr int MMI8_MR = 4, MMI8_NR = 16, MMI8_KR = 4; +static constexpr int MMI8_PSTEP = MMI8_NR * MMI8_KR; // packed bytes per group of KR rows + +// dpbusd matches the vector width: zmm with AVX-512 VNNI, ymm with AVX-VNNI in a 256-bit build +#if (CV_SIMD512 && CV_AVX_512VNNI) || (CV_SIMD256 && !CV_SIMD512 && CV_AVX_VNNI) +#define MMI8_USE_VNNI 1 +#else +#define MMI8_USE_VNNI 0 +#endif + +#if CV_SIMD +// nlanes, not vlanes(): the register arrays below need a compile-time count +static constexpr int MMI8_NV = MMI8_PSTEP / VTraits::nlanes; + +// lane i accumulates the products of bytes 4i..4i+3; with VNNI a is read as uint8 +static inline v_int32 dot4(const v_int8& a, const v_int8& b, const v_int32& c) +{ +#if MMI8_USE_VNNI && CV_SIMD512 + return v_int32(_mm512_dpbusd_epi32(c.val, a.val, b.val)); +#elif MMI8_USE_VNNI + return v_int32(_mm256_dpbusd_epi32(c.val, a.val, b.val)); +#else + return v_dotprod_expand(a, b, c); +#endif +} + +static CV_ALWAYS_INLINE void macStep(v_int32 (&acc)[MMI8_MR][MMI8_NV], const int8_t* bp, + const int (&a4)[MMI8_MR]) +{ + v_int8 b[MMI8_NV]; + for (int j = 0; j < MMI8_NV; j++) + b[j] = vx_load(bp + j * VTraits::vlanes()); + for (int i = 0; i < MMI8_MR; i++) { + v_int8 a = v_reinterpret_as_s8(vx_setall_s32(a4[i])); + for (int j = 0; j < MMI8_NV; j++) + acc[i][j] = dot4(a, b[j], acc[i][j]); + } +} +#endif + +// rows [r, r+mr) x one panel; rows past mr repeat the last row and are not stored +template +static void gemmTile(const uchar* A, size_t lda, int mr, const int8_t* bp, int K, int xor4, + int zp, const int* colsum, const int* corr, const int* rt, + int* Y, size_t ldy, int nvalid) +{ + const uchar* a[MMI8_MR]; + for (int i = 0; i < MMI8_MR; i++) + a[i] = A + std::min(i, mr - 1) * lda; +#if CV_SIMD + const int VLI = VTraits::vlanes(); + v_int32 acc[MMI8_MR][MMI8_NV]; + for (int i = 0; i < MMI8_MR; i++) + for (int j = 0; j < MMI8_NV; j++) + acc[i][j] = vx_setzero_s32(); + + int k = 0; + for (; k + MMI8_KR <= K; k += MMI8_KR, bp += MMI8_PSTEP) { + int a4[MMI8_MR]; + for (int i = 0; i < MMI8_MR; i++) { + memcpy(&a4[i], a[i] + k, MMI8_KR); + a4[i] ^= xor4; + } + macStep(acc, bp, a4); + } + if (k < K) { + // the padded weights are zero, so the padded bytes of A may hold anything + int a4[MMI8_MR] = {}; + for (int i = 0; i < MMI8_MR; i++) { + memcpy(&a4[i], a[i] + k, K - k); + a4[i] ^= xor4; + } + macStep(acc, bp, a4); + } + + v_int32 vzp = vx_setall_s32(-zp), bias[MMI8_NV]; + for (int j = 0; j < MMI8_NV; j++) + bias[j] = v_mul(vzp, vx_load(colsum + j * VLI)); + for (int i = 0; i < mr; i++) { + int buf[MMI8_NR]; + int* y = nvalid == MMI8_NR ? Y + i * ldy : buf; + for (int j = 0; j < MMI8_NV; j++) { + v_int32 s = v_add(acc[i][j], bias[j]); + if constexpr (CORR) + s = v_muladd(vx_load(corr + j * VLI), vx_setall_s32(rt[i]), s); + v_store(y + j * VLI, s); + } + if (y == buf) + for (int j = 0; j < nvalid; j++) + Y[i * ldy + j] = buf[j]; + } +#else + for (int i = 0; i < mr; i++) { + for (int j = 0; j < nvalid; j++) { + int s = 0; + for (int k = 0; k < K; k++) + s += (int)(schar)(a[i][k] ^ (xor4 & 255)) * + bp[(k / MMI8_KR) * MMI8_PSTEP + j * MMI8_KR + k % MMI8_KR]; + s -= zp * colsum[j]; + if constexpr (CORR) + s += corr[j] * rt[i]; + Y[i * ldy + j] = s; + } + } +#endif +} + +template +static void gemmInt8Int32(const uchar* A, size_t lda, const int8_t* packedB, const int* colsum, + const int* corr, const int* rowterm, int* Y, size_t ldy, + int M, int N, int K, int xor4, int zp) +{ + constexpr int TASK_ROWS = 64, TASK_PANELS = 2; + const int npanels = (N + MMI8_NR - 1) / MMI8_NR; + const size_t panelSize = (size_t)((K + MMI8_KR - 1) / MMI8_KR) * MMI8_PSTEP; + const int ngroups = (npanels + TASK_PANELS - 1) / TASK_PANELS; + const int ntasks = (M + TASK_ROWS - 1) / TASK_ROWS * ngroups; + + parallel_for_(Range(0, ntasks), [&](const Range& range) { + for (int t = range.start; t < range.end; t++) { + int r0 = t / ngroups * TASK_ROWS, r1 = std::min(M, r0 + TASK_ROWS); + int p0 = t % ngroups * TASK_PANELS, p1 = std::min(npanels, p0 + TASK_PANELS); + for (int p = p0; p < p1; p++) { + int n0 = p * MMI8_NR, nvalid = std::min(MMI8_NR, N - n0); + const int8_t* bp = packedB + p * panelSize; + for (int r = r0; r < r1; r += MMI8_MR) + gemmTile(A + r * lda, lda, std::min(MMI8_MR, r1 - r), bp, K, xor4, zp, + colsum + n0, CORR ? corr + n0 : nullptr, + CORR ? rowterm + r : nullptr, Y + r * ldy + n0, ldy, nvalid); + } + } + }); +} + +void matMulInt8Int32(const uchar* A, size_t lda, const int8_t* packedB, const int* colsum, + const int* corr, const int* rowterm, int* Y, size_t ldy, + int M, int N, int K, int a_zp, bool aIsU8) +{ + // xor 0x80 turns uint8 A into the int8 operand (or back) and moves its zero point by 128 +#if MMI8_USE_VNNI + const bool operandU8 = true; +#else + const bool operandU8 = false; +#endif + const int xor4 = aIsU8 == operandU8 ? 0 : (int)0x80808080u; + const int zp = aIsU8 == operandU8 ? a_zp : aIsU8 ? a_zp - 128 : a_zp + 128; + if (corr) + gemmInt8Int32(A, lda, packedB, colsum, corr, rowterm, Y, ldy, M, N, K, xor4, zp); + else + gemmInt8Int32(A, lda, packedB, colsum, corr, rowterm, Y, ldy, M, N, K, xor4, zp); +} + +#endif // !CV_CPU_OPTIMIZATION_DECLARATIONS_ONLY + +CV_CPU_OPTIMIZATION_NAMESPACE_END +}} // namespace cv::dnn diff --git a/modules/dnn/src/int8layers/matmul_int8_layer.cpp b/modules/dnn/src/int8layers/matmul_int8_layer.cpp index 8013abd5f0..185e29ab30 100644 --- a/modules/dnn/src/int8layers/matmul_int8_layer.cpp +++ b/modules/dnn/src/int8layers/matmul_int8_layer.cpp @@ -4,6 +4,9 @@ #include "../precomp.hpp" #include "layers_common.hpp" +#include "../net_impl.hpp" +#include "../layers/cpu_kernels/fast_gemm.hpp" +#include "matmul_int8_kernels.hpp" #include @@ -17,10 +20,28 @@ class MatMulInt8LayerImpl CV_FINAL : public MatMulInt8Layer public: enum { VEC_ALIGN = 32 }; + MatMulInt8LayerImpl(const LayerParams& params) + { + setParamsFrom(params); + int32_output = params.get("int32_output", false); + CV_CheckTrue(int32_output, + "DNN/MatMulInt8: only the ONNX MatMulInteger form is created by type name"); + trans_a = trans_b = false; + alpha = beta = 1.f; + input_zp = output_zp = 0; + input_sc = output_sc = 1.f; + output_type = CV_32S; + per_channel = false; + inp_dims = 2; + num_output = 0; + } + MatMulInt8LayerImpl(const MatMulInt8Params& p) { name = p.name; type = "MatMulInt8"; + trans_a = trans_b = false; + alpha = beta = 1.f; input_sc = p.input_sc; input_zp = p.input_zp; output_sc = p.output_sc; @@ -57,8 +78,20 @@ public: bool getMemoryShapes(const std::vector &inputs, const int requiredOutputs, std::vector &outputs, - std::vector &) const CV_OVERRIDE + std::vector &internals) const CV_OVERRIDE { + if (int32_output) { + CV_CheckGE(inputs.size(), (size_t)2, "DNN/MatMulInteger: A and B are required"); + MatShape ap, bp, full, out; + matmulShapes(inputs[0], inputs[1], false, false, ap, bp, full, out); + outputs.assign(1, out); + int rows = 1; + for (size_t i = 0; i + 1 < ap.size(); i++) + rows *= ap[i]; + // per-row correction term, used when B is uint8 or has a nonzero zero point + internals.assign(1, MatShape({std::max(rows, 1)})); + return false; + } CV_CheckEQ(inputs.size(), (size_t)1, ""); CV_CheckEQ(blobs[0].dims, 2, ""); int numOut = blobs[0].size[0]; @@ -81,6 +114,15 @@ public: std::vector& outputs, std::vector& internals) const CV_OVERRIDE { + if (int32_output) { + CV_CheckType(inputs[0], inputs[0] == CV_8U || inputs[0] == CV_8S, + "DNN/MatMulInteger: A must be uint8 or int8"); + CV_CheckType(inputs[1], inputs[1] == CV_8U || inputs[1] == CV_8S, + "DNN/MatMulInteger: B must be uint8 or int8"); + outputs.assign(requiredOutputs, CV_32S); + internals.assign(requiredInternals, CV_32S); + return; + } outputs.assign(requiredOutputs, output_type); internals.clear(); } @@ -96,6 +138,11 @@ public: CV_TRACE_FUNCTION(); CV_TRACE_ARG_VALUE(name, "name", name.c_str()); + if (int32_output) { + forwardInt32(inputs_arr, outputs_arr, internals_arr); + return; + } + std::vector input, output; inputs_arr.getMatVector(input); outputs_arr.getMatVector(output); @@ -130,7 +177,8 @@ public: virtual int64 getFLOPS(const std::vector &inputs, const std::vector &outputs) const CV_OVERRIDE { - CV_UNUSED(inputs); + if (int32_output) + return (int64)total(outputs[0]) * inputs[0][inputs[0].dims - 1]; long flops = 0; int innerSize = blobs[0].size[1]; for (size_t i = 0; i < outputs.size(); i++) { @@ -140,6 +188,193 @@ public: } private: + // B - 128 (uint8 B) or B (int8 B), each [K, N] matrix of B in the matMulInt8Int32 panel + // layout one after another, with their column sums + void packWeightsInteger(const Mat& B) + { + CV_CheckType(B.type(), B.type() == CV_8UC1 || B.type() == CV_8SC1, + "DNN/MatMulInteger: B must be uint8 or int8"); + CV_CheckGE(B.dims, 2, "DNN/MatMulInteger: B must have at least two dimensions"); + CV_Assert(B.isContinuous()); + constexpr int NR = MATMUL_INT8_NR, KR = MATMUL_INT8_KR; + const int K = B.size[B.dims - 2], N = B.size[B.dims - 1]; + const int nb = (int)(B.total() / ((size_t)K * N)); + const int Npad = alignSize(N, NR); + const size_t panelSize = (size_t)alignSize(K, KR) * NR, matSize = Npad / NR * panelSize; + const int delta = B.type() == CV_8UC1 ? 128 : 0; + packedB.create(1, (int)(nb * matSize), CV_8S); + packedB.setTo(Scalar::all(0)); + colsum = Mat::zeros(1, nb * Npad, CV_32S); + corr = Mat::zeros(1, nb * Npad, CV_32S); + const uchar* b = B.ptr(); + int8_t* dst = packedB.ptr(); + int* cs = colsum.ptr(); + parallel_for_(Range(0, nb * N), [&](const Range& range) { + for (int j = range.start; j < range.end; j++) { + const int m = j / N, n = j % N; + const uchar* bm = b + (size_t)m * K * N; + int8_t* d = dst + m * matSize + n / NR * panelSize + n % NR * KR; + int s = 0; + for (int k = 0; k < K; k++) { + const uchar v = bm[(size_t)k * N + n]; + int w = (delta ? (int)v : (int)(schar)v) - delta; + d[k / KR * NR * KR + k % KR] = (int8_t)w; + s += w; + } + cs[m * Npad + n] = s; + } + }, (double)nb * N * K / (1 << 16)); + } + + // ONNX MatMulInteger: https://onnx.ai/onnx/operators/onnx__MatMulInteger.html, opset 10 (its + // only version); a_zero_point may be per row of A, b_zero_point per column of B + void forwardInt32(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, + OutputArrayOfArrays internals_arr) + { + std::vector input, output, internals; + inputs_arr.getMatVector(input); + outputs_arr.getMatVector(output); + internals_arr.getMatVector(internals); + const int ninputs = (int)input.size(); + const Mat& A = input[0]; + Mat& Y = output[0]; + CV_CheckType(A.type(), A.type() == CV_8UC1 || A.type() == CV_8SC1, + "DNN/MatMulInteger: A must be uint8 or int8"); + CV_Assert(A.isContinuous() && Y.isContinuous()); + MatShape ap, bp, full, out; + matmulShapes(A.shape(), input[1].shape(), false, false, ap, bp, full, out); + const Mat B = input[1].reshape(1, bp); // a 1-D B is one column, [K, 1] + const bool isU8 = A.type() == CV_8UC1; + + const Mat zbm = ninputs > 3 ? input[3] : Mat(); + const int K = B.size[B.dims - 2], N = B.size[B.dims - 1]; + const int R = (int)A.total(0, A.dims - 1); + int za = 0; + std::vector zrow; // per-row a_zero_point, empty when it is a scalar + if (ninputs > 2 && !input[2].empty()) { + const Mat& zam = input[2]; + CV_CheckTypeEQ(zam.type(), A.type(), + "DNN/MatMulInteger: a_zero_point must have the type of A"); + const uchar* zp = zam.ptr(); + if (zam.total() == 1) { + za = isU8 ? (int)zp[0] : (int)(schar)zp[0]; + } else { + // [M] for a 2-D A, otherwise A's shape with K -> 1, where batch dims may be 1 + const MatShape as = A.shape(); + MatShape zs = zam.shape(); + if (zs.size() == 1) + zs.push_back(1); + while (zs.size() < as.size()) + zs.insert(zs.begin(), 1); + bool ok = zs.size() == as.size() && zs.back() == 1; + for (size_t d = 0; ok && d + 1 < as.size(); d++) + ok = zs[d] == as[d] || zs[d] == 1; + CV_Check(zam.total(), ok, + "DNN/MatMulInteger: a_zero_point must be a scalar or one value per row"); + zrow.resize(R); + for (int r = 0; r < R; r++) { + size_t zi = 0, zstep = 1; + for (int d = (int)as.size() - 2, rem = r; d >= 0; d--) { + if (zs[d] != 1) + zi += (size_t)(rem % as[d]) * zstep; + rem /= as[d]; + zstep *= zs[d]; + } + zrow[r] = isU8 ? (int)zp[zi] : (int)(schar)zp[zi]; + } + } + } + const int* zr = zrow.empty() ? nullptr : zrow.data(); + if (Y.total() == 0) + return; + if (K == 0) { + Y.setTo(Scalar::all(0)); + return; + } + const int nb = (int)(B.total() / ((size_t)K * N)); + if (!zbm.empty()) { + CV_CheckTypeEQ(zbm.type(), B.type(), + "DNN/MatMulInteger: b_zero_point must have the type of B"); + CV_Check(zbm.total(), zbm.total() == 1 || zbm.total() == (size_t)N || + zbm.total() == (size_t)nb * N, + "DNN/MatMulInteger: b_zero_point must be a scalar or one value per column"); + } + + const bool dynamicWeights = !getNetImpl(this)->isConstArg(inputs[1]); + if (dynamicWeights || packedB.empty()) + packWeightsInteger(B); + + // (B - zb) = (B' - zb') with B' = B - delta, so zb' leaves -zb'[n] * sum_k (A - za) + const int delta = B.type() == CV_8UC1 ? 128 : 0; + const int Npad = alignSize(N, MATMUL_INT8_NR); + int* cr = corr.ptr(); + bool hasCorr = false; + const size_t z = zbm.total(); + for (int m = 0; m < nb; m++) { + for (int n = 0; n < N; n++) { + const size_t i = z == 1 ? 0 : z == (size_t)N ? n : (size_t)m * N + n; + int zb = z == 0 ? 0 : delta ? (int)zbm.ptr()[i] : (int)zbm.ptr()[i]; + cr[m * Npad + n] = delta - zb; + hasCorr = hasCorr || cr[m * Npad + n] != 0; + } + } + + const uchar* a = A.ptr(); + int* rowterm = internals[0].ptr(); + if (hasCorr) { + parallel_for_(Range(0, R), [&](const Range& range) { + for (int r = range.start; r < range.end; r++) { + const uchar* ar = a + (size_t)r * K; + int s = 0; + if (isU8) + for (int k = 0; k < K; k++) + s += ar[k]; + else + for (int k = 0; k < K; k++) + s += (schar)ar[k]; + rowterm[r] = s - K * (zr ? zr[r] : za); + } + }, (double)R * K / (1 << 16)); + } + + // a per-row zero point runs the kernel with a_zp = 0 and subtracts za[r] * colsum[n] here + auto subtractRowZeroPoints = [&](const int* zrows, const int* csm, int* ym, int rows) { + parallel_for_(Range(0, rows), [&](const Range& range) { + for (int r = range.start; r < range.end; r++) + for (int n = 0; n < N; n++) + ym[(size_t)r * N + n] -= zrows[r] * csm[n]; + }, (double)rows * N / (1 << 16)); + }; + + const int8_t* pb = packedB.ptr(); + const int* cs = colsum.ptr(); + int* y = Y.ptr(); + if (nb == 1) { + matMulInt8Int32(a, K, pb, cs, hasCorr ? cr : nullptr, rowterm, y, N, R, N, K, + zr ? 0 : za, isU8); + if (zr) + subtractRowZeroPoints(zr, cs, y, R); + } else { + // one GEMM per output matrix, at the offsets MatMul uses to broadcast batch dims + const size_t matSize = packedB.total() / nb; + MatMulHelper helper; + helper.compute(false, false, ap, bp, full); + for (size_t i = 0; i < helper.batch; i++) { + const size_t m = helper.B_rows[i]; + const size_t ofs = helper.A_offsets[i]; + matMulInt8Int32(a + ofs, K, pb + m * matSize, cs + m * Npad, + hasCorr ? cr + m * Npad : nullptr, rowterm + ofs / K, + y + helper.C_offsets[i], N, helper.M, N, K, zr ? 0 : za, isU8); + if (zr) + subtractRowZeroPoints(zr + ofs / K, cs + m * Npad, y + helper.C_offsets[i], + helper.M); + } + } + + if (dynamicWeights) + packedB.release(); + } + // Int8 GEMM: C_int32 = A_int8 @ W_int8^T + bias_int32 // Then: output = clamp(round(C_int32 * multiplier) + output_zp) static void runInt8Gemm(const Mat& srcMat, const Mat& weights, const Mat& biasMat, @@ -286,8 +521,14 @@ private: int inp_dims; int num_output; Mat weightsMat, biasMat, outputMultiplier; + Mat packedB, colsum, corr; // int32 mode }; +Ptr MatMulInt8Layer::create(const LayerParams& params) +{ + return Ptr(new MatMulInt8LayerImpl(params)); +} + Ptr MatMulInt8Layer::create(const MatMulInt8Params& params) { return Ptr(new MatMulInt8LayerImpl(params)); diff --git a/modules/dnn/src/layers/cpu_kernels/fast_gemm.hpp b/modules/dnn/src/layers/cpu_kernels/fast_gemm.hpp index 5072e45ba8..11f13dcea6 100644 --- a/modules/dnn/src/layers/cpu_kernels/fast_gemm.hpp +++ b/modules/dnn/src/layers/cpu_kernels/fast_gemm.hpp @@ -166,6 +166,54 @@ struct MatMulHelper { } }; +// numpy 1-D promotion: A[K]->[1,K], B[K]->[K,1]. `out` drops the inserted 1-dims. +inline void matmulShapes(const MatShape& rawA, const MatShape& rawB, bool trans_a, bool trans_b, + MatShape& Ap, MatShape& Bp, MatShape& full, MatShape& out) { + const bool a1d = rawA.size() == 1, b1d = rawB.size() == 1; + Ap = a1d ? MatShape{1, rawA[0]} : rawA; + Bp = b1d ? MatShape{rawB[0], 1} : rawB; + CV_CheckGE(Ap.size(), (size_t)2, "DNN/MatMul: invalid shape of input A"); + CV_CheckGE(Bp.size(), (size_t)2, "DNN/MatMul: invalid shape of input B"); + + int mA = Ap[Ap.size() - 2], nA = Ap.back(); + int mB = Bp[Bp.size() - 2], nB = Bp.back(); + int M = trans_a ? nA : mA; + int N = trans_b ? mB : nB; + int K_A = trans_a ? mA : nA; + int K_B = trans_b ? nB : mB; + CV_CheckEQ(K_A, K_B, "DNN/MatMul: invalid dimension K"); + + if (Ap.size() != 2 || Bp.size() != 2) { + const auto &more = Ap.size() > Bp.size() ? Ap : Bp; + const auto &less = Ap.size() > Bp.size() ? Bp : Ap; + size_t diff_dims = more.size() - less.size(); + full = more; + for (size_t i = 0; i < less.size() - 2; i++) { + const auto dl = less[i], dm = more[i + diff_dims]; + if (dl != 1 && dm != 1 && dl != dm) + CV_Error(Error::StsBadSize, "DNN/MatMul: invalid shape for broadcasting"); + if (dm == 1) + full[i + diff_dims] = dl; + } + full[full.size() - 2] = M; + full[full.size() - 1] = N; + } else { + full = MatShape{M, N}; + } + + // both 1-D, no batch -> 0-D scalar (total 1), not empty (total 0) + if (a1d && b1d && full.size() == 2) { + out = MatShape::scalar(); + return; + } + // drop the 1-dims inserted by promotion + out.clear(); + for (size_t i = 0; i + 2 < full.size(); i++) + out.push_back(full[i]); + if (!a1d) out.push_back(M); + if (!b1d) out.push_back(N); +} + size_t fastGemmPackBSize(size_t N, size_t K, const FastGemmOpt &opt); void fastGemmPackB(const Mat &m, std::vector &packed_B, bool trans, FastGemmOpt &opt); diff --git a/modules/dnn/src/layers/matmul_layer.cpp b/modules/dnn/src/layers/matmul_layer.cpp index 79adde1c81..4476e79c39 100644 --- a/modules/dnn/src/layers/matmul_layer.cpp +++ b/modules/dnn/src/layers/matmul_layer.cpp @@ -74,54 +74,6 @@ class MatMulLayerImpl CV_FINAL : public MatMulLayer { backendId == DNN_BACKEND_CANN; } - // numpy 1-D promotion: A[K]->[1,K], B[K]->[K,1]. `out` drops the inserted 1-dims. - static void matmulShapes(const MatShape& rawA, const MatShape& rawB, bool trans_a, bool trans_b, - MatShape& Ap, MatShape& Bp, MatShape& full, MatShape& out) { - const bool a1d = rawA.size() == 1, b1d = rawB.size() == 1; - Ap = a1d ? MatShape{1, rawA[0]} : rawA; - Bp = b1d ? MatShape{rawB[0], 1} : rawB; - CV_CheckGE(Ap.size(), (size_t)2, "DNN/MatMul: invalid shape of input A"); - CV_CheckGE(Bp.size(), (size_t)2, "DNN/MatMul: invalid shape of input B"); - - int mA = Ap[Ap.size() - 2], nA = Ap.back(); - int mB = Bp[Bp.size() - 2], nB = Bp.back(); - int M = trans_a ? nA : mA; - int N = trans_b ? mB : nB; - int K_A = trans_a ? mA : nA; - int K_B = trans_b ? nB : mB; - CV_CheckEQ(K_A, K_B, "DNN/MatMul: invalid dimension K"); - - if (Ap.size() != 2 || Bp.size() != 2) { - const auto &more = Ap.size() > Bp.size() ? Ap : Bp; - const auto &less = Ap.size() > Bp.size() ? Bp : Ap; - size_t diff_dims = more.size() - less.size(); - full = more; - for (size_t i = 0; i < less.size() - 2; i++) { - const auto dl = less[i], dm = more[i + diff_dims]; - if (dl != 1 && dm != 1 && dl != dm) - CV_Error(Error::StsBadSize, "DNN/MatMul: invalid shape for broadcasting"); - if (dm == 1) - full[i + diff_dims] = dl; - } - full[full.size() - 2] = M; - full[full.size() - 1] = N; - } else { - full = MatShape{M, N}; - } - - // both 1-D, no batch -> 0-D scalar (total 1), not empty (total 0) - if (a1d && b1d && full.size() == 2) { - out = MatShape::scalar(); - return; - } - // drop the 1-dims inserted by promotion - out.clear(); - for (size_t i = 0; i + 2 < full.size(); i++) - out.push_back(full[i]); - if (!a1d) out.push_back(M); - if (!b1d) out.push_back(N); - } - virtual bool getMemoryShapes(const std::vector &inputs, const int requiredOutputs, std::vector &outputs, diff --git a/modules/dnn/src/onnx/onnx_importer2.cpp b/modules/dnn/src/onnx/onnx_importer2.cpp index f52008da72..720bb33fe1 100644 --- a/modules/dnn/src/onnx/onnx_importer2.cpp +++ b/modules/dnn/src/onnx/onnx_importer2.cpp @@ -295,6 +295,8 @@ protected: void parseDequantizeLinear (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto); void parseQuantizeLinear (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto); void parseDynamicQuantizeLinear(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto); + void parseConvInteger (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto); + void parseMatMulInteger (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto); void parseCustomLayer (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto); void parseQConv (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto); void parseQMatMul (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto); @@ -2509,6 +2511,26 @@ void ONNXImporter2::parseDynamicQuantizeLinear(LayerParams& layerParams, const o addLayer(layerParams, node_proto); } +// ONNX ConvInteger (opset 10) is the int32-output mode of Conv2Int8; zero points stay inputs +void ONNXImporter2::parseConvInteger(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto) +{ + int n_inputs = node_proto.input_size(); + CV_Assert(2 <= n_inputs && n_inputs <= 4); + layerParams.type = "Conv2Int8"; + layerParams.set("int32_output", true); + addLayer(layerParams, node_proto, n_inputs); +} + +// ONNX MatMulInteger (opset 10) is MatMulInt8 in int32-output mode; B and zero points stay inputs +void ONNXImporter2::parseMatMulInteger(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto) +{ + int n_inputs = node_proto.input_size(); + CV_Assert(2 <= n_inputs && n_inputs <= 4); + layerParams.type = "MatMulInt8"; + layerParams.set("int32_output", true); + addLayer(layerParams, node_proto, n_inputs); +} + void ONNXImporter2::parseRMSNormalization(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto) { layerParams.type = "RMSNormalization"; @@ -3507,6 +3529,8 @@ void ONNXImporter2::buildDispatchMap_ONNX_AI() dispatch["DequantizeLinear"] = &ONNXImporter2::parseDequantizeLinear; dispatch["QuantizeLinear"] = &ONNXImporter2::parseQuantizeLinear; dispatch["DynamicQuantizeLinear"] = &ONNXImporter2::parseDynamicQuantizeLinear; + dispatch["ConvInteger"] = &ONNXImporter2::parseConvInteger; + dispatch["MatMulInteger"] = &ONNXImporter2::parseMatMulInteger; dispatch["QLinearConv"] = &ONNXImporter2::parseQConv; dispatch["QLinearMatMul"] = &ONNXImporter2::parseQMatMul; diff --git a/modules/dnn/test/test_onnx_conformance_layer_filter__openvino.inl.hpp b/modules/dnn/test/test_onnx_conformance_layer_filter__openvino.inl.hpp index 3f88bca728..18ce12a3a4 100644 --- a/modules/dnn/test/test_onnx_conformance_layer_filter__openvino.inl.hpp +++ b/modules/dnn/test/test_onnx_conformance_layer_filter__openvino.inl.hpp @@ -273,7 +273,7 @@ CASE(test_basic_conv_without_padding) SKIP_MYRIAD; #endif CASE(test_basic_convinteger) - // no filter + SKIP; CASE(test_batchnorm_epsilon) SKIP; CASE(test_batchnorm_epsilon_training_mode) @@ -727,9 +727,9 @@ CASE(test_conv_with_strides_padding) SKIP_MYRIAD; #endif CASE(test_convinteger_with_padding) - // no filter + SKIP; CASE(test_convinteger_without_padding) - // no filter + SKIP; CASE(test_convtranspose) SKIP; CASE(test_convtranspose_1d) @@ -1721,7 +1721,7 @@ CASE(test_matmul_3d) CASE(test_matmul_4d) // no filter CASE(test_matmulinteger) - // no filter + SKIP; CASE(test_max_example) SKIP; CASE(test_max_float16) diff --git a/modules/dnn/test/test_onnx_conformance_layer_parser_denylist.inl.hpp b/modules/dnn/test/test_onnx_conformance_layer_parser_denylist.inl.hpp index 3ccdd1c4ab..aecd51f90e 100644 --- a/modules/dnn/test/test_onnx_conformance_layer_parser_denylist.inl.hpp +++ b/modules/dnn/test/test_onnx_conformance_layer_parser_denylist.inl.hpp @@ -24,7 +24,6 @@ "test_averagepool_3d_dilations_large_count_include_pad_is_1_ceil_mode_is_False", "test_averagepool_3d_dilations_large_count_include_pad_is_1_ceil_mode_is_True", "test_averagepool_3d_dilations_small", -"test_basic_convinteger", // Issues::Layer::Can't create layer "onnx_node_output_0!y" of type "ConvInteger" in function 'getLayerInstance' "test_basic_deform_conv_with_padding", "test_basic_deform_conv_without_padding", "test_batchnorm_epsilon_training_mode", // ---- same as above --- @@ -79,8 +78,6 @@ "test_compress_1", // ---- same as above --- "test_compress_default_axis", // ---- same as above --- "test_compress_negative_axis", // ---- same as above --- -"test_convinteger_with_padding", // Issues::Layer::Can't create layer "onnx_node_output_0!y" of type "ConvInteger" in function 'getLayerInstance' -"test_convinteger_without_padding", //Issues::Layer::Can't create layer "onnx_node_output_0!y" of type "ConvInteger" in function 'getLayerInstance' "test_deform_conv_with_mask_bias", "test_deform_conv_with_multiple_offset_groups", "test_dequantizelinear_float4e2m1", @@ -97,7 +94,6 @@ "test_if_seq", // Issue::typeProto.has_tensor_type() in function 'dumpValueInfoProto' "test_loop13_seq", // Loop with tensor sequences output, not yet supported in OpenCV "test_loop16_seq_none", // Loop with optional tensor sequences, not yet supported in OpenCV -"test_matmulinteger", // Issues::Layer does not exist. Can't create layer "onnx_node_output_0!Y" of type "MatMulInteger" in function 'getLayerInstance' "test_melweightmatrix", "test_momentum", // Issues::Layer does not exist. Can't create layer "onnx_node_output_0!X1_new" of type "ai.onnx.preview.training.Momentum" in function 'getLayerInstance' "test_momentum_multiple", // ---- same as above --- diff --git a/modules/dnn/test/test_onnx_importer.cpp b/modules/dnn/test/test_onnx_importer.cpp index e1ab66e9c1..516ccdbb61 100644 --- a/modules/dnn/test/test_onnx_importer.cpp +++ b/modules/dnn/test/test_onnx_importer.cpp @@ -2388,6 +2388,69 @@ TEST_P(Test_ONNX_layers, Quantized_Convolution) } } +TEST_P(Test_ONNX_layers, ConvInteger) +{ + if (backend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH) + applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_NGRAPH); + + testONNXModels("convinteger_u8"); + testONNXModels("convinteger_depthwise"); + testONNXModels("convinteger_1x1"); + testONNXModels("convinteger_s8"); + testONNXModels("convinteger_full_range_weights"); + testONNXModels("convinteger_groups"); + testONNXModels("convinteger_1d"); + testONNXModels("convinteger_runtime_weights", npy, 0, 0, false, true, 2); + testONNXModels("convinteger_dynamic"); + + // the second input gives DynamicQuantizeLinear another zero point on the same net + Net net = readNetFromONNX(_tf("models/convinteger_dynamic.onnx")); + ASSERT_FALSE(net.empty()); + net.setPreferableBackend(backend); + net.setPreferableTarget(target); + for (const String set : {"", "_set2"}) { + net.setInput(blobFromNPY(_tf("data/input_convinteger_dynamic" + set + ".npy"))); + Mat ref = blobFromNPY(_tf("data/output_convinteger_dynamic" + set + ".npy")); + normAssert(ref, net.forward(), set.c_str()); + } +} + +TEST_P(Test_ONNX_layers, MatMulInteger) +{ + if (backend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH) + applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_NGRAPH); + + testONNXModels("matmulinteger_u8_per_column"); + testONNXModels("matmulinteger_s8_weights"); + testONNXModels("matmulinteger_full_range_weights"); + testONNXModels("matmulinteger_s8"); + testONNXModels("matmulinteger_runtime_weights", npy, 0, 0, false, true, 2); + testONNXModels("matmulinteger_b_zero_point_only"); + testONNXModels("matmulinteger_transposed_a"); + testONNXModels("matmulinteger_k1_n1"); + testONNXModels("matmulinteger_extremes"); + testONNXModels("matmulinteger_extremes_s8"); + testONNXModels("matmulinteger_batched_b"); + testONNXModels("matmulinteger_batched_s8"); + testONNXModels("matmulinteger_vector_a"); + testONNXModels("matmulinteger_b_vector"); + testONNXModels("matmulinteger_vector_vector"); + testONNXModels("matmulinteger_a_zp_per_row"); + testONNXModels("matmulinteger_a_zp_per_row_nd"); + testONNXModels("matmulinteger_dynamic"); + + // the second input gives DynamicQuantizeLinear another zero point on the same net + Net net = readNetFromONNX(_tf("models/matmulinteger_dynamic.onnx")); + ASSERT_FALSE(net.empty()); + net.setPreferableBackend(backend); + net.setPreferableTarget(target); + for (const String set : {"", "_set2"}) { + net.setInput(blobFromNPY(_tf("data/input_matmulinteger_dynamic" + set + ".npy"))); + Mat ref = blobFromNPY(_tf("data/output_matmulinteger_dynamic" + set + ".npy")); + normAssert(ref, net.forward(), set.c_str()); + } +} + TEST_P(Test_ONNX_layers, Quantized_MatMul) { testONNXModels("quantized_matmul_uint8_weights", npy, 0.008, 0.015);