惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Attack and Defense Labs
Attack and Defense Labs
T
The Blog of Author Tim Ferriss
V
Visual Studio Blog
GbyAI
GbyAI
B
Blog RSS Feed
H
Help Net Security
美团技术团队
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
The Cloudflare Blog
Security Latest
Security Latest
F
Fortinet All Blogs
Microsoft Azure Blog
Microsoft Azure Blog
博客园 - Franky
P
Privacy & Cybersecurity Law Blog
J
Java Code Geeks
博客园 - 【当耐特】
Last Week in AI
Last Week in AI
Y
Y Combinator Blog
人人都是产品经理
人人都是产品经理
www.infosecurity-magazine.com
www.infosecurity-magazine.com
T
Threatpost
Schneier on Security
Schneier on Security
T
Tenable Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Latest news
Latest news
P
Proofpoint News Feed
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Know Your Adversary
Know Your Adversary
W
WeLiveSecurity
G
GRAHAM CLULEY
P
Palo Alto Networks Blog
The Hacker News
The Hacker News
Microsoft Security Blog
Microsoft Security Blog
罗磊的独立博客
Recent Commits to openclaw:main
Recent Commits to openclaw:main
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V2EX - 技术
V2EX - 技术
MongoDB | Blog
MongoDB | Blog
博客园_首页
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
Threat Research - Cisco Blogs
T
Tor Project blog
Google DeepMind News
Google DeepMind News
Blog — PlanetScale
Blog — PlanetScale
博客园 - 聂微东
Hacker News - Newest:
Hacker News - Newest: "LLM"
Google DeepMind News
Google DeepMind News
The GitHub Blog
The GitHub Blog
月光博客
月光博客

Towards AI

