From Probability to Response: Decoding, KV Cache and service delay

Compares the temperature with the value of top-p, calculates the presence of KV caches and separates the initial token delay, generation speed and total time.

System Chapter . StepCollate in 2 Graphics6 self-measurement3 First-hand sources
Start Body
Learning objectives and first steps3 objectives • 3 first fixes

Try to do it after reading

  • Manual temperature scaling and sampling to keep a pool
  • Estimation of caches by layer and by header KV
  • Distinguishing prefill, decode, queue and service indicators

Suggested first

  • Self-return language model and Attention
  • Softmax sample with probabilities
  • Size shape and byte units

Why does the same model give a different response

The post-training model produces logits at each step of the vocabulary, and the service system also determines which token will be selected. (a) Greed to select the maximum item, sampled on a probabilities basis; Temperatures, candidate filters, stop conditions and random seeds influence output. These generation conditions must be recorded when determining the capacity of the model, otherwise differences between duplicate operations are difficult to explain.

This chapter uses three synthesizing scores from the candidates and focuses on the separation of numerical operations from system costs. Readers need to understand the range of softmax and self-return visible. The example does not download models, nor does it consider animations in static web pages to be true reasoning speeds. Actual parameter name available Transformers Generation Document, the default behaviour of the different versions needs to be clearly fixed.

Temperature changes from top-p

temperature T More than zero, take each logit divided by T Do it later. softmax 。 (b) T smallness makes relative probability more concentrated but does not automatically improve factual correctness; If the most likely answer is wrong, centralized sampling will cause a steady error. T = 0 cannot be separated directly from the mathematical formula, and the engineering interface usually achieves greed or corresponding agreement through a special branch, and cannot rely on a zero-action process.

pi=exp(zi/T)∑jexp(zj/T),T>0

For logits = [2,01], T = 1 obtained [0665241,044728,0.09031]; T = 0.5 Received [0.866813, 0.11731, 0.015876]. top-p retains the minimum prefix necessary to reach the threshold for the cumulative mass in a sorted probability. For T = 1, p = 0.8, the first is not sufficient, the first two together are about 0.909699, so two are retained and re-consolidated to [0.731059,0.268941]. When filtered and the temperature scaled first, the assembly may vary, so the order of operations is part of the generation configuration.

Three probabilities after temperature drop(a) A composite column comparison of T equals one to one and one to one, the first from one to six to eight to six, and the last two drops; Each set of probabilities is one.Candidate 1Candidate 2Candidate 3.665.867.245.117.090.016Green T = 1 Blue T = 0.5
These are the probability of sampling after a given fraction of the model, not the true correctness of the three candidates.

Why can you cache K and V

Since the return of decoder, the old location will not read the new future token, so K/ V of the old location can be reused under the defined prefix and the same computing configuration. Prefill processing prefixing at once to create layer caches; decode calculates Q/ K/ V at each step for the new token and allows the new Q to read the old cache with the new entry. Cache reduces double counting, but not deleting historical context from calculation: new query still needs to access visible history key/ value.

For normal layered caches, storage amounts are close to 2 x L x B x T x Hkv x dh x s bytes. Second, K and V, L as layers, B as batch, T as cached length, Hkv as head count for KV, dh as header and s as bytes for each element. When using GQA, Hkv may be less than the number of query headers; If the header of query is wrongly used, the cache is overestimated. Quantified caches, page break metadata and matching costs are separately accounted for.

MKV≈2LBTHKVdhs

Take 32 floors, 8 KV head, 128 head, 4000-96 length, one batch and half-precision, two bytes, 536870912, or 512 MiB. The batches were doubled or doubled in length, and the plain cache was doubled. It does not contain model parameters, temporary activations and operating hours workspaces, so that "model weights can be placed in visible memory" is not sufficient to guarantee that long context services are running.Cache Official Explanation (a) A description of the concept of reuse; Caches are usually used for reasoning and cannot be moved directly into general training maps without ignoring the gradient relationship.

Prefix Cache GrowingThe three lines are prefill, the first decode, the second decode, and the grey green block is the four prefixes for reuse. The blue block is the new position for this, and the next line becomes a recyclable cache.After PrefillDecode 1Decode 2A handle prefixNew Location Only 4New Location Only 5The new Query still reads all visible K/ V; The old cache does not need to be re-projected.
The picture is a layer of time position with a complete model with a stand-alone K/ V; Position indexes must be continuously incremented.

Don't mix service indicators into a "quick"

