LLM Inference: Insights into Memory and Performance
Generating content with Large Languge Models (LLMs) depends on two steps: training, where models learn from vast datasets, and inference, where they apply the knowledge to produce responses.
Training builds the brain; inference makes it talk, fast and scale. The catch? Fitting massive models into memory and handling thousands of users is no small feat.
This post dives into the details of LLM inference, focusing on memory management for VRAM, performance metrics such as latency and tokens per second (TPS) and the role of GPU capabilities in optimizing large-scale deployments.
Here’s your guide to the key points.
Theoretical Memory Calculation for LLMs
Using an LLM on a GPU depends on handling its VRAM, shown in this formula:

- Model Memory: Space allocated for the model’s weights.
- KV Cache: Saves the “key” and “value” results from past tokens. Think of it as keeping notes from earlier steps so the model can work faster.
- GPU Overhead: It’s like the GPU’s own workspace, stuff it keeps for running smoothly, not for the model’s weights or its calculations.
To better understand how these components interact and impact LLM inference, let’s dive deeper into each one.
Model Memory
Model Memory refers to the space allocated for storing the model’s weights, which are the core parameters learned during training.
These weights determine how the model processes input data and generates outputs. The size of the model memory depends on the number of parameters in the LLM and the precision format used (e.g., FP16, INT8, or INT4).
For example, a model with billions of parameters can consume hundreds of gigabytes of VRAM in its raw form, but quantization can significantly reduce this footprint.
Quantization is a technique that enables LLMs to use less VRAM/RAM and operate faster. It reduces memory consumption and increases processing speed by converting the model’s weights and computations from higher precision formats like 16-bit (FP16) or 32-bit (FP32) to lower precision formats such as 8-bit (INT8), 4-bit (INT4), or even lower levels (INT2, INT1).
While quantization can lead to a reduction in model accuracy, advanced quantization techniques like GPTQ and AWQ help minimize this loss.
The memory required to store the model’s weights can be calculated using the following formula:

- P: Number of model parameters
- 4B: 4 Bytes per parameter
- Q: Quantization (in bits)
For a model like Llama 8B with FP32 precision, the memory required for the weights can be calculated as follows:

KV Cache
Key-Value Caching is a technique in transformer models where the key and value matrices from previous steps are stored and reused during the generation of subsequent tokens. This means that instead of recalculating all past tokens every time a new token is generated, the model retrieves the previous computations from the KV Cache.

- B: Batch Size is the number of sequences processed simultaneously. Increasing the batch size increases the memory required for the KV Cache because the model needs to store key-value pairs for all sequences in the batch.
- S: Sequence length is the number of tokens in the input sequence. Longer sequences require more memory because the KV Cache stores key-value pairs for every token in the sequence.
- L: Number of layers is the number of transformer layers in the model. Each layer has its own set of key-value pairs, so the memory scales with the number of layers.
- H: Hidden size is the dimensionality of the hidden states (key and value vectors). Larger hidden sizes increase memory usage because each key and value vector is larger.
- P: Precision is the number of bytes used to store each parameter (e.g., FP16 = 2 bytes, FP32 = 4 bytes). Lower precision (e.g., FP16) reduces memory usage but may affect model accuracy.
Each token generates both a key and a value, so the memory requirement is doubled. For example:
- Batch Size (B): 1
- Sequence Length (S): 2048
- Number of Layers (L): 32
- Hidden Size (H): 4096
- Precision (P): 1 byte (INT8)

