Learning path: Deep Learning for Production: Transformers, Fine-Tuning and Serving · Step 7 of 13
Model Size and Memory: Parameters x Bytes, Quantization, and Where to Run a Model
Will this model fit on my machine? One rule, parameters x bytes per number, gives a 7B model 14 GB at 16-bit and 3.5 GB at 4-bit. Then a real measurement of SmolLM2-135M (538 MB vs 269 MB) and the three ways to run a model: hosted API, local, or an inference server.
What you will learn
- Estimate a model's weight memory as parameters x bytes per number
- Explain what quantization trades: a little accuracy for a lot of memory
- Measure a model's memory footprint in float32 and bfloat16
- Choose between a hosted API, a local model and an inference server
Before you start
- Loading a Language Model and Running Inference
- Basic Python
You've found a model you like. Before anything else, every team asks three questions:
- How much memory does it need? Will it fit on my laptop, or do I need a bigger machine?
- How fast is it? How many tokens per second will my users get?
- Where does it run? On an API, on my own machine, or on a server many people share?
Here's the plan: one rule for memory, one trick to shrink it, and three places to run the model.
The memory rule
A model is a huge list of numbers, and each number is a parameter. Every number takes some bytes to store. So:
memory for the weights = number of parameters x bytes per number
A 7 billion parameter model stored at 16 bits (2 bytes per number) needs 7 billion x 2 = 14 GB. That counts the weights only. When the model actually runs, it needs some extra on top.
So the first answer is just arithmetic. You don't need to download anything to find out whether a model will fit.
The rule in Python
"""Memory needed for the weights = number of parameters x bytes per number."""
MODELS = {"SmolLM2 135M": 135e6, "1B model": 1e9, "7B model": 7e9, "70B model": 70e9}
FORMATS = {"fp32": 4, "fp16/bf16": 2, "int8": 1, "4-bit": 0.5}
def weights_gb(parameters, bytes_per_number):
return parameters * bytes_per_number / 1e9
print("Weights only, in GB (the runtime needs some extra on top)")
print(f"{'model':<14}" + "".join(f"{name:>11}" for name in FORMATS))
for model, parameters in MODELS.items():
row = "".join(f"{weights_gb(parameters, size):>11.2f}" for size in FORMATS.values())
print(f"{model:<14}{row}")
Weights only, in GB (the runtime needs some extra on top)
model fp32 fp16/bf16 int8 4-bit
SmolLM2 135M 0.54 0.27 0.14 0.07
1B model 4.00 2.00 1.00 0.50
7B model 28.00 14.00 7.00 3.50
70B model 280.00 140.00 70.00 35.00
The inputs are the model sizes in parameters and the bytes per number for each format: 4 bytes is float32, 2 bytes is 16-bit, 1 byte is 8-bit, and half a byte is 4-bit. The 1B and 7B rows are the sizes you'll meet most. A 7B model needs 14 GB at 16-bit, too much for a small laptop. At 4-bit it needs 3.5 GB.
Quantization: fewer bits per number
How do we get from 14 GB down to 3.5? With quantization: store the same numbers with fewer bits. Less detail per number, much less memory.
You'll also hear the word GGUF. It's a file format for packed (quantized) models, and local tools such as Ollama load it.
The trade-off: you lose a little accuracy, and you save a lot of memory. For many uses that's a very good deal. If you want to see quantization measured on real files, with the accuracy change and timings, read Making ML Inference Fast: ONNX, Micro-Batching and Quantisation. It also shows the case where quantizing doesn't help at all: a tiny model with no big weight matrices.
Measure a real model
The table is arithmetic. Now let's measure. This uses SmolLM2-135M from Loading a Language Model and Running Inference.
"""Load SmolLM2-135M in float32 and bfloat16, print memory and tokens per second."""
import time
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
MODEL_NAME = "HuggingFaceTB/SmolLM2-135M-Instruct"
PROMPT = "Explain in one sentence why the sky is blue."
NEW_TOKENS = 40
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
inputs = tokenizer(PROMPT, return_tensors="pt")
for label, dtype in [("float32", torch.float32), ("bfloat16", torch.bfloat16)]:
model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, dtype=dtype)
model.eval()
megabytes = model.get_memory_footprint() / 1e6
with torch.no_grad(): # warm-up so the timing is fair
model.generate(**inputs, max_new_tokens=3, do_sample=False)
start = time.perf_counter()
with torch.no_grad():
output = model.generate(
**inputs, max_new_tokens=NEW_TOKENS, min_new_tokens=NEW_TOKENS, do_sample=False
)
seconds = time.perf_counter() - start
made = output.shape[1] - inputs["input_ids"].shape[1]
print(f"{label:<9} memory {megabytes:7.0f} MB {made / seconds:5.1f} tokens/s")
float32 memory 538 MB 2.4 tokens/s
bfloat16 memory 269 MB 2.4 tokens/s
The same model is loaded twice, first as float32, then as bfloat16. get_memory_footprint() reports how many bytes the weights use. A short warm-up runs first, then 40 new tokens are timed to get tokens per second.
The memory is cut in half, just as the rule said. The speed stays near 2.4 tokens per second on this CPU. Your machine will give different numbers, and that's fine.
CPU or GPU
Why is it so slow? Generating one token is a huge pile of small multiplications. A CPU is like a few strong workers: good at many different jobs, one after another. A GPU is like a huge crowd of small workers, all doing the same kind of calculation at the same time. That's why a GPU generates faster. A tiny model runs fine on a CPU; a large one wants a GPU with enough memory to hold it.
Where should it run? Moving house
Think of moving house. First you pack your furniture flat so it fits in a smaller van: that's quantization. Then you pick a vehicle:
- A taxi is the hosted API. You pay per trip and have no car to maintain.
- Your own car is running the model locally. Private and yours, but you look after it.
- A bus is an inference server. It carries many passengers at once.
Same journey, same furniture. The choice is about who looks after the vehicle, and how many people travel.
Three ways to run it, in code
These are the shapes of the code, not runs. No outputs or prices are shown because none were measured.
1. Hosted API
from dotenv import load_dotenv
from anthropic import Anthropic
load_dotenv()
client = Anthropic()
reply = client.messages.create(
model="your-model-name",
max_tokens=200,
messages=[{"role": "user", "content": "Explain why the sky is blue."}],
)
print(reply.content[0].text)
The key comes from the .env file. Use it when you want to start fast and pay only for what you use.
2. Local with Ollama
ollama run gemma3
import httpx
reply = httpx.post(
"http://localhost:11434/api/generate",
json={"model": "gemma3", "prompt": "Explain why the sky is blue.", "stream": False},
timeout=120,
)
print(reply.json()["response"])
Ollama serves the model on your own machine, port 11434. Use it when data must stay private and you can look after the machine.
3. An inference server for many users
vllm serve HuggingFaceTB/SmolLM2-135M-Instruct --port 8000
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="not-needed-locally")
reply = client.chat.completions.create(
model="HuggingFaceTB/SmolLM2-135M-Instruct",
messages=[{"role": "user", "content": "Explain why the sky is blue."}],
)
print(reply.choices[0].message.content)
One command starts the server, then the same OpenAI-style client points at its address. Use it when many users share one model.
Why is a server good for many users? It batches requests. Each answer may wait a moment, but the machine serves many more people in the same time. That's the difference between latency (how long one user waits) and throughput (how many users you serve). Serving Open Models: vLLM, Batching and Cold Starts goes deeper.
Common mistakes
- Counting only the weights. The table is weights only; the running model needs extra on top.
- Mixing up GB and parameters. 7B is the parameter count. The GB depend on bytes per number: 28, 14, 7 or 3.5.
- Expecting a smaller format to be faster everywhere. Here bfloat16 halved memory but stayed at 2.4 tokens/s on a CPU. Measure on your machine.
- Picking the vehicle before the question. Privacy, cost and the number of users decide between API, local and server.
Quick recap
| Question | Answer |
|---|---|
| How much memory? | Parameters x bytes per number: 7B at 16-bit = 14 GB, weights only |
| How to shrink it? | Quantization: 8-bit = 7 GB, 4-bit = 3.5 GB, a little accuracy for a lot of memory |
| Measured | SmolLM2-135M: 538 MB float32, 269 MB bfloat16, 2.4 tokens/s on a CPU |
| Where to run? | Hosted API (start fast), local (private), inference server (many users, batching) |
Try it yourself
Add the model you want to use to MODELS and read its memory at 16-bit and 4-bit. Change MODEL_NAME in the measure script to another small model. Then decide which of the three ways fits your project, and why.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Loading a Language Model and Running Inference: Download, Load, Tokenize, Generate
Next →Training on a GPU: Mixed Precision, Gradient Accumulation and Checkpoints That Really Resume
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Why Neural Networks: Pixels, One Neuron and Layers
Why pictures need neural networks: a handwritten digit is 784 numbers, one neuron is a weighted sum plus a bias and one small rule, and neurons stack into layers. Worked out on MNIST with NumPy.
The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
Follow numbers through a tiny 3-2-3 network in NumPy: one matrix product per layer, ReLU inside, softmax at the end, and a count of every weight and bias.
Loss and Backpropagation: How Wrong, and Who Is to Blame
The loss says how wrong the network was; backpropagation says how much each weight is to blame. MSE and cross-entropy, the chain rule by hand on a two-weight chain, then the same gradients from PyTorch autograd.
The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
How training is organised: shuffle, cut into mini-batches, take one step per batch, repeat per epoch. Real MNIST runs compare three learning rates, SGD against Adam, and show the overfitting signal in the validation loss.