The first token delay includes queues, prefixing and necessary network costs; Follow-up token interval reflects the decode rhythm; The whole request is also subject to the length of the output and the cessation conditions. Twenty milliseconds, prefill 50, Network 10, first item arrives in 80 milliseconds. If a total of 10 items are exported, the follow-up interval is five milliseconds, the last entry arrives at one hundred and twenty-five milliseconds, as there are only nine intervals after the first entry. There can be no more 10 more than one step.

High levels of vomiting may result in additional queues and successive batch processing may change the dynamic batches of each request. Input length, output length, symmetry, fractions, hardware and accuracy should be reported. FlashAttention optimizes the IO path and intermediate storage of attention, and the original method remains precise attention; It and the KV cache reduce duplicate projection is optimized at different levels.FlashAttention dissertation It cannot be directly used as evidence of an acceleration of the service.

import math
z = [2., 1., 0.]
def softmax(t):
assert t > 0
e = [math.exp((v-max(z))/t) for v in z]
return [v/sum(e) for v in e]
p = softmax(1.)
kept = p[:2]
print(p, [v/sum(kept) for v in kept])
print(2*32*1*4096*8*128*2 / 2**20) # 512 MiB
print(20+50+10 + (10-1)*5) # 125 ms

Arithmetic has been performed using standard Python, which is not running Transformers or real service pressure. Staple random torrents and generate configurations when bugging, check EOS Max. token Cache location, attention mask Length and batches padding Direction. Only models with the same weight and different sampling configurations cannot be claimed to have been returned under the same conditions. Float differences between different devices may also be magnified to follow the different tokens, with a distinction to be made between numerical differences and semantic quality.

Check caches with two execution paths

The most practical correctness test for the cache is to calculate the same short prefix using the full forward and incremental forward, respectively, after closing randomity and dropout. Compares the new position of each layer and the final logits, allowing for small float point differences. If the first new location is significantly different, check position, mask length and cache for this step as a matter of priority; If only the batch length series fails, check the actual location of padding with each sample.

Service pressure measurements should also distinguish between time-consuming model implementation and time-consuming user observations. Writing local calculations in the same row as end-to-end network time would underestimate the queue, sequence and flow buffers. (a) The delay in the tail beyond the average value of the report, indicating whether it contains preheating, whether it is reused and whether there are requests for failure; The deletion of the slow request and the subsequent reporting of vomiting may lead to an optimism.

Check understanding

Is halving the temperature equal to halving the probability of error?

No, it's not. It recreates the relative proportions of all logitss, and does not know which candidate is right. If the error had been the greatest, the probability would have been higher.

top-p is 0.8, is it a fixed retention of eight words?

No, it's not. It has a cumulative mass in order of probabilities, with a centralized distribution that may be retained only one or two, a flat distribution that may retain many items, and which would need to be re-unified.

Cache history, new token, so you don't read history anymore?

Still needs to read the cache K/ V to calculate matching and weighting. The calculation of the old position was avoided, and the length of history continued to affect access and the size of the cache.

KV header is less than query head, which cache is used?

Use the really stored number of KV headers. Structures such as GQA share a section K/ V and cannot be replaced without any distinction between the headers of query.

What is the sum of the first 80 milliseconds, the 10 output, the next 5 milliseconds?

125 millisecond. The first one has been counted at the first time, followed by nine intervals; The consolidation of physical flow networks may complicate the time of arrival of observations.

FlashAttention and KV cache Can you replace each other?

Can't. The former improves memory visits to focus on implementation and the latter reverts to historical status; Both can occur simultaneously and the evaluation should indicate the respective switches.

Source core for 2026-10-29; FlashAttention corresponds to the original 2022 method, Transformers document is a current dynamic page, and the interface code does not make a version compatibility commitment. Next Evidence chain for RAG, the process of generation is captured by external sources that can be verified.

Sources and reconciliations

Definitions, methods and interfaces are available.

  1. Hugging Face Transformers — How caching works
  2. Hugging Face Transformers — Generation
  3. FlashAttention — Fast and Memory-Efficient Exact Attention with IO-Awareness

Figures and calculations are reorganized according to this chapter. Mathematical measurements, framework operations and real business effects are described separately in the body of the text.

← Back to the knowledge directory
Ask Max Ask about this site
Ask Max ↗

Opening the assistant…

Paper figure

Photo comments

LEAVE A NOTE

About this photograph

Connecting to the discussion board…

    Comments become public after moderation. You can delete your own comments from this browser.
    No email is required. Clearing cookies prevents this browser from claiming earlier comments.

    MAX WANG / INDEX

    Find something

    Enter a keyword, or explore the directory below.