The formula highlights how KV Cache memory usage scales with batch size, sequence length, and model architecture, enabling better planning for large-scale deployments.
GPU Overhead
GPU overhead refers to the additional memory and resources required by the GPU to manage tasks beyond just storing the model’s weights and KV Cache. It includes:
- Intermediate Activations: Temporary storage for activations during forward and backward passes.
- CUDA Kernels: Memory for GPU kernels and their execution.
- System Overhead: Memory reserved by the GPU driver and runtime for managing tasks.
- Workspace Memory: Memory used for optimizations like cuBLAS or cuDNN operations.
Unlike Model Memory and KV Cache Memory, GPU overhead is not directly tied to the model’s architecture but depends on the GPU hardware, drivers, and the deep learning framework being used.
GPU overhead is typically 5–10% of the total VRAM but can vary depending on:
- GPU Architecture: Newer GPUs have better memory management and lower overhead.
- Framework: PyTorch, TensorFlow and other frameworks have different overheads.
- Workload: Complex operations (e.g., attention mechanisms) increase overhead.
Performance Metrics
When deploying large language models (LLMs) in real-world applications, understanding and optimizing performance metrics is crucial. These metrics not only determine how efficiently a model operates but also directly impact user experience and system scalability. Whether you’re serving a chatbot, a translation service, or a content generation tool, three key metrics stand out: tokens per second (TPS), latency and max concurrent users.
TPS (Tokens per Second)
TPS measures the number of tokens a model can generate per second. It is a key metric for evaluating the inference speed of a model. The TPS value can be estimated using the GPU’s processing capacity (FLOPs/s) and the model’s computational requirements per token (FLOPs/token):

- GPU FLOPs/s: The theoretical computational power of the GPU (Floating Point Operations per Second).
- Model FLOPs/token: The number of floating-point operations required to generate one token (depends on the model’s size and architecture).
- Efficiency Factor: Typically ranges between 0.3 - 0.6 accounting for real-world inefficiencies.
In real-world scenarios, the theoretical TPS value is significantly reduced due to factors such as:
- Memory bandwidth limitations
- Cache optimization inefficiencies
- Quantization (4-bit, 8-bit, 16-bit)
- Parallelization efficiency
Latency
Latency is the time delay between a user sending a query and receiving a response. It is a critical metric for user experience.
- Low Latency: Faster responses, better user experience.
- High Latency: Users experience delays, and the system may become congested.
- Latency Response: The total time for the user to receive a complete response.

The latency can be broken down into two components:
- Latency per Token: The time the model takes to generate one token.

- Avg Tokens per Request: The average number of tokens generated per user request.
Max Concurrent Users
The maximum number of concurrent users a system can handle depends on the total TPS, response time, and average tokens per request.

To increase the number of concurrent users:
- Increase TPS: Use more powerful GPUs or optimize the model (e.g., FP16, quantization).
- Reduce Response Time: Improve first-token latency and inference speed.
- Reduce Avg Tokens per Request: Generate fewer tokens per user request to serve more users simultaneously.
Efficiently deploying LLMs requires balancing memory usage, inference speed, and scalability. By understanding and optimizing these key factors, you can ensure your models deliver fast, reliable, and cost-effective performance in real-world applications.
As the field of AI continues to evolve, staying ahead of the curve requires a deep understanding of these foundational concepts. Whether you’re deploying a small-scale application or a large-scale service, the principles outlined in this post will help you make informed decisions and build systems that stand the test of time.
Thank you for reading!

Large Language Models (LLMs) ile içerik üretimi iki aşamaya dayanır: modellerin büyük dataset’lerden öğrendiği training ve öğrendiklerini yanıt üretmek için kullandığı inference.
Training modelin öğrenmesini sağlar; inference ise hızlı ve ölçeklenebilir biçimde yanıt üretmesini. Büyük modelleri belleğe sığdırmak ve binlerce kullanıcıya hizmet vermek kolay değildir.
Bu yazı LLM inference ayrıntılarını; VRAM için bellek yönetimini, latency ve tokens per second (TPS) gibi performans metriklerini ve büyük deployment’ları optimize etmede GPU kapasitesinin rolünü inceliyor.
Temel noktaları birlikte ele alalım.
LLM’ler İçin Teorik Bellek Hesabı
Bir LLM’i GPU üzerinde kullanmak, aşağıdaki formülde gösterilen VRAM ihtiyacını yönetmeyi gerektirir:

