11C.6 Open-Weight and Local Models

ProductionLesson 6 of 614,975 wordsOptional10 parts
Module 11C · 0 of 5 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6

Until now every model in this path has been a hosted API: you send tokens, you pay per token, and someone else's GPUs do the work. This lesson is about the other side of the market — open-weight models you download and run yourself, on your laptop, a workstation, rented GPUs, or even inside a browser or phone. It covers when running your own model is the right engineering decision (and when it is an expensive mistake), the families and quantization formats you will meet, how to size hardware honestly, every runtime worth knowing as of November 2026 (Ollama, llama.cpp, LM Studio, MLX, vLLM, SGLang, TensorRT-LLM and the managed hosts), and how to serve open models in production without giving up the reliability lessons of 11C.3. It closes the loop with the local development and hybrid architectures that let you keep most of the convenience of APIs while owning the sensitive or cheap parts yourself.

What you'll learn

  • What "open-weight" and "local" actually mean, the four ways to run an open model (your hardware, rented GPUs, managed open-model hosts, edge/on-device), and an honest break-even analysis of API vs self-hosting — including the utilisation number that decides it
  • The open-weight landscape as of November 2026: families, sizes, licences, and — the part earlier lessons skipped — how quantization formats (GGUF, AWQ, GPTQ, FP8, MXFP4/NVFP4) change what you can run, and how to prove a model on your eval set
  • Hardware sizing done properly: the VRAM arithmetic for weights and the KV cache, CPU vs GPU vs unified memory, batching effects, and cost per million tokens — with a calculator you can run
  • Every local and self-hosted runtime worth knowing: Ollama (Modelfiles, keep-alive, parallelism, KV-cache quantization), llama.cpp's llama-server, LM Studio, MLX/mlx-lm on Apple Silicon, vLLM (PagedAttention, continuous batching, prefix caching, structured outputs, LoRA serving, tensor parallelism), SGLang's RadixAttention, NVIDIA TensorRT-LLM/Triton, and the archived status of Hugging Face TGI
  • Managed open-model hosting as of November 2026: Hugging Face Inference Endpoints, Together, Fireworks, Groq, Cerebras, Baseten, Modal, Replicate, RunPod — and OpenRouter as the aggregator route you already know
  • Production serving: OpenAI-compatible surfaces so your app swaps base_url, concurrency and queueing, prefix/KV caching, speculative decoding, monitoring, health checks, rolling upgrades, canaries, multi-tenancy, model-file provenance (safetensors vs pickle), licence compliance, GPU-fleet autoscaling and spot capacity, and what KV-aware routing and prefill/decode disaggregation (llm-d, NVIDIA Dynamo) add at fleet scale
  • Local development workflows: a small model for dev/test/CI, contract tests, hybrid architectures (local for sensitive or cheap work, hosted for hard work), and edge/on-device options (WebLLM, Apple Foundation Models/Core AI/MLX, Gemini Nano-class models)
  • Embeddings, rerankers, speech and vision models running locally — where the boundary falls with Modules 06 and 09

What you don't need

  • API keys or a GPU. Every calculator and code sample runs on a laptop with the standard library. The serving-engine samples are reference code you run later; the concepts, the arithmetic and the decision tables are the deliverable.
  • Model training or fine-tuning. 13A.8 owns the decision between prompting, RAG and fine-tuning; this lesson only covers serving a fine-tuned or adapter model (LoRA) once it exists.
  • Deep GPU/kernel knowledge. You need to size hardware and tune serving flags, not write CUDA.
  • A running Ollama, vLLM or any other service — nothing in this lesson installs or starts one. Lesson 03.1, Part 12 already showed the Ollama stand-in pattern; this lesson goes deep on what runs where.

Setup

This lesson's runnable code needs only Python 3.11+ and the standard library — no uv add, no packages, no keys:

bash
python3 gpu_sizing.py     # the worked sizing calculator from Part 3
python3 breakeven.py      # the API-vs-self-host calculator from Part 1
python3 bench_openai_compatible.py   # the throughput benchmark from Part 10 (start its fake_server.py in a second terminal first)

