Перейти к содержанию

Шпаргалка: инференс и сервинг LLM

~9 минут чтения

Предварительно: Архитектура трансформера | Позиционное кодирование и внимание

Справочная карточка по production-инференсу больших языковых моделей. KV cache для Llama 70B при 4K контексте занимает ~10 GB на запрос -- без оптимизации один H100 обслужит лишь 8 параллельных сессий. PagedAttention (vLLM) снижает waste с 60-80% до <4%, а speculative decoding (EAGLE-3) ускоряет генерацию в 2-4x без потери качества. Эта шпаргалка покрывает движки инференса (vLLM, SGLang, TensorRT-LLM), KV cache оптимизацию, квантизацию (AWQ/GPTQ/FP8), MoE, длинный контекст (Ring Attention до 10M+ токенов), SSM и test-time compute scaling.

Тип: synthesis / interview cheat sheet Дата: Февраль 2026 Synthesis of: 64 source files


Quick Reference: Key Numbers

Metric Value Context
KV Cache (Llama 70B, 4K) ~10 GB per request Memory formula: \(2 \times L \times H \times d \times T \times 2\) bytes
PagedAttention waste <4% vs 60-80% vLLM block allocation
Speculative Decoding speedup 1.8-4× EAGLE-3 on Llama-8B: 2.36×
Quantization memory (4-bit) 75% reduction AWQ/GPTQ/GGUF
MoE active params 12-15% Mixtral 8×7B: 12.5B/47B
Long context (Ring Attention) 10M+ tokens Distributed across GPUs

1. Inference Engines (2026)

Comparison Table

Engine Strength Best For Key Feature
vLLM Balanced General serving PagedAttention, OpenAI API
SGLang Throughput Agents, RAG RadixAttention, structured output
TensorRT-LLM Latency NVIDIA GPUs CUDA graphs, B200 optimized
llama.cpp Portability CPU/Edge GGUF, Apple Metal

Decision Matrix

Need maximum throughput?     → SGLang + RadixAttention
Need lowest latency?         → TensorRT-LLM on H200/B200
Running on CPU/laptop?       → llama.cpp + GGUF
Need OpenAI compatibility?   → vLLM (easiest integration)
Complex agent workflows?     → SGLang (3× faster on agents)

Code: vLLM vs SGLang

# vLLM
from vllm import LLM, SamplingParams
llm = LLM(model="meta-llama/Llama-3.1-70B", tensor_parallel_size=4)

# SGLang
import sglang as sgl
@sgl.function
def generate(s, prompt):
    s += prompt + sgl.gen("response", max_tokens=256)

2. KV Cache Optimization

Memory Formula

\[\text{KV Cache} = 2 \times L \times H \times d_{head} \times T \times 2 \text{ bytes}\]

Example (Llama 70B, 4K context): - 80 layers × 64 heads × 128 dim × 4096 tokens × 2 (K+V) × 2 bytes ≈ 10 GB

Optimization Methods

Method Memory Waste Speedup Mechanism
Static allocation 60-80% Baseline Pre-allocate max length
PagedAttention <4% 2-24× Block-based allocation
Prefix caching <2% 3-30× Hash shared prefixes
RadixAttention <1% 4-40× Token-level radix tree

When to Use What

Simple chatbot?              → PagedAttention (vLLM)
Multi-turn conversations?    → Prefix caching
Agent workflows?             → RadixAttention (SGLang)
Very long contexts?          → LMCache + CPU offload

3. Speculative Decoding

How It Works

1. Draft model generates N tokens (fast, cheap)
2. Target model verifies all N in ONE forward pass
3. Accept longest matching prefix
4. Output = lossless (identical to standard)

Methods Comparison

Method Draft Source Speedup Notes
EAGLE-3 Multi-layer features 2-4× Best quality/speed
EAGLE-2 Single-layer features 1.5-2.5× Broad compatibility
MTP Built-in heads 1.5-2× DeepSeek native
NGRAM Token statistics 1.2-1.5× Training-free
Standalone Smaller LLM 1.3-1.8× Any draft model

