llama-cpp-turboquant Documentation

repository·feature/turboquant-kv-cache·Indexed 24 days ago

https://github.com/thetom/llama-cpp-turboquant

Documentation for llama-cpp-turboquant, featuring llama-ui (a SvelteKit web interface for llama-server), a C++ implementation of the Jinja template engine for chat templates, and detailed guides for building and running llama.cpp on Snapdragon-based Android and Windows arm64 devices using CPU, OpenCL, and Hexagon NPU backends. Includes instructions for batched generation, llama2.c model conversion, and model debugging via llama-debug.

Tokens
164.3K
Snippets
352
Records
840
Agent score
80%

What's inside llama-cpp-turboquant

  1. Overview of the GGML-VirtGPU Backend

    feature/turboquant-kv-cache

    The GGML-VirtGPU backend allows GGML applications (like llama.cpp) running inside a virtual machine (Guest) to perform machine learning computations on the host hardware. It achieves this by splitting the backend into two parts:

    1. Guest-side Frontend (ggml-virtgpu/): Implements the GGML backend interface and forwards operations to the host via hypercalls and shared memory.
    2. Host-side Backend (ggml-virtgpu/backend/): Receives forwarded operations and executes them on actual hardware backends (e.g., Metal, Vulkan, CUDA, or CPU).

    This architecture enables high-performance computation in virtualized environments using zero-copy data transfers via host-guest shared memory.

  2. What is GBNF and how to use it

    feature/turboquant-kv-cache

    GBNF (GGML BNF) is a grammar format used to constrain model outputs in llama.cpp. It allows you to force a model to follow specific syntax, such as valid JSON, specific notation (like chess moves), or restricted character sets (like emojis).

    GBNF grammars are supported via:

    • llama-cli and llama-completion using --grammar or --grammar-file flags.
    • llama-server completion endpoints via the grammar body field.
    • test-gbnf-validator for testing grammars against strings.
    ./llama-cli -m <model> --grammar-file grammars/some-grammar.gbnf -p 'Some prompt'
  3. Overview of the PEG Parser for Model Output

    feature/turboquant-kv-cache

    The common library provides a Parsing Expression Grammar (PEG) implementation specifically designed for parsing model outputs. It supports partial parsing of streaming input, built-in JSON parsing, and AST generation with semantic tagging.

    There are two main namespaces of types:

    • common_peg_*: General-purpose PEG types for various parsing tasks.
    • common_chat_peg_*: Specialized helpers optimized for parsing model chat outputs (e.g., extracting reasoning, content, and tool calls).
  4. Use llama-bench for performance testing

    feature/turboquant-kv-cache

    Overview

    llama-bench is a performance testing tool for llama.cpp used to measure the speed of prompt processing, text generation, and both combined. It reports results in average tokens per second (t/s) and standard deviation.

    Test Types

    llama-bench performs three types of tests:

    • Prompt processing (pp): Processing a prompt in batches using -p.
    • Text generation (tg): Generating a sequence of tokens using -n.
    • Prompt processing + text generation (pg): A combination of both using -pg.

    Key Features

    • Repetitions: Each test is repeated -r times (default: 5) and results are averaged.
    • Context Depth: Use -d <n> to run tests at a specific context depth by prefilling the KV cache with <n> tokens.
    • Batching: Specify prompt length (-p), generation length (-n), batch size (-b), and micro-batch size (-ub).
    • Hardware Control: Control GPU offloading (-ngl), thread counts (-t), and NUMA modes (--numa).
    • Multiple Tests: Most options can be specified multiple times or with comma-separated values to run a matrix of tests (e.g., -n 16,32,64).
    NOTE

    Measurements do not include the time taken for tokenization and sampling.

    usage: llama-bench [options]
  5. Features of the llama-ui Web UI

    feature/turboquant-kv-cache

    The Web UI provides several capabilities for interacting with llama-server:

    • Chat Interface: Supports streaming responses.
    • Multi-model Support (ROUTER mode): Allows switching between models with automatic loading upon selection.
    • Modality Validation: Automatically checks if the selected model supports specific attachments (images, audio).
    • Conversation Management: Supports branching, regeneration, and editing while preserving history.
    • Attachment Support: Handles images, audio, and PDFs (utilizing vision or text fallbacks).
    • Configurable Parameters: Syncs parameters like temperature and top_p with server defaults.
    • Theming: Supports both Dark and Light modes.
  6. What is Speculative Decoding in llama.cpp

    feature/turboquant-kv-cache
    Speculative decoding is an acceleration technique used in llama.cpp to speed up token generation. It works by using a smaller, faster 'draft model' to predict multiple tokens ahead of time. These predicted tokens are then verified by the main (target) model in a single batch operation. Because batch processing is more efficient than sequential generation, this approach provides significant speedups when the draft model's predictions are frequently correct.
  7. What is libmtmd?

    feature/turboquant-kv-cache

    libmtmd is the modern library designed to replace the original llava.cpp implementation for handling multimodal inputs. It is built upon clip.cpp and provides several key improvements:

    • Unified Interface: Consolidates interaction for various multimodal models into a single system.
    • Improved UX/DX: Offers a more intuitive API inspired by the Processor class in the Hugging Face transformers library.
    • Flexibility: Supports multiple input types, including text, audio, and images, while managing the diverse chat templates required by different models.
  8. Understand JSON_NATIVE tool calling format

    feature/turboquant-kv-cache

    In JSON_NATIVE mode, the entire tool call (function name, arguments, and values) is contained within a JSON structure. The function name is detected when it appears inside a JSON structure (e.g., preceded by { or :).

    // Standard OpenAI-style
    <tool_call>
    {"name": "get_weather", "arguments": {"location": "Paris", "unit": "celsius"}}
    </tool_call>
    
    // Mistral Nemo with array wrapper
    [TOOL_CALLS]
    [{"name": "calculate", "arguments": {"expr": "2+2"}}]
    
    // Function name as JSON key (Apertus style)
    {"get_weather": {"location": "Paris"}}
  9. Understand TAG_WITH_TAGGED tool calling format

    feature/turboquant-kv-cache

    In TAG_WITH_TAGGED mode, both the function name and the argument names are contained within XML-style tags. String values are unquoted, while non-string values (like objects or booleans) use JSON formatting.

    <!-- Qwen/Hermes XML format -->
    <function=get_weather>
    <param=location>Paris</param>
    <param=unit>celsius</param>
    </function>
    
    <!-- Mixed types -->
    <function=calculate>
    <param=expr>2+2</param>
    <param=precision>2</param>
    <param=options>{"round": true}</param>
    </function>
  10. How the Agentic Loop works

    feature/turboquant-kv-cache

    When agenticConfig.enabled is true and MCP servers are connected, the chatStore delegates the request to agenticStore.runAgenticFlow. This initiates a multi-turn loop:

    1. Turn Execution: The agent calls ChatService.sendMessage().
    2. Tool Detection: If the API response contains tool_calls, the loop continues.
    3. Tool Execution: For each tool_call, the mcpStore.executeTool() is called.
    4. Result Integration: Tool results (including base64 attachments) are appended to the conversation as new messages.
    5. Loop/Termination: The loop repeats with the updated message history until either no more tool_calls are returned or maxTurns is reached.
    6. Finalization: The final response and accumulated timings are returned to the chatStore.
  11. How the MCP (Model Context Protocol) flow works

    feature/turboquant-kv-cache

    The Model Context Protocol (MCP) implementation in llama-ui manages the lifecycle of connections to external MCP servers, tool execution, resource management, and prompt operations. The architecture relies on several specialized stores:

    • mcpStore: The central orchestrator. It manages server configurations, connection states, health checks, and a toolsIndex (mapping tool names to their respective servers). It also handles tool execution and prompt retrieval.
    • mcpResStore (mcpResourceStore): Manages MCP resources, including server resources, cached resource content, subscriptions, and active attachments.
    • MCPSvc (MCPService): The service layer responsible for low-level transport (WebSocket, StreamableHTTP, or SSE) and protocol handshakes with external servers.
    • chatStore: Consumes MCP resources as message extras to provide context to the LLM.

    Key Lifecycle Flows

    1. Initialization

    Upon app startup, mcpStore.ensureInitialized() is called. It retrieves server settings from LocalStorage, parses them, and for each enabled server, initiates a connection via MCPSvc. This process includes a transport handshake, capability exchange, and indexing of available tools and resources.

    2. Tool Execution

    When a tool is called (e.g., via executeTool(mcpCall)), the mcpStore resolves the correct server using the toolsIndex. It acquires a connection (incrementing activeFlowCount to prevent shutdown during execution), calls the tool via MCPSvc, and formats the result (handling text, images, or embedded resources) before releasing the connection.

    3. Resource & Prompt Management

    • Prompts: mcpStore can list all prompts from connected servers or fetch a specific prompt using getPrompt(serverName, promptName, args?).
    • Resources: Users can add attachments via mcpResStore.addAttachment(). Content is fetched using mcpStore.readResource(serverName, uri) and cached in the mcpResStore.