How to Run a 7B LLM for Free on Google Colab (4-Bit Quantization, Step-by-Step)
By Muhammad Rustam · AIBYTEC · Python, Hugging Face & Google Colab
Want to run a real 7-billion-parameter language model without paying for a GPU? In this hands-on guide you'll load Qwen2.5-7B-Instruct on Google Colab's free T4 GPU using 4-bit quantization. You'll also learn how temperature, top_p and top_k control what the model writes.
bitsandbytes cuts that to roughly 5–5.5 GB, so it fits comfortably and runs at no cost.
Why a 7B Model Doesn't Fit on a Free GPU
A model's memory footprint comes from a simple formula:
| Precision | Bytes per parameter | Weights only | Fits on a free T4? |
|---|---|---|---|
| FP32 | 4 | 30.4 GB | ❌ No |
| FP16 / BF16 | 2 | 15.2 GB | ❌ No |
| INT8 | 1 | 7.6 GB | ✅ Yes |
| 4-bit (NF4) | 0.5 | 3.8 GB | ✅ Yes, with lots of room |
Remember that these numbers cover weights only. The KV cache (the model's short-term memory of your conversation), activations and CUDA overhead all add to the total. That's why FP16 crashes on a T4 even though 15.2 GB looks close to 16 GB.
What Is 4-Bit Quantization (NF4)?
Quantization compresses a model's weights from 16-bit decimals down to small integers, much like compressing a high-resolution photo. The basic idea uses a scale (S) and a zero-point (Z):
X_quantized = round(X / S) + Z
X_restored = (X_quantized - Z) × SNF4 (NormalFloat 4-bit), the format used by bitsandbytes, improves on this in two ways:
- It splits the weights into small blocks and scales each block separately, so one extreme value can't ruin the precision of everything else.
- It places its 16 levels where trained weights actually cluster, following a bell-shaped (normal) distribution. That means less rounding error than evenly spaced levels.
Step-by-Step: Run a 7B LLM on Google Colab
Step 1Switch to the free T4 GPU
In Colab, open Runtime → Change runtime type, choose T4 GPU, and click Save. 4-bit loading needs a CUDA GPU, so it won't work on the CPU runtime.
Step 2Install the libraries
# bitsandbytes = 4-bit quantization, accelerate = automatic GPU placement
!pip install -q -U transformers accelerate bitsandbytesStep 3Load the model in 4-bit
import torch
from transformers import pipeline, BitsAndBytesConfig
if not torch.cuda.is_available():
raise RuntimeError("No GPU found. Runtime → Change runtime type → T4 GPU, then re-run.")
model_id = "Qwen/Qwen2.5-7B-Instruct"
# 4-bit NF4 quantization settings
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4", # NormalFloat 4-bit
bnb_4bit_compute_dtype=torch.float16, # T4 GPUs don't support bfloat16
bnb_4bit_use_double_quant=True, # also compresses the scale factors
)
llm = pipeline(
"text-generation",
model=model_id,
model_kwargs={"quantization_config": bnb_config},
device_map="auto", # place layers on the GPU automatically
)
print(f"Model memory: {llm.model.get_memory_footprint() / 1e9:.2f} GB")Step 4Write a reusable generation function
def ask_llm(system_prompt: str, user_prompt: str,
temperature: float = 0.7, max_new_tokens: int = 500) -> str:
"""Send a system + user message and return the model's reply."""
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
]
output = llm(
messages,
max_new_tokens=max_new_tokens, # maximum reply length
temperature=temperature, # creativity control (see next section)
top_p=0.90, # nucleus sampling cutoff
do_sample=True, # sample instead of always picking the top token
)
# The pipeline returns the whole chat; the last message is the reply
return output[0]["generated_text"][-1]["content"]Step 5Try it: factual vs creative
# Low temperature → focused, factual answer
print(ask_llm(
"You are an AI teacher. Give clear, accurate answers.",
"Explain the difference between self-attention and cross-attention.",
temperature=0.2,
))
# High temperature → creative, different every run
print(ask_llm(
"You are an imaginative storyteller.",
"Write a 5-sentence story about a robot who learns to cook biryani in Karachi.",
temperature=1.0,
))Run the creative prompt twice and you'll get two different stories. Run the factual one twice and the answers will be nearly the same. The next section explains why.
model_id to another 7–8B instruct model on Hugging Face. Gated models such as Llama also require you to accept the license and log in with a Hugging Face token first.Temperature, Top-P and Top-K Explained
At every step, the model scores each word in its vocabulary. These raw scores are called logits. A function called softmax turns them into probabilities, and the decoding settings decide how a word is picked from those probabilities.
Temperature
- Low temperature (0.1–0.3) sharpens the probabilities so the top word almost always wins. Use it for code, maths, facts and JSON.
- High temperature (1.0 and above) flattens the probabilities so less likely words get a real chance. Use it for stories, marketing ideas and brainstorming.
Top-K vs Top-P (nucleus sampling)
- Top-K always keeps exactly the K most likely words (for example K = 50), however confident the model is.
- Top-P keeps the smallest group of words whose combined probability reaches P (for example 0.9). Its advantage is that it adapts: when the model is confident it keeps just one or two words, and when the model is unsure it keeps more options.
| Use case | Temperature | Top-P |
|---|---|---|
| Code, JSON, data extraction | 0.1–0.3 | 0.9 |
| Factual Q&A, RAG chatbots | 0.3–0.5 | 0.9 |
| General chat assistants | 0.7 | 0.9 |
| Stories, ads, brainstorming | 0.9–1.2 | 0.95 |
Common Errors and How to Fix Them
| Error or symptom | Fix |
|---|---|
| "No GPU found" or a bitsandbytes CUDA error | Switch the runtime to T4 GPU and run all cells again. |
CUDA out of memory | Make sure you loaded in 4-bit, lower max_new_tokens, and restart the runtime to clear old models from memory. |
Error about passing load_in_4bit directly | That style is deprecated. Use BitsAndBytesConfig as shown in Step 3. |
| bfloat16 errors or very slow runs on a T4 | T4 GPUs don't support bfloat16. Set bnb_4bit_compute_dtype=torch.float16. |
Error when setting temperature=0 | Sampling needs a temperature above 0. For fully deterministic output, use do_sample=False instead. |
Know the Limits
- Hallucinations: LLMs can state false facts with full confidence. For anything factual, ground the model with RAG (retrieval-augmented generation) and validate its output.
- Lost in the middle: even with long context windows, models recall information buried in the middle of a long prompt less reliably. Put key instructions at the start or end.
Frequently Asked Questions
Can I run a 7B LLM on Google Colab for free?
Yes. Load the model in 4-bit with bitsandbytes on Colab's free T4 GPU. A 7B model then needs roughly 5–5.5 GB of VRAM instead of about 15 GB.
How much VRAM does a 7B model need?
For the weights alone: about 30 GB in FP32, 15 GB in FP16, 7.6 GB in 8-bit and 3.8 GB in 4-bit (for a 7.6B-parameter model). Add extra headroom for the KV cache and runtime overhead.
Does 4-bit quantization reduce quality?
Slightly, mainly on complex multi-step reasoning. For chatbots, summaries, learning and demos, the difference is usually small, and the memory savings are huge.
What temperature should I use for an LLM?
Use 0.1–0.3 for code, JSON and facts, around 0.7 for general chat, and 0.9–1.2 for creative writing. Keep top_p around 0.9.
What is the difference between top-k and top-p?
Top-k always keeps a fixed number of candidate words. Top-p keeps however many words are needed to reach a probability threshold, so it narrows down when the model is confident and widens when it's unsure.
Build Real AI Apps With AIBYTEC
Learn LLMs, RAG chatbots and AI agents hands-on, with runnable code and real projects, at AIBYTEC in Karachi.
Explore AIBYTEC Courses