AI Hero Club

Efficient LLM Inference · Lesson 1

Marked Complete by You0 / 8

Saved in this browser only. Marking a lesson complete does not mean the project has passed verification.

Lesson Outline 7 subsections
Course Contents 8 lessons
Full course plan.
Efficient LLM Inference / Learning Plan ↗

LESSON 01 / 8Suggested study 120 minutes

Define the Workload Before Deriving Inference Costs

If two implementations both claim more tokens per second, how do we check that they use the same workload and time denominator?

3 Questions for This Lesson
  • Create the request timeline and distinguish model calculation from user waiting
  • Multiplier cost per item for prefilling and decoding
  • Applicable conditions for the estimation of costs by unit and reverse inspection
Course Project ZIP ↓

Project Entry Point and Prerequisite Contracts

The course is structured around a recyclable CPU reasoning lab. The first requirement is to read matrix shapes, understand causality and predict the word below; if these concepts are not yet familiar, the first four chapters of Transformer should be completed first. Instead of training language skills, the course freezes a small decoding device that compares output, space and time in different modes of execution. The random weights of the project provide only auditable numerical functions, and the random words provide only fixed working loads; they cannot answer Chinese questions and answers that quality is good and bad. The final delivery is a report with the source code, negative control and measurement of the boundary.

The length of a request to return is PP , the maximum output GG word character. The prefill sends the hint together into the model, and the last position of the logits selects the first output. Each new word is then returned to the model for the next distribution. GG One output is usually just required G−1G-1 Follow-up decoding forward; this item defines “Give a follow-up input trajectory” for a more regular workload and continues to process the designation after prefilling DD Enter a word character and compare D+1D+1 a forecast distribution. The two counts are not interchangeable and the performance table will use the latter explicitly.

Defining Metrics on the Timeline

Makes the arrival, start calculation, first output, and final output in order of origin. a,s,f,ea,s,f,e, unit is unified to seconds. The queue time is s−as-a, the service header time is f−sf-s, the user side initials wait for f−af-a. Total response time e−ae-a...... if there is G>1G>1 an output with average output spacing defined as (e−f)/(G−1)(e-f)/(G-1); the denominator is not the length of the hint, nor is it the number of outputs that include the initial characters. Whether network transfers, word fractions and formatting are included, it needs to be stated at the beginning and end points of the record, otherwise the same indicator may still be different.

There are also different denominators for the apocalypse. The number of output words completed in an observation area is divided by the number of seconds between regions; the output rate per request is averaged; the request rate is averaged. These two statistics are usually different. Only measured batches that have already been implemented will miss the queue when the congestion is increasing; only total vomiting will mask the experience of long requests, such as short requests. Chapter VII of the project will measure only forward, with both queues and user first word delays marked as unmeasured, and chapter VIII will separate probative conclusions from those that require service systems to judge.

Declare the Counting Convention Before Counting Multiply–Adds

Use BB This post is part of our special coverage Syria 2011. TT is the current sequence length, dd is the hidden width, ff It's the middle width of the front feed. NN This is the number of blocks. VV indicates the size of a glossary. A scale multiplied by one plus is calculated as two floating point operations. [m,k][m,k] Multiply [k,n][k,n] And the main thing is... 2mkn2mkn; it ignores the accuracy difference of one plus per output. The following statistics show the most closely achieved main items, excluding the costs of unipolation, bias, indexation, data movement and Python calls. The approximates are from account calibres, not model outputs.

The regular multi-directional Q, K, V, O are all wide. dd , each block total 8BTd28BTd^2 Sub-counting. Both levels of front feed from dd Present. ff From ff Present. dd Total 4BTdf4BTdf. Multiple points and weights and needs 2BT2d2BT^2d Total 4BT2d4BT^2d. The result is a mask after the full array is clearly calculated, so this is a square array; if the specific triangle kernel jumps into an invisible position, the constant changes. It cannot be assumed that the normal matrix multiplication has been eliminated because the upper triangle is set as negative.

Fprefill≈NB(8Td2+4Tdf+4T2d)+2BTVdF_{\mathrm{prefill}}\approx NB(8Td^2+4Tdf+4T^2d)+2BTVd
The prefilled density multiplied by the main entry; the last item is the projection of all positions.

