Module 2: Benchmark and Harness Run Logs and Baseline

Run Logs and Your First Baseline

You should now have a benchmark set with 30+ questions and gold answers. In this lesson, we'll define the structured format for recording experiments, run your first end-to-end baseline, and grade it. By the end, you'll have a concrete number, your baseline accuracy. That's the number every future improvement gets measured against.

This is the second component of your AI harness. The benchmark set (from the previous lessons) defines what to test. The run log defines how to record what happened. Together they give you reproducible, comparable experiments.

What you'll learn

  • Design a run-log schema that captures inputs, outputs, tool traces, and grading results
  • Run a complete benchmark pass against your anchor repository using manual prompting
  • Grade each answer using the four-level rubric and apply failure labels
  • Calculate your baseline accuracy and identify the most common failure modes
  • Save your first run log in structured JSONL format

Concepts

Run-log schema: the structured format for recording a single benchmark run. Each entry captures: the question asked, the system's response, any tools called or evidence retrieved, the grade assigned, the failure label (if applicable), and metadata like timestamps and model version. A well-designed schema makes runs comparable. You can diff two logs and see exactly what changed.

Baseline: your first graded benchmark run. It doesn't matter how bad the baseline is. What matters is that you have a number. "40% fully correct, 30% partially correct, 30% wrong" is infinitely more useful than "the system seems okay." Every improvement you make in later modules gets measured against this baseline.

