Convert Figma logo to code with AI

Tencent logoncnn

ncnn is a high-performance neural network inference framework optimized for the mobile platform

23,562
4,464
23,562
1,172

Top Related Projects

15,699

MNN: A blazing-fast, lightweight inference engine battle-tested by Alibaba, powering high-performance on-device LLMs and Edge AI.

5,042

MACE is a deep learning inference framework optimized for mobile heterogeneous computing platforms.

4,526

Tengine is a lite, high performance, modular inference engine for embedded device

The Compute Library is a set of computer vision and machine learning functions optimised for both Arm CPUs and GPUs using SIMD technologies.

13,579

Open Machine Learning Compiler Framework

Quick Overview

ncnn is a high-performance neural network inference framework optimized for mobile platforms. Developed by Tencent, it is designed to run deep learning models on mobile devices efficiently, with a focus on speed and low memory footprint.

Pros

  • Extremely fast inference speed on mobile devices
  • Low memory footprint, suitable for resource-constrained environments
  • Cross-platform support (Android, iOS, Windows, Linux, macOS)
  • Supports a wide range of deep learning models and operations

Cons

  • Steeper learning curve compared to some other inference frameworks
  • Limited documentation and examples, especially for beginners
  • Requires manual model conversion for some popular deep learning frameworks
  • Smaller community compared to more mainstream frameworks like TensorFlow Lite

Code Examples

  1. Loading and running a model:
#include "net.h"

ncnn::Net net;
net.load_param("model.param");
net.load_model("model.bin");

ncnn::Mat in(224, 224, 3);
// Fill 'in' with input data

ncnn::Mat out;
ncnn::Extractor ex = net.create_extractor();
ex.input("data", in);
ex.extract("output", out);
  1. Creating a custom layer:
class MyCustomLayer : public ncnn::Layer
{
public:
    MyCustomLayer()
    {
        one_blob_only = true;
    }

    virtual int forward(const ncnn::Mat& bottom_blob, ncnn::Mat& top_blob, const ncnn::Option& opt) const
    {
        // Implement your custom layer logic here
        return 0;
    }
};

DEFINE_LAYER_CREATOR(MyCustomLayer)
  1. Using Vulkan compute:
ncnn::create_gpu_instance();

ncnn::VulkanDevice* vkdev = ncnn::get_gpu_device();
ncnn::Net net;
net.opt.use_vulkan_compute = true;
net.set_vulkan_device(vkdev);

// Load and run model as usual

ncnn::destroy_gpu_instance();

Getting Started

  1. Clone the repository:

    git clone https://github.com/Tencent/ncnn.git
    
  2. Build the project:

    cd ncnn
    mkdir build && cd build
    cmake ..
    make
    
  3. Include ncnn in your project:

    #include "net.h"
    
  4. Link against the built library and include the necessary headers in your project's build configuration.

Competitor Comparisons

15,699

MNN: A blazing-fast, lightweight inference engine battle-tested by Alibaba, powering high-performance on-device LLMs and Edge AI.

Pros of MNN

  • Supports a wider range of platforms, including iOS, Android, Windows, Linux, and macOS
  • Offers more comprehensive model conversion tools, supporting various deep learning frameworks
  • Provides a higher-level API for easier integration and usage

Cons of MNN

  • Generally slower performance compared to ncnn, especially on mobile devices
  • Larger binary size, which may impact app size more significantly
  • Less focus on minimalism and lightweight design

Code Comparison

MNN example:

auto interpreter = std::shared_ptr<Interpreter>(Interpreter::createFromFile(modelPath));
auto session = interpreter->createSession();
auto input = interpreter->getSessionInput(session, nullptr);
interpreter->runSession(session);

ncnn example:

ncnn::Net net;
net.load_param("model.param");
net.load_model("model.bin");
ncnn::Mat in(224, 224, 3);
ncnn::Mat out;
net.extract("output", out);

Both libraries aim to provide efficient neural network inference on mobile and embedded devices. ncnn focuses on minimalism and performance, particularly excelling on mobile platforms. MNN offers broader platform support and more comprehensive tools but may sacrifice some performance for flexibility. The choice between them depends on specific project requirements, target platforms, and performance needs.