Cache decoding only generates queries about new locations and new K, V. The total visible length of the word added is tt, project and forward feed within a step NB(8d2+4df)NB(8d^2+4df) ♪ Focus on the 4NBtd4NBtd. The header of the statement is only available for the new position 2BVd2BVd. No cache of references achieves a recalculation of length tt to fill in the prefilling formula TT Change it to tt. The cache does not exempt new queries from the old content; it eliminates duplicate projection, feed and attention calculations of old positions.

Fdecode(t)≈NB(8d2+4df+4td)+2BVdF_{\mathrm{decode}}(t)\approx NB(8d^2+4df+4td)+2BVd
Caches the one-step main entry; this is the formula within a limited window.

Worked Example 1: Two Executions of the Same Small Model

Take N=2,B=1,d=32,f=128,V=31,P=12N=2,B=1,d=32,f=128,V=31,P=12. The unit of ownership for each project and the previous feed is 8×322+4×32×128=245768\times32^2+4\times32\times128=24576. A prefill of twelve lengths is 12×24576+4×144×32=31334412\times24576+4\times144\times32=313344 Two dollars and a head. 2×12×31×32=238082\times12\times31\times32=23808 Total 650496650496 Next operation. Cache in 13 visible lengths 2(24576+4×13×32)+1984=544642(24576+4\times13\times32)+1984=54464;for the full prefix recalculation 2(13×24576+4×169×32)+25792=7080322(13\times24576+4\times169\times32)+25792=708032 It's arithmetic. It's not a guarantee of 13 times speed.

Why is there a significant reduction in the volume of calculations and the actual speed is not necessarily the same as that of others? The use of small arrays may account for a significant proportion of fixed costs, load distribution, cache collage, interpreter schedule; large models are also authorized to reset reading and writing limits with KV. FF The minimum data flow is MM Bytes, ideal hardware rate RR Operation per second, bandwidth as WW Bytes per second, the execution time is at least taken max⁡(F/R,M/W)\max(F/R,M/W) Constraint. This lower threshold allows for an overlap of calculations and transmissions, which cannot be added directly to the exact time, nor can peak specifications be considered as actual achievement rates.

Worked Example 2: First-Token Latency and Throughput Give Opposite Rankings

Assuming that the first line of option is zero milliseconds, prefilled 40 milliseconds, with 10 milliseconds for nine intervals after the first output; 80 milliseconds, prefilled 20 milliseconds, and five milliseconds for nine seconds. Both produce ten words, the first part of a user waits for 40 milliseconds, one hundred and thirty milliseconds for completion, and one hundred milliseconds and one hundred and forty-five milliseconds for a second. The follow-up output is faster and the user gets the first word and the full answer later. If you report only two hundred and one hundred words per second, then the cost of the queue that affects the experience will be lost. This number is a construction reverse case, not an actual test.

Unit inspection is the first type of independent verification: time must not be directly added to a hyphen, multiplied by a factor of operations is a second; bytes divided by a byte is a second. The second type of verification is a structural limit: a command T=1T=1 When prefilling is consistent with the one-step formula G=1G=1 There should be no subsequent decoding interval. NN Doubles the main items within a block and does not double the head. These tests do not depend on a running library.

Standalone ProgramRun independently of the running library expense by multiplying the ledger.
def prefill(T, N=2, B=1, d=32, f=128, V=31):
    return N*B*(8*T*d*d+4*T*d*f+4*T*T*d)+2*B*T*V*d
def decode(t, N=2, B=1, d=32, f=128, V=31):
    return N*B*(8*d*d+4*d*f+4*t*d)+2*B*V*d
assert prefill(12)==650496
assert prefill(13)==708032 and decode(13)==54464
assert prefill(1)==decode(1)
print(prefill(13)/decode(13))

Checking Bandwidth Assumptions Against the Workload

Arithmetic strength is defined as I=F/MI=F/M, the unit is a bytes. Sets a linear layer weight of one million elements, each element having two bytes, and the requested unitized matrix vectors multiplied by about two million calculations. If each step is read from the master access and is not reused, the single request is about one byte in terms of weight. Four requests are shared one by one and four calculations are about four. This deduction indicates that the batch processing may be spread the weight through the same amount as KV, activation, output and cache levels, and does not prove that the four requests are delayed as a single request. Real flow should be measured separately by the corresponding hardware tool.

