MODULE 01.1 · PUBLISHED · ~1-2h

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_score in 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 pytest and 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

  1. Set up the fde-01-1 repository and virtual environment: Create the project folders, configure .env.example, .gitignore, and pyproject.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 .env

    Windows (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 .env

    Windows (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
  2. 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)
  3. 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
  4. Worked example: Retrieval evaluation

    Suppose the expected relevant documents are A, B, C, D, while the retrieval system returns A, B, E.

    MetricResult
    True positives2
    False positives1
    False negatives2
    Precision0.667
    Recall0.500
    F1 score0.571
  5. Calculate precision and recall: Track true positives (tp), false positives (fp), and false negatives (fn) explicitly so zero-denominator edge cases return 0.0 cleanly instead of raising ZeroDivisionError. 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
  6. Run tests and commit to Git: Run pytest locally, add .github/workflows/pytest.yml for CI, and commit your files cleanly.
    python -m pytest -v
    git status
    git add .
    git commit -m "Complete FDE module 01.1"

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.8 and recall = 0.5, plus the 0.667 and 0.500 retrieval example).
  • Zero precision and zero recall (returning 0.0 without division errors).
  • Perfect precision and recall (returning 1.0).
  • Out-of-range inputs (such as negative values or values above 1.0) raising ValueError.

Run python -m pytest -v and push your completed fde-01-1 repository (including .github/workflows/pytest.yml) to GitHub.

5. Knowledge Check

  1. How do tokens relate to context windows and request cost in an LLM workflow?
  2. How do temperature and top-p (nucleus sampling) affect generation, and why do they not guarantee factual accuracy or valid structured output?
  3. What is the difference between generating an embedding and computing cosine similarity, and why must you guard against zero vectors or mismatched dimensions?
  4. What is the difference between precision and recall, and how does F1 relate to them?
  5. When is high recall more important than high precision, and what is the cost of chasing high recall?
  6. 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, and compute_precision_recall implemented and tested.
  • Practice assignment complete: f1_score implemented 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 pytest tests pass locally and in GitHub Actions, and the repository is committed to GitHub.
Practice assignment

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.8 and recall = 0.5).
  • Zero precision and zero recall returning 0.0 without 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.

View reference repository ↗

Knowledge check

Test your understanding

  1. How do tokens relate to context windows and request cost in an LLM workflow?
  2. How do temperature and top-p (nucleus sampling) affect generation, and why do they not guarantee factual accuracy or valid structured output?
  3. What is the difference between generating an embedding and computing cosine similarity, and why must you guard against zero vectors or mismatched dimensions?
  4. What is the difference between precision and recall, and how does F1 relate to them?
  5. When is high recall more important than high precision, and what is the cost of chasing high recall?
  6. Why is it risky to compare embeddings generated by two different embedding models?
Reveal self-review answers (attempt the questions first)
  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.
Not completed
Discussion & field notes

Questions or notes on this module?

Leave a note or question

Comments are held in a moderation queue and appear once approved. Your email will not be published.