arjun10g commited on
Commit
b9bef54
·
verified ·
1 Parent(s): 785fdbc

Sync 1 audio file(s) and transcripts

Browse files
audio/llm-hardware-optimization.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d7cc939a5bde99c67fd5250a28647d9c964c5130fc1a2e003f5996f8b0761c86
3
+ size 60572092
lectures/llm-hardware-optimization.md ADDED
@@ -0,0 +1,1187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hardware-Aware LLM Optimization: CPUs, GPUs, and AWS Trainium
2
+
3
+ ## Lecture one A. What Does “Faster” Mean?
4
+
5
+ Before optimizing a CPU, GPU, or Trainium chip, decide whose clock matters.
6
+
7
+ **Time to first token**, abbreviated **TTFT**, measures the delay from sending a request until its first token arrives. **Inter-token latency**, or **ITL**, measures the gaps between subsequent tokens. **Output throughput** counts generated tokens per second across the entire service.
8
+
9
+ Imagine configuration A delivers forty tokens per second to one user. Configuration B delivers thirty per second to each of ten users: three hundred overall. B completes more work, but each individual stream is slower.
10
+
11
+ A useful target might be: maximize throughput while keeping first-token delay below one second and token gaps below fifty milliseconds. Those are illustrative requirements, not universal thresholds. Model quality must also remain acceptable.
12
+
13
+ **The takeaway: faster is a workload requirement, not a hardware property.**
14
+
15
+ Before changing settings, ask: which user-visible constraint must remain satisfied?
16
+
17
+ Next, we will separate the two phases that produce those measurements: prefill and decode.
18
+
19
+ ## Lecture one B. Prefill and Decode: Two Different Hardware Problems
20
+
21
+ Our first lecture separated response latency from service throughput. Now consider why those measurements favor different hardware behavior.
22
+
23
+ During **prefill**, the model processes known prompt tokens. Within each layer, their projections can form large matrix multiplications, reusing weight tiles across many tokens.
24
+
25
+ During **decode**, ordinary autoregressive generation processes one new token per active sequence. For one user, projections resemble matrix-vector operations: many weights are read for relatively little arithmetic.
26
+
27
+ Imagine reading the same weight tile for thirty-two concurrent users. A batched kernel can reuse that tile across thirty-two token calculations instead of just one. This increases arithmetic intensity: useful operations per byte moved.
28
+
29
+ However, more requests also increase attention-cache traffic. Long contexts can change the balance again.
30
+
31
+ **The takeaway: prefill is often compute-intensive and decode often bandwidth-limited, but neither label is unconditional.**
32
+
33
+ Ask: what are my actual batch size and context length?
34
+
35
+ Next, we will make those conditions explicit in a reproducible benchmark.
36
+
37
+ ## Lecture one C. Build a Benchmark You Can Trust
38
+
39
+ Suppose an optimization appears to improve throughput by forty percent. Before celebrating, check whether the experiment changed.
40
+
41
+ Use identical model weights, tokenization, precision, and decoding settings. Hold prompt lengths, output lengths, and the request-arrival pattern constant. Record concurrency: the number of outstanding requests, not necessarily the number executing in one batch.
42
+
43
+ For a controlled test, use prompts of one thousand twenty-four tokens and outputs of two hundred fifty-six tokens. Later, replay a representative mixture of lengths.
44
+
45
+ Warm the system before steady-state measurements. Record loading, compilation, and cold-start costs separately rather than pretending they do not exist.
46
+
47
+ Measure latency distributions, not only averages. **P95**, the ninety-fifth percentile, is the threshold below which ninety-five percent of observations fall. Specify whether those observations are requests or token gaps.
48
+
49
+ **The takeaway: compare like with like, repeat runs, and preserve quality.**
50
+
51
+ Ask: could a workload change explain the improvement?
52
+
53
+ Next, we will calculate the memory budget behind that workload.
54
+
55
+ ## Lecture two A. Build the Memory and Traffic Budgets
56
+
57
+ Our benchmark now specifies the workload. Before tuning it, separate memory capacity from memory traffic.
58
+
59
+ First, weights. An illustrative eight-billion-parameter model needs sixteen billion bytes for sixteen-bit weights, before metadata. That is sixteen decimal gigabytes, or about fourteen point nine binary gibibytes.
60
+
61
+ Second, the **KV cache**, meaning key-value cache. Assume thirty-two layers, eight key-value heads, a head dimension of one hundred twenty-eight, and two bytes per value.
62
+
63
+ Multiply layers, heads, head dimension, bytes, and two for keys plus values. The result is one hundred twenty-eight kibibytes per cached token.
64
+
65
+ Four thousand ninety-six tokens require half a gibibyte per request. Sixteen such requests require eight gibibytes, before allocation overhead.
66
+
67
+ Third, add temporary activations, workspaces, and runtime buffers.
68
+
69
+ **The takeaway: fitting in memory does not establish how quickly that memory can be read.**
70
+
71
+ Ask: which tensors must move during each generation step?
72
+
73
+ Next, we will connect those bytes to arithmetic intensity.
74
+
75
+ ## Lecture two B. Arithmetic Intensity and the Roofline Model
76
+
77
+ We know the memory footprint. Now ask how much computation each transferred byte supports.
78
+
79
+ **Arithmetic intensity** means operations performed per byte moved across a specified memory boundary. Here, use external memory to the processor.
80
+
81
+ Imagine hardware sustaining one hundred trillion operations per second and two trillion bytes per second at the relevant precision. Dividing gives fifty operations per byte: its approximate compute-to-bandwidth crossover.
82
+
83
+ For a simplified dense eight-billion-parameter model, one decode token involves roughly sixteen billion weight-related operations. Reading sixteen billion weight bytes gives approximately one operation per byte. Ignore attention and other traffic for this first estimate.
84
+
85
+ Batching sixty-four tokens could raise weight-related intensity toward sixty-four, provided the kernel actually reuses those weights. Additional traffic lowers the full-workload intensity.
86
+
87
+ **The takeaway: the roofline model gives a ceiling, not a guaranteed performance prediction.**
88
+
89
+ Ask: should I first reduce bytes moved or improve arithmetic execution?
90
+
91
+ Next, we will decide which operation is worth optimizing.
92
+
93
+ ## Lecture two C. Amdahl’s Law and the Critical Path
94
+
95
+ The roofline model identifies a possible resource limit. Amdahl’s law tells us whether improving that resource will matter overall.
96
+
97
+ Imagine one token takes one hundred milliseconds. An operation occupies twenty milliseconds, while everything else takes eighty. Assume these times are sequential.
98
+
99
+ Make that operation ten times faster. Its twenty milliseconds become two, giving eighty-two milliseconds overall. Latency falls eighteen percent; throughput for this sequential loop rises about twenty-two percent. Those are different percentages describing the same change.
100
+
101
+ Even eliminating the operation entirely would leave eighty milliseconds. That limits the total speedup to one point two five times.
102
+
103
+ Real traces include overlapping work. Adding every kernel’s duration can overstate elapsed time, so inspect dependencies and the critical path: the chain determining completion.
104
+
105
+ **The takeaway: prioritize time you can actually remove from the request.**
106
+
107
+ Ask: how much end-to-end improvement could this change possibly deliver?
108
+
109
+ Next, we will trace the operations inside one decoder block.
110
+
111
+ ## Lecture three A. Follow a Decoder Block Through Its Operations
112
+
113
+ We now need an execution map, not another transformer introduction.
114
+
115
+ Take a common decoder block using **RMSNorm**, root mean square normalization. It rescales activations before projections create queries, keys, and values. Positional transformations may follow, depending on the architecture.
116
+
117
+ During decode, attention compares the current query with cached keys, normalizes scores, and combines cached values. An output projection and residual addition follow. Another normalization leads into the feed-forward network, often with expansion, gating, and contraction.
118
+
119
+ Group the hardware work into large weight-bearing matrix operations, attention-cache access, and smaller elementwise or reduction operations.
120
+
121
+ A **kernel** is a low-level implementation of some computation; CPUs have kernels too. One mathematical operator can launch multiple kernels, while one fused kernel can implement several operators.
122
+
123
+ Writing an intermediate tensor between kernels can create avoidable traffic.
124
+
125
+ **The takeaway: operator boundaries and execution boundaries are not identical.**
126
+
127
+ Ask: which intermediate is materialized unnecessarily?
128
+
129
+ Next, we will locate those decisions in the software stack.
130
+
131
+ ## Lecture three B. Frameworks, Inference Engines, Compilers, and Kernels
132
+
133
+ Our decoder block becomes executable through several cooperating software layers, not one rigid assembly line.
134
+
135
+ A **framework**, such as PyTorch, expresses tensor operations and model behavior. An **inference engine**, such as vLLM, coordinates requests, batching, and attention-cache allocation.
136
+
137
+ A **compiler** transforms supported code into executable implementations. It may fuse operations, specialize shapes, or call existing libraries. Some kernels are compiled beforehand; others are compiled when needed.
138
+
139
+ The **kernel** performs the actual low-level work. Its layout and arithmetic must match the device.
140
+
141
+ These responsibilities overlap. An inference engine can contain custom kernels; a compiled graph can call prebuilt kernels without recompiling their internals.
142
+
143
+ For example, queueing caused by a poor scheduling policy is not automatically fixed by faster multiplication. Conversely, a bad multiplication implementation is not necessarily cured by changing the scheduler.
144
+
145
+ **The takeaway: place the bottleneck in the correct software layer before intervening.**
146
+
147
+ Ask: which component controls the wasted time?
148
+
149
+ Next, we will examine precision across these layers.
150
+
151
+ ## Lecture three C. Precision Is an Execution Contract
152
+
153
+ The software stack must agree on what a compressed model actually means.
154
+
155
+ Separate **weight storage precision**, **activation precision**, and **accumulation precision**. Accumulation is the format used while summing products, not simply the format of each multiplication input.
156
+
157
+ **W4A16** means four-bit weights and sixteen-bit activations. It does not fully specify accumulation or the instructions that execute.
158
+
159
+ Our eight-billion-parameter model would contain four billion raw weight bytes at four bits each. Scales, offsets, padding, and unquantized tensors add overhead.
160
+
161
+ A kernel might unpack those weights, apply scales, and convert values before multiplication. An efficient implementation performs this work close to computation instead of expanding the whole model into temporary memory.
162
+
163
+ Smaller storage can therefore help a bandwidth-limited workload while hurting another workload through conversion overhead.
164
+
165
+ **The takeaway: choose a numerical format together with a supported, measured kernel.**
166
+
167
+ Ask: what arithmetic does my backend actually execute?
168
+
169
+ Next, we begin CPU optimization with vector instructions.
170
+
171
+ ## Lecture four A. CPU SIMD: More Useful Work per Instruction
172
+
173
+ We move from software layers to the CPU instructions executing a linear layer.
174
+
175
+ **SIMD** means single instruction, multiple data. One vector instruction performs corresponding operations on several packed values. A dot product can use vector multiplication, accumulation, and a final reduction rather than separate scalar instructions for every pair.
176
+
177
+ Some CPUs also provide integer dot-product instructions that combine several products and accumulate into wider integer results.
178
+
179
+ For our quantized model, however, four-bit storage is only the starting point. The kernel must interpret packed values and scales, then arrange operands for supported instructions. That preparation can dominate a poorly implemented loop.
180
+
181
+ Wider vectors also do not guarantee proportional speedups when memory bandwidth already limits execution.
182
+
183
+ Imagine cutting arithmetic time in half while weight-read time stays unchanged. The benefit depends on which one sets the critical path.
184
+
185
+ **The takeaway: maximize useful work, not vector width alone.**
186
+
187
+ Ask: are arithmetic instructions or operand preparation limiting this kernel?
188
+
189
+ Next, we examine matrix-oriented CPU instructions.
190
+
191
+ ## Lecture four B. CPU Matrix Engines: Intel AMX and Arm SME
192
+
193
+ Vector instructions process several values together. Matrix-oriented instructions extend that idea to blocks of computation.
194
+
195
+ Intel **AMX**, Advanced Matrix Extensions, provides two-dimensional tile registers and matrix multiply-accumulate operations. Available numerical formats depend on the processor generation and supported extensions.
196
+
197
+ Arm **SME**, Scalable Matrix Extension, introduces two-dimensional accumulator storage called **ZA**, or Z Array. Outer-product instructions multiply elements from two vectors and accumulate the resulting matrix into that storage.
198
+
199
+ These are related capabilities, not identical hardware designs.
200
+
201
+ Imagine our model processing a long prompt. Many token rows provide enough matrix work to reuse loaded operands and amortize setup costs. During one-user decoding, much smaller shapes may leave that capability underused.
202
+
203
+ Batching can improve the fit, but it changes latency and memory requirements. A matrix-capable CPU needs a compatible operating environment and an efficient kernel.
204
+
205
+ **The takeaway: match precision and matrix shape to the available execution path.**
206
+
207
+ Ask: does this workload use the matrix engine?
208
+
209
+ Next, we connect capability to compiled code.
210
+
211
+ ## Lecture four C. CPU Targets, Compilers, and Runtime Dispatch
212
+
213
+ A CPU can support an instruction that your program never executes.
214
+
215
+ The **ISA**, instruction set architecture, defines the machine instructions available to software. A compiler target controls which of those instructions generated code may use.
216
+
217
+ For supported compilers and targets, the option commonly written as “march equals native” selects capabilities of the compilation machine. That can improve specialization, but the binary may fail on an older deployment machine.
218
+
219
+ Another approach is **runtime dispatch**: ship several kernel implementations and select a compatible one after detecting processor features. A portable binary can therefore still use advanced instructions.
220
+
221
+ llama.cpp supports CPU-specific build choices and backend variants. Nevertheless, a favorable build flag does not prove that a particular operation selected the desired kernel.
222
+
223
+ Check build information, runtime reporting, and performance evidence.
224
+
225
+ **The takeaway: distinguish hardware support, compiled availability, and actual kernel selection.**
226
+
227
+ Ask: which implementation ran for this tensor shape?
228
+
229
+ Next, we will arrange data to feed that implementation efficiently.
230
+
231
+ ## Lecture five A. Cache Blocking and Weight Packing
232
+
233
+ The right instructions still need the right operands at the right time.
234
+
235
+ **Cache blocking**, also called tiling, divides a matrix operation into pieces sized for useful reuse in registers and cache.
236
+
237
+ Imagine processing sixteen prompt tokens together. A weight tile can contribute to all sixteen before being displaced. That is more useful than repeatedly fetching it for independent token calculations.
238
+
239
+ **Weight packing** rearranges values into the layout an optimized kernel expects. For example, values consumed together by a vector or matrix instruction can be stored together rather than gathered from scattered locations.
240
+
241
+ Because inference weights remain unchanged, a backend can pack them once and reuse the result. Packing still consumes startup time and may require additional memory.
242
+
243
+ For single-token decoding, a model larger than cache still requires substantial weight traffic.
244
+
245
+ **The takeaway: blocking creates reuse; packing makes the required access pattern cheaper.**
246
+
247
+ Ask: am I repacking or reloading something unnecessarily?
248
+
249
+ Next, we explore how CPU threads compete for those resources.
250
+
251
+ ## Lecture five B. Find the Useful CPU Thread Count
252
+
253
+ Cache-aware kernels do not mean that every additional thread improves inference.
254
+
255
+ Imagine a decode test using eight, sixteen, and thirty-two threads. Throughput rises from eight to sixteen, then barely changes at thirty-two.
256
+
257
+ One hypothesis is memory-bandwidth saturation: sixteen workers already move weights as quickly as the memory system allows. Extra workers add scheduling and synchronization without increasing available bandwidth.
258
+
259
+ But a plateau alone is not proof. Also check core placement, thread oversubscription, and whether work is large enough to divide efficiently. Multiple software libraries can accidentally create competing thread pools.
260
+
261
+ Run separate sweeps for prefill and decode. Prefill may benefit from more compute resources even when single-user decode does not.
262
+
263
+ Keep power settings, model precision, and memory placement fixed during each sweep. Repeat measurements to separate noise from improvement.
264
+
265
+ **The takeaway: choose thread count from a scaling curve, not the advertised core count.**
266
+
267
+ Ask: what evidence explains the plateau?
268
+
269
+ Next, we will examine where those threads and their memory live.
270
+
271
+ ## Lecture five C. NUMA Placement and Thread Affinity
272
+
273
+ Thread count is only half the CPU placement problem.
274
+
275
+ **NUMA**, non-uniform memory access, means access cost depends on where memory resides relative to a processor. A multi-socket server commonly has memory attached near each socket.
276
+
277
+ **Thread affinity** keeps workers on chosen cores. Memory placement determines which locality domain supplies their pages. Pinning threads does not automatically move previously allocated memory.
278
+
279
+ Imagine weights allocated near socket one while workers execute on socket two. Reads cross the socket interconnect instead of using only local memory paths.
280
+
281
+ Compare a locally placed single-socket configuration with a deliberately partitioned multi-socket configuration. A larger deployment can expose more aggregate bandwidth, but communication and allocation policy matter.
282
+
283
+ For two independent replicas, placing one replica and its weights near each socket may avoid unnecessary cross-socket traffic, provided memory capacity permits.
284
+
285
+ **The takeaway: treat compute placement and data placement as one decision.**
286
+
287
+ Ask: are my workers reading locally?
288
+
289
+ Next, we will return to the arithmetic inside quantized CPU kernels.
290
+
291
+ ## Lecture six A. Four-Bit Storage Does Not Specify the Arithmetic
292
+
293
+ We have placed CPU threads and memory sensibly. Now inspect what a four-bit dot product actually does.
294
+
295
+ Two four-bit values fit into one byte. The kernel extracts them, interprets their signed or offset representation, and applies the appropriate scale information.
296
+
297
+ From there, execution paths differ. One kernel converts values into floating point. Another quantizes activations into eight-bit integers, uses integer dot-product instructions, and rescales accumulated results.
298
+
299
+ Neither path is described completely by saying “the model is four-bit.” Even a weight-only compressed file may execute with additional temporary activation quantization inside its backend.
300
+
301
+ Imagine two implementations reading identical compressed weights. The faster one might simply require fewer unpacking and conversion instructions, not fewer mathematical multiplications.
302
+
303
+ Measure the full operation, including preparation, rather than timing only its multiply loop.
304
+
305
+ **The takeaway: storage format and execution format are separate choices.**
306
+
307
+ Ask: where are unpacking, activation conversion, and scaling performed?
308
+
309
+ Next, we will reduce the memory traffic those steps can create.
310
+
311
+ ## Lecture six B. Fuse Dequantization with CPU Computation
312
+
313
+ Consider two ways to use our four-bit weights on a CPU.
314
+
315
+ The first expands an entire matrix into sixteen-bit values, stores that temporary matrix, and then multiplies it. During repeated inference, this can add a large write followed by another read.
316
+
317
+ The second loads a compressed tile, unpacks only the needed values, and consumes them immediately in the dot-product kernel. Intermediate values can stay in registers or nearby working storage instead of becoming a full external-memory tensor.
318
+
319
+ That is **fused dequantization**: combining reconstruction with useful computation.
320
+
321
+ It still costs instructions. Excessive live intermediate state can also pressure registers. A fused implementation must be measured, not assumed superior.
322
+
323
+ For fixed weights and large repeated batches, a separately prepared representation might sometimes repay its storage and preparation costs. The workload decides.
324
+
325
+ **The takeaway: avoid materializing expanded weights unless reuse justifies it.**
326
+
327
+ Ask: which temporary writes disappear in the fused path?
328
+
329
+ Next, we will compare the quantization layouts feeding these kernels.
330
+
331
+ ## Lecture six C. Match Quantization Groups and Layouts to the Kernel
332
+
333
+ Fusion works best when the compressed layout suits the kernel.
334
+
335
+ **Group size** describes how many values share quantization metadata, such as a scale. Smaller groups can represent local ranges more accurately, but require more metadata and scaling work.
336
+
337
+ Consider a deliberately simple format: thirty-two four-bit weights occupy sixteen bytes. Add one two-byte scale, and the group occupies eighteen bytes. Its effective storage is four point five bits per weight, before padding or other metadata.
338
+
339
+ That is why nominal bit width does not fully describe memory traffic.
340
+
341
+ Packing order matters too. A layout convenient for one vector instruction may require extra rearrangement on another CPU. Changing group size can also alter which optimized kernels are supported.
342
+
343
+ Compare formats at an acceptable quality level, measuring prefill and decode separately. Do not assume the smallest file is the fastest deployment.
344
+
345
+ **The takeaway: evaluate the complete format-kernel pair.**
346
+
347
+ Ask: am I saving weight bytes but adding expensive preparation?
348
+
349
+ Next, we assemble a CPU baseline.
350
+
351
+ ## Lecture seven A. Establish a CPU Baseline with llama.cpp
352
+
353
+ We now have enough theory to run a meaningful CPU experiment.
354
+
355
+ Start with a known llama.cpp version and a model representation it supports. Record the processor, build options, selected backend, precision, thread count, and memory placement.
356
+
357
+ Use **llama-bench**, the project’s benchmarking tool, to measure prompt processing and token generation separately. Confirm the meaning of its parameters in the documentation for your version.
358
+
359
+ Begin with a fixed prompt length and generation length. Warm the workload, run repeated trials, and preserve the raw results rather than only the best run.
360
+
361
+ A kernel-focused benchmark answers how this model configuration executes under controlled conditions. It does not automatically measure networking, request queueing, tokenization, or tail latency through a real server.
362
+
363
+ After establishing the baseline, repeat the chosen configuration through your actual serving path.
364
+
365
+ **The takeaway: a microbenchmark is a diagnostic instrument, not the entire service evaluation.**
366
+
367
+ Ask: which costs does this measurement exclude?
368
+
369
+ Next, we will change exactly one variable.
370
+
371
+ ## Lecture seven B. Tune One Variable and Explain the Result
372
+
373
+ Take the CPU baseline and choose one hypothesis: decode is limited by memory bandwidth, while prefill still benefits from extra threads.
374
+
375
+ Sweep thread count without changing precision, request lengths, or memory placement. Suppose decode plateaus at sixteen threads, but prefill improves through thirty-two. These are hypothetical results, not a claim about every processor.
376
+
377
+ Now inspect bandwidth and execution measurements. A flat decode curve with saturated memory traffic supports the hypothesis. A flat curve with mostly idle cores suggests another explanation, such as serialization or insufficient work.
378
+
379
+ Keep the best configuration for your actual service objective. Some engines allow distinct controls for different phases; verify support rather than assuming it.
380
+
381
+ Once the thread experiment is complete, you can separately test batch size. Combining both changes immediately would make attribution harder.
382
+
383
+ **The takeaway: predict, change, measure, and explain before combining optimizations.**
384
+
385
+ Ask: what observation would falsify my hypothesis?
386
+
387
+ Next, we will decide whether adding a GPU helps.
388
+
389
+ ## Lecture seven C. When CPU–GPU Offloading Helps
390
+
391
+ Suppose our model does not fit entirely in GPU memory. A hybrid configuration can keep some layers on the CPU and others on the GPU.
392
+
393
+ With persistent layer placement, weights remain near the processor executing them. Activations cross the boundary between assigned layer groups. That differs from repeatedly streaming large weight tensors into the GPU during generation.
394
+
395
+ **PCIe**, Peripheral Component Interconnect Express, is a common host-device connection. Its usable bandwidth and transfer latency must enter the performance budget.
396
+
397
+ Imagine saving ten milliseconds of CPU computation but adding twelve milliseconds of transfers and synchronization. The offload loses, despite the GPU kernel being faster.
398
+
399
+ Also account for attention-cache placement and temporary buffers. Some integrated systems share physical memory, so their transfer model differs from a discrete accelerator’s.
400
+
401
+ **The takeaway: evaluate the complete partition, not the GPU’s isolated speed.**
402
+
403
+ Ask: what crosses the boundary, how often, and on whose critical path?
404
+
405
+ Next, we move fully onto GPUs and examine matrix shapes.
406
+
407
+ ## Lecture eight A. Tensor-Core Capability Versus Useful Utilization
408
+
409
+ On a GPU, arithmetic capability matters only when the workload exposes suitable work.
410
+
411
+ Compare one-user decode with a batch of sixty-four users. Both use the same weights, but their activation matrices have different numbers of token rows.
412
+
413
+ A tiny operation may provide too few useful tiles to occupy the device. A larger operation can distribute more tiles and reuse weights across more rows.
414
+
415
+ Specialized matrix units also have supported shapes and numerical formats. Padding an awkward dimension may make an implementation possible, but some executed arithmetic then contributes nothing to the answer.
416
+
417
+ This does not mean that every small matrix must avoid tensor cores. Specialized kernels can still be effective; the comparison must use real shapes and include all overhead.
418
+
419
+ Record useful throughput alongside total execution time rather than trusting peak specifications.
420
+
421
+ **The takeaway: matrix dimensions are part of the hardware configuration.**
422
+
423
+ Ask: how many useful tiles does this operation expose?
424
+
425
+ Next, we will examine how their threads access memory.
426
+
427
+ ## Lecture eight B. Coalesced Access and Tensor Layout
428
+
429
+ Useful matrix tiles still need efficient memory access.
430
+
431
+ **Coalescing** means combining nearby threads’ memory requests into an efficient set of memory transactions. It depends on addresses, alignment, and access size, not simply on whether a tensor is contiguous somewhere in memory.
432
+
433
+ Imagine neighboring threads reading neighboring elements. Now imagine the same threads reading elements separated by a long stride. Both request the same amount of useful data, but the second pattern may require many more transactions.
434
+
435
+ A tensor layout determines which dimension sits next to which in memory. A layout convenient for one operation can be inconvenient for the next.
436
+
437
+ Transposing or repacking can repair access patterns, but that transformation also moves data. Prefer a pipeline whose adjacent kernels agree on layout when possible.
438
+
439
+ Measure the complete chain, including any rearrangement.
440
+
441
+ **The takeaway: optimize useful bytes per transaction, not just nominal tensor size.**
442
+
443
+ Ask: are neighboring threads requesting nearby addresses?
444
+
445
+ Next, we will reuse efficiently loaded data on-chip.
446
+
447
+ ## Lecture eight C. GPU Tiling and On-Chip Reuse
448
+
449
+ Coalescing makes a transfer efficient. Tiling makes each transferred value useful more than once.
450
+
451
+ Many datacenter GPUs use **HBM**, high-bandwidth memory. A matrix kernel loads tiles from external memory into on-chip storage, such as shared memory and registers, then reuses them for multiple products.
452
+
453
+ Imagine multiplying a tile containing sixteen token rows by a weight tile. Reusing each weight across those rows raises useful arithmetic per external byte.
454
+
455
+ A larger tile may increase reuse, but it also consumes more registers and shared memory. That can reduce the number of simultaneously resident thread blocks. An oversized tile can therefore lose despite reducing some traffic.
456
+
457
+ Edge tiles introduce another tradeoff: padded or masked elements may consume resources without producing useful outputs.
458
+
459
+ Try several tile shapes against the actual operation dimensions, including small decode batches and long prefills.
460
+
461
+ **The takeaway: reuse competes with resource capacity.**
462
+
463
+ Ask: does this tile save more traffic than the resources it consumes?
464
+
465
+ Next, we will examine occupancy.
466
+
467
+ ## Lecture nine A. Occupancy Is Not the Same as Speed
468
+
469
+ Our tile size controls how much work can reside on the GPU at once.
470
+
471
+ An NVIDIA **SM**, streaming multiprocessor, executes resident thread blocks. **Occupancy** measures resident warps relative to the architectural maximum. It is not the same as useful compute utilization.
472
+
473
+ More resident warps can hide latency by providing other work when one warp waits. But each block consumes registers, shared memory, and scheduling resources.
474
+
475
+ Imagine reducing registers per thread to admit more warps. If that forces intermediate values to spill into device-backed local memory, the extra traffic can outweigh improved occupancy.
476
+
477
+ Conversely, a kernel with moderate occupancy may keep its limiting execution units busy. Increasing occupancy would then solve the wrong problem.
478
+
479
+ Compare kernel duration, memory behavior, and execution stalls, not occupancy alone. Other GPU architectures use related concepts with different names and resource limits.
480
+
481
+ **The takeaway: occupancy is evidence, not the objective.**
482
+
483
+ Ask: what latency or resource limitation would additional resident work actually hide?
484
+
485
+ Next, we evaluate fusion.
486
+
487
+ ## Lecture nine B. Kernel Fusion and Its Limits
488
+
489
+ Occupancy explains one reason that combining kernels can both help and hurt.
490
+
491
+ Imagine a matrix multiplication writing an intermediate tensor, followed by an activation kernel reading it, transforming it, and writing again. A fused implementation may apply the activation before the result leaves the first kernel.
492
+
493
+ That can remove an intermediate memory round trip and a launch. Similar opportunities occur around normalization, residual additions, and quantization.
494
+
495
+ However, fusion increases the amount of live state or the complexity of scheduling. It can raise register use, reduce parallelism, or prevent a specialized library kernel from handling the largest operation.
496
+
497
+ A fused kernel is therefore not automatically the best kernel.
498
+
499
+ Measure the original chain and the fused chain under identical shapes. Include every conversion or layout change introduced around the replacement.
500
+
501
+ **The takeaway: fusion should remove more overhead than it introduces.**
502
+
503
+ Ask: which reads, writes, and launches disappear, and what new resource pressure appears?
504
+
505
+ Next, we overlap work that still needs to happen.
506
+
507
+ ## Lecture nine C. Overlap Data Movement with Computation
508
+
509
+ Fusion removes work. **Pipelining** hides some remaining work behind independent computation.
510
+
511
+ Consider loading tile two while computing on tile one. **Double buffering** reserves separate storage for the tile being consumed and the tile being prepared.
512
+
513
+ In a simplified example, loading each tile takes eight microseconds and computing takes twenty. Serial execution takes twenty-eight. With ideal independent overlap, the long-run interval can approach twenty, plus startup and drain costs.
514
+
515
+ That improvement requires real independence. Computation cannot use a tile before its load completes, and a buffer cannot be overwritten while still in use.
516
+
517
+ Transfers may also compete for bandwidth with other operations. More buffers consume more on-chip storage, potentially reducing residency.
518
+
519
+ Use a timeline to verify that the intended overlap occurs. An asynchronous instruction permits overlap; it does not guarantee it.
520
+
521
+ **The takeaway: overlap shortens the critical path only when dependencies and resources allow it.**
522
+
523
+ Ask: which waits remain exposed?
524
+
525
+ Next, we apply these ideas to attention.
526
+
527
+ ## Lecture ten A. What FlashAttention Changes
528
+
529
+ Attention combines our previous lessons about tiling, fusion, and data movement.
530
+
531
+ A straightforward prefill implementation can materialize a large attention-score matrix in external memory, then read it again for normalization and value aggregation.
532
+
533
+ **FlashAttention** instead processes tiles and maintains running normalization statistics and partial outputs. Intermediate scores need not become one full external-memory matrix.
534
+
535
+ The key is an online softmax calculation: updating normalization as new score blocks arrive while preserving the dense attention result mathematically.
536
+
537
+ Ordinary floating-point rounding can still differ between implementations. “Exact attention” distinguishes the algorithm from an approximation that drops or changes attention interactions.
538
+
539
+ For dense prefill attention, the underlying arithmetic still grows quadratically with sequence length. FlashAttention primarily changes memory behavior and execution efficiency, not that fundamental count.
540
+
541
+ Generation with one query per sequence needs its own suitable attention kernel and parallelization choices.
542
+
543
+ **The takeaway: fewer intermediate bytes can outperform fewer advertised operations.**
544
+
545
+ Ask: which attention tensors actually reach external memory?
546
+
547
+ Next, we tackle cache allocation.
548
+
549
+ ## Lecture ten B. What Paged Key-Value Caching Changes
550
+
551
+ FlashAttention improves attention execution. **Paged key-value caching** addresses a different problem: allocating and sharing cache memory.
552
+
553
+ Suppose every request reserves one contiguous region large enough for its maximum possible context. Short requests leave much of that reservation unused, limiting how many requests fit.
554
+
555
+ A paged design divides the cache into fixed-size blocks. A logical sequence maps to physical blocks that need not sit next to each other. Additional blocks can be allocated as the sequence grows.
556
+
557
+ A compatible attention kernel follows that mapping when reading keys and values. Shared prefixes may also share blocks when the implementation supports safe reuse.
558
+
559
+ There is still metadata, mapping overhead, and possible waste in the final partly filled block. Paging does not eliminate attention arithmetic or make every cache access cheaper.
560
+
561
+ **The takeaway: better allocation can enable more useful concurrency without shrinking the model.**
562
+
563
+ Ask: how much memory is reserved but not serving useful tokens?
564
+
565
+ Next, we investigate growing context length.
566
+
567
+ ## Lecture ten C. Diagnose Long-Context Decoding
568
+
569
+ We have improved cache allocation. Now consider the cost of reading the cache itself.
570
+
571
+ Hold model weights and active batch size constant while increasing context length. For ordinary full-attention decoding, each new query attends over more previous keys and values.
572
+
573
+ Weight traffic may remain broadly similar per step, while attention computation and cache traffic grow. Eventually, optimizing only the weight kernels can produce diminishing returns.
574
+
575
+ Possible interventions include a better decode-attention kernel, a lower-precision cache, or a different concurrency limit. Each changes a different part of the budget.
576
+
577
+ Cache quantization reduces stored bytes but introduces conversion work and potential quality changes. It is separate from quantizing model weights.
578
+
579
+ Shortening context, restricting the attention window, or evicting tokens may change model behavior; those are not equivalent replacements for exact full attention.
580
+
581
+ **The takeaway: context length can move the bottleneck into attention.**
582
+
583
+ Ask: how does attention time change as context grows?
584
+
585
+ Next, we will locate that time in a profiler.
586
+
587
+ ## Lecture eleven A. Read the GPU Timeline Before the Counters
588
+
589
+ A slow request needs an explanation in elapsed time before it needs an impressive counter report.
590
+
591
+ On NVIDIA systems, **Nsight Systems** provides a timeline spanning host activity, device work, and transfers. **Nsight Compute** examines individual kernels and detailed performance measurements.
592
+
593
+ Begin with the timeline. Are kernels separated by host-side gaps? Is a transfer delaying the next operation? Is the device continuously busy, but on expensive attention work?
594
+
595
+ Only then inspect the kernel responsible for the limiting region. Examine memory traffic, execution-unit activity, and resource pressure against your hypothesis.
596
+
597
+ Imagine a multiplication kernel that is already efficient, surrounded by substantial launch gaps. Spending weeks tuning its arithmetic would attack the wrong part of the request.
598
+
599
+ Profiling itself can perturb execution, particularly when counters require replay. Confirm improvements with ordinary end-to-end benchmarks afterward.
600
+
601
+ **The takeaway: local efficiency matters only in its execution context.**
602
+
603
+ Ask: which visible dependency determines completion?
604
+
605
+ Next, we compare precision choices on specific GPUs.
606
+
607
+ ## Lecture eleven B. Choose Low Precision for a Specific GPU
608
+
609
+ Our profiler identifies a costly matrix operation. Should we choose a smaller numerical format?
610
+
611
+ **FP8** means eight-bit floating point. **INT4** means four-bit integer. These labels describe different representations, not interchangeable speed settings.
612
+
613
+ For a given GPU, check native instruction support, the kernel’s supported operand combination, and the numerical scaling required. Stored four-bit weights may still feed higher-precision arithmetic after conversion.
614
+
615
+ NVIDIA and AMD devices also use different software ecosystems. AMD’s **ROCm** is its GPU software platform; a tuned NVIDIA kernel is not automatically a tuned AMD implementation.
616
+
617
+ Imagine four-bit weights improving one-user decode because fewer bytes are read, while an eight-bit floating-point kernel wins during larger prefills because its arithmetic path is more efficient. That is a hypothesis to test, not a universal ranking.
618
+
619
+ Evaluate representative quality tasks after numerical changes.
620
+
621
+ **The takeaway: select precision for the exact device, backend, shape, and quality target.**
622
+
623
+ Ask: where does conversion erase the expected saving?
624
+
625
+ Next, we address launch overhead.
626
+
627
+ ## Lecture eleven C. Reduce Launch Overhead with Graph Replay
628
+
629
+ Suppose the GPU timeline shows small kernels separated by host submission overhead.
630
+
631
+ **CUDA**, Compute Unified Device Architecture, is NVIDIA’s GPU programming platform. **CUDA Graphs** records an execution pattern so work can be submitted with less per-operation host overhead.
632
+
633
+ Graph replay does not fuse kernels or make the memory system faster. It mainly changes how work is launched and coordinated.
634
+
635
+ For a stable decode shape, this can reduce gaps around otherwise efficient kernels. Variable workloads may need multiple captures, shape buckets, or partial graph execution, depending on the framework.
636
+
637
+ Captured work also imposes constraints, such as stable memory addresses in common implementations. Frameworks manage these through prepared buffers and other machinery.
638
+
639
+ Measure capture costs and extra memory separately from warm replay. A compute-heavy kernel with little launch overhead may barely benefit.
640
+
641
+ **The takeaway: graph replay targets dispatch overhead, not every kind of inefficiency.**
642
+
643
+ Ask: did the gaps shrink without worsening memory or shape handling?
644
+
645
+ Next, we transfer our method to Trainium.
646
+
647
+ ## Lecture twelve A. Trainium: Think in Engines, Not GPU Warps
648
+
649
+ Our optimization method carries over to **AWS**, Amazon Web Services, Trainium. Our GPU execution model does not transfer unchanged.
650
+
651
+ A **NeuronCore** contains specialized engines. The Tensor Engine performs matrix-oriented work. Vector and Scalar Engines handle supported operations such as elementwise transforms and reductions. Other facilities handle computation and data movement.
652
+
653
+ These engine names describe Trainium resources, not a promise that every operation follows an ordinary CPU-style instruction path.
654
+
655
+ Imagine a matrix multiplication followed by an activation. Accelerating the matrix engine alone cannot eliminate a wait caused by moving its result or preparing the next input.
656
+
657
+ The useful mental model is a dependency graph mapped onto engines and memory buffers. Independent operations may overlap; dependent ones must respect ordering.
658
+
659
+ Exact capabilities vary by NeuronCore generation, so use the matching architecture guide.
660
+
661
+ **The takeaway: optimize the engine schedule and dataflow, not just matrix throughput.**
662
+
663
+ Ask: which engine or dependency is holding up the next operation?
664
+
665
+ Next, we inspect the buffers connecting them.
666
+
667
+ ## Lecture twelve B. Trainium’s Explicit On-Chip Buffers
668
+
669
+ Trainium’s engines communicate through storage that matters directly to kernel design.
670
+
671
+ **SBUF**, the state buffer, holds on-chip working tensors. **PSUM**, the partial-sum buffer, holds accumulation results for supported operations, notably matrix products.
672
+
673
+ A common matrix path loads operands from external high-bandwidth memory into SBUF, accumulates matrix results in PSUM, then moves or processes the result before storing it externally.
674
+
675
+ These are not ordinary CPU caches that transparently rescue arbitrary access patterns. The kernel and compiler must arrange legal layouts, lifetimes, and transfers.
676
+
677
+ Imagine retaining a weight tile while processing several activation tiles. That reuse saves external reads. But keeping too many tensors live can exceed the available on-chip storage and force additional movement.
678
+
679
+ A mathematically valid operation can therefore be slow because its buffer schedule is poor.
680
+
681
+ **The takeaway: manage on-chip residency as deliberately as arithmetic.**
682
+
683
+ Ask: which tensor should remain live, and which can be released or recomputed?
684
+
685
+ Next, we identify the exact Trainium configuration.
686
+
687
+ ## Lecture twelve C. Identify the Trainium Generation and Configuration
688
+
689
+ Before choosing tile sizes, be precise about what “a Trainium device” means.
690
+
691
+ A **NeuronCore** is a compute unit within a chip. A cloud instance can contain multiple chips. Some configurations combine resources from physical cores into a **logical NeuronCore**, changing the resource view exposed to software.
692
+
693
+ Trainium2 uses NeuronCore version three; Trainium3 uses version four. Their engine capabilities, buffer capacities, and supported numerical formats differ. A tuning assumption copied from another generation may therefore be wrong.
694
+
695
+ Build a hardware fact sheet: chip generation, physical and logical core configuration, external-memory capacity, on-chip limits, and device interconnects.
696
+
697
+ Record the Neuron software version alongside it. A hardware instruction becomes useful only when the selected software path supports it correctly.
698
+
699
+ Imagine moving a carefully tiled kernel between generations. Recheck its resource limits instead of assuming that successful compilation proves optimal mapping.
700
+
701
+ **The takeaway: optimize a concrete configuration, not a product-family name.**
702
+
703
+ Ask: which architectural limits apply here?
704
+
705
+ Next, we trace the Neuron software stack.
706
+
707
+ ## Lecture thirteen A. The Neuron Framework, Compiler, and Runtime
708
+
709
+ Our Trainium fact sheet now needs a software path.
710
+
711
+ **Neuron** is the software stack connecting frameworks and serving engines to Trainium hardware. Its components divide responsibilities rather than acting as one interchangeable package.
712
+
713
+ Framework integration presents model operations to the backend. The compiler produces device-executable work, applying supported transformations and using appropriate kernels. The runtime loads and executes compiled work, manages device interaction, and supports communication.
714
+
715
+ Serving software adds request scheduling and cache management around that execution.
716
+
717
+ Suppose startup is slow because several variants are being compiled. That is different from a warm request being slow because its attention kernel transfers too much data. The same latency number hides different problems.
718
+
719
+ Track model loading, compilation, initialization, and steady-state serving separately. Preserve compatible compilation artifacts where the chosen path supports reuse.
720
+
721
+ **The takeaway: locate the problem before changing compiler or runtime settings.**
722
+
723
+ Ask: am I paying a preparation cost or a repeated execution cost?
724
+
725
+ Next, we distinguish eager and compiled execution.
726
+
727
+ ## Lecture thirteen B. Eager Versus Compiled Execution on Trainium
728
+
729
+ Do not assume that every Trainium program must begin as one fully compiled static graph.
730
+
731
+ **Eager execution** runs operations as the program reaches them. It is convenient for debugging and experimentation. **Compiled execution** transforms supported regions into prepared device work that can be reused.
732
+
733
+ At this series’ documentation snapshot, **TorchNeuron**, the native PyTorch backend for Trainium2 and Trainium3, supports eager execution and PyTorch’s compile interface. That native backend is documented as a public beta.
734
+
735
+ This does not mean every existing model or custom GPU kernel transfers unchanged. Operator coverage, numerical behavior, and performance still require verification.
736
+
737
+ Imagine an experiment with changing control flow. Eager mode can simplify development, while a stable hot region may benefit from compilation. Compare both after separating first-use costs from warm execution.
738
+
739
+ Older Neuron framework paths also exist and have different constraints.
740
+
741
+ **The takeaway: name the execution path before discussing its limitations.**
742
+
743
+ Ask: what does compilation improve for this workload?
744
+
745
+ Next, we examine shape specialization.
746
+
747
+ ## Lecture thirteen C. Shape Bucketing and Compilation Reuse
748
+
749
+ Compiled execution often benefits from predictable shapes. Real requests rarely arrive in identical sizes.
750
+
751
+ **Bucketing** maps variable workloads onto a limited collection of prepared shapes. Padding fills unused positions when necessary; masks preserve the intended computation.
752
+
753
+ Imagine request lengths near five hundred, one thousand, and four thousand tokens. One maximum-size bucket may waste substantial work on shorter requests. More buckets can reduce padding, but increase preparation costs and the number of variants to maintain.
754
+
755
+ The relevant shape may describe a prompt, a decode batch, or a context-length range. Those are different tuning dimensions.
756
+
757
+ In supported Neuron serving paths, decode context-length bucketing can reduce unnecessary attention-cache reads. Compilation caches can reuse compatible artifacts, but changes in configuration or software may invalidate them.
758
+
759
+ Choose buckets from a measured traffic distribution, not round numbers alone.
760
+
761
+ **The takeaway: trade padding waste against variant complexity and compilation cost.**
762
+
763
+ Ask: which bucket receives most real requests?
764
+
765
+ Next, we consider when a custom kernel is justified.
766
+
767
+ ## Lecture fourteen A. When to Use the Neuron Kernel Interface
768
+
769
+ Bucketing changes which work executes. Sometimes the costly operation itself needs a better implementation.
770
+
771
+ **NKI**, Neuron Kernel Interface, lets developers write custom kernels with control over Trainium computation and data movement.
772
+
773
+ Begin with profiling, not enthusiasm for low-level code. Check the existing optimized kernel library and the compiler-generated implementation first. A mature kernel may already solve your problem.
774
+
775
+ Choose one expensive operation with stable, representative shapes. Write a correctness reference, then test normal inputs, edge shapes, and the required numerical tolerances.
776
+
777
+ Imagine a standalone activation between two operations causing an unnecessary external-memory round trip. A custom fused kernel might help, but only if it preserves efficient matrix execution and legal buffer lifetimes.
778
+
779
+ Include integration, compilation, and maintenance costs in the decision. A faster isolated kernel can still lose after surrounding layout conversions.
780
+
781
+ **The takeaway: custom kernels need a measured reason to exist.**
782
+
783
+ Ask: what overhead will this kernel remove?
784
+
785
+ Next, we learn the layout rules that determine whether it can.
786
+
787
+ ## Lecture fourteen B. Partition Dimensions, Layouts, and Tiles
788
+
789
+ A custom Trainium kernel must respect the structure of on-chip tensors.
790
+
791
+ In NKI, SBUF and PSUM tensors have a **partition dimension**, mapping across parallel storage partitions. Their remaining **free dimensions** describe elements within that organization.
792
+
793
+ This is more than a naming convention. Instructions impose layout requirements, and moving values across partitions can require real data movement rather than a free reinterpretation.
794
+
795
+ For common matrix instructions, the reduction dimension—the dimension whose products are summed—must match the required partition layout of the operands.
796
+
797
+ Imagine a tensor loaded in a convenient external-memory order but an inconvenient compute order. A transpose may become necessary before the Tensor Engine can consume it efficiently.
798
+
799
+ A better design may load directly into an appropriate layout or preserve that layout across adjacent operations. Exact limits depend on the instruction and generation.
800
+
801
+ **The takeaway: choose layouts for the whole producer-consumer chain.**
802
+
803
+ Ask: is this reshape metadata-only, or does it physically move values?
804
+
805
+ Next, we pipeline the required transfers.
806
+
807
+ ## Lecture fourteen C. Pipeline Transfers and Trainium Engine Execution
808
+
809
+ Once layouts are legal, the next question is when each operation happens.
810
+
811
+ **DMA**, direct memory access, refers to hardware-managed data transfers. Trainium kernels can arrange transfers and engine work so independent stages overlap when the architecture and compiler allow it.
812
+
813
+ Imagine loading the next activation tile into SBUF while the Tensor Engine computes the current tile. A later vector operation processes a completed result while another matrix product begins.
814
+
815
+ This pipeline needs enough buffer capacity and distinct live regions. Reusing storage too early creates a dependency or corrupts data; keeping everything indefinitely creates capacity pressure.
816
+
817
+ Small fragmented transfers may also be less efficient than larger ones. Combining transfers can help, but must preserve the needed ordering and layout.
818
+
819
+ Inspect the timeline for exposed waits rather than assuming that separate engines guarantee overlap.
820
+
821
+ **The takeaway: schedule the transfers, computation, and buffer lifetimes together.**
822
+
823
+ Ask: which stage sets the steady-state interval between completed tiles?
824
+
825
+ Next, we choose the arithmetic those engines execute.
826
+
827
+ ## Lecture fifteen A. Choose Native Trainium Arithmetic
828
+
829
+ An efficient pipeline still needs a numerical format the selected generation handles well.
830
+
831
+ **BF16**, brain floating point sixteen, is a sixteen-bit floating-point format. Trainium3 also supports matrix operations using **MXFP8** and **MXFP4**: microscaling eight-bit and four-bit floating-point representations.
832
+
833
+ Microscaling associates small groups of values with shared scale information. It is not the same representation as an arbitrary four-bit integer weight file.
834
+
835
+ Supported Trainium3 matrix instructions combine these formats with their scale handling. That capability does not imply that every model backend selects the fastest path, or that every model retains acceptable quality.
836
+
837
+ Imagine importing a compressed checkpoint whose grouping or layout differs from the native kernel’s expectations. Conversion, repacking, or a different execution format may be required.
838
+
839
+ Compare total operation time, memory traffic, and quality after those steps are included.
840
+
841
+ **The takeaway: match checkpoint representation to hardware arithmetic through a verified kernel path.**
842
+
843
+ Ask: what conversions remain inside the repeated execution loop?
844
+
845
+ Next, we inspect that loop with Neuron Explorer.
846
+
847
+ ## Lecture fifteen B. Profile with Neuron Explorer
848
+
849
+ Trainium performance analysis follows GPU analysis logic, using different tools.
850
+
851
+ **Neuron Explorer** provides profiling views for system behavior and device execution. Begin by separating host preparation, device work, transfers, and synchronization.
852
+
853
+ Then inspect the region controlling request completion. Is the Tensor Engine waiting for an input? Are vector operations extending the tail? Is compilation or host scheduling appearing inside the measurement window?
854
+
855
+ Imagine a matrix engine that looks active whenever it runs, but sits idle between short bursts. Increasing its arithmetic throughput may barely change the request. Removing an exposed transfer or dependency could matter more.
856
+
857
+ Conversely, a continuously busy limiting engine suggests a different experiment: improve its work mapping or reduce its required operations.
858
+
859
+ Form one hypothesis and state what trace change should follow from your intervention. Validate again without intrusive profiling.
860
+
861
+ **The takeaway: engine activity becomes useful only when connected to elapsed time.**
862
+
863
+ Ask: which wait can my next change remove?
864
+
865
+ Next, we run a controlled serving experiment.
866
+
867
+ ## Lecture fifteen C. Run a Controlled Trainium Serving Experiment
868
+
869
+ We can now connect Trainium architecture to a complete serving test.
870
+
871
+ Start with a documented model recipe and compatible hardware, Neuron release, and serving-plugin versions. The **vLLM Neuron** plugin provides a supported route; verify its feature matrix for the exact model and execution path.
872
+
873
+ Use our recurring dense-model workload, preserving prompt distribution, output lengths, concurrency, and quality requirements.
874
+
875
+ Separate cold preparation from warm serving. Record the selected compilation path and whether existing artifacts were reused.
876
+
877
+ Change one variable: for example, replace one broad context-length bucket with several narrower buckets. Predict less unnecessary cache traffic, then inspect whether the trace and end-to-end measurements support that prediction.
878
+
879
+ A faster median is insufficient when the slowest supported shapes regress badly or memory usage becomes unacceptable.
880
+
881
+ Only combine successful changes after testing them independently.
882
+
883
+ **The takeaway: a hardware-specific optimization must survive the real request distribution.**
884
+
885
+ Ask: what improved, what regressed, and why?
886
+
887
+ Next, we move above individual devices to optimize the request stream.
888
+
889
+ ## Lecture sixteen A. Continuous Batching and Prefill Scheduling
890
+
891
+ Fast devices can still deliver poor service when requests are scheduled badly.
892
+
893
+ **Continuous batching** updates the active batch as requests finish and new work becomes eligible. Unlike a fixed batch that waits for every sequence, it can reuse available capacity during generation.
894
+
895
+ However, a new request also brings prefill work. A long prompt can compete with ongoing decode steps and stretch users’ token gaps.
896
+
897
+ **Chunked prefill** divides prompt processing into smaller pieces that can be scheduled alongside generation. Smaller chunks may protect streaming latency, while larger chunks may use matrix hardware more efficiently. The tradeoff also affects first-token delay.
898
+
899
+ Imagine a document arriving while many short conversations are generating. The scheduler must decide how much prompt work to admit without violating their latency requirements.
900
+
901
+ Keep the workload distribution fixed while varying the token budget per scheduling step.
902
+
903
+ **The takeaway: optimize admitted work, not just kernel speed.**
904
+
905
+ Ask: which requests pay for the larger batch?
906
+
907
+ Next, we avoid repeated prompt computation.
908
+
909
+ ## Lecture sixteen B. Prefix Reuse and Cache-Aware Request Placement
910
+
911
+ Scheduling decides when prompt work runs. Prefix caching can remove some of that work entirely.
912
+
913
+ Suppose many requests begin with the same two-thousand-token system prompt. After processing it once, a compatible engine can reuse its cached keys and values for later requests with the identical prefix.
914
+
915
+ The match must include the relevant model and configuration, not merely text that looks similar. A shared passage appearing after a different prefix is not automatically reusable.
916
+
917
+ Reuse primarily avoids repeated prefill. Decode still attends to the cached prefix when full attention requires it.
918
+
919
+ In a multi-replica service, routing toward an existing cache may increase hits. But an overloaded cache-rich worker can be slower than an idle worker that recomputes the prefix.
920
+
921
+ Retained cache blocks also compete with active requests for memory. Respect isolation requirements when sharing across users.
922
+
923
+ **The takeaway: value saved computation against queueing and retained memory.**
924
+
925
+ Ask: does a cache hit reduce actual response time?
926
+
927
+ Next, we reduce repeated decode work.
928
+
929
+ ## Lecture sixteen C. Speculative Decoding as a Hardware Tradeoff
930
+
931
+ Prefix reuse accelerates repeated prompts. **Speculative decoding** attacks the sequential cost of generation.
932
+
933
+ A cheaper draft mechanism proposes several tokens. The target model verifies them together, accepting valid proposals and correcting rejected ones according to the algorithm.
934
+
935
+ Proper verification can preserve the target model’s sampling distribution. It does not imply every run produces identical text under every random-number implementation.
936
+
937
+ The hardware opportunity is to replace several small target-model steps with a larger verification operation that reuses weights more effectively.
938
+
939
+ Imagine ordinary decoding costs twenty milliseconds per token. A complete draft-and-verify round costing forty milliseconds and emitting four tokens averages ten milliseconds per token. Those are hypothetical numbers; include drafting, rejection, synchronization, and cache updates.
940
+
941
+ A high acceptance rate alone does not prove a speedup. A saturated service may lose throughput to extra draft and verification work.
942
+
943
+ **The takeaway: measure useful emitted tokens per complete round.**
944
+
945
+ Ask: does speculation improve my latency-constrained workload?
946
+
947
+ Next, we distribute work across devices.
948
+
949
+ ## Lecture seventeen A. Tensor Parallelism and Communication
950
+
951
+ When one device is insufficient, we can distribute a layer itself.
952
+
953
+ **Tensor parallelism** partitions weight tensors and the corresponding computation across devices. The exact partition determines which activations or partial results must be communicated.
954
+
955
+ An **all-reduce** combines contributions, such as partial sums, and makes the combined result available to every participant. Other partitions require different collective operations.
956
+
957
+ Imagine a layer taking eight milliseconds on one device. Four devices might ideally reduce its local computation to two milliseconds. But if exposed communication adds five milliseconds, total time becomes seven, not two.
958
+
959
+ Some communication can overlap computation; some sits directly on the dependency path. Include the exposed portion rather than blindly adding every transfer duration.
960
+
961
+ Partitioning can also create smaller, less efficient local matrix shapes. Attention-cache placement depends on the model and implementation.
962
+
963
+ **The takeaway: dividing arithmetic does not divide latency automatically.**
964
+
965
+ Ask: how much computation is saved after communication and shape penalties?
966
+
967
+ Next, we compare splitting layers with running independent replicas.
968
+
969
+ ## Lecture seventeen B. Pipeline Parallelism Versus Independent Replicas
970
+
971
+ Tensor parallelism splits work inside layers. **Pipeline parallelism** places different groups of layers on different devices.
972
+
973
+ An activation passes through those stages in order. Different requests or microbatches can occupy different stages simultaneously. A **microbatch** is a smaller group of examples scheduled as a unit.
974
+
975
+ With insufficient concurrent work, stages wait idle. These gaps are called pipeline bubbles. One token cannot traverse dependent stages simultaneously because more devices exist.
976
+
977
+ By contrast, **independent replicas** each hold a model and process separate requests. They avoid inter-device communication inside a request, but duplicate weights and require enough memory per replica.
978
+
979
+ Imagine a model that fits on one device and many unrelated users. Replication is a useful baseline. If the model cannot fit, partitioning may become necessary even before considering speed.
980
+
981
+ Choose based on capacity, latency, throughput, and the arrival pattern.
982
+
983
+ **The takeaway: model capacity and request parallelism are different problems.**
984
+
985
+ Ask: am I distributing one request or many?
986
+
987
+ Next, we include interconnect topology.
988
+
989
+ ## Lecture seventeen C. Make Parallelism Fit the Interconnect
990
+
991
+ A parallelism strategy is incomplete until we place its workers on real connections.
992
+
993
+ **Topology** describes which devices connect directly, the bandwidth of those links, and the paths communication must follow. Link latency matters as well as bandwidth, especially for small repeated collectives.
994
+
995
+ Imagine two servers, each with four tightly connected accelerators, joined by a slower network. One candidate uses tensor parallelism within each server and pipeline stages across servers. Another runs an independent replica per server.
996
+
997
+ Neither is automatically best. Compare model fit, local matrix shapes, communication volume, pipeline bubbles, and concurrency.
998
+
999
+ On Trainium, inspect the relevant NeuronLink and network arrangement. On GPUs, inspect the actual accelerator and network fabric rather than assuming every pair communicates equally well.
1000
+
1001
+ Adding devices can improve aggregate capacity while worsening an individual request’s latency.
1002
+
1003
+ **The takeaway: map frequent communication onto the links that can support it.**
1004
+
1005
+ Ask: which slow link lies on the critical path?
1006
+
1007
+ Next, we examine how training changes the optimization budget.
1008
+
1009
+ ## Lecture eighteen A. Training and Fine-Tuning Need a Different Memory Budget
1010
+
1011
+ So far, we have focused on inference. Training adds state that changes the optimization problem.
1012
+
1013
+ Beyond weights and working tensors, we need gradients, optimizer state, and activations retained for backward computation. A full-sequence training step does not use the same growing inference-cache pattern as autoregressive serving.
1014
+
1015
+ Consider an illustrative layout with two bytes of weights, two bytes of gradients, and eight bytes of optimizer state per parameter. That is twelve bytes before activations: ninety-six decimal gigabytes for eight billion parameters.
1016
+
1017
+ Some implementations also retain higher-precision master weights. Actual totals depend on the optimizer, precision policy, and sharding.
1018
+
1019
+ **LoRA**, low-rank adaptation, trains small added matrices rather than all base weights. It reduces trainable state, but does not eliminate activation or base-model execution costs.
1020
+
1021
+ Measure training tokens per second and time to an acceptable result, not inference streaming latency.
1022
+
1023
+ **The takeaway: rebuild the budget when the task changes.**
1024
+
1025
+ Ask: which state actually consumes peak memory?
1026
+
1027
+ Next, we trade recomputation for activation storage.
1028
+
1029
+ ## Lecture eighteen B. Activation Checkpointing and Recomputation
1030
+
1031
+ Training activations can dominate memory even when model state is carefully managed.
1032
+
1033
+ **Activation checkpointing** retains selected boundary values instead of every intermediate needed by the backward pass. Missing intermediates are recomputed when backward computation reaches that region.
1034
+
1035
+ It trades additional arithmetic for lower retained memory. This differs from saving a training checkpoint to disk for recovery.
1036
+
1037
+ Imagine memory limits us to a very small microbatch. Checkpointing frees enough space for a larger one. Each step may perform more arithmetic, yet useful tokens per second could improve through better hardware utilization or fewer accumulation steps.
1038
+
1039
+ Alternatively, recomputation may simply slow an already efficient workload. Compare at the same effective batch and training-quality target.
1040
+
1041
+ Selective policies can preserve expensive intermediates while recomputing cheaper ones. Correctness also requires consistent behavior for randomness and stateful operations.
1042
+
1043
+ **The takeaway: evaluate the complete memory-throughput tradeoff, not recomputation cost alone.**
1044
+
1045
+ Ask: what useful work becomes possible with the freed memory?
1046
+
1047
+ Next, we distribute training state across devices.
1048
+
1049
+ ## Lecture eighteen C. Shard Training State with FSDP
1050
+
1051
+ Checkpointing reduces retained activations. Another approach distributes model state itself.
1052
+
1053
+ **FSDP**, Fully Sharded Data Parallel, partitions parameters, gradients, and optimizer state across participating workers rather than keeping every copy everywhere.
1054
+
1055
+ Before a layer needs full parameters, an **all-gather** collects the required pieces. After backward computation, a **reduce-scatter** combines gradient contributions and distributes the resulting shards.
1056
+
1057
+ The exact gathering and resharding schedule depends on configuration. Each worker still needs activations and temporary space for the computation it performs.
1058
+
1059
+ Consequently, using eight workers does not guarantee that peak memory becomes exactly one-eighth of the original total. Temporarily gathered parameters and communication buffers also matter.
1060
+
1061
+ Imagine a configuration that finally fits but repeatedly waits for parameter gathering. Adjusting grouping or overlap might improve it, while a slower network could erase the benefit.
1062
+
1063
+ **The takeaway: state sharding exchanges replication for communication and scheduling complexity.**
1064
+
1065
+ Ask: what remains replicated, and which collectives are exposed?
1066
+
1067
+ Next, we revisit inference with mixture-of-experts models.
1068
+
1069
+ ## Lecture nineteen A. Mixture-of-Experts Models and Uneven Work
1070
+
1071
+ Our dense-model examples use roughly the same weight structure for every token. **MoE**, mixture of experts, changes that pattern.
1072
+
1073
+ A router selects a subset of expert networks for each token. Fewer active parameters can reduce arithmetic, but performance depends on how routed work is distributed.
1074
+
1075
+ Imagine eight experts and sixteen tokens, with two experts selected per token. Thirty-two assignments are produced, but they need not divide evenly. Some experts receive tiny batches; others become bottlenecks.
1076
+
1077
+ With **expert parallelism**, different devices own different experts. An **all-to-all** exchange can move each token’s activations to its selected experts and return results afterward.
1078
+
1079
+ Now small matrix shapes, routing imbalance, and communication can dominate. The full expert weights still need storage even when only a subset is active for one token.
1080
+
1081
+ Evaluate routing distributions, not just average active parameter counts.
1082
+
1083
+ **The takeaway: sparse arithmetic does not guarantee efficient execution.**
1084
+
1085
+ Ask: which expert or communication stage delays the batch?
1086
+
1087
+ Next, we separate prefill and decode resources.
1088
+
1089
+ ## Lecture nineteen B. Separate Prefill and Decode—or Keep Them Together
1090
+
1091
+ Prefill and decode favor different execution conditions. **Disaggregated serving** assigns them to separate resources rather than making each worker handle both phases.
1092
+
1093
+ This can reduce interference and allow independent scheduling or hardware choices. But the decode worker needs the key-value state produced during prefill.
1094
+
1095
+ Imagine transferring one decimal gigabyte over an effective fifty-gigabyte-per-second connection. Payload transfer alone takes twenty milliseconds, before coordination, conversion, contention, or additional copying.
1096
+
1097
+ Any latency benefit must survive those costs. Throughput also depends on balancing the two resource pools; an underloaded pool can waste expensive capacity.
1098
+
1099
+ Different device types may require compatible cache representations or extra transformation. Moving state is not automatically equivalent to copying a file.
1100
+
1101
+ Compare against a well-tuned colocated baseline using the same workload, quality, and total resource budget. Also test traffic shifts that change the prefill-to-decode ratio.
1102
+
1103
+ **The takeaway: phase specialization needs an end-to-end break-even calculation.**
1104
+
1105
+ Ask: what gain exceeds the transfer and coordination cost?
1106
+
1107
+ Next, we compare whole hardware choices.
1108
+
1109
+ ## Lecture nineteen C. Choose Hardware Using Matched Requirements
1110
+
1111
+ We can compare CPUs, GPUs, and Trainium without reducing the decision to peak arithmetic.
1112
+
1113
+ Hold the model task, acceptable quality, prompt distribution, output lengths, and latency requirements constant. Each platform may need a different implementation to meet that contract.
1114
+
1115
+ Then measure **goodput**: useful service output satisfying the defined constraints. State precisely how you count failed or late requests.
1116
+
1117
+ For a hypothetical service costing ten dollars per hour and delivering one thousand qualifying output tokens per second, one million output tokens cost about two dollars and seventy-eight cents. The calculation divides hourly cost by qualifying hourly output.
1118
+
1119
+ Include host machines, networking, idle provisioned capacity, and relevant storage costs. Compilation and engineering effort can matter over a deployment’s lifetime.
1120
+
1121
+ For energy, divide measured system energy by useful tokens; a chip’s rated power is not that measurement.
1122
+
1123
+ **The takeaway: compare complete services at matched requirements.**
1124
+
1125
+ Ask: which platform meets the contract most efficiently?
1126
+
1127
+ Next, we apply the method to three final diagnosis exercises.
1128
+
1129
+ ## Lecture twenty A. CPU Capstone: More Cores, Worse Performance
1130
+
1131
+ Here is a hypothetical CPU case using our recurring dense model.
1132
+
1133
+ Sixteen threads generate twenty-eight tokens per second. Thirty-two generate twenty-four. The larger configuration crosses sockets, and profiling shows increased remote-memory reads. Precision, prompt length, and output length are unchanged.
1134
+
1135
+ Do not conclude that thirty-two threads are always bad. Our first hypothesis is that placement is introducing expensive traffic.
1136
+
1137
+ Keep the thread count fixed and test a local or correctly partitioned allocation policy. Compare remote traffic, achieved bandwidth, and generation rate. Preserve enough capacity to avoid paging.
1138
+
1139
+ If locality improves but throughput does not, investigate bandwidth saturation and synchronization next. That outcome weakens the original explanation rather than proving the experiment failed.
1140
+
1141
+ Finally, repeat the chosen configuration for prefill and through the real serving path. A decode-only victory may not satisfy the complete workload.
1142
+
1143
+ **The takeaway: change one suspected cause and demand matching evidence.**
1144
+
1145
+ Ask: did both the mechanism and the user metric improve?
1146
+
1147
+ Next, we diagnose a busy GPU.
1148
+
1149
+ ## Lecture twenty B. GPU Capstone: High Utilization, Poor Response Times
1150
+
1151
+ Consider a hypothetical GPU service reporting ninety-five percent utilization. Users still experience long pauses while answers stream.
1152
+
1153
+ Its timeline shows large prefill operations arriving between decode steps. The device is busy, but busy on work that delays ongoing responses.
1154
+
1155
+ Our hypothesis is scheduling interference, not an inefficient matrix kernel. Capturing the same workload in a graph would not automatically fix that allocation of time.
1156
+
1157
+ Test a smaller prefill chunk budget while keeping the request-arrival trace, model, precision, and hardware unchanged. Predict shorter interruptions between decode steps, possibly at the expense of prompt-processing efficiency or first-token delay.
1158
+
1159
+ Measure tail token gaps, first-token latency, and qualifying throughput together. Reject the change if it merely transfers an unacceptable delay from one group of users to another.
1160
+
1161
+ Then test whether the improvement persists under different realistic prompt mixtures.
1162
+
1163
+ **The takeaway: utilization describes activity, not whether activity serves the right objective.**
1164
+
1165
+ Ask: whose latency improved, and who paid for it?
1166
+
1167
+ Next, we diagnose Trainium.
1168
+
1169
+ ## Lecture twenty C. Trainium Capstone: Fast Arithmetic, Slow Serving
1170
+
1171
+ Our hypothetical trace shows efficient Trainium matrix operations, yet disappointing decode latency.
1172
+
1173
+ Most requests have short contexts, but the serving configuration uses one broad context-length bucket. Profiling shows attention-cache transfers over a much larger prepared region than most requests need.
1174
+
1175
+ Our hypothesis is excess bucket-related traffic, not insufficient matrix throughput.
1176
+
1177
+ Test a small set of context buckets matched to the observed distribution. Keep model quality, active concurrency, and the arrival trace unchanged. Separate new compilation costs from warm execution.
1178
+
1179
+ Look for reduced cache traffic and shorter exposed waits. Then check long-context requests, memory consumption, and first-token latency. If transfers shrink but request time barely changes, another dependency has become dominant.
1180
+
1181
+ That is the complete optimization loop: specify the workload, measure, form a hypothesis, intervene, and validate.
1182
+
1183
+ **The takeaway: an optimization succeeds only under stated conditions, with evidence explaining why.**
1184
+
1185
+ Ask: what is the new bottleneck?
1186
+
1187
+ Across CPUs, GPUs, and Trainium, that question—not a favorite tuning flag—is the skill to retain.