Failure distribution: the pattern of how your system fails, not just how often. If 80% of your failures are retrieval_miss (the system couldn't find the right code), you know retrieval is the bottleneck. If failures are evenly split between retrieval and reasoning, the fix is different. The failure distribution tells you where to invest effort.

Walkthrough

Define your run-log schema

Create a file that defines the shape of each run-log entry. We'll use JSONL (one JSON object per line) because it's easy to append to, easy to parse, and easy to diff.

We'll work inside your anchor repository from now on. If you haven't already, set up a Python environment there and install the provider SDK you chose in Module 1:

cd anchor-repo  # or wherever you cloned your anchor repository
python -m venv .venv && source .venv/bin/activate

Install your provider SDK and set your API key:

pip install openai
export OPENAI_API_KEY="sk-..."

Then create the harness directory:

mkdir -p harness

Here's the schema we'll use. Each line in the log file will be one of these objects:

# harness/schema.py
"""Run-log schema for benchmark experiments.

Each entry in a .jsonl run log follows this structure.
"""

SCHEMA_DESCRIPTION = {
    # --- Identity ---
    "run_id": "Unique identifier for this run (e.g., 'baseline-2026-03-24')",
    "question_id": "Matches the 'id' field in benchmark-questions.jsonl",

    # --- Input ---
    "question": "The benchmark question text",
    "category": "symbol_lookup | architecture | change_impact | debugging | onboarding",

    # --- System response ---
    "answer": "The full text of the system's response",
    "model": "Model used (e.g., 'gpt-4o-mini', 'claude-sonnet-4-6')",
    "provider": "Provider used (e.g., 'openai', 'gemini', 'anthropic', 'github-models', 'huggingface', 'ollama-local', 'ollama-cloud')",

    # --- Evidence and tools ---
    "evidence_files": "List of file paths the system cited or retrieved",
    "tools_called": "List of tool names invoked (empty for manual prompting)",
    "retrieval_method": "How evidence was found (e.g., 'manual', 'vector', 'bm25', 'none')",

    # --- Grading ---
    "grade": "fully_correct | partially_correct | unsupported | wrong",
    "failure_label": "missing_evidence | retrieval_miss | wrong_chunk | hallucination | reasoning_error | scope_confusion | null",
    "grading_notes": "Brief explanation of why this grade was assigned",

    # --- Metadata ---
    "repo_sha": "Git SHA of the anchor repo at time of run",
    "timestamp": "ISO 8601 timestamp",
    "harness_version": "Version of your harness (start with 'v0.1')",
}

This schema is intentionally simple. You don't need a database. A JSONL file is enough. The important thing is that every run uses the same shape so you can compare them.

Create the baseline runner

For your first baseline, we'll keep it simple: manually prompt a model with each benchmark question and record the results. Pick your provider and paste the complete script into harness/run_baseline.py:

# harness/run_baseline.py
"""Run a manual baseline against your benchmark questions."""
import json
import os
from datetime import datetime, timezone
from openai import OpenAI

client = OpenAI()
MODEL = "gpt-4o-mini"
PROVIDER = "openai"

RUN_ID = "baseline-" + datetime.now(timezone.utc).strftime("%Y-%m-%d-%H%M%S")
BENCHMARK_FILE = "benchmark-questions.jsonl"
OUTPUT_FILE = f"harness/runs/{RUN_ID}.jsonl"
REPO_SHA = os.popen("git rev-parse --short HEAD").read().strip()

SYSTEM_PROMPT = (
    "You are a code assistant for a software project. "
    "Answer questions about the codebase based on your knowledge. "
    "If you're not sure, say so."
)

questions = []
with open(BENCHMARK_FILE) as f:
    for line in f:
        if line.strip():
            questions.append(json.loads(line))

print(f"Loaded {len(questions)} benchmark questions")
print(f"Run ID: {RUN_ID} | Repo SHA: {REPO_SHA} | Model: {MODEL}\n")

os.makedirs("harness/runs", exist_ok=True)
results = []

for i, q in enumerate(questions):
    print(f"[{i+1}/{len(questions)}] {q['category']}: {q['question'][:60]}...")

    response = client.chat.completions.create(
        model=MODEL,
        messages=[
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": q["question"]},
        ],
        temperature=0,
    )
    answer = response.choices[0].message.content

    results.append({
        "run_id": RUN_ID,
        "question_id": q["id"],
        "question": q["question"],
        "category": q["category"],
        "answer": answer,
        "model": MODEL,
        "provider": PROVIDER,
        "evidence_files": [],
        "tools_called": [],
        "retrieval_method": "none",
        "grade": None,
        "failure_label": None,
        "grading_notes": "",
        "repo_sha": REPO_SHA,
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "harness_version": "v0.1",
    })

with open(OUTPUT_FILE, "w") as f:
    for entry in results:
        f.write(json.dumps(entry) + "\n")

print(f"\nDone. {len(results)} results saved to {OUTPUT_FILE}")
print("Next step: open the file and grade each answer by hand.")

Run it:

python harness/run_baseline.py

This will take a minute or two depending on how many questions you have. The model is answering without any retrieval or tools. It's working from its training data only. Expect most answers to be wrong or unsupported for repo-specific questions. That's the point.

Grade your baseline by hand

Open the output file and grade each entry. This is the most important exercise in this module. You're building your grading instincts.

# harness/grade_baseline.py
"""Interactive grading tool for baseline run logs."""
import json
import sys

GRADES = ["fully_correct", "partially_correct", "unsupported", "wrong"]
FAILURE_LABELS = [
    "missing_evidence", "retrieval_miss", "wrong_chunk",
    "hallucination", "reasoning_error", "scope_confusion", "none",
]

if len(sys.argv) < 2:
    print("Usage: python harness/grade_baseline.py <run-file.jsonl>")
    print("Example: python harness/grade_baseline.py harness/runs/baseline-2026-03-24-143022.jsonl")
    sys.exit(1)

run_file = sys.argv[1]

# Load entries
entries = []
with open(run_file) as f:
    for line in f:
        if line.strip():
            entries.append(json.loads(line))

print(f"Grading {len(entries)} entries from {run_file}\n")

for i, entry in enumerate(entries):
    if entry["grade"] is not None:
        print(f"[{i+1}] Already graded: {entry['grade']}")
        continue

    print(f"\n{'='*60}")
    print(f"[{i+1}/{len(entries)}] {entry['category']}: {entry['question']}")
    print(f"{'='*60}")
    print(f"\nAnswer:\n{entry['answer']}\n")

    # Grade
    print(f"Grades: {', '.join(f'{j}={g}' for j, g in enumerate(GRADES))}")
    grade_idx = input("Grade (0-3): ").strip()
    if grade_idx.isdigit() and 0 <= int(grade_idx) < len(GRADES):
        entry["grade"] = GRADES[int(grade_idx)]
    else:
        print("Skipping...")
        continue

    # Failure label (only if not fully correct)
    if entry["grade"] != "fully_correct":
        print(f"Labels: {', '.join(f'{j}={l}' for j, l in enumerate(FAILURE_LABELS))}")
        label_idx = input(f"Failure label (0-{len(FAILURE_LABELS)-1}): ").strip()
        if label_idx.isdigit() and 0 <= int(label_idx) < len(FAILURE_LABELS):
            entry["failure_label"] = FAILURE_LABELS[int(label_idx)]

    # Notes
    entry["grading_notes"] = input("Brief note (or Enter to skip): ").strip()

# Save graded version
output = run_file.replace(".jsonl", "-graded.jsonl")
with open(output, "w") as f:
    for entry in entries:
        f.write(json.dumps(entry) + "\n")

print(f"\nGraded results saved to {output}")
# Use the exact filename from your baseline run
python harness/grade_baseline.py harness/runs/baseline-2026-03-24-143022.jsonl

For each question, you'll compare the model's answer against the actual code in your anchor repository, assign a grade, and (for non-correct answers) label the failure type.

Calculate your baseline metrics

After grading, calculate your baseline numbers:

# harness/summarize_run.py
"""Summarize a graded run log."""
import json
import sys
from collections import Counter

run_file = sys.argv[1]

entries = []
with open(run_file) as f:
    for line in f:
        if line.strip():
            entries.append(json.loads(line))

graded = [e for e in entries if e["grade"] is not None]
total = len(graded)

if total == 0:
    print("No graded entries found.")
    sys.exit(1)

# Grade distribution
grade_counts = Counter(e["grade"] for e in graded)
print(f"Run: {graded[0]['run_id']}")
print(f"Model: {graded[0]['model']}")
print(f"Total graded: {total}\n")

print("Grade distribution:")
for grade in ["fully_correct", "partially_correct", "unsupported", "wrong"]:
    count = grade_counts.get(grade, 0)
    pct = count / total * 100
    print(f"  {grade:20s}: {count:3d} ({pct:.0f}%)")

# Failure label distribution (non-correct only)
failures = [e for e in graded if e["grade"] != "fully_correct"]
if failures:
    label_counts = Counter(e["failure_label"] for e in failures if e["failure_label"])
    print(f"\nFailure labels ({len(failures)} non-correct answers):")
    for label, count in label_counts.most_common():
        print(f"  {label:20s}: {count:3d}")

# Per-category breakdown
print("\nPer-category accuracy:")
categories = sorted(set(e["category"] for e in graded))
for cat in categories:
    cat_entries = [e for e in graded if e["category"] == cat]
    correct = sum(1 for e in cat_entries if e["grade"] == "fully_correct")
    print(f"  {cat:20s}: {correct}/{len(cat_entries)} fully correct")
# Use the exact graded filename from the previous step
python harness/summarize_run.py harness/runs/baseline-2026-03-24-143022-graded.jsonl

Expected output (your numbers will differ):

Run: baseline-2026-03-24-143022
Model: gpt-4o-mini
Total graded: 30

Grade distribution:
  fully_correct       :   3 (10%)
  partially_correct   :   8 (27%)
  unsupported         :  11 (37%)
  wrong               :   8 (27%)

Failure labels (27 non-correct answers):
  hallucination       :  12
  missing_evidence    :   8
  reasoning_error     :   5
  scope_confusion     :   2

Per-category accuracy:
  architecture        :   0/6 fully correct
  change_impact       :   0/6 fully correct
  debugging           :   1/6 fully correct
  onboarding          :   1/6 fully correct
  symbol_lookup       :   1/6 fully correct

This baseline is a model answering from training data alone, no retrieval, no tools, and no context about your specific codebase, so low accuracy is what we'd expect at this stage. Look at the failure labels rather than the overall score. If missing_evidence and hallucination dominate, that tells you the system's main gap is access to your codebase, not reasoning ability. We'll build retrieval in Modules 3-5 and see how these numbers change.

You'll notice missing_evidence as a label here. Once we add retrieval, that label will split into more specific categories like retrieval_miss (the system searched but didn't find the right code) and wrong_chunk (it found related but wrong code). For now, missing_evidence captures the situation honestly: we haven't given the system any way to look at the code yet.