Building AI Agents in Rust — part 4 | Towards AI Building AI Agents in Rust — part 5 | Towards AI The Verified Identity Agent Bridge | Towards AI You Can’t Prompt Your Away Your LLM Problems | Towards AI The Free Agent Trap | Towards AI Your Agentic Loop Will Drift. Here Is the KL Divergence Equation That Measures How Far It Has Wandered From Its Original Instruction. | Towards AI Beyond Chat: Processing Images, PDFs, and Documents with the OpenAI Adapter in Oracle Integration Cloud | Towards AI Building AI Agents in Rust — part 3 | Towards AI Self-Hosting Airflow at Home: Automating Stock Price Data Collection | Towards AI The 76-Hour Frontier: How the Takedown of Claude Fable 5 Birthed the Military-Industrial-AI Complex | Towards AI I Trained a Markdown File to Boost GPT-5.5 by 23 Points — It Shouldn't Work | Towards AI We Replaced ChatGPT With a Local AI Server. Six Months of Honest Data. | Towards AI What Really Makes Cars Pollute? A Data Science Deep Dive into CO₂ Emissions | Towards AI Training GPT-2 From Scratch on a GTX1050 | Towards AI Principal Component Analysis (PCA): Theory, Mathematics, and Applications Build a Zero-Cost Web Automation Pipeline With OpenRouter, OpenClaw, and MediaUse I Gave Qwen3.7-Plus a Screenshot and It Found the Exact Pixel to Click for $0.40 Beyond the Prompt: Why Autonomous AI Agents Are Replacing the Chatbot Moonshot Cracked Claude Code’s Playbook with an MIT Terminal Agent and a $0.60 Model Connections, Roles, and Warehouses: Getting CoCo Desktop Production-Ready from Day One My First $5,000 Month Writing About AI Engineering on Medium Google Shrank Gemma 4 by 72% and Unsloth Fixed the 4-Bit Bug Nobody Else Caught on One 4090, and 4-Bit Shouldn’t Be This Good LangChain Explained: Understanding Models, Prompts, Chains, Memory, Indexes, and Agents TOON: Beyond JSON for LLMs Claude Code Casual, Pro, Elite: The Three Working Personas of Claude Code Mastery MiniMax M3 Decodes 1M Tokens 15x Faster — and It Shouldn’t Be This Cheap Using Amazon SQS for AI Agent Orchestration I Ran a 1.5B-Active Model on My Laptop That Embarrassed a 26B by 46 Points How to Build a Self-Improving Company with AI Part 3 — Implementation/Engine-Level: Choosing the Runtime That Gives You These for Free Part 2 — Serve-Level Speed: System Design That Stabilizes P95/P99 Claude Code: The AI Coding Partner Changing How Developers Build Software Claude Code Pitfalls: Claude Code Won’t Do What You Told It: A Troubleshooting Catalog Full-Stack Data Scientists for the Agentic Coding World Building Production-Grade AI Skills with Snowflake Cortex AI Function Studio I Tried 10 AI Agent Frameworks in 2026 — Here’s the Honest Guide I Wish I Had Earlier How One Spring Boot Optimization Saved Our Startup $30,000 a Year Inside Palantir AIP: How the World’s Most Controversial AI Platform Actually Works What Is a Reverse Proxy? (And Why Every Backend Developer Should Care) What Claude Opus 4.8 Actually Changes If You’re Building Agents QWEN 3.7 Max Worked For 35 Hrs Straight And The Results Were Mind-blowing When LLMs Meet Knowledge Graphs on the Battlefield Fine-Tuning is Dead: Why Context Orchestration Won in 2026 5 Things Broke When I Shipped a RAG + MCP Agent to Production. Google Co-Scientist: Hyper Scaling Research and Discovery Microsoft Just Embarrassed Browser Web Agents — 1,000 Lines Made GPT-5.4 Beat Opus 4.6 on 200 Web Tasks The Modern Data Stack Is Broken — Here’s How to Fix It With AI, Governance, and Real Architecture Building Production MCP Servers: What the Spec Won’t Tell You When Should an Agent Stop? The Anatomy of Termination Harness Engineering: The Layer That Matters More Than the Model AI Engineers Who Can’t Debug Are Getting Fired (Here’s How I Debug with Claude Code) Claude Code Memory: Why You Keep Explaining the Same Thing to Claude (and the Five Layers That Fix It) Claude Code Subagents: The Claude Code Feature You Skip Every Day (And Why It Quietly Wrecks Your Sessions) Agentic AI and the SMB Banking Advantage Claude Code: Spec-Driven Development — Why Your AI Coding Sessions Fall Apart at Hour Three The Real Cost of Agentic AI Nobody Budgets For SVM : 40 must visit Interview Questions (Part 2) Your AI Agent Works Perfectly in the Demo. Here Are the 6 Ways It Dies in Production. Unleashing the Power of ONNX for Speedier SBERT Inference Terraform vs CI/CD for Serverless Deployments Merve Noyan Stopped Writing Training Scripts — Her Agent Just Fine-Tuned 18 Models Solo for $11.40 Why Your Sales Forecast Is Always 20% Wrong (And How To Make It 12% Wrong) Genetic Cubic n{C/A} Ratios For Elementary Robotics Design Top 20 AdaBoost Interview Questions & Answers (Part 2 of 2) Agentic AI Vs AI Agents — What Are the Key Differences? LAI #127: The Infrastructure Layer of AI Is Becoming the Product Anthropic Caught Its Own AI Planning to Blackmail Engineers RNNs Cannot Think What Transformers Think Cheaply. ICLR 2026 Proved the Gap Is Exponential. Time Series Made So Easy My Aunt Got It on the Second Read Claude Cowork 101 | Towards AI Is 3-Bit KV Cache the Holy Grail? A Reality Check on Google’s TurboQuant LangGraph Multi-Agent Architecture: Building a Self-Critiquing AI Debate System AutoML on Autopilot | Towards AI I Ran This Open-Source AI Tool on a Messy Codebase and Got 71x Fewer Tokens — Here Is Exactly What Happened Month in 4 Papers (April 2026) AI Kept Forgetting My Notes. Fixing That Taught Me How It Actually Works. How ChatGPT Makes You Addicted Crack ML Interviews with Confidence: K-Nearest Neighbors (KNN 20 Q&A) The Event-Driven Blueprint: How I Scaled a Spring Boot System to 10 Million Kafka Messages/Day Building Vector Search? Why FAISS Alone Isn’t Enough TAI #202: GPT-5.5 Moves Codex Into Real Work Machine Learning System Design -The Model Serving Triangle, With One Forward Pass Flowing Through Every Trade-off (Part3) AI Orchestration in Action: How MuleSoft and LLMs Fuel the Future of Enterprise AI GPT-4 Has 1.8 Trillion Parameters. It Uses 2% of Them Per Token. Part 20: Data Manipulation in Multi-Dimensional Aggregation A Fundamental Introduction to Genetic Algorithm -Part Two TAI #200: Anthropic’s Mythos Capability Step Change and Gated Release From Notebook to Production: Running ML in the Real World (Part 4) Sqribble’s Template‑Driven Document Automation Anthropic Just Shipped the Layer That’s Already Going to Zero Long-Term vs Short-Term Memory for AI Agents: A Practical Guide Without the Hype The L1 Loss Gradient, Explained From Scratch Your Postcode Is Deciding Your Care. I Built a Pipeline to Prove It. I Directed AI Agents to Build a Tool That Stress-Tests Incentive Designs. Here’s What It Found. Your System Prompt Is the Product — Not the Feature The LLM Wiki Trend Has a Retention Problem Nobody Mentions Top 20 Data Preparation Interview Questions and Answers (Part 2 of 2) LAI #122: Word Embeddings Started in 1948, Not With Word2Vec Top 15 Computer Vision Datasets [2026] 40 Generative AI Interview Questions That Actually Get Asked in 2026 (With Answers)
3-Part Series: LLM Latency in Production (Part 1)
Editorial Team · 2026-06-03 · via Towards AI

