KTransformers: CPU-GPU Heterogeneous Inference Framework

repository·main·Indexed 12 days ago

https://github.com/kvcache-ai/ktransformers

A framework for efficient LLM inference and fine-tuning using CPU-GPU heterogeneous computing, specifically optimized for large Mixture-of-Experts (MoE) models. It allows running 'hot' experts on GPU and 'cold' experts on CPU to optimize resource utilization. Features include the kt-kernel package, a CLI tool for model management, and integration with a specialized fork of SGLang (sglang-kt). Supports AMX, AVX512, and AVX2 CPU variants, as well as GGUF weights via the LLAMAFILE backend.

Tokens
97K
Snippets
294
Records
407
Agent score
97%

What's inside KTransformers

  1. Overview of KTransformers

    main

    KTransformers is a research project designed for efficient inference and fine-tuning of Large Language Models (LLMs) using CPU-GPU heterogeneous computing. It optimizes performance for large Mixture-of-Experts (MoE) models by leveraging hybrid hardware resources.

    The project provides two primary user-facing capabilities:

    1. Inference: High-performance serving via kt-kernel using CPU-optimized kernel operations.
    2. SFT (Supervised Fine-Tuning): Integration with LLaMA-Factory for fine-tuning ultra-large MoE models on limited GPU memory.
  2. Use the ktransformers Server API for model inference

    main

    The ktransformers Server provides a RESTful API for external model inference. It offers two primary interaction modes designed for compatibility with existing ecosystems:

    1. ChatCompletion: Best for stateless interactions. This interface is compatible with the OpenAI and Ollama ChatCompletion APIs. Users must provide the entire dialogue history in each request. This allows for seamless switching from OpenAI or Ollama to the ktransformers Server.

    2. Assistant: Best for stateful, complex applications (e.g., educational bots). This interface is compatible with the OpenAI Assistant API. It allows developers to:

      • Create an Assistant with a specific system prompt and uploaded materials.
      • Create a Thread to manage conversational state.
      • Create a Run to execute the model and obtain responses.

    The Assistant mode handles the reuse of conversational contexts and multi-turn dialogues automatically, reducing the complexity of managing history in the client application.

  3. Hardware Requirements for Kimi-K2.5 LoRA SFT

    main

    The hardware requirements differ significantly between the training (SFT) phase and the inference (serving) phase.

    Training (LoRA SFT)

    • GPU: 4 * NVIDIA RTX 4090 24GB (or equivalent with at least 48GB total VRAM).
    • CPU: x86 CPU with AMX support.
    • RAM: At least 2TB system memory (Swap can be used if insufficient).

    Inference (LoRA Adapter + Original Model)

    • GPU: 2 * NVIDIA RTX 4090 24GB (or equivalent with at least 48GB total VRAM).
    • CPU: x86 CPU with AVX512F support (e.g., Intel Sapphire Rapids).
    • RAM: At least 600GB system memory.
    • Storage: ~600GB for model weights (native INT4 weight).
  4. Accelerate long-context inference with KTransformers

    main

    KTransformers provides a method to reduce the inference barrier for ultra-long context sequences (e.g., 128K to 1M tokens) on heterogeneous CPU/GPU systems. It leverages the sparsity of attention to achieve significant speedups compared to standard implementations like llama.cpp.

    Key Performance Benchmarks (Example: InternLM2.5-7B-Chat-1M):

    • 128K Context: Up to 7.1x faster than llama.cpp with 100% accuracy on 'needle in haystack' and 'passkey' tests. On kvretrieval datasets, it can achieve a 6.22x speedup while improving accuracy (e.g., 21.2 -> 24.4).
    • 1M Context: On a single 24GB GPU, it can achieve ~16 tokens/s (nearly 10x faster than llama.cpp) and can improve 'needle in haystack' scores (e.g., 89.31 -> 92.88).
  5. What is KT-Kernel

    main

    KT-Kernel is a high-performance kernel library for KTransformers designed to provide efficient MoE (Mixture-of-Experts) inference on CPUs. It optimizes throughput for MoE expert kernels by leveraging specific CPU instruction sets.

    Supported Backends & CPU Requirements:

    BackendMinimum CPU RequirementExample CPUsDescription
    LLAMAFILEAVX2Intel Haswell (2013+), AMD Zen+General compatibility
    RAWINT4AVX512F + AVX512BWIntel Skylake-X (2017+), Ice Lake, Cascade LakeSupports VNNI/BF16 software fallback
    AMXINT4/INT8AMXIntel Sapphire Rapids (2023+)Best performance; requires AMX hardware

    Key Features:

    • CPU-friendly MoE Kernels: Optimized for high-throughput expert inference.
    • AMX INT4/INT8 Backend: Quantized expert inference for Intel CPUs with AMX support.
    • Llamafile CPU Backend: Based on Llamafile (AVX2/AVX512) for general CPU deployment.
    • NUMA-aware Execution: Optimized thread pools and memory layout for multi-socket/multi-NUMA machines.
  6. What is the Llamafile Sgemm module?

    main
    The Llamafile Sgemm module is a high-performance implementation of general matrix multiplication (GEMM) optimized for various processor instruction sets. It automatically detects and leverages x86 instruction sets such as AVX, FMA, and AVX512 to accelerate computation. It supports multiple quantization types, including q8_0, q6_k, and q5_k, ensuring high computational efficiency across different hardware environments.
  7. Integrate KT-Kernel with SGLang for Heterogeneous Inference

    main

    KT-Kernel enables CPU-GPU heterogeneous inference by running "hot" experts on the GPU and "cold" experts on the CPU. This allows for optimal resource utilization by leveraging both GPU VRAM and CPU memory/compute. To use this, you must integrate KT-Kernel with the kvcache-ai fork of SGLang.

    python -m sglang.launch_server \
      [your normal SGLang parameters...] \
      --kt-method AMXINT8 \
      --kt-weight-path /path/to/cpu-weights \
      --kt-cpuinfer 64 \
      --kt-threadpool-count 2 \
      --kt-num-gpu-experts 32 \
      --kt-max-deferred-experts-per-token 2
  8. Configure CPU variants in KTransformers

    main

    The KTransformers Docker image includes support for multiple CPU instruction sets: AMX (Intel Sapphire Rapids+), AVX512, and AVX2. While the runtime performs automatic detection, you can manually override the variant using the KT_KERNEL_CPU_VARIANT environment variable.

    To force a specific variant (e.g., avx2) and debug the loading process, use:

    export KT_KERNEL_CPU_VARIANT=avx2
    export KT_KERNEL_DEBUG=1
    python your_script.py
  9. Request semantics for KT LoRA serving

    main

    When using the merged adapter workflow, the model field in your OpenAI-compatible API requests follows a specific naming convention based on the --served-model-name and the name assigned in --lora-paths.

    If you launch with: --served-model-name qwen3.5-kt-ft and --lora-paths qwen35b_lora=/path/to/merged_adapter

    Then:

    • model=qwen3.5-kt-ft results in: Base Model + KT Expert LoRA
    • model=qwen3.5-kt-ft:qwen35b_lora results in: Base Model + KT Expert LoRA + SGLang Non-expert LoRA

    The suffix after the colon (:) must exactly match the name provided on the left side of the --lora-paths assignment.

    --served-model-name qwen3.5-kt-ft
    --lora-paths qwen35b_lora=/path/to/merged_adapter
    
    Request model names:
    model=qwen3.5-kt-ft
    model=qwen3.5-kt-ft:qwen35b_lora
  10. How AMX optimizations work in KTransformers

    main

    KTransformers v0.3 introduces a specialized optimization path for Intel AMX (Advanced Matrix Extensions) to eliminate CPU bottlenecks during MoE inference. The optimization relies on three core pillars:

    1. AMX Tiling-aware Memory Layout: Instead of direct memory-mapping GGUF files, KTransformers performs preprocessing during model loading. Expert weight matrices are rearranged into sub-matrices that match AMX Tile register dimensions. This includes 64-byte alignment to prevent cache line splits and sequential arrangement to maximize L1/L2 cache hits.
    2. Cache-friendly AMX Kernel: The kernel is designed to minimize DRAM access. Expert weights are partitioned into blocks sized to fit within the L2 cache. Input activations are shared via the L3 cache. This ensures that most data movement happens within high-speed CPU caches rather than main memory.
    3. Dynamic Kernel Selection (AMX vs. AVX-512): AMX is highly efficient for large matrix multiplications (high arithmetic intensity) but has high overhead for small operations. KTransformers automatically switches kernels at runtime:
      • AMX Kernels: Used during long prompt prefill phases (where each expert handles >4 tokens on average).
      • AVX-512 Kernels: Used during short prompt prefill and the decode phase (low arithmetic intensity) to reduce latency.
  11. Expert Placement Strategies for MoE Models

    main

    KTransformers provides four strategies for distributing MoE experts between CPU and GPU via the --kt-expert-placement-strategy flag:

    StrategyDescriptionUse Case
    uniformDistributes GPU experts evenly across all MoE layersDefault, no prior statistics needed
    frequencyPlaces most frequently activated experts on GPUBest performance when activation statistics are available
    front-loadingFills GPU experts from the first layer onwardsTesting or specific workload patterns
    randomRandomly selects experts with fixed seed (42)Baseline comparison
  12. Understand KTransformers version features and optimizations

    main

    KTransformers has evolved through several versions, each introducing specific optimizations for DeepSeek models:

    V0.2.1 Improvements

    • Longer Context: Increased context support from 4K to 8K for 24GB VRAM setups.
    • Triton MLA Kernel: Integrated the highly efficient Triton MLA Kernel (from sglang) to enable longer context and faster prefill/decode speeds.
    • Speed: Approximately 15% speedup in prefill/decode over V0.2.

    V0.3-Preview Optimizations

    • Intel AMX Acceleration: Uses the Intel AMX instruction set and a cache-friendly memory layout for massive prefill speedups.
    • Selective Expert Activation: Implements an expert selection strategy that selects fewer experts based on offline profiling. This reduces computational load without significantly impacting output quality.
    • Performance: Prefill is up to 3.45x faster than V0.2.