Acceptance Rate Impact

Acceptance Rate: 33.8% → 1.82× speedup (Qwen3-32B)
Acceptance Rate: 65%   → 2.5× speedup
Acceptance Rate: 80%   → 3×+ speedup

Code: Enable EAGLE-3

# vLLM
vllm serve Qwen/Qwen3-32B \
  --speculative-config '{"model": "RedHatAI/Qwen3-32B-speculator.eagle3", "num_speculative_tokens": 3, "method": "eagle3"}'

# SGLang
python -m sglang.launch_server \
  --model meta-llama/Llama-3.1-8B-Instruct \
  --speculative-algorithm EAGLE3 \
  --speculative-draft-model-path lmsys/sglang-EAGLE3-llama3.1-8B

4. Quantization

Methods Comparison

Method Bits Speed Quality Best For
FP16/BF16 16 Baseline 100% Training, highest quality
INT8 8 1.5-2× 99%+ Balanced serving
AWQ 4 2-3× 98%+ Activation-aware
GPTQ 4 2-3× 97-99% Static calibration
GGUF 4-8 2-4× 95-99% CPU/Apple
FP8 8 1.5-2× 99%+ H100/Blackwell

Decision Framework

Production GPU serving?      → AWQ or GPTQ (4-bit)
Running on laptop?          → GGUF (llama.cpp)
Need training?              → FP16/BF16 or FP8
H100/Blackwell available?   → FP8 training + inference
Edge deployment?            → INT8 or GGUF Q4_K_M

Quality vs Size Trade-off

BF16 (100% quality) → 140 GB (Llama 70B)
INT8 (99.5% quality) → 70 GB
AWQ-4 (98% quality) → 35 GB
GGUF Q4_K_M (97% quality) → 40 GB

5. MoE (Mixture of Experts)

Architecture

Input → Router → Top-K Experts → Aggregation → Output
        Load Balancing Loss

Key Models

Model Total Params Active Params Experts Top-K
Mixtral 8×7B 47B 12.5B 8 2
DeepSeek V2 236B 21B 160 6
DeepSeek V3 671B 37B 256 8
Grok-1 314B 80B 8 2

Load Balancing Methods

Method Description Pros Cons
Auxiliary Loss Penalty for imbalance Simple Interferes with main loss
Loss-Free (DeepSeek V3) Dynamic bias per expert No interference Complex routing
SIMBAL Similarity-preserving 36% faster convergence New (2025)

Code: MoE Layer

class MoELayer(nn.Module):
    def __init__(self, d_model, d_ff, num_experts, top_k):
        self.experts = nn.ModuleList([Expert(d_model, d_ff) for _ in range(num_experts)])
        self.router = nn.Linear(d_model, num_experts)
        self.top_k = top_k

    def forward(self, x):
        # Router scores
        scores = F.softmax(self.router(x), dim=-1)
        topk_scores, topk_indices = torch.topk(scores, self.top_k)

        # Dispatch to experts
        output = torch.zeros_like(x)
        for i in range(self.top_k):
            expert_idx = topk_indices[:, :, i]
            expert_weight = topk_scores[:, :, i].unsqueeze(-1)
            expert_out = self.experts[i](x)
            output = output + expert_weight * expert_out

        return output

6. Long Context (2026)

Methods Comparison

Method Context Length Memory Mechanism
Standard attention 4-8K O(T²) Full attention matrix
Ring Attention 1M+ O(T/N) Distributed across GPUs
Infini-Attention Unlimited O(1) Compressive memory
Star Attention 128K O(T) Two-phase block-sparse
Context Parallelism 1M+ O(T/N) NeMo activation recompute

Ring Attention Formula

\[n_{\max} = n_{\text{local}} \times N_{\text{devices}}\]