Exercises

  1. Run the baseline script against your 30+ benchmark questions and save the results.
  2. Grade at least 15 answers by hand using the four-level rubric and failure labels.
  3. Run the summary script and record your baseline numbers.
  4. Write a one-paragraph "baseline memo" answering: What's the overall accuracy? Which category is strongest/weakest? What's the most common failure mode? What would help most?

Completion checkpoint

You have:

  • A run-log schema defined in harness/schema.py
  • At least one complete baseline run saved as JSONL in harness/runs/
  • At least 15 entries graded with the four-level rubric and failure labels
  • Baseline metrics calculated (overall accuracy, per-category breakdown, failure distribution)
  • A one-paragraph baseline memo identifying the biggest opportunity for improvement

Reflection prompts

  • What types of questions did the model handle best with no retrieval? Why?
  • What's the most common failure label? What does that tell you about what the system needs next?
  • Did any answers surprise you, either better or worse than expected?

Connecting to the project

This is the last lesson before we start building the actual code assistant. Everything from here forward (tool calling in Module 3, retrieval in Module 4, RAG in Module 5, evals in Module 6) will be measured against the baseline you just created.

Your harness/ directory is the beginning of your AI harness. Right now it has a benchmark set, a run log, and a summary script. In Module 5 we'll add telemetry, and in Module 6 we'll add automated grading. By then, you'll be able to compare any two system versions with one command.