Author(s): Mehedi Hasan

Originally published on Towards AI.

Originally published at https://mhabir.substack.com.

Part 1 — Model-Level Speed: Make the Model Fast on the GPU

If you’re shipping LLMs to production, your first performance bottleneck isn’t serving logic or network overhead-it’s the raw arithmetic happening inside the GPU. Most teams waste weeks tuning their batching logic before realizing their model baseline is 3–4x slower than it should be. This part is about fixing that baseline.

Why LLM Inference Is Memory-Bandwidth Bound (Especially in Decode)

The fundamental misconception: LLMs are not always compute-bound. Decode is typically memory-bandwidth bound, while prefill is mixed (compute + memory) and becomes kernel-sensitive, especially with long contexts. Here’s the intuition that proves it.

A 7B parameter model in FP16 needs 14 GB just for weights. For a single token generation step (decode), you’re moving those 14 GB through GPU memory bandwidth (TB/s-class HBM) to do ~ 14 GFLOPs of computation. That’s an arithmetic intensity around 1 FLOP/byte-well below the roofline where compute becomes the limit. On modern GPUs, you’d need >200 FLOP/byte to saturate tensor cores. In practice, during decode, you’re waiting on HBM reads, not matrix multiplications.

This has two consequences:

  • Batching helps because amortizing weight loads across multiple sequences improves effective memory bandwidth utilization.
  • Quantization is a bandwidth win: INT4 weights are 4x smaller, so you move 4x less data per token. That directly translates to lower latency.

Caveat: This is an upper-bound mental model. Effective traffic depends on batching, caching, and parallelization-real workloads see less than this theoretical maximum.

Every LLM request has two phases with completely different performance characteristics.

3-Part Series: LLM Latency in Production (Part 1)

The Prefill-Decode Asymmetry

Prefill processes the entire prompt in one forward pass, but it’s compute-intensive and memory-heavy because you’re building the KV cache. For a 4K-token prompt, you’re doing attention over a 4K sequence in parallel-not 4K autoregressive steps-creating an O(n²) attention matrix and storing 4K × hidden_dim × num_layers × 2 (K and V) values. This can be multiple GB per request on large models.

Decode generates tokens autoregressively. Each step processes one token, but reuses the KV cache. It’s memory-bandwidth dominated because you’re streaming the entire KV cache through HBM on every step.