Example: 128K local × 8 GPUs = 1M tokens

When to Use What

Context < 32K?              → Standard attention
Context 32K-128K?           → FlashAttention-3
Context 128K-1M?            → Ring Attention or Star Attention
Context > 1M?               → Ring Attention distributed
Bounded memory required?    → Infini-Attention (some quality loss)

7. State Space Models (SSM)

Why SSMs?

Aspect Transformer SSM (Mamba)
Complexity O(T²) O(T)
Memory KV cache grows Fixed state
Training Parallel Parallel
Inference Slow for long Fast, constant
Quality SOTA Near-SOTA

SSM Evolution

S4 (2022) → H3 (2022) → Mamba (2023) → Mamba-2 (2024) → Mamba-3 (2026)
                              Hybrid: Jamba, Bamba, Nemotron-H

Hybrid Architecture Ratio

Jamba: 1 Transformer layer : 7 Mamba layers

# Hybrid pattern
class HybridBlock(nn.Module):
    def __init__(self, d_model, layer_idx):
        if layer_idx % 8 == 0:
            self.layer = TransformerLayer(d_model)  # 1/8
        else:
            self.layer = MambaLayer(d_model)        # 7/8

When to Use SSMs

Short sequences (<1K)?      → Transformer
Medium (1K-16K)?            → SSM or Hybrid
Very long (>16K)?           → SSM or xLSTM
Memory-constrained?         → SSM (fixed memory)
Need SOTA quality?          → Transformer or Hybrid

8. Test-Time Compute Scaling

Methods

Method Description Example
Parallel Sample N, pick best Best-of-N
Sequential Iterate and refine Self-correction
Tree Search MCTS over tokens o1, R1
Latent Internal reasoning o1 hidden chain

Key Finding (DeepMind)

1B model + test-time scaling > 405B model without scaling

Cost-Benefit

More compute at inference = Better quality
But: Diminishing returns after ~100× FLOPs

Optimal: Balance training compute with inference compute

Code: Best-of-N

def best_of_n(model, prompt, n=8):
    candidates = []
    for _ in range(n):
        response = model.generate(prompt, temperature=0.7)
        score = reward_model(prompt, response)
        candidates.append((response, score))
    return max(candidates, key=lambda x: x[1])[0]

9. System Design Patterns

Pattern 1: High-Throughput Serving

graph TD
    LB["Load Balancer"] --> S1["SGLang + EAGLE-3<br/>+ RadixAttention"]
    LB --> S2["SGLang + EAGLE-3<br/>+ RadixAttention"]
    LB --> S3["SGLang + EAGLE-3<br/>+ RadixAttention"]
    S1 --> RC["Redis Cache<br/>(KV Cache)"]
    S2 --> RC
    S3 --> RC

    style LB fill:#e8eaf6,stroke:#3f51b5
    style S1 fill:#fff3e0,stroke:#ef6c00
    style S2 fill:#fff3e0,stroke:#ef6c00
    style S3 fill:#fff3e0,stroke:#ef6c00
    style RC fill:#e8f5e9,stroke:#4caf50

Pattern 2: RAG at Scale

Query → Embedding → Vector DB → Top-K → Reranker → LLM → Response
                ↓                        ↓
         HNSW index                 Cross-encoder
         (10M+ docs)                (BGE-reranker)

Pattern 3: Cost Optimization

graph LR
    SC["Semantic Cache<br/>(Redis)<br/>50-80% cache hit"] --> MR["Model Router"]
    MR -->|"Простые запросы"| SM["GPT-4o-mini /<br/>Llama-8B"]
    MR -->|"Сложные запросы"| QM["Quantized Models<br/>(AWQ/GPTQ 4-bit)<br/>75% cost reduction"]

    style SC fill:#e8f5e9,stroke:#4caf50
    style MR fill:#e8eaf6,stroke:#3f51b5
    style SM fill:#fff3e0,stroke:#ef6c00
    style QM fill:#f3e5f5,stroke:#9c27b0

