Core question: After downloading a model, how does the computer actually run it?
Key concepts: Inference, Inference Engine, Runtime, CPU, RAM, GPU, VRAM, Precision, Quantization, Device, Offload, KV Cache, Batch, Prefill, Decode, Latency, Throughput.
A model on disk is only weights, configuration, and input-processing files; the inference engine must create the computation structure from the config, load weights into RAM or VRAM, and call the CPU and GPU to run Tensor computations again and again before the model truly "runs."
Two processes:
- Load the model: read files, create structure, allocate memory, place weights;
- Run inference: process input, run model computation, generate Tokens one by one.
Pipeline
Inference
Inference means using already-trained model parameters to process new inputs and compute output results.
Large language model:
User input
β Model computation
β Predict next Token
β Gradually generate an answerImage classification model:
Image
β Model computation
β Classification probabilitiesImage or video generation model:
Prompt / image / video
β Multiple model computations
β Gradually generate image or videoBoth inference and training run the model's Forward Pass, but with different goals:
| Stage | Main work |
|---|---|
| Training | Forward computation, compute Loss, backpropagation, update parameters |
| Inference | Forward computation, obtain results, do not update model parameters |
For the same model, inference usually needs less VRAM and compute than training.
Inference Engine
A weight file only stores Tensor values; what loads and runs the model is the Inference Engine. It typically handles:
Inference Engine
β
βββ Read model configuration
βββ Create model structure
βββ Load weights
βββ Manage CPU / GPU devices
βββ Manage RAM / VRAM
βββ Execute Tensor operations
βββ Manage KV Cache
βββ Organize Batch
βββ Run sampling
βββ Return or stream resultsCommon inference tools and engines include:
| Tool or framework | Common uses |
|---|---|
| Transformers | Model loading, development, and general inference |
| PyTorch | Low-level Tensor computation and model execution |
| vLLM | High-throughput LLM serving |
| TensorRT-LLM | Optimized LLM inference on NVIDIA GPUs |
| llama.cpp | Local quantized model inference on CPU and GPU |
| ONNX Runtime | Cross-platform model inference |
| MLX | Model computation on Apple Silicon |
| Diffusers | Diffusion image and video models |
| ComfyUI | Organize generative model inference as node workflows |
What Does the Inference Engine Do When Loading a Model?
1. Read Config
The inference engine first reads: config.json. From it it obtains:
- Model type;
- Number of layers;
- Hidden Size;
- Number of Attention Heads;
- Vocabulary Size;
- Maximum context;
- Data type;
- Multimodal component configuration.
2. Create Model Structure
Based on Config and the corresponding model implementation code, create the computation structure:
Embedding
β Transformer Block 1
β Transformer Block 2
β ...
β LM HeadAt this point you can think of it as:
The inference framework first builds an "empty model" composed of computation layers.
3. Locate Weight Files
If weights are sharded, the inference engine reads:
model.safetensors.index.jsonto determine which Shard each parameter is in.
4. Deserialize Weights
The inference engine reads disk data into Tensors:
Safetensors file
β Tensor name
β Tensor shape
β Tensor data type
β Tensor values5. Match Structure and Weights
Parameters in the model structure must correspond to Tensors in the weight files.
6. Place Weights on Devices
Weights may be placed on:
- RAM associated with the CPU;
- VRAM associated with the GPU;
- Multiple GPUs;
- A combination of RAM and VRAM;
- In a few cases, disk-mapped regions.
What Do CPU and GPU Each Handle?
CPU, Central Processing Unit, is a general-purpose compute processor good at:
- Operating-system and program control;
- File reading;
- Input preprocessing;
- Tokenizer;
- Task scheduling;
- Branching and complex control logic;
- Memory management;
- Some model computation.
A model can run entirely on CPU, but large-model computation is usually very slow.
GPU, Graphics Processing Unit, is a massively parallel compute processor originally aimed at graphics, but very well suited to:
- Matrix multiplication;
- Vector computation;
- Parallel execution of large numbers of identical operations;
- Tensor operations in neural networks.
Model inference involves large amounts of matrix computation; GPUs can run many similar computations at once, so they are usually better suited than CPUs for large neural-network inference.
The GPU does not take over the entire application. The CPU usually still handles program control, data preparation, and task scheduling; the GPU mainly carries parallelizable model computation.
What Are RAM and VRAM?
RAM, Random Access Memory, system memory, often just called "memory." Managed by the CPU and OS, it mainly stores:
- Running programs;
- Model files read from disk;
- Weight Tensors on CPU;
- Input and output data;
- Intermediate computation results;
- File caches;
- Model layers that have been Offloaded.
VRAM, Video Random Access Memory, often called "video memory" or GPU memory. It sits on the graphics card and mainly stores data needed for GPU computation:
- Model weights;
- Input Tensors;
- Activations;
- KV Cache;
- Temporary compute buffers;
- CUDA Kernel workspace;
- Intermediate results in image or video generation.
| Resource | Primarily serves | Typical traits |
|---|---|---|
| RAM | CPU and OS | Usually larger capacity; fast CPU access |
| VRAM | GPU | Usually smaller capacity; fast GPU access |
| SSD / HDD | Long-term storage | Large capacity, but far slower than RAM and VRAM |
What Is in VRAM When a Model Runs?
Many people equate VRAM usage directly with weight size, but actual VRAM usually includes several parts:
VRAM Usage
β
βββ Model Weights
βββ KV Cache
βββ Activations
βββ Input / Output Tensors
βββ Temporary Buffers
βββ Framework Overhead
βββ CUDA ContextTherefore: VRAM needed to run > model weight file size
An 8GB weight file does not mean an 8GB GPU can necessarily run it, because space is still needed for other data. Different inference frameworks, model architectures, input lengths, Batch Sizes, and compute precisions all affect extra overhead.
Precision: What Numeric Format Is Used?
Precision means what numeric format model parameters and computation use.
Common formats include:
| Format | Full name | Typical bits per number | Intuitive traits |
|---|---|---|---|
| FP32 | 32-bit Floating Point | 32 bit | High precision, large footprint |
| FP16 | 16-bit Floating Point | 16 bit | About half the footprint of FP32 |
| BF16 | Brain Floating Point 16 | 16 bit | Dynamic range close to FP32 |
| FP8 | 8-bit Floating Point | 8 bit | More space-efficient; needs hardware and software support |
| INT8 | 8-bit Integer | 8 bit | Often used in quantization |
| INT4 | 4-bit Integer | 4 bit | Even lower footprint; quantization error may be more visible |
The coarsest weight-size relationship is:
FP32
β FP16 / BF16: about half
β FP8 / INT8: about one quarter
β INT4: about one eighthQuantization: Why Quantize a Model?
Quantization means: represent model weights or computation data with lower bit-widths to reduce storage, memory use, and compute cost. For example, original BF16 weights -> quantize -> INT8 or INT4 weights.
Main goals of quantization include:
- Reduce model file size;
- Reduce RAM and VRAM use;
- Lower memory-bandwidth pressure;
- Speed up inference on suitable hardware;
- Let large models run on devices with fewer resources.
Trade-offs may include:
- Loss of numeric precision;
- Drop in model quality;
- Some tasks more sensitive to quantization;
- Need for specialized operators and inference engines;
- Different speedups on different hardware.
Device: Which Device Does the Model Actually Run On?
Device means where Tensors and computation live.
Common forms include:
CPU
CUDA GPU
Apple Metal GPU
Other AI acceleratorsIn PyTorch you may see:
cpu
cuda:0
cuda:1
mpsWhere:
cuda:0 β first NVIDIA GPU
cuda:1 β second NVIDIA GPU
mps β Apple Silicon GPU backendModel weights and input Tensors involved in computation usually must live on compatible devices.
Offload: What If VRAM Is Not Enough?
Offload in model inference usually means: do not keep all model components in GPU VRAM at all times; instead keep some in RAM, or even on disk, and move them to the GPU when needed.
Common approaches include:
- CPU Offload
Keep some weights in RAM
β Move into VRAM before computation
β GPU finishes computation
β Swap in other weights when neededAdvantages:
- Lower VRAM demand;
- Let smaller-VRAM GPUs run larger models.
Costs:
- Data must move between CPU and GPU;
- Limited by PCIe bandwidth;
- Speed may drop significantly;
- Higher RAM use.
- Disk Offload
Keep some weights on disk
β Read into RAM
β Then move into VRAMThis can further reduce RAM demand, but disk is far slower than memory and usually causes larger performance loss.
- Sequential Offload
Some image or video generation workflows contain multiple model components:
Text Encoder
β Diffusion Model
β VAEThe inference engine can load them in stages:
Load Text Encoder
β Finish text encoding
β Unload Text Encoder
Load Diffusion Model
β Run generation
β Unload Diffusion Model
Load VAE
β Run decodingThis approach especially suits devices with limited VRAM, but increases time spent swapping models in and out.
Offload is not the same as treating RAM as VRAM
A program can keep some data in RAM, but: RAM does not truly become the GPU's local VRAM. Data the GPU needs for computation still must travel over the CPUβGPU path.
An analogy:
VRAM: the GPU's workbench at hand
RAM: shelves in the room
SSD: the warehouseWhen the workbench is full, materials can be parked on shelves or in the warehouse, but each use still requires carrying them over.
Multiple GPUs: Can You Just Add VRAM Across Cards?
Multiple GPUs can run a model together, but it is not simply: 12GB + 12GB = one 24GB GPU
The inference framework must explicitly support model splitting and cross-card communication. Common approaches include:
| Approach | Meaning |
|---|---|
| Tensor Parallelism | Split one matrix computation across multiple GPUs |
| Pipeline Parallelism | Place different model layers on different GPUs |
| Expert Parallelism | Place different MoE experts on different GPUs |
| Data Parallelism | Put a full model on each GPU and handle different requests |
The first three are mainly for:
Multiple GPUs
β Jointly complete one model instance or one inferenceData Parallelism is:
GPU 1 β request A
GPU 2 β request B
GPU 3 β request CSo in batch generation scenarios, first confirm: is the goal for multiple cards to jointly run one large model, or for each card to run a task independently?
The latter usually has a simpler architecture and more easily yields linear throughput gains.
KV Cache: Why Does Generation Keep Consuming More VRAM?
Large language models generate Tokens one by one autoregressively. If every new Token recomputed Attention intermediates for all previous Tokens, that would produce huge redundant computation. Therefore inference engines usually save Key and Value produced by past Tokens in Attention; this cache is called KV Cache (Key-Value Cache).
- Without KV Cache, every generation step reprocesses the full history.
- With KV Cache, save some intermediate results for historical Tokens and only compute new results for the new Token.
Effects:
- Reduce redundant computation;
- Speed up Token-by-Token generation;
- Support efficient autoregressive inference.
But it also uses RAM or VRAM, and usually grows with:
- Context length;
- Batch Size;
- Number of concurrent requests;
- Number of model layers;
- Number of KV Heads;
- KV Cache precision.
Therefore: being able to fit model weights in VRAM does not mean you can necessarily handle very long context or many concurrent requests.
Because remaining VRAM must also hold the KV Cache.
Latency and Throughput: How Do You Measure Inference Speed?
Latency means how long an operation takes to complete.
| Metric | Meaning |
|---|---|
| TTFT | Time to First Token: time from receiving a request to generating the first Token |
| ITL | Inter-Token Latency: delay between adjacent output Tokens |
| E2E Latency | Total time from sending a request to finishing the full answer |
Throughput means how much work the system can complete per unit time. Common forms include:
- Tokens per Second (TPS): Tokens generated per second;
- Requests per Second (RPS): requests handled per second;
- Images per Minute (IPM): images generated per minute;
- Videos per Hour (VPH): videos generated per hour.
Differences for Generative Image and Video Models
Image and video generation models may run differently. For example, diffusion-style models:
Prompt
β Text Encoder
β Initial noise
β Diffusion Model multi-step denoising
β VAE Decode
β Image or videoRuntime VRAM may include:
Generative Model VRAM
β
βββ Text Encoder Weights
βββ Diffusion Model Weights
βββ VAE Weights
βββ Latent
βββ Attention intermediates
βββ Temporary compute buffers
βββ Image / video TensorsConcepts
Model Loading & Inference
β
βββ Inference Software
β βββ Framework
β βββ Inference Engine
β βββ Runtime
β βββ Backend
β
βββ Hardware
β βββ CPU
β βββ RAM
β βββ GPU
β βββ VRAM
β βββ SSD
β
βββ Model Loading
β βββ Config
β βββ Architecture Implementation
β βββ Deserialization
β βββ Weight Loading
β βββ Device Map
β
βββ Numerical Representation
β βββ Precision
β βββ FP32 / FP16 / BF16
β βββ FP8 / INT8 / INT4
β βββ Quantization
β
βββ Memory Management
β βββ Model Weights
β βββ Activations
β βββ KV Cache
β βββ Temporary Buffers
β βββ Offload
β
βββ Execution
β βββ Prefill
β βββ Decode
β βββ Forward Pass
β βββ Sampling
β
βββ Request Scheduling
β βββ Batch
β βββ Dynamic Batching
β βββ Concurrency
β βββ Queue
β
βββ Performance
βββ Latency
βββ TTFT
βββ Tokens per Second
βββ Throughput
βββ OOMSummary
After a model is downloaded to disk, it still cannot run directly. The inference engine first reads Config to create the model structure, then deserializes weights from Safetensors and similar files into Tensors, and places them into RAM or VRAM according to device and memory strategy. After input is encoded, the CPU handles program organization and scheduling while the GPU runs the main parallel Tensor computation. A large language model first Prefills to process input and build the KV Cache, then enters Decode to generate Tokens one by one. Precision, Quantization, Offload, context length, and Batch Size together determine how much memory the model needs, how fast it runs, and how many requests it can handle at once.
- Downloading a model only saves files to disk; loading a model places weights into RAM or VRAM;
- Weight files themselves cannot run; they must be executed jointly by an inference engine, compute framework, and hardware;
- VRAM stores more than model weights; it must also hold KV Cache, intermediates, and temporary buffers;
- Quantization can lower memory demand, but results depend on the quantization method, inference engine, and hardware support;
- Offload lets small-VRAM devices run large models, but usually slows down due to data movement.