[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-115331":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":15,"subscribersCount":15,"size":15,"stars1d":15,"stars7d":15,"stars30d":15,"stars90d":15,"forks30d":15,"starsTrendScore":15,"compositeScore":16,"rankGlobal":10,"rankLanguage":10,"license":17,"archived":18,"fork":18,"defaultBranch":19,"hasWiki":20,"hasPages":20,"topics":21,"createdAt":10,"pushedAt":24,"updatedAt":25,"readmeContent":26,"aiSummary":27,"trendingCount":15,"starSnapshotCount":15,"syncStatus":14,"lastSyncTime":28,"discoverSource":29},115331,"ncnn.rust","Edwardssss\u002Fncnn.rust","Edwardssss","Rust bindings for ncnn inference with resource-safe ownership, reusable output buffers and an optional Vulkan backend.","https:\u002F\u002Fedwardssss.github.io\u002Fncnn.rust\u002F",null,"Rust",44,4,2,0,42.1,"BSD 3-Clause \"New\" or \"Revised\" License",false,"main",true,[22,23],"ncnn","rust","2026-11-23 07:12:37","2026-11-21 01:27:38","**English** | [简体中文](README_zh.md)\n\n# ncnn.rust\n\nRust bindings for [ncnn](https:\u002F\u002Fgithub.com\u002FTencent\u002Fncnn) with resource-safe ownership.\n\nThe repository contains two packages:\n\n| Package | Role |\n|---|---|\n| `ncnn-rust` | Safe API: networks, tensors, images, options, GPU resources |\n| `ncnn-rust-sys` | Generated C bindings and the project C++ adapters |\n\n## Features\n\n- Owned-input inference with final-vector or reusable-buffer output.\n- Typed tensor access: `ElementKind` readers and writers cover FP16, BF16 and the integer widths,\n  and `infer_stored` keeps the element width a layer wrote.\n- Batched tensors, layout rewriting with `flatten` and `with_packing`, and consuming helpers\n  (`into_normalized`\u002F`into_reshape`) that skip the copy when the caller owns the storage.\n- Zero-copy requests: `Mat::from_external`, `Extractor::input_borrowed` and `Input::borrowed` submit\n  caller memory without a copy.\n- Graph introspection: `Net::layers` and `Net::blobs` report the wiring, the shapes and the support\n  flags ncnn declares for each layer type, and `layer_type_index` resolves a type name to its index.\n- Scoped read-only CPU output guards that reserve the network without copying.\n- Graph-bound endpoint tokens that reject foreign or reloaded graphs.\n- Tensors, image preprocessing, custom layers, readers and allocators, including in-place\n  normalization, pixel output, letterbox and depth borders, and affine warping.\n- Effective option readback on a loaded network, and caller-owned pools for blobs, workspace and the\n  attention KV cache.\n- Optional Vulkan backend: device selection, resident tensors, allocator, recording commands,\n  completed guards, buffer import and persistent pipeline caches.\n- Explicit native configuration mapping without Rust-side hardware gating.\n\n## Install\n\n```sh\ncargo add ncnn-rust\n```\n\nThe crates ship Rust code only. Building them compiles the C++ adapters against an ncnn SDK that the\nbuild environment supplies, so the next section sets that SDK up.\n\n## Build\n\nCargo consumes an externally installed ncnn SDK. `NCNN_INSTALL_DIR` is required and must contain\n`include\u002Fncnn` plus `lib`. Rust 1.85.1 is the tested MSRV.\n\n```sh\nexport NCNN_INSTALL_DIR=\u002Fabsolute\u002Fpath\u002Fto\u002Fncnn-install\nexport NCNN_LINK_KIND=dylib\ncargo test --workspace\ncargo run -p ncnn-rust --example add\n```\n\nRequired native features: `NCNN_C_API`, `NCNN_STDIO`, `NCNN_STRING`, `NCNN_PIXEL`,\n`NCNN_PIXEL_ROTATE`, `NCNN_PIXEL_AFFINE`, `NCNN_PIXEL_DRAWING`, `NCNN_BATCH`, `NCNN_INT8`,\n`NCNN_BF16`, `NCNN_VALIDATION`. The default build requires `NCNN_VULKAN=OFF`; the `vulkan` Cargo\nfeature requires `NCNN_VULKAN=ON` and a shared SDK with its dependency closure.\n\n`NCNN_LINK_KIND` selects `static` (default) or `dylib`. A shared SDK also needs the directory that\nholds the shared library on the runtime loader path: `lib` through `LD_LIBRARY_PATH` or\n`DYLD_LIBRARY_PATH`, and the `bin` directory that CMake installs `ncnn.dll` into through `PATH` on\nWindows, where a static and an import library share the `ncnn.lib` name. `NCNN_EXTRA_LIBS` lists\nadditional libraries in link order, optionally prefixed with `static=` or `dylib=`.\n`NCNN_EXTRA_LIB_DIRS` adds search directories. The SDK version is pinned to 20261020;\n`NCNN_ALLOW_UNTESTED_VERSION=1` builds against another release for compatibility checks.\n\nThe `raw` feature exposes the generated bindings as `ncnn_rust::sys`. They carry ncnn's C ABI and no\nindependent version policy, so the default build publishes none; the safe API is the surface that\npromises stability.\n\n`tools\u002Ffetch-ncnn.py` verifies the pinned source archive, and `tools\u002Fbuild-ncnn-sdk.py` applies the\npatches in `tools\u002Fpatches\u002F` and builds an SDK with the required feature set. `--link-kind static`\nbuilds the static library that `NCNN_LINK_KIND=static` links instead of the default shared one.\n\n`tools\u002Finstall-sdk.py` skips that local build by installing a published archive for the pinned\nrelease. The archives ship the shared library, so no linker choice is baked into them, and the\ninstaller checks the download against the release's `SHA256SUMS` and the release stamped in\n`platform.h`:\n\n```sh\npython3 tools\u002Finstall-sdk.py --platform linux-x64-cpu --dest \u002Fopt\u002Fncnn-20261020\nexport NCNN_INSTALL_DIR=\u002Fopt\u002Fncnn-20261020\n```\n\n`--list` prints the published archives: `linux-x64-cpu`, `linux-x64-vulkan`, `windows-x64-cpu` and\n`macos-arm64-cpu`. The checksum detects a corrupted transfer rather than a substituted release, and\nno build script downloads anything on its own.\n\n## Usage\n\n```rust\nuse ncnn_rust::{Input, Mat, Net};\n\nlet net = Net::builder()?.threads(2)?.load_files(\"model.param\", \"model.bin\")?;\nlet input = Mat::from_f32(&values, &[224, 224, 3])?;\nlet outputs = net.infer([(\"input\", input)], &[\"output\"])?;\nfor output in outputs {\n    println!(\"{:?} {}\", output.info, output.values.len());\n}\n```\n\nA request has one storage decision per side. On an extractor:\n\n| Form | Storage |\n|---|---|\n| `extract(endpoint, width)` | borrowed read-only guard, which reserves the network until it drops |\n| `extract_mat(endpoint, width)` | owned native tensor, without a second copy on the default pool |\n| `extract_into(endpoint, buffer)` | appended to a caller vector that keeps its capacity |\n| `extract_owned(endpoint)` | independent FP32 values |\n\n`TensorWidth` selects FP32 conversion or the width the layer wrote. On a network, `Input` carries\nthat same decision, so one method covers owned storage, borrowed FP32 values and tensor sub views:\n\n```rust\nlet outputs = net.infer([(\"input\", Mat::from_f32(&values, &[224, 224, 3])?)], &[\"output\"])?;\nlet borrowed = net.infer([(\"input\", Input::borrowed(&values, &[224, 224, 3]))], &[\"output\"])?;\nlet mut buffer = Vec::new();\nnet.infer_into([(\"input\", Input::view(&image.channel(0)?))], &[\"output\"], &mut buffer)?;\n```\n\nFor repeated inference resolve endpoints once and fill one reusable vector:\n\n```rust\nlet input_id = net.resolve_blob(\"input\")?;\nlet output_id = net.resolve_blob(\"output\")?;\nlet mut ex = net.extractor()?;\nex.input(&input_id, Mat::from_f32(&values, &[224, 224, 3])?)?;\nlet mut buffer = Vec::new();\nex.extract_into(&output_id, &mut buffer)?;\n```\n\nRun on a Vulkan device by attaching it before the model is read. Native per-layer CPU fallback stays\navailable, so selection is not a guarantee that every layer runs on the GPU:\n\n```rust\nlet device = ncnn_rust::gpu::Device::default_device()?;\nlet net = Net::builder()?.vulkan(device).load_files(\"model.param\", \"model.bin\")?;\n```\n\nQuantized and half-precision outputs keep their stored width. `infer` converts to FP32, so read them\nthrough the stored forms and name the format:\n\n```rust\nlet outputs = net.infer_stored([(\"input\", input)], &[\"output\"])?;\nlet (info, stored) = &outputs[0];\nprintln!(\"{} bytes per element\", info.elemsize);\nlet bytes: Vec\u003Ci8> = stored.to_i8()?;\n```\n\n`Mat::from_typed` and `Mat::from_i8` build the same storage for an input side, and\n`Extractor::extract` with `TensorWidth::Stored` borrows it while one extractor runs. The [typed\ntensor example](crates\u002Fncnn\u002Fexamples\u002Ftyped_tensors.rs) and the [resident Vulkan\nexample](crates\u002Fncnn\u002Fexamples\u002Fvulkan_resident.rs) run end to end.\n\nAn extractor is safe to reuse: submitting an input restarts the request, so a second inference\nrecomputes instead of returning the output the first one cached. Per-extractor settings cover what\nthe network options do not, and they survive that restart:\n\n```rust\nlet mut ex = net.extractor()?;\nif net.shared_blobs()?.is_empty() {\n    ex.set_light_mode(true)?;\n}\nex.set_kvcache_max_seqlen_hint(2048)?;\n```\n\nA graph that keeps state across inputs, such as an attention cache for token-by-token decoding,\ncalls `ex.continue_session()` before the next input so that input extends the cached state instead\nof restarting the request. Light mode releases each intermediate after its first consumer, so\n`set_light_mode(true)` is refused while `net.shared_blobs()` lists a blob that feeds two layers;\ninsert an explicit `Split` layer or keep light mode off.\n\nPart of a tensor is readable without copying it. A view aliases the source storage: the slice\nreaders borrow it, `to_f32` copies out of it, and `Extractor::input` copies it because an alias\nkeeps no storage of its own. `Input::view` reads the region where it lives, which is the zero-copy\nform for a model that takes a crop, a channel or one batch item:\n\n```rust\nlet mut buffer = Vec::new();\nlet ranges = net.infer_into(\n    [(\"input\", Input::view(&image.channel(0)?))],\n    &[\"output\"],\n    &mut buffer,\n)?;\nlet range = &ranges[0].values;\nlet values = &buffer[range.start..range.end];\n```\n\nA network and its extractor stay on the thread that created them, so a service gives each worker its\nown pair; the [thread example](crates\u002Fncnn\u002Fexamples\u002Fthreads.rs) measures that against one network\nthat uses every core.\n\n## Performance\n\nWrapper cost is measured against the native C API from the same SDK in one process, so the tables\nisolate the binding rather than the engine. Every number below comes from one machine and one\ncampaign; the medians move with host load, so compare rows rather than absolute values.\n\n> **Hardware:** AMD Ryzen 7 5800H (8 cores, 16 threads), 16 GB DDR4-3200, NVIDIA GeForce RTX 3060\n> Laptop GPU (6 GB, driver 596.49), Windows 10 22H2 build 19045, MSVC 19.50, Rust 1.96.1, ncnn\n> 20261020 built from source with the repository's build script. Vulkan rows run on the same GPU;\n> the Linux figures quoted in [Performance](docs\u002Fperformance.md) come from a Debian WSL2 guest on\n> this machine with 8 logical cores.\n\nTrained models, median milliseconds per request, one thread, release build:\n\n| Model | Device | native | ncnn-rust | Delta |\n|---|---|---:|---:|---:|\n| NanoDet-m, 6 outputs | CPU | 23.011 | 23.379 | +1.6% |\n| PP-OCRv5 recognition | CPU | 57.566 | 58.842 | +2.2% |\n| NanoDet-m, 6 outputs | Vulkan | 4.489 | 4.702 | +4.7% |\n| PP-OCRv5 recognition | Vulkan | 10.863 | 10.210 | within spread |\n\nThe `ncnn-rust` column resolves endpoints once and fills a caller vector, which allocates nothing\nafter warm-up. A vector owned per request instead adds one output copy, which is why the reuse form\nis the one quoted; the CPU deltas sit inside the campaign's 10% run-to-run spread.\n\nA single-layer graph shows the same picture at microsecond scale, where the request path rather than\nthe arithmetic dominates:\n\n| Case | Device | native | ncnn-rust |\n|---|---|---:|---:|\n| ReLU | CPU | 0.002 ms | 0.002 ms |\n| AbsVal | CPU | 0.002 ms | 0.002 ms |\n| ReLU | Vulkan | 0.193 ms | 0.197 ms |\n| AbsVal | Vulkan | 0.183 ms | 0.221 ms |\n\nThe request path over one 65536-element FP32 tensor, median microseconds per request, one thread,\npinned to one core, nine runs on the Debian WSL2 guest. The native column runs the three steps of a\nrequest through the C API and hands the tensor back where the engine left it:\n\n| Form | native | ncnn-rust | Delta |\n|---|---:|---:|---:|\n| owned input, borrowed output view | 10.335 | 10.614 | +3% |\n| owned input, zero-copy owned output | 10.335 | 10.356 | within spread |\n\nBoth rows keep the result in the buffer the extractor already detached, so the wrapper adds the call\nand the endpoint resolution and nothing else. `Extractor::input` consumes the tensor, which releases\nthe caller's reference before the request runs: a native request that keeps its input handle alive\nblocks the light-mode reuse of that buffer and costs twenty times as much on the guest, so the\nwrapper's fast shape is also its default shape.\n\nThe forms that ask for a copy pay for one. A value vector per request allocates 256 KB on top of the\nnative clone that `Extractor::extract` already performs, which costs 218 us on the guest against the\n10.6 us above, and a cloned input and output allocate two such buffers.\n[Performance](docs\u002Fperformance.md) records both with their allocation counts, the native C\nreferences they compare against, and the glibc and NT heap behaviour that decides what a fresh 256\nKB buffer costs. That is why the reuse forms exist: `NetBuilder::reuse_blob_memory()` moves the\nengine's intermediate tensors into pools it owns, `infer_into` removes the caller vector for owned\nand borrowed inputs, and `ncnn_rust::heap::retain_pages()` keeps a caller-allocated buffer's pages\nmapped on glibc. The per-helper preprocessing medians, the pooling comparison, the Linux page-fault\ncampaign, the worker scaling and the reproduction commands are in\n[Performance](docs\u002Fperformance.md).\n\n## Documentation\n\nAPI documentation is generated by `.github\u002Fworkflows\u002Fdocs.yml` on every push to the default branch\nand published at \u003Chttps:\u002F\u002Fedwardssss.github.io\u002Fncnn.rust\u002Fncnn_rust\u002F>. docs.rs cannot build this\nworkspace: its sandbox has no ncnn SDK, and the build script compiles C++ adapters against the\ninstalled headers, so a missing `NCNN_INSTALL_DIR` fails before rustdoc starts.\n\n- [Documentation map](docs\u002FREADME.md)\n- [Safety contracts](docs\u002Fcontracts.md)\n- [Native ABI and adapter decisions](docs\u002Fnative-abi.md)\n- [Layer coverage](docs\u002Flayer-coverage.md)\n- [Supported platforms](docs\u002Fsupport-matrix.md)\n- [Troubleshooting](docs\u002Ftroubleshooting.md)\n- [Migration notes](docs\u002Fmigration.md)\n- [Evidence history](docs\u002Fevidence-history.md)\n- [Performance](docs\u002Fperformance.md)\n- [Advanced CPU adapters](docs\u002Fadvanced-cpu.md)\n- [Model fixtures](docs\u002Fmodel-fixtures.md)\n- [Changelog](CHANGELOG.md)\n- [Security policy](SECURITY.md)\n- [Contributing](CONTRIBUTING.md)\n\n## License\n\nBSD-3-Clause.\n","ncnn.rust 是一个为 Tencent ncnn 推理引擎提供的安全、高效的 Rust 语言绑定库。它通过 RAII 管理 GPU\u002FCPU 资源，支持零拷贝输入、可复用输出缓冲区、类型化张量访问（FP16\u002FBF16\u002FINT）、批处理与布局变换，并可选启用 Vulkan 后端实现跨平台高性能推理。项目采用纯 Rust 接口设计，底层调用 ncnn C API，兼顾内存安全性与运行时性能。适用于嵌入式设备、边缘计算及 Rust 生态中的轻量级 AI 模型部署场景，尤其适合对资源生命周期和低延迟有严格要求的工业视觉、移动端推理等应用。","2026-11-24 04:50:41","CREATED_QUERY"]