char-fork/llama.cpp

git clone https://git.t4t.associates/char-fork/llama.cpp

Mendy Bergerggml-webgpu: Update to a recent version of Dawn (#28683)d3146f2b5

char/aliceai-t5-moe
41.2 KiB845 linesraw

Build llama.cpp locally

The main product of this project is the llama library. Its C-style interface can be found in include/llama.h.

The project also includes many example programs and tools using the llama library. The examples range from simple, minimal code snippets to sophisticated sub-projects such as an OpenAI-compatible HTTP server.

To get the Code:

git clone https://github.com/ggml-org/llama.cpp
cd llama.cpp

The following sections describe how to build with different backends and options.

CPU Build

Build llama.cpp using CMake:

cmake -B build
cmake --build build --config Release

Notes:

  • For faster compilation, add the -j argument to run multiple jobs in parallel, or use a generator that does this automatically such as Ninja. For example, cmake --build build --config Release -j 8 will run 8 jobs in parallel.

  • For faster repeated compilation, install ccache

  • For debug builds, there are two cases:

    1. Single-config generators (e.g. default = Unix Makefiles; note that they just ignore the --config flag):

      cmake -B build -DCMAKE_BUILD_TYPE=Debug
      cmake --build build
    2. Multi-config generators (-G param set to Visual Studio, XCode...):

      cmake -B build -G "Xcode"
      cmake --build build --config Debug

    For more details and a list of supported generators, see the CMake documentation.

  • For static builds, add -DBUILD_SHARED_LIBS=OFF:

    cmake -B build -DBUILD_SHARED_LIBS=OFF
    cmake --build build --config Release
    
  • Building for Windows (x86, x64 and arm64) with MSVC or clang as compilers:

    • Install Visual Studio 2022, e.g. via the Community Edition. In the installer, select at least the following options (this also automatically installs the required additional tools like CMake,...):
    • Tab Workload: Desktop-development with C++
    • Tab Components (select quickly via search): C++-CMake Tools for Windows, Git for Windows, C++-Clang Compiler for Windows, MS-Build Support for LLVM-Toolset (clang)
    • Please remember to always use a Developer Command Prompt / PowerShell for VS2022 for git, build, test
    • For Windows on ARM (arm64, WoA), build with:
      cmake --preset arm64-windows-llvm-release -D GGML_OPENMP_FETCH=ON
      cmake --build build-arm64-windows-llvm-release
      • Use ARM64 Native Tools Command Prompt for VS 2022 if you are building on an ARM64 machine.
      • GGML_OPENMP_FETCH downloads the official LLVM OpenMP runtime and requires Clang, 7-Zip and network access during configuration. CMake selects the runtime from the target architecture, so this also works when cross-compiling for WoA from x64. The extracted header, import library, DLL and OpenMP license are placed under build/_deps. The build copies libomp.dll and LICENSE-LLVM-OpenMP to the runtime output directory and installs them together. Omit the option to use CMake's normal OpenMP detection, or pass -D GGML_OPENMP=OFF to disable OpenMP.
    • For building with ninja generator and clang compiler as default:
      • Set path:
        set LIB=C:\Program Files (x86)\Windows Kits\10\Lib\10.0.22621.0\um\x64;C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.41.34120\lib\x64\uwp;C:\Program Files (x86)\Windows Kits\10\Lib\10.0.22621.0\ucrt\x64
        
      • Run:
        cmake --preset x64-windows-llvm-release
        cmake --build build-x64-windows-llvm-release
  • If you want HTTPS/TLS features, you may install OpenSSL development libraries. If not installed, the project will build and run without SSL support.

    • Debian / Ubuntu: sudo apt-get install libssl-dev
    • Fedora / RHEL / Rocky / Alma: sudo dnf install openssl-devel
    • Arch / Manjaro: sudo pacman -S openssl

BLAS Build

Building the program with BLAS support may lead to some performance improvements in prompt processing using batch sizes higher than 32 (the default is 512). Using BLAS doesn't affect the generation performance. There are currently several different BLAS implementations available for build and use:

Accelerate Framework

This is only available on Mac PCs and it's enabled by default. You can just build using the normal instructions.

OpenBLAS

This provides BLAS acceleration using only the CPU. Make sure to have OpenBLAS installed on your machine.

  • Using CMake on Linux:

    cmake -B build -DGGML_BLAS=ON -DGGML_BLAS_VENDOR=OpenBLAS
    cmake --build build --config Release

BLIS

Check BLIS.md for more information.

Intel oneMKL

Building through oneAPI compilers will make avx_vnni instruction set available for intel processors that do not support avx512 and avx512_vnni. Please note that this build config does not support Intel GPU. For Intel GPU support, please refer to llama.cpp for SYCL.

  • Using manual oneAPI installation: By default, GGML_BLAS_VENDOR is set to Generic, so if you already sourced intel environment script and assign -DGGML_BLAS=ON in cmake, the mkl version of Blas will automatically been selected. Otherwise please install oneAPI and follow the below steps:

    source /opt/intel/oneapi/setvars.sh # You can skip this step if  in oneapi-basekit docker image, only required for manual installation
    cmake -B build -DGGML_BLAS=ON -DGGML_BLAS_VENDOR=Intel10_64lp -DCMAKE_C_COMPILER=icx -DCMAKE_CXX_COMPILER=icpx -DGGML_NATIVE=ON
    cmake --build build --config Release
  • Using oneAPI docker image: If you do not want to source the environment vars and install oneAPI manually, you can also build the code using intel docker container: oneAPI-basekit. Then, you can use the commands given above.

Check Optimizing and Running LLaMA2 on Intel® CPU for more information.

Other BLAS libraries

Any other BLAS library can be used by setting the GGML_BLAS_VENDOR option. See the CMake documentation for a list of supported vendors.

Metal Build

On MacOS, Metal is enabled by default. Using Metal makes the computation run on the GPU. To disable the Metal build at compile time use the -DGGML_METAL=OFF cmake option.

When built with Metal support, you can explicitly disable GPU inference with the --n-gpu-layers 0 command-line argument.

SYCL

SYCL is a higher-level programming model to improve programming productivity on various hardware accelerators.

llama.cpp based on SYCL is used to support Intel GPU (Data Center Max series, Flex series, Arc series, Built-in GPU and iGPU).

For detailed info, please refer to llama.cpp for SYCL.

CUDA

This provides GPU acceleration using an NVIDIA GPU. Make sure to have the CUDA toolkit installed.

Download directly from NVIDIA

You may find the official downloads here: NVIDIA developer site.

Compile and run inside a Fedora Toolbox Container

We also have a guide for setting up CUDA toolkit in a Fedora toolbox container.

Recommended for:

Compilation

Make sure to read the notes about the CPU build for general instructions for e.g. speeding up the compilation.

cmake -B build -DGGML_CUDA=ON
cmake --build build --config Release

Non-Native Builds

By default llama.cpp will be built for the hardware that is connected to the system at that time. For a build covering all CUDA GPUs, disable GGML_NATIVE:

cmake -B build -DGGML_CUDA=ON -DGGML_NATIVE=OFF

The resulting binary should run on all CUDA GPUs with optimal performance, though some just-in-time compilation may be required.

Override Compute Capability Specifications

If nvcc cannot detect your gpu, you may get compile warnings such as:

nvcc warning : Cannot find valid GPU for '-arch=native', default arch is used

One option is to do a non-native build as described above. However, this will result in a large binary that takes a long time to compile. Alternatively it is also possible to explicitly specify CUDA architectures. This may also make sense for a non-native build, for that one should look at the logic in ggml/src/ggml-cuda/CMakeLists.txt as a starting point.

To override the default CUDA architectures:

1. Take note of the Compute Capability of your NVIDIA devices: "CUDA: Your GPU Compute > Capability".

GeForce RTX 4090      8.9
GeForce RTX 3080 Ti   8.6
GeForce RTX 3070      8.6

2. Manually list each varying Compute Capability in the CMAKE_CUDA_ARCHITECTURES list.

cmake -B build -DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES="86;89"

Overriding the CUDA Version

If you have multiple CUDA installations on your system and want to compile llama.cpp for a specific one, e.g. for CUDA 11.7 installed under /opt/cuda-11.7:

cmake -B build -DGGML_CUDA=ON -DCMAKE_CUDA_COMPILER=/opt/cuda-11.7/bin/nvcc -DCMAKE_INSTALL_RPATH="/opt/cuda-11.7/lib64;\$ORIGIN" -DCMAKE_BUILD_WITH_INSTALL_RPATH=ON

Fixing Compatibility Issues with Old CUDA and New glibc

If you try to use an old CUDA version (e.g. v11.7) with a new glibc version you can get errors like this:

/usr/include/bits/mathcalls.h(83): error: exception specification is
  incompatible with that of previous function "cospi"


  /opt/cuda-11.7/bin/../targets/x86_64-linux/include/crt/math_functions.h(5545):
  here

It seems the least bad solution is to patch the CUDA installation to declare the correct signatures. Replace the following lines in /path/to/your/cuda/installation/targets/x86_64-linux/include/crt/math_functions.h:

// original lines
extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double                 cospi(double x);
extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float                  cospif(float x);
extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double                 sinpi(double x);
extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float                  sinpif(float x);
extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double                 rsqrt(double x);
extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float                  rsqrtf(float x);

// edited lines
extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double                 cospi(double x) noexcept (true);
extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float                  cospif(float x) noexcept (true);
extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double                 sinpi(double x) noexcept (true);
extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float                  sinpif(float x) noexcept (true);
extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double                 rsqrt(double x) noexcept (true);
extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float                  rsqrtf(float x) noexcept (true);

Runtime CUDA environmental variables

You may set the cuda environmental variables at runtime.

# Use `CUDA_VISIBLE_DEVICES` to hide the first compute device.
CUDA_VISIBLE_DEVICES="-0" ./build/bin/llama-server --model /srv/models/llama.gguf

CUDA_SCALE_LAUNCH_QUEUES

The environment variable CUDA_SCALE_LAUNCH_QUEUES controls the size of CUDA's command buffer, which determines how many GPU operations can be queued before the CPU must wait for the GPU to catch up. A larger buffer reduces CPU-side stalls and allows more work to be queued on a GPU.

Consider setting CUDA_SCALE_LAUNCH_QUEUES=4x, which increases the CUDA command buffer to 4 times its default size. This optimization is particularly beneficial for Multi-GPU setups with pipeline parallelism, where it significantly improves prompt processing throughput by allowing more operations to be enqueued across GPUs.

GGML_CUDA_CUBLAS_COMPUTE_TYPE

Override default, speed-optimized compute types for cuBLAS matrix multiplications. Legal values: auto, f16, fp16, bf16, f32, fp32.

Unified Memory

The environment variable GGML_CUDA_ENABLE_UNIFIED_MEMORY=1 can be used to enable unified memory in Linux. This allows swapping to system RAM instead of crashing when the GPU VRAM is exhausted. In Windows this setting is available in the NVIDIA control panel as System Memory Fallback.

Peer Access

The environment variable GGML_CUDA_P2P can be set to enable peer-to-peer access between multiple GPUs, allowing them to transfer data directly rather than to go through system memory. Requires driver support (usually restricted to workstation/datacenter GPUs). May cause crashes or corrupted outputs for some motherboards and BIOS settings (e.g. IOMMU).

Performance Tuning

The following compilation options are also available to tweak performance:

OptionLegal valuesDefaultDescription
GGML_CUDA_FORCE_MMQBooleanfalseForce the use of custom matrix multiplication kernels for quantized models instead of FP16 cuBLAS even if there is no int8 tensor core implementation available (affects V100, CDNA and RDNA3+). MMQ kernels are enabled by default on GPUs with int8 tensor core support. With MMQ force enabled, speed for large batch sizes will be worse but VRAM consumption will be lower.
GGML_CUDA_FORCE_CUBLASBooleanfalseForce the use of FP16 cuBLAS instead of custom matrix multiplication kernels for quantized models. There may be issues with numerical overflows (except for V100, CDNA and RDNA4 which use FP32 compute type by default) and memory use will be higher. Prompt processing may become faster on recent datacenter GPUs (the custom kernels were tuned primarily for RTX 3000/4000).
GGML_CUDA_FA_QUANTSall or type_K-type_V listq4_0-q4_0;q8_0-q8_0;f16-f16;bf16-bf16Select which K/V type combinations to compile the FlashAttention CUDA kernels for. all compiles every combination, but compilation takes much longer. Otherwise a ;-separated list of type_K-type_V pairs; f16-f16 is always compiled. Combinations that were not compiled fall back to f16-f16 kernel with a warning. Legal types: f16, bf16, q4_0, q4_1, q5_0, q5_1, q8_0.
GGML_CUDA_FA_ALL_QUANTSBooleanfalseDeprecated alias for GGML_CUDA_FA_QUANTS=all.

MUSA

This provides GPU acceleration using a Moore Threads GPU. Make sure to have the MUSA SDK installed.

Download directly from Moore Threads

You may find the official downloads here: Moore Threads developer site.

Compilation

cmake -B build -DGGML_MUSA=ON
cmake --build build --config Release

Override Compute Capability Specifications

By default, all supported compute capabilities are enabled. To customize this behavior, you can specify the MUSA_ARCHITECTURES option in the CMake command:

cmake -B build -DGGML_MUSA=ON -DMUSA_ARCHITECTURES="21"
cmake --build build --config Release

This configuration enables only compute capability 2.1 (MTT S80) during compilation, which can help reduce compilation time.

Compilation options

Most of the compilation options available for CUDA should also be available for MUSA, though they haven't been thoroughly tested yet.

  • For static builds, add -DBUILD_SHARED_LIBS=OFF and -DCMAKE_POSITION_INDEPENDENT_CODE=ON:
    cmake -B build -DGGML_MUSA=ON \
      -DBUILD_SHARED_LIBS=OFF -DCMAKE_POSITION_INDEPENDENT_CODE=ON
    cmake --build build --config Release
    

Runtime MUSA environmental variables

You may set the musa environmental variables at runtime.

# Use `MUSA_VISIBLE_DEVICES` to hide the first compute device.
MUSA_VISIBLE_DEVICES="-0" ./build/bin/llama-server --model /srv/models/llama.gguf

Unified Memory

The environment variable GGML_CUDA_ENABLE_UNIFIED_MEMORY=1 can be used to enable unified memory in Linux. This allows swapping to system RAM instead of crashing when the GPU VRAM is exhausted.

HIP

This provides GPU acceleration on HIP-supported AMD GPUs. Make sure to have ROCm installed. You can download it from your Linux distro's package manager or from here: ROCm Quick Start (Linux).

  • Using CMake for Linux (assuming a gfx1030-compatible AMD GPU):

    HIPCXX="$(hipconfig -l)/clang" HIP_PATH="$(hipconfig -R)" \
        cmake -S . -B build -DGGML_HIP=ON -DGPU_TARGETS=gfx1030 -DCMAKE_BUILD_TYPE=Release \
        && cmake --build build --config Release -- -j 16

    Note: GPU_TARGETS is optional, omitting it will build the code for all GPUs in the current system.

    Note that if you get the following error:

    clang: error: cannot find ROCm device library; provide its path via '--rocm-path' or '--rocm-device-lib-path', or pass '-nogpulib' to build without ROCm device library
    

    Try searching for a directory under HIP_PATH that contains the file oclc_abi_version_400.bc. Then, add the following to the start of the command: HIP_DEVICE_LIB_PATH=<directory-you-just-found>, so something like:

    HIPCXX="$(hipconfig -l)/clang" HIP_PATH="$(hipconfig -p)" \
    HIP_DEVICE_LIB_PATH=<directory-you-just-found> \
        cmake -S . -B build -DGGML_HIP=ON -DGPU_TARGETS=gfx1030 -DCMAKE_BUILD_TYPE=Release \
        && cmake --build build -- -j 16
  • Using CMake for Windows (using x64 Native Tools Command Prompt for VS, and assuming a gfx1100-compatible AMD GPU):

    set PATH=%HIP_PATH%\bin;%PATH%
    cmake -S . -B build -G Ninja -DGPU_TARGETS=gfx1100 -DGGML_HIP=ON -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ -DCMAKE_BUILD_TYPE=Release
    cmake --build build

    If necessary, adapt GPU_TARGETS to the GPU arch you want to compile for. The above example uses gfx1100 that corresponds to Radeon RX 7900XTX/XT/GRE. You can find a list of targets here Find your gpu version string by matching the most significant version information from rocminfo | grep gfx | head -1 | awk '{print $2}' with the list of processors, e.g. gfx1035 maps to gfx1030.

The environment variable HIP_VISIBLE_DEVICES can be used to specify which GPU(s) will be used. If your GPU is not officially supported you can use the environment variable [HSA_OVERRIDE_GFX_VERSION] set to a similar GPU, for example 10.3.0 on RDNA2 (e.g. gfx1030, gfx1031, or gfx1035) or 11.0.0 on RDNA3. Note that [HSA_OVERRIDE_GFX_VERSION] is not supported on Windows

Unified Memory

On Linux it is possible to use unified memory architecture (UMA) to share main memory between the CPU and integrated GPU by setting environment variable GGML_CUDA_ENABLE_UNIFIED_MEMORY=1. However, this hurts performance for non-integrated GPUs (but enables working with integrated GPUs).

Vulkan

For Windows Users:

w64devkit

Download and extract w64devkit.

Download and install the Vulkan SDK with the default settings.

Launch w64devkit.exe and run the following commands to copy Vulkan dependencies:

SDK_VERSION=1.3.283.0
cp /VulkanSDK/$SDK_VERSION/Bin/glslc.exe $W64DEVKIT_HOME/bin/
cp /VulkanSDK/$SDK_VERSION/Lib/vulkan-1.lib $W64DEVKIT_HOME/x86_64-w64-mingw32/lib/
cp -r /VulkanSDK/$SDK_VERSION/Include/* $W64DEVKIT_HOME/x86_64-w64-mingw32/include/
cat > $W64DEVKIT_HOME/x86_64-w64-mingw32/lib/pkgconfig/vulkan.pc <<EOF
Name: Vulkan-Loader
Description: Vulkan Loader
Version: $SDK_VERSION
Libs: -lvulkan-1
EOF

Switch into the llama.cpp directory and build using CMake.

cmake -B build -DGGML_VULKAN=ON
cmake --build build --config Release

Git Bash MINGW64

Download and install Git-SCM with the default settings

Download and install Visual Studio Community Edition and make sure you select C++

Download and install CMake with the default settings

Download and install the Vulkan SDK with the default settings.

Go into your llama.cpp directory and right click, select Open Git Bash Here and then run the following commands

cmake -B build -DGGML_VULKAN=ON
cmake --build build --config Release

Now you can load the model in conversation mode using Vulkan

build/bin/Release/llama-cli -m "[PATH TO MODEL]" -ngl 100 -c 16384 -t 10 -n -2 -cnv

MSYS2

Install MSYS2 and then run the following commands in a UCRT terminal to install dependencies.

pacman -S git \
    mingw-w64-ucrt-x86_64-gcc \
    mingw-w64-ucrt-x86_64-cmake \
    mingw-w64-ucrt-x86_64-vulkan-devel \
    mingw-w64-ucrt-x86_64-shaderc \
    mingw-w64-ucrt-x86_64-spirv-headers

Switch into the llama.cpp directory and build using CMake.

cmake -B build -DGGML_VULKAN=ON
cmake --build build --config Release

For Docker users:

You don't need to install the Vulkan SDK. It will be installed inside the container.

# Build the image
docker build -t llama-cpp-vulkan --target light -f .devops/vulkan.Dockerfile .

# Then, use it:
docker run -it --rm -v "$(pwd):/app:Z" --device /dev/dri/renderD128:/dev/dri/renderD128 --device /dev/dri/card1:/dev/dri/card1 llama-cpp-vulkan -m "/app/models/YOUR_MODEL_FILE" -p "Building a website can be done in 10 simple steps:" -n 400 -e -ngl 33

For Linux users:

Using the LunarG Vulkan SDK

First, follow the official LunarG instructions for the installation and setup of the Vulkan SDK in the Getting Started with the Linux Tarball Vulkan SDK guide.

[!IMPORTANT] After completing the first step, ensure that you have used the source command on the setup_env.sh file inside of the Vulkan SDK in your current terminal session. Otherwise, the build won't work. Additionally, if you close out of your terminal, you must perform this step again if you intend to perform a build. However, there are ways to make this persistent. Refer to the Vulkan SDK guide linked in the first step for more information about any of this.

Using system packages

On Debian / Ubuntu, you can install the required dependencies using:

sudo apt-get install libvulkan-dev glslc spirv-headers

SPIRV-Headers (spirv/unified1/spirv.hpp) are required for the Vulkan backend and are not always pulled in by the Vulkan loader dev package alone. Other distros use names such as spirv-headers (Ubuntu / Debian / Arch), or spirv-headers-devel (Fedora / openSUSE). On Windows, the LunarG Vulkan SDK’s Include directory already contains these headers.

Common steps

Second, after verifying that you have followed all of the SDK installation/setup steps, use this command to make sure before proceeding:

vulkaninfo

Then, assuming you have cd into your llama.cpp folder and there are no errors with running vulkaninfo, you can proceed to build llama.cpp using the CMake commands below:

cmake -B build -DGGML_VULKAN=1
cmake --build build --config Release

Finally, after finishing your build, you should be able to do something like this:

# Test the output binary
# "-ngl 99" should offload all of the layers to GPU for most (if not all) models.
./build/bin/llama-cli -m "PATH_TO_MODEL" -p "Hi you how are you" -ngl 99

# You should see in the output, ggml_vulkan detected your GPU. For example:
# ggml_vulkan: Using Intel(R) Graphics (ADL GT2) | uma: 1 | fp16: 1 | warp size: 32

For Mac users:

Generally, follow LunarG's Getting Started with the MacOS Vulkan SDK guide for installation and setup of the Vulkan SDK. There are two options of Vulkan drivers on macOS, both of which implement translation layers to map Vulkan to Metal. They can be hot-swapped by setting the VK_ICD_FILENAMES environment variable to point to the respective ICD JSON file.

Check the box for "KosmicKrisp" during the LunarG Vulkan SDK installation.

Set environment variable for the LunarG Vulkan SDK after installation (and optionally add to your shell profile for persistence):

source /path/to/vulkan-sdk/setup-env.sh

Using MoltenVK

MoltenVK is the default Vulkan driver installed with the LunarG Vulkan SDK on macOS, so you can use the above environment variable settings as is.

Using KosmicKrisp

Override the environment variable for KosmicKrisp:

export VK_ICD_FILENAMES=$VULKAN_SDK/share/vulkan/icd.d/libkosmickrisp_icd.json
export VK_DRIVER_FILES=$VULKAN_SDK/share/vulkan/icd.d/libkosmickrisp_icd.json

Build

This is the only step different from above instructions.

cmake -B build -DGGML_VULKAN=1 -DGGML_METAL=OFF
cmake --build build --config Release

CANN

This provides NPU acceleration using the AI cores of your Ascend NPU. And CANN is a hierarchical APIs to help you to quickly build AI applications and service based on Ascend NPU.

For more information about Ascend NPU in Ascend Community.

Make sure to have the CANN toolkit installed. You can download it from here: CANN Toolkit

Go to llama.cpp directory and build using CMake.

cmake -B build -DGGML_CANN=on -DCMAKE_BUILD_TYPE=release
cmake --build build --config release

You can test with:

./build/bin/llama-cli -m PATH_TO_MODEL -p "Building a website can be done in 10 steps:" -ngl 32

If the following info is output on screen, you are using llama.cpp with the CANN backend:

llm_load_tensors:       CANN model buffer size = 13313.00 MiB
llama_new_context_with_model:       CANN compute buffer size =  1260.81 MiB

For detailed info, such as model/device supports, CANN install, please refer to llama.cpp for CANN.

ZenDNN

ZenDNN provides optimized deep learning primitives for AMD EPYC™ CPUs. It accelerates matrix multiplication operations for inference workloads.

Compilation

  • Using CMake on Linux (automatic build):

    cmake -B build -DGGML_ZENDNN=ON
    cmake --build build --config Release

    The first build will automatically download and build ZenDNN, which may take 5-10 minutes. Subsequent builds will be much faster.

  • Using CMake with custom ZenDNN installation:

    cmake -B build -DGGML_ZENDNN=ON -DZENDNN_ROOT=/path/to/zendnn/install
    cmake --build build --config Release

Testing

You can test with:

./build/bin/llama-cli -m PATH_TO_MODEL -p "Building a website can be done in 10 steps:" -n 50

For detailed information about hardware support, setup instructions, and performance optimization, refer to llama.cpp for ZenDNN.

Arm® KleidiAI™

KleidiAI provides optimized Arm CPU microkernels used by the ggml CPU backend. Enabling it at build time makes those kernels available; it does not force every operation to use KleidiAI. At runtime, llama.cpp selects the best compatible CPU kernel from the detected CPU features, tensor type, operation shape, and active backend priority.

Supported targets:

PlatformSupported ABI / architectureNotes
LinuxAArch64 / arm64Runtime CPU feature detection is automatic.
Androidarm64-v8aUse the Android NDK command below for a portable build.
Applearm64Runtime CPU feature detection is automatic. Non-streaming SVE vector length is treated as unavailable.
Windowsarm64Runtime CPU feature detection is automatic. SMCU count is treated as unknown until a detection path is verified.

GGML_CPU_KLEIDIAI=ON is valid only for AArch64/arm64 builds. Do not enable it for x86, 32-bit Arm, or Android ABIs other than arm64-v8a.

Native AArch64/arm64 build

From the llama.cpp source directory:

cmake -S . -B build -DGGML_CPU_KLEIDIAI=ON
cmake --build build --config Release

Android arm64-v8a NDK build

Set ANDROID_NDK to the Android NDK root, then run the following from the llama.cpp source directory. This command configures a portable Android arm64-v8a build with KleidiAI enabled and avoids Android dependencies that are not part of the NDK stable native API set.

cmake -S . -B build-android \
  -DCMAKE_BUILD_TYPE=Release \
  -DCMAKE_TOOLCHAIN_FILE="$ANDROID_NDK/build/cmake/android.toolchain.cmake" \
  -DANDROID_ABI=arm64-v8a \
  -DANDROID_PLATFORM=android-28 \
  -DGGML_CPU_KLEIDIAI=ON \
  -DGGML_NATIVE=OFF \
  -DGGML_OPENMP=OFF \
  -DGGML_LLAMAFILE=OFF \
  -DLLAMA_OPENSSL=OFF
cmake --build build-android --config Release --parallel
cmake --install build-android --prefix {install-dir} --config Release

Important Android options:

  • GGML_CPU_KLEIDIAI=ON enables KleidiAI for Android arm64-v8a.
  • GGML_NATIVE=OFF is required for cross-compilation because the build host CPU is not the Android target CPU.
  • GGML_OPENMP=OFF avoids adding an OpenMP runtime dependency to this NDK command-line build.
  • GGML_LLAMAFILE=OFF avoids the llamafile backend, which is not supported on Android.
  • LLAMA_OPENSSL=OFF avoids depending on OpenSSL, which is not part of the Android NDK stable native API set.

The Android Studio project under examples/llama.android enables KleidiAI automatically for arm64-v8a. For Android command-line CMake builds on arm64-v8a, pass -DGGML_CPU_KLEIDIAI=ON explicitly.

Global -march flags such as -march=armv8.7a flag are not required for a portable Android arm64-v8a build. Global -march flags raise the baseline instruction set for generic code. No manual architecture-specific source selection is required; llama.cpp selects compatible KleidiAI kernels at runtime. The KleidiAI libraries internal CMake handles the -march flags for each particular kernel.

Verifying the build

Run an installed or in-tree binary:

./build/bin/llama-cli -m PATH_TO_MODEL -p "What is a car?"

If KleidiAI is enabled, the output contains a line similar to:

load_tensors: CPU_KLEIDIAI model buffer size =  3474.00 MiB

This confirms that the model has tensors allocated through the KleidiAI CPU buffer. It does not prove that every operation, or any specific SME-family operation, used a KleidiAI microkernel. Runtime CPU features, tensor type, operation shape, and backend priority still control dispatch.

Depending on the build target, another backend may have higher priority than the CPU backend. To force CPU execution for a run, disable higher priority backends at build time, for example -DGGML_METAL=OFF, or use a runtime device option such as --device none where supported.

Runtime dispatch

KleidiAI microkernels use Arm CPU features such as dotprod, i8mm, SVE, and SME/SME2. Build-time configuration makes the kernels available. Runtime dispatch selects a compatible kernel for the detected CPU and operation. Older or lower-feature CPUs fall back automatically to compatible kernels.

KleidiAI accelerates selected GGML_OP_MUL_MAT paths for F32 and common quantized formats. Exact coverage depends on the bundled KleidiAI version and the llama.cpp runtime selector, so unsupported tensor types, unsupported operation shapes, or higher priority backends may bypass KleidiAI even when the CPU supports the required Arm feature. This is also why a model may not use SME-family kernels on SME-capable hardware.

The current llama.cpp KleidiAI SVE selector only enables SVE kernels when the runtime SVE vector length is known to be QK8_0 bytes, currently 32 bytes. Linux and Android query this at runtime. Apple reports SVE capability separately from userspace non-streaming SVE availability, so llama.cpp treats the SVE vector length as unknown there. Windows exposes SVE feature presence but not the runtime SVE vector length used by this selector, so that value is also treated as unknown. Windows arm64 also treats SMCU count as unknown until a detection mechanism is verified.

The set of available SME-family kernels depends on the bundled KleidiAI version and the detected CPU capabilities. Production configuration does not require any KleidiAI runtime environment variables.

Diagnostics and debug overrides

KleidiAI runtime environment variables are diagnostics/debug overrides, not production configuration. Leave them unset for normal use.

GGML_KLEIDIAI_SME controls SME-family kernel selection and overrides the maximum number of threads assigned to selected quantized SME-family kernels:

  • Not set: use automatic runtime detection.
  • 0: disable SME-family kernels.
  • <n> > 0: enable compatible SME-family kernels and allow up to <n> threads for quantized SME-family kernels.

On Windows arm64, use GGML_KLEIDIAI_SME=<n> as the temporary diagnostics/debug override for SME thread-cap calibration until automatic SMCU count detection is verified.

If the CPU does not support the required SME-family capability for a bundled kernel, that kernel is disabled regardless of the environment variable.

OpenCL

This provides GPU acceleration through OpenCL on recent Adreno GPU. More information about OpenCL backend can be found in OPENCL.md for more information.

Android

Assume NDK is available in $ANDROID_NDK. First, install OpenCL headers and ICD loader library if not available,

mkdir -p ~/dev/llm
cd ~/dev/llm

git clone https://github.com/KhronosGroup/OpenCL-Headers && \
cd OpenCL-Headers && \
cp -r CL $ANDROID_NDK/toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/include

cd ~/dev/llm

git clone https://github.com/KhronosGroup/OpenCL-ICD-Loader && \
cd OpenCL-ICD-Loader && \
mkdir build_ndk && cd build_ndk && \
cmake .. -G Ninja -DCMAKE_BUILD_TYPE=Release \
  -DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK/build/cmake/android.toolchain.cmake \
  -DOPENCL_ICD_LOADER_HEADERS_DIR=$ANDROID_NDK/toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/include \
  -DANDROID_ABI=arm64-v8a \
  -DANDROID_PLATFORM=24 \
  -DANDROID_STL=c++_shared && \
ninja && \
cp libOpenCL.so $ANDROID_NDK/toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/lib/aarch64-linux-android

Then build llama.cpp with OpenCL enabled,

cd ~/dev/llm

git clone https://github.com/ggml-org/llama.cpp && \
cd llama.cpp && \
mkdir build-android && cd build-android

cmake .. -G Ninja \
  -DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK/build/cmake/android.toolchain.cmake \
  -DANDROID_ABI=arm64-v8a \
  -DANDROID_PLATFORM=android-28 \
  -DBUILD_SHARED_LIBS=OFF \
  -DGGML_OPENCL=ON

ninja

Windows Arm64

First, install OpenCL headers and ICD loader library if not available,

mkdir -p ~/dev/llm

cd ~/dev/llm
git clone https://github.com/KhronosGroup/OpenCL-Headers && cd OpenCL-Headers
mkdir build && cd build
cmake .. -G Ninja `
  -DBUILD_TESTING=OFF `
  -DOPENCL_HEADERS_BUILD_TESTING=OFF `
  -DOPENCL_HEADERS_BUILD_CXX_TESTS=OFF `
  -DCMAKE_INSTALL_PREFIX="$HOME/dev/llm/opencl"
cmake --build . --target install

cd ~/dev/llm
git clone https://github.com/KhronosGroup/OpenCL-ICD-Loader && cd OpenCL-ICD-Loader
mkdir build && cd build
cmake .. -G Ninja `
  -DCMAKE_BUILD_TYPE=Release `
  -DCMAKE_PREFIX_PATH="$HOME/dev/llm/opencl" `
  -DCMAKE_INSTALL_PREFIX="$HOME/dev/llm/opencl"
cmake --build . --target install

Then build llama.cpp with OpenCL enabled,

cmake .. -G Ninja `
  -DCMAKE_TOOLCHAIN_FILE="$HOME/dev/llm/llama.cpp/cmake/arm64-windows-llvm.cmake" `
  -DCMAKE_BUILD_TYPE=Release `
  -DCMAKE_PREFIX_PATH="$HOME/dev/llm/opencl" `
  -DBUILD_SHARED_LIBS=OFF `
  -DGGML_OPENCL=ON
ninja

Android

To read documentation for how to build on Android, click here

WebGPU

The WebGPU backend relies on Dawn. Follow the instructions here to install Dawn locally so that llama.cpp can find it using CMake. The current implementation is up-to-date with Dawn commit 94c3c9c.

In the llama.cpp directory, build with CMake:

cmake -B build -DGGML_WEBGPU=ON
cmake --build build --config Release

Browser Support

WebGPU allows cross-platform access to the GPU from supported browsers. We utilize Emscripten to compile ggml's WebGPU backend to WebAssembly. Emscripten does not officially support WebGPU bindings yet, but Dawn currently maintains its own WebGPU bindings called emdawnwebgpu.

Follow the instructions here to download or build the emdawnwebgpu package (Note that it might be safer to build the emdawnwebgpu package locally, so that it stays in sync with the version of Dawn you have installed above). When building using CMake, the path to the emdawnwebgpu port file needs to be set with the flag EMDAWNWEBGPU_DIR.

IBM Z & LinuxONE

To read documentation for how to build on IBM Z & LinuxONE, click here

OpenVINO

OpenVINO is an open-source toolkit for optimizing and deploying high-performance AI inference, specifically designed for Intel hardware (CPUs, GPUs, and NPUs).

For build instructions and usage examples, refer to OPENVINO.md.

Hexagon

Check README.md for target specific build and run info.


Notes about GPU-accelerated backends

The GPU may still be used to accelerate some parts of the computation even when using the -ngl 0 option. You can fully disable GPU acceleration by using --device none.

In most cases, it is possible to build and use multiple backends at the same time. For example, you can build llama.cpp with both CUDA and Vulkan support by using the -DGGML_CUDA=ON -DGGML_VULKAN=ON options with CMake. At runtime, you can specify which backend devices to use with the --device option. To see a list of available devices, use the --list-devices option.

Backends can be built as dynamic libraries that can be loaded dynamically at runtime. This allows you to use the same llama.cpp binary on different machines with different GPUs. To enable this feature, use the GGML_BACKEND_DL option when building.

1# Build llama.cpp locally
2
3The main product of this project is the `llama` library. Its C-style interface can be found in [include/llama.h](../include/llama.h).
4
5The project also includes many example programs and tools using the `llama` library. The examples range from simple, minimal code snippets to sophisticated sub-projects such as an OpenAI-compatible HTTP server.
6
7**To get the Code:**
8
9```bash
10git clone https://github.com/ggml-org/llama.cpp
11cd llama.cpp
12```
13
14The following sections describe how to build with different backends and options.
15
16* [CPU Build](#cpu-build)
17* [BLAS Build](#blas-build)
18* [Metal Build](#metal-build)
19* [SYCL](#sycl)
20* [CUDA](#cuda)
21* [MUSA](#musa)
22* [HIP](#hip)
23* [Vulkan](#vulkan)
24* [CANN](#cann)
25* [ZenDNN](#zendnn)
26* [Arm® KleidiAI™](#arm-kleidiai)
27* [OpenCL](#opencl)
28* [Android](#android-1)
29* [OpenVINO](#openvino)
30* [Hexagon](#hexagon)
31* [Notes about GPU-accelerated backends](#notes-about-gpu-accelerated-backends)
32
33## CPU Build
34
35Build llama.cpp using `CMake`:
36
37```bash
38cmake -B build
39cmake --build build --config Release
40```
41
42**Notes**:
43
44- For faster compilation, add the `-j` argument to run multiple jobs in parallel, or use a generator that does this automatically such as Ninja. For example, `cmake --build build --config Release -j 8` will run 8 jobs in parallel.
45- For faster repeated compilation, install [ccache](https://ccache.dev/)
46- For debug builds, there are two cases:
47
48    1. Single-config generators (e.g. default = `Unix Makefiles`; note that they just ignore the `--config` flag):
49
50       ```bash
51       cmake -B build -DCMAKE_BUILD_TYPE=Debug
52       cmake --build build
53       ```
54
55    2. Multi-config generators (`-G` param set to Visual Studio, XCode...):
56
57       ```bash
58       cmake -B build -G "Xcode"
59       cmake --build build --config Debug
60       ```
61
62    For more details and a list of supported generators, see the [CMake documentation](https://cmake.org/cmake/help/latest/manual/cmake-generators.7.html).
63- For static builds, add `-DBUILD_SHARED_LIBS=OFF`:
64  ```
65  cmake -B build -DBUILD_SHARED_LIBS=OFF
66  cmake --build build --config Release
67  ```
68
69- Building for Windows (x86, x64 and arm64) with MSVC or clang as compilers:
70    - Install Visual Studio 2022, e.g. via the [Community Edition](https://visualstudio.microsoft.com/vs/community/). In the installer, select at least the following options (this also automatically installs the required additional tools like CMake,...):
71    - Tab Workload: Desktop-development with C++
72    - Tab Components (select quickly via search): C++-_CMake_ Tools for Windows, _Git_ for Windows, C++-_Clang_ Compiler for Windows, MS-Build Support for LLVM-Toolset (clang)
73    - Please remember to always use a Developer Command Prompt / PowerShell for VS2022 for git, build, test
74    - For Windows on ARM (arm64, WoA), build with:
75      ```bash
76      cmake --preset arm64-windows-llvm-release -D GGML_OPENMP_FETCH=ON
77      cmake --build build-arm64-windows-llvm-release
78      ```
79      - Use `ARM64 Native Tools Command Prompt for VS 2022` if you are building on an ARM64 machine.
80      - `GGML_OPENMP_FETCH` downloads the official LLVM OpenMP runtime and requires Clang, 7-Zip and network access during configuration. CMake selects the runtime from the target architecture, so this also works when cross-compiling for WoA from x64. The extracted header, import library, DLL and OpenMP license are placed under `build/_deps`. The build copies `libomp.dll` and `LICENSE-LLVM-OpenMP` to the runtime output directory and installs them together. Omit the option to use CMake's normal OpenMP detection, or pass `-D GGML_OPENMP=OFF` to disable OpenMP.
81    - For building with ninja generator and clang compiler as default:
82      - Set path:
83        ```
84        set LIB=C:\Program Files (x86)\Windows Kits\10\Lib\10.0.22621.0\um\x64;C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.41.34120\lib\x64\uwp;C:\Program Files (x86)\Windows Kits\10\Lib\10.0.22621.0\ucrt\x64
85        ```
86      - Run:
87        ```bash
88        cmake --preset x64-windows-llvm-release
89        cmake --build build-x64-windows-llvm-release
90        ```
91- If you want HTTPS/TLS features, you may install OpenSSL development libraries. If not installed, the project will build and run without SSL support.
92  - **Debian / Ubuntu:** `sudo apt-get install libssl-dev`
93  - **Fedora / RHEL / Rocky / Alma:** `sudo dnf install openssl-devel`
94  - **Arch / Manjaro:** `sudo pacman -S openssl`
95
96## BLAS Build
97
98Building the program with BLAS support may lead to some performance improvements in prompt processing using batch sizes higher than 32 (the default is 512). Using BLAS doesn't affect the generation performance. There are currently several different BLAS implementations available for build and use:
99
100### Accelerate Framework
101
102This is only available on Mac PCs and it's enabled by default. You can just build using the normal instructions.
103
104### OpenBLAS
105
106This provides BLAS acceleration using only the CPU. Make sure to have OpenBLAS installed on your machine.
107
108- Using `CMake` on Linux:
109
110    ```bash
111    cmake -B build -DGGML_BLAS=ON -DGGML_BLAS_VENDOR=OpenBLAS
112    cmake --build build --config Release
113    ```
114
115### BLIS
116
117Check [BLIS.md](./backend/BLIS.md) for more information.
118
119### Intel oneMKL
120
121Building through oneAPI compilers will make avx_vnni instruction set available for intel processors that do not support avx512 and avx512_vnni. Please note that this build config **does not support Intel GPU**. For Intel GPU support, please refer to [llama.cpp for SYCL](./backend/SYCL.md).
122
123- Using manual oneAPI installation:
124  By default, `GGML_BLAS_VENDOR` is set to `Generic`, so if you already sourced intel environment script and assign `-DGGML_BLAS=ON` in cmake, the mkl version of Blas will automatically been selected. Otherwise please install oneAPI and follow the below steps:
125    ```bash
126    source /opt/intel/oneapi/setvars.sh # You can skip this step if  in oneapi-basekit docker image, only required for manual installation
127    cmake -B build -DGGML_BLAS=ON -DGGML_BLAS_VENDOR=Intel10_64lp -DCMAKE_C_COMPILER=icx -DCMAKE_CXX_COMPILER=icpx -DGGML_NATIVE=ON
128    cmake --build build --config Release
129    ```
130
131- Using oneAPI docker image:
132  If you do not want to source the environment vars and install oneAPI manually, you can also build the code using intel docker container: [oneAPI-basekit](https://hub.docker.com/r/intel/oneapi-basekit). Then, you can use the commands given above.
133
134Check [Optimizing and Running LLaMA2 on Intel® CPU](https://builders.intel.com/solutionslibrary/optimizing-and-running-llama2-on-intel-cpu) for more information.
135
136### Other BLAS libraries
137
138Any other BLAS library can be used by setting the `GGML_BLAS_VENDOR` option. See the [CMake documentation](https://cmake.org/cmake/help/latest/module/FindBLAS.html#blas-lapack-vendors) for a list of supported vendors.
139
140## Metal Build
141
142On MacOS, Metal is enabled by default. Using Metal makes the computation run on the GPU.
143To disable the Metal build at compile time use the `-DGGML_METAL=OFF` cmake option.
144
145When built with Metal support, you can explicitly disable GPU inference with the `--n-gpu-layers 0` command-line argument.
146
147## SYCL
148
149SYCL is a higher-level programming model to improve programming productivity on various hardware accelerators.
150
151llama.cpp based on SYCL is used to **support Intel GPU** (Data Center Max series, Flex series, Arc series, Built-in GPU and iGPU).
152
153For detailed info, please refer to [llama.cpp for SYCL](./backend/SYCL.md).
154
155## CUDA
156
157This provides GPU acceleration using an NVIDIA GPU. Make sure to have the [CUDA toolkit](https://developer.nvidia.com/cuda-toolkit) installed.
158
159#### Download directly from NVIDIA
160You may find the official downloads here: [NVIDIA developer site](https://developer.nvidia.com/cuda-downloads).
161
162
163#### Compile and run inside a Fedora Toolbox Container
164We also have a [guide](./backend/CUDA-FEDORA.md) for setting up CUDA toolkit in a Fedora [toolbox container](https://containertoolbx.org/).
165
166**Recommended for:**
167- ***Necessary*** for users of [Atomic Desktops for Fedora](https://fedoraproject.org/atomic-desktops/); such as: [Silverblue](https://fedoraproject.org/atomic-desktops/silverblue/) and [Kinoite](https://fedoraproject.org/atomic-desktops/kinoite/).
168  - (there are no supported CUDA packages for these systems)
169- ***Necessary*** for users that have a host that is not a: [Supported Nvidia CUDA Release Platform](https://developer.nvidia.com/cuda-downloads).
170  - (for example, you may have [Fedora 42 Beta](https://fedoramagazine.org/announcing-fedora-linux-42-beta/) as your host operating system)
171- ***Convenient*** For those running [Fedora Workstation](https://fedoraproject.org/workstation/) or [Fedora KDE Plasma Desktop](https://fedoraproject.org/spins/kde), and want to keep their host system clean.
172- *Optionally* toolbox packages are available: [Arch Linux](https://archlinux.org/), [Red Hat Enterprise Linux >= 8.5](https://www.redhat.com/en/technologies/linux-platforms/enterprise-linux), or [Ubuntu](https://ubuntu.com/download)
173
174
175### Compilation
176
177Make sure to read the notes about the CPU build for general instructions for e.g. speeding up the compilation.
178
179```bash
180cmake -B build -DGGML_CUDA=ON
181cmake --build build --config Release
182```
183
184### Non-Native Builds
185
186By default llama.cpp will be built for the hardware that is connected to the system at that time.
187For a build covering all CUDA GPUs, disable `GGML_NATIVE`:
188
189```bash
190cmake -B build -DGGML_CUDA=ON -DGGML_NATIVE=OFF
191```
192
193The resulting binary should run on all CUDA GPUs with optimal performance, though some just-in-time compilation may be required.
194
195### Override Compute Capability Specifications
196
197If `nvcc` cannot detect your gpu, you may get compile warnings such as:
198 ```text
199nvcc warning : Cannot find valid GPU for '-arch=native', default arch is used
200```
201
202One option is to do a non-native build as described above.
203However, this will result in a large binary that takes a long time to compile.
204Alternatively it is also possible to explicitly specify CUDA architectures.
205This may also make sense for a non-native build, for that one should look at the logic in `ggml/src/ggml-cuda/CMakeLists.txt` as a starting point.
206
207To override the default CUDA architectures:
208
209#### 1. Take note of the `Compute Capability` of your NVIDIA devices: ["CUDA: Your GPU Compute > Capability"](https://developer.nvidia.com/cuda-gpus).
210
211```text
212GeForce RTX 4090      8.9
213GeForce RTX 3080 Ti   8.6
214GeForce RTX 3070      8.6
215```
216
217#### 2. Manually list each varying `Compute Capability` in the `CMAKE_CUDA_ARCHITECTURES` list.
218
219```bash
220cmake -B build -DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES="86;89"
221```
222
223### Overriding the CUDA Version
224
225If you have multiple CUDA installations on your system and want to compile llama.cpp for a specific one, e.g. for CUDA 11.7 installed under `/opt/cuda-11.7`:
226
227```bash
228cmake -B build -DGGML_CUDA=ON -DCMAKE_CUDA_COMPILER=/opt/cuda-11.7/bin/nvcc -DCMAKE_INSTALL_RPATH="/opt/cuda-11.7/lib64;\$ORIGIN" -DCMAKE_BUILD_WITH_INSTALL_RPATH=ON
229```
230
231#### Fixing Compatibility Issues with Old CUDA and New glibc
232
233If you try to use an old CUDA version (e.g. v11.7) with a new glibc version you can get errors like this:
234
235```
236/usr/include/bits/mathcalls.h(83): error: exception specification is
237  incompatible with that of previous function "cospi"
238
239
240  /opt/cuda-11.7/bin/../targets/x86_64-linux/include/crt/math_functions.h(5545):
241  here
242```
243
244It seems the least bad solution is to patch the CUDA installation to declare the correct signatures.
245Replace the following lines in `/path/to/your/cuda/installation/targets/x86_64-linux/include/crt/math_functions.h`:
246
247```C++
248// original lines
249extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double                 cospi(double x);
250extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float                  cospif(float x);
251extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double                 sinpi(double x);
252extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float                  sinpif(float x);
253extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double                 rsqrt(double x);
254extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float                  rsqrtf(float x);
255
256// edited lines
257extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double                 cospi(double x) noexcept (true);
258extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float                  cospif(float x) noexcept (true);
259extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double                 sinpi(double x) noexcept (true);
260extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float                  sinpif(float x) noexcept (true);
261extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ double                 rsqrt(double x) noexcept (true);
262extern __DEVICE_FUNCTIONS_DECL__ __device_builtin__ float                  rsqrtf(float x) noexcept (true);
263```
264
265### Runtime CUDA environmental variables
266
267You may set the [cuda environmental variables](https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#env-vars) at runtime.
268
269```bash
270# Use `CUDA_VISIBLE_DEVICES` to hide the first compute device.
271CUDA_VISIBLE_DEVICES="-0" ./build/bin/llama-server --model /srv/models/llama.gguf
272```
273
274#### CUDA_SCALE_LAUNCH_QUEUES
275
276The environment variable [`CUDA_SCALE_LAUNCH_QUEUES`](https://docs.nvidia.com/cuda/cuda-programming-guide/05-appendices/environment-variables.html#cuda-scale-launch-queues) controls the size of CUDA's command buffer, which determines how many GPU operations can be queued before the CPU must wait for the GPU to catch up. A larger buffer reduces CPU-side stalls and allows more work to be queued on a GPU.
277
278Consider setting `CUDA_SCALE_LAUNCH_QUEUES=4x`, which increases the CUDA command buffer to 4 times its default size. This optimization is particularly beneficial for **Multi-GPU setups with pipeline parallelism**, where it significantly improves prompt processing throughput by allowing more operations to be enqueued across GPUs.
279
280#### GGML_CUDA_CUBLAS_COMPUTE_TYPE
281
282Override default, speed-optimized compute types for cuBLAS matrix multiplications.
283Legal values: `auto`, `f16`, `fp16`, `bf16`, `f32`, `fp32`.
284
285### Unified Memory
286
287The environment variable `GGML_CUDA_ENABLE_UNIFIED_MEMORY=1` can be used to enable unified memory in Linux. This allows swapping to system RAM instead of crashing when the GPU VRAM is exhausted. In Windows this setting is available in the NVIDIA control panel as `System Memory Fallback`.
288
289### Peer Access
290
291The environment variable `GGML_CUDA_P2P` can be set to enable peer-to-peer access between multiple GPUs, allowing them to transfer data directly rather than to go through system memory.
292Requires driver support (usually restricted to workstation/datacenter GPUs).
293May cause crashes or corrupted outputs for some motherboards and BIOS settings (e.g. IOMMU).
294
295### Performance Tuning
296
297The following compilation options are also available to tweak performance:
298
299| Option                        | Legal values           | Default | Description                                                                                                                                                                                                                                                                                                                                                                      |
300|-------------------------------|------------------------|---------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
301| GGML_CUDA_FORCE_MMQ           | Boolean                | false   | Force the use of custom matrix multiplication kernels for quantized models instead of FP16 cuBLAS even if there is no int8 tensor core implementation available (affects V100, CDNA and RDNA3+). MMQ kernels are enabled by default on GPUs with int8 tensor core support. With MMQ force enabled, speed for large batch sizes will be worse but VRAM consumption will be lower. |
302| GGML_CUDA_FORCE_CUBLAS        | Boolean                | false   | Force the use of FP16 cuBLAS instead of custom matrix multiplication kernels for quantized models. There may be issues with numerical overflows (except for V100, CDNA and RDNA4 which use FP32 compute type by default) and memory use will be higher. Prompt processing may become faster on recent datacenter GPUs (the custom kernels were tuned primarily for RTX 3000/4000).   |
303| GGML_CUDA_FA_QUANTS           | `all` or `type_K-type_V` list | q4_0-q4_0;q8_0-q8_0;f16-f16;bf16-bf16 | Select which K/V type combinations to compile the FlashAttention CUDA kernels for. `all` compiles every combination, but compilation takes much longer. Otherwise a `;`-separated list of `type_K-type_V` pairs; f16-f16 is always compiled. Combinations that were not compiled fall back to f16-f16 kernel with a warning. Legal types: f16, bf16, q4_0, q4_1, q5_0, q5_1, q8_0. |
304| GGML_CUDA_FA_ALL_QUANTS       | Boolean                | false   | Deprecated alias for `GGML_CUDA_FA_QUANTS=all`.                                                                                                                                                                                                                                                                                                                               |
305
306## MUSA
307
308This provides GPU acceleration using a Moore Threads GPU. Make sure to have the [MUSA SDK](https://developer.mthreads.com/musa/musa-sdk) installed.
309
310#### Download directly from Moore Threads
311
312You may find the official downloads here: [Moore Threads developer site](https://developer.mthreads.com/sdk/download/musa).
313
314### Compilation
315
316```bash
317cmake -B build -DGGML_MUSA=ON
318cmake --build build --config Release
319```
320
321#### Override Compute Capability Specifications
322
323By default, all supported compute capabilities are enabled. To customize this behavior, you can specify the `MUSA_ARCHITECTURES` option in the CMake command:
324
325```bash
326cmake -B build -DGGML_MUSA=ON -DMUSA_ARCHITECTURES="21"
327cmake --build build --config Release
328```
329
330This configuration enables only compute capability `2.1` (MTT S80) during compilation, which can help reduce compilation time.
331
332#### Compilation options
333
334Most of the compilation options available for CUDA should also be available for MUSA, though they haven't been thoroughly tested yet.
335
336- For static builds, add `-DBUILD_SHARED_LIBS=OFF` and `-DCMAKE_POSITION_INDEPENDENT_CODE=ON`:
337  ```
338  cmake -B build -DGGML_MUSA=ON \
339    -DBUILD_SHARED_LIBS=OFF -DCMAKE_POSITION_INDEPENDENT_CODE=ON
340  cmake --build build --config Release
341  ```
342
343### Runtime MUSA environmental variables
344
345You may set the [musa environmental variables](https://docs.mthreads.com/musa-sdk/musa-sdk-doc-online/programming_guide/Z%E9%99%84%E5%BD%95/) at runtime.
346
347```bash
348# Use `MUSA_VISIBLE_DEVICES` to hide the first compute device.
349MUSA_VISIBLE_DEVICES="-0" ./build/bin/llama-server --model /srv/models/llama.gguf
350```
351
352### Unified Memory
353
354The environment variable `GGML_CUDA_ENABLE_UNIFIED_MEMORY=1` can be used to enable unified memory in Linux. This allows swapping to system RAM instead of crashing when the GPU VRAM is exhausted.
355
356## HIP
357
358This provides GPU acceleration on HIP-supported AMD GPUs.
359Make sure to have ROCm installed.
360You can download it from your Linux distro's package manager or from here: [ROCm Quick Start (Linux)](https://rocm.docs.amd.com/projects/install-on-linux/en/latest/tutorial/quick-start.html#rocm-install-quick).
361
362- Using `CMake` for Linux (assuming a gfx1030-compatible AMD GPU):
363  ```bash
364  HIPCXX="$(hipconfig -l)/clang" HIP_PATH="$(hipconfig -R)" \
365      cmake -S . -B build -DGGML_HIP=ON -DGPU_TARGETS=gfx1030 -DCMAKE_BUILD_TYPE=Release \
366      && cmake --build build --config Release -- -j 16
367  ```
368
369  Note: `GPU_TARGETS` is optional, omitting it will build the code for all GPUs in the current system.
370
371  Note that if you get the following error:
372  ```
373  clang: error: cannot find ROCm device library; provide its path via '--rocm-path' or '--rocm-device-lib-path', or pass '-nogpulib' to build without ROCm device library
374  ```
375  Try searching for a directory under `HIP_PATH` that contains the file
376  `oclc_abi_version_400.bc`. Then, add the following to the start of the
377  command: `HIP_DEVICE_LIB_PATH=<directory-you-just-found>`, so something
378  like:
379  ```bash
380  HIPCXX="$(hipconfig -l)/clang" HIP_PATH="$(hipconfig -p)" \
381  HIP_DEVICE_LIB_PATH=<directory-you-just-found> \
382      cmake -S . -B build -DGGML_HIP=ON -DGPU_TARGETS=gfx1030 -DCMAKE_BUILD_TYPE=Release \
383      && cmake --build build -- -j 16
384  ```
385
386- Using `CMake` for Windows (using x64 Native Tools Command Prompt for VS, and assuming a gfx1100-compatible AMD GPU):
387  ```bash
388  set PATH=%HIP_PATH%\bin;%PATH%
389  cmake -S . -B build -G Ninja -DGPU_TARGETS=gfx1100 -DGGML_HIP=ON -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ -DCMAKE_BUILD_TYPE=Release
390  cmake --build build
391  ```
392  If necessary, adapt `GPU_TARGETS` to the GPU arch you want to compile for. The above example uses `gfx1100` that corresponds to Radeon RX 7900XTX/XT/GRE. You can find a list of targets [here](https://llvm.org/docs/AMDGPUUsage.html#processors)
393  Find your gpu version string by matching the most significant version information from `rocminfo | grep gfx | head -1 | awk '{print $2}'` with the list of processors, e.g. `gfx1035` maps to `gfx1030`.
394
395
396The environment variable [`HIP_VISIBLE_DEVICES`](https://rocm.docs.amd.com/en/latest/understand/gpu_isolation.html#hip-visible-devices) can be used to specify which GPU(s) will be used.
397If your GPU is not officially supported you can use the environment variable [`HSA_OVERRIDE_GFX_VERSION`] set to a similar GPU, for example 10.3.0 on RDNA2 (e.g. gfx1030, gfx1031, or gfx1035) or 11.0.0 on RDNA3. Note that [`HSA_OVERRIDE_GFX_VERSION`] is [not supported on Windows](https://github.com/ROCm/ROCm/issues/2654)
398
399### Unified Memory
400
401On Linux it is possible to use unified memory architecture (UMA) to share main memory between the CPU and integrated GPU by setting environment variable `GGML_CUDA_ENABLE_UNIFIED_MEMORY=1`. However, this hurts performance for non-integrated GPUs (but enables working with integrated GPUs).
402
403## Vulkan
404
405### For Windows Users:
406**w64devkit**
407
408Download and extract [`w64devkit`](https://github.com/skeeto/w64devkit/releases).
409
410Download and install the [`Vulkan SDK`](https://vulkan.lunarg.com/sdk/home#windows) with the default settings.
411
412Launch `w64devkit.exe` and run the following commands to copy Vulkan dependencies:
413```sh
414SDK_VERSION=1.3.283.0
415cp /VulkanSDK/$SDK_VERSION/Bin/glslc.exe $W64DEVKIT_HOME/bin/
416cp /VulkanSDK/$SDK_VERSION/Lib/vulkan-1.lib $W64DEVKIT_HOME/x86_64-w64-mingw32/lib/
417cp -r /VulkanSDK/$SDK_VERSION/Include/* $W64DEVKIT_HOME/x86_64-w64-mingw32/include/
418cat > $W64DEVKIT_HOME/x86_64-w64-mingw32/lib/pkgconfig/vulkan.pc <<EOF
419Name: Vulkan-Loader
420Description: Vulkan Loader
421Version: $SDK_VERSION
422Libs: -lvulkan-1
423EOF
424
425```
426
427Switch into the `llama.cpp` directory and build using CMake.
428```sh
429cmake -B build -DGGML_VULKAN=ON
430cmake --build build --config Release
431```
432
433**Git Bash MINGW64**
434
435Download and install [`Git-SCM`](https://git-scm.com/downloads/win) with the default settings
436
437Download and install [`Visual Studio Community Edition`](https://visualstudio.microsoft.com/) and make sure you select `C++`
438
439Download and install [`CMake`](https://cmake.org/download/) with the default settings
440
441Download and install the [`Vulkan SDK`](https://vulkan.lunarg.com/sdk/home#windows) with the default settings.
442
443Go into your `llama.cpp` directory and right click, select `Open Git Bash Here` and then run the following commands
444
445```
446cmake -B build -DGGML_VULKAN=ON
447cmake --build build --config Release
448```
449
450Now you can load the model in conversation mode using `Vulkan`
451
452```sh
453build/bin/Release/llama-cli -m "[PATH TO MODEL]" -ngl 100 -c 16384 -t 10 -n -2 -cnv
454```
455
456**MSYS2**
457
458Install [MSYS2](https://www.msys2.org/) and then run the following commands in a UCRT terminal to install dependencies.
459```sh
460pacman -S git \
461    mingw-w64-ucrt-x86_64-gcc \
462    mingw-w64-ucrt-x86_64-cmake \
463    mingw-w64-ucrt-x86_64-vulkan-devel \
464    mingw-w64-ucrt-x86_64-shaderc \
465    mingw-w64-ucrt-x86_64-spirv-headers
466```
467
468Switch into the `llama.cpp` directory and build using CMake.
469```sh
470cmake -B build -DGGML_VULKAN=ON
471cmake --build build --config Release
472```
473
474### For Docker users:
475
476You don't need to install the Vulkan SDK. It will be installed inside the container.
477
478```sh
479# Build the image
480docker build -t llama-cpp-vulkan --target light -f .devops/vulkan.Dockerfile .
481
482# Then, use it:
483docker run -it --rm -v "$(pwd):/app:Z" --device /dev/dri/renderD128:/dev/dri/renderD128 --device /dev/dri/card1:/dev/dri/card1 llama-cpp-vulkan -m "/app/models/YOUR_MODEL_FILE" -p "Building a website can be done in 10 simple steps:" -n 400 -e -ngl 33
484```
485
486### For Linux users:
487
488#### Using the LunarG Vulkan SDK
489
490First, follow the official LunarG instructions for the installation and setup of the Vulkan SDK in the [Getting Started with the Linux Tarball Vulkan SDK](https://vulkan.lunarg.com/doc/sdk/latest/linux/getting_started.html) guide.
491
492> [!IMPORTANT]
493> After completing the first step, ensure that you have used the `source` command on the `setup_env.sh` file inside of the Vulkan SDK in your current terminal session. Otherwise, the build won't work. Additionally, if you close out of your terminal, you must perform this step again if you intend to perform a build. However, there are ways to make this persistent. Refer to the Vulkan SDK guide linked in the first step for more information about any of this.
494
495#### Using system packages
496
497On Debian / Ubuntu, you can install the required dependencies using:
498```sh
499sudo apt-get install libvulkan-dev glslc spirv-headers
500```
501
502SPIRV-Headers (`spirv/unified1/spirv.hpp`) are required for the Vulkan backend and are **not** always pulled in by the Vulkan loader dev package alone. Other distros use names such as `spirv-headers` (Ubuntu / Debian / Arch), or `spirv-headers-devel` (Fedora / openSUSE). On Windows, the LunarG Vulkan SDK’s `Include` directory already contains these headers.
503
504#### Common steps
505
506Second, after verifying that you have followed all of the SDK installation/setup steps, use this command to make sure before proceeding:
507```bash
508vulkaninfo
509```
510
511Then, assuming you have `cd` into your llama.cpp folder and there are no errors with running `vulkaninfo`, you can proceed to build llama.cpp using the CMake commands below:
512```bash
513cmake -B build -DGGML_VULKAN=1
514cmake --build build --config Release
515```
516
517Finally, after finishing your build, you should be able to do something like this:
518```bash
519# Test the output binary
520# "-ngl 99" should offload all of the layers to GPU for most (if not all) models.
521./build/bin/llama-cli -m "PATH_TO_MODEL" -p "Hi you how are you" -ngl 99
522
523# You should see in the output, ggml_vulkan detected your GPU. For example:
524# ggml_vulkan: Using Intel(R) Graphics (ADL GT2) | uma: 1 | fp16: 1 | warp size: 32
525```
526
527### For Mac users:
528
529Generally, follow LunarG's [Getting Started with the MacOS Vulkan SDK](https://vulkan.lunarg.com/doc/sdk/latest/mac/getting_started.html) guide for installation and setup of the Vulkan SDK. There are two options of Vulkan drivers on macOS, both of which implement translation layers to map Vulkan to Metal. They can be hot-swapped by setting the `VK_ICD_FILENAMES` environment variable to point to the respective ICD JSON file.
530
531Check the box for "KosmicKrisp" during the LunarG Vulkan SDK installation.
532
533Set environment variable for the LunarG Vulkan SDK after installation (and optionally add to your shell profile for persistence):
534```bash
535source /path/to/vulkan-sdk/setup-env.sh
536```
537
538#### Using MoltenVK
539
540MoltenVK is the default Vulkan driver installed with the LunarG Vulkan SDK on macOS, so you can use the above environment variable settings as is.
541
542#### Using KosmicKrisp
543
544Override the environment variable for KosmicKrisp:
545```bash
546export VK_ICD_FILENAMES=$VULKAN_SDK/share/vulkan/icd.d/libkosmickrisp_icd.json
547export VK_DRIVER_FILES=$VULKAN_SDK/share/vulkan/icd.d/libkosmickrisp_icd.json
548```
549
550#### Build
551
552This is the only step different from [above](#common-steps) instructions.
553```bash
554cmake -B build -DGGML_VULKAN=1 -DGGML_METAL=OFF
555cmake --build build --config Release
556```
557
558## CANN
559This provides NPU acceleration using the AI cores of your Ascend NPU. And [CANN](https://www.hiascend.com/en/software/cann) is a hierarchical APIs to help you to quickly build AI applications and service based on Ascend NPU.
560
561For more information about Ascend NPU in [Ascend Community](https://www.hiascend.com/en/).
562
563Make sure to have the CANN toolkit installed. You can download it from here: [CANN Toolkit](https://www.hiascend.com/developer/download/community/result?module=cann)
564
565Go to `llama.cpp` directory and build using CMake.
566```bash
567cmake -B build -DGGML_CANN=on -DCMAKE_BUILD_TYPE=release
568cmake --build build --config release
569```
570
571You can test with:
572
573```bash
574./build/bin/llama-cli -m PATH_TO_MODEL -p "Building a website can be done in 10 steps:" -ngl 32
575```
576
577If the following info is output on screen, you are using `llama.cpp` with the CANN backend:
578```bash
579llm_load_tensors:       CANN model buffer size = 13313.00 MiB
580llama_new_context_with_model:       CANN compute buffer size =  1260.81 MiB
581```
582
583For detailed info, such as model/device supports, CANN install, please refer to [llama.cpp for CANN](./backend/CANN.md).
584
585## ZenDNN
586
587ZenDNN provides optimized deep learning primitives for AMD EPYC™ CPUs. It accelerates matrix multiplication operations for inference workloads.
588
589### Compilation
590
591- Using `CMake` on Linux (automatic build):
592
593    ```bash
594    cmake -B build -DGGML_ZENDNN=ON
595    cmake --build build --config Release
596    ```
597
598    The first build will automatically download and build ZenDNN, which may take 5-10 minutes. Subsequent builds will be much faster.
599
600- Using `CMake` with custom ZenDNN installation:
601
602    ```bash
603    cmake -B build -DGGML_ZENDNN=ON -DZENDNN_ROOT=/path/to/zendnn/install
604    cmake --build build --config Release
605    ```
606
607### Testing
608
609You can test with:
610
611```bash
612./build/bin/llama-cli -m PATH_TO_MODEL -p "Building a website can be done in 10 steps:" -n 50
613```
614
615For detailed information about hardware support, setup instructions, and performance optimization, refer to [llama.cpp for ZenDNN](./backend/ZenDNN.md).
616
617## Arm® KleidiAI™
618KleidiAI provides optimized Arm CPU microkernels used by the ggml CPU backend. Enabling it at build time makes those kernels available; it does not force every operation to use KleidiAI. At runtime, llama.cpp selects the best compatible CPU kernel from the detected CPU features, tensor type, operation shape, and active backend priority.
619
620Supported targets:
621
622| Platform | Supported ABI / architecture | Notes |
623| --- | --- | --- |
624| Linux | AArch64 / arm64 | Runtime CPU feature detection is automatic. |
625| Android | `arm64-v8a` | Use the Android NDK command below for a portable build. |
626| Apple | arm64 | Runtime CPU feature detection is automatic. Non-streaming SVE vector length is treated as unavailable. |
627| Windows | arm64 | Runtime CPU feature detection is automatic. SMCU count is treated as unknown until a detection path is verified. |
628
629`GGML_CPU_KLEIDIAI=ON` is valid only for AArch64/arm64 builds. Do not enable it for x86, 32-bit Arm, or Android ABIs other than `arm64-v8a`.
630
631### Native AArch64/arm64 build
632
633From the llama.cpp source directory:
634
635```bash
636cmake -S . -B build -DGGML_CPU_KLEIDIAI=ON
637cmake --build build --config Release
638```
639
640### Android arm64-v8a NDK build
641
642Set `ANDROID_NDK` to the Android NDK root, then run the following from the llama.cpp source directory. This command configures a portable Android `arm64-v8a` build with KleidiAI enabled and avoids Android dependencies that are not part of the NDK stable native API set.
643
644```bash
645cmake -S . -B build-android \
646  -DCMAKE_BUILD_TYPE=Release \
647  -DCMAKE_TOOLCHAIN_FILE="$ANDROID_NDK/build/cmake/android.toolchain.cmake" \
648  -DANDROID_ABI=arm64-v8a \
649  -DANDROID_PLATFORM=android-28 \
650  -DGGML_CPU_KLEIDIAI=ON \
651  -DGGML_NATIVE=OFF \
652  -DGGML_OPENMP=OFF \
653  -DGGML_LLAMAFILE=OFF \
654  -DLLAMA_OPENSSL=OFF
655cmake --build build-android --config Release --parallel
656cmake --install build-android --prefix {install-dir} --config Release
657```
658
659Important Android options:
660
661- `GGML_CPU_KLEIDIAI=ON` enables KleidiAI for Android `arm64-v8a`.
662- `GGML_NATIVE=OFF` is required for cross-compilation because the build host CPU is not the Android target CPU.
663- `GGML_OPENMP=OFF` avoids adding an OpenMP runtime dependency to this NDK command-line build.
664- `GGML_LLAMAFILE=OFF` avoids the llamafile backend, which is not supported on Android.
665- `LLAMA_OPENSSL=OFF` avoids depending on OpenSSL, which is not part of the Android NDK stable native API set.
666
667The Android Studio project under `examples/llama.android` enables KleidiAI automatically for `arm64-v8a`. For Android command-line CMake builds on `arm64-v8a`, pass `-DGGML_CPU_KLEIDIAI=ON` explicitly.
668
669Global -march flags such as `-march=armv8.7a` flag are not required for a portable Android `arm64-v8a` build. Global `-march` flags raise the baseline instruction set for generic code. No manual architecture-specific source selection is required; llama.cpp selects compatible KleidiAI kernels at runtime. The KleidiAI libraries internal CMake handles the -march flags for each particular kernel.
670
671### Verifying the build
672
673Run an installed or in-tree binary:
674
675```bash
676./build/bin/llama-cli -m PATH_TO_MODEL -p "What is a car?"
677```
678
679If KleidiAI is enabled, the output contains a line similar to:
680
681```
682load_tensors: CPU_KLEIDIAI model buffer size =  3474.00 MiB
683```
684
685This confirms that the model has tensors allocated through the KleidiAI CPU buffer. It does not prove that every operation, or any specific SME-family operation, used a KleidiAI microkernel. Runtime CPU features, tensor type, operation shape, and backend priority still control dispatch.
686
687Depending on the build target, another backend may have higher priority than the CPU backend. To force CPU execution for a run, disable higher priority backends at build time, for example `-DGGML_METAL=OFF`, or use a runtime device option such as `--device none` where supported.
688
689### Runtime dispatch
690
691KleidiAI microkernels use Arm CPU features such as dotprod, i8mm, SVE, and SME/SME2. Build-time configuration makes the kernels available. Runtime dispatch selects a compatible kernel for the detected CPU and operation. Older or lower-feature CPUs fall back automatically to compatible kernels.
692
693KleidiAI accelerates selected `GGML_OP_MUL_MAT` paths for F32 and common quantized formats. Exact coverage depends on the bundled KleidiAI version and the llama.cpp runtime selector, so unsupported tensor types, unsupported operation shapes, or higher priority backends may bypass KleidiAI even when the CPU supports the required Arm feature. This is also why a model may not use SME-family kernels on SME-capable hardware.
694
695The current llama.cpp KleidiAI SVE selector only enables SVE kernels when the runtime SVE vector length is known to be QK8_0 bytes, currently 32 bytes. Linux and Android query this at runtime. Apple reports SVE capability separately from userspace non-streaming SVE availability, so llama.cpp treats the SVE vector length as unknown there. Windows exposes SVE feature presence but not the runtime SVE vector length used by this selector, so that value is also treated as unknown. Windows arm64 also treats SMCU count as unknown until a detection mechanism is verified.
696
697The set of available SME-family kernels depends on the bundled KleidiAI version and the detected CPU capabilities. Production configuration does not require any KleidiAI runtime environment variables.
698
699### Diagnostics and debug overrides
700
701KleidiAI runtime environment variables are diagnostics/debug overrides, not production configuration. Leave them unset for normal use.
702
703`GGML_KLEIDIAI_SME` controls SME-family kernel selection and overrides the maximum number of threads assigned to selected quantized SME-family kernels:
704
705- Not set: use automatic runtime detection.
706- `0`: disable SME-family kernels.
707- `<n> > 0`: enable compatible SME-family kernels and allow up to `<n>` threads for quantized SME-family kernels.
708
709On Windows arm64, use `GGML_KLEIDIAI_SME=<n>` as the temporary diagnostics/debug override for SME thread-cap calibration until automatic SMCU count detection is verified.
710
711If the CPU does not support the required SME-family capability for a bundled kernel, that kernel is disabled regardless of the environment variable.
712
713## OpenCL
714
715This provides GPU acceleration through OpenCL on recent Adreno GPU.
716More information about OpenCL backend can be found in [OPENCL.md](./backend/OPENCL.md) for more information.
717
718### Android
719
720Assume NDK is available in `$ANDROID_NDK`. First, install OpenCL headers and ICD loader library if not available,
721
722```sh
723mkdir -p ~/dev/llm
724cd ~/dev/llm
725
726git clone https://github.com/KhronosGroup/OpenCL-Headers && \
727cd OpenCL-Headers && \
728cp -r CL $ANDROID_NDK/toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/include
729
730cd ~/dev/llm
731
732git clone https://github.com/KhronosGroup/OpenCL-ICD-Loader && \
733cd OpenCL-ICD-Loader && \
734mkdir build_ndk && cd build_ndk && \
735cmake .. -G Ninja -DCMAKE_BUILD_TYPE=Release \
736  -DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK/build/cmake/android.toolchain.cmake \
737  -DOPENCL_ICD_LOADER_HEADERS_DIR=$ANDROID_NDK/toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/include \
738  -DANDROID_ABI=arm64-v8a \
739  -DANDROID_PLATFORM=24 \
740  -DANDROID_STL=c++_shared && \
741ninja && \
742cp libOpenCL.so $ANDROID_NDK/toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/lib/aarch64-linux-android
743```
744
745Then build llama.cpp with OpenCL enabled,
746
747```sh
748cd ~/dev/llm
749
750git clone https://github.com/ggml-org/llama.cpp && \
751cd llama.cpp && \
752mkdir build-android && cd build-android
753
754cmake .. -G Ninja \
755  -DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK/build/cmake/android.toolchain.cmake \
756  -DANDROID_ABI=arm64-v8a \
757  -DANDROID_PLATFORM=android-28 \
758  -DBUILD_SHARED_LIBS=OFF \
759  -DGGML_OPENCL=ON
760
761ninja
762```
763
764### Windows Arm64
765
766First, install OpenCL headers and ICD loader library if not available,
767
768```powershell
769mkdir -p ~/dev/llm
770
771cd ~/dev/llm
772git clone https://github.com/KhronosGroup/OpenCL-Headers && cd OpenCL-Headers
773mkdir build && cd build
774cmake .. -G Ninja `
775  -DBUILD_TESTING=OFF `
776  -DOPENCL_HEADERS_BUILD_TESTING=OFF `
777  -DOPENCL_HEADERS_BUILD_CXX_TESTS=OFF `
778  -DCMAKE_INSTALL_PREFIX="$HOME/dev/llm/opencl"
779cmake --build . --target install
780
781cd ~/dev/llm
782git clone https://github.com/KhronosGroup/OpenCL-ICD-Loader && cd OpenCL-ICD-Loader
783mkdir build && cd build
784cmake .. -G Ninja `
785  -DCMAKE_BUILD_TYPE=Release `
786  -DCMAKE_PREFIX_PATH="$HOME/dev/llm/opencl" `
787  -DCMAKE_INSTALL_PREFIX="$HOME/dev/llm/opencl"
788cmake --build . --target install
789```
790
791Then build llama.cpp with OpenCL enabled,
792
793```powershell
794cmake .. -G Ninja `
795  -DCMAKE_TOOLCHAIN_FILE="$HOME/dev/llm/llama.cpp/cmake/arm64-windows-llvm.cmake" `
796  -DCMAKE_BUILD_TYPE=Release `
797  -DCMAKE_PREFIX_PATH="$HOME/dev/llm/opencl" `
798  -DBUILD_SHARED_LIBS=OFF `
799  -DGGML_OPENCL=ON
800ninja
801```
802
803## Android
804
805To read documentation for how to build on Android, [click here](./android.md)
806
807## WebGPU
808
809The WebGPU backend relies on [Dawn](https://dawn.googlesource.com/dawn). Follow the instructions [here](https://dawn.googlesource.com/dawn/+/refs/heads/main/docs/quickstart-cmake.md) to install Dawn locally so that llama.cpp can find it using CMake. The current implementation is up-to-date with Dawn commit `94c3c9c`.
810
811In the llama.cpp directory, build with CMake:
812
813```
814cmake -B build -DGGML_WEBGPU=ON
815cmake --build build --config Release
816```
817
818### Browser Support
819
820WebGPU allows cross-platform access to the GPU from supported browsers. We utilize [Emscripten](https://emscripten.org/) to compile ggml's WebGPU backend to WebAssembly. Emscripten does not officially support WebGPU bindings yet, but Dawn currently maintains its own WebGPU bindings called emdawnwebgpu.
821
822Follow the instructions [here](https://dawn.googlesource.com/dawn/+/refs/heads/main/src/emdawnwebgpu/) to download or build the emdawnwebgpu package (Note that it might be safer to build the emdawnwebgpu package locally, so that it stays in sync with the version of Dawn you have installed above). When building using CMake, the path to the emdawnwebgpu port file needs to be set with the flag `EMDAWNWEBGPU_DIR`.
823
824## IBM Z & LinuxONE
825
826To read documentation for how to build on IBM Z & LinuxONE, [click here](./build-s390x.md)
827
828## OpenVINO
829
830[OpenVINO](https://docs.openvino.ai/) is an open-source toolkit for optimizing and deploying high-performance AI inference, specifically designed for Intel hardware (CPUs, GPUs, and NPUs).
831
832For build instructions and usage examples, refer to [OPENVINO.md](backend/OPENVINO.md).
833
834### Hexagon
835
836Check [README.md](./backend/snapdragon/README.md) for target specific build and run info.
837
838---
839## Notes about GPU-accelerated backends
840
841The GPU may still be used to accelerate some parts of the computation even when using the `-ngl 0` option. You can fully disable GPU acceleration by using `--device none`.
842
843In most cases, it is possible to build and use multiple backends at the same time. For example, you can build llama.cpp with both CUDA and Vulkan support by using the `-DGGML_CUDA=ON -DGGML_VULKAN=ON` options with CMake. At runtime, you can specify which backend devices to use with the `--device` option. To see a list of available devices, use the `--list-devices` option.
844
845Backends can be built as dynamic libraries that can be loaded dynamically at runtime. This allows you to use the same llama.cpp binary on different machines with different GPUs. To enable this feature, use the `GGML_BACKEND_DL` option when building.