- Model Memory: Model weights için ayrılan alan.
- KV Cache: Önceki token’ların key ve value sonuçlarını saklar. Modelin daha hızlı çalışmak için tuttuğu notlar gibi düşünebilirsiniz.
- GPU Overhead: Model weights dışında GPU’nun sorunsuz çalışması için gereken ek çalışma alanıdır.
Bu bileşenlerin nasıl etkileştiğini ve LLM inference’ı nasıl etkilediğini anlamak için her birini inceleyelim.
Model Memory
Model Memory, training sırasında öğrenilen temel parametreler olan model weights’in saklandığı alanı ifade eder.
Bu weights, modelin girdiyi nasıl işlediğini ve çıktı ürettiğini belirler. Model memory boyutu, LLM’in parametre sayısına ve kullanılan precision formatına bağlıdır: FP16, INT8 veya INT4 gibi.
Örneğin milyarlarca parametreli bir model ham haliyle yüzlerce gigabyte VRAM tüketebilir; quantization bu ihtiyacı önemli ölçüde azaltabilir.
Quantization, LLM’lerin daha az VRAM/RAM kullanmasını ve daha hızlı çalışmasını sağlayan bir tekniktir. Model weights ve hesaplamaları 16-bit (FP16) veya 32-bit (FP32) gibi yüksek precision formatlarından 8-bit (INT8), 4-bit (INT4), hatta INT2 veya INT1 gibi daha düşük formatlara dönüştürerek bellek tüketimini azaltır ve işlem hızını artırabilir.
Quantization model accuracy değerinde düşüşe yol açabilse de GPTQ ve AWQ gibi gelişmiş teknikler bu kaybı azaltmaya yardımcı olur.
Model weights için gereken bellek aşağıdaki formülle hesaplanabilir:

- P: Modelin parametre sayısı
- 4B: Parametre başına 4 byte
- Q: Bit cinsinden quantization
Llama 8B gibi bir modelde FP32 precision ile weights için gereken bellek şöyle hesaplanabilir:

KV Cache
Key-Value Caching, transformer modellerinde önceki adımların key ve value matrislerinin saklanıp sonraki token’lar üretilirken yeniden kullanılmasıdır. Böylece model her yeni token için tüm geçmiş token’ları tekrar hesaplamak yerine KV Cache içindeki önceki hesaplamaları kullanır.

- B: Batch Size, aynı anda işlenen sequence sayısıdır. Batch size arttıkça tüm sequence’ların key-value çiftlerini tutmak gerektiği için KV Cache bellek ihtiyacı artar.
- S: Sequence Length, girdi sequence’ındaki token sayısıdır. KV Cache her token için key-value çifti sakladığından uzun sequence’lar daha çok bellek gerektirir.
- L: Number of Layers, modeldeki transformer layer sayısıdır. Her layer kendi key-value çiftlerine sahip olduğundan bellek ihtiyacı layer sayısıyla artar.
- H: Hidden Size, hidden state’lerin yani key ve value vektörlerinin boyutudur. Hidden size büyüdükçe her vektör daha büyük olduğundan bellek kullanımı artar.
- P: Precision, her parametreyi saklamak için kullanılan byte sayısıdır; örneğin FP16 = 2 byte, FP32 = 4 byte. Daha düşük precision bellek kullanımını azaltır ama model accuracy değerini etkileyebilir.
Her token hem key hem value ürettiği için bellek ihtiyacı ikiyle çarpılır. Örneğin:
- Batch Size (B): 1
- Sequence Length (S): 2048
- Number of Layers (L): 32
- Hidden Size (H): 4096
- Precision (P): 1 byte (INT8)