(Save each snippet to a file of the same name and run it; the full listings appear where they're introduced.)

For the reference samples that talk to real servers, the module's project folder is llm-service (uv init llm-service --bare --python 3.13, as in 11A.1), and the provider SDK from Module 03 applies (openai, checked against 3.42.1 as of November 2026; a plain install gives you the newest release). .env keys are only needed for the hosted-provider comparisons; every local-server sample uses a dummy key string the server ignores.


What you must be able to do after this lesson#

  • Explain the difference between open-weight and local, and the four ways to run an open model
  • Estimate VRAM for weights plus KV cache and say why a model that fits can still run out of memory
  • Decide when self-hosting beats an API on cost
  • Choose a serving engine for a given model and hardware, such as vLLM for a 70B chat product
  • Swap base_url to an OpenAI-compatible server and secure its API key
  • Check the licence gate before a model enters the pipeline

Why this matters for an AI engineer#

Every row below is a decision or a conversation you will actually have — and the earlier lesson that handed it to you:

You'll hear... You'll understand it after...
"Legal says customer data can't leave our VPC — can we still use an LLM?" 1.2 When self-hosting wins
"Is it cheaper to run our own GPU than pay per token?" 1.2, 3.4 Cost per million tokens
"Which open model should we pick — and is 'open' the same as 'free to ship'?" Part 2
"We downloaded a 4-bit model and it fits — why does it still OOM?" 3.1 The VRAM arithmetic
"Ollama, llama.cpp, vLLM, LM Studio — which one is 'the' local LLM tool?" Parts 4 and 5
"TGI is deprecated — what replaced it?" 5.4
"Our app already speaks OpenAI — how do we point it at our own server?" 7.1
"Prefix caching is free money, right?" 7.3
"The model server is on the public internet with no auth — is that a problem?" 7.6
"We fine-tuned a LoRA — how do we serve it without doubling GPU memory?" 7.7
"Our prefix-cache hit rate collapsed when we added replicas" / "What are llm-d and Dynamo?" 7.9
"Can we run the model on the user's laptop / in the browser?" 8.3
"Should the cheap local model handle the easy tickets and the API the hard ones?" 8.2

Part 1 — The decision: API, self-host, or managed open-model host#

1.1 What "open-weight" and "local" actually mean#

Open-weight means the trained parameters — the weights — are published for download, usually from Hugging Face, usually under a licence like Apache 2.0, MIT, or a custom community licence with conditions. That is not the same as "open source" in the software sense: you get the artifact, not the training data, the training pipeline, or a guarantee the weights stay up forever. Lesson 02.9, Part 3 owns the family-by-family survey and the licence landscape; this lesson assumes you can pick a model and instead answers how you run it.

Local means you run the inference: the model file sits on hardware you control and tokens never leave your network boundary. Two clarifications matter in production:

  • "Local" does not mean "safe". A llama-server or mlx_lm.server bound to 0.0.0.0 on a laptop on café Wi-Fi is a public endpoint with no authentication unless you configure one — and several runtimes' default setups assume 127.0.0.1. 7.6 covers the security posture.
  • "Open-weight" does not mean "free to ship". Licences carry conditions (attribution, acceptable-use clauses, share-alike terms on some families). 02.9 walks the licence check; it is a deployment gate, not paperwork.

Once you have weights, there are exactly four ways to run them:

Route Who runs the engine Who owns the GPUs Examples
Your hardware You install a runtime on a laptop, workstation, or server You Ollama, llama.cpp, LM Studio, MLX on Apple Silicon, vLLM on your GPU box
Rented GPU infra (self-managed) You install and operate the same engines You rent by the hour RunPod pods/servers, Lambda, Vast.ai, cloud VMs with GPUs
Managed open-model host The provider runs a serving engine and exposes an API The provider Together, Fireworks, Groq, Cerebras, HF Inference Endpoints, Baseten, Modal, Replicate
Edge / on-device The model runs inside the user's browser, phone, or app The user WebLLM (WebGPU), Apple Foundation Models/Core AI/MLX, on-device runtimes

The middle two rows are the ones people conflate. Self-hosting (rows 1–2) means you operate the serving engine — you own the batching, the uptime, the upgrades, and the pager. Managed open-model hosting (row 3) means the provider operates vLLM/SGLang/llama.cpp for you and you get an OpenAI-compatible API — you get open-weight economics (often lower per-token prices, and no dependence on a closed-model vendor) without the ops burden. Be precise about the data boundary, though: your tokens still leave your network and are processed by the host, so a managed host satisfies "no closed-model vendor" requirements but not "tokens never leave our VPC" ones unless it offers a private deployment you have reviewed. Both are "open-weight"; only one is "local".

1.2 When self-hosting wins — and when it doesn't#

Self-hosting an open-weight model earns its complexity when at least one of these is true:

  • Data residency / privacy / compliance. Tokens must not leave your network boundary — VPC-only deployments, air-gapped environments, regulated workloads, or contractual "no third-party processors" clauses. This is the strongest reason and the one that overrides cost math entirely.
  • Sustained high volume. At enough tokens per month, per-token API pricing exceeds the amortized cost of a GPU you keep busy. The break-even calculator below shows the utilisation threshold; in practice it also requires the workload to fill the GPU (batching many concurrent requests), which most apps never reach.
  • Control. You need a specific quantization, a custom chat template, fine-tuned weights or LoRA adapters, a modified sampling pipeline, or latency characteristics no hosted provider offers.
  • Model lifecycle. The model you need is retired from hosted APIs, or exists only as weights (research releases, distilled internal models, fine-tunes).
  • Offline / edge. No network, or latency budgets below what any network can deliver — that's row 4, on-device, covered in 8.3.

It loses — badly — when none of those apply. The hidden costs are real:

  • Utilisation. A GPU serving a chat app at 10% busy costs several times the API price per token. You pay for idle silicon 24/7.
  • Engineering time. Choosing quantization, sizing KV cache, tuning batching flags, writing health checks and rollback procedures, monitoring prefix-cache hit rates, upgrading engines without breaking clients. This is weeks of senior-engineer time per deployment, every time.
  • No managed fallbacks. When your vLLM replica OOMs mid-request, there is no with_fallbacks to rescue you — you are the fallback layer. 11C.3 owns that machinery, but the point stands: self-hosting removes the provider's redundancy and adds yours to build.
  • The quality gap. Open-weight models trail frontier closed models on hard reasoning, long-context, and agentic tasks. Self-hosting the best open model still means accepting that gap; sometimes the right answer is "pay the API for the hard 5%" — which is exactly what 8.2 is for.

The break-even calculator. Run this (stdlib only, save as breakeven.py):

python
"""Break-even calculator: hosted API vs self-hosted GPU, as a function of utilisation.

Every number is a parameter: replace them with quotes from your
provider's pricing page and your own benchmark before trusting the verdict.
"""


def api_cost_per_million(api_input_per_m, api_output_per_m, in_out_ratio):
    """Blended $/1M tokens. in_out_ratio = output tokens per input token."""
    total = 1 + in_out_ratio
    return (api_input_per_m + api_output_per_m * in_out_ratio) / total


def self_host_cost_per_million(gpu_hourly, gpus, tok_per_sec, utilisation):
    """$/1M tokens on rented GPUs at a given busy fraction."""
    tok_per_hour = tok_per_sec * 3600 * utilisation
    return gpu_hourly * gpus / tok_per_hour * 1e6 if tok_per_hour else float("inf")


# --- Parameters (illustrative; label illustrative in the lesson) ---
API_IN, API_OUT = 0.30, 1.20        # $/1M tokens, hosted open-weight model
GPU_HOURLY, GPUS = 2.50, 1          # one 80GB-class GPU
TOK_PER_SEC = 900                   # aggregate decode throughput at batch
IN_OUT = 4.0                        # 4 output tokens per input token

api_blend = api_cost_per_million(API_IN, API_OUT, IN_OUT)
print(f"Blended API price: ${api_blend:.3f} per 1M tokens "
      f"(in ${API_IN}, out ${API_OUT}, {IN_OUT}:1 out:in)")
print()
print(f"{'utilisation':>12} {'self-host $/1M':>15} {'verdict':>28}")
for util in [0.02, 0.05, 0.10, 0.25, 0.50, 0.75, 0.90]:
    own = self_host_cost_per_million(GPU_HOURLY, GPUS, TOK_PER_SEC, util)
    verdict = "self-host cheaper" if own < api_blend else "API cheaper"
    print(f"{util:>11.0%} ${own:>14,.2f} {verdict:>28}")

util_be = GPU_HOURLY * GPUS * 1e6 / (TOK_PER_SEC * 3600 * api_blend)
print(f"\nBreak-even utilisation: {util_be:.1%} "
      f"(GPUs must be busy more than this for self-hosting to win on price alone)")
print("Reminder: this ignores engineering time, monitoring, redundancy and the")
print("quality gap. Control, privacy and offline use are the usual real reasons.")
Output · run on this machine, Python 3, no packages14 lines
Blended API price: $1.020 per 1M tokens (in $0.3, out $1.2, 4.0:1 out:in)

 utilisation  self-host $/1M                      verdict
         2% $         38.58                  API cheaper
         5% $         15.43                  API cheaper
        10% $          7.72                  API cheaper
        25% $          3.09                  API cheaper
        50% $          1.54                  API cheaper
        75% $          1.03                  API cheaper
        90% $          0.86            self-host cheaper

Break-even utilisation: 75.6% (GPUs must be busy more than this for self-hosting to win on price alone)
Reminder: this ignores engineering time, monitoring, redundancy and the
quality gap. Control, privacy and offline use are the usual real reasons.

Read that honestly: with plausible prices, the self-hosted GPU only beats the API above ~76% sustained utilisation. Most real workloads sit far below that. Two consequences:

  • If your motivation is cost, measure your actual sustained throughput first (the benchmark skeleton in Part 10 measures exactly this). Self-hosting rarely wins on price for intermittent workloads; it wins at fleet scale or on flat-rate commitments where you can keep GPUs saturated.
  • If your motivation is control, privacy, offline, or model availability, the price table is irrelevant — take the GPU and accept the ops cost as the price of the requirement.

Managed open-model hosts change the math. Row 3 of the table above gives you open-weight prices without the ops burden — often close to API pricing with the data-boundary story of "open weights on someone else's GPU." When "we want open models but can't run GPUs" is the actual requirement, Part 6 is the answer, not row 1.

1.3 The four routes, as a decision diagram#

flowchart TD
    Q3{"Must the workload run with no network<br/>at all (user device, edge, offline)?"}
    Q1{"Do tokens have to stay inside<br/>your network boundary?<br/>(VPC, air-gap, contract, regulation)"}
    Q2{"Is sustained volume high enough<br/>to keep a GPU >~75% busy,<br/>or do you need control<br/>(quant, template, LoRA, custom serving)?"}
    API["Hosted frontier / open APIs<br/>OpenAI, Anthropic, Gemini,<br/>OpenRouter — pay per token, zero ops"]
    SELF["Self-host: your hardware or rented GPUs<br/>Ollama / llama.cpp / LM Studio / MLX locally;<br/>vLLM / SGLang / TensorRT-LLM on servers"]
    MANAGED["Managed open-model host<br/>Together, Fireworks, Groq, Cerebras,<br/>HF Inference Endpoints, Baseten, Modal, Replicate, RunPod"]
    EDGE["Edge / on-device<br/>WebLLM, Apple Foundation Models / Core AI / MLX, mobile runtimes"]
    Q3 -->|"yes"| EDGE
    Q3 -->|"no"| Q1
    Q1 -->|"yes"| SELF
    Q1 -->|"no"| Q2
    Q2 -->|"yes"| SELF
    Q2 -->|"no, but want open-model economics"| MANAGED
    Q2 -->|"no"| API

Two things the diagram can't capture:

  • Routes compose. Production systems routinely use all four: an API for the hard tail, a managed host for the open-model bulk, a self-hosted vLLM cluster for the VPC-bound tenant, and on-device for offline features. 8.2 builds that pattern.
  • "Open-weight" is orthogonal to "local." A managed host serves the same open weights you could download; the choice is who operates the engine, not whose weights. Don't let "we downloaded the model" talk you into row 1 when row 3 meets the requirement.

Part 2 — The open-weight landscape for serving#

Deep-dive

Lesson 02.9, Part 3 owns the model families — Llama, Qwen, Gemma, Mistral, DeepSeek, gpt-oss, the reasoning-model releases, and how licences differ. Do not re-learn that here. What changes when you serve them yourself:

2.1 What serving changes about model choice#

A model that wins on an API leaderboard may lose on your GPU. Three filters apply before quality:

  • Memory footprint vs your hardware. A 70B model at BF16 needs ~140 GB of weights — two 80 GB GPUs minimum, more once KV cache lands. The same model at 4-bit needs ~40 GB — one 48 GB card or a well-equipped Mac. Quantization (below) is the difference between "runs" and "doesn't."
  • Architecture support in your engine. Every runtime supports a subset of architectures. vLLM lists 200+ as of November 2026; llama.cpp's GGUF ecosystem covers most popular families but trails on brand-new architectures for days or weeks; MLX supports the mlx-community catalogue; SGLang and TensorRT-LLM each have their own supported-model pages. A model card saying "open weights" does not mean "your engine loads it."
  • Throughput per dollar. MoE models (the DeepSeek-V4 family, Qwen's 35B-A3B-style models, gpt-oss-120b, Meta's Muse Spark Open — see the 02.9 table) activate only a fraction of parameters per token — they deliver near-frontier quality at small-model speed if the engine's MoE kernels are good on your hardware. A dense 70B may be slower and more expensive than a 35B-A3B MoE despite similar quality. This is the single biggest throughput lever in open weights, and it is why gpt-oss-120b's "117B total / ~5B active" design matters operationally.

2.2 Quantization formats you will meet#

Quantization compresses the weights (and optionally the KV cache) to fewer bits. It is the main lever for fitting models on cheaper hardware — and the main source of "it fit but quality dropped" surprises. The formats, as of November 2026:

Format What it is Typical use Who makes it
GGUF llama.cpp's container format; stores tensors in many quant types (Q4_K_M, Q5_K_M, Q8_0, IQ*, etc.) CPU, Apple Silicon, edge, single-user local serving llama-quantize, community quants on HF
AWQ Activation-aware weight quantization to 4-bit GPU serving via vLLM/SGLang/TensorRT-LLM AutoAWQ toolkit, model authors
GPTQ Post-training quantization to 3–4 bit, with optional calibration GPU serving GPTQModel / AutoGPTQ
FP8 / FP8 variants 8-bit floating point weights (and often KV cache) H100/B200-class GPUs; near-lossless quality Model authors ship FP8 checkpoints; vLLM --quantization fp8
MXFP4 / NVFP4 4-bit microscaling formats (block-wise scales) designed for MoE experts gpt-oss models (MXFP4, required), Blackwell NVFP4 paths Model authors; vLLM/TensorRT-LLM support
bitsandbytes / compressed-tensors / TorchAO Library-level quantization formats vLLM's --quantization backends Transformers/PEFT ecosystem

Key operational facts:

  • Weight quantization and KV-cache quantization are different knobs. Weight quant shrinks the model file; KV-cache quant (--kv-cache-dtype in vLLM, OLLAMA_KV_CACHE_TYPE, MLX --kv-bits, llama.cpp flags) shrinks the per-request memory that grows with context length and concurrency. You can quantize weights and still OOM on KV cache — and vice versa. 3.1 quantifies this.
  • "4-bit" is not one thing. GGUF Q4_K_M (~4.9 bits/weight incl. overhead) is a different artifact than AWQ-4bit than MXFP4 than GPTQ-Int4. Quality rankings differ per model family; the only reliable check is your eval set.
  • The quant must match the runtime. A GGUF file runs on llama.cpp/Ollama/LM Studio (and vLLM via its GGUF plugin, with caveats); AWQ/GPTQ/FP8 safetensors run on vLLM/SGLang/TensorRT-LLM; MLX-format weights run on MLX tooling. You cannot feed a GGUF to vLLM's standard path or an AWQ checkpoint to llama.cpp.
  • Precision loss is real but bounded. 8-bit is near-lossless; 4-bit K-quants lose a little on hard tasks; sub-4-bit (IQ2, Q2_K) degrades noticeably — fine for chat demos, risky for extraction or tool-calling. The eval section below is how you measure it on your workload.

2.3 Licences and acceptable use — the deployment gate#

Weights come with two layers of terms: the model licence (Apache 2.0, MIT, Llama Community Licence, Gemma Terms, gpt-oss's Apache 2.0 + usage policy, etc.) and the provider's acceptable-use policy if you use a hosted route. Checklist before shipping:

  • Does the licence permit your use (commercial, redistribution, fine-tuning)? Some "open" licences restrict use above revenue thresholds or require "Built with X" attribution.
  • Does it permit serving to end users, or only research/internal use?
  • If you fine-tune or quantize, does the licence require releasing derivatives?
  • Hosted providers add their own AUP on top — a model being Apache 2.0 does not mean every host allows every use.

02.9, Part 3 owns the per-family licence survey. Treat the model card's licence field as a build-time gate: your pipeline should fail CI if the licence isn't on the approved list.

2.4 Tool calling, structured output, and context length on open models#

Not every open model does every API feature. As of November 2026:

  • Tool calling / function calling: supported by most instruct-tuned families (Llama, Qwen, Mistral, gpt-oss, DeepSeek distill) but with wildly varying reliability — weak models emit malformed tool calls or call tools when they shouldn't. Tool-call parsing is engine-side (vLLM's tool-call parsers, Ollama's tool support, SGLang's); model-side reliability is yours to measure.
  • Structured output / JSON schema: vLLM supports xgrammar/guidance backends (--structured-outputs-config.backend, default auto); SGLang supports it natively; Ollama exposes JSON mode and structured outputs for supported models; LM Studio implements response_format json_schema. But "the endpoint accepts the field" ≠ "the model fills it correctly" — grammar-constrained decoding guarantees syntax, not semantics.
  • Context length: model cards advertise e.g. 128K, but effective quality degrades well before the advertised max (the "lost in the middle" effect), and KV-cache memory scales linearly with context — serving a 128K-context model at high concurrency can need more memory than the weights. 02.7 owns context-window limits and behaviour; 04.7 owns budgeting what stays in the window over a long conversation; this lesson owns the memory math.
  • Reasoning/thinking models: open reasoning models (DeepSeek-R1 distills, Qwen3 thinking variants, gpt-oss with adjustable effort) emit long thinking traces — more tokens = more cost and latency, and different serving flags. Budget for it.

2.5 Prove it on your eval set#

The cardinal rule of open weights: the leaderboard is someone else's workload. Before committing to a self-hosted model:

  1. Pull the candidate weights (GGUF for local, safetensors for engines).
  2. Run your Module 10A eval set against it through whatever serving path you'll actually use (Ollama /v1, vLLM /v1, llama-server) — not a notebook, not a different quantization.
  3. Compare to your hosted-API baseline on the same eval harness.
  4. Check the failure modes that matter to you: tool-call validity, JSON-schema adherence, long-context recall, refusal behaviour, latency at your p95 concurrency.

Two ways to measure quantization damage, cheap then real. Distribution checks compare the quantized model with the full-precision one on a text sample: llama.cpp's llama-perplexity tool can record the FP16 model's logits once (--kl-divergence-base) and then report KL divergence, perplexity ratio and the share of tokens where the top choice is unchanged for each quant (--kl-divergence). They are fast and good for ranking quants of one model, but they say nothing about your task. Task evals (the numbered steps above) are the ones that decide. Run the cheap check first to discard hopeless quants, then spend your eval budget on the two or three survivors.

A 3-percentage-point eval gap that saves 60% of inference cost is a business decision, not a technical failure — but you can't make it without the numbers. Module 10A owns the eval machinery; this lesson just insists you run it against the served artifact, quantization included.


Part 3 — Hardware sizing: the VRAM arithmetic#

This is the part that separates "downloaded a model" from "can serve it in production." Memory is the binding constraint, and it's almost never just the weights.

3.1 The VRAM arithmetic#

Three memory consumers, in order of predictability:

1. Model weights. weights_bytes ≈ params × bits_per_weight / 8. A 7B model at BF16 ≈ 14 GB; at 4-bit ≈ 4 GB. Use the quantization table in 2.2.

2. KV cache — the one that bites you. Every concurrent request carries its own KV cache, sized by context_length. The formula:

text
KV bytes per token = 2 × n_layers × n_kv_heads × head_dim × bytes_per_element
KV bytes per request = above × context_tokens
KV bytes total = above × batch_size (concurrent sequences)

The 2 is for K and V. n_kv_heads is the GQA size (often much smaller than n_heads — Llama 3.1 8B has 32 query heads but only 8 KV heads). bytes_per_element is 2 for FP16, 1 for FP8, 0.5 for INT4/NVFP4 KV cache. Lesson 02.4, §11.4 already derived this arithmetic and worked the Llama-3.1-8B figure; the production consequence is that KV cache can exceed weight memory under long context and high concurrency — and, as the calculator below shows, hybrid architectures don't follow the dense formula at all.

3. Runtime overhead. CUDA context, framework buffers, activation scratch, the engine's own bookkeeping — typically 5–15% of GPU memory, plus whatever the engine reserves (--gpu-memory-utilization default 0.9 in vLLM means it targets 90%, leaving headroom). Add ~10% headroom minimum.

Worked example — Llama-3.1-8B on one 24 GB GPU:

  • Weights at Q4_K_M: ~4.9 GB
  • KV cache at FP16, 8 concurrent × 32K context: 2 × 32 layers × 8 KV heads × 128 head_dim × 2 bytes = 131 KB/token; × 32,768 tokens × 8 requests ≈ 34.4 GB
  • Total: ~39 GB needed on a 24 GB card → doesn't fit

The fix isn't a bigger GPU necessarily — it's fewer concurrent slots, shorter context, KV-cache quantization (Ollama's OLLAMA_KV_CACHE_TYPE=q8_0 halves it; q4_0 quarters it), or a smaller model. This is the "weights fit but OOMs under context/concurrency" failure, and it is the most common sizing mistake.

The calculator. Run this (stdlib only, save as gpu_sizing.py):

python
"""GPU sizing calculator for self-hosting an open-weight model.

Stdlib only. Estimates:
  - weight memory at a given quantization (bits per weight)
  - KV-cache memory per concurrent sequence at a given context length
  - total VRAM needed, and whether a given GPU fits
  - rough cost per 1M tokens at a given utilisation
"""

BYTES_PER_WEIGHT = {
    # name: (bits per weight, note)
    "bf16": (16.0, "full precision"),
    "fp8": (8.0, "8-bit float"),
    "q8_0": (8.5, "GGUF 8-bit (incl. scales)"),
    "q6_k": (6.5625, "GGUF 6-bit K-quant"),
    "q5_k_m": (5.5, "GGUF 5-bit K-quant medium"),
    "q4_k_m": (4.9, "GGUF 4-bit K-quant medium (incl. overhead)"),
    "q4_0": (4.5, "GGUF plain 4-bit"),
    "mxfp4": (4.25, "MXFP4 tensors only — check modules_to_not_convert"),
    "gpt-oss": (5.25, "gpt-oss checkpoint effective bpw: MXFP4 experts + "
                      "BF16 attention/router/embeddings (~13.8 GB file)"),
}


def weights_gb(params_b, quant):
    bits = BYTES_PER_WEIGHT[quant][0]
    return params_b * 1e9 * bits / 8 / 1e9


def kv_cache_gb_per_seq(layers, kv_heads, head_dim, ctx_tokens,
                        bytes_per_elem=2.0, batch=1,
                        full_attn_layers=None, sliding_window=None):
    """KV cache in GB for `batch` sequences of `ctx_tokens`.

    KV bytes = 2 (K and V) x layers x kv_heads x head_dim x ctx x bytes.

    Most models are dense full-attention: every layer's cache grows with
    context. Hybrid architectures break the naive formula — check
    `layer_types` in the model's config.json:
      - sliding-window layers (gpt-oss alternates them, window=128) cap
        their cache at `sliding_window` tokens; pass
        full_attn_layers=<layers that grow with ctx> and sliding_window.
      - linear-attention layers (Qwen3.6's Gated DeltaNet) carry a
        fixed-size recurrent state per sequence, not per-token KV — pass
        only the attention layers in `layers`; the state is small but
        not zero (~60 MB/seq for Qwen3.6-35B-A3B at fp32).
    """
    if full_attn_layers is None:
        full_attn_layers, sliding_layers = layers, 0
    else:
        sliding_layers = layers - full_attn_layers
    per_layer_token = 2 * kv_heads * head_dim * bytes_per_elem
    tokens_per_seq = (full_attn_layers * ctx_tokens
                      + sliding_layers
                      * min(ctx_tokens, sliding_window or ctx_tokens))
    return per_layer_token * tokens_per_seq * batch / 1e9


def report(name, params_b, quant, layers, kv_heads, head_dim,
           ctx, concurrency, gpu_gb, gpu_hourly, tok_per_sec, util,
           full_attn_layers=None, sliding_window=None):
    w = weights_gb(params_b, quant)
    kv = kv_cache_gb_per_seq(layers, kv_heads, head_dim, ctx, batch=concurrency,
                             full_attn_layers=full_attn_layers,
                             sliding_window=sliding_window)
    total = w + kv
    fits = "FITS" if total <= gpu_gb * 0.92 else "DOES NOT FIT"
    tok_per_hour = tok_per_sec * 3600 * util
    cost = gpu_hourly / tok_per_hour * 1e6 if tok_per_hour else float("inf")
    print(f"--- {name} ---")
    print(f"  quant={quant:<8} weights={w:6.1f} GB   KV cache ({concurrency} x {ctx//1024}K ctx)={kv:6.1f} GB")
    print(f"  total needed={total:6.1f} GB on a {gpu_gb:.0f} GB GPU -> {fits} (8% headroom assumed)")
    print(f"  at {tok_per_sec:.0f} tok/s, {util:.0%} utilisation: ${cost:,.2f} per 1M tokens")
    print()
    return total, cost


# Llama 3.1 8B: 32 layers, 8 KV heads (GQA), head_dim 128 -> matches 02.1/04 figures
report("Llama-3.1-8B on one 24GB GPU, 4-bit, 8 concurrent 32K chats",
       params_b=8, quant="q4_k_m", layers=32, kv_heads=8, head_dim=128,
       ctx=32_768, concurrency=8, gpu_gb=24, gpu_hourly=0.8,
       tok_per_sec=120, util=0.6)

# gpt-oss-20b: 24 layers alternate sliding_attention/full_attention
# (sliding_window=128) — only the 12 full-attention layers grow KV with
# context. Checkpoint is MXFP4 experts + BF16 attention/router/embeddings.
report("gpt-oss-20b on one 24GB GPU, 4 concurrent 32K chats",
       params_b=21, quant="gpt-oss", layers=24, kv_heads=8, head_dim=64,
       full_attn_layers=12, sliding_window=128,
       ctx=32_768, concurrency=4, gpu_gb=24, gpu_hourly=0.8,
       tok_per_sec=180, util=0.6)

# Qwen3.6-35B-A3B: hybrid MoE — 30 Gated DeltaNet linear-attention layers
# carry a fixed recurrent state; only the 10 Gated Attention layers grow
# per-token KV (2 KV heads, head_dim 256). Memory follows TOTAL params;
# speed follows ACTIVE (~3B).
report("Qwen3.6-35B-A3B Q4 on one 80GB GPU, 16 concurrent 32K chats",
       params_b=35, quant="q4_k_m", layers=10, kv_heads=2, head_dim=256,
       ctx=32_768, concurrency=16, gpu_gb=80, gpu_hourly=2.5,
       tok_per_sec=900, util=0.7)

# Same model at BF16 weights on 2x80GB (tensor parallel)
w = weights_gb(35, "bf16")
kv = kv_cache_gb_per_seq(10, 2, 256, 32_768, batch=16)
print(f"--- Qwen3.6-35B-A3B BF16 on 2x80GB ---")
print(f"  weights={w:.1f} GB  KV={kv:.1f} GB  total={w+kv:.1f} GB "
      f"-> {'FITS' if w+kv <= 160*0.92 else 'DOES NOT FIT'}")
print()
Output17 lines
--- Llama-3.1-8B on one 24GB GPU, 4-bit, 8 concurrent 32K chats ---
  quant=q4_k_m   weights=   4.9 GB   KV cache (8 x 32K ctx)=  34.4 GB
  total needed=  39.3 GB on a 24 GB GPU -> DOES NOT FIT (8% headroom assumed)
  at 120 tok/s, 60% utilisation: $3.09 per 1M tokens

--- gpt-oss-20b on one 24GB GPU, 4 concurrent 32K chats ---
  quant=gpt-oss  weights=  13.8 GB   KV cache (4 x 32K ctx)=   3.2 GB
  total needed=  17.0 GB on a 24 GB GPU -> FITS (8% headroom assumed)
  at 180 tok/s, 60% utilisation: $2.06 per 1M tokens

--- Qwen3.6-35B-A3B Q4 on one 80GB GPU, 16 concurrent 32K chats ---
  quant=q4_k_m   weights=  21.4 GB   KV cache (16 x 32K ctx)=  10.7 GB
  total needed=  32.2 GB on a 80 GB GPU -> FITS (8% headroom assumed)
  at 900 tok/s, 70% utilisation: $1.10 per 1M tokens

--- Qwen3.6-35B-A3B BF16 on 2x80GB ---
  weights=70.0 GB  KV=10.7 GB  total=80.7 GB -> FITS

Four things to internalize from that output:

  • KV cache dominates at long context — for dense attention. In the Llama case the KV cache is seven times the weights. But look at the two hybrid models: gpt-oss's alternating sliding-window layers and Qwen3.6's linear-attention layers mean most layers don't grow a per-token cache at all. The naive layers × ctx formula overestimates these models by ~4×.
  • The formula assumes dense full-attention transformers. Real config.json files tell the truth: gpt-oss-20b has layer_types alternating sliding_attention/full_attention with sliding_window: 128 (only 12 of 24 layers grow with context, head_dim 64 not 128); Qwen3.6-35B-A3B has 30 linear_attention (Gated DeltaNet) layers carrying a fixed recurrent state of tens of MB per sequence and only 10 full_attention layers (num_key_value_heads: 2, head_dim: 256). Hybrid and linear-attention architectures are now common — Qwen3-Next and successors — so always read layer_types, num_key_value_heads and head_dim from the config before trusting the arithmetic. Some engines exploit the sliding-window bound (allocating only 128 tokens of KV for those layers); others allocate full context anyway — the gpt-oss verdict is FITS either way (~20 GB worst case), but check your engine's docs.
  • MoE changes the throughput math, not the memory math. Qwen3.6-35B-A3B activates ~3B parameters per token (900 tok/s aggregate) but still needs memory for all 35B of weights — you get speed without the memory savings. Pick MoE for throughput; pick dense-small for memory.
  • Quantization buys headroom for concurrency — but check what the quant actually covers. The same Llama-8B at Q8_0 (~8.5 bits) would need ~8.5 GB weights but identical KV cache — quantization helps weights, not KV. And "MXFP4" for gpt-oss means MXFP4 experts with attention, router and embeddings left in BF16 — the real checkpoint is ~13.8 GB, not the ~11 GB a naive 4.25-bpw estimate gives. For KV you need KV-cache quantization or fewer/smaller requests.

3.2 CPU vs GPU vs unified memory#

  • Discrete GPU (NVIDIA CUDA, AMD ROCm): the production path for vLLM/SGLang/TensorRT-LLM. VRAM is the wall; H100/B200 80GB is the current sweet spot for 70B-class and MoE models. Consumer cards (RTX 4090/5090, 24–32 GB) run 7–14B quantized models fine for dev and light serving.
  • Apple Silicon unified memory: no VRAM wall — the GPU shares system RAM. A 128 GB Mac can hold a 70B 4-bit model plus KV cache that would never fit on a 24 GB card. MLX and llama.cpp (Metal backend) exploit this; LM Studio wraps both. Bandwidth (~400–800 GB/s) is the limit, not capacity — expect lower tok/s than a datacenter GPU but far better than CPU.
  • CPU-only: llama.cpp and Ollama run anywhere, but throughput is 5–20× lower than GPU for the same model. Fine for batch/offline/dev, painful for interactive serving. Modern CPUs with AVX-512/AMX help; quantized models help more.
  • Integrated / edge NPUs: phones, browsers (WebGPU via WebLLM), Apple Neural Engine via Core AI — see 8.3. Capability is limited to small models (~1–8B) but latency and privacy are unbeatable.

3.3 Throughput, batching, and latency#

Three regimes, three different bottlenecks:

  • Single request, low latency (chat, autocomplete): decode-bound; tokens/sec is roughly fixed per model/hardware. Batch size 1 is the latency floor.
  • Concurrent requests (production serving): the engine batches decode across sequences — vLLM's continuous batching, SGLang's scheduler, llama.cpp's -np parallel slots. Throughput scales with batch until memory saturates, then preemption/queuing kicks in. This is why "the model fits" ≠ "the model serves."
  • Long context (RAG, agents): prefill-bound; processing a 32K prompt costs more compute than generating 500 tokens. Prefix caching (7.3) amortizes repeated prefixes — the difference between 200ms and 5s time-to-first-token on shared system prompts.

The benchmark skeleton in Part 10 measures your actual tok/s at your actual concurrency — run it before committing to a GPU size.

3.4 Cost per million tokens#

Self-hosted cost per 1M tokens = GPU_hourly × GPUs / (tok_per_sec × 3600 × utilisation) × 1e6. The calculator above already prints this per scenario. Compare against your API quote blended for your input/output ratio (03.7 owns cost tracking). Remember: the GPU is billed whether it generates tokens or not — a $2.50/hr GPU at 900 tok/s costs ~$7.72 per 1M tokens at 10% utilisation and ~$0.86 at 90% (the table in 1.2) — a 9× swing from the same hardware. Utilisation is the entire game.


Part 4 — Local runtimes: the laptop tier#

These four run on a developer machine — CPU, consumer GPU, or Apple Silicon — and share one job: turn a downloaded model file into an HTTP endpoint your code can call. They are not production serving engines (no continuous batching at scale, no multi-tenant isolation); they are for development, prototyping, light internal use, and offline/edge work. Production engines are Part 5.

4.1 Ollama — the easiest on-ramp#

Ollama (v0.40.15 as of 8 November 2026; it ships several releases a week, so check the releases page) wraps llama.cpp-style inference behind a dead-simple CLI and a local REST API on http://localhost:11434. You ollama pull qwen3 and ollama run qwen3, or point an OpenAI-compatible client at http://localhost:11434/v1.

What it actually is under the hood: a Go server that manages model files in ~/.ollama/models, loads them into memory on demand, and serves both its native API (/api/chat, /api/generate) and OpenAI-compatible endpoints (/v1/chat/completions, /v1/responses since v0.13.3, non-stateful only) plus Anthropic Messages API (/v1/messages since v0.14.0, with tools/thinking/vision support). As of November 2026 it also offers cloud-hosted models via ollama.com through OLLAMA_API_KEY — the same client, remote weights.

The Modelfile is how you customize a model without code — FROM a base, set PARAMETERs, SYSTEM prompt, TEMPLATE, LICENSE, CAPABILITY. The parameter that bites people is num_ctx — the context the server allocates KV cache for. Its default is VRAM-dependent: the context-length docs give 4K tokens under 24 GiB VRAM, 32K for 24–48 GiB, and 256K at ≥48 GiB (the FAQ still says a flat 4096 and older Modelfile references print 2048 — the docs disagree with each other, so don't memorise a number). Check what was actually allocated with ollama ps (the CONTEXT column) and set num_ctx explicitly for long-context work:

dockerfile
# Modelfile — reference example, not run in this lesson
FROM qwen3:8b
PARAMETER num_ctx 32768
PARAMETER temperature 0.7
SYSTEM You are a careful coding assistant.
bash
ollama create my-qwen -f Modelfile   # build the custom model
ollama run my-qwen                   # chat with it

The environment variables that matter for capacity (from ollama serve env config, version-sensitive):

Variable Default Effect
OLLAMA_KEEP_ALIVE 5m How long a model stays loaded after last use; -1 = forever, 0 = unload immediately. The /api/chat request can also set keep_alive per-call (duration string, seconds, negative=forever, 0=unload now).
OLLAMA_NUM_PARALLEL 1 Parallel request slots per loaded model — the batching knob. 1 = one request at a time; higher = continuous-batching-like concurrency at the cost of KV memory per slot.
OLLAMA_MAX_LOADED_MODELS 3 × GPUs (3 on CPU-only) How many models stay resident simultaneously, provided they fit in memory.
OLLAMA_MAX_QUEUE 512 Requests queued before rejection.
OLLAMA_FLASH_ATTENTION automatic where the backend and device support it 1 forces the flash-attention kernel on, 0 turns it off. It is required for KV-cache quantization to take effect.
OLLAMA_KV_CACHE_TYPE f16 KV cache precision: f16/q8_0/q4_0. Requires flash attention. q8_0 halves KV memory, q4_0 quarters it — small quality cost.
OLLAMA_CONTEXT_LENGTH model default Override the context window the server allocates KV cache for.
OLLAMA_HOST / OLLAMA_MODELS 127.0.0.1:11434 / ~/.ollama/models Bind address and model storage path.

OpenAI-compatible surface (as of v0.40.x): /v1/chat/completions (streaming, JSON mode, tools, vision, reasoning control for thinking models), /v1/completions, /v1/responses (non-stateful), /v1/models, /v1/embeddings. Anthropic-compatible: /v1/messages with system prompts, multi-turn, tool calling, extended thinking, vision. Point the existing openai/anthropic SDKs at base_url/baseURL — the same provider-swap pattern as 11C.3.

Where Ollama fits: dev machines, CI stand-ins (03.1 Part 12), single-user local assistants, quick eval baselines. It is not the tool for multi-tenant production serving — OLLAMA_NUM_PARALLEL gives you a few slots, not a serving engine. For that, Part 5.

4.2 llama.cpp and llama-server — the engine underneath#

llama.cpp (v0.9.0 released 4 November 2026; continuous b#### pre-releases between) is the C/C++ inference engine that made local LLMs practical. It runs on CPU, CUDA, Metal, Vulkan, ROCm, SYCL and more; it's what Ollama and LM Studio wrap, and what WebLLM-style runtimes descend from. The GGUF format is its native weight container.

llama-server is its built-in HTTP server — OpenAI-compatible /v1/chat/completions, /v1/completions, /v1/embeddings, plus a web UI. The flags that matter:

bash
# reference — llama-server, run on your own machine when ready
llama-server \
  -m ./qwen3-8b-Q4_K_M.gguf \
  -c 32768 \
  -ngl 99 \
  -np 4 \
  --jinja \
  -a my-model \
  --api-key "$LOCAL_KEY"

(No comments after the backslashes: in a shell, a \ must be the last character on the line, so a trailing comment would break the command.) What each flag does: -c is the context size the KV cache is allocated for; -ngl 99 offloads up to 99 layers to the GPU (0 = CPU only); -np 4 is the number of parallel slots; --jinja enables the model's Jinja chat template, which tool calls need; -a my-model is the alias shown in /v1/models; --api-key requires a bearer token on the /v1 endpoints.

Key capacity flags: -c sets the context per slot — -c 32768 -np 4 allocates KV for 4×32K; --parallel is the concurrency knob; -ngl controls GPU offload (partial offload is possible — some layers on GPU, rest on CPU, which is how big models run on small VRAM slowly); --kv-unified and cache-type flags control KV memory; --flash-attn enables the fast attention path. llama.cpp also has llama-quantize to convert safetensors→GGUF and requantize between quant types, and llama-cli/llama-bench for interactive/benchmark runs.

Where it fits: maximum control, minimum dependencies, edge/embedded deployments, converting quantizing and benchmarking models, platforms where you can't install a full framework. It's the substrate under Ollama/LM Studio and the reference implementation for GGUF.

4.3 LM Studio — the GUI wrapper#

LM Studio is a desktop application (macOS, Windows, Linux) that bundles model download, GGUF/MLX inference engines, and a local server behind a friendly UI. As of November 2026:

  • lms CLI (npx lmstudio install-cli) for scripting; lms get <model>, lms load, lms server start.
  • Local server on port 1234 by default, bindable to LAN for other devices.
  • OpenAI-compatible endpoints: /v1/models, /v1/chat/completions, /v1/completions, /v1/responses, /v1/embeddings, /v1/decisions; Anthropic-compatible endpoints too.
  • Two engines: llama.cpp (GGUF models) and MLX (Apple Silicon, MLX-format models) — you pick per model.
  • Structured output via response_format json_schema; tool use; JIT model loading.

Where it fits: the fastest way for a developer to try a model on their own hardware, prototype against a local OpenAI-compatible endpoint, or serve a model to a couple of LAN devices. It's a development tool, not a production server — no multi-tenancy, no serious concurrency story, and "serve on LAN" means your model endpoint is on the local network with whatever auth LM Studio provides (check its docs for the current auth options).

4.4 MLX / mlx-lm — Apple Silicon native#

MLX is Apple's array framework for Apple Silicon; mlx-lm (MIT licence) is the LLM package on top. It exploits unified memory — the GPU shares system RAM, so a 128 GB Mac can hold models that would need multiple datacenter GPUs.

bash
# reference — mlx-lm on Apple Silicon
pip install mlx-lm
mlx_lm.server --model mlx-community/Qwen3-8B-4bit --port 8080
# serves OpenAI-style /v1/chat/completions on http://127.0.0.1:8080

Key commands: mlx_lm.generate/mlx_lm.chat for interactive use, mlx_lm.convert -q to convert+quantize HF models to MLX format (4-bit/8-bit), mlx_lm.server for the OpenAI-compatible endpoint, mlx_lm.cache_prompt for prompt caching. Capacity flags: --max-kv-size (rotating KV cache — smaller = less RAM, worse long-context quality), --kv-bits (quantize KV cache — but disables batching), --prefill-step-size (chunked prefill to bound peak memory). For very large models relative to RAM, macOS 15+ lets you raise the wired-memory limit via sudo sysctl iogpu.wired_limit_mb=N — the docs warn about this carefully.

Important caveat from the docs: mlx-lm's server is explicitly not recommended for production — it implements only basic security checks and expects 127.0.0.1. Treat it as a local dev/serving tool on your own machine, exactly like the others in this part.

Where it fits: Apple Silicon workstations that need to run models too big for their GPU's discrete memory would suggest — the 70B-on-a-Mac-Pro use case. Pair it with LM Studio (which wraps MLX) or use mlx_lm directly when you want the Python API (mlx_lm.load, generate, stream_generate).


Part 5 — Production serving engines#

When you move from "run a model on my laptop" to "serve it to users," you need an engine built for throughput, concurrency, and uptime. These are the production-grade options as of November 2026, all of which expose OpenAI-compatible APIs so your application code barely changes.

5.1 vLLM — the default choice#

vLLM (v0.33.0 on PyPI, Apache-2.0) is the most widely deployed open serving engine. Its core innovations, all documented and current:

  • PagedAttention — treats the KV cache like OS virtual memory: non-contiguous blocks, near-zero waste. This is what makes high concurrency affordable.
  • Continuous batching — requests join and leave the batch every decode step instead of waiting for the batch to finish. Combined with chunked prefill, this keeps GPUs saturated across mixed request lengths.
  • Prefix caching — hash-based reuse of KV blocks for shared prefixes (system prompts, RAG context, few-shot examples). Enabled by default in the V1 engine with near-zero overhead; --no-enable-prefix-caching disables it. 7.3 covers when it helps and its tenant-isolation caveat.
  • Quantization breadth — --quantization accepts fp8, mxfp4/nvfp4, int8/int4 variants, awq, gptq, gguf (via the vllm-gguf-plugin extra), compressed-tensors, modelopt, torchao, bitsandbytes — with hardware-dependent support.
  • Structured outputs — --structured-outputs-config.backend (default auto) selects xgrammar or guidance; structured_outputs request field supports JSON schema, regex, choice, grammar, structural tags. (Older guided_* fields were removed in current versions — check the docs for your pinned version.)
  • Speculative decoding — n-gram, suffix, EAGLE, DFlash draft-model schemes for 1.5–3× decode speedup on supported setups.
  • LoRA serving — --enable-lora --lora-modules name=path loads adapters; requests pick one via the model field; --max-lora-rank, --max-loras bound memory.
  • Parallelism — three different axes, and the choice matters: --tensor-parallel-size shards one model's weights across GPUs (needed when a model exceeds one GPU's memory; every layer's activations cross GPUs each step, so it wants a high-bandwidth fabric — NVLink or InfiniBand — and all ranks live and die together); --pipeline-parallel-size splits the model into stages across GPUs (for very deep models, at the cost of pipeline bubbles); --data-parallel-size runs independent replicas of the whole model, one per GPU or node — no fabric requirement between them and separate failure domains, which is usually what you want for serving throughput. Expert/context parallelism covers MoE and long-context sharding.
  • Endpoints — OpenAI-compatible /v1/chat/completions (+batch), /v1/completions, /v1/responses, /v1/decisions, /v1/embeddings, audio endpoints; plus Anthropic Messages API and gRPC.

Launch (Docker or pip; reference, for your own GPU machine when you are ready):

bash
# vLLM OpenAI-compatible server, reference
vllm serve Qwen/Qwen3-32B \
  --tensor-parallel-size 2 \
  --max-model-len 32768 \
  --gpu-memory-utilization 0.9 \
  --enable-lora \
  --lora-modules support-v1=/models/lora-support-v1

Or the Docker image vllm/vllm-openai with the model name as the command argument.

⚠️ Security gotcha that matters: --api-key / VLLM_API_KEY protects only endpoints under the /v1, /v2, /inference, and /cohere path prefixes — everything else on the same HTTP server is unauthenticated. That includes not just the SageMaker-style /invocations inference endpoint but operational endpoints like /pause, /resume, /abort_requests, /update_weights, /metrics and /load — an attacker who can reach the port can stall or reconfigure your server without a token, not merely spend your GPU. For any network-exposed deployment, put a reverse proxy (nginx, your gateway) in front that allowlists only the paths your clients need and enforces auth, rate limits and logging on them, or restrict to a private network. vLLM's own security guide says not to rely exclusively on --api-key, and to never set VLLM_SERVER_DEV_MODE=1 in production (it adds endpoints such as /collective_rpc and /sleep that the guide calls extremely dangerous). Leave profiler endpoints off too. This is the single most common self-hosted security mistake.

When to choose vLLM: default for NVIDIA GPU production serving; the broadest model/quant support; the most documentation and community; LoRA multi-adapter serving; when you need OpenAI + Anthropic + gRPC surfaces.

5.2 SGLang — the radix-cache alternative#

SGLang (Apache-2.0, sglang on PyPI, Docker lmsysorg/sglang) is vLLM's main competitor, developed by the LMSYS team behind Chatbot Arena. Its differentiator is RadixAttention — a radix-tree KV cache that automatically shares prefixes across requests and enables efficient session/tree-structured workloads (multi-turn chats, agents that branch). Other features:

  • Continuous batching, paged attention, tensor parallelism (--tp), data parallelism (--dp), pipeline parallelism, expert parallelism for MoE.
  • Chunked prefill (--chunked-prefill-size), structured outputs, quantization (FP8/INT4/AWQ/GPTQ), multi-LoRA batching.
  • OpenAI-compatible /v1 endpoints plus native endpoints (/generate, /encode, /classify, /score, etc.).
  • Broad hardware support: NVIDIA, AMD, Google TPU (via SGLang-TorchTPU/JAX), Intel GPU/CPU, Apple Silicon via MLX backend, Huawei Ascend, and more — unusually wide for a serving engine.
  • Strong in RL rollout and agentic workloads (used by training frameworks like miles, slime, verl for rollout generation).
bash
# reference — SGLang launch
python -m sglang.launch_server \
  --model-path Qwen/Qwen3-32B \
  --tp 2 \
  --port 30000
# or: sglang serve ...  (newer CLI)

When to choose SGLang: workloads with heavy shared prefixes (agents, multi-turn sessions), RL/training-rollout pipelines, hardware where its backend is the better-supported one (its docs list NVIDIA, AMD, Intel Xeon, Google TPU, Ascend NPU and Moore Threads), or when RadixAttention's tree-structured caching beats vLLM's flat prefix cache for your access pattern. vLLM also runs on AMD ROCm, Intel XPU, CPUs and (via vLLM-Metal) Apple Silicon, so "non-NVIDIA" alone is not a reason to switch engines: read both support matrices for your exact accelerator and model, then benchmark.

5.3 NVIDIA TensorRT-LLM and Triton Inference Server#

The NVIDIA-native stack, for when you're already in the CUDA/TensorRT ecosystem:

  • TensorRT-LLM compiles models into optimized TensorRT engines — the highest-performance path on NVIDIA hardware, with NVFP4/FP8 quantization, in-flight batching, paged KV cache, and trtllm-serve providing an OpenAI-compatible server (/v1/chat/completions, /v1/completions, /v1/models, /health, /metrics).
  • Triton Inference Server is NVIDIA's general model-server; its TensorRT-LLM backend (the "LLM API" / PyTorch backend) serves HF models without manual engine compilation. Triton handles model management, ensembles, and multi-model serving.
  • Status notes (as of November 2026): the legacy convert_checkpoint.py + trtllm-build engine-build workflow is deprecated in favour of the PyTorch-backend LLM API; NVIDIA ships nvcr.io/nvidia/tritonserver:26.10-trtllm-python-py3-style containers. TensorRT-LLM is powerful but has the steepest operational complexity — engine compilation, version-specific containers, NVIDIA-only.

When to choose: existing NVIDIA/Triton shops, maximum single-model throughput on NVIDIA hardware, NVFP4-optimized deployments (gpt-oss-120b on Blackwell), or when you need Triton's multi-model management.

5.4 TGI is archived, and TEI belongs to Module 06#

Hugging Face TGI (Text Generation Inference) reached end of life: maintenance mode announced 11 December 2025, repository archived 21 March 2026, last release v3.3.7. HF's own docs now recommend vLLM, SGLang, llama.cpp, or MLX for new deployments. If you inherit a TGI deployment: it still runs, but plan migration — don't start new projects on it.

TEI (Text Embeddings Inference) is HF's Rust-based embedding server — separate project, still relevant for embeddings, but lesson 06.1 Part 4 owns it. This lesson links rather than re-teaches.

5.5 Choosing an engine — the honest comparison#

Engine Best for Hardware OpenAI API Prefix cache Quant LoRA Maturity
vLLM Default NVIDIA production serving NVIDIA (primary), AMD, CPU ✅ + Anthropic + gRPC ✅ default-on (V1) ✅ widest ✅ multi-adapter Most mature, most docs
SGLang Agents/shared prefixes, RL rollouts, wide hardware support NVIDIA, AMD, Intel Xeon, TPU, Ascend (per its docs) ✅ + native endpoints ✅ RadixAttention ✅ FP8/INT4/AWQ/GPTQ ✅ batching Mature, growing
TensorRT-LLM/Triton Max NVIDIA perf, NVFP4, multi-model NVIDIA only ✅ via trtllm-serve ✅ ✅ NVFP4/FP8 ✅ Powerful, complex
TGI Legacy only — archived Mar 2026 NVIDIA, CPU ✅ partial ✅ ✅ Archived — don't start new
llama.cpp server Edge/embedded/light serving CPU, all GPUs, Apple ✅ basic limited ✅ GGUF native ✅ Very mature, not a prod engine
Ollama/LM Studio/MLX Dev/prototype/local Laptop-class ✅ limited ✅ partial Dev tools, not prod

The pragmatic default: vLLM on NVIDIA for production; SGLang if your workload is agent/prefix-heavy or its backend suits your silicon better; TensorRT-LLM only if you're already an NVIDIA shop chasing last-mile performance. Everything else in this table is either a dev tool or legacy.


Part 6 — Managed open-model hosting#

Deep-dive

The middle route from 1.1: the provider runs the serving engine (vLLM, SGLang, llama.cpp, or their own) on their GPUs and exposes an OpenAI-compatible API. You get open-weight economics and data-boundary flexibility without operating GPUs. As of November 2026:

6.1 Hugging Face Inference Endpoints#

HF's own dedicated-endpoint product: pick a model from the Hub, pick an instance type (CPU or GPU, billed per minute by hourly rate — GPU instances from roughly $0.5/hr depending on class), choose an engine (vLLM, SGLang, llama.cpp, TGI-deprecated, TEI, or custom container), and HF deploys it with Hub-integrated weight downloads. Requires an HF account with a subscription and credits; an Enterprise tier adds SLAs and uptime guarantees. Best when you want the HF ecosystem (private repos, gated models, the Hub workflow) with managed ops.

6.2 The GPU clouds — serverless to dedicated#

These split into two shapes: serverless/shared-fleet (pay per token, provider manages everything) and dedicated/deploy-your-own (you bring weights or a container, they run it on reserved GPUs).

Provider Shape What it's known for (as of Nov 2026)
Together AI Serverless catalogue + dedicated + fine-tuning Per-token serverless models (its docs list 83 serverless models across chat, image, video and audio, 22 of them chat, as of 8 November 2026 — the serverless list is much smaller than the full Hub, and rerank/embedding models are dedicated-only); dedicated endpoints and GPU clusters when volume justifies it
Fireworks AI Serverless + dedicated + post-training Pay-per-token serverless models; on-demand dedicated GPUs with autoscaling; supervised and reinforcement fine-tuning (its docs say models up to 1T+ parameters); an OpenAI-compatible migration path. Check its docs for adapter limits before planning a many-LoRA design
Groq Serverless on LPU hardware Very low latency on a narrow, open-weight-only catalogue that changes; per-token; free tier with rate limits. In December 2025 Groq signed a non-exclusive licence of its inference technology to NVIDIA, and on 22 June 2026 it announced $650M to expand GroqCloud, which it says keeps running — still, check the model list and your volume limits before depending on one model
Cerebras Serverless on wafer-scale WSE Very high published tokens/sec on a very small catalogue that is added to and retired at short notice (query the models endpoint rather than trusting a blog list); per-token, plus contract-based dedicated inference
Baseten Dedicated model APIs + GPU deployments Model APIs plus dedicated inference; Truss packaging; for teams that want control without self-operating
Modal Serverless Python functions with GPUs Python decorators → GPU containers; sub-second cold-start claims; full code control; consumption billing; best when inference is code, not just a model name
Replicate Prediction API + Cog packaging Huge public model marketplace (50,000+ models per Cloudflare's announcement); Cog container format → push and get an API; good for long-tail/multimodal models. Joined Cloudflare (announced 17 November 2025), which said existing APIs and workflows continue without interruption
RunPod Serverless workers + pods Bring-your-own container; queue-based (/run//runsync) or load-balanced HTTP endpoints; scale-to-zero or warm workers; per-second billing; has a managed vLLM endpoint option

The choice pattern:

  • Fastest to production, pay per token → Together, Fireworks, Groq, or Cerebras (pick by model availability and latency needs).
  • Your own fine-tuned weights, managed → Fireworks, Together, Baseten, or HF Endpoints.
  • Custom inference code / non-standard pipeline → Modal, RunPod, Replicate (bring a container).
  • Cheapest raw GPU for self-managed engines → RunPod pods/serverless, Lambda, Vast.ai (you're back to row 2 of 1.1 — you operate the engine).
  • Aggregator route → OpenRouter already resells many of these plus closed models behind one key and one bill — the 11C.3 gateway makes it a fallback target.

6.3 What "OpenAI-compatible" does and doesn't guarantee#

Every route above — self-hosted vLLM, Ollama, LM Studio, managed hosts, OpenRouter — exposes an OpenAI-shaped API. That buys you base_url portability and reuse of the openai SDK. It does not guarantee:

  • Same model weights (a "Llama-3.3-70B" on host A may be a different quant than host B).
  • Same feature support (structured outputs, tool calling, vision, reasoning fields differ per host and per model).
  • Same latency/throughput characteristics.
  • Same uptime/SLA (serverless shared fleets have noisier neighbours than dedicated endpoints).

Treat the OpenAI-compatible surface as an adapter boundary — your code targets the common subset, and a capability probe (7.1) verifies what each route actually supports. This is the same lesson 03.11 taught for providers, now applied to self-hosted and managed open-model endpoints.


Part 7 — Serving in production#

Deep-dive

Running an engine is the easy half; running it reliably is the lesson. Everything here assumes a production engine from Part 5 (vLLM/SGLang/TRT-LLM) behind your gateway from 11C.3.

7.1 The OpenAI-compatible surface and the provider swap#

Because every route speaks OpenAI-shaped API, your application targets one interface:

python
# reference — point the existing OpenAI client at any OpenAI-compatible server
from openai import OpenAI

# hosted frontier API
prod = OpenAI()  # reads OPENAI_API_KEY, OPENAI_BASE_URL from env

# self-hosted vLLM on the GPU box
local_vllm = OpenAI(base_url="http://gpu-box.internal:8000/v1",
                    api_key="dummy")  # vLLM ignores it unless --api-key set

# Ollama on the dev laptop
ollama = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")

# llama-server
llamacpp = OpenAI(base_url="http://localhost:8080/v1", api_key="local-key")

# managed host (Together/Fireworks/etc — each has its own base_url + key)
managed = OpenAI(base_url="https://api.together.xyz/v1", api_key="...")

The same chat.completions.create(model=..., messages=...) call works on all of them. What changes is the model string (an HF repo id, an Ollama tag, an alias you configured), the supported parameters, and the failure modes. Route through your 11C.3 gateway so a self-hosted replica can be a fallback target for a hosted primary — or vice versa. What your client should still own when a gateway sits in front is covered in 03.11, 13.8b.

Capability probing: before routing real traffic to a new open-model endpoint, verify it actually supports what your app sends — response_format (structured output), tools, stream, max_tokens, vision image_url parts, reasoning_effort. A 200 response to /v1/models doesn't prove feature parity. Write the probe once, run it per route, store results in your capability registry (03.11 owns that pattern).

7.2 Concurrency, batching, and queueing#

The engine batches internally (continuous batching in vLLM/SGLang; -np slots in llama.cpp; OLLAMA_NUM_PARALLEL in Ollama). Your job is to feed it the right amount of work:

  • Don't over-parallelize the client. Firing 500 concurrent requests at a server sized for 32 in-flight just builds a queue — and if the queue is unbounded you get timeouts instead of backpressure. Match client concurrency to server capacity; use the benchmark in Part 10 to find the knee.
  • Shard across replicas, not one giant batch. Run N engine replicas (data-parallel) behind a load balancer rather than one engine with huge batch — you get independent failure domains and linear scaling. vLLM's --data-parallel-size or external replication both work.
  • Queue deliberately. If you must absorb bursts, put a bounded queue in front (your gateway, a message broker) with explicit rejection — never let requests pile up inside the engine's memory. 03.8 owns retry/backoff; the self-hosted addition is that your queue is now the backpressure point.
  • Prefill vs decode asymmetry. Long prompts (RAG, agents) hit prefill hard; chunked prefill (default-on in vLLM V1) prevents one giant prompt from stalling the batch. If you see latency spikes correlated with long contexts, that's prefill contention — prefix caching and request shaping help.

7.3 Prefix and KV caching strategy#

Prefix caching (vLLM default-on, SGLang RadixAttention, Ollama's KV reuse, MLX prompt cache) reuses computed KV blocks for shared prefixes — the single biggest latency win for chat/RAG/agent workloads where the system prompt + tools + retrieved context repeat across requests.

  • Design prompts cache-friendly: stable prefix first (system prompt, tool definitions, few-shot examples, RAG context if stable), volatile user query last. 11B.3 owns the full caching strategy; the self-hosted note is that engine-level prefix caching is automatic but only helps if your prompt assembly produces byte-identical prefixes.
  • It reduces prefill, not decode. A cache hit skips recomputing the prefix's KV — faster time-to-first-token — but generation speed is unchanged. Don't expect it to make decoding faster.
  • Tenant isolation caveat. Prefix caches are keyed by content hash. If two tenants share a prefix (e.g., a common system prompt) that's fine — the cache stores KV, not your data. But if tenant A's private context becomes a prefix that tenant B's request matches, you've leaked A's KV into B's computation. In multi-tenant self-hosted deployments, namespace or disable cross-tenant prefix caching — check your engine's isolation options (vLLM has cache salt/namespace support).
  • Cache is per-replica. With N replicas, each has its own cache; a request routed to replica 2 misses replica 1's warm cache. Sticky routing or shared-prefix-aware load balancing recovers some of this.

7.4 Speculative decoding — awareness, not configuration#

Speculative decoding (draft model proposes tokens, target model verifies) gives 1.5–3× decode speedup without quality loss — the target model's distribution is preserved. vLLM supports n-gram, suffix, EAGLE, DFlash schemes; SGLang has EAGLE integration; TensorRT-LLM has its own. You don't configure it per-request usually — it's an engine flag (--speculative-config in vLLM). Know it exists because: it changes latency profiles (faster decode, slightly more memory for the draft model), it's a free win you should enable on supported hardware, and it's a reason two deployments of "the same model" benchmark differently.

7.5 Monitoring, health checks, upgrades, canaries#

A self-hosted model server is a production dependency — treat it like your database:

  • Health checks: /health (vLLM, trtllm-serve) or /v1/models reachability. But a 200 on health ≠ model loaded and responsive — add a canary generation (tiny prompt, assert non-empty response within timeout) for real readiness. 11A.2 owns SLOs; the self-hosted addition is GPU memory utilization, KV cache usage, prefix-cache hit rate, queue depth, and preemption counts as first-class metrics. If your servers or gateway emit OpenTelemetry, the gen_ai.server.* request-duration, time-to-first-token and time-per-output-token metrics are the standard names for these (11A.1, 3.2); vLLM and SGLang also expose their own Prometheus metrics, so map the two rather than assuming they match.
  • Rolling upgrades: model weights and engine versions are your deployment artifact. Pin both — vllm serve Qwen/Qwen3-32B --revision <40-char-commit-sha> (Hugging Face revisions are commit SHAs, not @sha256: digests — that syntax is for container images) or a local snapshot directory, and a pinned engine image tag (vllm/vllm-openai:v0.33.0, not :latest). Upgrade engine and model separately; eval-gate model changes (2.5).
  • Canaries: route a small % of traffic (or a scheduled probe) to new engine/model versions, compare eval scores and latency before full cutover — the same canary discipline as 11C.3 Part 11.
  • Cold starts: loading a 70B model takes tens of seconds to minutes; engine startup + CUDA graph capture adds more. Keep replicas warm (min replicas > 0), use smaller models for latency-sensitive paths, or accept cold-start amortization on batch workloads. Managed hosts hide this; self-hosted you own it.

7.6 Multi-tenancy, security, provenance, and licence compliance#

  • Auth on every path. The vLLM --api-key gap (5.1) is the canonical example — put a gateway/reverse proxy in front that authenticates all routes, or bind to private interfaces only. Ollama/LM Studio/MLX default to localhost — fine for dev, dangerous on a shared host or LAN.
  • Tenant isolation in the KV cache. Prefix caching, continuous batching, and paged attention share GPU memory across requests — a bug or misconfiguration can leak one tenant's context into another's generation. Namespace caches per tenant where the engine supports it; otherwise isolate tenants on separate replicas.
  • Model file provenance. Download weights from Hugging Face by repo + revision SHA, not main — a force-pushed or compromised repo can silently change weights. Verify checksums where provided; safetensors format is safer than pickle (pickle can execute arbitrary code on load — another reason 02.1 prefers safetensors). Scan GGUF files from untrusted sources.
  • Licences are a deployment gate. Re-check 2.3 at ship time: the licence must permit your use case (commercial serving, redistribution, fine-tuning derivatives) and your jurisdiction. CI should fail if a model's licence isn't on the approved list.
  • No secrets in model serving. Your gateway holds the API keys; the model server should sit behind it on a private network. Never expose vLLM/Ollama directly to the internet without auth.

7.7 LoRA adapters in serving#

Fine-tuned models don't need separate deployments — LoRA adapters are small weight deltas that load on top of a shared base model. vLLM's --enable-lora --lora-modules name=path serves multiple adapters on one engine; requests select via the model field ("model": "my-lora-adapter"). --max-lora-rank and --max-loras bound the extra memory. SGLang has multi-LoRA batching; TensorRT-LLM supports LoRA; Ollama/llama.cpp have more limited adapter support. This is how you serve "the base model + 50 customer fine-tunes" on one GPU instead of 50 copies. 13A.8 owns the decision of whether to fine-tune; this is the serving mechanics once you've decided.

7.8 Scaling the GPU fleet: autoscaling, spot instances, and scale-to-zero#

The deployment patterns — single node, replicated pods, autoscaling GPUs, cold starts, spot instances — deserve honest treatment, because GPU fleets behave nothing like stateless web pods:

  • Single node vs replicated pods. One engine process on one GPU is the dev/small-prod shape; production is N identical replicas behind a load balancer (10.1). Replication is horizontal scaling you control — the autoscaler discussion below is about the nodes underneath.
  • GPU autoscaling is slow by nature. A cluster autoscaler or Karpenter-style provisioner can only scale when a node exists: the chain is node boot → GPU operator/driver readiness → container image pull → model weight download (tens of GB) → engine start → CUDA-graph capture. That's minutes, not seconds — and model weights are usually cached on a persistent volume or node-local cache, which a brand-new node doesn't have. Autoscaling therefore reacts to sustained load, not bursts; for burst absorption you need warm headroom or a queue in front (7.2). Scale on queue depth or time-to-first-token, not CPU — GPU servers are I/O-bound waiting on the accelerator.
  • Scale-to-zero and sleep modes are the middle path. vLLM's sleep mode (--enable-sleep-mode, CUDA/HIP) releases most GPU memory without stopping the server: level 1 offloads weights to CPU RAM and discards the KV cache (wake in seconds), level 2 discards weights too (slower wake, minimal RAM). Paired with an orchestrator that wakes the pod on request, this approximates serverless GPU economics while keeping the engine warm-ish — the trade is CPU RAM for weights and a multi-second wake penalty on the first request. Managed hosts (Part 6) hide all of this; self-hosted you own the wake-up latency budget.
  • Spot / preemptible GPUs are dangerous for interactive serving. Spot capacity is reclaimed without warning: AWS gives an interruption notice ~2 minutes before stop/terminate (best effort), GCP Spot VMs default to a ~30-second shutdown window (an optional 120-second preemption notice exists at creation), Azure notifies via scheduled events ~30 seconds ahead. A 70B model takes minutes to load — longer than any of those windows — so a preempted replica can't drain gracefully; in-flight requests die. Spot is legitimate for fault-tolerant batch work (evals, data generation, offline embedding) where jobs checkpoint and retry, and for baseline capacity you accept losing; it is the wrong shape for p99-latency chat unless you keep warm on-demand replicas for the interactive slice and let spot absorb overflow that can be re-queued.
  • Cloud GPU marketplaces are the rental route. The hyperscalers' marketplaces (AWS, GCP, Azure) and the neoclouds (Lambda, CoreWeave, Nebius, Crusoe, TensorWave) sell GPU capacity in three pricing shapes: on-demand (pay per second/hour, most expensive), committed-use/reserved (1–3 year discounts, inflexible), and spot/preemptible (deepest discount, reclaimable). For self-managed engines (1.1 row 2) marketplaces are how you buy the GPUs; for managed serving you never touch them. Match the pricing shape to the workload's tolerance for interruption — the same spot-vs-on-demand decision as above, now at the procurement layer.

The composite picture: warm replicas for the interactive baseline, autoscaling for sustained growth (minutes-latency), spot for interruptible overflow, sleep mode or scale-to-zero for the long tail of idle hours. Each mechanism trades money against wake-up latency and preemption risk — there is no free GPU-hour.

7.9 Fleet-scale serving: KV-aware routing and prefill/decode disaggregation#

Section 7.3 ended with an uncomfortable fact: the prefix cache is per-replica, so a plain round-robin load balancer scatters requests that share a prefix across replicas and throws away most of the cache hit rate. Once you run more than a handful of replicas, three ideas matter. Each is a serving-platform feature you adopt, not something you write:

Idea The problem it solves How it works
KV-cache-aware routing Round-robin ignores which replica already holds the prefix The router scores replicas by load and by how much of the incoming prompt is already cached there, then picks the best one
Prefill/decode disaggregation Prefill (compute-bound) and decode (memory-bandwidth-bound) interfere when they share a GPU, so a long prompt stalls other users' streaming Separate worker pools do prefill and decode; the KV blocks move between them over a fast interconnect, and each pool scales independently
Multi-tier KV offload KV cache is limited by GPU memory, so evicted prefixes must be recomputed Cold blocks spill to CPU RAM or storage and are reloaded when a matching request arrives

Two open-source platforms packaged these ideas as of November 2026 (both are orchestration layers above an engine, not engines):

  • llm-d — a Kubernetes-native stack, a CNCF Sandbox project. Its router scores pods with real-time metrics and KV-cache affinity, it supports prefill/decode disaggregation with high-speed KV transfer, and it builds on the Kubernetes Gateway API Inference Extension (an InferencePool resource connects gateway routing to model servers). The default engine is vLLM; SGLang and TensorRT-LLM are also supported (source: llm-d architecture docs, checked 8 November 2026).
  • NVIDIA Dynamo — an Apache-2.0 datacenter-scale inference stack with disaggregated serving, a KV-aware router, multi-tier KV offload (KVBM) and an SLA-based autoscaling planner, with vLLM, SGLang and TensorRT-LLM as backends; the feature matrix differs per backend (source: Dynamo repository, checked 8 November 2026).

Part 8 — Local development workflows and hybrid architectures#

Deep-dive

8.1 Dev, test, and CI with a local model#

The most underrated use of local models: a deterministic, free, offline test double. 03.10 owns mocking strategies; the self-hosted addition is that a small local model (1–8B, Q4, via Ollama or llama-server) gives you a real model in CI without API keys, rate limits, or cost — good enough to test your plumbing (does the tool call parse? does the JSON schema validate? does streaming work?), not good enough to test quality (that's what evals are for).

python
# reference — dev/test client pointed at a local Ollama stand-in
import os
from openai import OpenAI

client = OpenAI(
    base_url=os.getenv("LLM_BASE_URL", "http://localhost:11434/v1"),
    api_key=os.getenv("LLM_API_KEY", "ollama"),
)

def chat(messages):
    return client.chat.completions.create(
        model=os.getenv("LLM_MODEL", "qwen3:4b"),
        messages=messages,
        temperature=0,
    )

Contract tests: assert the shape of responses (fields present, types correct, tool-call structure valid) against the local model — the same tests run against prod APIs where a real key exists. This catches your code's bugs without catching the model's quality issues, which is exactly what a test double should do.

8.2 Hybrid architectures#

The production pattern that makes open-weight economics work without giving up frontier quality: route easy work to a cheap local/managed open model, hard work to a frontier API. 11B.5 owns routing machinery; the self-hosted addition is that "cheap" can now mean your own GPU for the VPC-bound slice and a managed open host for the rest.

python
# reference — hybrid router: local model for easy, API for hard
# clients as in 7.1: local_vllm = OpenAI(base_url="http://gpu-box:8000/v1", ...)
#                     gateway = OpenAI(...)   # your 11C.3 gateway / hosted route
from openai import OpenAI

local_vllm = OpenAI(base_url="http://gpu-box.internal:8000/v1", api_key="dummy")
gateway = OpenAI()  # frontier route via env-configured base_url + key


def answer(query: str, difficulty: str) -> str:
    if difficulty == "easy":
        # local vLLM — free-ish, VPC-bound, good enough for FAQs/extraction
        return local_vllm.chat.completions.create(
            model="Qwen/Qwen3-8B", messages=[{"role": "user", "content": query}]
        ).choices[0].message.content
    # hard reasoning / agentic work → frontier API via the gateway
    return gateway.chat.completions.create(
        model="claude-sonnet-5-5", messages=[{"role": "user", "content": query}]
    ).choices[0].message.content

The routing decision uses the 11B.5 machinery (rules, classifier, cascade); the self-hosted part is just another base_url in the client pool. Data-residency tenants can be pinned to the local route entirely; cost-sensitive bulk work goes to the cheapest open host; only the genuinely hard 5–10% touches the expensive API.

8.3 Edge and on-device#

For workloads that must run with no network or sub-50ms latency, the model moves to the user's device:

  • WebLLM / MLC — in-browser LLM inference via WebGPU; OpenAI-compatible; runs Llama/Phi/Gemma/Mistral/Qwen-class models (1–8B quantized) inside a web worker. Downloads weights to the browser's cache; no server.
  • Apple ecosystem (as of November 2026) — at WWDC26 Apple expanded the Foundation Models framework (session 241, What's new in the Foundation Models framework): a rebuilt on-device system model, Private Cloud Compute (a larger server model with a 32,000-token context window and configurable reasoning, needing no API key), and a LanguageModel protocol so a LanguageModelSession can be backed by Apple's models or by a third-party local or server model (session 339 shows providers how to plug in; MLX-backed models are one example). Core AI is the framework for bringing your own model to Apple hardware, which Apple positions as the successor to Core ML. The community Swift package AnyLanguageModel offers a similar drop-in surface over llama.cpp, MLX, Core ML, Ollama and hosted APIs. All of this is Swift-side: Python is not involved on-device, so for this path it is awareness, not a skill to build.
  • Mobile/edge runtimes — llama.cpp compiles to iOS/Android; ONNX Runtime Mobile, ExecuTorch, and vendor NPUs (Qualcomm, MediaTek) run small quantized models on phones.
  • Gemini Nano-class — on-device models bundled in mobile OSes (Android AICore, iOS Apple Intelligence) accessible via platform APIs.

The honest constraints: models are small (1–8B), quantized aggressively, and capability-limited — fine for classification, short summaries, privacy-preserving autocomplete, offline assistants. Not for long-context reasoning, large tool sets, or frontier-quality generation. The pattern is small model on device for the easy/private stuff, API for the rest — the same hybrid logic as 8.2, pushed to the edge.


Part 9 — Beyond text: embeddings, rerankers, speech, vision locally#

Reference

Self-hosting isn't just chat models. The same runtimes serve the rest of the stack:

  • Embeddings — run embedding models locally via sentence-transformers, TEI (06.1 Part 4 owns TEI), or Ollama's /v1/embeddings. Local embeddings are the norm in RAG pipelines handling sensitive documents — you don't want to send chunks to an external embedding API any more than you'd send the query.
  • Rerankers — cross-encoder rerankers (bge-reranker, jina-reranker) run locally via TEI or transformers; 06.9 owns the reranking strategy.
  • Speech-to-text / TTS — Whisper (STT) and Kokoro/Piper-style models run locally; 09.4 and 09.5 own the audio lessons. Local STT/TTS is standard for privacy-sensitive voice features.
  • Vision — VLMs (Qwen-VL, LLaVA, Gemma vision) run on vLLM/SGLang/Ollama; 09.1 owns vision applications. Local VLM serving is less mature than text but works for document understanding on sensitive images.
  • Image generation — Stable Diffusion/Flux run via ComfyUI/diffusers locally; 09.3 owns it. Different serving stack entirely (not OpenAI-compatible LLM API) but same self-hosting economics.

The pattern is consistent: anything you can run as weights, you can run locally — the question is always the same four-way trade from 1.1.


Part 10 — Putting it together#

Deep-dive

10.1 Reference architecture#

A production self-hosted deployment looks like this — your app never talks to the engine directly:

flowchart LR
    Client["Your application<br/>(OpenAI-compatible client)"]
    GW["Gateway / router<br/>(auth, fallbacks, rate limits — 11C.3)"]
    LB["Load balancer"]
    VLLM1["vLLM replica 1<br/>Qwen3-32B Q4 + LoRA adapters"]
    VLLM2["vLLM replica 2<br/>Qwen3-32B Q4 + LoRA adapters"]
    Cache["Prefix cache<br/>(per-replica KV)"]
    Metrics["Metrics/OTel<br/>(tok/s, KV usage, hit rate)"]
    Client --> GW --> LB
    LB --> VLLM1
    LB --> VLLM2
    VLLM1 -.-> Cache
    VLLM2 -.-> Cache
    VLLM1 --> Metrics
    VLLM2 --> Metrics
    GW -.->|fallback| API["Hosted API<br/>(OpenRouter / frontier)"]
  • Gateway terminates auth, applies rate limits, routes to local vs hosted, and holds the fallback chain — exactly the 11C.3 machinery, with the vLLM cluster as just another backend.
  • Replicas are identical engine+model+adapter sets behind a load balancer; scale horizontally.
  • Prefix cache is per-replica and automatic; monitor hit rate as a health signal.
  • Metrics feed your 11A.2 dashboards: tok/s, time-to-first-token, KV-cache utilization, queue depth, preemption count, prefix-cache hit rate.

10.2 docker-compose reference#

yaml
# docker-compose.yml — REFERENCE ONLY, not run in this lesson
# Self-hosted vLLM serving Qwen3-32B on 2x80GB GPUs
services:
  vllm:
    image: vllm/vllm-openai:v0.33.0   # pin the version!
    command: >
      --model Qwen/Qwen3-32B
      --tensor-parallel-size 2
      --max-model-len 32768
      --gpu-memory-utilization 0.9
      --enable-lora
      --lora-modules support-v1=/models/lora-support-v1
      --api-key ${VLLM_API_KEY}
    environment:
      - HUGGING_FACE_HUB_TOKEN=${HF_TOKEN}
    volumes:
      - vllm-models:/root/.cache/huggingface
      - ./lora-adapters:/models
    ports:
      - "127.0.0.1:8000:8000"   # localhost only — put a gateway in front!
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: 2
              capabilities: [gpu]
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
      interval: 30s
      timeout: 10s
      retries: 3

volumes:
  vllm-models:

Note 127.0.0.1:8000 — bind to localhost and let your authenticated gateway be the only path in. Never expose :8000 directly; remember the --api-key gap from 5.1.

10.3 Benchmark skeleton (runs against any OpenAI-compatible endpoint)#

This measures throughput and latency at controlled concurrency — the numbers you need for the 1.2 break-even math. Stdlib only, works against a fake local server for testing:

python
"""Benchmark an OpenAI-compatible endpoint: throughput + latency at fixed concurrency.

Usage: python3 bench_openai_compatible.py [--base-url URL] [--model NAME]
                                          [--concurrency N] [--requests N]
                                          [--api-key KEY]

The defaults target the fake server below, so it runs with no keys and no GPU.
--model must be a name the real server knows (an Ollama tag, a vLLM repo id,
a managed host's model id). The API key comes from --api-key or the
BENCH_API_KEY environment variable; local servers ignore the "dummy" default.
"""
import argparse
import json
import os
import time
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from functools import partial


def one_request(i, *, base_url, model, api_key):
    """One chat completion; returns (latency_seconds, completion_tokens)."""
    payload = {
        "model": model,
        "messages": [{"role": "user", "content": f"Count to {i % 10}."}],
        "max_tokens": 64,
        "temperature": 0,
    }
    req = urllib.request.Request(
        f"{base_url}/chat/completions",
        data=json.dumps(payload).encode(),
        headers={"Content-Type": "application/json",
                 "Authorization": f"Bearer {api_key}"},
        method="POST",
    )
    t0 = time.perf_counter()
    with urllib.request.urlopen(req, timeout=120) as resp:
        body = json.loads(resp.read())
    dt = time.perf_counter() - t0
    # completion_tokens may be absent on some servers; estimate from content
    usage = body.get("usage", {})
    ct = usage.get("completion_tokens")
    if ct is None:
        ct = len(body["choices"][0]["message"]["content"].split())
    return dt, ct


def main():
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--base-url", default="http://127.0.0.1:9999/v1")
    ap.add_argument("--model", default="bench-model")
    ap.add_argument("--concurrency", type=int, default=8)
    ap.add_argument("--requests", type=int, default=32)
    ap.add_argument("--api-key", default=os.environ.get("BENCH_API_KEY", "dummy"))
    args = ap.parse_args()

    work = partial(one_request, base_url=args.base_url.rstrip("/"),
                   model=args.model, api_key=args.api_key)
    t0 = time.perf_counter()
    with ThreadPoolExecutor(max_workers=args.concurrency) as ex:
        results = list(ex.map(work, range(args.requests)))
    wall = time.perf_counter() - t0

    latencies = sorted(r[0] for r in results)
    total_tokens = sum(r[1] for r in results)
    p50 = latencies[len(latencies) // 2]
    p95 = latencies[int(len(latencies) * 0.95)]

    print(f"endpoint={args.base_url} concurrency={args.concurrency} requests={args.requests}")
    print(f"wall={wall:.2f}s  throughput={total_tokens/wall:.1f} tok/s  "
          f"{args.requests/wall:.2f} req/s")
    print(f"latency p50={p50:.2f}s p95={p95:.2f}s")


if __name__ == "__main__":
    main()

To try it with no GPU and no keys, run it against this fake endpoint — a ~30-line stdlib server that sleeps a fixed 50 ms per request (simulating model latency) and returns a canned response with a real usage block, so the benchmark's token counting exercises the genuine code path:

python
"""Fake OpenAI-compatible /v1/chat/completions endpoint — local testing only.

Run: python3 fake_server.py [port]   (default 9999), then point the
benchmark at http://127.0.0.1:9999/v1. Stdlib only.
"""
import json
import sys
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 9999
LATENCY_S = 0.05            # simulated per-request model time
COMPLETION_TOKENS = 32      # canned usage.completion_tokens


class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        if not self.path.endswith("/chat/completions"):
            self.send_error(404)
            return
        self.rfile.read(int(self.headers.get("Content-Length", 0)))
        time.sleep(LATENCY_S)
        body = {
            "id": "chatcmpl-fake", "object": "chat.completion",
            "choices": [{"index": 0, "finish_reason": "stop",
                         "message": {"role": "assistant",
                                     "content": "word " * COMPLETION_TOKENS}}],
            "usage": {"prompt_tokens": 8, "completion_tokens": COMPLETION_TOKENS,
                      "total_tokens": 8 + COMPLETION_TOKENS},
        }
        data = json.dumps(body).encode()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def log_message(self, *args):
        pass


if __name__ == "__main__":
    print(f"fake server on http://127.0.0.1:{PORT}/v1")
    ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever()
Example output · illustrative5 lines
$ python3 fake_server.py 9999 &          # terminal 1
$ python3 bench_openai_compatible.py --concurrency 8 --requests 32
endpoint=http://127.0.0.1:9999/v1 concurrency=8 requests=32
wall=0.49s  throughput=2077.4 tok/s  64.92 req/s
latency p50=0.06s p95=0.28s

(The benchmark uses a thread pool rather than asyncio — for a measurement harness that fires fixed-size HTTP requests, threads are the simpler correct tool; the async conventions of 03.9 matter for application code, not for load generation.)

Point it at a real endpoint instead, naming a model the server actually serves: python3 bench_openai_compatible.py --base-url http://gpu-box:8000/v1 --model Qwen/Qwen3-32B --concurrency 16 --requests 64. For a managed host, add --api-key or set BENCH_API_KEY. The tok/s at your target concurrency × your GPU hourly cost = your real $/1M tokens for the 3.4 comparison — and the same script works against Ollama (--base-url http://localhost:11434/v1 --model qwen3:8b) or any OpenAI-compatible route from 1.1.

10.4 Decision table — which route for which workload#

Workload Route Why
Quick dev/test, no keys Ollama / llama-server / LM Studio on laptop Free, offline, real model, zero ops
CI contract tests Local 1–8B model via Ollama Deterministic plumbing tests without API spend
Prototype against production-like API vLLM on a rented GPU (RunPod/Lambda) Real engine, real OpenAI API, hourly cost
Production open-model serving, NVIDIA Self-hosted vLLM cluster behind gateway Control, VPC option, LoRA, predictable cost at scale
Production open-model serving, non-NVIDIA vLLM or SGLang (whichever supports your accelerator and model — read both matrices), or a managed host AMD/Intel/TPU/Ascend, or just pay per token
Open-model bulk without GPU ops Together / Fireworks / HF Endpoints Open-weight economics, zero infra
Lowest latency on supported models Groq / Cerebras Custom silicon, lowest TTFT/tok-s
Custom model + custom code Modal / RunPod / Replicate Bring a container, they run it
Frontier-quality hard tail Hosted API via gateway fallback Quality the open models can't match
VPC-bound / regulated / air-gapped Self-hosted vLLM/llama.cpp, no external calls Only option that meets the boundary
Offline / on-device features WebLLM / Apple FM+MLX / mobile runtimes No network, privacy, sub-50ms
Interruptible batch (evals, data-gen, embeddings) Spot/preemptible GPUs, checkpointed jobs Deepest discount; preemption is survivable when work resumes (7.8)
Embeddings/rerank/STT/vision locally TEI / transformers / whisper.cpp / vLLM-VLM Same self-host economics, same runtimes
Failure Symptom Root cause Detection Fix
Weights fit, OOMs under load Requests fail with CUDA OOM at peak concurrency KV cache × context × batch exceeds VRAM GPU memory metrics, OOM errors in logs Fewer slots/shorter ctx, KV-cache quant, smaller model, bigger GPU (3.1)
Incompatible quant/runtime Engine won't load the file / wrong results GGUF fed to vLLM-standard path, AWQ to llama.cpp, wrong format Engine startup errors, eval regression Match format to runtime (2.2)
Wrong chat template Gibberish, ignored system prompt, broken tool calls Model loaded without its Jinja/template (--jinja off, wrong tokenizer_config) Output inspection, eval failures on prompt-following Enable chat template, use the model's official serving recipe
Unsupported structured output/tools response_format ignored, malformed tool calls Engine lacks the backend, or model too weak Capability probe fails, schema-validation errors Pick engine+model that supports it, or downgrade to prompt-based JSON + validation
Cold-start latency First request after idle takes 30s+ Model load + CUDA graph capture Time-to-first-token spikes after idle Keep min replicas warm, smaller model for latency paths, pre-warm on deploy
Licence violation Legal exposure discovered post-launch Model licence doesn't permit your use Licence review missed at deploy CI licence gate, legal review before ship (2.3)
Exposed local server Model endpoint reachable without auth Bound to 0.0.0.0, vLLM /invocations unprotected Security scan, unexpected traffic Bind localhost/private net, gateway auth on all paths (5.1, 7.6)
Tenant KV-cache leak Tenant B's output contains Tenant A's context Shared prefix cache across tenants Output inspection, security audit Namespace/disable cross-tenant prefix caching, isolate replicas (7.3)
Silent quality regression Eval scores drop after model/quant/engine upgrade New quant, engine version, or model revision changed behaviour Scheduled evals on canary (Module 10A) Pin versions, eval-gate upgrades, canary before cutover
Deprecated engine TGI deployment can't get fixes TGI archived Mar 2026 Dependency audit, HF docs Migrate to vLLM/SGLang (5.4)
Unpinned model drift Behaviour changes with no deploy main branch weights updated upstream Output diffs, eval drift Pin HF revision SHA, checksum weights (7.6)
Over-quantized quality loss Model "dumber" than expected IQ2/Q2_K or aggressive KV quant Eval regression vs higher quant Step up quant, measure on your eval set (2.5)
Self-hosting costs more than the API $/1M tokens above the API quote GPU idle most of the day — utilisation below break-even Cost-per-token metrics vs API baseline (3.4) Route bulk to API/managed host; keep the GPU only for the slice that needs it (8.2, 7.8)

Common misconceptions#

Misconception Reality
"Open-weight means free." The weights are free to download; running them costs GPU-hours, engineering time, and ops burden. The break-even math decides whether it's actually cheaper
"If the weights fit in VRAM, it will serve." KV cache scales with context × concurrency and can exceed weight memory — and hybrid architectures (sliding-window, linear-attention) don't even follow the dense formula. Size for p95 concurrent context, not the model file
"Ollama is a production server." It's a dev tool — a few parallel slots, no multi-tenancy, localhost assumptions. Production needs vLLM/SGLang/TensorRT-LLM behind a gateway
"OpenAI-compatible means feature-compatible." The endpoint shape matches; structured outputs, tool calling, vision, and reasoning fields differ per engine, per host, per model. Probe capabilities per route
"A bigger quant number is always better." Q8 is near-lossless, Q4_K_M is the sweet spot, sub-4-bit degrades. But "4-bit" spans GGUF/AWQ/GPTQ/FP8/MXFP4 — different artifacts, different quality, and mixed-precision checkpoints like gpt-oss don't match their headline format. Measure on your eval set
"Prefix caching makes generation faster." It skips recomputing shared prefixes — faster time-to-first-token — but decode speed is unchanged
"Self-hosting removes all third parties." You still depend on Hugging Face for weights, NVIDIA for drivers/CUDA, and your own monitoring stack. The boundary is inference tokens, not the whole supply chain
"TGI is the standard." It's archived as of March 2026 — vLLM/SGLang are the current defaults
"Local models are always private." A local server bound to 0.0.0.0 is a public endpoint; Ollama's OLLAMA_HOST default is localhost but nothing stops you exposing it. And your weights still came from somewhere — provenance matters
"Spot GPUs are just cheaper GPUs." They're reclaimable with seconds to about two minutes of notice — shorter than a model load. Fine for checkpointable batch work, wrong for interactive serving unless warm replicas carry the load

Key takeaways#

  • Four routes, one choice: your hardware, rented GPUs (self-managed), managed open-model hosts, or edge/on-device. "Open-weight" is orthogonal to "local" — the question is who operates the engine.
  • Self-host wins on control, privacy, offline, and sustained high volume — not on intermittent workloads. The break-even is ~75%+ GPU utilisation; below that the API is cheaper.
  • Memory is weights + KV cache + overhead. KV cache scales with context × concurrency and routinely exceeds weights. Size for p95 concurrent context.
  • Quantization is the fit lever, eval is the quality check. GGUF/AWQ/GPTQ/FP8/MXFP4 each have their runtime; measure quality on your own eval set through the actual serving path.
  • vLLM is the default production engine on NVIDIA; SGLang for agent/prefix-heavy workloads or where its backend fits your hardware better; TensorRT-LLM for max NVIDIA perf; TGI is archived. All expose OpenAI-compatible APIs.
  • OpenAI-compatible is an adapter boundary, not a parity guarantee — probe capabilities per route.
  • Production self-hosting is operations: pin versions, eval-gate upgrades, isolate tenants in the KV cache, authenticate every path, monitor prefix-cache hit rate and KV utilization.
  • Local models shine in dev/test/CI as free deterministic test doubles, and in hybrid architectures where the cheap local route handles easy/sensitive work and the API handles the hard tail.

Terms introduced in this lesson#

Term One-line definition
Open-weight model A model whose trained parameters are published for download, distinct from "open source" software — you get the weights, not the training pipeline or data
GGUF llama.cpp's model container format storing tensors in configurable quantization types (Q4_K_M, Q8_0, IQ*, etc.); the native format for CPU/Apple/edge inference
KV cache quantization Reducing the precision of the key-value cache (separate from weight quantization) to shrink per-request memory at the cost of some quality — e.g., Ollama's OLLAMA_KV_CACHE_TYPE=q8_0, vLLM's --kv-cache-dtype
Continuous batching A serving strategy where requests join and leave the decode batch every step rather than waiting for batch completion — the core throughput mechanism in vLLM/SGLang
Prefix caching Reusing computed KV-cache blocks for shared prompt prefixes (system prompts, RAG context) across requests — reduces prefill time, not decode time
RadixAttention SGLang's radix-tree KV cache that automatically shares prefixes across requests and supports tree-structured (branching) conversation workloads
Managed open-model host A provider that runs a serving engine (vLLM/SGLang/llama.cpp) on their GPUs and exposes an OpenAI-compatible API for open-weight models — Together, Fireworks, Groq, Cerebras, HF Inference Endpoints, etc.
MXFP4 / NVFP4 4-bit microscaling quantization formats with block-wise scales, designed for MoE expert weights — MXFP4 is required for gpt-oss models; NVFP4 is NVIDIA's Blackwell-optimized variant
LoRA serving Serving multiple fine-tuned adapters on a shared base model by loading small weight deltas — vLLM's --enable-lora --lora-modules lets requests select adapters via the model field
Speculative decoding A serving optimization where a small draft model proposes tokens that the target model verifies in parallel — 1.5–3× decode speedup without quality loss
OpenAI-compatible surface The de-facto API shape (/v1/chat/completions, /v1/models, etc.) shared by hosted providers, Ollama, vLLM, llama-server, LM Studio, and managed open-model hosts — an adapter boundary enabling base_url portability, not a feature-parity guarantee
Sleep mode vLLM's --enable-sleep-mode facility that offloads model weights to CPU RAM (level 1) or discards them (level 2) to release GPU memory without stopping the server — a scale-to-zero middle path
Spot / preemptible GPU Discounted GPU capacity the provider can reclaim with only seconds to about two minutes of warning — cheap for checkpointable batch work, hazardous for interactive serving
Tensor / pipeline / data parallelism Three ways to use several GPUs: shard one model's layers across GPUs (tensor), split the model into stages (pipeline), or run independent full replicas (data); data parallelism is usually the serving default (5.1)
Prefill vs decode The two phases of generation: one compute-bound pass over the prompt that builds the KV cache, then a memory-bandwidth-bound token-by-token loop (3.3)
Capability probe A small script that sends the exact features your app uses (response_format, tools, streaming, vision) to a new endpoint and asserts the results, because "OpenAI-compatible" does not guarantee them (7.1)
KV-aware routing A router that sends a request to the replica already holding the most of its prompt prefix in cache, instead of round-robin (7.9)
Prefill/decode disaggregation Running prefill and decode on separate GPU pools, transferring KV blocks between them, so long prompts do not stall streaming users (7.9)

All terms are also collected in the glossary.

Exercises#

No API keys, no GPU, no model downloads — everything runs on a laptop with Python 3.11+ stdlib.

  1. Break-even analysis. Run breakeven.py (Part 1). Change API_IN/API_OUT to your provider's actual prices and GPU_HOURLY/TOK_PER_SEC to a real quote. At what utilisation does self-hosting win? Is your expected workload above or below it?

  2. Size a deployment. Pick a model family (Llama-3.1-8B, Qwen3-32B, gpt-oss-20b). Fill in its n_layers, n_kv_heads, head_dim from the model card, pick a quantization, and run gpu_sizing.py. How many concurrent 32K-context requests fit on your GPU? What if you halve the context?

  3. Quantization trade-off. For the same model, compute weight memory at Q8_0 vs Q4_K_M vs Q2_K. At what point does quality loss outweigh the memory savings for your use case? (Check the model card's quantization recommendations; run your eval set if you have one.)

  4. Cold-start vs warm cost. A 70B model takes ~60s to load. If you serve 100 requests/day in bursts, what's the amortized cold-start cost per request? Does keeping the model warm (always-on GPU) cost more than the cold starts save?

  5. Capability probe design. Write a 20-line Python script that hits /v1/models, then sends one chat completion with response_format={"type":"json_schema",...} and one with tools=[...] to a given base_url. What would you assert to verify the endpoint actually supports structured output and tool calling?

  6. Hybrid routing sketch. Draw (on paper or in Mermaid) a router that sends FAQ/extraction queries to a local 8B model and reasoning/agentic queries to a frontier API. What signals would you use to classify? What's the failure mode if the classifier is wrong?

  7. Licence audit. Pick three open-weight models you're considering. For each, find the licence on the model card and answer: Can you serve it commercially? Must you attribute? Can you fine-tune and keep the derivatives private?

Hints and worked answers for the exercises
  1. With the lesson's example numbers the break-even is 75.6%. If your quote is a cheaper GPU or a pricier API the threshold falls, but the shape is the same: compute GPU_HOURLY × GPUS × 1e6 / (TOK_PER_SEC × 3600 × blended_api_price). If you cannot honestly say your GPU will be busy that fraction of every hour (measure with the Part 10 benchmark, not a vendor's peak number), the verdict is "API or managed host".
  2. For Llama-3.1-8B at q4_k_m on a 24 GB card the calculator's budget is 24 × 0.92 = 22.1 GB; minus 4.9 GB of weights leaves about 17.2 GB for KV, and one 32K sequence costs 131,072 bytes × 32,768 ≈ 4.3 GB, so about 4 concurrent chats fit. Halve the context to 16K and the same budget holds about 8. For gpt-oss-20b, read layer_types, num_key_value_heads and head_dim from the model's config.json first: only the full-attention layers grow with context.
  3. For an 8B model the weights are roughly 8.5 GB (Q8_0), 4.9 GB (Q4_K_M) and 2.6 GB (Q2_K is about 2.6 bits per weight, so add a row such as "q2_k": (2.63, "GGUF 2-bit K-quant") to BYTES_PER_WEIGHT). The memory saved from Q4 to Q2 is only about 2.3 GB, while the quality loss is the largest step in the table: only your eval set can say whether it is acceptable. Extraction and tool calling usually break first.
  4. Assume four bursts a day, each needing a 60 s load plus about 5 minutes of serving: roughly 24 GPU-minutes a day, about $1.00 at $2.50/hour, against $60 a day (2.50 × 24) for an always-on GPU. Cold starts win massively on cost at that volume; the price is a ~60 s first-request wait, which Ollama's keep_alive, min-replica settings or sleep mode can shorten. The break-even flips when bursts become frequent enough that the GPU is busy most of the day.
  5. Assert at least: /v1/models returns your model id; the json_schema response parses with json.loads and validates against the schema (not merely "is JSON"); the tools response contains a tool_calls entry whose function.name is one you declared and whose arguments parse; and a streaming call yields more than one chunk. Run each probe several times: a weak model may pass once and fail on the third try.
  6. Useful signals: a keyword or rule check (known FAQ intents), the retrieval score or number of tool calls needed, input length, tenant policy (a data-residency flag forces the local route), and a cheap classifier's confidence. The failure modes are the two in Check yourself question 11; bound them with a "hard" default on low confidence and a sampled audit of local-route answers.
  7. A good answer names the licence by exact text (Apache 2.0, MIT, or a custom licence), states the commercial-use, attribution and derivative conditions separately, and notes the date you read it. If you cannot find the licence file, treat the model as not shippable until you can.

Check yourself#

  1. What's the difference between "open-weight" and "local"?
  2. Why does a model that fits in VRAM still OOM?
  3. When does self-hosting beat the API on cost?
  4. Which engine for a 70B model on 2×H100 for a chat product?
  5. What's the security gotcha with vLLM's --api-key?
  6. TGI status?
  7. Does prefix caching speed up generation?
  8. How do you serve 50 fine-tuned variants of one base model?
  9. MXFP4 vs GGUF — can you feed one to the other's runtime?
  10. Why is prefix caching a tenant-isolation concern in self-hosted serving?
  11. Your hybrid router sends everything "easy" to the local model — what's the failure mode if the classifier is wrong, and how do you bound it?
  12. What's the licence gate, and where in the pipeline should it fire?

Further resources#


← 11C.5 — Model Lifecycle on One Page | Module 11C overview | Module 12: Safety & Security →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close