If you have ever watched an LLM generate a long response and wondered why it seems to crawl after the initial prompt flash, you are observing a hardware bottleneck in real time. Most developers blame their Python code, the framework, or the sheer size of the model. They profile functions, swap optimizers, and shave milliseconds off preprocessing. None of that fixes the real problem. The speed limit is not in your software. It is in the silicon.

Every large language model inference job depends on two physical traits of the GPU sitting in your server: how fast it can crunch numbers, and how fast it can move those numbers into position to be crunched.

Math Is Cheap. Moving Data Is Not

GPU marketing loves to talk about compute. Trillions of floating-point operations per second. The numbers are staggering. But compute is only half the story. The other half is memory bandwidth, the rate at which data travels from high-bandwidth memory into the compute cores where the actual arithmetic happens.

An LLM cannot run faster than the weaker of these two links. Imagine a commercial kitchen with twenty master chefs. The ovens are hot, the knives are sharp, and every cook is ready. But the produce delivery arrives by bicycle, one basket at a time. The kitchen stalls. Adding more chefs will not fix it. Buying faster ovens will not fix it. The bottleneck is the road.

In modern datacenter GPUs, the arithmetic units are so powerful that they often finish their calculations and then sit idle, burning cycles while they wait for weights and activations to stream through memory. This imbalance is not a bug in your code. It is the physical reality of how chips are built. Memory bandwidth has not kept pace with raw compute, and LLMs are particularly cruel to this imbalance because their forward passes require touching every single parameter for every single output token.

Why Prompts Feel Fast and Generation Feels Slow

LLM inference splits into two distinct phases, and they stress the hardware in completely different ways.

Prefill happens when your prompt first hits the model. All tokens arrive together. The GPU can process them in parallel using large matrix-matrix multiplications. Thousands of arithmetic units fire at once, and the workload stays dense. This phase is compute-bound. That sudden burst of speed you see at the start? That is the GPU doing exactly what it was built to do.

Decode is where things turn painful. When the model generates the next token, it does so one token at a time. This stage relies on matrix-vector operations, which use only a tiny fraction of the GPU's parallel capacity. Worse, every new token forces the GPU to reload the entire model weights from memory. The arithmetic units want work. Instead, they wait. Decode is memory-bound. The GPU is effectively acting as an expensive traffic controller, shuttling parameters back and forth across the memory bus while the math engines cool off. This is why a hundred-word response can take ten seconds even though the initial prompt analysis felt instant.

The KV cache makes this even more interesting. During decode, the model stores key and value tensors for every previous token so it does not recompute attention from scratch. That cache grows with sequence length. It also lives in memory. So now the GPU is not just reloading weights; it is reading and writing an ever-expanding cache on every single forward pass. The compute cores are barely breaking a sweat while the memory bus sweats for both of them.

Fighting the Memory Wall

Engineers have developed a small arsenal of techniques to reduce how much data must move, or at least to share the cost of moving it.

Batching is the most straightforward. If one user’s request forces a full weight load from memory, then processing eight or sixteen requests at once lets the GPU amortize that load across all of them. The weights are read once and reused for every sequence in the batch. In production, sophisticated scheduling systems group requests dynamically, sometimes called continuous or in-flight batching, so that the GPU rarely pauses. It is the difference between a bus and sixteen separate cars on the same route.

Квантування безпосередньо вирішує проблему пропускної здатності. Ваги моделі зазвичай зберігаються у шістнадцятибітних форматах із рухомою комою. Стискаючи їх до восьмибітних або навіть чотирьохбітних цілих чисел, ви буквально зменшуєте обсяг даних, що передаються через шину, вдвічі або більше. Моделі все ще потрібна достатня точність для створення зв'язних результатів, але сучасні методи квантування після навчання (post-training quantization) можуть кардинально зменшити обсяг пам'яті, який займає модель, не втрачаючи при цьому якості. Менше даних у процесі передачі означає менше часу очікування на контролері пам'яті.

FlashAttention реструктуризує механізм уваги, щоб зберігати проміжні результати у швидкій вбудованій пам'яті GPU. Стандартна увага потребувала запису великих матриць уваги у повільну зовнішню пам'ять із подальшим їх зчитуванням. FlashAttention розбиває обчислення на менші блоки (tiles), які вміщуються в SRAM, виконує кроки softmax та масштабування безпосередньо на чіпі та записує назад у пам'ять із високою пропускною здатністю лише кінцеві результати. Він обмінює невелику кількість додаткових обчислень на значне скорочення циклів звернення до основної пам'яті, що майже завжди є вигідним рішенням.

PagedAttention вирішує інший тип марнотратства пам'яті. Під час декодування KV-кеш зростає непередбачувано. Традиційні системи виділяють фіксовані безперервні фрагменти пам'яті для кожної послідовності, залишаючи великі прогалини, оскільки одні послідовності завершуються раніше, а інші розширюються. PagedAttention запозичує концепцію віртуальної пам'яті з операційних систем. Він зберігає записи KV-кешу у блоках фіксованого розміру, які можуть бути виділені не безперервно та відображені через таблицю непрямої адресації. Це запобігає простою пам'яті в зарезервованих, але напівпорожніх буферах, і дозволяє збільшити розмір пакетів (batch sizes), що, своєю чергою, підвищує загальну пропускну здатність, завантажуючи шину пам'яті корисною роботою замість витрат на фрагментацію.

Змініть фокус запитання

Коли затримка (latency) різко зростає, занадто багато команд запитують, чи не варто перейти на меншу модель або переписати свій сервер виведення (inference server). Ці питання важливі, але вони другорядні. Першим питанням має бути саме обладнання. Чи справді ваш GPU зайнятий обчисленнями, чи він «голодує» через брак даних?

Подивіться на свої метрики використання. Проаналізуйте насичення пропускної здатності пам'яті разом із рівнем завантаження обчислювальних ресурсів GPU. Якщо під час декодування ви бачите високу конкуренцію за пам'ять (memory contention) та низьку арифметичну інтенсивність, то у вас проблема не в архітектурі моделі. У вас проблема з фізикою. Рішення не полягатиме в написанні чистого коду на Python. Воно полягатиме в агресивнішому пакетному обробленні (batching), квантуванні ваг для швидшого проходження через «трубу», реструктуризації механізму уваги для роботи на чіпі та управлінні KV-кешем, щоб можна було вмістити більші пакети, не вичерпуючи пам'ять.

Як тільки ви поглянете на процес виведення (inference) під цим кутом, оптимізація стане механічною. Ви перестанете переслідувати міфи про те, що інтелект моделі сповільнює роботу, і почнете приймати інженерні рішення, засновані на тому, що обладнання може забезпечити насправді. Саме цей перехід відрізняє масштабовані продуктивні системи від тих, що просто функціонують.