New cohort: Agentic AI & LLM Engineering remote internship. Limited seats.Apply now
Lesson 19 of 21 22 minFree

Building with Small Language Models (SLMs)

Why small language models like Phi, Gemma and Llama 3.2 matter, how quantization fits them on laptops and phones, and when small beats big.

By the end of this lesson you will be able to:

  • Explain what a small language model (SLM) is and why it can compete with bigger models on focused tasks.
  • Estimate how much memory a model needs, and how quantization shrinks it.
  • Name popular SLM families and the tools that run them on devices.
  • Decide when to use an SLM, a large model, or both together.

Small is the new smart

Many students in India use budget phones, and many schools have patchy internet. A study buddy that only works with a fast connection to a giant cloud model leaves them behind. Small language models (SLMs) are models with roughly a few hundred million up to around 10 billion parameters. They are small enough to run on a laptop, a phone or a single modest GPU, often offline.

They are good because of how they're trained: carefully filtered, high-quality data (including synthetic "textbook-like" data), and often distillation, where a smaller "student" model learns from a bigger "teacher". On focused tasks a well-trained SLM can match much larger models from a year or two earlier.

Why choose an SLM?

  • Privacy: data stays on the device.
  • Offline: works without internet.
  • Low latency: no network round trip.
  • Cost: no per-token API fees, and far cheaper to host and fine-tune.
  • Specialisation: easy to fine-tune for one job (Lesson 18).

The trade-offs: less broad knowledge, weaker complex reasoning, and shorter practical context on small devices.

Will it fit? Memory, precision and quantization

A model's memory need is roughly parameters × bytes per parameter, plus some overhead. At 16-bit precision each parameter takes 2 bytes, so an 8B model needs about 16 GB just for its weights. Quantization stores weights with fewer bits, such as 8-bit or 4-bit, cutting memory by 2–4× with usually a small loss in quality. Pick a device and a precision and see which models fit:

Rule of thumb: a 4-bit 3–4B model runs comfortably on a modern laptop and on many phones. A 4-bit 7–8B model needs a good laptop or a gaming GPU. 70B+ models need server GPUs.

Popular SLM families

  • Microsoft Phi: Phi-3-mini (3.8B), Phi-3.5 and Phi-4-mini, known for strong reasoning for their size. MIT-licensed.
  • Google Gemma: small open models such as Gemma 2 2B and 9B.
  • Meta Llama 3.2: 1B and 3B text models designed for phones and edge devices (Lesson 21).
  • Qwen2.5 (0.5B–7B), Mistral 7B and Ministral: other strong small options (Lesson 20).

Model families update often, so check Hugging Face for current versions and read each model card (Lesson 16).

Running SLMs

  • Ollama and LM Studio: download and chat locally in minutes, with a local API your apps can call.
  • llama.cpp and the GGUF file format: fast CPU and GPU inference with many quantization levels.
  • ONNX Runtime (including ONNX Runtime GenAI): optimised inference across Windows, mobile and the web.
  • In the browser: WebGPU runtimes can run small models directly in a web page.
# On a laptop with Ollama installed:
ollama run phi3          # chat in the terminal
# Your app can call the local API:
curl http://localhost:11434/api/generate -d '{"model": "phi3", "prompt": "Explain photosynthesis in 2 lines"}'

Small and big, together

Many real apps route requests: an SLM handles simple, frequent or private tasks, and only hard questions go to a large cloud model.

Hands-on

Your task: complete memory_gb() as parameters (billions) × bytes per parameter × 1.2 (overhead), and fits(). Use 4-bit precision (0.5 bytes) and a 16 GB laptop. Expected: Fits on laptop (16 GB): 1B, 3.8B, 8B.

models = {"1B": 1, "3.8B": 3.8, "8B": 8, "70B": 70, "405B": 405}
BYTES = {"16-bit": 2, "8-bit": 1, "4-bit": 0.5}

def memory_gb(params_b, precision):
    # TODO: params (billions) * bytes per parameter * 1.2
    return 0.0

def fits(params_b, precision, device_gb):
    # TODO: True when memory_gb(...) <= device_gb
    return False

for name, p in models.items():
    print(f"{name:5}  16-bit {memory_gb(p, '16-bit'):7.1f} GB   4-bit {memory_gb(p, '4-bit'):7.1f} GB")
ok = [name for name, p in models.items() if fits(p, "4-bit", 16)]
print("Fits on laptop (16 GB):", ", ".join(ok) if ok else "none")
Show solution
def memory_gb(params_b, precision):
    return params_b * BYTES[precision] * 1.2

def fits(params_b, precision, device_gb):
    return memory_gb(params_b, precision) <= device_gb

Your task: 8-bit quantization maps each weight to an integer from -127 to 127 using a scale. Complete quantize() as round(w / scale) and dequantize() as q * scale, then see how small the error is. Expected last line: Max error after 8-bit quantization: 0.004.

weights = [0.52, -1.03, 0.007, 0.88, -0.41, 0.25, -0.77, 0.99]
scale = max(abs(w) for w in weights) / 127     # one scale for the whole group

def quantize(w):
    # TODO: return round(w / scale) as an int between -127 and 127
    return 0

def dequantize(q):
    # TODO: return q * scale
    return 0.0

q = [quantize(w) for w in weights]
back = [dequantize(x) for x in q]
print("int8 :", q)
print("back :", [round(b, 3) for b in back])
print(f"Memory: {len(weights) * 4} bytes as float32 → {len(weights)} bytes as int8 (+ 1 scale)")
print(f"Max error after 8-bit quantization: {max(abs(a - b) for a, b in zip(weights, back)):.3f}")
Show solution
def quantize(w):
    return max(-127, min(127, round(w / scale)))

def dequantize(q):
    return q * scale

Check your understanding

Roughly how much memory do the weights of an 8B model need at 16-bit precision?

  1. About 1 GB
  2. About 4 GB
  3. About 16 GB
  4. About 160 GB

8 billion × 2 bytes ≈ 16 GB, plus overhead for running it.

What does 4-bit quantization do?

  1. Stores weights with fewer bits, cutting memory about 4× versus 16-bit with a small quality loss
  2. Makes the model 4 times smarter
  3. Removes 4 layers
  4. Limits answers to 4 words

Quantization trades a little precision for much less memory and often faster inference.

A village school needs a homework helper with no reliable internet. The best choice is…

  1. The biggest cloud model
  2. A 405B model on the school laptop
  3. No AI at all
  4. A quantized small model running locally

SLMs run offline on modest hardware, which is exactly this case.

Key takeaways

  • SLMs (about 1–10B parameters) trade breadth for privacy, offline use, speed and low cost.
  • Memory ≈ parameters × bytes per parameter. Quantization shrinks it 2–4×.
  • Phi, Gemma, Llama 3.2, Qwen and Mistral offer strong small models. Run them with Ollama, llama.cpp or ONNX Runtime.
  • Route between small and large models to get the best of both.

Next: Mistral's models, and the clever mixture-of-experts design.

Your progress is saved in this browser.

Adapted from Lesson 19 of Microsoft's "Generative AI for Beginners" (MIT License), rewritten and extended by Aiprojects4U. View source