5,042

MACE is a deep learning inference framework optimized for mobile heterogeneous computing platforms.

Pros of mace

  • Supports a wider range of deep learning frameworks, including TensorFlow, Caffe, and ONNX
  • Provides comprehensive performance optimization for various mobile platforms
  • Offers a user-friendly command-line interface for model conversion and deployment

Cons of mace

  • Larger library size compared to ncnn
  • Steeper learning curve for beginners due to more complex architecture
  • Less frequent updates and community contributions

Code Comparison

mace:

MaceEngine mace_engine(device_type);
mace_engine.Init(net_def, input_nodes, output_nodes, device_context);
mace_engine.Run(inputs, &outputs);

ncnn:

ncnn::Net net;
net.load_param("model.param");
net.load_model("model.bin");
ncnn::Extractor ex = net.create_extractor();
ex.input("input", in);
ex.extract("output", out);

Both libraries provide straightforward APIs for loading and running models, but mace's interface is slightly more verbose. ncnn's approach is more compact and may be easier for quick implementations. However, mace's structure allows for more flexibility in specifying device types and contexts, which can be beneficial for complex deployment scenarios.

4,526

Tengine is a lite, high performance, modular inference engine for embedded device

Pros of Tengine

  • Supports a wider range of hardware platforms, including ARM, RISC-V, and x86
  • Offers a more comprehensive set of operators and network models
  • Provides better support for quantization and model compression techniques

Cons of Tengine

  • Less optimized for mobile devices compared to ncnn
  • Smaller community and fewer third-party contributions
  • Documentation may be less comprehensive or up-to-date

Code Comparison

ncnn:

ncnn::Net net;
net.load_param("model.param");
net.load_model("model.bin");
ncnn::Mat in = ncnn::Mat::from_pixels(image_data, ncnn::Mat::PIXEL_BGR, w, h);
ncnn::Mat out;
net.extract("output", out);

Tengine:

graph_t graph = create_graph(NULL, "tengine", "model.tmfile");
tensor_t input_tensor = get_graph_input_tensor(graph, 0, 0);
set_tensor_shape(input_tensor, dims, 4);
set_tensor_buffer(input_tensor, input_data, img_size);
run_graph(graph, 1);
tensor_t output_tensor = get_graph_output_tensor(graph, 0, 0);

Both repositories focus on efficient neural network inference on various platforms, with ncnn being more specialized for mobile devices and Tengine offering broader hardware support. The code examples demonstrate the different approaches to loading and running models in each framework.

The Compute Library is a set of computer vision and machine learning functions optimised for both Arm CPUs and GPUs using SIMD technologies.

Pros of ComputeLibrary

  • Optimized for ARM architectures, providing excellent performance on ARM-based devices
  • Comprehensive support for various neural network operations and algorithms
  • Extensive documentation and examples for easier integration

Cons of ComputeLibrary

  • Limited cross-platform support compared to ncnn's wider compatibility
  • Steeper learning curve due to its more complex API and architecture
  • Larger codebase and potentially higher resource requirements

Code Comparison

ncnn:

ncnn::Net net;
net.load_param("model.param");
net.load_model("model.bin");

ncnn::Mat in(224, 224, 3);
ncnn::Mat out;
net.extract("input", in, "output", out);

ComputeLibrary:

arm_compute::graph::Graph graph;
arm_compute::graph::frontend::Stream stream(graph);
stream << arm_compute::graph::frontend::InputLayer(input_shape)
       << arm_compute::graph::frontend::ConvolutionLayer(...)
       << arm_compute::graph::frontend::OutputLayer();

Both libraries offer efficient neural network inference on mobile and embedded devices. ncnn focuses on cross-platform compatibility and ease of use, while ComputeLibrary provides optimized performance specifically for ARM architectures with a more comprehensive set of operations.

13,579

Open Machine Learning Compiler Framework

