Cactus AI Inference Engine

repository·main·Indexed 26 days ago

https://github.com/cactus-compute/cactus

An AI inference engine for mobile devices and wearables supporting high-performance quantization and multimodal inference (text, vision, audio). It provides a core engine, libcactus_engine, with language bindings for Python, Swift, Kotlin (KMP), Flutter (Dart FFI), Rust, and React Native. Supports streaming transcription using 16 kHz mono PCM16 audio and provides build tools for Android (arm64-v8a), iOS, and macOS.

Tokens
72K
Snippets
155
Records
429
Agent score
91%

What's inside Cactus

  1. Overview of Parakeet-CTC-1.1B Architecture

    main

    Parakeet CTC 1.1B is a non-autoregressive English speech-to-text model built on NVIDIA's FastConformer. It is optimized for high-speed, on-device transcription.

    Key Components:

    • Audio Front-end: Converts input audio to log-mel features followed by an 8x depthwise-separable convolutional subsampler.
    • FastConformer Encoder: Uses Limited Context Attention (LCA) for local efficiency and Global Tokens (GT) for long-range context.
    • CTC Projection Head: Projects encoder states directly to token logits using CTC (Connectionist Temporal Classification) decoding, enabling highly parallel inference and low latency.
  2. Overview of Cactus Quants (CQ) quantization

    main

    Cactus Quants (CQ) is a post-training quantization (PTQ) system designed for on-device multimodal model deployment. Unlike standard PTQ methods (like GPTQ, AWQ, or HQQ) that primarily target transformer linear layers, CQ applies a unified rotation-and-codebook recipe to every weight tensor in a multimodal model, including:

    • Transformer linears
    • Vision encoders (vision towers)
    • Audio encoders (audio towers)
    • Cross-modal bridges
    • Per-layer embedding tables
    • Shared token embeddings

    CQ supports bit widths ranging from 4-bit down to 1-bit and is specifically optimized to maintain accuracy in multimodal settings and for embedding tables where activation-based methods fail.

  3. Overview of TurboQuant-H for Embedding Quantization

    main

    TurboQuant-H is an offline quantization variant designed specifically for per-layer input (PLI) embedding tables. It is optimized for models where embeddings constitute a large portion of the total weight storage (e.g., models using the AltUp architecture like Gemma 4 E2B or Gemma 3n).

    Key features include:

    • Hadamard Rotation: Replaces the random orthogonal rotation used in standard TurboQuant to simplify the offline process.
    • Per-group Lloyd-Max Codebooks: Uses specialized codebooks for quantization.
    • High Compression: Can achieve significant memory reduction (e.g., 4x compression on Gemma 4 E2B) at approximately 2.125 effective bits per dimension.
    • Low Overhead: Designed to reduce total LLM storage (up to 40% in tested cases) with minimal perplexity increase and no measured speed regression.
  4. Component Pipeline vs Monolithic Capture

    main

    The transpiler chooses between two output shapes based on the model architecture:

    • Component Pipeline: Used for models that benefit from staged graphs. This splits the model into independent components (e.g., vision_encoder, audio_encoder, lm_encoder, decoder for Gemma4 multimodal). This is triggered if component specs exist and --component-pipeline is set to auto or on.
    • Monolithic Capture: Used for simpler tasks (e.g., text logits or encoder-only audio) where the entire model is captured as a single wrapped graph.
  5. Supported language bindings for Cactus

    main

    Cactus provides bindings for multiple platforms and languages. Depending on your target environment, the underlying integration mechanism differs:

    • Python: Uses ctypes.
    • Swift: Uses a C module map.
    • Kotlin (KMP): Uses JNI on Android and Kotlin/Native cinterop on iOS.
    • Flutter: Uses Dart FFI.
    • Rust: Uses raw extern "C" declarations.
    • React Native: Uses a thin React Native bridge backed by the raw Kotlin and Swift bindings.
  6. Setup the Cactus Graph environment

    main

    To set up your development environment, install dependencies, build the library, and verify the installation, run the following commands:

    # Setup the environment and install dependencies
    source ./setup
    
    # Build the Cactus library
    cactus build
    
    # Run tests to verify everything works
    cactus test
    source ./setup
    cactus build
    cactus test
  7. Manage Cactus runtime and model weight compatibility

    main

    Cactus releases may change the internal weight format. When a breaking weight change occurs, cached weights from older versions will not load with a newer runtime and must be re-downloaded.

    Compatibility Rule: Always use the latest Hugging Face weight tag that is less than or equal to ($\le$) your current Cactus runtime version.

    Versioning Behavior: Weights are only re-tagged on Hugging Face when the format actually changes. If a runtime release does not affect the weight format, the previous tag remains valid and no new upload is performed.

  8. Locate and use Cactus Python Bindings

    main

    The Cactus Python bindings use ctypes FFI to interface with cactus_engine.h. The core binding module is located at /python/cactus/bindings/cactus.py.

    To use these bindings, the module requires the shared library libcactus_engine.{so,dylib}. This library is expected to be found in one of two locations:

    1. /python/cactus/bindings/lib/ (the bundled version)
    2. cactus-engine/build/ (for development builds)

    For high-level API usage, CLI commands, or server setup, refer to the main Python documentation at /python/README.md.

  9. Understand the TurboQuant-H Quantization Pipeline

    main

    TurboQuant-H is a method for 2-bit embedding weight quantization used during the cactus convert process. It uses Hadamard rotation to concentrate coordinates and Lloyd-Max codebooks for quantization.

    Quantization (Offline/Conversion):

    1. Partitioning: Divide the PLI embedding matrix into positional groups of $G=128$ contiguous elements.
    2. Hadamard Rotation: Apply a normalized Hadamard rotation $\hat{\mathbf{x}}_{v,p} = \bar{\mathbf{H}}G \cdot \mathbf{x}{v,p}$ to each group. The normalization factor is $1/\sqrt{G}$.
    3. Codebook Training: For each positional group, train a Lloyd-Max codebook $\mathcal{C}_p$ containing 4 centroids (for 2-bit quantization) in FP16.
    4. Quantization: Map each rotated element to its nearest centroid and store the 2-bit index.

    Dequantization (Inference/Runtime):

    1. Gather: Look up the 2-bit indices and the corresponding positional codebook.
    2. Scatter: Replace indices with their FP16 centroid values.
    3. Inverse Rotation: Apply the same Hadamard rotation (since $\bar{\mathbf{H}}_G$ is symmetric and self-inverse) to return to the original space.
    4. Output: Resulting FP16 embedding is fed to the transformer layer.
    QUANTIZATION (offline, during cactus convert)
    ==============================================
    
    PLI Matrix E  (262K x 8190)
          |
          v
    +-----------------------+
    | Partition into        |
    | groups of G=128       |
    +-----------+-----------+
                |
                v
    +-----------------------+
    | Hadamard rotation     |
    | x_hat = (1/sqrt(G)) * H_128 * x
    | per group             |
    +-----------+-----------+
                |
                v
    +-----------------------+
    | Lloyd-Max codebook    |
    | Train 4 centroids (2-bit) per position
    | across all 262K vocab rows
    | C_p = {c1, c2, c3, c4} in FP16
    +-----------+-----------+
                |
                v
    +-----------------------+
    | Quantize by           |
    | proximity             |
    | q = argmin_j |x_hat_i - c_j|
    | Store 2-bit indices per element
    +-----------+-----------+
    Output: 2-bit index tensor + 64 FP16 codebooks
    Effective: 2.125 bits/element
    
    DEQUANTIZATION (at inference, per token)
    =========================================
    
    Token IDs
          |
          v
    +-----------------------+
    | Gather 2-bit indices  |
    | + codebook per pos.   |
    +-----------+-----------+
                |
                v
    +-----------------------+
    | Scatter codebook      |
    | Replace 2-bit indices with FP16
    | centroid values from C_p
    +-----------+-----------+
                |
                v
    +-----------------------+
    | Hadamard rotation     |
    | x_tilde = (1/sqrt(G)) * H_128 * scatter(...)
    | (same as forward,     |
    | H_bar is symmetric: H_bar = H_bar^T = H_bar^-1
    +-----------+-----------+
                |
                v
    FP16 embedding -> feed to transformer layer
  10. Install the Cactus CLI

    main

    You can install the Cactus CLI via Homebrew on macOS or by building from source on macOS and Linux.

    # Homebrew (macOS)
    brew install cactus-compute/cactus/cactus
    
    # From Source (macOS)
    brew install cmake
    git clone https://github.com/cactus-compute/cactus && cd cactus && source ./setup && cactus build --python
    
    # From Source (Linux)
    sudo apt-get install python3.12 python3.12-venv python3-pip cmake build-essential libcurl4-openssl-dev
    git clone https://github.com/cactus-compute/cactus && cd cactus && source ./setup && cactus build --python