Author SHA1 Message Date
IrrelevantandGitHub e3b2925150 Revise contribution policy in README
Updated contribution guidelines in README.
2026-07-30 17:49:13 -05:00
IrrelevantandGitHub f6ebb06dc4 Update README.md 2026-07-30 17:47:20 -05:00
14 changed files with 48 additions and 1901 deletions
+5 -600
View File
@@ -1,604 +1,9 @@
# llama.cpp # Longhaul.cpp
![llama](https://raw.githubusercontent.com/ggml-org/llama.brand/refs/heads/master/cover/llama-cpp/cover-llama-cpp-dark.svg) This is a private fork that I decided to make public due to it working better than I expected.
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT) Do I recommend you use this for anything important? No. Is it cool? I like to think so.
[![Release](https://img.shields.io/github/v/release/ggml-org/llama.cpp)](https://github.com/ggml-org/llama.cpp/releases)
[![Server](https://github.com/ggml-org/llama.cpp/actions/workflows/server.yml/badge.svg)](https://github.com/ggml-org/llama.cpp/actions/workflows/server.yml)
[![Docker](https://github.com/ggml-org/llama.cpp/actions/workflows/docker.yml/badge.svg)](https://github.com/ggml-org/llama.cpp/actions/workflows/docker.yml)
[![Winget](https://github.com/ggml-org/llama.cpp/actions/workflows/winget.yml/badge.svg)](https://github.com/ggml-org/llama.cpp/actions/workflows/winget.yml)
[Manifesto](https://github.com/ggml-org/llama.cpp/discussions/205) / [ggml](https://github.com/ggml-org/ggml) / [ops](https://github.com/ggml-org/llama.cpp/blob/master/docs/ops.md) / [maintainer PRs](https://github.com/ggml-org/llama.cpp/issues?q=is%3Apr%20is%3Aopen%20draft%3AFalse%20(author%3Argerganov%20OR%20author%3AKitaitiMakoto%20OR%20author%3Adanbev%20OR%20author%3Aaldehir%20OR%20author%3Amax-krasnyansky%20OR%20author%3ACISC%20OR%20author%3Aggerganov%20OR%20author%3Aam17an%20OR%20author%3Abartowski1182%20OR%20author%3Ahipudding%20OR%20author%3AServeurpersoCom%20OR%20author%3Apwilkin%20OR%20author%3Areeselevine%20OR%20author%3Angxson%20OR%20author%3Ajeffbolznv%20OR%20author%3A0cc4m%20OR%20author%3Aangt%20OR%20author%3AIMbackK%20OR%20author%3Aarthw%20OR%20author%3AJohannesGaessler%20OR%20author%3AORippler%20OR%20author%3Aruixiang63%20OR%20author%3Axctan%20OR%20author%3Aallozaur%20OR%20author%3Ayomaytk%20OR%20author%3Aaendk%20OR%20author%3Agaugarg-nv%20OR%20author%3Ataronaeo%20OR%20author%3Aforforever73%20OR%20author%3Alhez%20OR%20author%3Anetrunnereve%20OR%20author%3Afairydreaming)%20sort%3Aupdated-desc) It only supports Metal at the moment.
LLM inference in C/C++ This is a personal project and because of this I have disabled open PRs. If you want to contribute, you can open an issue.
## Recent API changes
- [Changelog for `libllama` API](https://github.com/ggml-org/llama.cpp/issues/9289)
- [Changelog for `llama-server` REST API](https://github.com/ggml-org/llama.cpp/issues/9291)
## Hot topics
- **Hugging Face cache migration: models downloaded with `-hf` are now stored in the standard Hugging Face cache directory, enabling sharing with other HF tools.**
- **[guide : using the new WebUI of llama.cpp](https://github.com/ggml-org/llama.cpp/discussions/16938)**
- [guide : running gpt-oss with llama.cpp](https://github.com/ggml-org/llama.cpp/discussions/15396)
- [[FEEDBACK] Better packaging for llama.cpp to support downstream consumers 🤗](https://github.com/ggml-org/llama.cpp/discussions/15313)
- Support for the `gpt-oss` model with native MXFP4 format has been added | [PR](https://github.com/ggml-org/llama.cpp/pull/15091) | [Collaboration with NVIDIA](https://blogs.nvidia.com/blog/rtx-ai-garage-openai-oss) | [Comment](https://github.com/ggml-org/llama.cpp/discussions/15095)
- Multimodal support arrived in `llama-server`: [#12898](https://github.com/ggml-org/llama.cpp/pull/12898) | [documentation](./docs/multimodal.md)
- VS Code extension for FIM completions: https://github.com/ggml-org/llama.vscode
- Vim/Neovim plugin for FIM completions: https://github.com/ggml-org/llama.vim
- Hugging Face Inference Endpoints now support GGUF out of the box! https://github.com/ggml-org/llama.cpp/discussions/9669
- Hugging Face GGUF editor: [discussion](https://github.com/ggml-org/llama.cpp/discussions/9268) | [tool](https://huggingface.co/spaces/CISCai/gguf-editor)
- WebGPU support is now available in the browser, see a blog/demo introducing it [here](https://reeselevine.github.io/llamas-on-the-web/).
----
## Quick start
Getting started with llama.cpp is straightforward. Here are several ways to install it on your machine:
- Install `llama.cpp` using [brew, nix, winget, or conda-forge](docs/install.md)
- Run with Docker - see our [Docker documentation](docs/docker.md)
- Download pre-built binaries from the [releases page](https://github.com/ggml-org/llama.cpp/releases)
- Build from source by cloning this repository - check out [our build guide](docs/build.md)
Once installed, you'll need a model to work with. Head to the [Obtaining and quantizing models](#obtaining-and-quantizing-models) section to learn more.
Example command:
```sh
# Use a local model file
llama-cli -m my_model.gguf
# Or download and run a model directly from Hugging Face
llama-cli -hf ggml-org/gemma-3-1b-it-GGUF
# Launch OpenAI-compatible API server
llama-server -hf ggml-org/gemma-3-1b-it-GGUF
```
## Description
The main goal of `llama.cpp` is to enable LLM inference with minimal setup and state-of-the-art performance on a wide
range of hardware - locally and in the cloud.
- Plain C/C++ implementation without any dependencies
- Apple silicon is a first-class citizen - optimized via ARM NEON, Accelerate and Metal frameworks
- AVX, AVX2, AVX512 and AMX support for x86 architectures
- RVV, ZVFH, ZFH, ZICBOP and ZIHINTPAUSE support for RISC-V architectures
- 1.5-bit, 2-bit, 3-bit, 4-bit, 5-bit, 6-bit, and 8-bit integer quantization for faster inference and reduced memory use
- Custom CUDA kernels for running LLMs on NVIDIA GPUs (support for AMD GPUs via HIP and Moore Threads GPUs via MUSA)
- Vulkan and SYCL backend support
- CPU+GPU hybrid inference to partially accelerate models larger than the total VRAM capacity
The `llama.cpp` project is the main playground for developing new features for the [ggml](https://github.com/ggml-org/ggml) library.
<details>
<summary>Models</summary>
Typically finetunes of the base models below are supported as well.
Instructions for adding support for new models: [HOWTO-add-model.md](docs/development/HOWTO-add-model.md)
#### Text-only
- [X] LLaMA 🦙
- [x] LLaMA 2 🦙🦙
- [x] LLaMA 3 🦙🦙🦙
- [X] [Mistral 7B](https://huggingface.co/mistralai/Mistral-7B-v0.1)
- [x] [Mixtral MoE](https://huggingface.co/models?search=mistral-ai/Mixtral)
- [x] [DBRX](https://huggingface.co/databricks/dbrx-instruct)
- [x] [Jamba](https://huggingface.co/ai21labs)
- [X] [Falcon](https://huggingface.co/models?search=tiiuae/falcon)
- [X] [Chinese LLaMA / Alpaca](https://github.com/ymcui/Chinese-LLaMA-Alpaca) and [Chinese LLaMA-2 / Alpaca-2](https://github.com/ymcui/Chinese-LLaMA-Alpaca-2)
- [X] [Vigogne (French)](https://github.com/bofenghuang/vigogne)
- [X] [BERT](https://github.com/ggml-org/llama.cpp/pull/5423)
- [X] [Koala](https://bair.berkeley.edu/blog/2023/04/03/koala/)
- [X] [Baichuan 1 & 2](https://huggingface.co/models?search=baichuan-inc/Baichuan) + [derivations](https://huggingface.co/hiyouga/baichuan-7b-sft)
- [X] [Aquila 1 & 2](https://huggingface.co/models?search=BAAI/Aquila)
- [X] [Starcoder models](https://github.com/ggml-org/llama.cpp/pull/3187)
- [X] [Refact](https://huggingface.co/smallcloudai/Refact-1_6B-fim)
- [X] [MPT](https://github.com/ggml-org/llama.cpp/pull/3417)
- [X] [Bloom](https://github.com/ggml-org/llama.cpp/pull/3553)
- [x] [Yi models](https://huggingface.co/models?search=01-ai/Yi)
- [X] [StableLM models](https://huggingface.co/stabilityai)
- [x] [Deepseek models](https://huggingface.co/models?search=deepseek-ai/deepseek)
- [x] [Qwen models](https://huggingface.co/models?search=Qwen/Qwen)
- [x] [PLaMo-13B](https://github.com/ggml-org/llama.cpp/pull/3557)
- [x] [Phi models](https://huggingface.co/models?search=microsoft/phi)
- [x] [PhiMoE](https://github.com/ggml-org/llama.cpp/pull/11003)
- [x] [GPT-2](https://huggingface.co/gpt2)
- [x] [Orion 14B](https://github.com/ggml-org/llama.cpp/pull/5118)
- [x] [InternLM2](https://huggingface.co/models?search=internlm2)
- [x] [CodeShell](https://github.com/WisdomShell/codeshell)
- [x] [Gemma](https://ai.google.dev/gemma)
- [x] [Mamba](https://github.com/state-spaces/mamba)
- [x] [Grok-1](https://huggingface.co/keyfan/grok-1-hf)
- [x] [Xverse](https://huggingface.co/models?search=xverse)
- [x] [Command-R models](https://huggingface.co/models?search=CohereForAI/c4ai-command-r)
- [x] [SEA-LION](https://huggingface.co/models?search=sea-lion)
- [x] [GritLM-7B](https://huggingface.co/GritLM/GritLM-7B) + [GritLM-8x7B](https://huggingface.co/GritLM/GritLM-8x7B)
- [x] [OLMo](https://allenai.org/olmo)
- [x] [OLMo 2](https://allenai.org/olmo)
- [x] [OLMoE](https://huggingface.co/allenai/OLMoE-1B-7B-0924)
- [x] [Granite models](https://huggingface.co/collections/ibm-granite/granite-code-models-6624c5cec322e4c148c8b330)
- [x] [GPT-NeoX](https://github.com/EleutherAI/gpt-neox) + [Pythia](https://github.com/EleutherAI/pythia)
- [x] [Snowflake-Arctic MoE](https://huggingface.co/collections/Snowflake/arctic-66290090abe542894a5ac520)
- [x] [Smaug](https://huggingface.co/models?search=Smaug)
- [x] [Poro 34B](https://huggingface.co/LumiOpen/Poro-34B)
- [x] [Bitnet b1.58 models](https://huggingface.co/1bitLLM)
- [x] [Flan T5](https://huggingface.co/models?search=flan-t5)
- [x] [Open Elm models](https://huggingface.co/collections/apple/openelm-instruct-models-6619ad295d7ae9f868b759ca)
- [x] [ChatGLM3-6b](https://huggingface.co/THUDM/chatglm3-6b) + [ChatGLM4-9b](https://huggingface.co/THUDM/glm-4-9b) + [GLMEdge-1.5b](https://huggingface.co/THUDM/glm-edge-1.5b-chat) + [GLMEdge-4b](https://huggingface.co/THUDM/glm-edge-4b-chat)
- [x] [GLM-4-0414](https://huggingface.co/collections/THUDM/glm-4-0414-67f3cbcb34dd9d252707cb2e)
- [x] [SmolLM](https://huggingface.co/collections/HuggingFaceTB/smollm-6695016cad7167254ce15966)
- [x] [EXAONE-3.0-7.8B-Instruct](https://huggingface.co/LGAI-EXAONE/EXAONE-3.0-7.8B-Instruct)
- [x] [FalconMamba Models](https://huggingface.co/collections/tiiuae/falconmamba-7b-66b9a580324dd1598b0f6d4a)
- [x] [Jais](https://huggingface.co/inceptionai/jais-13b-chat)
- [x] [Bielik-11B-v2.3](https://huggingface.co/collections/speakleash/bielik-11b-v23-66ee813238d9b526a072408a)
- [x] [RWKV-7](https://huggingface.co/collections/shoumenchougou/rwkv7-gxx-gguf)
- [x] [RWKV-6](https://github.com/BlinkDL/RWKV-LM)
- [x] [QRWKV-6](https://huggingface.co/recursal/QRWKV6-32B-Instruct-Preview-v0.1)
- [x] [GigaChat-20B-A3B](https://huggingface.co/ai-sage/GigaChat-20B-A3B-instruct)
- [X] [Trillion-7B-preview](https://huggingface.co/trillionlabs/Trillion-7B-preview)
- [x] [Ling models](https://huggingface.co/collections/inclusionAI/ling-67c51c85b34a7ea0aba94c32)
- [x] [Liquid LFM2 models](https://huggingface.co/collections/LiquidAI/lfm2)
- [x] [Liquid LFM2.5 models](https://huggingface.co/collections/LiquidAI/lfm25)
- [x] [Liquid Nanos](https://huggingface.co/collections/LiquidAI/liquid-nanos)
- [x] [Hunyuan models](https://huggingface.co/collections/tencent/hunyuan-dense-model-6890632cda26b19119c9c5e7)
- [x] [BailingMoeV2 (Ring/Ling 2.0) models](https://huggingface.co/collections/inclusionAI/ling-v2-68bf1dd2fc34c306c1fa6f86)
- [x] [Mellum models](https://huggingface.co/JetBrains/models?search=mellum)
#### Multimodal
- [x] [LLaVA 1.5 models](https://huggingface.co/collections/liuhaotian/llava-15-653aac15d994e992e2677a7e), [LLaVA 1.6 models](https://huggingface.co/collections/liuhaotian/llava-16-65b9e40155f60fd046a5ccf2)
- [x] [BakLLaVA](https://huggingface.co/models?search=SkunkworksAI/Bakllava)
- [x] [Obsidian](https://huggingface.co/NousResearch/Obsidian-3B-V0.5)
- [x] [ShareGPT4V](https://huggingface.co/models?search=Lin-Chen/ShareGPT4V)
- [x] [MobileVLM 1.7B/3B models](https://huggingface.co/models?search=mobileVLM)
- [x] [Yi-VL](https://huggingface.co/models?search=Yi-VL)
- [x] [Mini CPM](https://huggingface.co/models?search=MiniCPM)
- [x] [Moondream](https://huggingface.co/vikhyatk/moondream2)
- [x] [Bunny](https://github.com/BAAI-DCAI/Bunny)
- [x] [GLM-EDGE](https://huggingface.co/models?search=glm-edge)
- [x] [Qwen2-VL](https://huggingface.co/collections/Qwen/qwen2-vl-66cee7455501d7126940800d)
- [x] [LFM2-VL](https://huggingface.co/collections/LiquidAI/lfm2-vl-68963bbc84a610f7638d5ffa)
</details>
<details>
<summary>Bindings</summary>
- Python: [ddh0/easy-llama](https://github.com/ddh0/easy-llama)
- Python: [abetlen/llama-cpp-python](https://github.com/abetlen/llama-cpp-python)
- Go: [go-skynet/go-llama.cpp](https://github.com/go-skynet/go-llama.cpp)
- Node.js: [withcatai/node-llama-cpp](https://github.com/withcatai/node-llama-cpp)
- JS/TS (llama.cpp server client): [lgrammel/modelfusion](https://modelfusion.dev/integration/model-provider/llamacpp)
- JS/TS (Programmable Prompt Engine CLI): [offline-ai/cli](https://github.com/offline-ai/cli)
- JavaScript/Wasm (works in browser): [tangledgroup/llama-cpp-wasm](https://github.com/tangledgroup/llama-cpp-wasm)
- Typescript/Wasm (nicer API, available on npm): [ngxson/wllama](https://github.com/ngxson/wllama)
- Ruby: [yoshoku/llama_cpp.rb](https://github.com/yoshoku/llama_cpp.rb)
- Ruby: [docusealco/rllama](https://github.com/docusealco/rllama)
- Rust (more features): [edgenai/llama_cpp-rs](https://github.com/edgenai/llama_cpp-rs)
- Rust (nicer API): [mdrokz/rust-llama.cpp](https://github.com/mdrokz/rust-llama.cpp)
- Rust (more direct bindings): [utilityai/llama-cpp-rs](https://github.com/utilityai/llama-cpp-rs)
- Rust (automated build from crates.io): [ShelbyJenkins/llm_client](https://github.com/ShelbyJenkins/llm_client)
- C#/.NET: [SciSharp/LLamaSharp](https://github.com/SciSharp/LLamaSharp)
- C#/VB.NET (more features - community license): [LM-Kit.NET](https://docs.lm-kit.com/lm-kit-net/index.html)
- Scala 3: [donderom/llm4s](https://github.com/donderom/llm4s)
- Clojure: [phronmophobic/llama.clj](https://github.com/phronmophobic/llama.clj)
- React Native: [mybigday/llama.rn](https://github.com/mybigday/llama.rn)
- Java: [kherud/java-llama.cpp](https://github.com/kherud/java-llama.cpp)
- Java: [QuasarByte/llama-cpp-jna](https://github.com/QuasarByte/llama-cpp-jna)
- Zig: [deins/llama.cpp.zig](https://github.com/Deins/llama.cpp.zig)
- Flutter/Dart: [netdur/llama_cpp_dart](https://github.com/netdur/llama_cpp_dart)
- Flutter: [xuegao-tzx/Fllama](https://github.com/xuegao-tzx/Fllama)
- PHP (API bindings and features built on top of llama.cpp): [distantmagic/resonance](https://github.com/distantmagic/resonance) [(more info)](https://github.com/ggml-org/llama.cpp/pull/6326)
- Guile Scheme: [guile_llama_cpp](https://savannah.nongnu.org/projects/guile-llama-cpp)
- Swift [srgtuszy/llama-cpp-swift](https://github.com/srgtuszy/llama-cpp-swift)
- Swift [ShenghaiWang/SwiftLlama](https://github.com/ShenghaiWang/SwiftLlama)
- Delphi [Embarcadero/llama-cpp-delphi](https://github.com/Embarcadero/llama-cpp-delphi)
- Go (no CGo needed): [hybridgroup/yzma](https://github.com/hybridgroup/yzma)
- Android: [llama.android](/examples/llama.android)
</details>
<details>
<summary>UIs</summary>
*(to have a project listed here, it should clearly state that it depends on `llama.cpp`)*
- [AI Sublime Text plugin](https://github.com/yaroslavyaroslav/OpenAI-sublime-text) (MIT)
- [BonzAI App](https://apps.apple.com/us/app/bonzai-your-local-ai-agent/id6752847988) (proprietary)
- [cztomsik/ava](https://github.com/cztomsik/ava) (MIT)
- [Dot](https://github.com/alexpinel/Dot) (GPL)
- [eva](https://github.com/ylsdamxssjxxdd/eva) (MIT)
- [iohub/collama](https://github.com/iohub/coLLaMA) (Apache-2.0)
- [janhq/jan](https://github.com/janhq/jan) (AGPL)
- [johnbean393/Sidekick](https://github.com/johnbean393/Sidekick) (MIT)
- [KanTV](https://github.com/zhouwg/kantv?tab=readme-ov-file) (Apache-2.0)
- [KodiBot](https://github.com/firatkiral/kodibot) (GPL)
- [llama.vim](https://github.com/ggml-org/llama.vim) (MIT)
- [LARS](https://github.com/abgulati/LARS) (AGPL)
- [Llama Assistant](https://github.com/vietanhdev/llama-assistant) (GPL)
- [LlamaLib](https://github.com/undreamai/LlamaLib) (Apache-2.0)
- [LLMFarm](https://github.com/guinmoon/LLMFarm?tab=readme-ov-file) (MIT)
- [LLMUnity](https://github.com/undreamai/LLMUnity) (MIT)
- [LMStudio](https://lmstudio.ai/) (proprietary)
- [LocalAI](https://github.com/mudler/LocalAI) (MIT)
- [LostRuins/koboldcpp](https://github.com/LostRuins/koboldcpp) (AGPL)
- [MindMac](https://mindmac.app) (proprietary)
- [MindWorkAI/AI-Studio](https://github.com/MindWorkAI/AI-Studio) (FSL-1.1-MIT)
- [Mobile-Artificial-Intelligence/maid](https://github.com/Mobile-Artificial-Intelligence/maid) (MIT)
- [Mozilla-Ocho/llamafile](https://github.com/Mozilla-Ocho/llamafile) (Apache-2.0)
- [nat/openplayground](https://github.com/nat/openplayground) (MIT)
- [nomic-ai/gpt4all](https://github.com/nomic-ai/gpt4all) (MIT)
- [ollama/ollama](https://github.com/ollama/ollama) (MIT)
- [oobabooga/text-generation-webui](https://github.com/oobabooga/text-generation-webui) (AGPL)
- [PocketPal AI](https://github.com/a-ghorbani/pocketpal-ai) (MIT)
- [psugihara/FreeChat](https://github.com/psugihara/FreeChat) (MIT)
- [ptsochantaris/emeltal](https://github.com/ptsochantaris/emeltal) (MIT)
- [pythops/tenere](https://github.com/pythops/tenere) (AGPL)
- [ramalama](https://github.com/containers/ramalama) (MIT)
- [semperai/amica](https://github.com/semperai/amica) (MIT)
- [withcatai/catai](https://github.com/withcatai/catai) (MIT)
- [Autopen](https://github.com/blackhole89/autopen) (GPL)
</details>
<details>
<summary>Tools</summary>
- [akx/ggify](https://github.com/akx/ggify) download PyTorch models from Hugging Face Hub and convert them to GGML
- [akx/ollama-dl](https://github.com/akx/ollama-dl) download models from the Ollama library to be used directly with llama.cpp
- [crashr/gppm](https://github.com/crashr/gppm) launch llama.cpp instances utilizing NVIDIA Tesla P40 or P100 GPUs with reduced idle power consumption
- [gpustack/gguf-parser](https://github.com/gpustack/gguf-parser-go/tree/main/cmd/gguf-parser) - review/check the GGUF file and estimate the memory usage
- [Styled Lines](https://marketplace.unity.com/packages/tools/generative-ai/styled-lines-llama-cpp-model-292902) (proprietary licensed, async wrapper of inference part for game development in Unity3d with pre-built Mobile and Web platform wrappers and a model example)
- [unslothai/unsloth](https://github.com/unslothai/unsloth) 🦥 exports/saves fine-tuned and trained models to GGUF (Apache-2.0)
</details>
<details>
<summary>Infrastructure</summary>
- [Paddler](https://github.com/intentee/paddler) - Open-source LLMOps platform for hosting and scaling AI in your own infrastructure
- [GPUStack](https://github.com/gpustack/gpustack) - Manage GPU clusters for running LLMs
- [llama_cpp_canister](https://github.com/onicai/llama_cpp_canister) - llama.cpp as a smart contract on the Internet Computer, using WebAssembly
- [llama-swap](https://github.com/mostlygeek/llama-swap) - transparent proxy that adds automatic model switching with llama-server
- [Kalavai](https://github.com/kalavai-net/kalavai-client) - Crowdsource end to end LLM deployment at any scale
- [llmaz](https://github.com/InftyAI/llmaz) - ☸️ Easy, advanced inference platform for large language models on Kubernetes.
- [LLMKube](https://github.com/defilantech/llmkube) - Kubernetes operator for llama.cpp with multi-GPU and Apple Silicon Metal
support"
</details>
<details>
<summary>Games</summary>
- [Lucy's Labyrinth](https://github.com/MorganRO8/Lucys_Labyrinth) - A simple maze game where agents controlled by an AI model will try to trick you.
</details>
## Supported backends
| Backend | Target devices |
| --- | --- |
| [Metal](docs/build.md#metal-build) | Apple Silicon |
| [BLAS](docs/build.md#blas-build) | All |
| [BLIS](docs/backend/BLIS.md) | All |
| [SYCL](docs/backend/SYCL.md) | Intel GPU |
| [OpenVINO [In Progress]](docs/backend/OPENVINO.md) | Intel CPUs, GPUs, and NPUs |
| [MUSA](docs/build.md#musa) | Moore Threads GPU |
| [CUDA](docs/build.md#cuda) | Nvidia GPU |
| [HIP](docs/build.md#hip) | AMD GPU |
| [ZenDNN](docs/build.md#zendnn) | AMD CPU |
| [Vulkan](docs/build.md#vulkan) | GPU |
| [CANN](docs/build.md#cann) | Ascend NPU |
| [OpenCL](docs/backend/OPENCL.md) | Adreno GPU |
| [IBM zDNN](docs/backend/zDNN.md) | IBM Z & LinuxONE |
| [WebGPU](docs/build.md#webgpu) | All |
| [RPC](https://github.com/ggml-org/llama.cpp/tree/master/tools/rpc) | All |
| [Hexagon [In Progress]](docs/backend/snapdragon/README.md) | Snapdragon |
| [VirtGPU](docs/backend/VirtGPU.md) | VirtGPU APIR |
## Obtaining and quantizing models
The [Hugging Face](https://huggingface.co) platform hosts a [number of LLMs](https://huggingface.co/models?library=gguf&sort=trending) compatible with `llama.cpp`:
- [Trending](https://huggingface.co/models?library=gguf&sort=trending)
- [LLaMA](https://huggingface.co/models?sort=trending&search=llama+gguf)
You can either manually download the GGUF file or directly use any `llama.cpp`-compatible models from [Hugging Face](https://huggingface.co/) or other model hosting sites, by using this CLI argument: `-hf <user>/<model>[:quant]`. For example:
```sh
llama-cli -hf ggml-org/gemma-3-1b-it-GGUF
```
By default, the CLI would download from Hugging Face, you can switch to other options with the environment variable `MODEL_ENDPOINT`. The `MODEL_ENDPOINT` must point to a Hugging Face compatible API endpoint.
After downloading a model, use the CLI tools to run it locally - see below.
`llama.cpp` requires the model to be stored in the [GGUF](https://github.com/ggml-org/ggml/blob/master/docs/gguf.md) file format. Models in other data formats can be converted to GGUF using the `convert_*.py` Python scripts in this repo.
The Hugging Face platform provides a variety of online tools for converting, quantizing and hosting models with `llama.cpp`:
- Use the [GGUF-my-repo space](https://huggingface.co/spaces/ggml-org/gguf-my-repo) to convert to GGUF format and quantize model weights to smaller sizes
- Use the [GGUF-my-LoRA space](https://huggingface.co/spaces/ggml-org/gguf-my-lora) to convert LoRA adapters to GGUF format (more info: https://github.com/ggml-org/llama.cpp/discussions/10123)
- Use the [GGUF-editor space](https://huggingface.co/spaces/CISCai/gguf-editor) to edit GGUF meta data in the browser (more info: https://github.com/ggml-org/llama.cpp/discussions/9268)
- Use the [Inference Endpoints](https://ui.endpoints.huggingface.co/) to directly host `llama.cpp` in the cloud (more info: https://github.com/ggml-org/llama.cpp/discussions/9669)
To learn more about model quantization, [read this documentation](tools/quantize/README.md)
## [`llama-cli`](tools/cli)
#### A CLI tool for accessing and experimenting with most of `llama.cpp`'s functionality.
- <details open>
<summary>Run in conversation mode</summary>
Models with a built-in chat template will automatically activate conversation mode. If this doesn't occur, you can manually enable it by adding `-cnv` and specifying a suitable chat template with `--chat-template NAME`
```bash
llama-cli -m model.gguf
# > hi, who are you?
# Hi there! I'm your helpful assistant! I'm an AI-powered chatbot designed to assist and provide information to users like you. I'm here to help answer your questions, provide guidance, and offer support on a wide range of topics. I'm a friendly and knowledgeable AI, and I'm always happy to help with anything you need. What's on your mind, and how can I assist you today?
#
# > what is 1+1?
# Easy peasy! The answer to 1+1 is... 2!
```
</details>
- <details>
<summary>Run in conversation mode with custom chat template</summary>
```bash
# use the "chatml" template (use -h to see the list of supported templates)
llama-cli -m model.gguf -cnv --chat-template chatml
# use a custom template
llama-cli -m model.gguf -cnv --in-prefix 'User: ' --reverse-prompt 'User:'
```
</details>
- <details>
<summary>Constrain the output with a custom grammar</summary>
```bash
llama-cli -m model.gguf -n 256 --grammar-file grammars/json.gbnf -p 'Request: schedule a call at 8pm; Command:'
# {"appointmentTime": "8pm", "appointmentDetails": "schedule a a call"}
```
The [grammars/](grammars/) folder contains a handful of sample grammars. To write your own, check out the [GBNF Guide](grammars/README.md).
For authoring more complex JSON grammars, check out https://grammar.intrinsiclabs.ai/
</details>
## [`llama-server`](tools/server)
#### A lightweight, [OpenAI API](https://github.com/openai/openai-openapi) compatible, HTTP server for serving LLMs.
- <details open>
<summary>Start a local HTTP server with default configuration on port 8080</summary>
```bash
llama-server -m model.gguf --port 8080
# Basic web UI can be accessed via browser: http://localhost:8080
# Chat completion endpoint: http://localhost:8080/v1/chat/completions
```
</details>
- <details>
<summary>Support multiple-users and parallel decoding</summary>
```bash
# up to 4 concurrent requests, each with 4096 max context
llama-server -m model.gguf -c 16384 -np 4
```
</details>
- <details>
<summary>Enable speculative decoding</summary>
```bash
# the draft.gguf model should be a small variant of the target model.gguf
llama-server -m model.gguf -md draft.gguf
```
</details>
- <details>
<summary>Serve an embedding model</summary>
```bash
# use the /embedding endpoint
llama-server -m model.gguf --embedding --pooling cls -ub 8192
```
</details>
- <details>
<summary>Serve a reranking model</summary>
```bash
# use the /reranking endpoint
llama-server -m model.gguf --reranking
```
</details>
- <details>
<summary>Constrain all outputs with a grammar</summary>
```bash
# custom grammar
llama-server -m model.gguf --grammar-file grammar.gbnf
# JSON
llama-server -m model.gguf --grammar-file grammars/json.gbnf
```
</details>
## [`llama-perplexity`](tools/perplexity)
#### A tool for measuring the [perplexity](tools/perplexity/README.md) [^1] (and other quality metrics) of a model over a given text.
- <details open>
<summary>Measure the perplexity over a text file</summary>
```bash
llama-perplexity -m model.gguf -f file.txt
# [1]15.2701,[2]5.4007,[3]5.3073,[4]6.2965,[5]5.8940,[6]5.6096,[7]5.7942,[8]4.9297, ...
# Final estimate: PPL = 5.4007 +/- 0.67339
```
</details>
- <details>
<summary>Measure KL divergence</summary>
```bash
# TODO
```
</details>
[^1]: [https://huggingface.co/docs/transformers/perplexity](https://huggingface.co/docs/transformers/perplexity)
## [`llama-bench`](tools/llama-bench)
#### Benchmark the performance of the inference for various parameters.
- <details open>
<summary>Run default benchmark</summary>
```bash
llama-bench -m model.gguf
# Output:
# | model | size | params | backend | threads | test | t/s |
# | ------------------- | ---------: | ---------: | ---------- | ------: | ------------: | -------------------: |
# | qwen2 1.5B Q4_0 | 885.97 MiB | 1.54 B | Metal,BLAS | 16 | pp512 | 5765.41 ± 20.55 |
# | qwen2 1.5B Q4_0 | 885.97 MiB | 1.54 B | Metal,BLAS | 16 | tg128 | 197.71 ± 0.81 |
#
# build: 3e0ba0e60 (4229)
```
</details>
## [`llama-simple`](examples/simple)
#### A minimal example for implementing apps with `llama.cpp`. Useful for developers.
- <details>
<summary>Basic text completion</summary>
```bash
llama-simple -m model.gguf
# Hello my name is Kaitlyn and I am a 16 year old girl. I am a junior in high school and I am currently taking a class called "The Art of
```
</details>
## Contributing
- Contributors can open PRs
- Collaborators will be invited based on contributions
- Maintainers can push to branches in the `llama.cpp` repo and merge PRs into the `master` branch
- Any help with managing issues, PRs and projects is very appreciated!
- See [good first issues](https://github.com/ggml-org/llama.cpp/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) for tasks suitable for first contributions
- Read the [CONTRIBUTING.md](CONTRIBUTING.md) for more information
- Make sure to read this: [Inference at the edge](https://github.com/ggml-org/llama.cpp/discussions/205)
- A bit of backstory for those who are interested: [Changelog podcast](https://changelog.com/podcast/532)
## Other documentation
- [cli](tools/cli/README.md)
- [completion](tools/completion/README.md)
- [server](tools/server/README.md)
- [GBNF grammars](grammars/README.md)
#### Development documentation
- [How to build](docs/build.md)
- [Running on Docker](docs/docker.md)
- [Build on Android](docs/android.md)
- [Multi-GPU usage](docs/multi-gpu.md)
- [Performance troubleshooting](docs/development/token_generation_performance_tips.md)
- [GGML tips & tricks](https://github.com/ggml-org/llama.cpp/wiki/GGML-Tips-&-Tricks)
#### Seminal papers and background on the models
If your issue is with model generation quality, then please at least scan the following links and papers to understand the limitations of LLaMA models. This is especially important when choosing an appropriate model size and appreciating both the significant and subtle differences between LLaMA models and ChatGPT:
- LLaMA:
- [Introducing LLaMA: A foundational, 65-billion-parameter large language model](https://ai.facebook.com/blog/large-language-model-llama-meta-ai/)
- [LLaMA: Open and Efficient Foundation Language Models](https://arxiv.org/abs/2302.13971)
- GPT-3
- [Language Models are Few-Shot Learners](https://arxiv.org/abs/2005.14165)
- GPT-3.5 / InstructGPT / ChatGPT:
- [Aligning language models to follow instructions](https://openai.com/research/instruction-following)
- [Training language models to follow instructions with human feedback](https://arxiv.org/abs/2203.02155)
## XCFramework
The XCFramework is a precompiled version of the library for iOS, visionOS, tvOS,
and macOS. It can be used in Swift projects without the need to compile the
library from source. For example:
```swift
// swift-tools-version: 5.10
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "MyLlamaPackage",
targets: [
.executableTarget(
name: "MyLlamaPackage",
dependencies: [
"LlamaFramework"
]),
.binaryTarget(
name: "LlamaFramework",
url: "https://github.com/ggml-org/llama.cpp/releases/download/b5046/llama-b5046-xcframework.zip",
checksum: "c19be78b5f00d8d29a25da41042cb7afa094cbf6280a225abe614b03b20029ab"
)
]
)
```
The above example is using an intermediate build `b5046` of the library. This can be modified
to use a different version by changing the URL and checksum.
## Completions
Command-line completion is available for some environments.
#### Bash Completion
```bash
$ build/bin/llama-cli --completion-bash > ~/.llama-completion.bash
$ source ~/.llama-completion.bash
```
Optionally this can be added to your `.bashrc` or `.bash_profile` to load it
automatically. For example:
```console
$ echo "source ~/.llama-completion.bash" >> ~/.bashrc
```
## Dependencies
- [yhirose/cpp-httplib](https://github.com/yhirose/cpp-httplib) - Single-header HTTP server, used by `llama-server` - MIT license
- [stb-image](https://github.com/nothings/stb) - Single-header image format decoder, used by multimodal subsystem - Public domain
- [nlohmann/json](https://github.com/nlohmann/json) - Single-header JSON library, used by various tools/examples - MIT License
- [miniaudio.h](https://github.com/mackron/miniaudio) - Single-header audio format decoder, used by multimodal subsystem - Public domain
- [subprocess.h](https://github.com/sheredom/subprocess.h) - Single-header process launching solution for C and C++ - Public domain
+2 -37
View File
@@ -16,41 +16,6 @@ llama-cli \
`--longhaul-cache` is the expert cache budget in GiB. It is required when `--longhaul` is used. The same options are accepted by `llama-server`. `--longhaul-cache` is the expert cache budget in GiB. It is required when `--longhaul` is used. The same options are accepted by `llama-server`.
## RPC mode
RPC longhaul keeps the paging loop on the accelerator host so expert payloads do
not cross the network during generation. Build both hosts with `-DGGML_RPC=ON`.
Place the same GGUF shard files on both hosts, preserving their basenames, then
start the Metal host with the directory containing those shards:
```sh
ggml-rpc-server \
--device MTL0 \
--longhaul-root /path/to/model-directory \
--host 192.168.1.20
```
Start the client normally:
```sh
llama-server \
--model /local/path/model.gguf \
--rpc 192.168.1.20:50052 \
--longhaul \
--longhaul-cache 2 \
--n-gpu-layers 99
```
RPC longhaul currently requires all repeating layers on one remote Metal device.
The server validates each shard basename, size, GGUF metadata layout digest, and
every registered expert range before decoding. An older server, a server without
`--longhaul-root`, or a shard mismatch is a fatal model-load error; the client
does not fall back to sending expert slices over RPC.
`--longhaul-root` grants connected RPC clients read access to registered byte
ranges in files in that directory. The RPC server remains experimental and
insecure and must not be exposed to an untrusted network.
Longhaul may reduce `--ubatch-size` so that every expert selected by one graph segment can be present in the cache at the same time. The effective value is logged during context creation. If one token selects more experts than the cache has slots, the routed MoE computation is split into multiple stages and the partial results are summed. This permits smaller caches at the cost of additional graph work. Longhaul may reduce `--ubatch-size` so that every expert selected by one graph segment can be present in the cache at the same time. The effective value is logged during context creation. If one token selects more experts than the cache has slots, the routed MoE computation is split into multiple stages and the partial results are summed. This permits smaller caches at the cost of additional graph work.
The normal startup warmup is skipped automatically in longhaul mode. Routed expert weights are not read until the first real decode. The normal startup warmup is skipped automatically in longhaul mode. Routed expert weights are not read until the first real decode.
@@ -59,9 +24,9 @@ The normal startup warmup is skipped automatically in longhaul mode. Routed expe
Longhaul currently requires: Longhaul currently requires:
- the Metal backend, either local on macOS or on one RPC host - macOS with the Metal backend
- Qwen3.5 MoE or Laguna architecture - Qwen3.5 MoE or Laguna architecture
- all repeating model layers assigned to local Metal or one RPC Metal device - all repeating model layers assigned to Metal
- text generation without embeddings or LoRA adapters - text generation without embeddings or LoRA adapters
Longhaul does not restrict the GGUF quantization type. Individual tensor types must still be supported by Metal. Longhaul does not restrict the GGUF quantization type. Individual tensor types must still be supported by Metal.
+1 -44
View File
@@ -8,7 +8,7 @@ extern "C" {
#define RPC_PROTO_MAJOR_VERSION 4 #define RPC_PROTO_MAJOR_VERSION 4
#define RPC_PROTO_MINOR_VERSION 0 #define RPC_PROTO_MINOR_VERSION 0
#define RPC_PROTO_PATCH_VERSION 4 #define RPC_PROTO_PATCH_VERSION 3
#ifdef __cplusplus #ifdef __cplusplus
static_assert(GGML_OP_COUNT == 101, "GGML_OP_COUNT has changed - update RPC_PROTO_PATCH_VERSION"); static_assert(GGML_OP_COUNT == 101, "GGML_OP_COUNT has changed - update RPC_PROTO_PATCH_VERSION");
@@ -27,49 +27,6 @@ GGML_BACKEND_API void ggml_backend_rpc_get_device_memory(const char * endpoint,
GGML_BACKEND_API void ggml_backend_rpc_start_server(const char * endpoint, const char * cache_dir, GGML_BACKEND_API void ggml_backend_rpc_start_server(const char * endpoint, const char * cache_dir,
size_t n_threads, size_t n_devices, ggml_backend_dev_t * devices); size_t n_threads, size_t n_devices, ggml_backend_dev_t * devices);
struct ggml_backend_rpc_longhaul_shard {
const char * name;
uint64_t size;
uint64_t metadata_size;
uint8_t metadata_sha256[32];
};
struct ggml_backend_rpc_longhaul_source {
struct ggml_tensor * tensor;
uint32_t shard;
uint64_t offset;
uint64_t expert_size;
int32_t layer;
};
struct ggml_backend_rpc_longhaul_params {
uint32_t n_layers;
uint32_t n_experts;
uint32_t n_slots;
size_t n_shards;
const struct ggml_backend_rpc_longhaul_shard * shards;
size_t n_sources;
const struct ggml_backend_rpc_longhaul_source * sources;
};
GGML_BACKEND_API bool ggml_backend_rpc_longhaul_register(
const struct ggml_backend_rpc_longhaul_params * params,
uint64_t * registration_id,
char * error,
size_t error_size);
GGML_BACKEND_API void ggml_backend_rpc_longhaul_unregister(
struct ggml_tensor * tensor,
uint64_t registration_id);
GGML_BACKEND_API void ggml_backend_rpc_start_server_with_options(
const char * endpoint,
const char * cache_dir,
const char * longhaul_root,
size_t n_threads,
size_t n_devices,
ggml_backend_dev_t * devices);
GGML_BACKEND_API ggml_backend_reg_t ggml_backend_rpc_reg(void); GGML_BACKEND_API ggml_backend_reg_t ggml_backend_rpc_reg(void);
GGML_BACKEND_API ggml_backend_reg_t ggml_backend_rpc_add_server(const char * endpoint); GGML_BACKEND_API ggml_backend_reg_t ggml_backend_rpc_add_server(const char * endpoint);
File diff suppressed because it is too large Load Diff
+3 -5
View File
@@ -1359,12 +1359,10 @@ llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, ll
res->reset(); res->reset();
ggml_backend_sched_reset(sched.get()); ggml_backend_sched_reset(sched.get());
auto * longhaul = model.longhaul_cache();
const bool local_longhaul = longhaul && !longhaul->is_remote();
ggml_backend_sched_set_eval_callback( ggml_backend_sched_set_eval_callback(
sched.get(), sched.get(),
local_longhaul ? longhaul_eval_callback : cparams.cb_eval, model.longhaul_cache() ? longhaul_eval_callback : cparams.cb_eval,
local_longhaul ? this : cparams.cb_eval_user_data); model.longhaul_cache() ? this : cparams.cb_eval_user_data);
//const auto t_start_us = ggml_time_us(); //const auto t_start_us = ggml_time_us();
@@ -2463,7 +2461,7 @@ llm_graph_params llama_context::graph_params(
bool llama_context::longhaul_eval_callback(ggml_tensor * tensor, bool ask, void * user_data) { bool llama_context::longhaul_eval_callback(ggml_tensor * tensor, bool ask, void * user_data) {
auto * ctx = static_cast<llama_context *>(user_data); auto * ctx = static_cast<llama_context *>(user_data);
auto * cache = ctx->model.longhaul_cache(); auto * cache = ctx->model.longhaul_cache();
GGML_ASSERT(cache != nullptr && !cache->is_remote()); GGML_ASSERT(cache != nullptr);
int layer = -1; int layer = -1;
const bool remap = sscanf(tensor->name, "longhaul.remap.%d", &layer) == 1; const bool remap = sscanf(tensor->name, "longhaul.remap.%d", &layer) == 1;
+2 -102
View File
@@ -1,108 +1,23 @@
#include "llama-longhaul.h" #include "llama-longhaul.h"
#include "llama-impl.h" #include "llama-impl.h"
#include "llama-token-cache.h"
#include "ggml-rpc.h"
#include <algorithm> #include <algorithm>
#include <array>
#include <cstring> #include <cstring>
#include <inttypes.h> #include <inttypes.h>
#include <stdexcept>
llama_longhaul_cache::llama_longhaul_cache( llama_longhaul_cache::llama_longhaul_cache(
llama_files files, llama_files files,
std::vector<llama_model_loader::longhaul_source> sources, std::vector<llama_model_loader::longhaul_source> sources,
std::vector<llama_model_loader::longhaul_shard> shards,
size_t n_slots, size_t n_slots,
uint32_t n_experts, uint32_t n_experts,
uint32_t n_layers, uint32_t n_layers) :
bool remote) :
files(std::move(files)), files(std::move(files)),
sources(std::move(sources)), sources(std::move(sources)),
shards(std::move(shards)),
sources_by_layer(n_layers), sources_by_layer(n_layers),
layers(n_layers), layers(n_layers),
n_slots(n_slots), n_slots(n_slots),
n_experts(n_experts), n_experts(n_experts) {
remote(remote) {
if (remote) {
if (this->shards.size() != this->files.size() || this->sources.empty()) {
throw std::runtime_error("RPC longhaul requires named GGUF shards");
}
std::vector<std::array<uint8_t, 32>> digests(this->shards.size());
std::vector<ggml_backend_rpc_longhaul_shard> rpc_shards(this->shards.size());
for (size_t i = 0; i < this->shards.size(); ++i) {
const auto & shard = this->shards[i];
if (shard.metadata_size > shard.size) {
throw std::runtime_error("invalid RPC longhaul shard metadata range");
}
std::vector<uint8_t> metadata(shard.metadata_size);
if (!metadata.empty()) {
this->files[i]->read_at(metadata.data(), metadata.size(), 0);
}
const std::string hex = llama_token_cache_hash(metadata.data(), metadata.size());
if (hex.size() != 64) {
throw std::runtime_error("failed to fingerprint RPC longhaul shard");
}
for (size_t j = 0; j < digests[i].size(); ++j) {
auto nibble = [](char c) -> uint8_t {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return 0xff;
};
const uint8_t hi = nibble(hex[2*j]);
const uint8_t lo = nibble(hex[2*j + 1]);
if (hi > 0x0f || lo > 0x0f) {
throw std::runtime_error("invalid RPC longhaul shard fingerprint");
}
digests[i][j] = (hi << 4) | lo;
}
rpc_shards[i] = {
shard.name.c_str(),
shard.size,
shard.metadata_size,
{},
};
memcpy(rpc_shards[i].metadata_sha256, digests[i].data(), digests[i].size());
}
std::vector<ggml_backend_rpc_longhaul_source> rpc_sources;
rpc_sources.reserve(this->sources.size());
for (const auto & source : this->sources) {
rpc_sources.push_back({
source.tensor,
source.file_idx,
source.offset,
source.expert_size,
source.layer,
});
}
ggml_backend_rpc_longhaul_params params = {
n_layers,
n_experts,
(uint32_t) n_slots,
rpc_shards.size(),
rpc_shards.data(),
rpc_sources.size(),
rpc_sources.data(),
};
ggml_backend_reg_t reg = ggml_backend_reg_by_name("RPC");
auto register_fn = reg ? (decltype(ggml_backend_rpc_longhaul_register) *)
ggml_backend_reg_get_proc_address(reg, "ggml_backend_rpc_longhaul_register") : nullptr;
if (!register_fn) {
throw std::runtime_error("RPC backend does not expose longhaul registration");
}
char error[256] = {};
if (!register_fn(&params, &remote_registration_id, error, sizeof(error))) {
throw std::runtime_error(error[0] ? error : "RPC longhaul registration failed");
}
this->files.clear();
return;
}
for (auto & file : this->files) { for (auto & file : this->files) {
file->set_no_cache(); file->set_no_cache();
} }
@@ -130,17 +45,6 @@ llama_longhaul_cache::llama_longhaul_cache(
} }
llama_longhaul_cache::~llama_longhaul_cache() { llama_longhaul_cache::~llama_longhaul_cache() {
if (remote) {
if (!sources.empty() && remote_registration_id != 0) {
ggml_backend_reg_t reg = ggml_backend_reg_by_name("RPC");
auto unregister_fn = reg ? (decltype(ggml_backend_rpc_longhaul_unregister) *)
ggml_backend_reg_get_proc_address(reg, "ggml_backend_rpc_longhaul_unregister") : nullptr;
if (unregister_fn) {
unregister_fn(sources.front().tensor, remote_registration_id);
}
}
return;
}
{ {
std::lock_guard<std::mutex> lock(io_mutex); std::lock_guard<std::mutex> lock(io_mutex);
io_stopping = true; io_stopping = true;
@@ -417,7 +321,3 @@ uint64_t llama_longhaul_cache::misses() const {
uint64_t llama_longhaul_cache::bytes_read_count() const { uint64_t llama_longhaul_cache::bytes_read_count() const {
return bytes_read; return bytes_read;
} }
bool llama_longhaul_cache::is_remote() const {
return remote;
}
+1 -7
View File
@@ -17,11 +17,9 @@ struct llama_longhaul_cache {
llama_longhaul_cache( llama_longhaul_cache(
llama_files files, llama_files files,
std::vector<llama_model_loader::longhaul_source> sources, std::vector<llama_model_loader::longhaul_source> sources,
std::vector<llama_model_loader::longhaul_shard> shards,
size_t n_slots, size_t n_slots,
uint32_t n_experts, uint32_t n_experts,
uint32_t n_layers, uint32_t n_layers);
bool remote);
~llama_longhaul_cache(); ~llama_longhaul_cache();
bool remap(int layer, ggml_tensor * ids); bool remap(int layer, ggml_tensor * ids);
@@ -33,7 +31,6 @@ struct llama_longhaul_cache {
bool failed() const; bool failed() const;
uint64_t misses() const; uint64_t misses() const;
uint64_t bytes_read_count() const; uint64_t bytes_read_count() const;
bool is_remote() const;
private: private:
struct layer_state { struct layer_state {
@@ -52,7 +49,6 @@ private:
llama_files files; llama_files files;
std::vector<llama_model_loader::longhaul_source> sources; std::vector<llama_model_loader::longhaul_source> sources;
std::vector<llama_model_loader::longhaul_shard> shards;
std::vector<std::vector<const llama_model_loader::longhaul_source *>> sources_by_layer; std::vector<std::vector<const llama_model_loader::longhaul_source *>> sources_by_layer;
std::vector<layer_state> layers; std::vector<layer_state> layers;
size_t n_slots; size_t n_slots;
@@ -88,8 +84,6 @@ private:
std::condition_variable io_done; std::condition_variable io_done;
size_t io_pending = 0; size_t io_pending = 0;
bool io_stopping = false; bool io_stopping = false;
bool remote = false;
uint64_t remote_registration_id = 0;
bool source_is_direct(const llama_model_loader::longhaul_source & source) const; bool source_is_direct(const llama_model_loader::longhaul_source & source) const;
bool load_plan_sources(); bool load_plan_sources();
-10
View File
@@ -594,11 +594,6 @@ llama_model_loader::llama_model_loader(
files.emplace_back(new llama_file(fname.c_str(), "rb", use_direct_io)); files.emplace_back(new llama_file(fname.c_str(), "rb", use_direct_io));
contexts.emplace_back(ctx); contexts.emplace_back(ctx);
longhaul_shards.push_back({
std::filesystem::path(fname).filename().string(),
files.back()->size(),
gguf_get_data_offset(metadata),
});
// Save tensors data offset of the main file. // Save tensors data offset of the main file.
// For subsidiary files, `meta` tensor data offset must not be used, // For subsidiary files, `meta` tensor data offset must not be used,
@@ -667,11 +662,6 @@ llama_model_loader::llama_model_loader(
files.emplace_back(new llama_file(fname_split, "rb", use_direct_io)); files.emplace_back(new llama_file(fname_split, "rb", use_direct_io));
contexts.emplace_back(ctx); contexts.emplace_back(ctx);
longhaul_shards.push_back({
std::filesystem::path(fname_split).filename().string(),
files.back()->size(),
gguf_get_data_offset(ctx_gguf.get()),
});
// Save tensors data offset info of the shard. // Save tensors data offset info of the shard.
for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) { for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
-8
View File
@@ -9,7 +9,6 @@
#include "ggml-cpp.h" #include "ggml-cpp.h"
#include <array>
#include <cstddef> #include <cstddef>
#include <cstring> #include <cstring>
#include <map> #include <map>
@@ -78,12 +77,6 @@ struct llama_model_loader {
int layer; int layer;
}; };
struct longhaul_shard {
std::string name;
uint64_t size;
uint64_t metadata_size;
};
int n_kv = 0; int n_kv = 0;
int n_tensors = 0; int n_tensors = 0;
int n_created = 0; int n_created = 0;
@@ -122,7 +115,6 @@ struct llama_model_loader {
std::vector<std::pair<size_t, size_t>> mmaps_used; std::vector<std::pair<size_t, size_t>> mmaps_used;
size_t longhaul_slots = 0; size_t longhaul_slots = 0;
std::vector<longhaul_source> longhaul_sources; std::vector<longhaul_source> longhaul_sources;
std::vector<longhaul_shard> longhaul_shards;
// define a comparator for the buft -> ctx map to ensure that the order is well-defined: // define a comparator for the buft -> ctx map to ensure that the order is well-defined:
struct ggml_backend_buft_comparator { struct ggml_backend_buft_comparator {
+7 -29
View File
@@ -1039,7 +1039,6 @@ struct llama_model::impl {
std::vector<float> tensor_split_owned; std::vector<float> tensor_split_owned;
std::unique_ptr<llama_longhaul_cache> longhaul; std::unique_ptr<llama_longhaul_cache> longhaul;
bool longhaul_remote = false;
}; };
llama_model::llama_model(const llama_model_params & params) : params(params), pimpl(std::make_unique<impl>()) { llama_model::llama_model(const llama_model_params & params) : params(params), pimpl(std::make_unique<impl>()) {
@@ -1357,6 +1356,9 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) {
} }
if (params.load_mode == LLAMA_LOAD_MODE_LONGHAUL) { if (params.load_mode == LLAMA_LOAD_MODE_LONGHAUL) {
#if !defined(__APPLE__)
throw std::runtime_error("longhaul is only supported on macOS");
#endif
if (arch != LLM_ARCH_QWEN35MOE && arch != LLM_ARCH_LAGUNA) { if (arch != LLM_ARCH_QWEN35MOE && arch != LLM_ARCH_LAGUNA) {
throw std::runtime_error("longhaul currently requires a qwen35moe or laguna model"); throw std::runtime_error("longhaul currently requires a qwen35moe or laguna model");
} }
@@ -1366,35 +1368,12 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) {
if (params.check_tensors || params.no_alloc || params.vocab_only) { if (params.check_tensors || params.no_alloc || params.vocab_only) {
throw std::runtime_error("longhaul does not support check-tensors, no-alloc, or vocab-only loading"); throw std::runtime_error("longhaul does not support check-tensors, no-alloc, or vocab-only loading");
} }
bool all_metal = true;
bool all_rpc = true;
for (int il = 0; il < n_layer_all; ++il) { for (int il = 0; il < n_layer_all; ++il) {
ggml_backend_dev_t dev = pimpl->dev_layer[il].dev; ggml_backend_dev_t dev = pimpl->dev_layer[il].dev;
const char * reg_name = ggml_backend_reg_name(ggml_backend_dev_backend_reg(dev)); if (ggml_backend_dev_type(dev) != GGML_BACKEND_DEVICE_TYPE_GPU ||
all_metal = all_metal && strcmp(ggml_backend_reg_name(ggml_backend_dev_backend_reg(dev)), "MTL") != 0) {
ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_GPU && throw std::runtime_error("longhaul requires every model layer on Metal");
strcmp(reg_name, "MTL") == 0;
all_rpc = all_rpc &&
ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_GPU &&
strcmp(reg_name, "RPC") == 0;
}
if (!all_metal && !all_rpc) {
throw std::runtime_error(
"longhaul requires all model layers on local Metal or one RPC device");
}
if (all_metal) {
#if !defined(__APPLE__)
throw std::runtime_error("local longhaul is only supported on macOS");
#endif
} else {
ggml_backend_dev_t first = pimpl->dev_layer.front().dev;
for (int il = 1; il < n_layer_all; ++il) {
if (pimpl->dev_layer[il].dev != first) {
throw std::runtime_error(
"RPC longhaul v1 requires every model layer on one RPC device");
}
} }
pimpl->longhaul_remote = true;
} }
ml.configure_longhaul(params.longhaul_cache_bytes, n_expert, n_layer_all); ml.configure_longhaul(params.longhaul_cache_bytes, n_expert, n_layer_all);
if (ml.longhaul_slots < (size_t) n_expert_used) { if (ml.longhaul_slots < (size_t) n_expert_used) {
@@ -1715,8 +1694,7 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) {
if (params.load_mode == LLAMA_LOAD_MODE_LONGHAUL) { if (params.load_mode == LLAMA_LOAD_MODE_LONGHAUL) {
pimpl->longhaul = std::make_unique<llama_longhaul_cache>( pimpl->longhaul = std::make_unique<llama_longhaul_cache>(
std::move(ml.files), std::move(ml.longhaul_sources), std::move(ml.longhaul_shards), std::move(ml.files), std::move(ml.longhaul_sources), ml.longhaul_slots, hparams.n_expert, hparams.n_layer_all);
ml.longhaul_slots, hparams.n_expert, hparams.n_layer_all, pimpl->longhaul_remote);
} }
return true; return true;
+8 -13
View File
@@ -263,21 +263,16 @@ static bool llama_prepare_model_devices(const llama_model_params & params, llama
} }
} }
if (params.load_mode == LLAMA_LOAD_MODE_LONGHAUL && !rpc_servers.empty()) { // add RPC servers at the front of the list to minimize network transfers
// RPC longhaul v1 keeps the entire paging domain on one remote device. model->devices.insert(model->devices.begin(), rpc_servers.begin(), rpc_servers.end());
model->devices.push_back(rpc_servers.front());
} else {
// add RPC servers at the front of the list to minimize network transfers
model->devices.insert(model->devices.begin(), rpc_servers.begin(), rpc_servers.end());
// add GPUs // add GPUs
model->devices.insert(model->devices.end(), gpus.begin(), gpus.end()); model->devices.insert(model->devices.end(), gpus.begin(), gpus.end());
// add integrated GPUs only if no discrete GPUs were found // add integrated GPUs only if no discrete GPUs were found
// (RPC servers do not count, otherwise the local iGPU would be dropped on iGPU+RPC setups) // (RPC servers do not count, otherwise the local iGPU would be dropped on iGPU+RPC setups)
if (gpus.empty()) { if (gpus.empty()) {
model->devices.insert(model->devices.end(), igpus.begin(), igpus.end()); model->devices.insert(model->devices.end(), igpus.begin(), igpus.end());
}
} }
} }
+1 -2
View File
@@ -58,8 +58,7 @@ struct longhaul_fixture {
sources.push_back({ weights_b, 0, n_experts * expert_size, expert_size, 0 }); sources.push_back({ weights_b, 0, n_experts * expert_size, expert_size, 0 });
} }
cache = std::make_unique<llama_longhaul_cache>( cache = std::make_unique<llama_longhaul_cache>(
std::move(files), std::move(sources), std::vector<llama_model_loader::longhaul_shard>{}, std::move(files), std::move(sources), n_slots, n_experts, 1);
n_slots, n_experts, 1, false);
} }
~longhaul_fixture() { ~longhaul_fixture() {
+1 -11
View File
@@ -36,17 +36,6 @@ flowchart TD
By default, `ggml-rpc-server` exposes all available accelerator devices on the host. By default, `ggml-rpc-server` exposes all available accelerator devices on the host.
If there are no accelerators, it exposes a single `CPU` device. If there are no accelerators, it exposes a single `CPU` device.
For server-resident longhaul MoE paging, place the same GGUF shards on the RPC
host and point the server at their directory:
```sh
$ bin/ggml-rpc-server --device MTL0 --longhaul-root /path/to/model-directory
```
The client can then use `--rpc`, `--longhaul`, and `--longhaul-cache` together.
RPC longhaul v1 requires one remote Metal device. Expert cache misses are read
from the RPC host's local files rather than uploaded by the client.
## Usage ## Usage
### Remote hosts ### Remote hosts
@@ -118,3 +107,4 @@ Use the `GGML_RPC_DEBUG` environment variable to enable debug messages from `ggm
```bash ```bash
$ GGML_RPC_DEBUG=1 bin/ggml-rpc-server $ GGML_RPC_DEBUG=1 bin/ggml-rpc-server
``` ```
+3 -35
View File
@@ -13,7 +13,6 @@
#include <algorithm> #include <algorithm>
#include <clocale> #include <clocale>
#include <codecvt> #include <codecvt>
#include <cstring>
#include <filesystem> #include <filesystem>
#include <regex> #include <regex>
#include <stdio.h> #include <stdio.h>
@@ -174,7 +173,6 @@ struct rpc_server_params {
std::string host = "127.0.0.1"; std::string host = "127.0.0.1";
int port = 50052; int port = 50052;
bool use_cache = false; bool use_cache = false;
std::string longhaul_root;
int n_threads = std::max(1U, std::thread::hardware_concurrency()/2); int n_threads = std::max(1U, std::thread::hardware_concurrency()/2);
std::vector<std::string> devices; std::vector<std::string> devices;
}; };
@@ -188,7 +186,6 @@ static void print_usage(int /*argc*/, char ** argv, rpc_server_params params) {
fprintf(stderr, " -H, --host HOST host to bind to (default: %s)\n", params.host.c_str()); fprintf(stderr, " -H, --host HOST host to bind to (default: %s)\n", params.host.c_str());
fprintf(stderr, " -p, --port PORT port to bind to (default: %d)\n", params.port); fprintf(stderr, " -p, --port PORT port to bind to (default: %d)\n", params.port);
fprintf(stderr, " -c, --cache enable local file cache\n"); fprintf(stderr, " -c, --cache enable local file cache\n");
fprintf(stderr, " --longhaul-root PATH serve longhaul expert data from this model directory\n");
fprintf(stderr, "\n"); fprintf(stderr, "\n");
} }
@@ -236,11 +233,6 @@ static bool rpc_server_params_parse(int argc, char ** argv, rpc_server_params &
} }
} else if (arg == "-c" || arg == "--cache") { } else if (arg == "-c" || arg == "--cache") {
params.use_cache = true; params.use_cache = true;
} else if (arg == "--longhaul-root") {
if (++i >= argc) {
return false;
}
params.longhaul_root = argv[i];
} else if (arg == "-h" || arg == "--help") { } else if (arg == "-h" || arg == "--help") {
print_usage(argc, argv, params); print_usage(argc, argv, params);
exit(0); exit(0);
@@ -321,23 +313,6 @@ int main(int argc, char * argv[]) {
fprintf(stderr, "No devices found\n"); fprintf(stderr, "No devices found\n");
return 1; return 1;
} }
if (!params.longhaul_root.empty()) {
std::error_code ec;
const auto root = std::filesystem::canonical(params.longhaul_root, ec);
if (ec || !std::filesystem::is_directory(root, ec)) {
fprintf(stderr, "Invalid longhaul root: %s\n", params.longhaul_root.c_str());
return 1;
}
params.longhaul_root = root.string();
for (auto * dev : devices) {
auto * dev_reg = ggml_backend_dev_backend_reg(dev);
if (!dev_reg || strcmp(ggml_backend_reg_name(dev_reg), "MTL") != 0) {
fprintf(stderr, "--longhaul-root currently requires Metal devices\n");
return 1;
}
}
}
std::string endpoint = params.host + ":" + std::to_string(params.port); std::string endpoint = params.host + ":" + std::to_string(params.port);
const char * cache_dir = nullptr; const char * cache_dir = nullptr;
std::string cache_dir_str; std::string cache_dir_str;
@@ -356,19 +331,12 @@ int main(int argc, char * argv[]) {
return 1; return 1;
} }
auto start_server_fn = (decltype(ggml_backend_rpc_start_server_with_options)*) auto start_server_fn = (decltype(ggml_backend_rpc_start_server)*) ggml_backend_reg_get_proc_address(reg, "ggml_backend_rpc_start_server");
ggml_backend_reg_get_proc_address(reg, "ggml_backend_rpc_start_server_with_options");
if (!start_server_fn) { if (!start_server_fn) {
fprintf(stderr, "Failed to obtain RPC backend start server function with options\n"); fprintf(stderr, "Failed to obtain RPC backend start server function\n");
return 1; return 1;
} }
start_server_fn( start_server_fn(endpoint.c_str(), cache_dir, params.n_threads, devices.size(), devices.data());
endpoint.c_str(),
cache_dir,
params.longhaul_root.empty() ? nullptr : params.longhaul_root.c_str(),
params.n_threads,
devices.size(),
devices.data());
return 0; return 0;
} }