diff --git a/modules/dnn/CMakeLists.txt b/modules/dnn/CMakeLists.txt index eed79a7bef..d5d0b6a25d 100644 --- a/modules/dnn/CMakeLists.txt +++ b/modules/dnn/CMakeLists.txt @@ -19,6 +19,7 @@ ocv_add_dispatched_file("layers/cpu_kernels/activation_kernels" AVX AVX2 NEON NE ocv_add_dispatched_file("layers/cpu_kernels/flash_attention" AVX2) # no AVX: below AVX2 the intrinsics are 128-bit and the baseline copy runs faster ocv_add_dispatched_file("layers/cpu_kernels/fast_gemm_thin" AVX2 NEON RVV LASX) +ocv_add_dispatched_file("layers/cpu_kernels/matmulnbits_kernels" AVX2 AVX512_SKX NEON) ocv_add_dispatched_file_force_all("layers/cpu_kernels/gridsample_kernels" AVX AVX2 NEON RVV LASX) ocv_add_dispatched_file_force_all("dnn_utils" AVX AVX2 AVX512_SKX AVX512_ICL NEON RVV LASX) diff --git a/modules/dnn/include/opencv2/dnn/all_layers.hpp b/modules/dnn/include/opencv2/dnn/all_layers.hpp index 9074de53d7..9c2b744cc6 100644 --- a/modules/dnn/include/opencv2/dnn/all_layers.hpp +++ b/modules/dnn/include/opencv2/dnn/all_layers.hpp @@ -480,6 +480,17 @@ CV__DNN_INLINE_NS_BEGIN static Ptr create(const LayerParams& params); }; + class CV_EXPORTS GatherBlockQuantizedLayer : public Layer + { + public: + int gather_axis; + int quantize_axis; + int block_size; + int bits; + + static Ptr create(const LayerParams& params); + }; + /** @brief GatherElements layer * GatherElements takes two inputs data and indices of the same rank r >= 1 and an optional attribute axis and works such that: * output[i][j][k] = data[index[i][j][k]][j][k] if axis = 0 and r = 3 @@ -724,6 +735,8 @@ CV__DNN_INLINE_NS_BEGIN { public: MatShape newShapeDesc; + //! ONNX allowzero: a 0 in the shape is a zero-size axis, not a copy of the input's. + bool allowZero; static Ptr create(const LayerParams& params); }; diff --git a/modules/dnn/perf/perf_layer.cpp b/modules/dnn/perf/perf_layer.cpp index bb5d37511e..e498134831 100644 --- a/modules/dnn/perf/perf_layer.cpp +++ b/modules/dnn/perf/perf_layer.cpp @@ -1392,4 +1392,53 @@ PERF_TEST_P_(Layer_DynamicInt8, MatMulInteger) INSTANTIATE_TEST_CASE_P(/**/, Layer_DynamicInt8, testing::Values(std::make_tuple(DNN_BACKEND_OPENCV, DNN_TARGET_CPU))); +typedef TestBaseWithParam > Layer_MatMulNBits; +PERF_TEST_P_(Layer_MatMulNBits, matmulnbits) +{ + const int N = get<0>(GetParam())[0], K = get<0>(GetParam())[1]; + const int M = get<1>(GetParam()); + const std::string format = get<2>(GetParam()); + const int bits = format == "8bit" ? 8 : 4, block_size = 32; + const int n_blk = (K + block_size - 1) / block_size, epb = 8 / bits; + + Mat A(std::vector{M, K}, CV_32F); + Mat B(std::vector{N, n_blk * block_size * bits / 8}, CV_8U); + Mat scales(std::vector{N, n_blk}, CV_32F); + randu(A, -1.f, 1.f); + randu(B, 0, 256); + randu(scales, 0.001f, 0.01f); + + LayerParams lp; + lp.set("K", K); + lp.set("N", N); + lp.set("bits", bits); + lp.set("block_size", block_size); + lp.blobs.push_back(B); + lp.blobs.push_back(scales); + if (format == "4bit_zp") { + Mat zp(std::vector{N, (n_blk + epb - 1) / epb}, CV_8U); + randu(zp, 0, 256); + lp.blobs.push_back(zp); + } + + Net net; + net.addLayerToPrev("matmulnbits", "MatMulNBits", lp); + net.setInput(A); + net.setPreferableBackend(DNN_BACKEND_OPENCV); + net.setPreferableTarget(DNN_TARGET_CPU); + net.forward(); + + TEST_CYCLE() + { + net.forward(); + } + SANITY_CHECK_NOTHING(); +} + +// Qwen2.5-0.5B projections: q/o, gate/up, down. +INSTANTIATE_TEST_CASE_P(/**/, Layer_MatMulNBits, Combine( + Values(Vec2i(896, 896), Vec2i(4864, 896), Vec2i(896, 4864)), + Values(1, 16, 128), + Values("4bit", "4bit_zp", "8bit"))); + } // namespace diff --git a/modules/dnn/src/adjacency_graph.hpp b/modules/dnn/src/adjacency_graph.hpp index 53de500c74..bf4441be94 100644 --- a/modules/dnn/src/adjacency_graph.hpp +++ b/modules/dnn/src/adjacency_graph.hpp @@ -588,6 +588,11 @@ struct FusionOps * the order unfold expects to read it back. A null slot means the layer owns none. */ bool (*ownedBuffers)(const Layer* self, std::vector& out) = nullptr; + + //! Folds a scalar multiplier applied to input @p slot into the layer's own parameters, + //! so a pass can remove the Mul without knowing where the factor lives. A Div contributes + //! its reciprocal. Refusing is always safe; a null slot means the layer never does. + bool (*foldInputScalar)(Layer* self, int slot, float scale) = nullptr; }; /** @brief Binds @p ops to one concrete layer class. Last registration for a type wins. */ diff --git a/modules/dnn/src/graph_fusion_basic.cpp b/modules/dnn/src/graph_fusion_basic.cpp index 903133fbd8..1a514c713e 100644 --- a/modules/dnn/src/graph_fusion_basic.cpp +++ b/modules/dnn/src/graph_fusion_basic.cpp @@ -5,6 +5,7 @@ #include "precomp.hpp" #include "net_impl.hpp" #include "adjacency_graph.hpp" +#include "layers/layers_common.hpp" namespace cv { namespace dnn { CV__DNN_INLINE_NS_BEGIN @@ -297,6 +298,140 @@ struct FuseBNPass std::vector usecounts; }; +// Rewrites two Slices that partition one tensor along an axis into a single Split. +// X -> Slice[0:P] and X -> Slice[P:end] => X -> Split[{P, -1}] +// Split2 resolves the -1 and clamps P at runtime, so the axis length need not be known. + +struct ModelFusionSliceToSplit +{ + explicit ModelFusionSliceToSplit(Net::Impl* netimpl_) : netimpl(netimpl_) {} + + void fuse() { fuseGraph(netimpl->mainGraph); } + + // Only a single-axis step-1 slice maps onto Split. An omitted optional input is padded + // to an empty Arg, which is a missing step rather than a non-constant one. + bool readSlice(const Ptr& layer, int64_t& start, int64_t& end, int& axis) const + { + size_t n = layer->inputs.size(); + if (n < 4 || n > 5) return false; + for (size_t i = 1; i < 4; i++) + if (!netimpl->isConstArg(layer->inputs[i])) return false; + + vector s, e, a, st; + tensorToIntVec(netimpl->argTensor(layer->inputs[1]), s); + tensorToIntVec(netimpl->argTensor(layer->inputs[2]), e); + tensorToIntVec(netimpl->argTensor(layer->inputs[3]), a); + if (n == 5 && !layer->inputs[4].empty()) { + if (!netimpl->isConstArg(layer->inputs[4])) return false; + tensorToIntVec(netimpl->argTensor(layer->inputs[4]), st); + if (st.size() != 1 || st[0] != 1) return false; + } + if (s.size() != 1 || e.size() != 1 || a.size() != 1) return false; + + // tensorToIntVec saturates INT64_MAX to INT_MAX, which is the "to the end" marker. + start = s[0]; end = e[0]; axis = a[0]; + return start >= 0 && end >= 0; + } + + bool fuseGraph(Ptr& graph) + { + const vector>& prog = graph->prog(); + size_t nops = prog.size(); + bool modified = false; + + for (size_t i = 0; i < nops; i++) { + if (!prog[i]) continue; + vector>* subgraphs = prog[i]->subgraphs(); + if (subgraphs) { + for (Ptr& g : *subgraphs) + if (fuseGraph(g)) modified = true; + } + } + + std::map producer; + for (size_t i = 0; i < nops; i++) { + if (!prog[i]) continue; + for (Arg out : prog[i]->outputs) + producer[out.idx] = (int)i; + } + + // Slice layers reading each tensor, in program order. + std::map> readers; + for (size_t i = 0; i < nops; i++) { + if (!prog[i] || prog[i]->inputs.empty()) continue; + if (!dynamic_cast(prog[i].get())) continue; + if (prog[i]->outputs.size() != 1) continue; + readers[prog[i]->inputs[0].idx].push_back((int)i); + } + + vector dropped(nops, false); + vector> newprog = prog; + + for (const auto& kv : readers) { + const vector& idx = kv.second; + if (idx.size() != 2) continue; + + // A multi-output producer would have the Split read one of several results, + // and a Shape producer feeds indices rather than data. + auto pr = producer.find(kv.first); + if (pr != producer.end() && prog[pr->second]) { + if (prog[pr->second]->outputs.size() != 1) continue; + if (dynamic_cast(prog[pr->second].get())) continue; + } + + int64_t s0 = 0, e0 = 0, s1 = 0, e1 = 0; + int a0 = 0, a1 = 0; + if (!readSlice(prog[idx[0]], s0, e0, a0)) continue; + if (!readSlice(prog[idx[1]], s1, e1, a1)) continue; + if (a0 != a1) continue; + + int first = 0, second = 1; + if (s0 > s1) std::swap(first, second); + const int64_t fs = first == 0 ? s0 : s1, fe = first == 0 ? e0 : e1; + const int64_t ss = first == 0 ? s1 : s0, se = first == 0 ? e1 : e0; + + // [0, P) then [P, end): only an open end is provably the rest of the axis. + if (fs != 0 || ss != fe || fe <= 0 || se != INT_MAX) continue; + + LayerParams sp; + sp.name = prog[idx[first]]->name; + sp.type = "Split2"; + sp.set("axis", a0); + int sizes[2] = { (int)fe, -1 }; + sp.set("split", DictValue::arrayInt(sizes, 2)); + + Ptr split = LayerFactory::createLayerInstance("Split2", sp); + if (!split) continue; + split->inputs = { prog[idx[0]]->inputs[0] }; + split->outputs = { prog[idx[first]]->outputs[0], prog[idx[second]]->outputs[0] }; + split->netimpl = netimpl; + + // At the earlier Slice: a layer between the two may read either output. + newprog[idx[0]] = split; + dropped[idx[1]] = true; + modified = true; + } + + if (modified) { + vector> finalprog; + finalprog.reserve(nops); + for (size_t i = 0; i < nops; i++) + if (!dropped[i] && newprog[i]) + finalprog.push_back(newprog[i]); + graph->setProg(finalprog); + } + return modified; + } + + Net::Impl* netimpl; +}; + +void Net::Impl::fuseSliceToSplit() +{ + ModelFusionSliceToSplit pass(this); + pass.fuse(); +} + void Net::Impl::fuseBN() { FuseBNPass pass(this); diff --git a/modules/dnn/src/graph_fusion_chain.cpp b/modules/dnn/src/graph_fusion_chain.cpp index 18ac57ea35..7c55a7372e 100644 --- a/modules/dnn/src/graph_fusion_chain.cpp +++ b/modules/dnn/src/graph_fusion_chain.cpp @@ -506,12 +506,16 @@ void Net::Impl::fuseChains() fuseBN(); // Order is load-bearing: each pass matches shapes the one before it leaves. + // RMSNorm first: the chain pass below would otherwise absorb either of its + // Muls into a neighbouring chain and leave the pattern unmatchable. + fuseRMSNorm(); fuseAttention(); + fuseSliceToSplit(); fuseMatMulConstBToGemm(); fuseSharedInputGemm(); fuseReshapeTranspose(); + fuseInputScalars(); fuseTransposeMatMul(); - fuseScaleSoftmax(); // A sink runs the math it absorbs in its own CPU kernel. setPreferableTarget resolves // only CPU and CUDA while mainGraph is set, so nothing reaches here on OpenCL today. diff --git a/modules/dnn/src/graph_fusion_input_scalar.cpp b/modules/dnn/src/graph_fusion_input_scalar.cpp new file mode 100644 index 0000000000..fdda748e50 --- /dev/null +++ b/modules/dnn/src/graph_fusion_input_scalar.cpp @@ -0,0 +1,148 @@ +// 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. + +// Folds a scalar Mul or Div on a layer's input into that layer's own parameters. +// +// X -> Mul(X, c) -> L => X -> L, with c folded in +// X -> Div(X, c) -> L => X -> L, with 1/c folded in +// +// Where it lands is the layer's choice: alpha for MatMul and Gemm, scale for Softmax. +// Declining is always safe, so the offer costs nothing. + +#include "precomp.hpp" +#include "net_impl.hpp" +#include "adjacency_graph.hpp" + +namespace cv { namespace dnn { +CV__DNN_INLINE_NS_BEGIN + +using std::vector; + +struct ModelFusionInputScalar +{ + explicit ModelFusionInputScalar(Net::Impl* netimpl_) : netimpl(netimpl_) {} + + void fuse() { fuseGraph(netimpl->mainGraph); } + + bool scalarOf(Arg a, float& out) const + { + if (!netimpl->isConstArg(a)) return false; + Mat t = netimpl->argTensor(a); + // A one-element tensor of higher rank broadcasts the input up to that rank. + if (t.total() != 1 || t.dims > 1) return false; + if (t.type() == CV_32F) { out = t.ptr()[0]; return true; } + if (t.type() == CV_64F) { out = (float)t.ptr()[0]; return true; } + if (t.type() == CV_16F) { + Mat f; t.convertTo(f, CV_32F); out = f.ptr()[0]; return true; + } + return false; + } + + bool fuseGraph(Ptr& graph) + { + const vector>& prog = graph->prog(); + size_t nops = prog.size(); + bool modified = false; + + for (size_t i = 0; i < nops; i++) { + if (!prog[i]) continue; + vector>* subgraphs = prog[i]->subgraphs(); + if (subgraphs) { + for (Ptr& g : *subgraphs) + if (fuseGraph(g)) modified = true; + } + } + + vector usecounts; + netimpl->useCounts(usecounts); + + std::map producer; + for (size_t i = 0; i < nops; i++) { + if (!prog[i]) continue; + for (Arg out : prog[i]->outputs) + producer[out.idx] = (int)i; + } + + vector dropped(nops, false); + + for (size_t i = 0; i < nops; i++) { + const Ptr& layer = prog[i]; + if (!layer || dropped[i]) continue; + Layer* sink = dynamic_cast(layer.get()); + if (!sink) continue; + const FusionOps* ops = fusionOpsFor(sink); + if (!ops || !ops->foldInputScalar) continue; + + for (size_t slot = 0; slot < layer->inputs.size(); slot++) { + Arg mid = layer->inputs[slot]; + auto it = producer.find(mid.idx); + if (it == producer.end()) continue; + int pidx = it->second; + if (pidx < 0 || dropped[pidx]) continue; + + const Ptr& pl = prog[pidx]; + NaryEltwiseLayer* elt = dynamic_cast(pl.get()); + if (!elt) continue; + const bool is_mul = elt->op == NaryEltwiseLayer::OPERATION::PROD; + const bool is_div = elt->op == NaryEltwiseLayer::OPERATION::DIV; + if (!is_mul && !is_div) continue; + if (pl->inputs.size() != 2 || pl->outputs.size() != 1) continue; + + float scale = 1.f; + int data_slot = -1; + if (scalarOf(pl->inputs[1], scale)) data_slot = 0; + // Mul commutes, Div does not + else if (is_mul && scalarOf(pl->inputs[0], scale)) data_slot = 1; + else continue; + + if (is_div) { + if (scale == 0.f) continue; + scale = 1.f / scale; + } + if (!std::isfinite(scale)) continue; + + // Offered last: a layer that accepts has already changed itself. + if (!ops->foldInputScalar(sink, (int)slot, scale)) continue; + + // A shared Mul/Div stays until its last consumer has folded it. + Arg src = pl->inputs[data_slot]; + layer->inputs[slot] = src; + usecounts[src.idx]++; + if (--usecounts[mid.idx] == 0) { + dropped[pidx] = true; + for (Arg a : pl->inputs) + if (a.idx > 0) + usecounts[a.idx]--; + } + modified = true; + } + } + + if (modified) { + vector> newprog; + newprog.reserve(nops); + for (size_t i = 0; i < nops; i++) + if (!dropped[i] && prog[i]) + newprog.push_back(prog[i]); + graph->setProg(newprog); + } + return modified; + } + + Net::Impl* netimpl; +}; + +void Net::Impl::fuseInputScalars() +{ + // Only the CPU kernels read the folded factor. + if (preferableBackend != DNN_BACKEND_OPENCV || preferableTarget != DNN_TARGET_CPU) + return; + ModelFusionInputScalar pass(this); + pass.fuse(); +} + +CV__DNN_INLINE_NS_END +}} diff --git a/modules/dnn/src/graph_fusion_matmul_to_gemm.cpp b/modules/dnn/src/graph_fusion_matmul_to_gemm.cpp index 59803e2784..00d7afc424 100644 --- a/modules/dnn/src/graph_fusion_matmul_to_gemm.cpp +++ b/modules/dnn/src/graph_fusion_matmul_to_gemm.cpp @@ -12,6 +12,9 @@ // by BiasedMatmulSubgraph when it was a const Add): // A(any rank) -> MatMul[const B (2D), optional const bias [N] / scalar] // +// B is a blob when it was already const at parse time, and a const input arg when +// constFold() made it const afterwards (e.g. a Transpose of an initializer). +// // Replacement: // A -> Gemm[transA=false, transB=mm.trans_b, alpha=mm.alpha, beta=mm.beta, // constB=true, const_C=have_bias, flatten_a=false, @@ -20,7 +23,7 @@ // Restrictions (skip otherwise): // - MatMul.trans_a must be false (ND-A flattening assumes row-major K is the // last axis) -// - blobs.size() in {1, 2} and blobs[0] (B) is 2D float32 +// - B is 2D float32, from blobs[0] or from a const input; a bias needs blobs[1] // - if a bias is present, it must be scalar (total==1) or 1D length-N. The // Gemm flatten_a=false bias path tiles a per-row pattern, so 2D / per-row // biases like [M, N] aren't supported by this rewriter (they would change @@ -171,18 +174,24 @@ struct ModelFusionMatMulToGemm // doesn't know how to translate to Gemm. if (dynamic_cast(layer.get())) continue; - // Constant B lives in blobs[0] post-parse; if blobs is empty the - // MatMul has a runtime B and isn't a candidate. - if (layer->blobs.empty() || layer->blobs.size() > 2) continue; + if (layer->blobs.size() > 2) continue; if (mm->trans_a) continue; // ND-A flatten assumes K = last axis - const Mat& B = layer->blobs[0]; + // parseMatMul blobs a B that is const at import time; one that constFold() + // made const afterwards is still an input, and carries no bias. + Mat B; + bool constInputB = layer->blobs.empty(); + if (constInputB) { + if (layer->inputs.size() != 2) continue; + if (!netimpl->isConstArg(layer->inputs[1])) continue; + B = netimpl->argTensor(layer->inputs[1]); + } else { + if (layer->inputs.size() != 1) continue; + B = layer->blobs[0]; + } if (B.dims != 2 || B.type() != CV_32F) continue; - // Single runtime input expected (the const B was absorbed into blobs). - if (layer->inputs.size() != 1) continue; - int N = mm->trans_b ? B.size[0] : B.size[1]; int K = mm->trans_b ? B.size[1] : B.size[0]; (void)K; @@ -231,7 +240,7 @@ struct ModelFusionMatMulToGemm Ptr gemm = LayerFactory::createLayerInstance("Gemm", gp); CV_Assert(gemm); // the Mul/Add layers folded into it are already marked as dropped - gemm->inputs = layer->inputs; + gemm->inputs = constInputB ? vector{ layer->inputs[0] } : layer->inputs; gemm->outputs = outputs; gemm->netimpl = netimpl; diff --git a/modules/dnn/src/graph_fusion_reshape_transpose.cpp b/modules/dnn/src/graph_fusion_reshape_transpose.cpp index 133232c190..b6497afb24 100644 --- a/modules/dnn/src/graph_fusion_reshape_transpose.cpp +++ b/modules/dnn/src/graph_fusion_reshape_transpose.cpp @@ -10,6 +10,10 @@ // - Transpose(p1) -> Transpose(p2): compose into a single Transpose with // perm[i] = p1[p2[i]]. // - Identity Transpose (perm == [0,1,...,n-1]): bypass. +// - Reshape whose shape operand is Concat(Unsqueeze(Gather(Shape(s), i)), consts...): +// replace it with a constant, writing 0 where the gathered dimension provably equals +// the Reshape input's own at that position, which Reshape reads as "keep this axis". +// Skipped under allowzero, where a 0 is a zero-size axis. // These run iteratively, so a Reshape+Transpose+Reshape that ends up with an // identity transpose collapses to a single Reshape, and adjacent transposes // in attention layouts merge. @@ -64,6 +68,100 @@ struct ModelFusionReshapeTranspose return false; } + bool constInts(Arg a, std::vector& out) const + { + if (!netimpl->isConstArg(a)) return false; + Mat t = netimpl->argTensor(a); + if (t.empty() || t.total() > 16) return false; + tensorToIntVec(t, out); + return !out.empty(); + } + + // The declared length of `arg`'s axis `ax`, or 0 when it is not known. + int declaredDim(Arg arg, int ax) const + { + auto it = netimpl->declaredShapes.find(arg.idx); + if (it == netimpl->declaredShapes.end()) return 0; + const MatShape& sh = it->second; + if (ax < 0 || ax >= sh.dims) return 0; + return sh[ax]; + } + + bool foldShapeOperand(const vector>& prog, const std::map& producer, + vector& dropped, const std::set& externalArgs, + const Ptr& layer) + { + if (layer->inputs.size() != 2) return false; + const Arg root = layer->inputs[0], shapeArg = layer->inputs[1]; + if (netimpl->isConstArg(shapeArg)) return false; + if (usecounts[shapeArg.idx] != 1 || externalArgs.count(shapeArg.idx)) return false; + + auto pit = producer.find(shapeArg.idx); + if (pit == producer.end() || dropped[pit->second]) return false; + const Ptr& cl = prog[pit->second]; + Concat2Layer* cat = dynamic_cast(cl.get()); + if (!cat || cat->axis != 0 || cl->outputs.size() != 1) return false; + + std::vector shape, chain; + for (size_t k = 0; k < cl->inputs.size(); k++) { + std::vector vals; + if (constInts(cl->inputs[k], vals)) { + shape.insert(shape.end(), vals.begin(), vals.end()); + continue; + } + auto uit = producer.find(cl->inputs[k].idx); + if (uit == producer.end()) return false; + const Ptr& ul = prog[uit->second]; + if (!dynamic_cast(ul.get()) || ul->inputs.empty()) return false; + chain.push_back(uit->second); + + auto git = producer.find(ul->inputs[0].idx); + if (git == producer.end()) return false; + const Ptr& gl = prog[git->second]; + Gather2Layer* gath = dynamic_cast(gl.get()); + if (!gath || gath->axis != 0 || gl->inputs.size() != 2) return false; + chain.push_back(git->second); + + std::vector idx; + if (!constInts(gl->inputs[1], idx) || idx.size() != 1) return false; + + auto sit = producer.find(gl->inputs[0].idx); + if (sit == producer.end()) return false; + const Ptr& sl = prog[sit->second]; + ShapeLayer* shp = dynamic_cast(sl.get()); + if (!shp || shp->start != 0 || shp->end != INT_MAX || sl->inputs.empty()) + return false; + chain.push_back(sit->second); + + const int pos = (int)shape.size(); + const int gathered = declaredDim(sl->inputs[0], idx[0]); + // Only a shared symbolic dim stays equal at runtime; matching statics need not. + if (gathered >= 0 || gathered != declaredDim(root, pos)) return false; + shape.push_back(0); + } + if (shape.empty() || std::count(shape.begin(), shape.end(), -1) > 1) return false; + + Mat sm(1, (int)shape.size(), CV_32S, shape.data()); + layer->inputs[1] = netimpl->newConstArg(netimpl->argData(shapeArg).name + "/const", + sm.clone()); + dropped[pit->second] = true; + usecounts[shapeArg.idx] = 0; + + // Each triple is Unsqueeze, Gather, Shape. A producer is released only once its own + // reader here went, so a Shape several Gathers share outlives all but the last. + for (size_t k = 0; k + 2 < chain.size(); k += 3) { + for (size_t t = k; t < k + 3; t++) { + const int li = chain[t]; + if (dropped[li] || prog[li]->outputs.size() != 1) break; + const int oi = prog[li]->outputs[0].idx; + if (usecounts[oi] == 0 || externalArgs.count(oi)) break; + if (--usecounts[oi] != 0) break; + dropped[li] = true; + } + } + return true; + } + bool fuseGraph(Ptr& graph) { const vector>& prog = graph->prog(); @@ -148,8 +246,12 @@ struct ModelFusionReshapeTranspose } } - //Reshape + Reshape -> Reshape (drop the inner reshape). Reshape2Layer* rs = dynamic_cast(layer.get()); + if (rs && !rs->allowZero && layer->outputs.size() == 1 && + foldShapeOperand(prog, producer, dropped, externalArgs, layer)) + modified = true; + // The fold runs first: the check below reads the spec it may have resolved. + //Reshape + Reshape -> Reshape (drop the inner reshape). if (rs && layer->outputs.size() == 1 && !shapeSpecCopiesInputDims(rs)) { auto it = producer.find(layer->inputs[0].idx); if (it != producer.end()) { diff --git a/modules/dnn/src/graph_fusion_rmsnorm.cpp b/modules/dnn/src/graph_fusion_rmsnorm.cpp new file mode 100644 index 0000000000..5484f13226 --- /dev/null +++ b/modules/dnn/src/graph_fusion_rmsnorm.cpp @@ -0,0 +1,188 @@ +// 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. + +// Fuses the decomposed RMSNorm that HuggingFace/optimum exports emit: +// X * (1 / Sqrt(ReduceMean(Pow(X, 2), [-1]) + eps)) * scale -> RMSNormalization(X, scale) + +#include "precomp.hpp" +#include "net_impl.hpp" + +namespace cv { namespace dnn { +CV__DNN_INLINE_NS_BEGIN + +using std::vector; +using std::string; + +struct ModelFusionRMSNorm +{ + explicit ModelFusionRMSNorm(Net::Impl* netimpl_) : netimpl(netimpl_) {} + + void fuse() { fuseGraph(netimpl->mainGraph); } + + static NaryEltwiseLayer* nary(const Ptr& layer, NaryEltwiseLayer::OPERATION op) + { + NaryEltwiseLayer* n = dynamic_cast(layer.get()); + return n && n->op == op ? n : nullptr; + } + + bool constScalar(Arg a, float& v) const + { + if (!netimpl->isConstArg(a)) return false; + const Mat& t = netimpl->argTensor(a); + // A one-element tensor of higher rank would raise X's rank, which the fused layer keeps. + if (t.total() != 1 || t.dims > 1 || t.type() != CV_32F) return false; + v = t.ptr()[0]; + return true; + } + + // The operand of a 2-input layer that is not `known`, or an invalid Arg if neither is. + static Arg otherInput(const Ptr& layer, Arg known) + { + if (layer->inputs.size() != 2) return Arg(); + if (layer->inputs[0].idx == known.idx) return layer->inputs[1]; + if (layer->inputs[1].idx == known.idx) return layer->inputs[0]; + return Arg(); + } + + bool fuseGraph(Ptr& graph) + { + const vector>& prog = graph->prog(); + size_t nops = prog.size(); + bool modified = false; + + for (size_t i = 0; i < nops; i++) { + if (!prog[i]) continue; + vector>* subgraphs = prog[i]->subgraphs(); + if (subgraphs) { + for (Ptr& g : *subgraphs) + if (fuseGraph(g)) modified = true; + } + } + + vector usecounts; + netimpl->useCounts(usecounts); + + std::set externalArgs; + for (Arg out : graph->outputs()) + externalArgs.insert(out.idx); + + std::map consumer, nconsumers; + for (size_t i = 0; i < nops; i++) { + if (!prog[i]) continue; + for (Arg in : prog[i]->inputs) { + consumer[in.idx] = (int)i; + nconsumers[in.idx]++; + } + } + + vector dropped(nops, false); + vector> newprog = prog; + + // One link of the chain: `a` feeds exactly one surviving single-output op and is + // not a graph output, which is what makes the removal self-contained. + auto step = [&](Arg a, int& op) -> bool { + if (externalArgs.count(a.idx) || usecounts[a.idx] != 1) return false; + auto nit = nconsumers.find(a.idx); + if (nit == nconsumers.end() || nit->second != 1) return false; + op = consumer[a.idx]; + return prog[op] && !dropped[op] && prog[op]->outputs.size() == 1; + }; + + for (size_t i = 0; i < nops; i++) { + const Ptr& pow_layer = prog[i]; + if (!pow_layer || dropped[i]) continue; + if (!nary(pow_layer, NaryEltwiseLayer::OPERATION::POW)) continue; + if (pow_layer->inputs.size() != 2 || pow_layer->outputs.size() != 1) continue; + + Arg X = pow_layer->inputs[0]; + float exponent = 0.f; + if (!constScalar(pow_layer->inputs[1], exponent) || exponent != 2.f) continue; + + int rm_idx = -1; + if (!step(pow_layer->outputs[0], rm_idx)) continue; + Reduce2Layer* rm = dynamic_cast(prog[rm_idx].get()); + if (!rm || rm->reduce_type != Reduce2Layer::ReduceType::MEAN) continue; + // Shapes are not inferred before fusion, so only -1 is known to be the last axis. + if (!rm->keepdims || rm->axes.size() != 1 || rm->axes[0] != -1) continue; + + int add_idx = -1; + if (!step(prog[rm_idx]->outputs[0], add_idx)) continue; + if (!nary(prog[add_idx], NaryEltwiseLayer::OPERATION::ADD)) continue; + Arg eps_arg = otherInput(prog[add_idx], prog[rm_idx]->outputs[0]); + float epsilon = 0.f; + if (eps_arg.empty() || !constScalar(eps_arg, epsilon)) continue; + + int sqrt_idx = -1; + if (!step(prog[add_idx]->outputs[0], sqrt_idx)) continue; + if (!dynamic_cast(prog[sqrt_idx].get())) continue; + + int div_idx = -1; + if (!step(prog[sqrt_idx]->outputs[0], div_idx)) continue; + if (!nary(prog[div_idx], NaryEltwiseLayer::OPERATION::DIV)) continue; + // Only Div(1, sqrt) is a reciprocal; Div(sqrt, 1) would invert the scaling. + const vector& div_in = prog[div_idx]->inputs; + if (div_in.size() != 2 || div_in[1].idx != prog[sqrt_idx]->outputs[0].idx) continue; + float numerator = 0.f; + if (!constScalar(div_in[0], numerator) || numerator != 1.f) continue; + + int mul_idx = -1; + if (!step(prog[div_idx]->outputs[0], mul_idx)) continue; + if (!nary(prog[mul_idx], NaryEltwiseLayer::OPERATION::PROD)) continue; + if (otherInput(prog[mul_idx], prog[div_idx]->outputs[0]).idx != X.idx) continue; + + int scale_idx = -1; + if (!step(prog[mul_idx]->outputs[0], scale_idx)) continue; + if (!nary(prog[scale_idx], NaryEltwiseLayer::OPERATION::PROD)) continue; + Arg scale = otherInput(prog[scale_idx], prog[mul_idx]->outputs[0]); + if (scale.empty() || !netimpl->isConstArg(scale)) continue; + // RMSNormalization needs a rank-1 scale; Mul would have broadcast anything. + const MatShape sshape = netimpl->argTensor(scale).shape(); + if (sshape.dims != 1 || sshape[0] < 2) continue; + + LayerParams lp; + lp.name = prog[scale_idx]->name; // keep the name for profiling continuity + lp.type = "RMSNormalization"; + lp.set("axis", -1); + lp.set("epsilon", epsilon); + + Ptr rmsnorm = LayerFactory::createLayerInstance("RMSNormalization", lp); + if (!rmsnorm) continue; + rmsnorm->inputs = { X, scale }; + rmsnorm->outputs = prog[scale_idx]->outputs; + rmsnorm->netimpl = netimpl; + + newprog[i] = rmsnorm; + for (int op : { rm_idx, add_idx, sqrt_idx, div_idx, mul_idx, scale_idx }) + dropped[op] = true; + modified = true; + } + + if (modified) { + vector> fused; + fused.reserve(nops); + for (size_t i = 0; i < nops; i++) { + if (!dropped[i] && newprog[i]) + fused.push_back(newprog[i]); + } + graph->setProg(fused); + } + return modified; + } + + Net::Impl* netimpl; +}; + +void Net::Impl::fuseRMSNorm() +{ + // RMSNormalization has no CUDA exec, and one such op sends the whole graph to the CPU. + if (preferableBackend != DNN_BACKEND_OPENCV || preferableTarget != DNN_TARGET_CPU) + return; + ModelFusionRMSNorm pass(this); + pass.fuse(); +} + +CV__DNN_INLINE_NS_END +}} diff --git a/modules/dnn/src/graph_fusion_scale_softmax.cpp b/modules/dnn/src/graph_fusion_scale_softmax.cpp deleted file mode 100644 index 37ad9c43b1..0000000000 --- a/modules/dnn/src/graph_fusion_scale_softmax.cpp +++ /dev/null @@ -1,151 +0,0 @@ -// 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. - -// Folds a scalar Mul / Div immediately preceding Softmax into the Softmax -// layer's `scale` parameter. The fused softmax bakes the scale into the -// per-element load before max/exp/sum/divide, removing one full pass over -// the (often large) [B, H, S, S] attention-logits tensor. -// -// Pattern: -// X -> Mul(X, c) -> Softmax => X -> Softmax(scale=c) -// X -> Div(X, c) -> Softmax => X -> Softmax(scale=1/c) - -#include "precomp.hpp" -#include "net_impl.hpp" - -namespace cv { namespace dnn { -CV__DNN_INLINE_NS_BEGIN - -using std::vector; -using std::string; - -struct ModelFusionScaleSoftmax -{ - explicit ModelFusionScaleSoftmax(Net::Impl* netimpl_) : netimpl(netimpl_) {} - - bool extractScalar(Arg a, float& out) const - { - if (!netimpl->isConstArg(a)) return false; - Mat t = netimpl->argTensor(a); - if (t.total() != 1) return false; - if (t.type() == CV_32F) { out = t.ptr()[0]; return true; } - if (t.type() == CV_64F) { out = (float)t.ptr()[0]; return true; } - return false; - } - - void fuse() { fuseGraph(netimpl->mainGraph); } - - bool fuseGraph(Ptr& graph) - { - const vector>& prog = graph->prog(); - size_t nops = prog.size(); - bool modified = false; - - for (size_t i = 0; i < nops; i++) { - if (!prog[i]) continue; - vector>* subgraphs = prog[i]->subgraphs(); - if (subgraphs) { - for (Ptr& g : *subgraphs) - if (fuseGraph(g)) modified = true; - } - } - - // Graph outputs count as uses, so a producer that is one never reaches zero. - vector usecounts; - netimpl->useCounts(usecounts); - - std::map producer; - for (size_t i = 0; i < nops; i++) { - if (!prog[i]) continue; - for (Arg out : prog[i]->outputs) - producer[out.idx] = (int)i; - } - - vector dropped(nops, false); - - for (size_t i = 0; i < nops; i++) { - const Ptr& layer = prog[i]; - if (!layer || dropped[i]) continue; - - SoftmaxLayer* sm = dynamic_cast(layer.get()); - if (!sm || sm->logSoftMax) continue; - if (layer->inputs.size() != 1) continue; - - Arg sm_in = layer->inputs[0]; - auto it = producer.find(sm_in.idx); - if (it == producer.end()) continue; - int prod_idx = it->second; - if (prod_idx < 0 || dropped[prod_idx]) continue; - - const Ptr& pl = prog[prod_idx]; - NaryEltwiseLayer* elt = dynamic_cast(pl.get()); - if (!elt) continue; - const auto op = elt->op; - const bool is_mul = (op == NaryEltwiseLayer::OPERATION::PROD); - const bool is_div = (op == NaryEltwiseLayer::OPERATION::DIV); - if (!is_mul && !is_div) continue; - if (pl->inputs.size() != 2 || pl->outputs.size() != 1) continue; - - // Identify which operand is the scalar constant. - float scalar = 0.f; - int x_slot = -1; - if (extractScalar(pl->inputs[1], scalar)) { - x_slot = 0; - } else if (is_mul && extractScalar(pl->inputs[0], scalar)) { - // Mul is commutative; Div with the data on the right doesn't - // simplify (1 / scale*x ≠ softmax-fold) so only handle Mul here. - x_slot = 1; - } else { - continue; - } - - if (is_div) { - if (scalar == 0.f) continue; - scalar = 1.f / scalar; - } - if (!std::isfinite(scalar)) continue; - - sm->scale *= scalar; - // A shared Mul/Div stays until its last consumer has folded it. - Arg src = pl->inputs[x_slot]; - layer->inputs[0] = src; - usecounts[src.idx]++; - if (--usecounts[sm_in.idx] == 0) { - dropped[prod_idx] = true; - for (Arg a : pl->inputs) - if (a.idx > 0) - usecounts[a.idx]--; - } - modified = true; - } - - if (modified) { - vector> newprog; - newprog.reserve(nops); - for (size_t i = 0; i < nops; i++) { - if (!dropped[i] && prog[i]) - newprog.push_back(prog[i]); - } - graph->setProg(newprog); - } - - return modified; - } - - Net::Impl* netimpl; -}; - -void Net::Impl::fuseScaleSoftmax() -{ - if (preferableBackend != DNN_BACKEND_OPENCV || - preferableTarget != DNN_TARGET_CPU) - return; - ModelFusionScaleSoftmax pass(this); - pass.fuse(); -} - -CV__DNN_INLINE_NS_END -}} diff --git a/modules/dnn/src/init.cpp b/modules/dnn/src/init.cpp index 918dac5ade..c526ca85fe 100644 --- a/modules/dnn/src/init.cpp +++ b/modules/dnn/src/init.cpp @@ -230,6 +230,7 @@ void initializeLayerFactory() CV_DNN_REGISTER_LAYER_CLASS(Reciprocal, ReciprocalLayer); CV_DNN_REGISTER_LAYER_CLASS(Gather, GatherLayer); CV_DNN_REGISTER_LAYER_CLASS(Gather2, Gather2Layer); + CV_DNN_REGISTER_LAYER_CLASS(GatherBlockQuantized, GatherBlockQuantizedLayer); CV_DNN_REGISTER_LAYER_CLASS(GatherElements, GatherElementsLayer); CV_DNN_REGISTER_LAYER_CLASS(LayerNormalization, LayerNormLayer); CV_DNN_REGISTER_LAYER_CLASS(RMSNormalization, RMSNormLayer); diff --git a/modules/dnn/src/layers/cpu_kernels/matmulnbits_kernels.cpp b/modules/dnn/src/layers/cpu_kernels/matmulnbits_kernels.cpp new file mode 100644 index 0000000000..f612bd9a23 --- /dev/null +++ b/modules/dnn/src/layers/cpu_kernels/matmulnbits_kernels.cpp @@ -0,0 +1,40 @@ +// 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 "matmulnbits_kernels.hpp" +#include "matmulnbits_kernels.simd.hpp" +#include "layers/cpu_kernels/matmulnbits_kernels.simd_declarations.hpp" + +namespace cv { namespace dnn { + +void matMulNBitsStripe(const float* a, const uchar* bq, const float* sc, const uchar* zp, + float* y, int M, int N, int K, int block_size, int bits, + int n_start, int n_end, float* wcol) +{ + CV_CPU_DISPATCH(matMulNBitsStripe_, (a, bq, sc, zp, y, M, N, K, block_size, bits, + n_start, n_end, wcol), CV_CPU_DISPATCH_MODES_ALL); +} + +int matMulNBitsGemvMinBlobBytes() +{ + CV_CPU_DISPATCH(matMulNBitsGemvMinBlobBytes_, (), CV_CPU_DISPATCH_MODES_ALL); +} + +void matMulNBitsSplitA(const float* a, float* a_even, float* a_odd, int pairs) +{ + CV_CPU_DISPATCH(matMulNBitsSplitA_, (a, a_even, a_odd, pairs), CV_CPU_DISPATCH_MODES_ALL); +} + +void matMulNBitsGemv(const float* a_even, const float* a_odd, const uchar* bq, + const float* sc, const uchar* zp, float* y, int K, int block_size, + int n_start, int n_end) +{ + CV_CPU_DISPATCH(matMulNBitsGemv_, (a_even, a_odd, bq, sc, zp, y, K, block_size, + n_start, n_end), CV_CPU_DISPATCH_MODES_ALL); +} + +}} // cv::dnn diff --git a/modules/dnn/src/layers/cpu_kernels/matmulnbits_kernels.hpp b/modules/dnn/src/layers/cpu_kernels/matmulnbits_kernels.hpp new file mode 100644 index 0000000000..a2b930e821 --- /dev/null +++ b/modules/dnn/src/layers/cpu_kernels/matmulnbits_kernels.hpp @@ -0,0 +1,32 @@ +// 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_MATMULNBITS_KERNELS_HPP +#define OPENCV_DNN_MATMULNBITS_KERNELS_HPP + +namespace cv { namespace dnn { + +// Output columns [n_start, n_end) of Y = A @ dequant(B).T. +// wcol is caller-owned scratch of ceil(K/block_size)*block_size floats. +// zp is null for the symmetric form, where the zero point is 2^(bits-1). +void matMulNBitsStripe(const float* a, const uchar* bq, const float* sc, const uchar* zp, + float* y, int M, int N, int K, int block_size, int bits, + int n_start, int n_end, float* wcol); + +// Below this per-block byte count the staged kernel is faster than the fused one. +int matMulNBitsGemvMinBlobBytes(); + +// Byte j holds weights 2j and 2j+1, so a_even[j] / a_odd[j] are what it multiplies. +void matMulNBitsSplitA(const float* a, float* a_even, float* a_odd, int pairs); + +// Fused 4-bit M=1 GEMV: dequant stays in registers, no column is materialized. +void matMulNBitsGemv(const float* a_even, const float* a_odd, const uchar* bq, + const float* sc, const uchar* zp, float* y, int K, int block_size, + int n_start, int n_end); + +}} // cv::dnn + +#endif // OPENCV_DNN_MATMULNBITS_KERNELS_HPP diff --git a/modules/dnn/src/layers/cpu_kernels/matmulnbits_kernels.simd.hpp b/modules/dnn/src/layers/cpu_kernels/matmulnbits_kernels.simd.hpp new file mode 100644 index 0000000000..67c750bf7a --- /dev/null +++ b/modules/dnn/src/layers/cpu_kernels/matmulnbits_kernels.simd.hpp @@ -0,0 +1,200 @@ +// 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 + +// Output columns [n_start, n_end) of Y = A @ dequant(B).T. +// wcol is caller-owned scratch of ceil(K/block_size)*block_size floats. +void matMulNBitsStripe_(const float* a, const uchar* bq, const float* sc, const uchar* zp, + float* y, int M, int N, int K, int block_size, int bits, + int n_start, int n_end, float* wcol); + +// Below this per-block byte count the staged kernel is faster than the fused one. +int matMulNBitsGemvMinBlobBytes_(); + +// Deinterleave A into the even/odd halves the fused path indexes by byte. +void matMulNBitsSplitA_(const float* a, float* a_even, float* a_odd, int pairs); + +// Fused 4-bit M=1 GEMV: dequant stays in registers, no column is materialized. +void matMulNBitsGemv_(const float* a_even, const float* a_odd, const uchar* bq, + const float* sc, const uchar* zp, float* y, int K, int block_size, + int n_start, int n_end); + +CV_CPU_OPTIMIZATION_NAMESPACE_END +}} + +#ifndef CV_CPU_OPTIMIZATION_DECLARATIONS_ONLY + +namespace cv { +namespace dnn { +CV_CPU_OPTIMIZATION_NAMESPACE_BEGIN + +// Dequantize one block into w[0..block_size-1]. BITS is compile-time so the per-byte +// unpack unrolls and the shift folds to a constant (the hot half of the kernel). +template +static inline void dequantBlock(const uchar* packed, int blob_bytes, float scale, int zp, + float* w) { + const int EPB = 8 / BITS; // elements per byte: 4-bit:2 8-bit:1 + const int QMASK = (1 << BITS) - 1; + for (int j = 0; j < blob_bytes; j++) { + const uchar byte = packed[j]; + for (int e = 0; e < EPB; e++) // LSB-first within the byte + w[j * EPB + e] = (((byte >> (e * BITS)) & QMASK) - zp) * scale; + } +} + +// Zero points are packed per column exactly like the weights, 8/BITS to a byte. +template +static inline int zeroPoint(const uchar* zp_n, int blk) { + const int EPB = 8 / BITS; + if (!zp_n) + return 1 << (BITS - 1); + return (zp_n[blk / EPB] >> ((blk % EPB) * BITS)) & ((1 << BITS) - 1); +} + +template +static void runStripe(const float* a, const uchar* bq, const float* sc, const uchar* zp, + float* y, int M, int N, int K, int block_size, + int n_start, int n_end, float* wcol) { + const int n_blk = (K + block_size - 1) / block_size; + const int blob_bytes = block_size * BITS / 8; // packed weights per block + const int zp_stride = (n_blk + 8 / BITS - 1) / (8 / BITS); + + for (int n = n_start; n < n_end; n++) { + const uchar* bq_n = bq + static_cast(n) * n_blk * blob_bytes; + const float* sc_n = sc + static_cast(n) * n_blk; + const uchar* zp_n = zp ? zp + static_cast(n) * zp_stride : nullptr; + // Dequant the whole column once so it amortizes across the M rows. + for (int blk = 0; blk < n_blk; blk++) + dequantBlock(bq_n + static_cast(blk) * blob_bytes, blob_bytes, + sc_n[blk], zeroPoint(zp_n, blk), wcol + blk * block_size); + + const float* w = wcol; + for (int m = 0; m < M; m++) { + const float* arow = a + static_cast(m) * K; + float acc = 0.f; + int t = 0; +#if (CV_SIMD || CV_SIMD_SCALABLE) + const int vlanes = VTraits::vlanes(); + v_float32 vacc0 = vx_setzero_f32(), vacc1 = vx_setzero_f32(); + v_float32 vacc2 = vx_setzero_f32(), vacc3 = vx_setzero_f32(); + for (; t <= K - 4 * vlanes; t += 4 * vlanes) { + vacc0 = v_fma(vx_load(arow + t), vx_load(w + t), vacc0); + vacc1 = v_fma(vx_load(arow + t + vlanes), vx_load(w + t + vlanes), vacc1); + vacc2 = v_fma(vx_load(arow + t + 2 * vlanes), vx_load(w + t + 2 * vlanes), vacc2); + vacc3 = v_fma(vx_load(arow + t + 3 * vlanes), vx_load(w + t + 3 * vlanes), vacc3); + } + v_float32 vacc = v_add(v_add(vacc0, vacc1), v_add(vacc2, vacc3)); + for (; t <= K - vlanes; t += vlanes) + vacc = v_fma(vx_load(arow + t), vx_load(w + t), vacc); + acc = v_reduce_sum(vacc); +#endif + for (; t < K; t++) + acc += arow[t] * w[t]; + y[static_cast(m) * N + n] = acc; + } + } +} + +void matMulNBitsStripe_(const float* a, const uchar* bq, const float* sc, const uchar* zp, + float* y, int M, int N, int K, int block_size, int bits, + int n_start, int n_end, float* wcol) { + switch (bits) { // bits in {4,8} enforced in the layer constructor + case 4: runStripe<4>(a, bq, sc, zp, y, M, N, K, block_size, n_start, n_end, wcol); break; + default: runStripe<8>(a, bq, sc, zp, y, M, N, K, block_size, n_start, n_end, wcol); break; + } +} + +int matMulNBitsGemvMinBlobBytes_() { +#if (CV_SIMD || CV_SIMD_SCALABLE) + return VTraits::vlanes(); +#else + return INT_MAX; // no vector path: the caller keeps the staged kernel +#endif +} + +void matMulNBitsSplitA_(const float* a, float* a_even, float* a_odd, int pairs) { + int i = 0; +#if (CV_SIMD || CV_SIMD_SCALABLE) + const int vlanes = VTraits::vlanes(); + for (; i <= pairs - vlanes; i += vlanes) { + v_float32 e, o; + v_load_deinterleave(a + 2 * i, e, o); + vx_store(a_even + i, e); + vx_store(a_odd + i, o); + } +#endif + for (; i < pairs; i++) { + a_even[i] = a[2 * i]; + a_odd[i] = a[2 * i + 1]; + } +} + +void matMulNBitsGemv_(const float* a_even, const float* a_odd, const uchar* bq, + const float* sc, const uchar* zp, float* y, int K, int block_size, + int n_start, int n_end) { + const int blob_bytes = block_size / 2; // 4-bit: two weights per byte + const int n_blk = (K + block_size - 1) / block_size; + const int pairs = K / 2; // bytes holding a live weight pair + const int zp_stride = (n_blk + 1) / 2; +#if (CV_SIMD || CV_SIMD_SCALABLE) + const int vlanes = VTraits::vlanes(); + const v_uint32 nibble = vx_setall_u32(0xF); +#endif + + for (int n = n_start; n < n_end; n++) { + const uchar* bq_n = bq + static_cast(n) * n_blk * blob_bytes; + const float* sc_n = sc + static_cast(n) * n_blk; + const uchar* zp_n = zp ? zp + static_cast(n) * zp_stride : nullptr; + float acc = 0.f; +#if (CV_SIMD || CV_SIMD_SCALABLE) + v_float32 vacc_e = vx_setzero_f32(), vacc_o = vx_setzero_f32(); +#endif + for (int blk = 0; blk < n_blk; blk++) { + const int b0 = blk * blob_bytes; + // Clamped, not blob_bytes: a partial last block owns fewer bytes than it spans. + const int b1 = std::min(b0 + blob_bytes, pairs); + if (b0 >= b1) + break; + const float scale = sc_n[blk]; + const int zpv = zeroPoint<4>(zp_n, blk); + int j = b0; +#if (CV_SIMD || CV_SIMD_SCALABLE) + const v_float32 vs = vx_setall_f32(scale); + const v_int32 zp_v = vx_setall_s32(zpv); + for (; j <= b1 - vlanes; j += vlanes) { + // One packed byte per 32-bit lane, so the nibble masks and the shift + // stay at a width where v_shr exists and v_sub does not saturate. + v_uint32 q = vx_load_expand_q(bq_n + j); + v_int32 qe = v_reinterpret_as_s32(v_and(q, nibble)); + v_int32 qo = v_reinterpret_as_s32(v_and(v_shr<4>(q), nibble)); + v_float32 we = v_mul(v_cvt_f32(v_sub(qe, zp_v)), vs); + v_float32 wo = v_mul(v_cvt_f32(v_sub(qo, zp_v)), vs); + vacc_e = v_fma(we, vx_load(a_even + j), vacc_e); + vacc_o = v_fma(wo, vx_load(a_odd + j), vacc_o); + } +#endif + for (; j < b1; j++) { + const uchar byte = bq_n[j]; + acc += (static_cast(byte & 0xF) - zpv) * scale * a_even[j]; + acc += (static_cast(byte >> 4) - zpv) * scale * a_odd[j]; + } + } +#if (CV_SIMD || CV_SIMD_SCALABLE) + acc += v_reduce_sum(v_add(vacc_e, vacc_o)); +#endif + y[n] = acc; + } +} + +CV_CPU_OPTIMIZATION_NAMESPACE_END +}} // cv::dnn:: + +#endif // CV_CPU_OPTIMIZATION_DECLARATIONS_ONLY diff --git a/modules/dnn/src/layers/gather_block_quantized_layer.cpp b/modules/dnn/src/layers/gather_block_quantized_layer.cpp new file mode 100644 index 0000000000..d23dbdbd74 --- /dev/null +++ b/modules/dnn/src/layers/gather_block_quantized_layer.cpp @@ -0,0 +1,236 @@ +// 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 "layers_common.hpp" + +// com.microsoft GatherBlockQuantized (contrib op, since com.microsoft opset 1): +// https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#commicrosoftgatherblockquantized +// Gathers rows of a block-quantized table and dequantises them in one step: +// out = (value - zero_point) * scale, where value is a {2,4,8}-bit field of the uint8 data. + +namespace cv { namespace dnn { + +class GatherBlockQuantizedLayerImpl CV_FINAL : public GatherBlockQuantizedLayer +{ +public: + GatherBlockQuantizedLayerImpl(const LayerParams& params) + { + setParamsFrom(params); + gather_axis = params.get("gather_axis", 0); + quantize_axis = params.get("quantize_axis", 1); + block_size = params.get("block_size", 128); + bits = params.get("bits", 4); + + CV_Check(bits, bits == 2 || bits == 4 || bits == 8, + "DNN/GatherBlockQuantized: bits must be 2, 4 or 8"); + CV_Check(block_size, block_size >= 16 && (block_size & (block_size - 1)) == 0, + "DNN/GatherBlockQuantized: block_size must be a power of two and at least 16"); + } + + virtual bool supportBackend(int backendId) CV_OVERRIDE + { + return backendId == DNN_BACKEND_OPENCV; + } + + // Resolved axes and the block counts derived from them, in unpacked elements. + struct BlockInfo + { + int gather_axis, quantize_axis, components; + int64_t gather_M, gather_N, gather_axis_dim, gather_block; + int64_t quantize_axis_dim, quantize_N, n_blk; + }; + + BlockInfo resolve(const MatShape& data, const MatShape& indices) const + { + BlockInfo info; + info.components = 8 / bits; + info.gather_axis = normalize_axis(gather_axis, data.dims); + info.quantize_axis = normalize_axis(quantize_axis, data.dims); + CV_Check(info.gather_axis, info.gather_axis == 0, + "DNN/GatherBlockQuantized: uint8 data requires gather_axis 0"); + CV_Check(info.quantize_axis, info.quantize_axis == data.dims - 1, + "DNN/GatherBlockQuantized: uint8 data requires quantize_axis to be the last one"); + + info.gather_axis_dim = data[info.gather_axis]; + info.gather_M = 1; + for (int i = 0; i < info.gather_axis; i++) + info.gather_M *= data[i]; + info.gather_block = info.components; + for (int i = info.gather_axis + 1; i < data.dims; i++) + info.gather_block *= data[i]; + info.gather_N = (int64_t)indices.total(); + info.quantize_axis_dim = (int64_t)data[info.quantize_axis] * info.components; + info.quantize_N = 1; + for (int i = info.quantize_axis + 1; i < data.dims; i++) + info.quantize_N *= data[i]; + info.n_blk = (info.quantize_axis_dim + block_size - 1) / block_size; + return info; + } + + // The gathered axis becomes the indices' shape, and the packed last axis unpacks. + MatShape getOutShape(const MatShape& data, const MatShape& indices) const + { + const int axis_ = normalize_axis(gather_axis, data.dims); + MatShape out(data.dims - 1 + indices.dims); + int k = 0; + for (int i = 0; i < axis_; i++) + out[k++] = data[i]; + for (int i = 0; i < indices.dims; i++) + out[k++] = indices[i]; + for (int i = axis_ + 1; i < data.dims; i++) + out[k++] = data[i]; + CV_Assert(k == out.dims && out.dims > 0); + out[out.dims - 1] *= 8 / bits; + return out; + } + + void checkQuantParams(const MatShape& data, const MatShape& scales, + const MatShape& zp, const BlockInfo& info) const + { + CV_CheckEQ(scales.dims, data.dims, "DNN/GatherBlockQuantized: data and scales rank differ"); + for (int i = 0; i < data.dims; i++) { + const int want = i == info.quantize_axis ? (int)info.n_blk : data[i]; + CV_CheckEQ(scales[i], want, "DNN/GatherBlockQuantized: scales shape mismatch"); + } + // Optional, and its shape is not always known here; forward reads the tensor itself. + if (zp.dims <= 0) + return; + CV_CheckEQ(zp.dims, scales.dims, + "DNN/GatherBlockQuantized: scales and zero_points rank differ"); + for (int i = 0; i < scales.dims; i++) { + const int64_t packed = (info.n_blk + info.components - 1) / info.components; + const int want = i == info.quantize_axis ? (int)packed : scales[i]; + CV_CheckEQ(zp[i], want, "DNN/GatherBlockQuantized: zero_points shape mismatch"); + } + } + + bool getMemoryShapes(const std::vector &inputs, + const int, + std::vector &outputs, + std::vector &internals) const CV_OVERRIDE + { + CV_Check((int)inputs.size(), inputs.size() == 3 || inputs.size() == 4, + "DNN/GatherBlockQuantized: expected (data, indices, scales[, zero_points])"); + CV_CheckGE(inputs[0].dims, 2, "DNN/GatherBlockQuantized: data must have rank 2 or more"); + + const BlockInfo info = resolve(inputs[0], inputs[1]); + checkQuantParams(inputs[0], inputs[2], inputs.size() == 4 ? inputs[3] : MatShape(), info); + outputs.assign(1, getOutShape(inputs[0], inputs[1])); + internals.clear(); + return false; + } + + void getTypes(const std::vector& inputs, + const int requiredOutputs, + const int requiredInternals, + std::vector& outputs, + std::vector& internals) const CV_OVERRIDE + { + CV_Check((int)inputs.size(), inputs.size() == 3 || inputs.size() == 4, + "DNN/GatherBlockQuantized: expected (data, indices, scales[, zero_points])"); + CV_CheckType(inputs[0], inputs[0] == CV_8U, + "DNN/GatherBlockQuantized: data must be CV_8U"); + CV_CheckType(inputs[1], inputs[1] == CV_32S || inputs[1] == CV_64S, + "DNN/GatherBlockQuantized: indices must be CV_32S or CV_64S"); + CV_CheckType(inputs[2], inputs[2] == CV_32F, + "DNN/GatherBlockQuantized: scales must be CV_32F"); + if (inputs.size() == 4 && inputs[3] != CV_8U && inputs[3] != -1) + CV_Error(Error::StsNotImplemented, + "DNN/GatherBlockQuantized: zero_points must be CV_8U"); + outputs.assign(requiredOutputs, inputs[2]); + CV_Assert(requiredInternals == 0); + internals.clear(); + } + + void forward(InputArrayOfArrays inputs_arr, + OutputArrayOfArrays outputs_arr, + OutputArrayOfArrays) CV_OVERRIDE + { + CV_TRACE_FUNCTION(); + CV_TRACE_ARG_VALUE(name, "name", name.c_str()); + + std::vector inputs, outputs; + inputs_arr.getMatVector(inputs); + outputs_arr.getMatVector(outputs); + + const Mat& data = inputs[0]; + const Mat& indices = inputs[1]; + const Mat& scales = inputs[2]; + const Mat zeroPoints = inputs.size() == 4 ? inputs[3] : Mat(); + Mat& out = outputs[0]; + CV_Assert(data.isContinuous() && indices.isContinuous() && scales.isContinuous()); + CV_Assert(out.isContinuous() && (zeroPoints.empty() || zeroPoints.isContinuous())); + + const BlockInfo info = resolve(data.shape(), indices.shape()); + + // Resolved once here, so the parallel loop reads a plain row; -1 means zero-fill. + std::vector rows((size_t)info.gather_N); + const int indType = indices.type(); + for (int64_t j = 0; j < info.gather_N; j++) { + int64_t v = indType == CV_32S ? (int64_t)indices.ptr()[j] + : indices.ptr()[j]; + v += v < 0 ? info.gather_axis_dim : 0; + // Unlike ONNX Gather, an out-of-range index zeroes its slice instead of failing. + rows[(size_t)j] = (v < 0 || v >= info.gather_axis_dim) ? -1 : v; + } + + const uchar* dataPtr = data.ptr(); + const float* scalePtr = scales.ptr(); + const uchar* zpPtr = zeroPoints.empty() ? nullptr : zeroPoints.ptr(); + float* outPtr = out.ptr(); + + const int64_t total = info.gather_M * info.gather_N; + parallel_for_(Range(0, (int)total), [&](const Range& r) { + for (int i = r.start; i < r.end; i++) + gatherOne(dataPtr, scalePtr, zpPtr, outPtr, rows, info, i); + }, std::min((double)total, (double)total * info.gather_block / 1e5)); + } + + // One gathered row: blocks outer so the scale and zero point are read once each. + void gatherOne(const uchar* data, const float* scales, const uchar* zp, float* out, + const std::vector& rows, const BlockInfo& info, int idx) const + { + const int64_t m = idx / info.gather_N, n = idx % info.gather_N; + const int64_t outBase = (int64_t)idx * info.gather_block; + if (rows[(size_t)n] < 0) { + std::memset(out + outBase, 0, (size_t)info.gather_block * sizeof(float)); + return; + } + const int64_t dataBase = m * info.gather_axis_dim * info.gather_block + + rows[(size_t)n] * info.gather_block; + const int64_t zpStride = (info.n_blk + info.components - 1) / info.components; + const int mask = (1 << bits) - 1; + const int defaultZp = 1 << (bits - 1); + + for (int64_t sub = 0; sub < info.gather_block; sub += info.quantize_axis_dim) { + const int64_t x = (dataBase + sub) / info.quantize_axis_dim; + for (int64_t b = 0; b < info.n_blk; b++) { + const float scale = scales[x * info.n_blk + b]; + int zpVal = defaultZp; + if (zp) { + const uchar packed = zp[x * zpStride + b / info.components]; + zpVal = (packed >> ((b % info.components) * bits)) & mask; + } + const int64_t lo = b * block_size; + const int64_t hi = std::min(lo + block_size, info.quantize_axis_dim); + for (int64_t y = lo; y < hi; y++) { + const int64_t di = dataBase + sub + y; + const uchar byte = data[di / info.components]; + const int v = (byte >> ((di % info.components) * bits)) & mask; + out[outBase + sub + y] = (float)(v - zpVal) * scale; + } + } + } + } +}; + +Ptr GatherBlockQuantizedLayer::create(const LayerParams& params) +{ + return makePtr(params); +} + +}} // namespace cv::dnn diff --git a/modules/dnn/src/layers/gemm_layer.cpp b/modules/dnn/src/layers/gemm_layer.cpp index 7461b4dc48..93047d8097 100644 --- a/modules/dnn/src/layers/gemm_layer.cpp +++ b/modules/dnn/src/layers/gemm_layer.cpp @@ -59,13 +59,24 @@ class GemmLayerImpl CV_FINAL : public GemmLayer { public: mutable int inpType = -1; + // A and B scale the product; C is the bias and would need beta, so it is refused. + static bool foldScaleOp(Layer* self, int slot, float scale) + { + if (slot != 0 && slot != 1) + return false; + static_cast(self)->alpha *= scale; + return true; + } + static bool absorbOp(Layer* self, const Ptr& expr) { return static_cast(self)->fusion.take(expr); } GemmLayerImpl(const LayerParams& params) { - registerFusionOpsOnce({ nullptr, &GemmLayerImpl::absorbOp }); + registerFusionOpsOnce({ nullptr, &GemmLayerImpl::absorbOp, false, + nullptr, nullptr, + &GemmLayerImpl::foldScaleOp }); setParamsFrom(params); trans_a = params.get("transA", false); diff --git a/modules/dnn/src/layers/matmul_layer.cpp b/modules/dnn/src/layers/matmul_layer.cpp index ffb1c68341..8fd5329c61 100644 --- a/modules/dnn/src/layers/matmul_layer.cpp +++ b/modules/dnn/src/layers/matmul_layer.cpp @@ -37,13 +37,24 @@ class MatMulLayerImpl CV_FINAL : public MatMulLayer { PreparedFusion fusion; public: + // Scaling either operand scales the product, so both slots fold into alpha. + static bool foldScaleOp(Layer* self, int slot, float scale) + { + if (slot != 0 && slot != 1) + return false; + static_cast(self)->alpha *= scale; + return true; + } + static bool absorbOp(Layer* self, const Ptr& expr) { return static_cast(self)->fusion.take(expr); } MatMulLayerImpl(const LayerParams& params) { - registerFusionOpsOnce({ nullptr, &MatMulLayerImpl::absorbOp }); + registerFusionOpsOnce({ nullptr, &MatMulLayerImpl::absorbOp, false, + nullptr, nullptr, + &MatMulLayerImpl::foldScaleOp }); setParamsFrom(params); trans_a = params.get("transA", false); diff --git a/modules/dnn/src/layers/matmulnbits_layer.cpp b/modules/dnn/src/layers/matmulnbits_layer.cpp index aef6747b79..1e6f9bf56a 100644 --- a/modules/dnn/src/layers/matmulnbits_layer.cpp +++ b/modules/dnn/src/layers/matmulnbits_layer.cpp @@ -7,12 +7,13 @@ #include "../precomp.hpp" #include -#include +#include "cpu_kernels/matmulnbits_kernels.hpp" // com.microsoft MatMulNBits (contrib op, since com.microsoft opset 1): // https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#commicrosoftmatmulnbits -// Y = A @ dequant(B).T. Weights are block-quantized to {4,8} bits (symmetric, default -// zero-point 2^(bits-1)) and dequantized per block inside the GEMM (no fp32 copy). +// Y = A @ dequant(B).T. Weights are block-quantized to {4,8} bits with a scale and an optional +// packed uint8 zero point per block (2^(bits-1) when absent), and dequantized per block inside +// the GEMM (no fp32 copy). namespace cv { namespace dnn { @@ -42,7 +43,7 @@ class MatMulNBitsLayerImpl CV_FINAL : public MatMulNBitsLayer { std::vector &internals) const CV_OVERRIDE { CV_CheckEQ(inputs.size(), static_cast(1), "DNN/MatMulNBits: expected a single activation input; weights and scales must be constants"); - CV_CheckEQ(blobs.size(), static_cast(2), + CV_Check((int)blobs.size(), blobs.size() == 2 || blobs.size() == 3, "DNN/MatMulNBits: expected packed weights and scales as constant blobs"); const int n_blk = (K + block_size - 1) / block_size; // ceil: K need not divide block_size; last block may be partial @@ -50,6 +51,13 @@ class MatMulNBitsLayerImpl CV_FINAL : public MatMulNBitsLayer { "DNN/MatMulNBits: packed weight size mismatch"); CV_CheckEQ(static_cast(blobs[1].total()), N * n_blk, "DNN/MatMulNBits: scales size mismatch"); + if (blobs.size() == 3) { + const int epb = 8 / bits; + CV_CheckEQ(static_cast(blobs[2].total()), N * ((n_blk + epb - 1) / epb), + "DNN/MatMulNBits: zero_points size mismatch"); + CV_CheckType(blobs[2].type(), blobs[2].type() == CV_8U, + "DNN/MatMulNBits: zero_points must be CV_8U"); + } CV_CheckType(blobs[0].type(), blobs[0].type() == CV_8U, "DNN/MatMulNBits: packed weights must be CV_8U; int32-packed weights are not supported"); CV_CheckType(blobs[1].type(), blobs[1].type() == CV_32F, @@ -62,7 +70,8 @@ class MatMulNBitsLayerImpl CV_FINAL : public MatMulNBitsLayer { MatShape out = shape_A; out.back() = N; outputs.assign(1, out); - internals.clear(); + // A as even and odd halves for the fused M=1 path; K floats hold both. + internals.assign(bits == 4 ? 1 : 0, MatShape({K})); return false; } @@ -74,7 +83,7 @@ class MatMulNBitsLayerImpl CV_FINAL : public MatMulNBitsLayer { CV_CheckEQ(inputs.size(), static_cast(1), "DNN/MatMulNBits: expected a single activation input"); CV_CheckType(inputs[0], inputs[0] == CV_32F, "DNN/MatMulNBits: activation must be CV_32F"); outputs.assign(requiredOutputs, CV_32F); - internals.assign(requiredInternals, MatType(-1)); + internals.assign(requiredInternals, CV_32F); } virtual int64 getFLOPS(const std::vector &inputs, @@ -84,89 +93,65 @@ class MatMulNBitsLayerImpl CV_FINAL : public MatMulNBitsLayer { return CV_BIG_INT(2) * M * N * K; } - // Dequantize one block into w[0..block_size-1]. BITS is compile-time so the per-byte - // unpack unrolls and the shift folds to a constant (the hot half of the kernel). - template - static inline void dequantBlock(const uchar* packed, int blob_bytes, float scale, float* w) { - const int EPB = 8 / BITS; // elements per byte: 4-bit:2 8-bit:1 - const int QMASK = (1 << BITS) - 1; - const int ZP = 1 << (BITS - 1); // symmetric default zero-point - for (int j = 0; j < blob_bytes; j++) { - const uchar byte = packed[j]; - for (int e = 0; e < EPB; e++) // LSB-first within the byte - w[j * EPB + e] = (((byte >> (e * BITS)) & QMASK) - ZP) * scale; - } - } - - template - void runImpl(const Mat& A, const Mat& B, const Mat& scales, Mat& Y) const { + void runImpl(const Mat& A, const Mat& B, const Mat& scales, const Mat& zeroPoints, + Mat& Y, Mat& split) const { const int M = static_cast(A.total() / K); const int n_blk = (K + block_size - 1) / block_size; - const int blob_bytes = block_size * BITS / 8; // packed weights per block const float* a = A.ptr(); const uchar* bq = B.ptr(); const float* sc = scales.ptr(); + const uchar* zp = zeroPoints.empty() ? nullptr : zeroPoints.ptr(); float* y = Y.ptr(); - // Each range owns a disjoint set of output columns n, so the column writes are race-free. - parallel_for_(Range(0, N), [&](const Range& r) { - // Dequant the whole column once so it amortizes across the M rows. - AutoBuffer wcol(n_blk * block_size); // whole blocks (>= K): the last block is dequantized in full - for (int n = r.start; n < r.end; n++) { - const uchar* bq_n = bq + static_cast(n) * n_blk * blob_bytes; - const float* sc_n = sc + static_cast(n) * n_blk; - for (int blk = 0; blk < n_blk; blk++) - dequantBlock(bq_n + static_cast(blk) * blob_bytes, blob_bytes, - sc_n[blk], wcol.data() + blk * block_size); + // Staging costs 4 bytes written and read back per 0.5 byte of weight and amortizes + // only over the M rows, so at M=1 it is pure overhead. Everything else stays staged. + const bool fused = M == 1 && bits == 4 && K % 2 == 0 && !split.empty() && + block_size / 2 >= matMulNBitsGemvMinBlobBytes(); - const float* w = wcol.data(); - for (int m = 0; m < M; m++) { - const float* arow = a + static_cast(m) * K; - float acc = 0.f; - int t = 0; -#if (CV_SIMD || CV_SIMD_SCALABLE) - const int vlanes = VTraits::vlanes(); - v_float32 vacc0 = vx_setzero_f32(), vacc1 = vx_setzero_f32(); - v_float32 vacc2 = vx_setzero_f32(), vacc3 = vx_setzero_f32(); - for (; t <= K - 4 * vlanes; t += 4 * vlanes) { - vacc0 = v_fma(vx_load(arow + t), vx_load(w + t), vacc0); - vacc1 = v_fma(vx_load(arow + t + vlanes), vx_load(w + t + vlanes), vacc1); - vacc2 = v_fma(vx_load(arow + t + 2 * vlanes), vx_load(w + t + 2 * vlanes), vacc2); - vacc3 = v_fma(vx_load(arow + t + 3 * vlanes), vx_load(w + t + 3 * vlanes), vacc3); - } - v_float32 vacc = v_add(v_add(vacc0, vacc1), v_add(vacc2, vacc3)); - for (; t <= K - vlanes; t += vlanes) - vacc = v_fma(vx_load(arow + t), vx_load(w + t), vacc); - acc = v_reduce_sum(vacc); -#endif - for (; t < K; t++) - acc += arow[t] * w[t]; - y[static_cast(m) * N + n] = acc; - } + const float* a_even = nullptr; + const float* a_odd = nullptr; + if (fused) { + float* buf = split.ptr(); + matMulNBitsSplitA(a, buf, buf + K / 2, K / 2); + a_even = buf; + a_odd = buf + K / 2; + } + + // Each range owns a disjoint set of output columns n, so the column writes are race-free. + // A stripe spans >= 16 columns: that is one 64-byte output line, and the per-stripe + // dequant buffer makes finer splitting cost more than it saves. + parallel_for_(Range(0, N), [&](const Range& r) { + if (fused) { + matMulNBitsGemv(a_even, a_odd, bq, sc, zp, y, K, block_size, r.start, r.end); + return; } - }, static_cast(N) * M * K * (1 / 1024.0)); + // whole blocks (>= K): the last block is dequantized in full + AutoBuffer wcol(n_blk * block_size); + matMulNBitsStripe(a, bq, sc, zp, y, M, N, K, block_size, bits, + r.start, r.end, wcol.data()); + }, std::min(N / 16.0, 8.0 * std::max(1, getNumThreads()))); } void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) CV_OVERRIDE { CV_TRACE_FUNCTION(); CV_TRACE_ARG_VALUE(name, "name", name.c_str()); - std::vector inputs, outputs; + std::vector inputs, outputs, internals; inputs_arr.getMatVector(inputs); outputs_arr.getMatVector(outputs); + internals_arr.getMatVector(internals); const Mat& A = inputs[0]; const Mat& B = blobs[0]; // packed weights, uint8 [N, n_blk, block_size*bits/8] const Mat& scales = blobs[1]; // fp32 [N, n_blk] + const Mat zeroPoints = blobs.size() == 3 ? blobs[2] : Mat(); // uint8, packed per column Mat& Y = outputs[0]; CV_Assert(A.isContinuous() && Y.isContinuous()); - switch (bits) { // bits ∈ {4,8} enforced in the constructor - case 4: runImpl<4>(A, B, scales, Y); break; - default: runImpl<8>(A, B, scales, Y); break; - } + Mat split = internals.empty() ? Mat() : internals[0]; + runImpl(A, B, scales, zeroPoints, Y, split); } }; diff --git a/modules/dnn/src/layers/reshape2_layer.cpp b/modules/dnn/src/layers/reshape2_layer.cpp index 82ff5aad5e..69c8c5abf7 100644 --- a/modules/dnn/src/layers/reshape2_layer.cpp +++ b/modules/dnn/src/layers/reshape2_layer.cpp @@ -42,9 +42,6 @@ class Reshape2LayerImpl CV_FINAL : public Reshape2Layer { public: bool dynamicShapeSpec; - // ONNX 'allowzero' (opsets 14 to 23): when set, a 0 in the shape means a zero-size axis - // instead of "copy this axis from the input" - bool allowZero; static bool sameDims(const MatShape& a, const MatShape& b) { @@ -106,6 +103,7 @@ public: { dynamicShapeSpec = true; setParamsFrom(params); + // ONNX 'allowzero', opsets 14 to 23 allowZero = params.get("allowzero", 0) != 0; if (params.has("shape")) { diff --git a/modules/dnn/src/layers/softmax_layer.cpp b/modules/dnn/src/layers/softmax_layer.cpp index b5e67da5e3..19ba03c3ac 100644 --- a/modules/dnn/src/layers/softmax_layer.cpp +++ b/modules/dnn/src/layers/softmax_layer.cpp @@ -41,6 +41,7 @@ //M*/ #include "../precomp.hpp" +#include "../adjacency_graph.hpp" #include "layers_common.hpp" #include "../op_cuda.hpp" #include "../op_inf_engine.hpp" @@ -74,10 +75,22 @@ class SoftMaxLayerImpl CV_FINAL : public SoftmaxLayer { public: + // The factor must reach the kernel; logSoftMax has no scaled one, so it declines. + static bool foldScaleOp(Layer* self, int slot, float scale) + { + SoftMaxLayerImpl* l = static_cast(self); + if (slot != 0 || l->logSoftMax) + return false; + l->scale *= scale; + return true; + } + SoftMaxLayerImpl(const LayerParams& params) { axisRaw = params.get("axis", -1); logSoftMax = params.get("log_softmax", false); + registerFusionOpsOnce({ nullptr, nullptr, false, nullptr, nullptr, + &SoftMaxLayerImpl::foldScaleOp }); scale = params.get("scale", 1.f); coerced2d = params.get("coerced_2d", false); setParamsFrom(params); diff --git a/modules/dnn/src/layers/split2_layer.cpp b/modules/dnn/src/layers/split2_layer.cpp index 31b6f3b0eb..5ce0034ff8 100644 --- a/modules/dnn/src/layers/split2_layer.cpp +++ b/modules/dnn/src/layers/split2_layer.cpp @@ -114,14 +114,31 @@ public: CV_Assert(0 <= axis_ && axis_ < inpDims); const bool blockC = isBlockChannelSplit(inpShape, axis_); const int C0 = blockC ? inpShape.back() : 1; + const int len = axisSize(inpShape, axis_); int totalSize_a = 0; + // One size may be -1 and takes the rest of the axis, as in Reshape. With a -1 the sizes + // also clamp like Slice ends: a part running past the end of the axis stops there. + int inferred = -1, known = 0; + for (size_t i = 0; i < noutputs; i++) { + if (split[i] == -1) { + CV_Assert(inferred < 0); + inferred = (int)i; + } else { + CV_Assert(split[i] >= 0); + known += split[i]; + } + } + CV_Assert(inferred >= 0 || known <= len); + outShapes.resize(noutputs); for (size_t i = 0; i < noutputs; i++) { MatShape outShape = inpShape; - int s = split[i]; + int s = (int)i == inferred ? std::max(len - known, 0) : split[i]; + if (inferred >= 0) + s = std::min(s, len - totalSize_a); CV_Assert(s >= 0); - CV_Assert(s <= axisSize(inpShape, axis_) - totalSize_a); + CV_Assert(s <= len - totalSize_a); if (blockC) { outShape[axis_] = (s + C0 - 1) / C0; outShape.C = s; diff --git a/modules/dnn/src/net_impl.hpp b/modules/dnn/src/net_impl.hpp index ef416ea80a..489851a993 100644 --- a/modules/dnn/src/net_impl.hpp +++ b/modules/dnn/src/net_impl.hpp @@ -134,6 +134,10 @@ struct Net::Impl : public detail::NetImplBase size_t totalLayers; std::vector dimnames_vec; std::vector args; + + // Dimensions the model declares, keyed by arg index; ArgData::shape is filled only at + // forward time. A symbolic dimension is its interned id, equal only to the same symbol. + std::map declaredShapes; std::vector __tensors__; std::vector bufidxs; std::vector buffers; @@ -568,6 +572,10 @@ struct Net::Impl : public detail::NetImplBase // fuseChains()'s chain pass limited to TransformLayout sinks; run // after useBlockLayout(), which is what creates those nodes void fuseTransformLayoutChains(); + // collapse decomposed RMS normalization into one RMSNormalization layer + void fuseRMSNorm(); + // replace Slices that together partition one axis with a single Split + void fuseSliceToSplit(); // fuse ViT-style multi-head attention subgraphs void fuseAttention(); // rewrite MatMul(A, const_B [, const_bias]) into Gemm so projection-style @@ -577,10 +585,10 @@ struct Net::Impl : public detail::NetImplBase void fuseSharedInputGemm(); // collapse redundant Reshape/Transpose chains void fuseReshapeTranspose(); + // fold a scalar Mul/Div on an input into the consuming layer's own parameters + void fuseInputScalars(); // absorb a last-two-dims Transpose into the consuming MatMul void fuseTransposeMatMul(); - // fold a scalar Mul/Div before Softmax into Softmax::scale (CPU only) - void fuseScaleSoftmax(); // replace constant sub-expressions with their results // widen FP16/BF16 constants to execution precision while the engine lacks half kernels diff --git a/modules/dnn/src/onnx/onnx_importer2.cpp b/modules/dnn/src/onnx/onnx_importer2.cpp index 65450b035f..148f2fa8b6 100644 --- a/modules/dnn/src/onnx/onnx_importer2.cpp +++ b/modules/dnn/src/onnx/onnx_importer2.cpp @@ -251,6 +251,7 @@ protected: void parseLSTM (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto); void parseMatMul (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto); void parseMatMulNBits (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto); + void parseGatherBlockQuantized (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto); void parseMaxPool (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto); void parseMaxUnpool (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto); void parseNeg (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto); @@ -1055,6 +1056,34 @@ Ptr ONNXImporter2::parseGraph(opencv_onnx::GraphProto* graph_proto, bool curr_graph->setProg(curr_prog); curr_prog = saved_prog; + // Shape inference fills ArgData::shape at forward time, after every fusion pass has run. + for (int src = 0; src < 3; src++) { + const int n = src == 0 ? graph_proto->value_info_size() + : src == 1 ? graph_proto->input_size() : graph_proto->output_size(); + for (int i = 0; i < n; i++) { + const opencv_onnx::ValueInfoProto& vi = src == 0 ? graph_proto->value_info(i) + : src == 1 ? graph_proto->input(i) + : graph_proto->output(i); + if (!vi.has_name() || !vi.has_type() || !vi.type().has_tensor_type()) + continue; + const opencv_onnx::TypeProto::Tensor& t = vi.type().tensor_type(); + if (!t.has_shape()) + continue; + const std::string name = remap(vi.name()); + if (!netimpl->haveArg(name)) + continue; + const opencv_onnx::TensorShapeProto& ts = t.shape(); + MatShape shape(ts.dim_size()); + for (int j = 0; j < ts.dim_size(); j++) { + const opencv_onnx::TensorShapeProto_Dimension& d = ts.dim(j); + // findDim interns by name, so two symbolic dims match only if same symbol. + const std::string dp = d.has_dim_param() ? d.dim_param() : std::string(); + shape[j] = d.has_dim_value() ? (int)d.dim_value() : netimpl->findDim(dp, true); + } + netimpl->declaredShapes[netimpl->getArg(name).idx] = shape; + } + } + Ptr just_constructed = curr_graph; curr_graph_proto = saved_graph_proto; curr_graph = saved_graph; @@ -1810,17 +1839,43 @@ void ONNXImporter2::parseMatMul(LayerParams& layerParams, const opencv_onnx::Nod void ONNXImporter2::parseMatMulNBits(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto) { int n_inputs = node_proto.input_size(); - CV_CheckEQ(n_inputs, 3, "DNN/MatMulNBits: only the symmetric (A, B, scales) form is supported"); + CV_Check(n_inputs, 3 <= n_inputs && n_inputs <= 6, + "DNN/MatMulNBits: expected (A, B, scales[, zero_points, g_idx, bias])"); CV_CheckTrue(net.isConstArg(node_inputs[1]) && net.isConstArg(node_inputs[2]), "DNN/MatMulNBits: packed weights and scales must be constants"); + // g_idx would reorder K, which the blocked kernels cannot express. + CV_CheckFalse(n_inputs > 4 && !node_inputs[4].empty(), + "DNN/MatMulNBits: g_idx is not supported"); + CV_CheckFalse(n_inputs > 5 && !node_inputs[5].empty(), + "DNN/MatMulNBits: bias is not supported"); layerParams.blobs.push_back(net.argTensor(node_inputs[1])); Mat scales; net.argTensor(node_inputs[2]).convertTo(scales, CV_32F); layerParams.blobs.push_back(scales); + if (n_inputs >= 4 && !node_inputs[3].empty()) { + CV_CheckTrue(net.isConstArg(node_inputs[3]), + "DNN/MatMulNBits: zero_points must be a constant"); + layerParams.blobs.push_back(net.argTensor(node_inputs[3])); + } addLayer(layerParams, node_proto, 1); } +void ONNXImporter2::parseGatherBlockQuantized(LayerParams& layerParams, + const opencv_onnx::NodeProto& node_proto) +{ + const int n_inputs = node_proto.input_size(); + CV_Check(n_inputs, n_inputs == 3 || n_inputs == 4, + "GatherBlockQuantized: expected (data, indices, scales[, zero_points])"); + CV_CheckTrue(net.isConstArg(node_inputs[0]) && net.isConstArg(node_inputs[2]), + "GatherBlockQuantized: the quantized table and its scales must be constants"); + // int4/uint4 tables load one value per byte; the layer reads packed uint8 only. + CV_CheckEQ(findGraphTensorOnnxType(node_proto.input(0)), + (int)opencv_onnx::TensorProto_DataType_UINT8, + "GatherBlockQuantized: only uint8 data is supported"); + addLayer(layerParams, node_proto, n_inputs); +} + void ONNXImporter2::parseConv(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto) { int n_inputs = node_proto.input_size(); @@ -3427,7 +3482,7 @@ void ONNXImporter2::parseMultiHeadAttention(LayerParams& params, const opencv_on } // Operator spec: https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#com.microsoft.GroupQueryAttention -// Supported opsets: com.microsoft 1. Supported inputs: 0..8, query through sin_cache. +// Supported opsets: com.microsoft 1. Supported inputs: 0..8 and 10, attention_bias. // Lowers to AttentionOnnxAi, told here about seqlens_k, rotary, the window and a shared buffer. void ONNXImporter2::parseGroupQueryAttention(LayerParams& params, const opencv_onnx::NodeProto& node_proto) { CV_CheckTrue(params.has("num_heads") && params.has("kv_num_heads"), @@ -3446,9 +3501,12 @@ void ONNXImporter2::parseGroupQueryAttention(LayerParams& params, const opencv_o if (do_rotary) CV_CheckTrue(hasInput(node_proto, 7) && hasInput(node_proto, 8), "GroupQueryAttention: do_rotary=1 requires cos_cache and sin_cache"); - for (int i = 9; i < node_proto.input_size(); i++) // position_ids / attention_bias / head_sink + // attention_bias (10) is additive and becomes the layer's attn_mask. + const bool has_bias = hasInput(node_proto, 10); + CV_CheckFalse(hasInput(node_proto, 9), "GroupQueryAttention: position_ids is not supported"); + for (int i = 11; i < node_proto.input_size(); i++) // head_sink / kv scales / qk norm CV_CheckFalse(hasInput(node_proto, i), - "GroupQueryAttention: only inputs 0..8 (query .. sin_cache) are supported"); + "GroupQueryAttention: inputs after attention_bias are not supported"); // A preallocated buffer is rewritten in place, so present_key keeps past_key's length; // a growing cache declares a longer one. A static past alone does not separate them -- @@ -3468,6 +3526,7 @@ void ONNXImporter2::parseGroupQueryAttention(LayerParams& params, const opencv_o // total_sequence_length (6) is redundant with seqlens_k and dropped. std::vector ins{node_inputs[0], node_inputs[1], node_inputs[2]}; + if (has_bias) ins.push_back(node_inputs[10]); if (has_past_k) { ins.push_back(node_inputs[3]); ins.push_back(node_inputs[4]); } ins.push_back(node_inputs[5]); if (do_rotary) { ins.push_back(node_inputs[7]); ins.push_back(node_inputs[8]); } @@ -3477,7 +3536,7 @@ void ONNXImporter2::parseGroupQueryAttention(LayerParams& params, const opencv_o params.set("q_num_heads", params.get("num_heads")); params.set("kv_num_heads", params.get("kv_num_heads")); params.set("is_causal", true); - params.set("has_attn_mask", 0); + params.set("has_attn_mask", has_bias ? 1 : 0); params.set("has_past", has_past_k ? 1 : 0); params.set("has_seqlens_k", 1); params.set("has_rotary_cache", do_rotary ? 1 : 0); @@ -3840,6 +3899,7 @@ void ONNXImporter2::buildDispatchMap_COM_MICROSOFT() dispatch["SimplifiedLayerNormalization"] = &ONNXImporter2::parseSimplifiedLayerNormalization; dispatch["SkipSimplifiedLayerNormalization"] = &ONNXImporter2::parseSkipSimplifiedLayerNorm; dispatch["MatMulNBits"] = &ONNXImporter2::parseMatMulNBits; + dispatch["GatherBlockQuantized"] = &ONNXImporter2::parseGatherBlockQuantized; domain_dispatch_map[str_domain_com_microsoft] = dispatch; } diff --git a/modules/dnn/test/test_fusion.cpp b/modules/dnn/test/test_fusion.cpp index 040aad4327..9253b829c4 100644 --- a/modules/dnn/test/test_fusion.cpp +++ b/modules/dnn/test/test_fusion.cpp @@ -769,6 +769,126 @@ TEST(Fusion, AttentionQKVGroupingBatchMerge) checkAttentionQKVGrouping("attention_qkv_grouping_batch_merge"); } +TEST(Fusion, RMSNormCollapsesToOneLayer) +{ + const std::string model = findDataFile("dnn/onnx/models/rms_norm_expanded.onnx"); + Net net = readNetFromONNX(model, ENGINE_OPENCV); + ASSERT_TRUE(net.getMainGraph()); + + const int shape[] = {1, 2, 4}; + Mat input(3, shape, CV_32F); + for (int i = 0; i < 8; i++) + input.ptr()[i] = (float)(i + 1); + net.setInput(input); + Mat out = net.forward(); + + EXPECT_EQ(fusedCount(net, "RMSNormalization"), 1); + EXPECT_EQ(fusedCount(net, "NaryEltwise"), 0); + EXPECT_EQ(fusedCount(net, "Reduce2"), 0); + EXPECT_EQ(fusedCount(net, "Sqrt"), 0); + + // x / sqrt(mean(x^2) + 1e-5) * scale, scale = {0.5, 1.5, -2, 1} + const float expected[] = { 0.182574f, 1.095444f, -2.190889f, 1.460593f, + 0.379049f, 1.364576f, -2.122674f, 1.212957f }; + normAssert(out.reshape(1, 1), Mat(1, 8, CV_32F, (void*)expected), "", 1e-5, 1e-5); +} + +TEST(Fusion, LayerNormIsNotTakenForRMSNorm) +{ + const std::string model = findDataFile("dnn/onnx/models/layer_norm_expanded.onnx"); + Net net = readNetFromONNX(model, ENGINE_OPENCV); + ASSERT_TRUE(net.getMainGraph()); + + const int shape[] = {1, 4, 5}; + Mat input(3, shape, CV_32F, Scalar(1.f)); + net.setInput(input); + net.forward(); + + EXPECT_EQ(fusedCount(net, "RMSNormalization"), 0); +} + +TEST(Fusion, ReshapeShapeOperandFoldsToConstant) +{ + const std::string name = "attention_shared_shape_reshape"; + Net net = readNetFromONNX(findDataFile("dnn/onnx/models/" + name + ".onnx"), ENGINE_OPENCV); + ASSERT_TRUE(net.getMainGraph()); + + net.setInput(blobFromNPY(findDataFile("dnn/onnx/data/input_" + name + ".npy"))); + Mat out = net.forward(); + + EXPECT_EQ(fusedCount(net, "Concat2"), 0) << "the runtime shape was not folded"; + EXPECT_EQ(fusedCount(net, "Shape"), 0) << "the shape chain outlived its only reader"; + EXPECT_EQ(fusedCount(net, "Gather2"), 0); + EXPECT_EQ(fusedCount(net, "Unsqueeze"), 0); + normAssert(blobFromNPY(findDataFile("dnn/onnx/data/output_" + name + ".npy")), out, + "", 1e-4, 5e-4); +} + +TEST(Fusion, ReshapeShapeOperandKeptUnderAllowZero) +{ + const std::string name = "reshape_allowzero_shape"; + Net net = readNetFromONNX(findDataFile("dnn/onnx/models/" + name + ".onnx"), ENGINE_OPENCV); + ASSERT_TRUE(net.getMainGraph()); + + net.setInput(blobFromNPY(findDataFile("dnn/onnx/data/input_" + name + ".npy"))); + Mat out = net.forward(); + + normAssert(blobFromNPY(findDataFile("dnn/onnx/data/output_" + name + ".npy")), out); +} + +TEST(Fusion, AdjacentSlicesCollapseToOneSplit) +{ + const std::string name = "slice_to_split"; + Net net = readNetFromONNX(findDataFile("dnn/onnx/models/" + name + ".onnx"), ENGINE_OPENCV); + ASSERT_TRUE(net.getMainGraph()); + + net.setInput(blobFromNPY(findDataFile("dnn/onnx/data/input_" + name + ".npy"))); + Mat out = net.forward(); + + EXPECT_EQ(fusedCount(net, "Slice2"), 0) << "a partitioning Slice pair survived"; + EXPECT_EQ(fusedCount(net, "Split2"), 2); + normAssert(blobFromNPY(findDataFile("dnn/onnx/data/output_" + name + ".npy")), out); +} + +TEST(Fusion, SliceEndPastAxisIsClampedInSplit) +{ + const std::string name = "slice_to_split_clamp"; + Net net = readNetFromONNX(findDataFile("dnn/onnx/models/" + name + ".onnx"), ENGINE_OPENCV); + ASSERT_TRUE(net.getMainGraph()); + + net.setInput(blobFromNPY(findDataFile("dnn/onnx/data/input_" + name + ".npy"))); + Mat out = net.forward(); + + EXPECT_EQ(fusedCount(net, "Split2"), 1); + normAssert(blobFromNPY(findDataFile("dnn/onnx/data/output_" + name + ".npy")), out); +} + +TEST(Fusion, InputScalarFoldsIntoConsumer) +{ + const std::string name = "input_scalar_fold"; + Net net = readNetFromONNX(findDataFile("dnn/onnx/models/" + name + ".onnx"), ENGINE_OPENCV); + ASSERT_TRUE(net.getMainGraph()); + + net.setInput(blobFromNPY(findDataFile("dnn/onnx/data/input_" + name + ".npy"))); + Mat out = net.forward(); + + EXPECT_EQ(fusedCount(net, "NaryEltwise"), 0) << "a scalar Mul or Div was left in place"; + normAssert(blobFromNPY(findDataFile("dnn/onnx/data/output_" + name + ".npy")), out); +} + +TEST(Fusion, InputScalarOfHigherRankIsNotFolded) +{ + const std::string name = "input_scalar_rank"; + Net net = readNetFromONNX(findDataFile("dnn/onnx/models/" + name + ".onnx"), ENGINE_OPENCV); + ASSERT_TRUE(net.getMainGraph()); + + net.setInput(blobFromNPY(findDataFile("dnn/onnx/data/input_" + name + ".npy"))); + Mat out = net.forward(); + + EXPECT_EQ(MatShape({1, 2, 3, 5}), out.shape()); + normAssert(blobFromNPY(findDataFile("dnn/onnx/data/output_" + name + ".npy")), out); +} + static void checkBatchNormFoldsIntoConv(const std::string& name) { Net net = readNetFromONNX(findDataFile("dnn/onnx/models/" + name + ".onnx"), ENGINE_OPENCV); diff --git a/modules/dnn/test/test_onnx_importer.cpp b/modules/dnn/test/test_onnx_importer.cpp index 2331ace79c..e2acc78169 100644 --- a/modules/dnn/test/test_onnx_importer.cpp +++ b/modules/dnn/test/test_onnx_importer.cpp @@ -3987,6 +3987,67 @@ TEST_P(Test_ONNX_layers, MatMulNBits) { testONNXModels("matmulnbits_partial_block", npy, 1e-4, 1e-3); // K=34 not a multiple of block_size=16: partial last block + scalar SIMD tail } +// M=1 fuses dequantization into the dot product; the M=3 cases above never reach it. +TEST_P(Test_ONNX_layers, MatMulNBits_GEMV) { + testONNXModels("matmulnbits_gemv", npy, 1e-4, 1e-3); + // block narrower than one vector at 512 bits + testONNXModels("matmulnbits_gemv_bs16", npy, 1e-4, 1e-3); + // K=130, block_size=32: partial last block + testONNXModels("matmulnbits_gemv_partial", npy, 1e-4, 1e-3); + // 8 bits: no nibble pairing, stays on the staged kernel + testONNXModels("matmulnbits_gemv_8bits", npy, 1e-4, 1e-3); +} + +TEST_P(Test_ONNX_layers, MatMulNBits_ZeroPoints) { + testONNXModels("matmulnbits_zp", npy, 1e-4, 1e-3); + testONNXModels("matmulnbits_gemv_zp", npy, 1e-4, 1e-3); + // n_blk=5: the last zero-point byte holds one nibble, not two + testONNXModels("matmulnbits_gemv_zp_oddblk", npy, 1e-4, 1e-3); + testONNXModels("matmulnbits_zp_empty_tail", npy, 1e-4, 1e-3); +} + +TEST_P(Test_ONNX_layers, GatherBlockQuantized) { + testONNXModels("gather_block_quantized", npy, 1e-4, 1e-3); + // no zero_points: the symmetric 2^(bits-1) default + testONNXModels("gather_block_quantized_nozp", npy, 1e-4, 1e-3); + testONNXModels("gather_block_quantized_8bits", npy, 1e-4, 1e-3); + // 3 blocks of 16 over 40 values: odd block count and a partial last block + testONNXModels("gather_block_quantized_oddblk", npy, 1e-4, 1e-3); + // negative indices wrap; a repeated one must give the same row + testONNXModels("gather_block_quantized_negidx", npy, 1e-4, 1e-3); + // past either end: unlike ONNX Gather, the slice comes back zero rather than failing + testONNXModels("gather_block_quantized_oob", npy, 1e-4, 1e-3); +} + +TEST(Test_ONNX_importer, GatherBlockQuantized_uint4_refused) +{ + Net net; + EXPECT_NO_THROW(net = readNetFromONNX(_tf("models/gather_block_quantized_uint4.onnx"))); + EXPECT_TRUE(net.empty()); +} + +static void testGQAWindowBias(const std::string& name, bool required) +{ + Net net = readNetFromONNX(_tf("models/" + name + ".onnx", required), ENGINE_OPENCV); + ASSERT_FALSE(net.empty()); + + // total_sequence_length is dropped by the importer, so the remaining seven are fed by + // name: the order the layer takes them in is not the order the ONNX graph declares. + const char* names[] = {"query", "key", "value", "past_key", "past_value", + "seqlens_k", "attention_bias"}; + for (int i = 0; i < 7; i++) + net.setInput(blobFromNPY(_tf("data/input_" + name + format("_%d", i) + ".npy")), names[i]); + + Mat out = net.forward("output"); + normAssert(blobFromNPY(_tf("data/output_" + name + ".npy")), out, "", 1e-4, 1e-3); +} + +TEST_P(Test_ONNX_layers, GroupQueryAttentionWindowBias) { + testGQAWindowBias("gqa_window_bias", required); + // a bias of its own per head: one shared across heads cannot catch a head-0 broadcast + testGQAWindowBias("gqa_window_bias_perhead", required); +} + TEST_P(Test_ONNX_layers, ClipDivSharedConstant) { testONNXModels("clip_div_shared_constant"); }