This asymmetry means your optimization strategy must be phase-aware. Faster prefill requires better attention kernels (Flash Attention). Faster decode requires better cache management (paged KV, quantization).

Quantization is the single most effective model-level optimization. It reduces memory footprint, improves bandwidth efficiency, and often comes with minimal quality loss.

INT8 (LLM.int8()) uses vector-wise quantization with outlier preservation. It’s the safest starting point-most models show <0.1% perplexity degradation. Implementation is straightforward:

# bitsandbytes INT8 inference
pip install bitsandbytes

In your model loading code:

from transformers import BitsAndBytesConfig 
quantization_config = BitsAndBytesConfig(
load_in_8bit=True,
llm_int8_threshold=6.0, # outlier threshold
llm_int8_has_fp16_weight=False
)

This works out-of-the-box in vLLM and TGI:

# TGI with bitsandbytes INT8
text-generation-launcher --model-id mistralai/Mistral-7B-Instruct-v0.2 --quantize bitsandbytes

# vLLM with INT8 (via config)
python -m vllm.entrypoints.api_server --model mistralai/Mistral-7B-Instruct-v0.2 --quantization bitsandbytes

INT4 is where the real speedup lives. You achieve 4x memory reduction and 2–3x latency improvement, but measurable quality degradation occurs. Always validate with your actual prompt distribution.

AWQ: Activation-Aware Weight Quantization

AWQ’s key insight: not all weights are equally important. Activation magnitudes reveal which weights matter most. By scaling weights based on activation statistics, AWQ achieves better 4-bit accuracy than naive quantization.

Installation & Usage:

git clone https://github.com/mit-han-lab/llm-awq
cd llm-awq
pip install -e .
cd awq/kernels && python setup.py install # Build efficient CUDA kernels

Quantize a model:

# Step 1: AWQ search (calibration)
python -m awq.entry --model_path meta-llama/Llama-2-7b-hf \
--w_bit 4 --q_group_size 128 \
--run_awq --dump_awq llama-2-7b-w4-g128.pt

# Step 2: Generate quantized weights
python -m awq.entry --model_path meta-llama/Llama-2-7b-hf \
--w_bit 4 --q_group_size 128 \
--load_awq llama-2-7b-w4-g128.pt \
--q_backend real --dump_quant llama-2-7b-w4-g128-awq.pt

In vLLM/TGI, use pre-quantized models:

# vLLM with AWQ (supported in many recent versions)
python -m vllm.entrypoints.api_server --model TheBloke/Llama-2-7B-AWQ --quantization awq

# TGI with AWQ
text-generation-launcher --model-id TheBloke/Llama-2-7B-AWQ

AWQ Configuration Details:

  • q_group_size=128: Weights are quantized in groups of 128 channels. Smaller groups improve accuracy but increase quantization overhead.
  • w_bit=4: 4-bit quantization. AWQ also supports 3-bit for extreme compression.
  • version="GEMM": Choose between GEMM (general matrix multiply) or GEMV (vector) kernels. GEMM is faster for batch sizes > 1.

GPTQ: Gradient-Based Post-Training Quantization

GPTQ uses second-order information (Hessian) to minimize quantization error. It’s slightly more computationally expensive to quantize but produces excellent 4-bit models.

Installation:

pip install auto-gptq --no-build-isolation

Quantization:

from transformers import AutoTokenizer
from auto_gptq import AutoGPTQForCausalLM, BaseQuantizeConfig

model = AutoGPTQForCausalLM.from_pretrained(
"meta-llama/Llama-2-7b-hf",
quantize_config=BaseQuantizeConfig(
bits=4,
group_size=128,
desc_act=False, # False for speed, True for slight quality improvement
)
)

# Calibrate with ~128-256 samples from your domain
examples = [...] # List of tokenized samples
model.quantize(examples)
model.save_quantized("llama-2-7b-gptq")

GPTQ in Serving:

# vLLM with GPTQ
python -m vllm.entrypoints.api_server --model TheBloke/Llama-2-7B-GPTQ --quantization gptq

