LLM 推理原理详解:从 Prefill 到 Decode Avi Chawla 2026-06-29 23.7 KB 320.3K 776 ☆ 收藏 𝕏 文章列表 本文深入解析了大语言模型(LLM)推理的计算流程。文章指出,LLM 推理主要包含 Prefill(处理提示词,计算密集型)和 Decode(逐词生成,显存带宽密集型)两个阶段。作者详细阐述了分词、Embedding、Transformer 层及 KV Cache 的工作原理,并分析了 KV Cache 带来的内存挑战及 vLLM 的优化方案。最后,探讨了 DeepSeek-V4 等新架构通过重新设计注意力机制来从根本上压缩 KV Cache 的创新思路。 LLM推理KV CachePrefillDecodeDeepSeekTransformer性能优化 # How LLM Inference Works, Clearly Explained. **作者**: Avi Chawla **日期**: 2026-06-27T11:14:22.000Z **来源**: [https://x.com/_avichawla/status/2071201619530956863](https://x.com/_avichawla/status/2071201619530956863) ---  Every generate() call to an LLM runs two distinct computational phases on the same GPU: - prefill (processing the prompt) is compute-bound - while decode (generating tokens one at a time) is memory-bound. Most inference optimizations target one phase or the other, and diagnosing which phase is the bottleneck is the first step in making a deployment faster. In this article, I'll walk through the full pipeline, from tokenized input to streamed output, and look at where the time goes in each phase. # Tokenization and embedding Tokenizers like Byte Pair Encoding (BPE) convert raw text into integer IDs from a vocabulary of roughly 50,000 tokens. ``` prompt = "How does inference work?" ids = tokenizer.encode(prompt) # ids -> [2437, 1374, 32278, 670, 30] ``` Each ID maps to a row in the embedding table, a learned matrix of shape [vocab_size, hidden_dim]. For a model with a hidden dimension of 4,096, each token becomes a 4,096-dimensional vector. ``` # embedding_table has shape [vocab_size, hidden_dim] vectors = embedding_table[ids] # shape: [num_tokens, 4096] ```  Position information gets injected at this stage. Most modern architectures use Rotary Position Embeddings (RoPE), which encode position by rotating the embedding vectors rather than adding a separate positional vector. # Transformer layers The embedded sequence passes through a stack of transformer layers (typically 32 to 80+, depending on model size). Each layer applies two operations in sequence: 1) Self-attention computes three projections per token (query Q, key K, value V) via learned weight matrices.  Each token's query is scored against every other token's key, and those scores (after scaling and softmax) determine how much of each token's value gets mixed in. ``` # scores: how much each token attends to every other token Q, K, V = x @ Wq, x @ Wk, x @ Wv scores = (Q @ K.T) / sqrt (d_k) weights = softmax(scaled) # one row per token, sums to 1 attn_output = weights @ V ``` 2) Feed-forward network (FFN) processes each token's vector independently through a two-layer MLP. Attention moves information between positions. The FFN transforms it. After the final layer, the model projects the last token's hidden state back to vocabulary size ([hidden_dim, vocab_size]), applies softmax, and samples from the resulting distribution to produce the first output token. # Prefill: the compute-bound phase Processing the input prompt is the first phase. All tokens are processed in parallel: Q, K, and V are computed for every token simultaneously, and attention runs as a large matrix-matrix multiplication. This is compute-bound work. The GPU's arithmetic throughput is the bottleneck, and utilization is high. The metric that captures this phase is Time to First Token (TTFT), the latency before the first output token appears. During prefill, the model also populates the KV cache: the K and V tensors for every layer get stored in GPU memory for reuse. ``` # Prefill: process the whole prompt in one shot hidden = embed(prompt_tokens) + positions for layer in model.layers: Q, K, V = project(hidden) # for ALL tokens at once hidden = attention(Q, K, V) + hidden hidden = feedforward(hidden) + hidden cache_kv(layer, K, V) # save for later first_token = sample(project_to_vocab(hidden[-1])) ``` # Decode: the memory-bound phase Once the first token is generated, the model switches to generating one token at a time. For each new token, it only computes Q, K, and V for that single token. The K and V from all previous tokens are already in the cache. ``` # Decode: one token per iteration token = first_token steps = 0 while token != STOP and steps < MAX_STEPS: x = embed(token) + position(steps) for layer in model.layers: q, k, v = project(x) K_all, V_all = caches[layer].append(k, v) # cached history + new x = layer.forward(q, K_all, V_all, x) # attention + FFN, residuals token = sample(project_to_vocab(x)) steps += 1 yield token ``` The arithmetic per step is tiny (one query vector against the cached key matrix instead of a full matrix-matrix multiply). But the GPU still loads every weight matrix and the entire cached K/V from memory for that small computation. The bottleneck flips from compute to memory bandwidth.  The metric for this phase is Inter-Token Latency (ITL): the time between consecutive output tokens. Low ITL is what makes a model feel responsive. # The KV cache Without caching, generating a 1,000-token response would require recomputing attention over the entire growing sequence at every step, giving quadratic complexity. The KV cache stores each layer's K and V tensors once and appends new entries incrementally. The video below depicts LLM inference speed with vs. without KV caching:  The speedup is roughly 5x or more for long generations. The cost is that the cache grows linearly with sequence length and exists per-layer. For a 13B-parameter model, the cache consumes roughly 1 MB per token. A 4K-token context burns through 4 GB of VRAM on the cache alone. This is why long contexts get expensive. The cache competes directly with batch size for GPU memory, i.e., more cache per request means fewer concurrent requests per GPU. Standard mitigations include quantizing the cache to INT8 or INT4, sliding window attention (dropping tokens outside a fixed window), grouped-query attention (GQA, sharing K/V across attention heads to reduce the number of cached tensors), and PagedAttention (the memory management trick behind vLLM that pages the cache like an OS pages virtual memory, eliminating fragmentation). There's another interesting idea that I talked about around KV cache management below: > **Avi Chawla@_avichawla**: [原文链接](https://x.com/_avichawla/status/2070828078247604480) > > A tricky LLM interview question: > You're serving a reasoning model on vLLM, and it keeps running out of GPU memory on long traces. > So you add KV cache compression and evict 90% of the cached tokens. > VRAM usage stays as is and GPU still runs out of memory. > Why? > (answer below) > >  # Redesigning attention around the cache Quantization and paging treat the KV cache as a fixed cost to manage. DeepSeek's V4 series (released April 2025) takes a different approach: redesign attention so the cache is structurally smaller from the start.  V4 uses a hybrid of two compressed attention mechanisms. Compressed Sparse Attention (CSA) compresses KV entries by 4x using softmax-gated pooling, then applies sparse attention over the compressed tokens. Heavily Compressed Attention (HCA) is more aggressive. It consolidates KV entries across 128 tokens into a single compressed entry and applies dense attention over those representations. At a 1M-token context, V4-Pro requires 27% of the single-token inference FLOPs and 10% of the KV cache compared to DeepSeek-V3.2. In absolute terms, that's 9.62 GiB of KV cache per sequence at 1M context in bf16, compared to an estimated 83.9 GiB for a V3.2-style architecture. With fp4/fp8 quantization on top, the cache shrinks by another 2x. The KV cache has become the constraint that the field is optimizing the model architecture around. # Quantization Training uses FP32 or BF16 for gradient stability. Inference doesn't need that precision. The memory savings from reducing bit width are linear: - 7B parameters at FP32: 28 GB - 7B parameters at FP16/BF16: 14 GB - 7B parameters at INT8: 7 GB - 7B parameters at INT4: 3.5 GB  INT4 is why 7B models run on laptop GPUs with 4-6 GB of VRAM. Methods like GPTQ and AWQ use per-channel scaling factors to minimize quality degradation from the lossy compression. Done well, INT4 lands within 1-2 percentage points of the full-precision model on standard benchmarks. Going from FP16 to INT8 often cuts inference latency in half with negligible quality loss, making quantization the single highest-leverage optimization for most deployments. # Serving infrastructure Modern inference servers wrap the prefill-decode loop with several optimizations:  - Continuous batching interleaves tokens from multiple requests on the same GPU step, keeping utilization high even during memory-bound decode phases. - Speculative decoding uses a small draft model to propose multiple tokens, then the large model verifies them in a single forward pass. When the draft model's acceptance rate is high, this effectively converts multiple sequential decode steps into one parallel verification.  I covered Speculative decoding in detail here: > **Avi Chawla@_avichawla**: [原文链接](https://x.com/_avichawla/status/2054860740541207032) > - PagedAttention (vLLM) manages KV cache memory in fixed-size blocks, eliminating fragmentation and enabling more concurrent requests per GPU. Frameworks like vLLM, TensorRT-LLM, and Text Generation Inference (TGI) combine these techniques. A single GPU can serve dozens of concurrent users because decode leaves most of the arithmetic capacity idle, and continuous batching fills that idle capacity with other requests. # The full inference path  1. Tokenize: Text becomes integer IDs via BPE. 2. Embed: IDs become vectors. RoPE encodes position. 3. Prefill: All input tokens are processed in parallel through every layer. Compute-bound. KV cache populated. First token emitted. 4. Decode loop: One token per step: project Q for the new token, attend over cached K/V, run FFN, sample. Append new K/V to cache. Memory-bound. 5. Detokenize: Token IDs mapped back to text and streamed. # Some practical implications - long prompts are expensive in TTFT (prefill) - long outputs are expensive in ITL (decode) - and they stress different hardware resources. - Context length isn't free because it bloats the KV cache and directly reduces batch capacity. - GPU utilization during decode can drop to 30% even on a fully loaded server, because the bottleneck is memory bandwidth, not arithmetic. - The fix isn't more compute, it's faster memory, a smaller cache, or better batching. When someone tells you their model is slow, the first diagnostic is whether it's slow to start (prefill-bound, optimize TTFT) or slow to stream (decode-bound, optimize ITL). 👉 Over to you: are you running into TTFT or ITL bottlenecks in your deployments, and what's worked for you? That's a wrap! If you enjoyed this tutorial: Find me → @_avichawla Every day, I share tutorials and insights on DS, ML, LLMs, and RAGs. ## 相关链接 - [Avi Chawla](https://x.com/_avichawla) - [@_avichawla](https://x.com/_avichawla) - [28K](https://x.com/_avichawla/status/2071201619530956863/analytics) - [Jun 27](https://x.com/_avichawla/status/2070828078247604480) - [242K](https://x.com/_avichawla/status/2070828078247604480/analytics) - [May 14](https://x.com/_avichawla/status/2054860740541207032) - [39K](https://x.com/_avichawla/status/2054860740541207032/analytics) - [@_avichawla](https://x.com/@_avichawla) - [Upgrade to Premium](https://x.com/i/premium_sign_up) - [7:58 PM · Jun 28, 2026](https://x.com/_avichawla/status/2071201619530956863) - [28.6K Views](https://x.com/_avichawla/status/2071201619530956863/analytics) --- *导出时间: 2026/6/29 12:02:40* --- ## 中文翻译 # 大语言模型推理的工作原理,清晰讲解。 **作者**: Avi Chawla **日期**: 2026-06-27T11:14:22.000Z **来源**: [https://x.com/_avichawla/status/2071201619530956863](https://x.com/_avichawla/status/2071201619530956863) ---  对大语言模型的每次 generate() 调用,都会在同一块 GPU 上运行两个截然不同的计算阶段: - 预填充(prefill,处理提示词)是计算受限的 - 而解码(decode,逐个生成 token)是内存受限的。 大多数推理优化都针对其中一个阶段,因此诊断哪个阶段是瓶颈,是加快部署速度的第一步。 在本文中,我将梳理从 token 化输入到流式输出的完整流程,并分析每个阶段的时间都花在了哪里。 # 分词与嵌入 像字节对编码(BPE)这样的分词器,会将原始文本转换为来自约 50,000 个词表的整数 ID。 ``` prompt = "How does inference work?" ids = tokenizer.encode(prompt) # ids -> [2437, 1374, 32278, 670, 30] ``` 每个 ID 映射到嵌入表(embedding table)中的一行,嵌入表是一个形状为 [vocab_size, hidden_dim] 的可学习矩阵。对于一个隐藏维度为 4,096 的模型,每个 token 会变成一个 4,096 维的向量。 ``` # embedding_table has shape [vocab_size, hidden_dim] vectors = embedding_table[ids] # shape: [num_tokens, 4096] ```  位置信息在这一阶段被注入。 大多数现代架构使用旋转位置编码(RoPE),它通过旋转嵌入向量而非添加单独的位置向量来编码位置信息。 # Transformer 层 嵌入后的序列经过一叠 Transformer 层(通常为 32 到 80+ 层,取决于模型大小)。 每层依次执行两个操作: 1) 自注意力机制通过学习到的权重矩阵,为每个 token 计算三个投影(查询 Q、键 K、值 V)。  每个 token 的查询与所有其他 token 的键进行打分,这些分数(经过缩放和 softmax 后)决定了每个 token 的值有多少会被混合进来。 ``` # scores: how much each token attends to every other token Q, K, V = x @ Wq, x @ Wk, x @ Wv scores = (Q @ K.T) / sqrt (d_k) weights = softmax(scaled) # one row per token, sums to 1 attn_output = weights @ V ``` 2) 前馈网络(FFN)通过一个两层 MLP 独立处理每个 token 的向量。注意力机制在位置之间传递信息,而 FFN 对其进行变换。 在最后一层之后,模型将最后一个 token 的隐藏状态投影回词表大小([hidden_dim, vocab_size]),应用 softmax,并从所得分布中采样以生成第一个输出 token。 # 预填充:计算受限阶段 处理输入提示词是第一个阶段。所有 token 被并行处理:为每个 token 同时计算 Q、K 和 V,注意力以大型矩阵-矩阵乘法的方式运行。 这是计算受限的工作。GPU 的算术吞吐量是瓶颈,利用率很高。衡量这一阶段的指标是首 token 时间(TTFT),即第一个输出 token 出现之前的延迟。 在预填充期间,模型还会填充 KV 缓存:每一层的 K 和 V 张量被存储在 GPU 内存中以供复用。 ``` # Prefill: process the whole prompt in one shot hidden = embed(prompt_tokens) + positions for layer in model.layers: Q, K, V = project(hidden) # for ALL tokens at once hidden = attention(Q, K, V) + hidden hidden = feedforward(hidden) + hidden cache_kv(layer, K, V) # save for later first_token = sample(project_to_vocab(hidden[-1])) ``` # 解码:内存受限阶段 一旦第一个 token 生成完毕,模型就切换为每次生成一个 token。对于每个新 token,它只计算该 token 的 Q、K 和 V。之前所有 token 的 K 和 V 已经在缓存中了。 ``` # Decode: one token per iteration token = first_token steps = 0 while token != STOP and steps < MAX_STEPS: x = embed(token) + position(steps) for layer in model.layers: q, k, v = project(x) K_all, V_all = caches[layer].append(k, v) # cached history + new x = layer.forward(q, K_all, V_all, x) # attention + FFN, residuals token = sample(project_to_vocab(x)) steps += 1 yield token ``` 每一步的算术运算量很小(一个查询向量对缓存键矩阵的操作,而非完整的矩阵-矩阵乘法)。但为了这一小部分计算,GPU 仍然要从内存中加载每一个权重矩阵以及整个缓存的 K/V。瓶颈从计算转向了内存带宽。  这一阶段的指标是 token 间延迟(ITL):连续输出 token 之间的时间间隔。低 ITL 才能让模型感觉响应迅速。 # KV 缓存 如果没有缓存,生成一个 1,000 token 的回复将需要每一步都对整个不断增长的序列重新计算注意力,导致平方级的复杂度。 KV 缓存将每一层的 K 和 V 张量只存储一次,并增量式地追加新条目。 下面的视频展示了有无 KV 缓存时大语言模型推理速度的对比:  对于长文本生成,加速可达约 5 倍或更多。 代价是缓存随序列长度线性增长,且每一层都有独立缓存。对于一个 130 亿参数的模型,缓存每个 token 约消耗 1 MB 内存。4K token 的上下文仅在缓存上就要占用 4 GB 显存。 这就是为什么长上下文的成本如此高昂。缓存直接与批处理大小争夺 GPU 内存,也就是说,每个请求占用的缓存越多,每块 GPU 能处理的并发请求就越少。 标准的缓解措施包括:将缓存量化为 INT8 或 INT4、滑动窗口注意力(丢弃固定窗口之外的 token)、分组查询注意力(GQA,在注意力头之间共享 K/V 以减少缓存张量的数量),以及 PagedAttention(vLLM 背后的内存管理技巧,它像操作系统对虚拟内存分页那样对缓存进行分页,从而消除内存碎片)。 关于 KV 缓存管理,我还谈到了另一个有趣的想法,如下所示: > **Avi Chawla@_avichawla**: [原文链接](https://x.com/_avichawla/status/2070828078247604480) > > 一个刁钻的 LLM 面试题: > 你在 vLLM 上部署了一个推理模型,但在长轨迹上它总是耗尽 GPU 内存。 > 于是你添加了 KV 缓存压缩,并逐出了 90% 的缓存 token。 > VRAM 使用量保持不变,GPU 仍然内存不足。 > 为什么? > (答案见下) > >  # 围绕缓存重新设计注意力机制 量化和分页都是把 KV 缓存当作需要管理的固定成本。DeepSeek 的 V4 系列(2025 年 4 月发布)采取了不同的方法:重新设计注意力机制,让缓存从一开始就在结构上更小。  V4 使用了两种压缩注意力机制的混合。 压缩稀疏注意力(CSA)使用 softmax 门控池化将 KV 条目压缩 4 倍,然后在压缩后的 token 上应用稀疏注意力。 重度压缩注意力(HCA)则更加激进。它将 128 个 token 的 KV 条目合并为单个压缩条目,并对这些表示应用密集注意力。 在 100 万 token 上下文下,与 DeepSeek-V3.2 相比,V4-Pro 仅需单 token 推理 FLOPs 的 27% 和 KV 缓存的 10%。 从绝对数值来看,在 100 万上下文、bf16 精度下,每个序列的 KV 缓存为 9.62 GiB,而 V3.2 风格架构估计需要 83.9 GiB。再加上 fp4/fp8 量化,缓存还可以再缩小 2 倍。 KV 缓存已成为该领域围绕其优化模型架构的核心约束。 # 量化 训练使用 FP32 或 BF16 以保证梯度稳定。推理则不需要这种精度。降低位宽带来的内存节省是线性的: - 7B 参数 @ FP32:28 GB - 7B 参数 @ FP16/BF16:14 GB - 7B 参数 @ INT8:7 GB - 7B 参数 @ INT4:3.5 GB  INT4 正是 7B 模型能在 4-6 GB VRAM 的笔记本 GPU 上运行的原因。GPTQ 和 AWQ 等方法使用逐通道缩放因子来最大限度减少有损压缩造成的质量下降。 做得好的话,INT4 在标准基准测试上的表现与全精度模型相差仅 1-2 个百分点。 从 FP16 到 INT8 通常能将推理延迟减半,而质量损失微乎其微,这使量化成为大多数部署中杠杆率最高的单一优化手段。 # 服务基础设施 现代推理服务器围绕预填充-解码循环封装了多种优化:  - 连续批处理(Continuous batching)在同一 GPU 步骤中交错处理来自多个请求的 token,即使在受内存限制的解码阶段也能保持高利用率。 - 投机解码(Speculative decoding)使用一个小型草稿模型提出多个 token,然后由大模型在单次前向传播中验证它们。当草稿模型的接受率较高时,这实际上将多个顺序解码步骤转化为一次并行验证。  我在这里详细介绍过投机解码: > **Avi Chawla@_avichawla**: [原文链接](https://x.com/_avichawla/status/2054860740541207032) > - PagedAttention(vLLM)以固定大小的块管理 KV 缓存内存,消除了碎片化,并使每个 GPU 能够处理更多并发请求。 vLLM、TensorRT-LLM 和 Text Generation Inference(TGI)等框架将这些技术结合起来。单个 GPU 可以同时服务数十个并发用户,因为解码会让大部分算力闲置,而连续批处理则用其他请求填补了这些空闲算力。 # 完整的推理路径  1. 分词:文本通过 BPE 转换为整数 ID。 2. 嵌入:ID 转换为向量。RoPE 编码位置信息。 3. 预填充:所有输入 token 并行地通过每一层处理。属于计算受限。填充 KV 缓存。输出第一个 token。 4. 解码循环:每步生成一个 token:为新 token 投影 Q,对缓存的 K/V 做注意力,运行 FFN,采样。将新的 K/V 追加到缓存。属于内存受限。 5. 反分词:将 token ID 映射回文本并进行流式输出。 # 一些实际的启示 - 长提示词在 TTFT(预填充)上代价高昂 - 长输出在 ITL(解码)上代价高昂 - 且它们对硬件资源的压力各不相同。 - 上下文长度并非没有代价,因为它会撑大 KV 缓存,直接降低批处理容量。 - 解码期间的 GPU 利用率可能降至 30%,即使在满载的服务器上也是如此,因为瓶颈在于内存带宽而非算术运算。 - 解决办法不是更多的算力,而是更快的内存、更小的缓存,或者更好的批处理。 当有人告诉你他们的模型很慢时,首要的诊断是判断它是启动慢(预填充受限,优化 TTFT)还是流式输出慢(解码受限,优化 ITL)。 👉 轮到你了:在你的部署中,你遇到的是 TTFT 还是 ITL 瓶颈?哪些方法对你有效? 本期到此结束! 如果你喜欢本教程: 在这里找到我 → @_avichawla 我每天都会分享关于数据科学、机器学习、大语言模型和 RAG 的教程与见解。 ## 相关链接 - [Avi Chawla](https://x.com/_avichawla) - [@_avichawla](https://x.com/_avichawla) - [28K](https://x.com/_avichawla/status/2071201619530956863/analytics) - [6月27日](https://x.com/_avichawla/status/2070828078247604480) - [242K](https://x.com/_avichawla/status/2070828078247604480/analytics) - [5月14日](https://x.com/_avichawla/status/2054860740541207032) - [39K](https://x.com/_avichawla/status/2054860740541207032/analytics) - [@_avichawla](https://x.com/@_avichawla) - [升级到高级版](https://x.com/i/premium_sign_up) - [2026年6月28日 19:58](https://x.com/_avichawla/status/2071201619530956863) - [2.86万次浏览](https://x.com/_avichawla/status/2071201619530956863/analytics) --- *导出时间: 2026/6/29 12:02:40*
P Prefill & Decode made Crystal Clear 本文从第一性原理出发,逐步讲解 LLM 推理过程中 Prefill 和 Decode 两个阶段的真实含义。作者先介绍自回归模型逐 token 预测的基本机制,然后通过 ChatGPT 聊天的例子,展示文本如何经过分词、token ID、embedding 转化为 S×D 矩阵并进入 Transformer 层。重点澄清一个常见误解:处理输入 prompt 时模型并非逐个 token 顺序处理,而是因为所有输入 token 已知,可以并行处理——这一整个输入处理过程就是 Prefill。文章还引出因果掩码等问题,帮助读者建立对推理流程的正确直觉。 技术 › LLM Abhinandan 2026-10-03 LLM推理PrefillDecodeTransformer自回归TokenizerEmbedding原理讲解
L LLM Inference After Training: Prefill, Decode, KV Cache 本文系统讲解 LLM 推理阶段的核心原理。作者指出推理与训练不同,分为 prefill 和 decode 两个阶段:prefill 并行处理整个提示词、计算密集型、决定首 token 延迟(TTFT);decode 逐 token 生成、受 HBM 内存带宽限制、决定 token 间延迟(ITL)。文章介绍了 GPU 关键硬件概念(Tensor Core FLOPS、HBM、SRAM),逐步演示一个请求的完整流程(分词、采样、KV cache 机制),并将 FlashAttention、PagedAttention、continuous batching、RadixAttention 等优化技术归位到这两个阶段中,帮助读者理解推理瓶颈与优化方向。 技术 › LLM Karan 2026-09-17 LLM推理PrefillDecodeKV CacheFlashAttentionPagedAttentionvLLMGPU推理优化
P Prefill and Decode:理解 LLM 推理的两个阶段 文章以'读长文档只要三条结论为何很慢,写两千字演讲稿反而很快开口'为切入点,讲解 LLM 推理的 prefill 与 decode 两个阶段。Prefill 并行处理全部输入 token 并保存 KV cache,决定首 token 延迟(TTFT);decode 自回归地逐个生成 token,受内存带宽影响,影响 token 间隔(ITL)。文章进一步介绍 chunked prefill、prefill/decode disaggregation 和 prefix caching 三种优化手段,并以 EXO 用 DGX Spark 做 prefill、Mac 做 decode 的演示说明跨设备分工的可能性,帮助读者具体分析 AI 响应慢的原因。 技术 › LLM Dongxi 东锡 NLP 2026-09-15 LLM推理优化PrefillDecodeKV CacheTTFTTransformer自回归生成chunked prefilldisaggregation
L LLM 为什么缓存 K 和 V,却通常不缓存 Q? 本文深入浅出地讲解了 LLM 推理中 KV cache 的原理。作者以长文档问答为场景,说明模型生成每个 token 时无需重复计算全部历史状态,解释了为什么缓存 K/V 而不需要缓存 Q:历史 Q 已完成对应位置计算,而 K/V 需供后续新位置读取。文章还讨论了 causal attention 的信息方向如何决定 cache 失效条件、KV cache 的显存开销计算、prefix caching 复用共同前缀的策略,以及 DeepSeek-V4.1-Flash 中 causal encoder-decoder、跨层 KV 共享与 shared KV representation 等架构优化。 技术 › LLM Dongxi 东锡 NLP 2026-09-13 KV CacheLLMAttentionPrefillPrefix Caching推理优化DeepSeekTransformer
L LLM 优化面试笔记:训练与推理核心技术 这是一份针对 AI 实验室面试准备的笔记,涵盖了高效训练和部署大语言模型(LLM)的核心优化策略。内容主要分为三部分:内存优化(如 Flash Attention、MQA/GQA、激活检查点)、计算优化(序列打包、高效变体 Transformer)以及推理优化(KV 缓存、投机解码、量化技术)。文章旨在总结在大规模模型开发中应对算力和内存瓶颈的关键技术。 技术 › LLM Gauri Gupta 2026-05-06 LLM优化推理训练Flash AttentionKV Cache量化面试Transformer性能优化
D Disaggregated Inference From The Ground Up 本文由 Cerebras 撰写,从基础原理讲解推理系统中的分离式推理技术。文章先介绍加速器的构成(计算单元与存储),并引入算术强度概念,通过矩阵加法与矩阵乘法的实例说明数据搬运与计算的关系。随后分析 LLM 推理的两个阶段:prefill(处理整个 prompt,计算密集型)与 decode(逐 token 生成,受限于内存带宽),解释二者对硬件需求的不同。Cerebras 提出异构分离式推理,将不同类型芯片分配给不同推理阶段,在相同硬件数量下将吞吐量提升 5 倍且不损失单用户生成速度。 技术 › LLM Cerebras 2026-10-02 Cerebras推理disaggregation算术强度prefilldecode加速器GPUKV cache硬件
一 一文了解大模型推理流程 文章系统讲解大模型推理的完整流程:输入文本先经Tokenizer切分为token并转换为token id,再通过Embedding转为带位置信息的语义向量;随后进入Prefill阶段,模型并行处理整个prompt,通过Transformer的Self-Attention计算Q、K、V并生成KV Cache,经Causal Mask确保不偷看未来token;最后经LM Head和softmax输出第一个token。进入Decode阶段后,逐个生成token、不断更新KV Cache,直到满足EOS、max_tokens或stop条件终止,最终反解码为文本输出。 技术 › LLM Jerry Fang 2026-09-18 大模型推理PrefillDecodeTransformerKV CacheTokenizerEmbeddingCausal MaskSampling
L LLM 原理与实践指南 (2026 版) 这是一份关于大语言模型(LLM)的实践指南。文章从基础循环机制出发,详细解释了文本如何转化为 Token,以及 Transformer、注意力机制、KV Cache 和 RoPE 等核心概念的工作原理。作者强调理解模型内部的推理机制(如 Prefill 和 Decode 阶段)对于硬件选型、显存估算和本地部署的重要性。文章涵盖了 Token 化、上下文窗口、量化、模型服务及本地 AI 硬件数学计算等关键主题,旨在为深入理解 LLM 提供直观的基础。 技术 › LLM Ahmad 2026-05-23 LLMTransformer本地部署Tokenization推理Attention硬件教程KV Cache
大 大语言模型训练与服务背后的数学原理 本文基于 Reiner Pope 的播客内容,深入剖析了大模型在集群中的运行机制。文章通过 Roofline 分析和 KV Cache 等核心概念,解释了推理延迟、Batch Size、API 定价策略及 MoE 架构背后的物理与经济逻辑,揭示了硬件限制如何塑造 AI 进展。 技术 › LLM Saito 2026-05-01 LLM推理架构设计数学原理MoEAPI定价性能优化Transformer
D DeepSeek V4.1 Flash 大规模推理部署实践 文章介绍 DeepSeek V4.1 Flash 大规模推理系统的部署实践与开源推理框架 DeepInfer。系统设定三大目标:兼容多厂商计算芯片、基于通用硬件组织 Prefill 与 Decode(8 卡机 Prefill、64-128 卡超节点 Decode)、支持 KVCache 保留 72 小时以上以实现上下文复用、减少冗余计算。团队通过在计算、通信、调度与存储上的持续优化,在满足延迟要求下提升有效吞吐。DeepInfer 集成高性能算子与深度优化推理引擎,支持分布式推理、投机解码、SWA Bounded Replay 和结构化输出等能力。目前单集群服务吞吐达每天 155 万亿 tokens,整体收入为每卡每小时 38 美元(按低谷价格计)。 技术 › 后端 Latent.Space 2026-10-21 DeepSeek推理框架大规模部署DeepInferLLM性能优化KVCache开源推理引擎GPU
A AI 工程师面试:大厂反复考的 25 道通用题 文章总结了 AI 工程师面试中各科技大厂(OpenAI、Meta、DeepSeek、Anthropic 等)反复考察的高频题目,覆盖三大模块:LLM 内部原理(attention、KV cache、RoPE、MoE、scaling laws、解码策略等)、推理部署与 GPU 性能(continuous batching、PagedAttention、量化、并行策略、显存估算、延迟指标等),以及 RAG、Agent、微调、评测、安全、多模态、系统设计等方向。作者指出各家面试题高度重合,建议优先刷这些通用题以获得最高性价比。 技术 › LLM 山景城小路 2026-10-07 面试LLMTransformerKV cache推理部署量化并行策略scaling lawsAI工程师大模型
从 从零手写大模型系列完结了 作者宣布「从零手写大模型」系列完结,共20篇,包括推理篇15篇和训练篇5篇。推理篇涵盖分词器、嵌入层、位置编码、自注意力机制、多头注意力、残差连接、层归一化、Transformer模块等内容;训练篇涵盖损失函数、反向传播、梯度下降、Adam优化器和学习率调度。每篇都有可练习的代码示例,帮助读者理解模型如何生成文字以及如何从误差中学习更新参数。作者强调理论公式是精华,代码多被PyTorch封装。系列笔记已发布在个人网站上,欢迎交流指正。 技术 › LLM 纳米AI (@antiAIvo) 2026-09-26 大模型LLMTransformer教程深度学习训练推理PyTorch系列笔记