arjun10g commited on
Commit
0419383
·
verified ·
1 Parent(s): 7fa5a1b

Sync 1 audio file(s) and transcripts

Browse files
audio/llm-memory-hierarchy.mp3 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:461c88f9b09e0e1b8e4b2958e586d97ba72df9ecb28b66eef210986595de7e1b
3
+ size 24748142
lectures/llm-memory-hierarchy.md ADDED
@@ -0,0 +1,902 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Memory Hierarchy for LLMs
2
+ *A narration-first lecture, roughly thirty minutes spoken.*
3
+
4
+ ## Opening: why LLM performance is really about moving data
5
+
6
+ When people first learn about GPUs, they usually focus on computation. They hear about Tensor Cores, teraFLOPS, thousands of threads, and huge matrix multiplications.
7
+
8
+ But a GPU can only compute on data that has arrived.
9
+
10
+ A Tensor Core may be capable of an enormous number of operations per second, but if the next weights are still traveling from GPU memory, that Tensor Core can sit partially idle.
11
+
12
+ That gives us the central idea for this entire lecture:
13
+
14
+ **LLM performance is a data-movement problem as much as it is a compute problem.**
15
+
16
+ We are going to build one mental model connecting VRAM, HBM, cache, shared memory, registers, warps, Tensor Cores, tiling, quantization, attention, KV caches, and expert prefetching. By the end, phrases like "memory-bound" or "prefetch into cache" should correspond to a concrete hardware picture.
17
+
18
+ ---
19
+
20
+ ## Start with the complete memory journey
21
+
22
+ Imagine one weight from a transformer.
23
+
24
+ Before the model is loaded, that weight may be on an SSD.
25
+
26
+ When the program loads the model, data may pass through ordinary CPU system memory, or DRAM.
27
+
28
+ Then the model is transferred to GPU memory across an interconnect such as PCI Express.
29
+
30
+ Inside the GPU, the large main memory is what we commonly call VRAM. On an NVIDIA H one hundred SXM, that VRAM is HBM three, meaning High Bandwidth Memory.
31
+
32
+ During inference, a weight needed by a kernel is fetched through the GPU memory system. It may be served from the GPU's L two cache if it is already there, or from HBM if it is not.
33
+
34
+ Once data reaches a streaming multiprocessor, or SM, the kernel can make use of much smaller and faster on-chip storage.
35
+
36
+ That includes L one cache, explicitly managed shared memory, and registers belonging to individual threads.
37
+
38
+ Finally, the compute units execute instructions using those values.
39
+
40
+ So our simplified picture is:
41
+
42
+ SSD, then CPU RAM, then GPU HBM, then on-chip cache and shared storage, then registers, then arithmetic units.
43
+
44
+ The closer we get to the arithmetic units, the memory generally becomes faster but dramatically smaller.
45
+
46
+ That tradeoff is the reason the hierarchy exists.
47
+
48
+ ---
49
+
50
+ ## VRAM, HBM, DRAM, and SRAM
51
+
52
+ Let us clean up some terminology.
53
+
54
+ VRAM is a broad term. It simply means the main memory attached to the GPU.
55
+
56
+ On many consumer GPUs, the VRAM is built using GDDR memory.
57
+
58
+ On high-end accelerator GPUs such as the H one hundred SXM, the main GPU memory is HBM three.
59
+
60
+ HBM is still a form of dynamic random-access memory, or DRAM. It is designed to provide very high bandwidth by placing multiple memory stacks close to the GPU and using an extremely wide interface.
61
+
62
+ The H one hundred SXM, for example, has eighty gigabytes of HBM three and memory bandwidth measured in multiple terabytes per second.
63
+
64
+ That sounds unbelievably fast, and it is.
65
+
66
+ But from the perspective of a Tensor Core doing arithmetic on-chip, HBM is still far away.
67
+
68
+ Caches and shared memory are implemented using much faster on-chip memory structures, commonly described in terms of SRAM.
69
+
70
+ SRAM is fast, but physically expensive. It consumes much more chip area per stored bit than DRAM.
71
+
72
+ That is why we cannot simply put eighty gigabytes of SRAM beside the Tensor Cores.
73
+
74
+ Instead, we use a hierarchy.
75
+
76
+ Large DRAM holds the full model.
77
+
78
+ Small SRAM-like structures hold the tiny portion of the model that is useful right now.
79
+
80
+ The optimization objective is simple:
81
+
82
+ **Move useful data inward and reuse it before fetching more.**
83
+
84
+ ---
85
+
86
+ ## The GPU is made of streaming multiprocessors
87
+
88
+ Now let us move from memory to execution.
89
+
90
+ A modern NVIDIA GPU contains many streaming multiprocessors, abbreviated SMs.
91
+
92
+ Think of each SM as a local execution engine.
93
+
94
+ When you launch a GPU kernel, the total work is divided into thread blocks. The GPU schedules those thread blocks onto SMs.
95
+
96
+ Inside a thread block are many threads.
97
+
98
+ And on NVIDIA GPUs, threads are grouped into sets of thirty-two called warps.
99
+
100
+ A warp is one of the fundamental execution units you should picture when thinking about GPU software.
101
+
102
+ The thirty-two threads in a warp execute the same kernel instruction stream under NVIDIA's SIMT model, meaning single instruction, multiple threads.
103
+
104
+ Each thread has its own data and its own state.
105
+
106
+ This structure is ideal for matrix operations. Instead of asking one CPU-like thread to compute a giant multiplication, we divide the matrices into tiles. Different blocks handle different output tiles, warps cooperate inside the blocks, and individual threads contribute to smaller fragments.
107
+
108
+ So picture the execution hierarchy as GPU, then SM, then thread block, then warp, then thread. Those threads ultimately cooperate to feed the arithmetic units.
109
+
110
+ ---
111
+
112
+ ## Registers — each thread's private working area
113
+
114
+ The closest general-purpose storage to a thread is its registers.
115
+
116
+ Imagine every thread has a tiny personal workbench.
117
+
118
+ A thread can keep loop variables, addresses, intermediate values, fragments of input data, and partial sums in registers.
119
+
120
+ For LLM matrix multiplication, partial sums are extremely important.
121
+
122
+ Suppose we are computing part of an output matrix.
123
+
124
+ We do not want to perform one multiplication, write the partial answer all the way back to HBM, load it again, add another multiplication, and repeat.
125
+
126
+ That would create enormous memory traffic.
127
+
128
+ Instead, the kernel keeps partial accumulations close to the compute units while many multiply-and-accumulate operations happen.
129
+
130
+ Registers are ideal for this because access is extremely fast.
131
+
132
+ But there is a tradeoff.
133
+
134
+ The register file on an SM is finite.
135
+
136
+ If each thread demands too many registers, fewer warps can live on that SM at the same time.
137
+
138
+ This is called register pressure.
139
+
140
+ And if the compiler cannot keep everything in registers, some values may spill into what CUDA calls local memory.
141
+
142
+ Despite the word local, spilled local memory is not another tiny register-like store. It is backed by device memory and uses the cache hierarchy, so heavy spilling can be expensive.
143
+
144
+ So the lesson is:
145
+
146
+ **Registers are extremely valuable, but they are a limited resource that must be budgeted.**
147
+
148
+ ---
149
+
150
+ ## Why we want many warps: latency hiding
151
+
152
+ Suppose one warp requests data and has to wait.
153
+
154
+ A CPU might spend substantial effort trying to make one thread execute as quickly as possible.
155
+
156
+ A GPU uses a different strategy.
157
+
158
+ It keeps many warps available.
159
+
160
+ If warp A is waiting on memory, the SM can issue instructions from warp B.
161
+
162
+ Then perhaps warp C.
163
+
164
+ Then warp D.
165
+
166
+ By the time the scheduler returns to warp A, its data may have arrived.
167
+
168
+ This is called latency hiding.
169
+
170
+ It explains why occupancy matters.
171
+
172
+ Occupancy roughly describes how many warps are resident and available on an SM relative to the hardware limit.
173
+
174
+ However, maximum occupancy is not automatically maximum performance.
175
+
176
+ A high-performance matrix multiplication may intentionally use many registers for accumulator fragments and a substantial amount of shared memory for tiles.
177
+
178
+ That can reduce the number of blocks or warps that fit simultaneously.
179
+
180
+ But the kernel may still run faster because each active warp performs much more efficient work.
181
+
182
+ So do not memorize:
183
+
184
+ "High occupancy equals good."
185
+
186
+ Memorize:
187
+
188
+ **We want enough parallel work to hide latency, but we also want enough registers and shared memory to maximize reuse.**
189
+
190
+ GPU kernel optimization is often about finding that balance.
191
+
192
+ ---
193
+
194
+ ## Shared memory — the block's cooperative scratchpad
195
+
196
+ Registers are private to individual threads.
197
+
198
+ Shared memory is available to the threads of a block.
199
+
200
+ Think of registers as personal notebooks and shared memory as a whiteboard used by the entire team.
201
+
202
+ Suppose a block of threads needs the same tile of a weight matrix.
203
+
204
+ A bad design might repeatedly fetch overlapping data from farther out in the memory hierarchy.
205
+
206
+ A better design loads the tile once into shared memory and allows many threads to reuse it.
207
+
208
+ That is one of the central ideas behind tiled matrix multiplication.
209
+
210
+ There is an important nuance here.
211
+
212
+ Earlier, we can describe the hierarchy as HBM, then L two, then shared memory, then registers.
213
+
214
+ That is useful conceptually, but shared memory is not simply another automatic cache.
215
+
216
+ L two and L one are hardware-managed caches.
217
+
218
+ Shared memory is explicitly managed by the kernel.
219
+
220
+ The program deliberately allocates it, deliberately loads values into it, and deliberately decides how threads will reuse those values.
221
+
222
+ On H one hundred, L one cache, texture cache, and shared memory use a combined on-chip resource. The exact partition can be configured, with more than two hundred kilobytes per SM available for shared memory in supported configurations.
223
+
224
+ So shared memory gives the programmer direct control over a small, fast part of the memory system.
225
+
226
+ That control is one of the main tools used by optimized LLM kernels.
227
+
228
+ ---
229
+
230
+ ## Coalescing and bank conflicts
231
+
232
+ Fast memory is not enough.
233
+
234
+ You must also access it correctly.
235
+
236
+ When the thirty-two threads of a warp load from global memory, the hardware tries to combine their requests into a small number of memory transactions.
237
+
238
+ This is called coalescing.
239
+
240
+ If neighboring threads request nearby addresses, the GPU can usually make efficient use of each memory transaction.
241
+
242
+ If the threads request scattered addresses, the hardware may need many more transactions.
243
+
244
+ That wastes bandwidth.
245
+
246
+ Now move into shared memory.
247
+
248
+ Shared memory is divided into banks so multiple accesses can happen in parallel.
249
+
250
+ If different threads access addresses that map nicely across those banks, the accesses are efficient.
251
+
252
+ But if many threads access different addresses that map to the same bank, the requests may become serialized.
253
+
254
+ That is called a bank conflict.
255
+
256
+ So when optimizing an LLM kernel, there are two different questions.
257
+
258
+ First:
259
+
260
+ Did I move the data into fast memory?
261
+
262
+ Second:
263
+
264
+ Did I arrange the data so the threads can access it efficiently?
265
+
266
+ This is why memory layout matters so much.
267
+
268
+ Two kernels can implement the exact same mathematical matrix multiplication and have radically different performance because one produces coalesced global loads and conflict-free shared-memory access while the other does not.
269
+
270
+ ---
271
+
272
+ ## Tensor Cores — the arithmetic engines
273
+
274
+ Now we reach the Tensor Cores.
275
+
276
+ Tensor Cores are specialized hardware units designed to perform matrix multiply-and-accumulate operations at extremely high throughput.
277
+
278
+ Conceptually, the operation is:
279
+
280
+ C becomes A multiplied by B, plus C.
281
+
282
+ A large LLM matrix multiplication is decomposed into many smaller matrix operations that ultimately feed these units.
283
+
284
+ Modern Tensor Cores support multiple numerical formats. Hopper-generation GPUs support formats especially useful for transformers, including BF sixteen, FP sixteen, and FP eight paths.
285
+
286
+ But Tensor Cores do not magically solve memory problems.
287
+
288
+ They make the arithmetic side extremely fast.
289
+
290
+ That can actually make memory limitations more important.
291
+
292
+ Imagine a hypothetical kernel where moving the data takes ten units of time and computing on it takes two units.
293
+
294
+ Now suppose we double Tensor Core speed.
295
+
296
+ The compute portion falls from two units to one.
297
+
298
+ But the ten units spent moving data remain.
299
+
300
+ Total time only changes from twelve units to eleven.
301
+
302
+ The workload barely speeds up.
303
+
304
+ This is the essence of a memory-bound operation.
305
+
306
+ So when someone quotes the peak Tensor Core performance of a GPU, remember that peak compute only matters if the rest of the system can feed it.
307
+
308
+ ---
309
+
310
+ ## Tiling: how a GEMM uses the hierarchy
311
+
312
+ Consider a transformer operation where activation matrix X is multiplied by weight matrix W.
313
+
314
+ The complete matrices are far too large to fit in registers or shared memory.
315
+
316
+ So the kernel divides them into tiles.
317
+
318
+ A thread block takes responsibility for a tile of the output.
319
+
320
+ To compute that tile, it needs corresponding pieces of X and W.
321
+
322
+ Those pieces are loaded from global GPU memory.
323
+
324
+ If the requested data is already in L two cache, some requests can be served there instead of going all the way to HBM.
325
+
326
+ The kernel then stages reusable pieces into on-chip storage, commonly shared memory.
327
+
328
+ Warps consume smaller fragments from those tiles.
329
+
330
+ Tensor Core instructions perform multiply-and-accumulate operations.
331
+
332
+ Partial output values stay close to the arithmetic units, often in registers or architecture-specific accumulator structures.
333
+
334
+ Then the kernel moves along the reduction dimension.
335
+
336
+ Load the next tile.
337
+
338
+ Multiply.
339
+
340
+ Accumulate.
341
+
342
+ Load the next tile.
343
+
344
+ Multiply.
345
+
346
+ Accumulate.
347
+
348
+ Eventually, the final output tile is written back to global memory.
349
+
350
+ We cannot eliminate memory movement. The goal is to make every expensive load support as much useful arithmetic as possible. Tiling is therefore fundamentally a data-reuse strategy.
351
+
352
+ ---
353
+
354
+ ## Pipeline the loads instead of waiting
355
+
356
+ A naive kernel might perform these steps:
357
+
358
+ Load a tile.
359
+
360
+ Wait for it.
361
+
362
+ Compute.
363
+
364
+ Load the next tile.
365
+
366
+ Wait again.
367
+
368
+ Compute again.
369
+
370
+ That creates idle gaps.
371
+
372
+ A more sophisticated kernel overlaps movement with computation.
373
+
374
+ While Tensor Cores are operating on the current tile, the next tile begins moving toward the place where it will be needed.
375
+
376
+ This idea is often implemented using pipelining or double buffering.
377
+
378
+ One buffer is actively being consumed.
379
+
380
+ Another is being filled with future data.
381
+
382
+ When the current computation finishes, the next data is already available or much closer to ready.
383
+
384
+ Hopper GPUs also contain mechanisms such as the Tensor Memory Accelerator, or TMA, designed to help transfer multidimensional data between global and shared memory asynchronously.
385
+
386
+ The general principle matters more than the particular instruction:
387
+
388
+ **Do not merely reduce data movement. Hide the unavoidable movement behind useful work whenever possible.**
389
+
390
+ That principle will become very important when we discuss mixture-of-experts prefetching.
391
+
392
+ ---
393
+
394
+ ## Prefill versus decode
395
+
396
+ This is one of the most important distinctions in LLM inference.
397
+
398
+ During **prefill**, the model processes the prompt.
399
+
400
+ If the prompt contains hundreds or thousands of tokens, the GPU can process many token activations together.
401
+
402
+ That creates large matrix multiplications.
403
+
404
+ A weight loaded from HBM can contribute to the computation of many tokens.
405
+
406
+ So each byte of weight data supports a large amount of arithmetic.
407
+
408
+ We call that high arithmetic intensity.
409
+
410
+ During **decode**, the model usually generates one new token at a time for each active sequence.
411
+
412
+ The weight matrices remain enormous.
413
+
414
+ But now the amount of activation work for one sequence is much smaller.
415
+
416
+ The GPU may stream a huge quantity of weights through the memory system to compute just one new token.
417
+
418
+ There is much less weight reuse per sequence.
419
+
420
+ That makes decode much more likely to become memory-bandwidth bound.
421
+
422
+ This is why the same GPU can behave very differently during prefill and decode.
423
+
424
+ Prefill often has large GEMMs that use Tensor Cores efficiently.
425
+
426
+ Single-sequence decode often has much skinnier operations and a much stronger dependence on memory bandwidth.
427
+
428
+ Whenever you hear that an optimization improves "LLM inference," ask:
429
+
430
+ **Does it improve prefill, decode, or both?**
431
+
432
+ That question prevents a lot of misleading conclusions.
433
+
434
+ ---
435
+
436
+ ## Arithmetic intensity and the roofline idea
437
+
438
+ There is a useful concept called arithmetic intensity.
439
+
440
+ The definition is simple:
441
+
442
+ **Arithmetic intensity is the amount of useful computation performed per byte of data moved.**
443
+
444
+ If you load a large weight tensor and use each value only once, arithmetic intensity is low.
445
+
446
+ If you load that same weight and reuse it across many tokens, arithmetic intensity rises.
447
+
448
+ This connects to the roofline model.
449
+
450
+ Imagine two ceilings on performance.
451
+
452
+ One ceiling comes from compute throughput.
453
+
454
+ The other comes from memory bandwidth.
455
+
456
+ At low arithmetic intensity, memory bandwidth usually limits performance first.
457
+
458
+ At high arithmetic intensity, the kernel may eventually become compute-bound.
459
+
460
+ This gives us a clean explanation for batching.
461
+
462
+ Suppose one decode request generates one token.
463
+
464
+ The model weights are loaded for that work.
465
+
466
+ Now suppose we batch many decode requests together.
467
+
468
+ The same weight tile can contribute to multiple tokens.
469
+
470
+ We perform more arithmetic for roughly the same weight load.
471
+
472
+ Arithmetic intensity rises.
473
+
474
+ Tensor Core utilization can improve.
475
+
476
+ So batching is not merely a serving-system trick.
477
+
478
+ It changes the hardware economics of the matrix multiplication.
479
+
480
+ ---
481
+
482
+ ## Why quantization can speed up decode
483
+
484
+ Now quantization becomes intuitive.
485
+
486
+ Suppose model weights are stored using sixteen bits per value.
487
+
488
+ If we represent them using four bits, the raw weight storage becomes roughly one quarter as large, ignoring scales, metadata, padding, and other overhead.
489
+
490
+ If decode is limited by moving weight bytes from HBM, then reducing the number of bits that must be transported creates a direct opportunity for speedup.
491
+
492
+ But there is a catch.
493
+
494
+ The compute kernel has to consume the compact representation efficiently.
495
+
496
+ Imagine a bad one-bit or four-bit implementation.
497
+
498
+ The packed weights are loaded.
499
+
500
+ They are unpacked.
501
+
502
+ They are converted to a wider representation.
503
+
504
+ The expanded weights are written into a large temporary buffer in HBM.
505
+
506
+ Then an ordinary matrix multiplication reads them again.
507
+
508
+ The model may be small on disk and small when first loaded, but the execution path has recreated a large memory-traffic problem.
509
+
510
+ A better implementation keeps the weights compressed for as long as possible.
511
+
512
+ Small tiles are unpacked close to the computation.
513
+
514
+ Scaling and conversion are fused into the kernel.
515
+
516
+ Expanded values exist briefly in registers or shared memory instead of being materialized as a giant global tensor.
517
+
518
+ This is why quantization formats and kernel design cannot be separated.
519
+
520
+ **Compression only produces speed when it reduces bytes moved along the actual execution path.**
521
+
522
+ ---
523
+
524
+ ## The KV cache is another bandwidth problem
525
+
526
+ Weights are only part of the memory story.
527
+
528
+ Autoregressive attention maintains a key-value cache, usually called the KV cache.
529
+
530
+ For previous tokens, the model stores key and value vectors that future tokens may attend to.
531
+
532
+ As the context becomes longer, the cache grows.
533
+
534
+ So there are two separate issues.
535
+
536
+ The first is capacity.
537
+
538
+ How much KV data can fit in GPU memory?
539
+
540
+ The second is bandwidth.
541
+
542
+ How much historical KV data must be read when computing the next token?
543
+
544
+ Grouped-query attention helps by letting several query heads share a smaller number of key and value heads.
545
+
546
+ KV-cache quantization can reduce the number of bytes stored and transferred.
547
+
548
+ Paged-attention systems organize cache memory into manageable blocks so that serving many variable-length sequences does not require one enormous contiguous region for every request.
549
+
550
+ Decode has several memory streams at once: weights, KV data, activations, and temporaries. Removing one bottleneck can expose another, which is why profiling matters.
551
+
552
+ ---
553
+
554
+ ## FlashAttention: same math, smarter movement
555
+
556
+ FlashAttention is one of the clearest examples of memory-aware algorithm design.
557
+
558
+ Standard attention conceptually computes a matrix of similarities between queries and keys.
559
+
560
+ For long sequences, that attention matrix can become enormous.
561
+
562
+ A naive implementation may write large intermediate matrices to HBM and later read them back.
563
+
564
+ The mathematics is correct, but the data movement is expensive.
565
+
566
+ FlashAttention reorganizes the calculation into tiles.
567
+
568
+ Blocks of queries, keys, and values are processed using fast on-chip memory.
569
+
570
+ An online softmax procedure allows the algorithm to produce exact attention without storing the entire attention-score matrix in HBM.
571
+
572
+ The important point is that FlashAttention does not primarily win by changing the definition of attention.
573
+
574
+ It wins by changing how the computation interacts with the memory hierarchy.
575
+
576
+ The original work explicitly describes this as IO-aware attention.
577
+
578
+ This teaches a general optimization lesson:
579
+
580
+ **Sometimes the biggest speedup comes from keeping the same mathematics but changing where intermediate values live.**
581
+
582
+ Whenever you see a huge intermediate tensor, ask:
583
+
584
+ Does this really need to be written to HBM?
585
+
586
+ Or can it be consumed while it is still on-chip?
587
+
588
+ ---
589
+
590
+ ## Kernel fusion follows the same principle
591
+
592
+ Suppose operation A creates an intermediate tensor.
593
+
594
+ Operation B immediately consumes it.
595
+
596
+ A naive execution might run operation A, write the complete intermediate tensor to HBM, launch operation B, and then read the tensor back.
597
+
598
+ That round trip can be expensive.
599
+
600
+ If the operations can be fused, intermediate values may stay in registers or shared memory long enough to be consumed directly.
601
+
602
+ That reduces global-memory traffic.
603
+
604
+ LLM implementations use fusion in many places.
605
+
606
+ An activation function can be fused with nearby linear operations.
607
+
608
+ Normalization can sometimes be combined with neighboring work.
609
+
610
+ Quantization or dequantization can be integrated into the kernel that consumes the values.
611
+
612
+ But fusion is not automatically good.
613
+
614
+ A larger kernel may use more registers.
615
+
616
+ It may use more shared memory.
617
+
618
+ It may reduce occupancy.
619
+
620
+ So the correct question is not:
621
+
622
+ "Can these operations be fused?"
623
+
624
+ The better question is:
625
+
626
+ **Does the fusion eliminate enough expensive memory traffic to justify the extra on-chip resource pressure?**
627
+
628
+ Again, everything comes back to balancing the hierarchy.
629
+
630
+ ---
631
+
632
+ ## Mixture of experts and prefetching
633
+
634
+ Mixture-of-experts models create an especially interesting memory problem.
635
+
636
+ A router chooses only a small subset of experts for each token.
637
+
638
+ For example, a model might contain many experts while activating only a handful per token.
639
+
640
+ That saves arithmetic because we do not execute every expert.
641
+
642
+ But expert access becomes irregular.
643
+
644
+ Different tokens may select different expert weights.
645
+
646
+ Different layers may select different experts.
647
+
648
+ This creates a natural opportunity for prediction.
649
+
650
+ Suppose information available in the current layer lets us predict which experts are likely to be used in the next layer.
651
+
652
+ We could begin memory movement before the exact demand occurs.
653
+
654
+ The point is not necessarily to force the entire expert into the smallest possible memory.
655
+
656
+ The point is to move useful data closer to where it will be needed, or at least start the request early enough that memory latency overlaps current computation.
657
+
658
+ For example, a prediction could help increase the chance that useful expert data is already present in L two when the next layer requests it.
659
+
660
+ But a prefetch can also hurt.
661
+
662
+ Wrong experts consume bandwidth.
663
+
664
+ Too many candidate experts consume cache capacity.
665
+
666
+ Prefetch too early and the data may be evicted.
667
+
668
+ Prefetch too late and the transfer is still exposed on the critical path.
669
+
670
+ So prediction accuracy is not the final metric.
671
+
672
+ The real question is:
673
+
674
+ **How much correct memory latency did the prediction successfully hide?**
675
+
676
+ That is the hardware-level objective.
677
+
678
+ ---
679
+
680
+ ## L two cache versus shared memory in prefetching
681
+
682
+ This distinction is worth making explicit.
683
+
684
+ L two is a large cache shared by the GPU's SMs.
685
+
686
+ On an H one hundred, it is around fifty megabytes.
687
+
688
+ Shared memory is much smaller and belongs to a thread block on an SM.
689
+
690
+ You usually do not manage ordinary L two cache lines in exactly the same explicit way that you allocate shared memory.
691
+
692
+ So when someone says, "Prefetch the expert into cache," ask which stage they actually mean.
693
+
694
+ They may mean:
695
+
696
+ Start the HBM request earlier so the memory system is already working.
697
+
698
+ Or:
699
+
700
+ Increase the probability that the relevant data is resident in L two before the expert kernel begins.
701
+
702
+ Or:
703
+
704
+ Once the kernel starts, asynchronously stage the next tile from global memory into shared memory while Tensor Cores process the current tile.
705
+
706
+ These are related ideas, but they happen at different levels.
707
+
708
+ A clean framework is:
709
+
710
+ **Prediction tells us what data we expect to need.**
711
+
712
+ **Prefetch scheduling tells us when to begin moving it.**
713
+
714
+ **The memory hierarchy tells us how close to computation we can place it before use.**
715
+
716
+ That distinction is essential when designing a mixture-of-experts prefetch experiment.
717
+
718
+ ---
719
+
720
+ ## One complete decode-token walkthrough
721
+
722
+ Let us trace one token through a transformer.
723
+
724
+ The model weights are already stored in GPU HBM.
725
+
726
+ A token representation enters a transformer layer.
727
+
728
+ Normalization produces an activation vector.
729
+
730
+ Linear projections require large weight matrices.
731
+
732
+ Tiles of those weights move through the memory hierarchy toward the SMs.
733
+
734
+ Warps cooperate on the matrix operations.
735
+
736
+ Shared memory may stage reusable tiles.
737
+
738
+ Registers hold thread-local fragments and partial accumulations.
739
+
740
+ Tensor Cores execute multiply-and-accumulate operations.
741
+
742
+ Attention then combines the new query with historical keys from the KV cache.
743
+
744
+ Historical values contribute to the attention output.
745
+
746
+ A memory-efficient attention kernel tries to minimize unnecessary HBM reads and writes.
747
+
748
+ Then comes another projection.
749
+
750
+ Next is the feed-forward network.
751
+
752
+ In a dense transformer, more large weight matrices are streamed and multiplied.
753
+
754
+ In a mixture-of-experts transformer, a router first selects experts, and the selected expert weights are used.
755
+
756
+ The result becomes the input to the next transformer layer.
757
+
758
+ This repeats layer after layer.
759
+
760
+ Finally, the last hidden state is transformed into vocabulary logits and the next token is selected.
761
+
762
+ Then the entire process repeats for the following token.
763
+
764
+ So the true story of inference is not:
765
+
766
+ "Tensor Cores multiply matrices."
767
+
768
+ The fuller story is:
769
+
770
+ **The system repeatedly predicts, moves, stages, reuses, computes, synchronizes, and stores data while trying to keep expensive off-chip traffic off the critical path.**
771
+
772
+ ---
773
+
774
+ ## Why a giant GPU can still struggle with one sequence
775
+
776
+ An H one hundred has enormous parallel compute capability.
777
+
778
+ So why can single-sequence token generation still fail to use all of it?
779
+
780
+ Autoregressive decoding contains a sequential dependency.
781
+
782
+ Token one hundred and one depends on the result of token one hundred.
783
+
784
+ Within one token there is substantial parallelism, but we cannot arbitrarily compute many future tokens at the same time with ordinary decoding.
785
+
786
+ That means one sequence can produce relatively skinny matrix multiplications.
787
+
788
+ The GPU may have far more arithmetic capacity than one token can efficiently use.
789
+
790
+ Serving systems therefore use continuous batching.
791
+
792
+ They combine work from many active sequences.
793
+
794
+ Now one weight tile can support computations for several current tokens.
795
+
796
+ The GPU performs more arithmetic for the same weight movement.
797
+
798
+ Tensor Core utilization improves.
799
+
800
+ This shows how tightly the software and hardware stacks are connected. A scheduler changes batch shape; batch shape changes GEMM dimensions; GEMM dimensions change weight reuse and arithmetic intensity; and that changes whether the kernel is limited by compute or memory. High-performance LLM inference is hardware-software co-design even without a custom chip.
801
+
802
+ ---
803
+
804
+ ## A practical framework for analyzing any LLM kernel
805
+
806
+ When you encounter a new LLM optimization, ask five questions.
807
+
808
+ First:
809
+
810
+ **What data does the operation need?**
811
+
812
+ Weights, activations, KV-cache blocks, routing scores, expert weights, or something else?
813
+
814
+ Second:
815
+
816
+ **Where does that data live before it is used?**
817
+
818
+ HBM, L two, another GPU, or CPU memory?
819
+
820
+ Third:
821
+
822
+ **How many times can each byte be reused once it reaches the chip?**
823
+
824
+ This tells you a lot about arithmetic intensity.
825
+
826
+ Fourth:
827
+
828
+ **Where do intermediate values live?**
829
+
830
+ Registers, shared memory, or HBM?
831
+
832
+ Could a fusion or tiled algorithm avoid writing them out?
833
+
834
+ Fifth:
835
+
836
+ **What resource is actually limiting performance?**
837
+
838
+ HBM bandwidth?
839
+
840
+ Tensor Core throughput?
841
+
842
+ L two behavior?
843
+
844
+ Shared-memory bandwidth?
845
+
846
+ Register pressure?
847
+
848
+ Inter-GPU communication?
849
+
850
+ Kernel-launch overhead?
851
+
852
+ If you can answer those five questions, you can usually explain why an optimization works.
853
+
854
+ ---
855
+
856
+ ## Final recap
857
+
858
+ Let us compress the lecture into one final mental model.
859
+
860
+ The model lives in large memory, while compute operates on small pieces. The GPU therefore keeps pulling useful tiles inward.
861
+
862
+ HBM stores the large working set.
863
+
864
+ L two can catch useful data shared across the GPU.
865
+
866
+ L one and shared memory provide fast on-chip access within an SM, with shared memory explicitly controlled by the kernel.
867
+
868
+ Registers hold the immediate state of threads and partial results.
869
+
870
+ Warps organize thirty-two threads.
871
+
872
+ Thread blocks let those threads cooperate.
873
+
874
+ SMs schedule their work.
875
+
876
+ Tensor Cores perform dense matrix arithmetic at enormous speed.
877
+
878
+ High-performance kernels tile large tensors, coalesce memory accesses, avoid shared-memory bank conflicts, reuse data on-chip, overlap future loads with current compute, and avoid writing unnecessary intermediate tensors back to HBM.
879
+
880
+ For LLMs, this explains almost everything we have discussed.
881
+
882
+ Prefill is often efficient because many tokens reuse the same weights.
883
+
884
+ Decode is often memory-bound because relatively little computation is performed for each large stream of weights.
885
+
886
+ Quantization can accelerate decode because fewer weight bits have to move.
887
+
888
+ FlashAttention accelerates attention by reducing costly HBM traffic.
889
+
890
+ Kernel fusion keeps temporary data close to compute.
891
+
892
+ KV-cache optimizations reduce capacity and bandwidth pressure.
893
+
894
+ Batching increases reuse.
895
+
896
+ And mixture-of-experts prefetching attempts to begin future memory movement before it becomes a blocking demand.
897
+
898
+ The most important sentence to remember is:
899
+
900
+ **A GPU is fastest when expensive data movement is minimized, useful data is reused close to the compute units, and unavoidable movement is overlapped with useful work.**
901
+
902
+ That turns the memory hierarchy from a list of hardware terms into one system, and it explains why two implementations of the same LLM can have dramatically different latency and throughput.