Pros of TVM

  • More comprehensive and flexible, supporting a wider range of hardware targets and optimization techniques
  • Offers automatic optimization and tuning capabilities for better performance across different platforms
  • Provides a higher-level API and supports multiple frontend frameworks (e.g., TensorFlow, PyTorch)

Cons of TVM

  • Steeper learning curve due to its complexity and extensive features
  • Larger codebase and potentially higher resource requirements for compilation and deployment

Code Comparison

TVM example (Python):

import tvm
from tvm import relay

# Define a simple network
data = relay.var("data", relay.TensorType((1, 3, 224, 224), "float32"))
weight = relay.var("weight")
conv2d = relay.nn.conv2d(data, weight)
func = relay.Function([data, weight], conv2d)

# Compile the network
target = "llvm"
with tvm.transform.PassContext(opt_level=3):
    lib = relay.build(func, target)

NCNN example (C++):

#include "net.h"

ncnn::Net net;
net.load_param("model.param");
net.load_model("model.bin");

ncnn::Mat in(224, 224, 3);
ncnn::Mat out;
net.extract("output", out, in);

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

ncnn

ncnn

License Download Total Count codecov

ncnn is a high-performance neural network inference framework optimized for mobile, embedded, and desktop deployment. It has no third-party runtime dependencies, runs across CPU and Vulkan GPU backends, and provides tools such as pnnx for converting PyTorch and ONNX models to ncnn. Developers can deploy deep learning models efficiently on phones, PCs, browsers, and edge devices. ncnn is currently being used in many Tencent applications, such as QQ, Qzone, WeChat, Pitu, and so on.

ncnn 是一个面向移动端、嵌入式和桌面端部署优化的高性能神经网络推理框架。 ncnn 无第三方运行时依赖,支持 CPU 和 Vulkan GPU 后端,并提供 pnnx 等工具将 PyTorch 和 ONNX 模型转换为 ncnn 模型。 基于 ncnn,开发者可以将深度学习模型高效部署到手机、PC、浏览器和边缘设备上。 ncnn 目前已在腾讯多款应用中使用,如:QQ,Qzone,微信,天天 P 图等。


Quick Start

The recommended beginner path is PyTorch -> pnnx -> ncnn.

Install pnnx in a PyTorch environment

pip3 install pnnx

Export a PyTorch model to ncnn

import torch
import torch.nn as nn
import pnnx