Key GPTQ Configs:

  • desc_act=False: Disables activation reordering. This is 2-3x faster in inference with minimal quality loss. Set to True only if perplexity degradation is > 2%.
  • use_marlin=True: On Ampere GPUs (A100, RTX 30xx/40xx), Marlin kernels are 30-50% faster than default exllamav2.

bitsandbytes NF4/FP4: The No-Precompute Option

bitsandbytes 4-bit (used in QLoRA) quantizes on-the-fly during model loading. No calibration needed, but inference is often slower than AWQ/GPTQ because quantization happens per forward pass.

Use when: Config:

from transformers import BitsAndBytesConfig bnb_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", # or "fp4" bnb_4bit_compute_dtype=torch.float16, bnb_4bit_use_double_quant=True # Compresses quantization constants )

Performance note: NF4 inference is often slower than AWQ/GPTQ for pure inference because of runtime dequantization overhead. Use it for development, not max-throughput serving.

GPU Acceleration: Kernels That Actually Matter

Quantization reduces memory traffic. These kernels make the traffic you do have more efficient.

Flash Attention: The Prefill King

Flash Attention eliminates the need to materialize the full N×N attention matrix. Instead, it tiles the computation and uses smart memory management to reduce HBM reads/writes by 10–20x in theory, with typical speedups of 30–50% in practice on long sequences.

Installation:

pip install flash-attn --no-build-isolation

In Practice: FlashAttention-2 is integrated into all major inference engines. You just need to install it before building your engine. For custom PyTorch code, use the flash_attn interface.

Performance Impact: On long prompts (>2K tokens), Flash Attention can significantly reduce prefill time, often by 30–50% depending on hardware and sequence length. The improvement is most dramatic on memory-bound configs.

Fused Kernels: The Decode Accelerator

In autoregressive generation, every token passes through attention, layernorm, and MLP blocks. Each operation launches a separate kernel, incurring overhead. Fused kernels merge these into a single launch.

Examples:

In vLLM/TGI: These are automatically used when available. For custom implementations, look at Triton’s fused operations.

Performance Impact: Fused kernels improve decode tokens/sec by 15–25% by reducing kernel launch overhead and memory roundtrips.

Paged KV Cache: The Memory Fragmentation Fix

vLLM’s breakthrough innovation treats the KV cache like virtual memory. Instead of pre-allocating fixed-size cache blocks per request, paged attention allocates blocks dynamically (typically 16–64 tokens per block). This eliminates fragmentation and allows 2–3x higher batch sizes.

How it works:

  1. Allocate KV cache in fixed-size blocks (e.g., 16 tokens × hidden_dim)
  2. Maintain a block table per request (like page tables)
  3. On each decode step, gather scattered blocks into a contiguous attention computation

In vLLM: This is automatic and transparent. Configure block size:

python -m vllm.entrypoints.api_server \ --model meta-llama/Llama-2-7b-hf \ --block-size 16 # 16 tokens per block

Performance Impact: On shared inference services, paged attention can dramatically improve GPU utilization by eliminating memory fragmentation, often from ~45% to 85%. This directly improves throughput and reduces P99 latency.

KV Cache Quantization: The Memory Saver

The KV cache dominates memory usage in long-context scenarios. KV cache quantization (often to FP8 or INT8) cuts this memory in half, enabling longer sequences or larger batches.

Implementation: NVIDIA’s FP8 format is emerging as the sweet spot. In vLLM (experimental):

python -m vllm.entrypoints.api_server \ --model your-model \ --kv-cache-dtype fp8_e4m3

Tradeoffs: KV cache quantization adds a dequantization step to each attention computation, costing ~5–10% throughput. But it doubles your effective batch size capacity, which often yields net positive system throughput.

Decision Ladder: What to Try First

Based on production deployments, this is the empirical order that yields fastest time-to-value:

Level 1: Baseline (Zero Effort)

  • Use BF16/FP16: Ensure you’re not in FP32 mode
  • Install Flash Attention: pip install flash-attn --no-build-isolation
  • Verify GPU behavior: Watch memory bandwidth % and SM active cycles; low utilization is common at batch=1