10. Типичные заблуждения

Заблуждение: 4-bit квантизация дает 4x ускорение инференса

4-bit квантизация дает 4x сокращение памяти, но ускорение зависит от bottleneck. Для batch size=1 (memory-bound) ускорение 2-3x. Для больших батчей (compute-bound) ускорение может быть всего 1.2-1.5x, потому что dequantization добавляет overhead. AWQ и GPTQ дают разное ускорение на разном оборудовании: AWQ лучше на NVIDIA, GGUF -- на CPU/Apple.

Заблуждение: speculative decoding всегда дает 3-4x ускорение

Ускорение напрямую зависит от acceptance rate: при 33.8% -- лишь 1.82x (Qwen3-32B), при 65% -- 2.5x, при 80% -- 3x+. Acceptance rate падает на creative/diverse задачах (low temperature) и растет на predictable задачах (code completion, translation). Если draft model плохо совпадает с target, overhead верификации может замедлить инференс.

Заблуждение: MoE модели требуют в N раз больше памяти, чем dense

Mixtral 8x7B содержит 47B параметров, но активирует лишь 12.5B (2 из 8 экспертов). Однако все 47B параметров должны быть в памяти. MoE не экономит память при инференсе -- экономит compute. DeepSeek V3 (671B total, 37B active) требует несколько узлов для размещения модели в памяти, хотя compute per token сравним с 37B dense моделью.


11. Интервью-вопросы

Базовые

В: Что такое KV cache и зачем он нужен?

❌ "Это кэш для ускорения трансформера"

✅ "KV cache хранит вычисленные key и value тензоры для всех предыдущих токенов, чтобы при генерации нового токена не пересчитывать attention по всей истории. Без кэша -- O(T^2) на каждый новый токен, с кэшем -- O(T). Формула памяти: 2 * L * H_kv * d_head * T * 2 bytes. Для Llama 70B при 4K контексте это ~10 GB на запрос. PagedAttention (vLLM) снижает waste с 60-80% до <4% через блочное выделение"


В: Объясните speculative decoding

❌ "Маленькая модель генерирует, большая проверяет"

✅ "Draft модель генерирует N токенов-кандидатов за N forward passes (быстро, маленькая модель). Target модель верифицирует все N токенов за ОДИН forward pass (параллельно). Принимается самый длинный совпадающий префикс. Критично: результат lossless -- идентичен стандартной генерации. EAGLE-3 использует multi-layer features из самой target модели вместо отдельного draft -- 2-4x ускорение с acceptance rate до 80%"


В: Зачем нужна квантизация?

❌ "Чтобы модель работала быстрее"

✅ "Квантизация 4-bit (AWQ/GPTQ) сокращает память в 4x с потерей качества <3%. Llama 70B: 140 GB в BF16 -> 35 GB в AWQ-4. Это позволяет запустить 70B модель на одном GPU (H100 80 GB) вместо двух. AWQ (activation-aware) лучше сохраняет качество, чем GPTQ (static calibration). FP8 на H100/Blackwell -- компромисс: 2x сжатие с минимальной потерей, подходит даже для training"

Продвинутые

В: Сравните EAGLE-3 и классический draft-target подход

❌ "EAGLE-3 -- просто улучшенная версия"

✅ "Классический подход требует отдельной draft модели (пример: Llama-8B как draft для Llama-70B) -- это дополнительная память и сложность деплоя. EAGLE-3 извлекает multi-layer features из самой target модели, обучает легковесный predictor. Преимущества: (1) не нужна отдельная модель, (2) выше acceptance rate (features точнее представляют target), (3) меньше overhead. На Llama-3.1-8B: EAGLE-3 дает 2.36x vs 1.3-1.8x у standalone draft"


В: Когда выбрать SSM/Mamba вместо трансформера для инференса?