class Model(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv = nn.Conv2d(3, 8, 1)
        self.relu = nn.ReLU()
        self.fc = nn.Linear(8, 4)

    def forward(self, x):
        x = self.conv(x)
        x = self.relu(x)
        x = x.mean((2, 3))
        return self.fc(x)

model = Model().eval()

x = torch.rand(1, 3, 224, 224)
pnnx.export(model, "model.pt", (x,))

This generates model.ncnn.param and model.ncnn.bin.

Run with ncnn C++ API

#include "net.h"

ncnn::Net net;
net.load_param("model.ncnn.param");
net.load_model("model.ncnn.bin");

ncnn::Mat in(224, 224, 3);

auto ex = net.create_extractor();
ex.input("in0", in);

ncnn::Mat out;
ex.extract("out0", out);

Or use Python

import numpy as np
import ncnn

net = ncnn.Net()
net.load_param("model.ncnn.param")
net.load_model("model.ncnn.bin")

x = np.zeros((3, 224, 224), np.float32)
mat = ncnn.Mat(x)

ex = net.create_extractor()
ex.input("in0", mat)

ret, out = ex.extract("out0")
print(np.array(out).shape)

See pnnx, use ncnn with PyTorch or ONNX, Python API, and examples for complete workflows.


Community

技术交流 QQ 群
637093648 (超多大佬)
答案:卷卷卷卷卷(已满)
Telegram Group

https://t.me/ncnnyes

Discord Channel

https://discord.gg/YRsxgmF

Pocky QQ 群(MLIR YES!)
677104663 (超多大佬)
答案:multi-level intermediate representation
他们都不知道 pnnx 有多好用群
818998520 (新群!)

Download & Build status

https://github.com/Tencent/ncnn/releases/latest

how to build ncnn library on Linux / Windows / macOS / Raspberry Pi3, Pi4 / POWER / Android / NVIDIA Jetson / iOS / WebAssembly / AllWinner D1 / Loongson 2K1000

Source

Android

Android shared

HarmonyOS

HarmonyOS shared

iOS

iOS-Simulator

macOS

Mac-Catalyst

watchOS

watchOS-Simulator

tvOS

tvOS-Simulator

visionOS

visionOS-Simulator

Apple xcframework

Ubuntu 22.04

Ubuntu 24.04

windows
VS2015

VS2017

VS2019

VS2022

WebAssembly

Linux (arm)

Linux (aarch64)

Linux (mips)

Linux (mips64)

Linux (ppc64)

Linux (riscv64)

Linux (loongarch64)


Build

Use the prebuilt packages above when possible. To build from source, see the full how to build ncnn library guide for Linux, Windows, macOS, Android, iOS, WebAssembly, HarmonyOS, Raspberry Pi, Jetson, and embedded targets.

Common Linux build:

git clone --recursive https://github.com/Tencent/ncnn.git
cd ncnn
mkdir build && cd build
cmake -DCMAKE_BUILD_TYPE=Release -DNCNN_VULKAN=ON -DNCNN_BUILD_EXAMPLES=ON ..
cmake --build . -j$(nproc)

Model Conversion

Source modelRecommended pathDocs
PyTorchpnnx.export(model, "model.pt", (input_tensor,)) or pnnx model.pt inputshape=[...]pnnx, PyTorch / ONNX guide
ONNXpnnx model.onnxpnnx, onnx tools
ncnn model optimizationncnnoptimize model.param model.bin new.param new.bin flagquantization, model file spec
Legacy Caffe / MXNet / DarknetUse compatibility converters when maintaining older modelscaffe, mxnet, darknet, AlexNet legacy tutorial

Use Netron to inspect .param, .onnx, and .pnnx.param graphs.


Features

  • No third-party runtime dependencies and no BLAS / NNPACK requirement.
  • Pure C++ implementation with C API and Python binding.
  • Optimized CPU inference for mobile and embedded processors, including ARM NEON and multi-core scheduling.
  • Vulkan GPU acceleration for supported platforms.
  • Low memory footprint with explicit blob/workspace allocator design.
  • Supports multi-input, multi-output, and multi-branch graphs.
  • PyTorch and ONNX conversion through pnnx, plus legacy converter support for older model formats.
  • Supports fp16 storage/arithmetic paths, int8 quantized inference, model optimization, and custom layers.
  • Direct memory reference loading for .param and .bin models.

Model and Workload Coverage

ncnn is still strong for classic and mobile CNN workloads, but current usage is broader than CNN-only deployment.

For operator-level detail, see supported PyTorch operator status, supported ONNX operator status, and operation param weight table.


Project Examples

AreaProject
Image generationzimage-ncnn-vulkan - Z-Image generation with ncnn and Vulkan
LLM / embedding / vision-languagencnn_llm - LLM, embedding, and vision-language examples with ncnn
Android classificationncnn-android-squeezenet
Android style transferncnn-android-styletransfer
Android detectionncnn-android-mobilenetssd, ncnn-android-yolov5, ncnn-android-yolov7, ncnn-android-scrfd
Face detectionmtcnn_ncnn
Qt / Android integrationqt_android_ncnn_lib_encrypt_example
Colorizationncnn-colorization-siggraph17
Fortran bindingncnn-fortran
Speech recognitionsherpa - real-time speech recognition on embedded and mobile devices

Documentation And FAQ

TopicLinks
Buildhow to build
PyTorch / ONNX conversionuse ncnn with PyTorch or ONNX, pnnx, PyTorch converter notes
API and examplesC++ examples, Python API, low-level operation API
Model formatparam and model file spec, operation param weight table
Extensioncustom layer guide, plugin tools
FAQdeepwiki, throw error, wrong result, Vulkan
Legacy beginner materialuse ncnn with AlexNet, AlexNet Chinese tutorial

License

BSD 3 Clause