Impact: 30–50% prefill speedup, minimal effort.

Level 2: Safe Quantization (1–2 Hours)

  • Apply INT8 quantization via bitsandbyte

bash

text-generation-launcher --model-id your-model --quantize bitsandbytes
  • Validate quality: Run 100 representative prompts, check output fidelity
  • Measure memory: Should see ~40% reduction in GPU memory usage

Impact: 1.5–2x batch size capacity, minimal quality loss.

Level 3: Aggressive Quantization (Half Day)

  • Choose AWQ or GPTQ based on availability:
  • Use AWQ if pre-quantized models exist for your model
  • Use GPTQ if you need to quantize custom models
  • Quantize with conservative settings:
  • AWQ: w_bit=4, q_group_size=128
  • GPTQ: bits=4, group_size=128, desc_act=False
  • Run quality evaluation: Check perplexity on your validation set, target <2% degradation
  • Deploy in vLLM/TGI: Use --quantization awq or --quantization gptq

Impact: 3–4x memory reduction, 2–3x throughput improvement.

Level 4: Kernel Optimization (Full Day)

  • Switch to vLLM: If not already using it
  • Tune block size: Start with --block-size 16, measure fragmentation
  • Enable KV cache quantization (if supported)
  • Profile with PyTorch Profiler: Identify remaining bottlenecks

Impact: 2–3x higher concurrency, 30–50% P99 latency reduction.

Level 5: Advanced (When All Else Fails)

  • Speculative decoding: For very long outputs
  • Custom fused kernels: For specialized architectures
  • Tensor parallelism: When a single GPU is insufficient

Impact: Variable, but can unlock 70B+ models on commodity hardware.

The Bottom Line for Tech Leads

Before you redesign your serving architecture, make sure you’re getting every ounce of performance from the model itself. In 90% of production deployments, the optimization ladder above yields 2–3x throughput improvements at zero serving-level changes.

Your order of operations:

  1. Measure prefill vs decode latency — know which phase hurts you
  2. Apply INT8 quantization — low risk, immediate memory win
  3. Switch to vLLM with Flash Attention — best-in-class kernel performance
  4. Evaluate AWQ/GPTQ INT4 — when you need another 2x
  5. Enable KV cache quantization — when context length is your limit

Most teams stop at Level 3 and see production latency drop from 800ms TTFT to 250ms, and tokens/sec increase from 30 to 80. That’s the difference between a usable product and a frustrating demo.

In Part 2, we’ll cover how to take this optimized model and build a serving system that doesn’t squander these gains through poor queueing, batching, and resource management.

📚 References & Further Reading

🔥 Core Papers

LLM Serving & Memory Management

  • Efficient Memory Management for LLM Serving with PagedAttention (vLLM)
    https://arxiv.org/abs/2309.06180
    Introduces paged attention, KV cache virtualization, and high-throughput batching used by vLLM.

Attention Optimization

  • FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness
    https://arxiv.org/abs/2205.14135
    Foundational paper explaining why attention is memory-bound and how IO-aware tiling reduces HBM traffic.
  • FlashAttention-2: Faster Attention with Better Parallelism
    https://arxiv.org/abs/2307.08691
    Improves kernel parallelism and throughput, especially for long-context prefill.

Quantization for LLM Inference

  • AWQ: Activation-Aware Weight Quantization for LLM Compression and Acceleration
    https://arxiv.org/abs/2306.00978
    Shows why activation statistics matter for INT4 quantization accuracy and latency.
  • SmoothQuant: Accurate and Efficient Post-Training Quantization for LLMs
    https://arxiv.org/abs/2211.10438
    Explains activation smoothing to make INT8 quantization more robust.
  • GPTQ: Accurate Post-Training Quantization for Generative Models
    https://arxiv.org/abs/2210.17323
    Gradient-based quantization minimizing second-order error; widely used in production.

🧠 Official GitHub Repositories (Production Code)

Inference Engines

Attention & Kernels

Quantization Libraries

Performance Modeling & Systems Thinking

Published via Towards AI