❌ "Когда нужна скорость"

✅ "SSM оптимален при: (1) длинных последовательностях > 16K -- фиксированная память state vs растущий KV cache, (2) streaming с фиксированным бюджетом памяти, (3) edge deployment с ограниченным GPU. Mamba-3 (2026) достиг SOTA качества. Но трансформер лучше для in-context learning и few-shot задач. Гибрид Jamba (1:7 ratio) -- production-выбор: Transformer-слои для in-context retrieval, Mamba для длинного контекста"


В: Объясните Ring Attention

❌ "Это distributed attention"

✅ "Ring Attention распределяет последовательность по N GPU: каждый GPU обрабатывает T/N токенов. GPU организованы в кольцо и передают KV блоки по кругу. Каждый GPU вычисляет partial attention со своим Q и полученными KV, затем агрегирует. Формула: n_max = n_local * N_devices. Пример: 128K local * 8 GPU = 1M tokens. Star Attention (2024) -- альтернатива: two-phase block-sparse, 11x быстрее для 128K на одном GPU"

System Design

В: Спроектируйте LLM serving для 10K concurrent users

❌ Линейное описание одного сервера

✅ "Архитектура: Load Balancer -> N инстансов SGLang с RadixAttention + EAGLE-3. Три уровня оптимизации: (1) Semantic cache (Redis) с 50-80% hit rate для повторяющихся запросов, (2) Model routing -- простые запросы на Llama-8B, сложные на 70B, (3) AWQ 4-bit квантизация для 4x сокращения GPU. Масштабирование: при 10K users и 100ms latency target нужно ~50-100 GPU (H100). EAGLE-3 дает 2-3x ускорение -> 2-3x меньше GPU"


11. Formulas Quick Reference

KV Cache Memory

\[\text{Memory} = 2 \times L \times H_{kv} \times d_{head} \times T \times 2 \text{ bytes (FP16)}\]

Note: Use \(H_{kv}\) (not \(H\)) for GQA models. Llama-70B: \(H=64\), \(H_{kv}=8\) (8x reduction vs MHA).

Speculative Decoding Acceptance

\[P(\text{accept}) = \min\left(1, \frac{p_{\text{target}}(t)}{p_{\text{draft}}(t)}\right)\]

Quantization (Asymmetric)

\[x_{\text{quant}} = \text{round}\left(\frac{x - x_{\min}}{x_{\max} - x_{\min}} \times (2^b - 1)\right)\]

MoE Load Balancing Loss

\[L_{\text{aux}} = \alpha \sum_{i=1}^{N} f_i \cdot P_i\]

Where \(f_i\) = fraction of tokens to expert \(i\), \(P_i\) = router probability.

Ring Attention Capacity

\[n_{\max} = n_{\text{local}} \times N_{\text{devices}}\]

12. Sources Synthesized

  1. inference-engines-comparison-2025-2026.md — vLLM, SGLang, TensorRT-LLM
  2. speculative-decoding-2025-2026.md — EAGLE-⅔, MTP, NGRAM
  3. kv-cache-optimization-2025-2026.md — PagedAttention, RadixAttention
  4. llm-quantization-2025-2026.md — GPTQ, AWQ, GGUF, FP8
  5. moe-load-balancing-2025-2026.md — Auxiliary loss, loss-free
  6. long-context-2025-2026.md — Ring Attention, Infini-Attention
  7. state-space-models-2025-2026.md — Mamba, RWKV, hybrids
  8. test-time-compute-scaling-2025-2026.md — Best-of-N, MCTS
  9. llm-compression-distillation-2026.md — P-KD-Q sequence, LoRA, pruning (ФАЗА 5)
  10. llmops-cost-optimization-2026.md — Semantic caching, model routing, batching (ФАЗА 5)
  11. llm-production-deployment-2026.md — vLLM deployment, scaling patterns (ФАЗА 5)