476 Commits

Author SHA1 Message Date
nihui 44b02dabdc vulkan: stabilize InstanceNorm subgroup reduction (#7136)
Co-authored-by: futz12 <1391525377@qq.com>
Co-authored-by: futz12 <56149058+futz12@users.noreply.github.com>
2026-10-18 21:31:56 +08:00
nihui 8f644266e8 GroupNorm Vulkan subgroup reduction with stability and dispatch fixes (#7135)
Co-authored-by: futz12 <1391525377@qq.com>
Co-authored-by: futz12 <56149058+futz12@users.noreply.github.com>
2026-10-18 21:30:56 +08:00
風的彷徨 5d1c5ad4fd rmsnorm vulkan subgroup reduce optimization (#6755) 2026-10-17 23:26:34 +08:00
風的彷徨 d02548fb5f layernorm vulkan subgroup reduce optimization (#6754) 2026-10-17 23:25:52 +08:00
kongxin 776cd837c3 vulkan: use roundEven for UnaryOp round (#7119)
GLSL round() leaves the direction of halfway cases to the implementation.
MoltenVK rounds them away from zero, while every cpu implementation rounds
half to even, so 0.5 / 2.5 / -0.5 came out as 1 / 3 / -1 on Apple gpus.

Add exact halfway inputs to test_unaryop for op_type 18.
2026-10-17 18:28:49 +08:00
nihui d79c29e67d riscv: add bf16 detection, cast and clip (#7111) 2026-10-17 14:55:31 +08:00
nihui fcde729c7b riscv: add int8 convolution winograd (#7093) 2026-10-14 14:58:05 +08:00
nihui b0f97f43f2 riscv: add int8 convolution im2col gemm (#7090)
* riscv: add tiled int8 convolution im2col gemm

Pack weights and input in cache-sized M/N/K tiles with a 1x1 input shortcut.
Use vector-length-agnostic 8/4/2/1-position microkernels with signed
widening accumulation, including an XTheadVector-compatible path.

Reuse bounded per-worker input panels across output-channel tiles and
keep split-K partial sums in the existing int32 output. Wire the GEMM
option into the int8 pipeline while retaining direct convolution and
existing requantization, dequantization and activation handling.

Add focused tests for actual pipeline selection, packing, tails,
split-K accumulation, full-range int8 values and thread-count changes.

* riscv: fix int8 convolution split-K test sizing

A tile balanced for a large artificial K can be smaller than the cache
limit. Choosing that tile size plus one does not guarantee that the
actual test shape splits K, as exposed by the C907 and C908 CI jobs.

Query the tiler for each actual candidate K and grow the candidate until
it spans multiple panels. Keep the transformed-weight K-row assertion
and numerical checks, and report a missing split separately from an
incorrect pipeline selection.

* riscv: write int8 convolution gemm blocks explicitly

* riscv: separate full int8 gemm channel blocks and tails

* riscv: widen int8 convolution gemm to m4 accumulators

* apply code-format changes

* riscv: keep int8 convolution partial sums in packed tiles

* riscv: align int8 convolution gemm helpers with ncnn style

* apply code-format changes

* riscv: unify int8 convolution gemm channel loops

* riscv: reduce int8 im2col indexing and single-k tile overhead

* riscv: use scalar 2x2 int8 gemm and consolidate convolution tests

* mips, loongarch: fix packed int8 im2col K tile offsets

---------

Co-authored-by: nihui <171016+nihui@users.noreply.github.com>
2026-10-13 13:11:17 +08:00
LI f4e86ad88f fix lrn even across-channel window size (#7070) 2026-10-12 14:08:14 +08:00
LI bd38ca5b0c arm/riscv: avoid fp16 GELU overflow (#7060) 2026-10-12 14:07:42 +08:00
LI 4a0e0dba89 fix(vulkan): include element packing in BinaryOp shape hints (#7040) 2026-10-12 14:07:04 +08:00
Dreladwyn 201145bdd9 fix crash reading past end of memory-mapped model file (#7021)
* fix crash reading past end of memory-mapped model file

DataReaderFromMemory used by mapped model loading was unbounded:
read()/reference() advanced past the mapped region, so a truncated
or corrupt .bin crashed with an access violation inside
ModelBinFromDataReader instead of failing cleanly.

Add a size-aware DataReaderFromMemory ctor that clamps reads and
fails references past the end, use it in the mapped branches of
Net::load_model, and propagate load_model()'s return value which
was previously dropped.

* fix bounded memory reader scans and add loading regressions

* f

* reuse bounded memory reader scan buffer

---------

Co-authored-by: Dr3ladwyn <Dr3ladwyn@users.noreply.github.com>
Co-authored-by: nihui <nihuini@tencent.com>
2026-10-12 00:01:46 +08:00
風的彷徨 1dd0355612 Fix Vulkan fallback crash with empty optional inputs (#6870)
* test net transfers with empty optional inputs
2026-10-10 23:18:27 +08:00
風的彷徨 ab3790faca fix MHA singleton mask broadcast across backends (#6869)
Keep persistent KV caches on the blob allocator, broadcast single-channel attention masks across heads on CPU and Vulkan paths, and add long multi-token cache regressions.
2026-10-10 19:47:13 +08:00
nihui 1efcd3ac4a fix interp scale factor sampling and pnnx recomputed sizes (#7075)
* fix interp scale factor sampling and pnnx recomputed sizes

Use the original scale factor for linear and cubic interpolation instead
of deriving coordinates from the truncated output size. Preserve explicit
sizes, reference sizes, and size expressions across CPU and Vulkan paths.
Keep same-axis linear behavior, resample non-unit same-size bicubic input,
and clamp interpolation taps for short axes without out-of-bounds reads.

Lower recompute_scale_factor to runtime size expressions, retain the flag
when importing nn.Upsample, and avoid deleting non-unit same-size resizes.

Add independent ncnn reference checks and pnnx static/dynamic round-trip
tests covering fractional up/downscales, recomputed sizes, short axes,
align_corners, and nn.Upsample.

Validated CPU interpolation tests, ASan/UBSan, Vulkan llvmpipe, and pnnx
TorchScript interpolation tests against PyTorch 2.10.0 CPU. The original
bilinear/bicubic reproductions fail on the base and pass with this fix.

Refs: Tencent/ncnn#6836, Tencent/ncnn#6837, Tencent/ncnn#6844

---------

Co-authored-by: Acture <acturea@gmail.com>
Co-authored-by: xy200303 <3483421977@qq.com>
Co-authored-by: nihui <171016+nihui@users.noreply.github.com>
2026-10-10 00:00:45 +08:00
Stern bbaca40c35 x86: reduce Col2im memory access for non-overlapping deconvolution (#7015)
* Reduce memory access in x86 deconvolution Col2im

The SGEMM path fills the output with bias, then reads and updates each
output value. When kernel tiles do not overlap, each value has one source.
Write the source plus bias once, and fill only the output padding.

Use this path for rectangular kernels with unit dilation and stride equal
to the kernel size. Support packs of 1, 4, and 8. Split input rows between
workers when there are fewer output channel groups than threads. Each
worker writes separate output rows. Keep the existing path for other
cases. Add 32 test cases to test_deconvolution.

Test Plan
---------
These commands passed in the local benchmark workspace:

```bash
ctest --test-dir .tools/ncnn-col2im-build -R '^test_deconvolution$' --output-on-failure
.venv-esp/bin/python results/oss/col2im_transfer_20260920/generalization/test_ncnn.py --parallel
.venv-esp/bin/python results/oss/col2im_transfer_20260920/generalization/sanitize_ncnn.py
```

The complete forward test gave equal output bits for 236 cases and
1,433,578 values. The extracted loops passed ASan and UBSan for 300 cases.
The sanitizer test uses a small Mat substitute, not a full sanitizer build.
The local probe scripts are outside this repository.

The final format check and git diff --check passed. The format changes do
not change the tested operations.

This change was prepared with help from an AI assistant.
2026-10-08 19:44:27 +08:00
風的彷徨 c4393a13b0 pnnx: preserve batch semantics across reshape and flatten (#6934)
Co-authored-by: nihui <nihuini@tencent.com>
2026-10-08 19:08:41 +08:00
acture c798db5525 RotaryEmbed: support full-width cos/sin cache for 2D / vision RoPE (#6834)
* RotaryEmbed: support full-width cos/sin cache for 2D / vision RoPE

The non-interleaved path read only the first embed_dim/2 values of the
cos/sin cache and reused them for both halves of each head vector. That is
correct for standard 1-D RoPE (cos = concat(freqs, freqs), identical halves),
but the pnnx fuse_convert_rotaryembed pass lowers the general expression
x*cos + rotate_half(x)*sin — with a full-width cos — into this op without
checking that the halves are equal. For 2-D / vision RoPE where the halves
differ (cos = concat(cos_h, cos_w), e.g. the Penguin-VL vision encoder) the
second half was rotated with the wrong frequencies, silently producing
wrong output (max|diff| ~3.4 vs PyTorch on the Penguin-VL vision encoder).

Read the second half's cos/sin for the second output half. Backward
compatible via a cache-width guard: when the cache is full width (== embed_dim)
the two halves are independent; when it is embed_dim/2 (the standard-rope form,
as the unit test supplies) the second half reuses the first, so existing
half-width callers stay bit-identical. Applied to every backend
(naive / arm / x86 / loongarch / mips / vulkan) and its bf16/fp16 paths.

Adds a full-width differing-halves test case; the previous test only exercised
half-width caches, which are trivially identical-halves.

After the fix the Penguin-VL vision encoder converts in-graph at
max|diff| = 6.2e-4 vs PyTorch (fp32).

Fixes #6833

* test: add a pnnx test that can actually fail for the full-width cache fix

tests/test_rotaryembed.cpp cannot detect this bug. ncnn's test_layer() compares
the optimized backends against the naive layer, and this PR changes the naive
layer too, so the test stays green whether the semantics are right or wrong —
rebuilding the PR's test against master's src/layer still exits 0.

tools/pnnx/tests/ncnn/ is the only harness in-tree that pins semantics to an
external reference (torch.allclose against PyTorch), so the check belongs there.

Every input is drawn with torch.rand in forward() parameter order, because the
generated test_ncnn_fuse_rotaryembed_ncnn.py takes no arguments: it reseeds with
manual_seed(0) and regenerates each input the same way. An input built any other
way would leave the two sides comparing different tensors, and the test would
fail unconditionally while appearing to test something.

Random caches are also the stronger choice here: the defect is that the layer
reads one cache row for both halves, so it only shows when the halves differ,
which random values guarantee and a hand-built cat(f, f) cache would hide. A
"standard RoPE stays correct" case is deliberately absent — the cache must stay a
pnnx.Input for the fusion pattern to match, and the generator always randomizes
inputs, so that case cannot be expressed in this harness.

Also parameterizes the interleaved path in tests/test_rotaryembed.cpp. On a
CPU-only build that is code-path coverage rather than a correctness check, for
the reason above; its value is on the Vulkan backend.

Not run here: building pnnx needs libtorch. Worth confirming under ctest that the
generated .param really contains RotaryEmbed layers — if the fusion does not
fire, the test passes without exercising anything.

* fix pnnx rotaryembed regression test layout and fusion checks

---------

Co-authored-by: nihui <nihuini@tencent.com>
2026-10-08 18:56:24 +08:00
Lune 16bdc2da54 x86: optimize permute with SIMD (#6762)
Co-authored-by: nihui <nihuini@tencent.com>
2026-10-07 23:21:38 +08:00
losewayy 51f3b0bf03 vulkan: implement tile (#7027) 2026-10-06 21:27:08 +08:00
Justin Fung 6a1fce7802 RVV1.0 Packed INT8 Convolution (#6763)
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: nihui <nihuini@tencent.com>
Co-authored-by: nihui <shuizhuyuanluo@126.com>
2026-10-05 23:03:55 +08:00
nihui c7ad4fc6a8 fix test mat batch fp16/bf16 cast (#7044) 2026-10-05 15:22:37 +08:00
nihui 41f031e045 reduce redundant tests that do not contribute to coverage (#7042)
* adjust tests
* opt shader coverage op
* update gpu_coverage.cpp atomicor coalesce
2026-10-05 08:57:20 +08:00
nihui 9f9d4ec815 reduce gpu test cases (#7017) 2026-10-01 23:33:05 +08:00
Lune 1857775c98 x86: optimize normalize with SIMD (#6761)
Co-authored-by: nihui <nihuini@tencent.com>
2026-09-20 10:49:20 +08:00
Lune 70e7bfd608 x86: optimize Reduction with SIMD (#6743)
* [test] reduction: add perf_reduction harness target
* [feat] reduction: add x86 optimized Reduction layer

Co-authored-by: nihui <nihuini@tencent.com>
2026-09-18 18:37:24 +08:00
Lune b931b0ca63 x86: optimize CumulativeSum with SIMD Kogge-Stone prefix scan (#6693)
Co-authored-by: nihui <nihuini@tencent.com>
2026-09-18 17:24:37 +08:00
primorLee babb819dfa fix: stabilize logaddexp expression evaluation (#6924)
Co-authored-by: nihui <nihuini@tencent.com>
2026-09-17 10:41:00 +08:00
nihui 8bc95a1e7f pnnx: store bool MemoryData attributes as raw int8 (#7006)
* pnnx: store bool MemoryData attributes as raw int8

Keep bool constants as one byte per element and select MemoryData
load_type=3. Implement the reserved raw int8 ModelBin loading mode and
pad exported bool data to four bytes so subsequent weights stay aligned.
This preserves the byte representation used by the proposed logical ops.

Add regression coverage for scalar and padded bool exports in both fp16
modes, multidimensional MemoryData, raw int8 loading through reference
and copy readers, trailing fp32 weights, and missing padding. Document
the format.

Based on the bool attribute serialization fixes proposed in:
https://github.com/Tencent/ncnn/pull/6956
https://github.com/Tencent/ncnn/pull/6866

Fixes #6855

* tools: preserve byte MemoryData when optimizing models

Save MemoryData load_type so raw int8 constants retain their byte
representation after ModelWriter saves the model. Skip fusion paths that
interpret MemoryData as float32 when its elements are not four bytes.

This change does not add bool arithmetic support or automatic type
promotion. Byte bool storage is intended for future logical, comparison
and selection operators.

Validated ncnnoptimize save and reload for scalar and one-to-five-element
bool constants in fp32 and fp16 storage modes, preserving byte values
and element size in all 12 cases.

---------

Co-authored-by: ktz03 <2484593937@qq.com>
Co-authored-by: Giulio Corradi <53930027+giuliocorradi@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 10:09:00 +08:00
lazypool 4366038c23 fix spirv compile failure diagnostics read past shader buffer (#6882)
* fix spirv compile failure diagnostics read past shader buffer (#6881)

the shader source slice passed to glslang (comp_datas[3]) is not
null-terminated, since the .comp_data arrays generated by
ncnn_generate_shader_comp_header.cmake are hex-encoded without a
trailing 0x00. the error-printing path in compile_spirv_module()
scanned it with strchr() and checked *p != '\0', causing an
out-of-bounds read and garbled diagnostics whenever a shader fails
to compile.

bound the scan with memchr() using the known source length and print
the trailing partial line with %.*s instead of relying on
null-termination. verified with asan: before, a broken non-null-
terminated shader source reports a stack-buffer-overflow in
compile_spirv_module(); after, the error path prints correctly with
no overrun.

* fix bounded shader version parsing and add regression tests

---------

Signed-off-by: lazypool <lazypool@proton.me>
Co-authored-by: Marcin Sochacki <136440930+marcin-sochacki@users.noreply.github.com>
Co-authored-by: nihui <nihuini@tencent.com>
2026-09-15 21:49:34 +08:00
nihui 5ea98309e3 layer param hardening (#7003)
* harden layer parameter validation

Original patches and author identities:
https://github.com/Tencent/ncnn/pull/6912 (beilzx)
https://github.com/Tencent/ncnn/pull/6919 (FluxMind-O)
https://github.com/Tencent/ncnn/pull/6928 (lxcxjxhx)
https://github.com/Tencent/ncnn/pull/6948 (ktz03)
https://github.com/Tencent/ncnn/pull/6950 (ktz03)
https://github.com/Tencent/ncnn/pull/6971 (LI)
https://github.com/Tencent/ncnn/pull/6974 (LI)
https://github.com/Tencent/ncnn/pull/6977 (LI)

Co-authored-by: beilzx <2069360659@qq.com>
Co-authored-by: FluxMind-O <3283918317@qq.com>
Co-authored-by: lxcxjxhx <lxcxjxhx@users.noreply.github.com>
Co-authored-by: ktz03 <2484593937@qq.com>
Co-authored-by: LI <2484593937@qq.com>
2026-09-15 19:18:46 +08:00
nihui 0cdc3351c8 harden net loading (#6989)
* Harden Net graph loading and metadata validation

Apply count and blob index validation from Tencent/ncnn PRs #6902,
#6916, #6922 and #6949 to both text and binary graph loading. Bound
header counts to 1,000,000 while preserving repeated blob references
and zero-output layers.

Validate text integer tokens and name lengths, shape hint types,
record lengths and extent arithmetic, feature masks, layer type tags,
and one-blob layer connection counts. Guard missing producers during
extraction and handle null custom layer creators.

Own partially loaded layers before reading their connections, honor
registered destroyers on all failure and CPU replacement paths, and
clear stale graph metadata when reloading or rejecting a model.

Add in-memory Net regressions for malformed and truncated inputs, valid
shape layouts, reload isolation, custom layer lifetime and external
inputs, without requiring filesystem access.
Validated with native tests, SqueezeNet inference, ASan/UBSan and
32-bit big-endian PowerPC tests; compile checked Vulkan and reduced
C++03 configurations.

Sources:
https://github.com/Tencent/ncnn/pull/6902
https://github.com/Tencent/ncnn/pull/6916
https://github.com/Tencent/ncnn/pull/6922
https://github.com/Tencent/ncnn/pull/6949

Co-authored-by: kaltsit-10 <kaltsit-10@users.noreply.github.com>
Co-authored-by: beilzx <2069360659@qq.com>
Co-authored-by: ktz03 <2484593937@qq.com>
2026-09-14 14:23:50 +08:00
nihui c0abf4830d harden paramdict parsing and typed access (#6983)
Co-authored-by: Nathan Keys <nathan.keys@pm.me>
Co-authored-by: beilzx <2069360659@qq.com>
2026-09-10 17:23:55 +08:00
Linton fa5754e864 arm: fix fp16 tanh_ps_f16 saturating at 1.044 instead of 1.0 (#6979)
The fp32 rational approximation coefficients cannot be represented in
half precision: alpha_9/11/13 underflow to zero and alpha_7 becomes
subnormal, so tanh_ps_f16 saturates at ~1.044 and fast gelu returns
+0.022*|x| for large negative inputs. Transformer models with large
activations (SigLIP2, CLIP ViT) produce input-independent features under
use_fp16_arithmetic.

Refit the rational approximation for fp16 on [0, 4.5], return +/-1
beyond that range, clamp the result to 1, and add large-magnitude test
cases for GELU and TanH.
2026-09-09 14:33:58 +08:00
nihui 3a3ceb6b9e various workaround for adreno cooperative matrix shader (#6972) 2026-09-09 10:42:36 +08:00
nihui b440d37b88 fix vulkan bf16 packed without shaderInt16 (#6962)
Co-authored-by: blue wombat <219594305+aadpnde@users.noreply.github.com>
2026-09-07 10:46:50 +08:00
nihui 34a748349c fp8/fp16 conversion round to nearest ties away from zero (#6958) 2026-09-04 16:23:00 +08:00
nihui 60bfa40044 sdpa flash attention x86 optimization, llm models enable gqa, dispatch for avx2 bfloat2float (#6923)
* enable gqa
* update perf test
2026-09-01 17:35:42 +08:00
nihui 0a2c46bc75 let float2bfloat round to nearest, even or ties away from zero (#6925) 2026-08-25 11:21:15 +08:00
風的彷徨 946fe3fb14 x86/loongarch/mips: refine rsqrt with newton-raphson iterations && vulkan: use fp32 for coefficient (#6903) 2026-08-18 16:40:18 +08:00
nihui 7f162381ab kvcache allocator (#6901)
* decode benchmark
* reject kvcache batch
* enable mha vulkan gemm out_elempack 1
2026-08-17 15:44:30 +08:00
nihui c189d88a8d modelbin bf16 storage type (#6900)
* fix modelwriter on big-endian
2026-08-13 17:19:50 +08:00
nihui 5e66f094bf avoid test failure on fp16 denormal flush to zero (#6891) 2026-08-05 20:05:07 +08:00
nihui 5c4c03a880 adapt to vkwebgpu and vkopencl (#6876)
* support image storage
2026-08-04 14:37:26 +08:00
nihui 92b73d6665 x86/arm/mips/loongarch/riscv gemm block quantization optimization (#6831)
* benchncnn_llm int8 models
2026-08-04 14:34:22 +08:00
nihui dda2e28bae skip fp16a gpu test (#6820) 2026-07-13 15:13:46 +08:00
nihui f74639deeb gemm block quantization infrastructure for llm decoder style (#6814)
* another mha oob read
2026-07-13 10:13:39 +08:00
nihui 13b6d5318c fix naive mha out-of-bound read (#6812) 2026-07-08 13:55:11 +08:00
nihui 127b414614 reshape support batch to/from dim (#6784) 2026-07-02 19:29:34 +08:00
nihui f6f734f44d vulkan int8 kernels (#6751)
* vulkan: add int8 kernels for core layers
Implement Vulkan int8 paths for convolution, convolutiondepthwise, innerproduct, and gemm with scalar fallback and integer dot product shader branches. Add goal.md and enable existing int8 unit tests for Vulkan coverage.
* enable int8 gpu benchmark
2026-06-17 17:39:49 +08:00