Formül, KV Cache bellek kullanımının batch size, sequence length ve model mimarisiyle nasıl büyüdüğünü gösterir; büyük deployment’lar için planlama yapmayı kolaylaştırır.
GPU Overhead
GPU overhead, weights ve KV Cache saklamanın dışında GPU’nun işleri yönetmek için ihtiyaç duyduğu ek bellek ve kaynaklardır. Şunları içerir:
- Intermediate Activations: Forward ve backward pass sırasında activation’lar için geçici alan.
- CUDA Kernels: GPU kernel’ları ve bunların çalışması için gereken bellek.
- System Overhead: GPU driver ve runtime tarafından görev yönetimine ayrılan bellek.
- Workspace Memory: cuBLAS veya cuDNN gibi işlemlerde optimizasyon için kullanılan bellek.
Model Memory ve KV Cache Memory’den farklı olarak GPU overhead doğrudan model mimarisine değil; GPU donanımına, driver’lara ve kullanılan deep learning framework’üne bağlıdır.
GPU overhead genellikle toplam VRAM’in %5–10’u civarında ele alınır, ancak şu etkenlere göre değişebilir:
- GPU Architecture: Yeni GPU’lar daha iyi bellek yönetimi ve daha düşük overhead sunabilir.
- Framework: PyTorch, TensorFlow ve diğer framework’lerin overhead maliyetleri farklıdır.
- Workload: Attention mekanizmaları gibi karmaşık işlemler overhead’i artırır.
Performans Metrikleri
LLM’leri gerçek uygulamalarda deploy ederken performans metriklerini anlamak ve optimize etmek önemlidir. Bunlar hem modelin verimliliğini hem kullanıcı deneyimini hem de ölçeklenebilirliği etkiler. Chatbot, çeviri servisi veya içerik üretim aracı sunarken üç metrik öne çıkar: tokens per second (TPS), latency ve max concurrent users.
TPS (Tokens per Second)
TPS, modelin saniyede üretebildiği token sayısını ölçer ve inference hızını değerlendirmede temel bir metriktir. TPS değeri GPU’nun işlem kapasitesi (FLOPs/s) ve modelin token başına hesaplama ihtiyacı (FLOPs/token) üzerinden tahmin edilebilir:

- GPU FLOPs/s: GPU’nun teorik işlem kapasitesi, Floating Point Operations per Second.
- Model FLOPs/token: Bir token üretmek için gereken floating-point işlem sayısı; modelin boyutuna ve mimarisine bağlıdır.
- Efficiency Factor: Gerçek koşullardaki verimsizlikleri hesaba katmak için örnekte 0,3–0,6 aralığında ele alınır.
Gerçek koşullarda teorik TPS değeri şu etkenlerle önemli ölçüde düşebilir:
- Memory bandwidth sınırları
- Cache optimizasyonundaki verimsizlikler
- Quantization (4-bit, 8-bit, 16-bit)
- Parallelization verimliliği
Latency
Latency, kullanıcının sorgu göndermesiyle yanıt alması arasında geçen süredir. Kullanıcı deneyimi için temel bir metriktir.
- Low Latency: Daha hızlı yanıtlar, daha iyi kullanıcı deneyimi.
- High Latency: Kullanıcı bekler; sistemde yoğunluk oluşabilir.
- Response Latency: Kullanıcının tam yanıtı almasına kadar geçen toplam süre.

Latency şu bileşenlerle ele alınabilir:
- Latency per Token: Modelin bir token üretmesi için geçen süre.

- Avg Tokens per Request: Kullanıcı isteği başına üretilen ortalama token sayısı.
Max Concurrent Users
Sistemin destekleyebileceği eşzamanlı kullanıcı sayısı; toplam TPS, response time ve istek başına ortalama token sayısına bağlıdır.

Eşzamanlı kullanıcı sayısını artırmak için:
- TPS’i artırın: Daha güçlü GPU’lar kullanın veya modeli FP16 ve quantization gibi yöntemlerle optimize edin.
- Response Time’ı azaltın: First-token latency ve inference hızını iyileştirin.
- Avg Tokens per Request değerini azaltın: Daha fazla kullanıcıya aynı anda hizmet vermek için istek başına daha az token üretin.
LLM’leri verimli deploy etmek; bellek kullanımı, inference hızı ve ölçeklenebilirlik arasında denge kurmayı gerektirir. Bu etkenleri anlayıp optimize ederek gerçek uygulamalarda hızlı, güvenilir ve maliyet açısından verimli sistemler kurabilirsiniz.
AI geliştikçe bu temel kavramları iyi anlamak önemini koruyor. İster küçük bir uygulama ister büyük bir servis deploy edin, bu ilkeler bilinçli kararlar almanıza ve dayanıklı sistemler kurmanıza yardımcı olur.
Okuduğunuz için teşekkürler!