What's next

Building a Raw Tool Loop. With a measured baseline in place, you can start building without losing the plot; the next lesson gives the model direct ways to inspect the repo instead of guessing.

References

Start here

Build with this

Deep dive

Your Notes
GitHub Sync

Sync your lesson notes to a private GitHub Gist. If you have not entered a token yet, the sync button will open the GitHub token modal.

Glossary
API (Application Programming Interface)Foundational terms
A structured way for programs to communicate. In this context, usually an HTTP endpoint you call to interact with an LLM.
AST (Abstract Syntax Tree)Foundational terms
A tree representation of source code structure. Used by parsers like Tree-sitter to understand code as a hierarchy of functions, classes, and statements. You'll encounter this more deeply in the Code Retrieval module, but the concept appears briefly in retrieval fundamentals.
BM25 (Best Match 25)Foundational terms
A classical ranking function for keyword search. Scores documents by term frequency and inverse document frequency. Often competitive with or complementary to vector search.
ChunkingFoundational terms
Splitting a document into smaller pieces for indexing and retrieval. Chunk boundaries significantly affect retrieval quality. Split at the wrong place and your retrieval will return half a function or the end of one paragraph glued to the start of another.
Context engineeringFoundational terms
The discipline of selecting, packaging, and budgeting the information a model sees at inference time. Prompts, retrieved evidence, tool results, memory, and state are all parts of context. Context engineering is arguably the core skill of AI engineering. Bigger context windows are not a substitute for better context selection.
Context rotFoundational terms
Degradation of output quality caused by stale, noisy, or accumulated context. Symptoms include stale memory facts, conflicting retrieved evidence, bloated prompt history, and accumulated instructions that contradict each other. A form of technical debt in AI systems.
Context windowFoundational terms
The maximum number of tokens an LLM can process in a single request (input + output combined).
EmbeddingFoundational terms
A fixed-length numeric vector representing a piece of text. Used for similarity search: texts with similar meanings have nearby embeddings.
EndpointFoundational terms
A specific URL path that accepts requests and returns responses (e.g., POST /v1/chat/completions).
GGUFFoundational terms
A file format for quantized models used by llama.cpp and Ollama. When you see a model name like qwen2.5:7b-q4_K_M, the suffix indicates the quantization scheme. GGUF supports mixed quantization (different precision for different layers) and is the most common format for local inference.
HallucinationFoundational terms
When a model generates content that sounds confident but isn't supported by the evidence it was given, or fabricates details that don't exist. Not the same as "any wrong answer"; a model that misinterprets ambiguous instructions gave a bad answer but didn't hallucinate. Common causes: weak prompt, missing context, context rot, model limitation, or retrieval failure.
InferenceFoundational terms
Running a trained model to generate output from input. What happens when you call an API. Most AI engineering work is inference-time work: building systems around models, not training them. Use "inference," not "inferencing."
JSON (JavaScript Object Notation)Foundational terms
A lightweight text format for structured data. The lingua franca of API communication.
Lexical searchFoundational terms
Finding items by matching keywords or terms. Includes BM25, TF-IDF (Term Frequency–Inverse Document Frequency), and simple keyword matching. Returns exact term matches, not semantic similarity.
LLM (Large Language Model)Foundational terms
A neural network trained on large text corpora that generates text by predicting the next token. The core technology behind AI engineering; every tool, pattern, and pipeline in this curriculum runs on top of one.
MetadataFoundational terms
Structured information about a document or chunk (file path, language, author, date, symbol type). Used for filtering retrieval results.
Neural networkFoundational terms
A computing system loosely inspired by biological neurons, built from layers of mathematical functions that transform inputs into outputs. LLMs are a specific type of neural network (transformers) trained on text. You don't need to understand neural network internals to do AI engineering, but knowing the term helps when reading external resources.
Reasoning modelFoundational terms
A model optimized for complex multi-step planning, math, and logic (e.g., o3, o4-mini). Slower and more expensive but better on hard problems. Sometimes called "LRM" (large reasoning model), but "reasoning model" is the more consistent term across provider docs.
RerankingFoundational terms
A second-pass scoring step that re-orders retrieved results using a more expensive model. Improves precision after an initial broad retrieval.
SchemaFoundational terms
A formal description of the shape and types of a data structure. Used to validate inputs and outputs.
SLM (small language model)Foundational terms
A compact model (typically 1-7B parameters) that runs on consumer hardware with lower cost, latency, and better privacy (e.g., Phi, small Llama variants, Gemma). The right choice when privacy, offline operation, predictable cost, or low latency matter more than peak capability.
System promptFoundational terms
A special message that sets the model's behavior, role, and constraints for a conversation.
TemperatureFoundational terms
A parameter controlling output randomness. Lower values produce more deterministic output; higher values produce more varied output. Does not affect the model's intelligence.
TokenFoundational terms
The basic unit an LLM processes. Not a word. Tokens are sub-word fragments. "unhappiness" might be three tokens: "un", "happi", "ness". Token count determines cost and context window usage.
Top-kFoundational terms
The number of results returned from a retrieval query. "Top-5" means the five highest-scoring results.
Top-p (nucleus sampling)Foundational terms
An alternative to temperature for controlling output diversity. Selects from the smallest set of tokens whose cumulative probability exceeds p.
Vector searchFoundational terms
Finding items by proximity in embedding space (nearest neighbors). Returns "similar" results, not "exact match" results.
vLLM (virtual LLM)Foundational terms
An inference serving engine (not a model) that hosts open-weight models behind an OpenAI-compatible HTTP endpoint. Infrastructure layer, not model layer. Relevant when moving from hosted APIs to self-hosting.
WeightsFoundational terms
The learned parameters inside a model. Changed during training, fixed during inference.
Workhorse modelFoundational terms
A general-purpose LLM optimized for speed and broad capability (e.g., GPT-4o-mini, Claude Haiku, Gemini Flash). The default for most tasks. When someone says "LLM" without qualification, they usually mean this.
BaselineBenchmark and Harness terms
The first measured performance of your system on a benchmark. Everything else is compared against this. Without a baseline, you can't tell whether a change helped.
BenchmarkBenchmark and Harness terms
A fixed set of questions or tasks with known-good answers, used to measure system performance over time.
Run logBenchmark and Harness terms
A structured record (typically JSONL) of every system run: what input was given, what output was produced, what tools were called, how long it took, and what it cost. The raw data that evals, telemetry, and cost analysis are built from.
A2A (Agent-to-Agent protocol)Agent and Tool Building terms
An open protocol for peer-to-peer agent collaboration. Agents discover each other's capabilities and delegate or negotiate tasks as equals. Different from MCP (which connects agents to tools, not to other agents) and from handoffs (which transfer control within one system).
AgentAgent and Tool Building terms
A system where an LLM decides which tools to call, observes results, and iterates until a task is complete. Agent = model + tools + control loop.
Control loopAgent and Tool Building terms
The code that manages the agent's cycle: send prompt, check for tool calls, execute tools, append results, repeat or finish.
HandoffAgent and Tool Building terms
Passing control from one agent or specialist to another within an orchestrated system.
MCP (Model Context Protocol)Agent and Tool Building terms
An open protocol for exposing tools, resources, and prompts to AI applications in a standardized way. Connects agents to capabilities (tools and data), not to other agents.
Tool calling / function callingAgent and Tool Building terms
The model's ability to request execution of a specific function with structured arguments, rather than just generating text.
Context compilation / context packingCode Retrieval terms
The process of selecting and assembling the smallest useful set of evidence for a specific task. Not "dump everything retrieved into the prompt."
GroundingCode Retrieval terms
Tying model assertions to specific evidence. A grounded answer cites what it found; an ungrounded answer asserts without evidence.
Hybrid retrievalCode Retrieval terms
Combining multiple retrieval methods (e.g., vector search + keyword search + metadata filters) and merging or reranking the results.
Knowledge graphCode Retrieval terms
A data structure that stores entities and their relationships explicitly (e.g., "function A calls function B," "module X imports module Y"). Useful for traversal and dependency reasoning. One retrieval strategy among several, often overused when simpler metadata or adjacency tables would suffice.
RAG (Retrieval-Augmented Generation)Code Retrieval terms
A pattern where the model's response is grounded in retrieved external evidence rather than relying solely on its training data.
Symbol tableCode Retrieval terms
A mapping of code identifiers (functions, classes, variables) to their locations and metadata.
Tree-sitterCode Retrieval terms
An incremental parsing library that builds ASTs for source code. Used in this curriculum for code-aware chunking and symbol extraction.
Context packRAG and Grounded Answers terms
A structured bundle of evidence assembled for a specific task, with metadata about provenance, relevance, and token budget.
Evidence bundleRAG and Grounded Answers terms
A collection of retrieved items grouped for a specific sub-task, with enough metadata to evaluate whether the evidence is relevant and sufficient.
Retrieval routingRAG and Grounded Answers terms
Deciding which retrieval strategy or method to use for a given query. Different questions need different retrieval methods.
EvalObservability and Evals terms
A structured test that measures system quality. Not the same as training. Evals measure, they don't change the model.
Harness (AI harness / eval harness)Observability and Evals terms
The experiment and evaluation framework around your model or agent. It runs benchmark tasks, captures outputs, logs traces, grades results, and compares system versions. It turns ad hoc "try it and see" into repeatable, comparable experiments. Typically includes: input dataset, prompt and tool configuration, model/provider selection, execution loop, logging, grading, and artifact capture.
LLM-as-judgeObservability and Evals terms
Using a language model to evaluate or grade the output of another model or system. Useful for scaling evaluation beyond manual review, but requires rubric quality, judge consistency checks, and human spot-checking. Not a replacement for exact-match checks where they apply.
OpenTelemetry (OTel)Observability and Evals terms
An open standard for collecting and exporting telemetry data (traces, metrics, logs). Vendor-agnostic.
RAGASObservability and Evals terms
A specific eval framework for retrieval-augmented generation. Measures metrics like faithfulness, relevance, and context precision. One tool example, not a foundational concept. Learn the metrics first, then the tool.
SpanObservability and Evals terms
A single operation within a trace (e.g., one tool call, one retrieval query). Traces are made of spans.
TelemetryObservability and Evals terms
Structured data about system behavior: what happened, when, how long it took, what it cost. Includes traces, metrics, and events.
TraceObservability and Evals terms
A structured record of one complete run through the system, including all steps, tool calls, and decisions.
Long-term memoryOrchestration and Memory terms
Persistent facts that survive across conversations. Requires write policies to manage what gets stored, updated, or deleted.
OrchestrationOrchestration and Memory terms
Explicit control over how tasks are routed, delegated, and synthesized across multiple agents or specialists.
RouterOrchestration and Memory terms
A component that decides which specialist or workflow path to use for a given query.
SpecialistOrchestration and Memory terms
An agent or workflow tuned for a narrow task (e.g., "code search," "documentation lookup," "test generation"). Specialists are composed by an orchestrator.
Thread memoryOrchestration and Memory terms
Conversation state that persists within a single session or thread.
Workflow memoryOrchestration and Memory terms
Intermediate state that persists within a multi-step task but doesn't survive beyond the workflow's completion.
Catastrophic forgettingOptimization terms
When fine-tuning causes a model to lose capabilities it had before training. The model gets better at the fine-tuned task but worse at tasks it previously handled. PEFT methods like LoRA reduce this risk by freezing original weights.
DistillationOptimization terms
Training a smaller (student) model to reproduce the behavior of a larger (teacher) model on a specific task.
DPO (Direct Preference Optimization)Optimization terms
A method for preference-based model optimization that's simpler than RLHF, training the model directly on preference pairs without a separate reward model.
Fine-tuningOptimization terms
Updating a model's weights on task-specific data to change its behavior permanently. An umbrella term that includes SFT, instruction tuning, RLHF, DPO, and other techniques. See the fine-tuning landscape table in Lesson 8.3 for how these relate.
Full fine-tuningOptimization terms
Updating all of a model's parameters during training, as opposed to PEFT methods that update only a small subset. Requires significantly more GPU memory and compute. Produces the most thorough adaptation but carries higher risk of catastrophic forgetting.
Inference serverOptimization terms
Software (like vLLM or Ollama) that hosts a model and serves inference requests.
Instruction tuningOptimization terms
A specific application of SFT where the training data consists of instruction-response pairs. This is how base models become chat models: the technique is SFT, the data format is instructions. Not a separate technique from SFT.
LoRA (Low-Rank Adaptation)Optimization terms
A parameter-efficient fine-tuning method that trains small adapter matrices instead of updating all model weights. Dramatically reduces GPU memory and compute requirements.
Parameter countOptimization terms
The number of learned weights in a model, commonly expressed in billions (e.g., "7B" = 7 billion parameters). Determines memory requirements (roughly 2 bytes per parameter at FP16) and broadly correlates with capability, though training quality and architecture matter as much as size. See Model Selection and Serving for sizing guidance.
PEFT (Parameter-Efficient Fine-Tuning)Optimization terms
A family of methods (including LoRA) that fine-tune a small subset of parameters instead of the full model.
Preference optimizationOptimization terms
Training methods (RLHF, DPO) that use human or automated preference signals to improve model behavior. "This output is better than that output" rather than "this is the correct output."
QLoRA (Quantized LoRA)Optimization terms
LoRA applied to a quantized (compressed) base model. Further reduces memory requirements, enabling fine-tuning on consumer hardware.
QuantizationOptimization terms
Reducing the precision of model weights (e.g., FP16 → INT4) to shrink memory usage and increase inference speed at some quality cost. A 7B model at FP16 needs ~14 GB VRAM; quantized to 4-bit, it fits in ~4 GB. Common formats include GGUF (llama.cpp/Ollama), GPTQ and AWQ (vLLM/HuggingFace). See Model Selection and Serving for format details and tradeoffs.
OverfittingOptimization terms
When a model memorizes training examples instead of learning generalizable patterns. The model performs well on training data but poorly on new inputs. Detected by monitoring validation loss alongside training loss.
RLHF (Reinforcement Learning from Human Feedback)Optimization terms
A training method that uses human preference signals to improve model behavior through a reward model. More complex than DPO (requires training a separate reward model) but offers more control over the optimization objective.
SFT (Supervised Fine-Tuning)Optimization terms
Fine-tuning using input-output pairs where the desired output is known. The most common fine-tuning approach.
TRL (Transformer Reinforcement Learning)Optimization terms
A Hugging Face library for training language models with reinforcement learning, SFT, and other optimization methods.
Consumer chat appCross-cutting terms
The browser or desktop product meant for human conversation (ChatGPT, Claude, HuggingChat). Useful for experimentation, but not the same as API access.
Developer platformCross-cutting terms
The provider's API, billing, API-key, and developer-docs surface. This is what you need for this learning path.
Hosted APICross-cutting terms
The provider runs the model for you and you call it over HTTP.
Local inferenceCross-cutting terms
You run the model on your own machine.
ProviderCross-cutting terms
The company or service that hosts a model API you call from code.
Prompt cachingCross-cutting terms
Reusing computation from repeated prompt prefixes to reduce latency and cost on subsequent requests with the same prefix.
Rate limitingCross-cutting terms
Constraints on how many API requests you can make per unit of time. An operational concern that affects system design and cost.
Token budgetCross-cutting terms
The maximum number of tokens you allocate for a specific part of the context (e.g., "retrieval evidence gets at most 4K tokens"). A context engineering tool for preventing any single component from dominating the context window.