Notes
All notes

Types of Models (AI Engg #5)

A finance team asks you to add an “ask your statements” feature. Legal says customer data cannot leave the company’s cloud. Procurement has budget for exactly one thing, and it is not GPUs. The obvious answer — call the biggest closed model — is off the table. The alternative — self-host a small open model — may or may not be good enough. How do you decide?

This chapter gives you the decision procedure. You will learn the three model families, what actually differs between them, how to evaluate them on your task instead of public leaderboards, and how to build a router so cheap requests stay cheap. By the end, “which model?” becomes a spreadsheet, not a vibe.

Three families

The line between them keeps moving. Open models that were frontier two years ago now run on a laptop; closed models leap ahead on the hardest tasks. Assume you will re-decide every quarter, and build so a swap is an environment variable, not a rewrite.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=5pt, minimum width=3.0cm, minimum height=1.2cm, font=\rmfamily\small, align=center},
  a/.style={->, thick}]
  \node[b, fill=red!10] (c) at (-3.6,0) {closed\\GPT / Claude / Gemini\\best quality, per-token};
  \node[b, fill=blue!10] (o) at (0,0) {open weights\\Llama / Qwen / Mistral\\hostable, fine-tunable};
  \node[b, fill=green!12] (s) at (3.6,0) {small / local\\3–8B quantized\\private, cheap, fast};
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-1.5) {prototype closed $\to$ measure everything $\to$ move hot paths down this ladder};
\end{tikzpicture}

What actually differs (not just “quality”)

“Quality” is a single blurry number. In practice these dimensions decide:

Dimension Why it matters Where open wins Where closed wins
Reasoning hard multi-step tasks improving fast currently ahead
Tool / function calling agents (Ch. 11) decent most reliable
Structured output parsing, schemas varies strong schema mode
Context window long docs up to 128K+ up to 1M
Latency UX tunable, self-hosted network + queue
Cost scale ~$0 marginal per token
Privacy compliance full control data leaves VPC
Licensing legal check each license vendor terms
Version stability regressions you pin the weights vendor updates

The last two rows are the ones engineers forget and lawyers remember. A closed model can change under you overnight; your regression suite (Chapter 13) exists partly to catch that. An open model you can freeze byte-for-byte — at the cost of never improving until you choose to.

Choosing the right model: the procedure

Stop asking “what’s the best model?” Ask “what is the cheapest model that passes my evals?”

  1. Write the task spec. Input, output schema, and 50–200 golden examples with expected outputs. If you cannot write this, no model will save you.
  2. Set constraints. Data residency, max latency, max cost per 1K calls, required context length.
  3. Shortlist 4–6 models. One flagship closed, one small closed, two open, one local.
  4. Run the same evals through all of them. Score with deterministic checks + a model judge (Chapter 13).
  5. Pick the cheapest that clears your bar. Route the rest.
# a dead-simple bench harness — run it on YOUR goldens, not MMLU
from openai import OpenAI
CANDIDATES = [
    ("gpt-4o",        OpenAI()),
    ("gpt-4o-mini",   OpenAI()),
    ("qwen2.5:7b",    OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")),
]
def score(model, client, goldens):
    ok = 0
    for g in goldens:
        r = client.chat.completions.create(model=model, temperature=0,
            messages=[{"role": "user", "content": g["prompt"]}])
        out = r.choices[0].message.content
        if g["must_contain"].lower() in out.lower():
            ok += 1
    return ok / len(goldens)
for name, c in CANDIDATES:
    print(f"{name:16} {score(name, c, goldens):.2%}")

Public leaderboards (MMLU, GPQA, coding arena) are useful for shortlisting and useless for deciding. Your task is peculiar: your documents, your format, your edge cases. The only score that matters is the one on your goldens.

Benchmarks: how to read them without being fooled

The honest use of benchmarks: filter 50 models to 5, then benchmark those 5 on your data. Never skip the second step.

The router: cheap by default, escalate on doubt

The mature architecture is not one model. It is a router that sends each request to the cheapest model likely to succeed, and escalates when confidence is low.

def classify_reasoning_needed(q: str) -> bool:
    # cheap heuristic model call, or a tiny classifier
    r = small.chat.completions.create(
        model="gpt-4o-mini", temperature=0, max_tokens=4,
        messages=[{"role": "system", "content": "Answer only SIMPLE or HARD."},
                  {"role": "user", "content": q}])
    return "HARD" in r.choices[0].message.content.upper()

def answer(q):
    if classify_reasoning_needed(q):
        return flagship(q)              # GPT-5 / Claude / Gemini
    return cheap(q)                     # 4o-mini / Qwen-7B

Two more patterns worth knowing:

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=2.2cm, minimum height=0.7cm, font=\rmfamily\small, align=center},
  a/.style={->, thick}]
  \node[b, fill=gray!10] (q) at (-3.6,0) {request};
  \node[b, fill=orange!15] (r) at (-1.3,0) {router\\classify};
  \node[b, fill=green!12] (c) at (1.6,0.9) {cheap model\\80\% of traffic};
  \node[b, fill=red!10] (f) at (1.6,-0.9) {flagship\\hard 20\%};
  \draw[a] (q) -- (r); \draw[a] (r) -- (c); \draw[a] (r) -- (f);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-1.6) {same evals gate every branch};
\end{tikzpicture}

Fine-tuning on small open models

Once you have a high-volume, narrow task that a small model almost passes, fine-tuning can close the gap and collapse cost and latency. Use it for:

Do not use it for facts (stale, cannot cite — use RAG, Chapter 10), and do not start there. The order is: prompt → context/RAG → small model → fine-tune. Teams that fine-tune first burn weeks and inherit an eval problem with an extra model to maintain.

A worked decision

Back to the finance team. The feature: answer questions over a customer’s statements.

  1. Spec: 300 golden Q→A pairs, must cite the statement page, must refuse if not present.
  2. Constraints: data cannot leave VPC ⇒ closed APIs disallowed. Latency < 3s p95. Budget ≈ one A10 GPU.
  3. Shortlist: Llama-3-8B, Qwen2.5-7B, Mistral-7B (all local), plus a 3B for drafts.
  4. Bench: measure answer correctness (judge) + citation accuracy (deterministic page check) + p95 latency.
  5. Outcome: Qwen2.5-7B at ~40 tok/s, 92% correctness, 95% citation accuracy meets the bar. Route simple lookups (“what was my balance in June?”) to a 3B model with a SQL tool; use 7B for synthesis.

The decision was driven by the constraint, not by the leaderboard — and the evals proved it was good enough.

Pitfalls

QQuestionSelf-check

Why can the cheapest model be the right default? When is self-hosting forced rather than chosen?

ASolution

Because most production traffic is easy, and routing easy requests to a cheap model cuts cost and latency without hurting quality; evals tell you the cheap model clears the bar. Self-hosting is forced by data-residency/compliance rules, by latency constraints, or by marginal-cost economics at very high volume — not usually by raw quality.

Next: The Open Stack (AI Engg #6) — how to actually run these models locally and route between them.