Take another device that is clearly marked as hypothetical: one billion times per second for effective operations, one billion bits per second for effective bandwidth. If the mission contains 100 million calculations and 20 million bytes of traffic, the lower limit between the two is 10 milliseconds and 20 milliseconds, respectively, the desired lower limit of overlap is 20 milliseconds. Halve the calculation, but the flow remains unchanged, the lower limit is 20 milliseconds. Halve the flow, and the same two times the same amount of 10 milliseconds. This means that the same multiplier optimisation may not yield benefits under different bottlenecks. CPU In the forward, actual bandwidth counts were not collected, and it cannot be claimed that the operation was confirmed to be a bottleneck.

Checking polymeric ablation also requires closing the observation area. If A is asked to complete 10 words in one second, B is requested to complete 10 words in two seconds, and both are requested to start at zero, then a total of 20 words are completed in the second, and the sum of all requests is 10 words per second; the average of each request rate is 7.05 words per second. If the last slow request is omitted, only the first second completed, it will create an error. The post-measurement table retains all repetitions and all fixed follow-up steps and does not increase the number by deleting slow samples.

Exercises and Project Contributions

TRY IT YOURSELF

Basis: calculation of indicators

The request reaches 0 seconds, 0.03 seconds to calculate, 0.08 seconds to first output, 0 20 seconds to final output, for a total of seven outputs.

Hint 1
Draw first four points of time, start calculating, first output, and last output.
Hint 2
Queues from when the calculation is reached; the user's first word is used to reach the first output, and the number of subsequent intervals is one less than the number of outputs.
Compare with the Solution
Queues to 0.03 seconds; the user ' s first word is waiting to be 0.08 seconds; there are six intervals that follow (0.20−0.08)/6 = 0.02 seconds). When you use seven denominators, you mix the first tokens that do not have a corresponding interval. The service side start word time is 0.05 seconds.

TRY IT YOURSELF

Step: Change in front feed width

For example I, how much of the main operation would be added to the prefilling of 12 in length, which would change f from 128 to 256?

Hint 1
When f changes only, which matrix with the main items will change and which will remain unchanged?
Hint 2
The cost formula for the two layers of forward feed is different, the number of insulations, B, T,d and the additional width, without recalculating irrelevant attention items.
Compare with the Solution
Only two layers of prior feedback were added, with the difference being N×4 x B×T x d×128 = 2×4 x 12×32 x 128=393216. Neither the focus score, nor the four projectors nor the headlines were changed. The original number of 650496 was thus 1043712.

TRY IT YOURSELF

Challenge: Identification of unestablished speed findings

Some people say from 708032/54464 that the cache must be 13 times faster. Give a quantitative counter-example and specify what to measure.

Hint 1
What would happen to the same fixed call costs for both of them, in addition to the arithmetic workload?
Hint 2
The total construction time = two sets of fixed item plus arithmetic items, distinguishing the FLOPs ratio from the actual measured delay ratio, to match the range.
Compare with the Solution
Sets a fixed call cost of 1 millisecond in both directions and arithmetic time of 0.13 and 0.01 milliseconds, respectively, for a total time of 1.13 and 1.01 milliseconds, or about 1.12 times more. The output equals are checked with fixed models, input, threads, timescales, recording preheat and pairs of original hours. Multiplication is an explanatory variable that cannot substitute for delayed measurements.

This chapter adds to the work load contract: Project README describes fixed follow-up input instead of sample generation, records tips XII, XVI, lot I, and window 64. The following chapter II must prove that the cache is identical to the reference function and chapter III examines space growth; only if both are adopted will it be allowed to interpret the time sheet as an implementation difference for the same task. If the number of windows, phrases or output locations is changed, a new work load record should be created, and two inconsistent tables cannot be separated directly.

CHECK YOUR UNDERSTANDING

Check Your Understanding

Answer first, then open the explanation to check your reasoning. These questions help reveal gaps in understanding; independent implementation and transfer require separate evaluation.

1. What does the prefilling last position provide?

Show ExplanationThe last position of the hint is used to predict the next word, the first output.
2. How does the length master of the cache of one-step attention change?

Show ExplanationThe new query still needs to interact with all visible K.V. Therefore, it increases linearly in visible lengths.
3. What can this chapter of the FLOPs do directly?

Show ExplanationNo fixed cost, bandwidth or actual kernel is included and the remaining conclusions cannot be directly rolled out.
4. What are the first stages of the 10 output?

Show ExplanationThere are nine intervals between the initial and the subsequent output.

Manual completion records your progress; it does not certify your project.