ML & LLM Fundamentals
Tokens, context windows, sampling, embeddings, cosine similarity, and precision/recall trade-offs implemented in Python and verified with pytest.
Before building agents, RAG pipelines, or evaluation harnesses, you need practical intuition for how text becomes vectors, how similarity scores behave, how context windows and sampling affect outputs, and how precision and recall trade off in real systems.
In this module, you will work with tokens and context limits, compare embedding similarity on sample notes, implement cosine similarity and precision/recall helpers in the walkthrough, build and test f1_score in the practice assignment, and verify your work with pytest and GitHub Actions.
What You Will Build
- Embedding and similarity helpers: Compare sample vectors, compute cosine similarity, and rank candidate notes against a query vector.
- Precision and recall walkthrough + F1 assignment: Implement precision and recall in the walkthrough, then independently implement and test
f1_scorein the practice assignment. - Context and sampling notes: Understand how token counts, context windows, temperature, and top-p change predictability and cost.
- Tests and CI: Verify similarity math, edge cases, and precision, recall, and F1 metrics with
pytestand GitHub Actions.
1. Tokens, Context Windows, Sampling, Embeddings, and Precision/Recall
- Tokens and context windows: Models process text as tokens (subword units) rather than raw characters or whole words. Every prompt, system instruction, retrieved document, and generated output shares the context window budget, which affects both latency and token cost.
- Temperature and top-p sampling: Temperature controls how sharply token probabilities are distributed. Top-p (nucleus sampling) considers the smallest set of likely next tokens whose cumulative probability reaches a configured threshold, then samples from that set. Lower temperature or greedy decoding favors higher-probability tokens for more consistent outputs, whereas higher temperature or broader top-p increases diversity. However, these settings influence generation and do not guarantee factual accuracy or valid structured output.
- Embeddings and cosine similarity: An embedding model converts text into a numerical vector, while cosine similarity compares two already-generated vectors by measuring the cosine of the angle between them. Cosine similarity does not itself understand text or generate embeddings. In this module, we use sample vectors to understand the mathematics, and actual embedding-model integration comes later before RAG.
- Precision vs. recall trade-off: Precision measures what fraction of returned or flagged items are actually relevant (
TP / (TP + FP)). Recall measures what fraction of all relevant items were successfully retrieved or caught (TP / (TP + FN)). Tightening a threshold or filter usually raises precision while lowering recall; loosening it usually raises recall while lowering precision.
2. Step-by-Step Build Walkthrough
- Set up the
fde-01-1repository and virtual environment: Create the project folders, configure.env.example,.gitignore, andpyproject.toml, and install editable dev dependencies.macOS / Linux:
mkdir -p fde-01-1/src/fde_01_1 fde-01-1/tests cd fde-01-1 python3 -m venv .venv source .venv/bin/activate python -m pip install --upgrade pip python -m pip install -e ".[dev]" cp .env.example .envWindows (PowerShell):
mkdir fde-01-1 cd fde-01-1 py -m venv .venv .\.venv\Scripts\Activate.ps1 py -m pip install --upgrade pip py -m pip install -e ".[dev]" Copy-Item .env.example .envWindows (CMD):
mkdir fde-01-1 cd fde-01-1 py -m venv .venv .venv\Scripts\activate.bat python -m pip install --upgrade pip python -m pip install -e ".[dev]" copy .env.example .env - Compute cosine similarity between two vectors: Check vector lengths first, reject zero-norm vectors so division by zero cannot happen silently, and compute the dot product divided by the product of norms.
import math def cosine_similarity(vec_a: list[float], vec_b: list[float]) -> float: if len(vec_a) != len(vec_b): raise ValueError("Vectors must have the same dimension") if not vec_a: raise ValueError("Vectors must not be empty") dot = sum(a * b for a, b in zip(vec_a, vec_b)) norm_a = math.sqrt(sum(a * a for a in vec_a)) norm_b = math.sqrt(sum(b * b for b in vec_b)) if norm_a == 0.0 or norm_b == 0.0: raise ValueError("Cannot compute cosine similarity for a zero vector") return dot / (norm_a * norm_b) - Rank sample notes by similarity score: Score candidate notes against a query vector and sort highest-to-lowest so you can inspect top matches and similarity gaps.
def rank_notes( query_vec: list[float], notes: list[tuple[str, list[float]]], ) -> list[tuple[str, float]]: scored = [ (doc_id, cosine_similarity(query_vec, doc_vec)) for doc_id, doc_vec in notes ] return sorted(scored, key=lambda item: item[1], reverse=True)Example output (illustrative: scores depend on your input vectors):
doc_id score note-billing 0.9142 note-webhook 0.7820 note-login 0.1950 - Calculate precision and recall: Track true positives (
tp), false positives (fp), and false negatives (fn) explicitly so zero-denominator edge cases return0.0cleanly instead of raisingZeroDivisionError. This implementation treats retrieved document IDs as unique; duplicate IDs are counted only once.def compute_precision_recall( relevant_ids: set[str], retrieved_ids: list[str], ) -> tuple[float, float]: retrieved_set = set(retrieved_ids) tp = len(relevant_ids & retrieved_set) fp = len(retrieved_set - relevant_ids) fn = len(relevant_ids - retrieved_set) precision = tp / (tp + fp) if (tp + fp) > 0 else 0.0 recall = tp / (tp + fn) if (tp + fn) > 0 else 0.0 return precision, recall - Run tests and commit to Git: Run
pytestlocally, add.github/workflows/pytest.ymlfor CI, and commit your files cleanly.python -m pytest -v git status git add . git commit -m "Complete FDE module 01.1"
Worked example: Retrieval evaluation
Suppose the expected relevant documents are A, B, C, D, while the retrieval system returns A, B, E.
| Metric | Result |
|---|---|
| True positives | 2 |
| False positives | 1 |
| False negatives | 2 |
| Precision | 0.667 |
| Recall | 0.500 |
| F1 score | 0.571 |
3. Common Pitfalls and Operational Hygiene
- Comparing embeddings from different models or dimensions: Vectors from different embedding models or different output dimensions live in incompatible spaces; always verify model compatibility and vector length before comparing.
- Optimizing only for accuracy or only for recall: In imbalanced tasks (such as incident alerts or compliance checks), high accuracy or high precision can hide missed critical items (low recall), while chasing high recall can flood operators with false alarms (low precision).
- Assuming sampling parameters guarantee correctness: Temperature and top-p (nucleus sampling) shape token probability selection, not factual truth or strict JSON schema adherence; always validate outputs and test edge cases.
- Ignoring zero-division or out-of-range edge cases in metrics: When no items are retrieved or no relevant items match, handle denominators safely so evaluation scripts do not crash mid-run.
4. Practice Assignment
In fde-01-1, implement f1_score(precision: float, recall: float) -> float independently in src/fde_01_1/metrics.py (validating that precision and recall are within [0.0, 1.0] and returning 0.0 when precision + recall == 0.0) and add unit tests in tests/test_metrics.py covering:
- Standard precision and recall values (for example,
precision = 0.8andrecall = 0.5, plus the0.667and0.500retrieval example). - Zero precision and zero recall (returning
0.0without division errors). - Perfect precision and recall (returning
1.0). - Out-of-range inputs (such as negative values or values above
1.0) raisingValueError.
Run python -m pytest -v and push your completed fde-01-1 repository (including .github/workflows/pytest.yml) to GitHub.
5. Knowledge Check
- How do tokens relate to context windows and request cost in an LLM workflow?
- How do temperature and top-p (nucleus sampling) affect generation, and why do they not guarantee factual accuracy or valid structured output?
- What is the difference between generating an embedding and computing cosine similarity, and why must you guard against zero vectors or mismatched dimensions?
- What is the difference between precision and recall, and how does F1 relate to them?
- When is high recall more important than high precision, and what is the cost of chasing high recall?
- Why is it risky to compare embeddings generated by two different embedding models?
Self-Review Answers
- 1. Tokens and context windows: Prompts, retrieved context, and model responses consume tokens from a shared context window; more tokens increase latency and usage cost.
- 2. Sampling and guarantees: Temperature controls how sharply token probabilities are distributed, and top-p (nucleus sampling) considers the smallest set of likely next tokens whose cumulative probability reaches a configured threshold, then samples from that set; neither guarantees factual accuracy or schema-valid output.
- 3. Embeddings vs. cosine similarity: An embedding model turns text into a vector, while cosine similarity compares two existing vectors; checking dimensions avoids shape errors and checking zero norm avoids division by zero.
- 4. Precision, recall, and F1: Precision is the share of returned positive items that are relevant; recall is the share of all relevant items that were returned; F1 is their harmonic mean.
- 5. High recall trade-offs: High recall matters when missing a true positive is costly (such as catching risky actions or urgent incidents), at the cost of more false positives and review noise.
- 6. Embedding model compatibility: Different embedding models project text into different vector spaces with different dimensions and semantics, so similarity scores across models are not meaningful.
6. Completion Criteria
- Walkthrough complete:
cosine_similarity,rank_notes, andcompute_precision_recallimplemented and tested. - Practice assignment complete:
f1_scoreimplemented independently and tested across standard, zero, boundary, and out-of-range cases. - Precision vs. recall trade-offs, embedding vs. similarity roles, and sampling or context window behavior explained clearly.
- All
pytesttests pass locally and in GitHub Actions, and the repository is committed to GitHub.
Build this
Implement f1_score(precision: float, recall: float) -> float independently in src/fde_01_1/metrics.py (validating [0.0, 1.0] and returning 0.0 when precision + recall == 0.0) and add unit tests in tests/test_metrics.py covering:
- Standard precision and recall values (for example,
precision = 0.8andrecall = 0.5). - Zero precision and zero recall returning
0.0without division errors. - Perfect precision and recall returning
1.0. - Out-of-range values raising
ValueError.
Run python -m pytest -v and push your completed fde-01-1 repository (including .github/workflows/pytest.yml) to GitHub.
Test your understanding
- How do tokens relate to context windows and request cost in an LLM workflow?
- How do temperature and top-p (nucleus sampling) affect generation, and why do they not guarantee factual accuracy or valid structured output?
- What is the difference between generating an embedding and computing cosine similarity, and why must you guard against zero vectors or mismatched dimensions?
- What is the difference between precision and recall, and how does F1 relate to them?
- When is high recall more important than high precision, and what is the cost of chasing high recall?
- Why is it risky to compare embeddings generated by two different embedding models?
Reveal self-review answers (attempt the questions first)
- Tokens and context windows: Prompts, retrieved context, and model responses consume tokens from a shared context window; more tokens increase latency and usage cost.
- Sampling and guarantees: Temperature controls how sharply token probabilities are distributed, and top-p (nucleus sampling) considers the smallest set of likely next tokens whose cumulative probability reaches a configured threshold, then samples from that set; neither guarantees factual accuracy or schema-valid output.
- Embeddings vs. cosine similarity: An embedding model turns text into a vector, while cosine similarity compares two existing vectors; checking dimensions avoids shape errors and checking zero norm avoids division by zero.
- Precision, recall, and F1: Precision is the share of returned positive items that are relevant; recall is the share of all relevant items that were returned; F1 is their harmonic mean.
- High recall trade-offs: High recall matters when missing a true positive is costly (such as catching risky actions or urgent incidents), at the cost of more false positives and review noise.
- Embedding model compatibility: Different embedding models project text into different vector spaces with different dimensions and semantics, so similarity scores across models are not meaningful.
Questions or notes on this module?