Skip to main content
Software Engineering for Machine Learning

Quality Assurance and System Quality for Machine Learning

Published: 2026-08-01
Level: postgraduate
Audience: Postgraduate students in machine learning and software engineering

Prerequisite Knowledge

This lecture builds on the following concepts from earlier lectures. If any feel unfamiliar, review the linked notes before proceeding.

Previously Covered in This Subject

  • OOP for ML systems — classes, objects, inheritance, and polymorphism — covered in Lecture 10 (Object-Oriented Programming for ML Systems)
  • The ML pipeline and lifecycle — covered in Lectures 1-2 and 3 (The ML Pipeline; ML Pipeline and Lifecycle)
  • Garbage in, garbage out and data quality — covered in Lecture 1 (Convergence of Data Science, AI, and Software Engineering)
  • Measures, metrics, accuracy, and precision — covered in Lecture 4 (GR for ML, Quality Attributes, and System Architecture)
  • Model registry and feature stores — covered in Lecture 7 (Design Patterns for ML Systems: Registry, Serving, and Agentic Orchestration)
  • Batch versus real-time serving — covered in Lecture 7 (The Two Serving Paradigms)
  • Retrieval-Augmented Generation (RAG) — covered in Lecture 5 (Architectural Patterns, CQRS, and Retrieval-Augmented Generation)
  • APIs for ML services — covered in Lecture 11 (APIs for ML Services)
  • Git and Docker overview — covered in Lecture 11 (Version Control and Packaging)

12.1 OOP Applicability in Agentic AI

Object-Oriented Programming (OOP) concepts — especially encapsulation, composition, and polymorphism — apply directly when building agentic AI systems. An agentic AI system is a system in which a large language model (LLM) performs a multi-step task by planning, using tools, and checking its own work, rather than answering a single prompt. The lecture motivates these concepts with a concrete analogy: a Hollywood film production crew.

Hook: Have you ever wondered why a movie credit roll lists dozens of people — gaffer, boom operator, stunt double — when one person could, in theory, do it all? The answer is the same reason your LLM workflow should not be one giant script: a crew divides work so that each specialist can be managed, replaced, and scaled independently.

12.1.1 The Monolithic Procedure Problem

Consider a movie set where the director does everything: holds the cameras, applies the actor's makeup, writes the script line by line, adjusts the lighting, and sweeps the floor. This is absurd — if the lighting breaks, the director stops directing to change a bulb. The situation is fragile and ambiguous: nobody can tell whether the movie fails because of the script, the camera work, or the lighting.

The same problem occurs in software when a monolithic procedure script runs and dozens of if-else statements guide an LLM through a complex workflow. Such a system is highly fragile and impossible to scale. There is no clear way to identify which part to scale, which performance to measure, or which piece of code to fix.

Why the monolithic script breaks:

  • Fragility: one misplaced else branch silently reroutes the entire workflow — a single change can break the whole chain.
  • No observability: if the workflow produces a bad answer, you cannot tell whether the retrieval step, the prompt step, or the validation step caused it.
  • No scaling: when traffic doubles, you cannot spin up just the expensive step (say, the summarizer); you must replicate the entire script.
  • No reuse: the logic is welded together, so a good step (e.g., a keyword checker) cannot be lifted out and reused in another pipeline.

12.1.2 The OOP Crew Approach

In the collaborative (OOP) approach, the production crew is organized so that every crew member — actors, writers, cinematographer — has their own defined role, name, paycheck, and specialist assignment. Each member operates in their own bubble. The same idea underlies the four classic OOP principles: encapsulation, abstraction, inheritance, and polymorphism.

Encapsulation: Each crew member has its own set of tools and duties, keeping track of its own responsibilities independently. Like a capsule, each bubble contains its own scope. In code, encapsulation means a class hides its internal details from the outside — the rest of the system sees only the interface (the methods and attributes you choose to expose), never the wiring underneath.

Encapsulation (from encapsulation = "to enclose in a capsule"): the class hides its internal state and implementation details from the outside world; other code interacts only through a controlled interface. Just as a crew member's script notes are private unless they hand them over, an agent's internal variables are private unless a method exposes them.

Why it matters for agentic AI: the workflow only needs to call agent.execute(); it never needs to know whether the agent uses a regex, a keyword list, or an LLM call internally. The interface is the contract.

Composition: The executive producer merely tells everyone to execute. Each member knows their job and performs it. The overall workflow is composed of these independent roles working together. In code, composition builds larger behavior by combining smaller, independent objects — the workflow does not contain the logic of each step, it merely wires the steps together.

Polymorphism: If a sound engineer needs to be added mid-production, there is no need to shuffle the entire group. The sound engineer plugs in wherever needed, and the existing structure adapts. In code, polymorphism (from Greek poly = many, morph = forms) means many different classes share the same interface: same method name, different behavior.

Polymorphism — one interface, many implementations. Every crew member responds to the same command "action!" — actors act, the cinematographer shoots, the sound engineer records — without the producer managing each differently. Similarly, every scikit-learn classifier has the same fit(X, y) method even though logistic regression and a random forest do completely different math inside. The caller treats every model identically; the behavior differs by class.

Abstraction and inheritance complete the set. Abstraction means dealing with a class at the right level of detail — the producer talks to "the cinematographer," not to the internals of the camera. Inheritance means a new class builds on an existing one (class ValidationAgent(BaseAgent)) so the child reuses the parent's attributes and methods while adding its own. The demo in the next section shows all five concepts in one small system.

12.1.3 Agentic AI Example: Paper Validation Workflow

A concrete code demo — the paper validation system from earlier sessions — illustrates these OOP concepts in agentic AI. The system uses:

  • An abstract base agent class with variables name (string) and model (string), which encapsulates agent identity.
  • Two agents that inherit from the base: a validation agent and a summary agent. Both implement an execute method (returning a string), demonstrating inheritance and polymorphism — one abstract method splits into two different behaviors.
  • The validation agent checks paper length and keywords.
  • The summary agent synthesizes the abstract, producing a summary in about 200–300 words.
  • Both agents feed into a research paper workflow — a composition that chains validation then summarization in sequence.

This single example shows all five OOP concepts: encapsulation (each agent owns its state), abstraction (the base class defines the interface), polymorphism (one execute method, two behaviors), inheritance (agents extend the base), and composition (the workflow composes agents into a pipeline).

Worked trace — the paper validation pipeline in action.

Imagine a student submits a 12-page paper titled "Efficient Attention for Low-Resource Translation" with keywords ["attention", "translation", "low-resource"].

  1. ValidationAgent is constructed — its name = "validation", model = "gpt-4o". Identity is encapsulated: no other object can see or mutate these fields directly.
  2. Workflow calls validation_agent.execute(paper) — the workflow knows nothing about how the check works; it only knows the interface. The agent checks:
  • Length: 12 pages is within the allowed range (say 5–15 pages) → passes.
  • Keywords: all three keywords match the paper's declared keywords → passes.
  • Result: returns "valid" (a string).
  1. Workflow calls summary_agent.execute(paper)polymorphism: same execute name, totally different behavior. The agent instructs its LLM to compress the abstract into 200–300 words and returns the summary text.
  2. Workflow returns the pair (valid, summary)composition: the workflow never performed either step itself; it chained two independent objects.

Sense-check: if the paper were 3 pages, only the validation agent changes its verdict; the summary agent and the workflow code remain untouched — exactly the property the Hollywood crew gave us.

Q: The validation agent is used as part of a feedback loop — is that a reflection pattern? A: Yes, the validation agent acts as a control loop. It checks the output and feeds back into the workflow, which is the essence of the reflection pattern in agentic systems. The same idea returns in Lecture 12.5: a control loop — validate, feed the result back, and decide whether to retry, accept, or retrain — is how both agentic systems and ML Ops keep quality enforced continuously.

Recap: a monolithic script that if-elses its way through a workflow is fragile and unscalable, exactly like a director doing every job on set. The OOP crew — encapsulated agents, one polymorphic execute interface, inheritance from a base class, and a composed workflow — gives you replaceable, testable, scalable components. Real-world connection: production LLM platforms (LangGraph, crewAI, OpenAI Agents) are built exactly this way — small specialized agents wired into a composed graph, which is why the industry standard for agentic AI is a crew of agents, not a script.

12.2 Quality Assurance and System Quality

12.2.1 Why Quality Assurance Matters

Quality assurance ensures that what is being built matches customer expectations and delivered requirements. It measures how much a system deviates from what was promised. Before going to production, a bug-free application must be verified so that clients do not face issues while conducting business.

The eventual goal is to land the system into production, monitor it there, and ensure everything works well with production data. For this, understanding quality assurance and system quality is essential.

Hook: A model can reach 98% accuracy on your test set and still destroy business value in production — because "quality" is not a property of the model alone, it is a property of the whole system in the hands of the customer. That is why this lecture treats QA as a lifecycle activity, not a final check.

Quality assurance (QA) broadly refers to all activities that evaluate whether a system meets its requirements and whether it meets the needs of its users. Three properties are in play, and all three must be verified:

  • Functional correctness — does the software produce the expected output for the given input?
  • Operational efficiency — does it run fast enough, and within its resource budget?
  • Usefulness — does an end user actually get value from it?

QA as a portfolio, not a single test. Quality assurance is a broad portfolio of activities, usually grouped into three kinds:

  1. Dynamic approaches — execute the software and observe it (traditional testing, load testing, runtime monitoring).
  2. Static approaches — analyze code and artifacts without running them (code review, linting, type checking, static analysis).
  3. Process evaluation approaches — analyze how the software was produced (requirements documented? known bugs tracked? tests run after every change?).

The lecture's core claim is that for ML systems this portfolio must extend beyond the code: the data, the model, the pipeline, and the deployed system each need their own assurance — which is exactly the structure of the rest of this lecture (data quality → model quality → pipeline quality → system quality).

Scope — what QA is NOT. QA does not mean "one last testing phase before release." QA is a continuous, lifecycle-spanning activity: the ML Ops control loop (Lecture 12.5) runs validation gates before training, tests the model during development, and monitors drift after deployment. The deviation measurement ("how far is the delivered system from what was promised?") must be re-run every time the data or the code changes — not once at the end.

Why this matters for ML specifically: a traditional application's quality is dominated by code correctness. An ML application's quality is dominated by data and model behavior — which can degrade silently after deployment. So QA in ML means answering not only "does the code run?" but "is the data trustworthy?", "does the model behave well for all user groups?", and "does the deployed system survive production traffic?" The remainder of this lecture builds each of those answers, one layer at a time.

Recap: QA is the set of activities that verify a system against its promised requirements — functional, operational, and user-facing — and it must continue in production, where the real data lives. The remaining sections of this lecture give you the QA toolkit for ML: testing types, data gates, model metrics, pipeline reproducibility, production experimentation, and security.

12.3 Traditional Software Testing vs Machine Learning Testing

Traditional software testing and ML testing differ fundamentally in what they verify, how they fail, and what drives the logic.

Hook: Two teams run their test suites on Friday afternoon. Both pass. On Monday, one product is bug-free and the other quietly recommends winter coats to shoppers in 40 °C summer heat. The difference is not effort — it is what each test suite was verifying.

12.3.1 Logic Source

In traditional software, logic is explicitly programmed. Testing verifies that the code produces expected outputs. Data goes in, the program runs, and any errors are logged and fixed.

In machine learning, logic is learned from data. Testing must verify the learning process, data integrity, and statistical output. Everything starts from and runs around the data.

The core difference — where the rules come from. In traditional software the rules live in the source code: if total > 100: apply_discount(). You can read the code and verify it by hand. In ML the rules live in the model weights, which were learned from data. You cannot "read" a neural network the way you read code — you can only verify it statistically: feed it inputs, compare outputs to expectations, and check the data it was trained on. This is why ML testing is fundamentally about data integrity, the learning process, and statistical output, while software testing is about code behavior.

12.3.2 Failure Modes

Traditional software fails due to bugs — straightaway identifiable errors in the code.

ML fails due to concept drift, data corruption, or biased training data. These failures are subtler and harder to detect.

Why ML failures are stealthier:

  • Bugs are loud; drift is silent. A bug crashes or throws — it calls attention to itself. A model with degraded accuracy still returns a confident-looking prediction; nothing "throws" and nobody notices until the business metric drops.
  • Delayed detection. A bug fails the moment the bad code runs. A biased model fails only when the affected population interacts with it — possibly weeks after deployment.
  • Blame is diffuse. Was it the data pipeline, the labels, the model architecture, or a change in user behavior? Unlike a stack trace, an ML failure rarely points at the responsible component.

12.3.3 Shopping Example: Traditional vs ML Failure

Consider an e-commerce shopping scenario in a hot climate (such as Rajasthan in summer). A user browses summer wear — shirts, t-shirts, shorts — adds items to the cart, and checks out.

Traditional software failure: If there are billing errors or problems adding items to the cart, those are traditional software bugs. The checkout process, payment, and search functions are all code-driven.

ML failure: While shopping, the recommendation engine at the bottom of the page starts showing winter wear — overcoats, winter caps, socks, jackets — alongside summer items. The website itself works perfectly: no UI bugs, no billing issues, no search problems. But the recommendation model is giving wrong suggestions. This is a model training failure — the rules the model learned are not producing correct predictions.

The top layer (checkout, billing, search) is traditional software. The bottom layer (recommendations) is the ML model. When the model recommends winter wear during summer shopping, something is wrong with the ML testing, even though the software layer is fine.

Worked diagnosis — same page, two different failure classes.

Layer Example If it fails, what kind of failure is it? How would you find it?
Checkout + billing + payment Cart total shows ₹1,200 but charges ₹1,900 Traditional bug — a coding error in price arithmetic Unit test the billing function; it is deterministic and reproducible
Search Query "cotton shirt" returns "rubber boots" Traditional bug — a buggy search filter or index Reproduce locally with the same query
Recommendations Browsing summer shirts shows overcoats ML failure — the learned rules do not fit current context Check training data (season), monitor the recommendation metric, slice by category

Sense-check: the same screen, the same user, the same session — yet one failure is a bug you can fix in a debugger, and the other is a learned-behavior failure that requires inspecting data and model behavior, not code. If your testing strategy only covers the top layer, you will ship the winter-coat bug to every summer shopper.

Q: On the traditional side, data is user-entered details and the code reacts to produce results. On the ML side, what does "data" mean — user-given data or system-fed data? A: It has both, and more. In ML, data includes user inputs, system-fed data, and the expected outputs (answers/labels) concatenated together for model training. The algorithm runs on this combined data to generate rules. "Answers" are the expectations or predictions we provide during training — they define what the model should learn to produce.

Recap: Traditional testing verifies code against expected outputs; ML testing verifies learned rules — which means testing the data, the learning process, and the statistical output. Bugs are identifiable and loud; ML failures (drift, corruption, bias) are subtle and silent, so ML QA is a continuous lifecycle activity, not a release-day checklist.

12.4 Types of Software and ML Tests

Machine learning testing caters to three main dimensions (with a fourth, less common one).

Hook: Think of the testing pyramid from Lecture 12.3's shopping example: the checkout layer, the model layer, and the data underneath all need tests — but different kinds of tests. The pyramid is the map of where each kind of test lives.

12.4.1 The ML Testing Pyramid

Base — Data set tests: Everything around the data. Schema validations, unit tests for data cleansing, feature pipelines. The base includes all data-related testing.

Middle — Model tests: How the model performs — fairness, staleness, overfitting checks, robustness, scalability, and predictive performance. Everything around model behavior.

Top — Infrastructure tests (also called system tests): End-to-end pipeline testing, UI integration, latencies, and overall system behavior. Machine learning is only a small part of the entire system; infrastructure testing ensures the model integrates properly with APIs, databases, and other components.

Heuristic tests (less common): Common-sense rules that apply across all phases, most importantly on the data stage. For example, age cannot be negative — a basic sanity check that catches impossible values. Heuristic tests are not a main pillar but hold importance in each testing dimension.

The three-layer testing pyramid for ML systems:

  1. Data set tests (base — widest layer). Everything about the data: schema validations (columns present, correct types), unit tests for data-cleaning functions, and feature-pipeline tests. The base is widest because the largest share of ML bugs historically live here — remember "garbage in, garbage out" (Lecture 12.6).
  2. Model tests (middle). How the model behaves: fairness checks, staleness (is the model up to date?), overfitting checks, robustness, scalability, and predictive performance. Everything around model behavior.
  3. Infrastructure/system tests (top). End-to-end pipeline testing, UI integration, latency requirements, and overall system behavior. The model is only a small part of the whole system — this layer proves the model integrates with APIs, databases, and other components.

Heuristic tests are common-sense rules that apply across all phases, most importantly on the data stage — e.g., "age cannot be negative." They are not a fourth pillar, but they hold importance in each dimension: a schema check catches a type change, a heuristic catches an impossible value, and both are sanity checks that run cheaply on every batch.

Scope — what each layer catches and what it misses. Data tests will not tell you the model is unfair; model tests will not tell you the API times out; system tests will not tell you the training data has a schema bug. Teams that test only the top layer (or only the model) leave two-thirds of the pyramid unverified. The pyramid is not decorative: every layer is a separate failure class (as in the shopping example, the top layer passed while the model layer failed).

12.4.2 Unit Testing in Software vs ML

Unit testing methods are conceptually the same — testing individual modules for correct functionality with varying inputs and checking outputs, including graceful error handling.

However, the way unit tests are performed differs. In traditional software, developers run code against data. In ML, unit tests verify the behavior of algorithms and models. These tests may relate to a module, a core business concept, or an entire application requirement. The scope differs from developer-centric testing to business-centric testing of algorithm behavior.

Unit testing defined. A unit test (from "unit" = one small piece) executes a single unit of functionality — one function, one class, one method — with chosen inputs and asserts the outputs, including graceful error handling. In traditional software the unit is code: test_billing() runs the billing function with different cart contents and checks the totals. In ML the unit is algorithm behavior: test_model() feeds a tiny data set through the training loop and asserts the model learns (loss decreases), or feeds crafted inputs to a trained model and asserts behavior.

The scope shift — developer-centric vs business-centric: a traditional unit test is written by a developer about the code they wrote. An ML unit test is written about the model's behavior — and that behavior is judged against business expectations: a module, a core business concept, or an entire application requirement. Example: a unit test that asserts the recommendation model never returns winter wear when the season feature is "summer" is a unit test of a business concept, not just of code.

Q: Is the unit test method the same for software and ML? A: Conceptually the same — testing individual modules with varying inputs and checking outputs. But in traditional software, developers run code against data; in ML, unit tests verify algorithm and model behavior, which may relate to a module, a business concept, or an application requirement. The scope differs from developer-centric to business-centric.

Recap: ML testing spans three layers — data tests at the base, model tests in the middle, system tests at the top — with heuristic sanity rules running across all of them. Unit testing keeps the same method (isolated module, chosen inputs, asserted outputs) but shifts scope from code correctness to algorithm behavior against business concepts.

12.5 ML Ops Control Loops

The ML Ops control loop describes how testing and monitoring occur continuously throughout the ML lifecycle.

Hook: Most teams treat "deploying the model" as the finish line. In ML Ops, deployment is just the point where the loop closes — the model's life after launch is one continuous cycle of data, training, serving, and re-training.

12.5.1 The Control Loop Flow

  1. Raw data storage: Data arrives and gets validated.
  2. Validation gate: If data fails validation, it gets quarantined and alerts are generated immediately. If it passes, it proceeds.
  3. Feature stores: Data moves into different feature pipelines.
  4. Training orchestrator: Governs the model training process.
  5. Model registries and CI/CD: The model history and pipeline side. Metrics are generated and dashboards are populated.
  6. Deployment to production: If everything passes — data, features, model — it deploys.
  7. Monitoring: After deployment, monitoring continues for any drift. This does not stop at deployment.
  8. Retraining loop: Monitoring triggers the next retraining cycle. Data flows into features, then training, then registry/serving, and finally monitoring — which triggers the next loop.

The key insight is that this is a continuous loop. The job does not finish after deploying to production. Monitoring keeps running, catching any drift, and the cycle repeats. The loop is "controlled" at every stage — metrics flow back into dashboards and trigger retraining when needed.

A control loop is a cycle with feedback. The name comes from control theory: a control loop senses a system's state (here: data and model health), compares it against a target, and adjusts to keep the system on target (here: retrain when drift is detected). Each cycle has the same shape:

Data arrives → validation gate → feature stores → training → model registry + CI/CD
      ↑                                                                          ↓
   monitoring ←────────────────── deployment ←────────────────────────────────────
      ↑ (drift detected) → retraining loop repeats

Every stage feeds the next, and monitoring feeds back into the beginning. "Controlled" means decisions at each stage are made from measured metrics, not guesses.

Where control loops break in practice:

  • Monitoring that never triggers anything. Dashboards that nobody reads are decoration — the loop requires an action (alert → retrain decision) after drift.
  • Quarantine without alerting. Failing data must alert immediately; silently dropped records quietly starve the model of data.
  • Retraining without validation. Retraining on new data reintroduces the whole lifecycle: the new model still has to pass gates 2–6 before it is served. Skipping the loop "for speed" is how broken models reach production.
  • Stopping at deployment. Teams that end the process at step 6 have no idea when the world changed under their model — and drift guarantees that it eventually will.

Recap + Exam note: the ML Ops control loop is the continuous cycle — data → validation → features → training → registry/CI-CD → deployment → monitoring → retraining → back to data. Monitoring never stops at deployment; drift detection triggers the next cycle. Exam note: be ready to describe the full cycle from data validation through monitoring and retraining, and to explain why the loop is "controlled" (metrics drive decisions at every stage).

12.6 Data Quality: The Foundation

The principle of "garbage in, garbage out" governs ML systems. Whatever data is fed to the model, the output will reflect that quality.

Hook: A model is like a student who learns only from the textbook you hand it. Hand it a book with half the pages torn out, wrong answers in the margins, and units that switch midway — and no amount of tutoring can fix what it learned.

12.6.1 Why Data Quality Matters

Hospital temperature example: In a hospital, one ward measures patient temperature in Fahrenheit while another uses Celsius. At a surface level, both are measuring temperature. But the data quality differs because the units are inconsistent. No matter how much historical data is collected, predictions will always be wrong if the inputs are mixed. The model performance degrades and eventually the production system fails.

Data quality dictates the upper bound of model performance. Historical data may contain human biases that the model amplifies. Errors in data collection pipelines degrade production systems. Automated data validation is a strict requirement before any training begins.

Worked example — the mixed-unit hospital data.

A hospital wants a model that predicts sepsis risk from patient temperature. Ward A records in Fahrenheit (°F), Ward B in Celsius (°C).

True temperature Ward A records Ward B records
37.5 °C 99.5 °F 37.5 °C
38.2 °C 100.8 °F 38.2 °C

The two columns are internally fine and individually accurate — both wards measured the same fever. But the combined training set mixes 99.5 with 37.5 as if they were the same unit. The model learns "a value around 37–38 means normal, a value around 100 means danger" — nonsense rules that generalize to nothing.

Sense-check: doubling the historical data makes the problem worse, not better: more mixed-unit examples reinforce the same contradiction. This is why the lecture's rule is absolute — data quality dictates the upper bound of model performance, and automated data validation must run before any training begins. No algorithm can recover information the data never contained in a consistent form.

12.6.2 Dimensions of Data Quality

Accuracy: Data reflects real-world truth. For example, correctly labeled customer churn status. Do not say "tomatoes are purple" — accuracy means matching reality.

Completeness: No missing records or null values. All user profiles have age and locations filled in. There is no ambiguity in the data.

Consistency: Data formats are uniform across the system. Date of birth should not be YYYY-MM-DD in one module and DD-MM-YYYY in another. Formats must be uniform.

Timeliness: Data is up to date and relevant. It should not come from ancient sources. Real-time stock prices, for example, must be delayed by less than one second to be useful.

The four quality dimensions — definitions and failure examples:

Dimension Definition Failure example
Accuracy The data reflects real-world truth — it was recorded correctly Churn label marked "churned" for a customer who is still active; "tomatoes are purple"
Completeness All relevant data was recorded; no missing records or null values A user profile with no age; a shipment record with the item count blank
Consistency Data agrees with itself — same facts, same formats everywhere Date of birth YYYY-MM-DD in one module, DD-MM-YYYY in another; 37.5 °C and 99.5 °F in the same column
Timeliness Data is kept up to date and reflects the current state A stock-price model trained on prices delayed by 5 minutes; a churn model using last year's usage data

The reference literature adds further criteria (uniqueness — every entry recorded once; currentness — kept up to date), but these four are the professor's exam-ready set: accuracy, completeness, consistency, timeliness.

Assumptions & scope — where data quality fails silently.

  • Biases hide inside accurate data. Historical data may be perfectly accurate and systematically biased (e.g., a decade of hiring records from a firm that hired mostly one demographic). The model amplifies those biases because nothing is "wrong" per record.
  • Errors in collection pipelines are invisible. A sensor misreading, a truncated import, a logging outage — each corrupts the data before it ever reaches the model, and the model cannot tell.
  • Timeliness assumptions differ by domain. "Up to date" means under one second for stock prices but could mean a day for weather forecasts. Define the freshness requirement per use case, not globally.

Q: Do ML models follow FAIR (Findable, Accessible, Interoperable, Reusable) principles? A: For interpretability and fairness aspects, yes — the model quality metrics align with FAIR principles. For computational efficiency, it varies depending on the algorithm and type of testing being performed. Computational efficiency is more about algorithm performance than data principles.

Recap: data quality sets the ceiling on model performance — no algorithm can rise above inconsistent, incomplete, or stale data. The four dimensions — accuracy, completeness, consistency, timeliness — are the checklists behind the validation gates that guard every ML pipeline (Lecture 12.7 turns each dimension into a concrete gate).

12.7 Data Pipeline Validation

A data pipeline validation system checks records at gateway stages before they enter training. Each record passes through multiple validation gates.

Hook: A single bad record that slips past validation can silently poison a model trained on a million records. The gates in this section exist to make sure the million are clean before the model ever sees them.

12.7.1 Validation Gate Types

Schema check gate: Verifies missing columns or type changes (e.g., data-to-string conversions). This is the first gateway before data enters training.

Value check gate: Defines impossible ranges — negative ages, statistical outliers. This aligns with heuristic testing (common-sense rules).

Label health check gate: Checks for extreme class imbalances or missing target labels.

Action gate: If inputs do not match expectations, the pipeline automatically holds or quarantines the record.

The four gates, in order:

  1. Schema check gate — structural check: are all required columns present, and do they have the expected types? Catches completeness and consistency failures: a missing age column, or age silently converted to a string.
  2. Value check gate — domain check: does every value fall in a plausible range? age >= 0, price > 0, statistical outliers flagged. This is the heuristic testing from Lecture 12.4 in action.
  3. Label health check gate — target check: are labels present for every record, and is the class distribution sane? Extreme class imbalance (99.9% one class) or missing labels means training would learn a degenerate model.
  4. Action gate — the enforcement point: records that fail any gate are automatically held (quarantined) and an alert is raised. Holding, not deleting, is important — quarantined records preserve audit trails and can be inspected to find the upstream bug.

Each gate maps to a data quality dimension: schema → completeness/consistency, value → accuracy (implausible values), label health → accuracy of the target + completeness, action → enforcement of the pipeline itself.

12.7.2 Worked Example: Three-Record Validation

Three records are passed through the data validation pipeline:

Record 1: User ID with valid age (e.g., 25) and status "active." This record passes all validation gates — schema, value, and label checks all succeed.

Record 2: User ID with negative age (e.g., -5) and status "active." This record fails the value check gate. The error message: "Field age input should be greater than or equal to 0."

Record 3: User ID with the age column entirely missing and status "active." This record fails the schema check gate because the required age field is absent.

The output shows:

  • Record 1 passes all gates and enters the pipeline.
  • Record 2 fails with a validation gate error (negative age).
  • Record 3 fails with a validation gate error (missing age column).
  • The pipeline continues with one valid record out of three.

Worked trace — three records, gate by gate.

Record Schema gate (columns present, right types) Value gate (age ≥ 0) Label gate (status valid) Verdict
R1: {user: u1, age: 25, status: active} ✅ passes ✅ 25 ≥ 0 ✅ active Enter pipeline
R2: {user: u2, age: -5, status: active} ✅ passes ❌ −5 < 0 → "Field age input should be greater than or equal to 0" Quarantined
R3: {user: u3, age: (missing), status: active} ❌ required age column absent — (never reached) Quarantined

Final count: 1 of 3 records enters training; 2 quarantined with a clear error message attached to each. Note the gate order matters — R3 is caught by the first gate, R2 by the second, and the label gate never even runs on them.

Sense-check: each rejection is cheap, fast, and identifies its own failure class — which is exactly what we want at scale, where millions of records pass through every batch and no human can review them.

This shows how the validation pipeline catches errors at the gateway level, before data ever reaches the training stage. In real-world scenarios with lakhs or millions of records, these gates run at scale. The dimensions of accuracy, completeness, consistency, and timeliness must be well-defined and enforced continuously. The pipeline does not stop — it runs in iterative loops, checking every batch of data as it arrives.

Q: Even with lakhs of records, is it still required to validate one by one? Will it not take too much time? A: In real-world ML, we are not testing with just a few lines — it will be lakhs or millions of records. The model runs through reiterative loops. The key is that all quality dimensions (accuracy, completeness, consistency, timeliness) must be well-defined and enforced. The demo shows three records to illustrate the concept, but the same pipeline operates at scale in production, processing batches continuously.

Scope — what the gates cannot do. The four gates catch structural and plausibility problems (missing columns, wrong types, impossible values, bad labels). They cannot catch semantic problems — a correctly formatted age of 35 that was entered for the wrong person, or a perfectly consistent data set that is systematically biased. Those need the deeper data-quality checks (Lecture 12.6's dimensions, bias auditing) and the model-level tests (Lecture 12.9). Gates are the first line of defense, not the last.

Recap: every record entering training runs a gauntlet of gates — schema, value, label health, and the action gate that quarantines failures with immediate alerts. Validation runs continuously on every arriving batch, at scale, mapping directly onto the four data-quality dimensions. Real-world connection: production platforms (e.g., TFX Data Validation, Great Expectations) implement exactly these gates — schema checks, value range checks, and anomaly alerts — as standard components of industrial ML pipelines.

12.8 Pipeline Quality

Pipeline quality ensures reproducibility and automation. No matter how many times a pipeline is run with the same input — days, weeks, or months later — it must produce the same exact outputs.

Hook: "It worked on my machine" is the most expensive sentence in ML. Pipeline quality exists to make that sentence impossible — the same input must produce the same output on any machine, any day.

12.8.1 Key Principles

Reproducibility: Rerunning a pipeline with the same input must yield identical outputs. Data, code, and model artifacts must be explicitly linked and versioned together. If any component changes, the output changes.

Orchestration: Tools like Airflow and Kubeflow manage complex dependency graphs — if some code has a dependency on another part, the orchestrator manages it internally with well-maintained dependency tracking.

Reproducibility defined. A pipeline is reproducible if rerunning it with the same input — days, weeks, or months later — yields the exact same outputs. Three things must be explicitly linked and versioned together as one unit:

  1. Data — the exact snapshot ingested (a versioned data set, not "whatever is in the bucket today").
  2. Code — the scripts and library versions that processed it.
  3. Model artifacts — the trained weights and their metadata (training config, seed, hyperparameters).

If any component changes, the output changes — that is precisely the point: reproducibility means you can explain any output by pointing at the exact triple (data, code, artifacts) that produced it. Practically, this means pinning versions (e.g., hashes for data, requirements.txt for libraries, fixed random seeds) everywhere the pipeline touches.

Orchestration defined. An orchestrator manages the pipeline's dependency graph: which steps must finish before which steps start, what to retry when a step fails, and how to schedule the whole graph. Tools like Airflow and Kubeflow maintain this dependency tracking internally, so a data scientist declares "training depends on feature-building" and the orchestrator enforces the order, reruns failures, and logs every execution.

12.8.2 Continuous Integration for ML Pipelines

CI/CD in the ML context works as follows:

  1. Code commits trigger automated syntax and unit tests.
  2. Model architecture changes trigger training on small synthetic data sets (a form of unit testing for the model).
  3. Data schema updates trigger validation checks against historical data sets.
  4. Successful tests result in deployable artifacts that are ready for deployment to a central repository.

This is the check-in, check-out concept in CI/CD — all tests must pass before code enters the main pipeline.

CI/CD (Continuous Integration / Continuous Delivery) is the practice of automatically testing every change as soon as it is committed, so that broken code never enters the main line. In ML the triggers are broader than in pure software, because three kinds of things can change:

Change Automated response
Code commit Syntax checks + unit tests on the pipeline code
Model architecture change Retrain on a small synthetic data set — a fast "can this model learn at all?" smoke test (unit testing for the model)
Data schema update Re-run validation checks against historical data sets — does the new schema still fit the old data?

Only after all tests pass does the change produce a deployable artifact that goes to a central repository — the check-in/check-out gate: nothing enters the main pipeline without passing every test.

Where pipeline quality breaks:

  • Unversioned data. The code is pinned but the data source is "latest available" — next week's run silently uses different data, and the outputs change with no code change to explain them.
  • Hidden randomness. Training without a fixed seed or floating-point-sensitive library versions makes two runs differ even with identical inputs — the reproducibility contract is broken before you begin.
  • Tests that do not run on the change. A schema update that skips the historical-data validation passes CI silently and breaks training in production.
  • Script-only pipelines. Notebooks and scripts without an orchestrator have no dependency tracking, no retry policy, and no audit log — the opposite of Airflow/Kubeflow-managed graphs.

Recap + Exam note: pipeline quality = reproducibility (same input → same output, via versioned data + code + artifacts) plus orchestration (Airflow/Kubeflow managing the dependency graph). CI/CD for ML means every change — code, architecture, or schema — is automatically tested before it is merged. Exam note: be able to state the reproducibility contract and list what CI/CD triggers for each type of ML change.

12.9 Model Quality

Model quality goes beyond simple accuracy. Accuracy is often misleading, especially in highly imbalanced data sets.

Hook: A model can be 95% "correct" and still be catastrophically wrong — for the people the average hides. This section is about the metrics and techniques that expose what aggregate accuracy buries.

12.9.1 Why Accuracy Alone Is Misleading

Face recognition example: A study showed that a US firm's face recognition model had less than 2–3% accuracy drop for fairer skin tones, but 10–15% accuracy drop for darker skin tones. When looking at the model overall, the accuracy appears very high — perhaps 95% or more. But when the data is broken into subgroups by skin type, the imbalance becomes visible. The model performs well on one demographic and poorly on another.

This is why model quality must be evaluated beyond aggregate accuracy. It includes:

  • Interpretability: The model's outputs must be explainable — if a certain input is pushed, a likable and understandable output should result.
  • Fairness: The data and predictions should not give absurd or biased outputs.
  • Computational efficiency: The mathematical operations must be efficient.

Quality degrades over time and requires continuous validation. Evaluating quality requires testing on data strictly unseen during training.

The three quality lenses beyond accuracy:

  • Interpretability — can you explain why the model gave this output? If the prediction cannot be understood, it cannot be trusted or debugged.
  • Fairness — the model must not give systematically wrong or biased outputs for particular groups. The face-recognition numbers above are a fairness failure: 10–15% drop for darker skin tones is not noise, it is a group effect that aggregate accuracy hides.
  • Computational efficiency — the mathematical operations must run within the latency and cost budget of the application.

Two more hard rules complete the picture: quality degrades over time (drift, Lecture 12.5) and must be continuously re-validated, and evaluation must use data strictly unseen during training — testing on training data only proves the model memorized.

12.9.2 Core Metrics: Precision and Recall

These are the two most important model quality metrics — extremely common in interviews, assignments, and vivas.

Precision measures accuracy: how accurate are the model's positive predictions?

\[ \text{Precision} = \frac{TP}{TP + FP} \]

where \(TP\) is true positive (correctly predicted positive) and \(FP\) is false positive (incorrectly predicted as positive — the model predicted positive but the answer was negative).

Recall measures completeness: does the model capture all actual positives?

\[ \text{Recall} = \frac{TP}{TP + FN} \]

where \(FN\) is false negative (the model predicted negative but the answer was positive — the model missed it).

F1 Score balances precision and recall for imbalanced data. It is the root mean square (harmonic mean) of precision and recall:

\[ F1 = 2 \cdot \frac{\text{Precision} \times \text{Recall}}{\text{Precision} + \text{Recall}} \]

If both precision and recall hold accurate values, the F1 score is also accurate. Otherwise, it produces large errors, especially in regression tasks.

The confusion matrix — the foundation of all four numbers. For binary classification, every prediction falls into exactly one of four cells:

Predicted Positive Predicted Negative
Actually Positive TP (true positive) — correctly caught FN (false negative) — missed
Actually Negative FP (false positive) — false alarm TN (true negative) — correctly passed
  • Precision = \(\frac{TP}{TP+FP}\) — of everything the model called positive, how much was actually positive? "When the model says yes, how often is it right?" (Positive predictive value.)
  • Recall = \(\frac{TP}{TP+FN}\) — of all the actually positive cases, how many did the model catch? "When reality is yes, how often does the model find it?" (True positive rate, hit rate.)
  • F1 = \(2\cdot\frac{\text{Precision}\times\text{Recall}}{\text{Precision}+\text{Recall}}\) — the harmonic mean of precision and recall, a single number that balances them. The harmonic mean is harsh: it is low whenever either number is low, so a model must be good at both to score well. (Some transcripts loosely call this a "balanced average"; the formula above is the standard harmonic mean, which is what is used everywhere in practice.)

Which metric to trust? The professor's rule: if the precision and recall values themselves are computed from a trustworthy confusion matrix, F1 is trustworthy too; if the underlying counts (TP, FP, FN) are wrong, the error flows into F1. Accuracy alone cannot show this — it counts TN in the numerator, which lets a model that says "negative" for everyone still look great.

Worked example — spam filter with real numbers.

A spam filter processes 200 emails. The truth: 60 emails are actually spam. The model flags 50 emails as spam; of those, 40 really are spam (TP = 40, FP = 10). Of the 60 true spam, it missed 20 (FN = 20).

\[ \text{Precision} = \frac{TP}{TP+FP} = \frac{40}{40+10} = \frac{40}{50} = 0.80 \]

\[ \text{Recall} = \frac{TP}{TP+FN} = \frac{40}{40+20} = \frac{40}{60} \approx 0.67 \]

\[ F1 = 2\cdot\frac{0.80 \times 0.67}{0.80+0.67} = 2\cdot\frac{0.536}{1.47} \approx 0.73 \]

Sense-check: the filter is fairly precise (80% of flagged mail is really spam) but catches only two-thirds of actual spam — the F1 of 0.73 reflects both facts, while plain accuracy (correct = TP+TN = 40+130 = 170 of 200 = 85%) would hide the 20 missed spams.

12.9.3 Slicing and Subpopulation Testing (The Iceberg Model)

This is a critical evaluation technique. Think of an iceberg: what is visible above the water looks good, but the massive hidden portion below can cause disaster. The Titanic sank because it hit the iceberg below the waterline — everything looked fine above the surface.

Similarly, a model with 95% global accuracy might have only 50% accuracy on a minority demographic. The overall number hides the problem.

Slicing means dividing data sets into distinct subgroups — by location, gender, device type, skin type, etc. — and calculating performance metrics independently for each slice. This provides actionable insights into specific areas where the model requires mitigation or retraining.

Slicing (subpopulation testing) defined. Slicing splits the evaluation set into distinct subgroups (location, gender, device type, skin type, age band, ...) and computes every metric independently per slice. Aggregate metrics average away group differences — a slice with 50% accuracy is invisible next to a 99% slice. Slicing is what surfaces the face-recognition failure: the global 95%+ is real, and so is the 10–15% drop on darker skin tones — both are true, and only per-slice numbers let you see and act on the second one. The takeaway of the iceberg: the part you cannot see is the part that sinks you.

12.9.4 Worked Example: Slicing Test with Desktop vs Mobile

Eight records are split into two subgroups: desktop (4 records) and mobile (4 records).

Actual labels: [1, 0, 1, 1, 1, 0, 1, 0] (first four = desktop, last four = mobile)

Model predictions:

  • Desktop (first four): [1, 0, 1, 1] — all four match the actual labels perfectly.
  • Mobile (last four): [0, 1, 0, 0] — only the fourth record matches.

Sliced accuracy:

  • Desktop: 4/4 = 100% — all records predicted correctly.
  • Mobile: 1/4 = 25% — only one record predicted correctly.

The global metric hides the fact that the mobile subgroup has critically poor performance. This is why slicing and subpopulation testing is essential — it reveals hidden failures that aggregate metrics mask.

Worked trace — the arithmetic of the iceberg.

Step 1 — write out the records side by side.

# Slice Actual \(y\) Prediction \(\hat{y}\) Correct?
1 desktop 1 1
2 desktop 0 0
3 desktop 1 1
4 desktop 1 1
5 mobile 1 0
6 mobile 0 1
7 mobile 1 0
8 mobile 0 0

Step 2 — compute per slice.

  • Desktop: correct = 4, total = 4 → 100%.
  • Mobile: correct = 1, total = 4 → 25%.

Step 3 — compute the global number.

  • Correct = 4 (desktop) + 1 (mobile) = 5 of 862.5%.

(The professor's slide quotes the same value, 62.5% — 5 correct out of 8, which is exactly what the arrays above produce.)

Step 4 — the lesson: the global 62.5% does not tell you which slice is failing; the sliced numbers tell you the mobile experience is 25%. If the mobile slice were a minority demographic instead of a device type, that 25% would be a fairness failure invisible to the overall metric — the iceberg below the waterline.

Sense-check: global accuracy and sliced accuracy are both "correct" — they answer different questions. Slicing answers "for whom does the model work?" which aggregate accuracy cannot.

Q: Is the point of sub-population and slicing only for analysis purposes? A: No, it is a model testing technique. Remember the testing pyramid: the base is data testing, the middle is model testing, and the top is system testing. Slicing falls under model testing. We do not just test the bottom layer and stop — every stage has its own testing. Slicing is how we verify that the model performs fairly across all subgroups, not just on average.

Recap + Exam note: accuracy alone is misleading — evaluate interpretability, fairness, and computational efficiency too. Precision = \(\frac{TP}{TP+FP}\) (are the positives right?), recall = \(\frac{TP}{TP+FN}\) (are the positives found?), F1 = harmonic mean of the two. Slicing tests each subgroup independently and exposes failures aggregate metrics hide — the iceberg. Exam note: be ready to compute precision/recall/F1 from a confusion matrix, state the iceberg analogy, and work a slicing example end to end.

12.10 Testing Model Training vs Model Inference

Understanding the difference between training testing and inference testing is essential. Combining them is analogous to combining functional and non-functional requirements in testing.

Hook: A model can train beautifully and still fail the moment real users hit it — because "training" and "serving" are two different games with two different rules. Testing each phase is like testing the kitchen (can it cook?) versus testing the restaurant (can it feed 200 customers in peak hour?).

12.10.1 Training Testing (Functional)

Primary goal: Verify learning capability and convergence.

  • Compute constraints: High throughput, long duration, batch processing.
  • Failure modes: Exploding gradients, out-of-memory errors.
  • Environment: Offline — isolated compute clusters.

Training testing answers "can this model learn at all?" It verifies the learning process: does the loss decrease over epochs, does the model converge, does it fit the training data without exploding? Because training runs offline on dedicated clusters, the constraints are different — high throughput (lots of data per second), long duration (hours to weeks of compute), and batch processing (data flows in large chunks, not one query at a time). Failure modes are computational: exploding gradients (loss becomes NaN as updates blow up) or out-of-memory errors (the batch does not fit in GPU memory). This is the functional side — it checks what the model does.

12.10.2 Inference Testing (Non-Functional)

Primary goal: Verify prediction speed, format, and stability.

  • Compute constraints: Low latencies, real-time response, high concurrency.
  • Failure modes: API timeouts, incompatible input shapes.
  • Environment: Online — production-facing, exposed via HTTP services and APIs.

The inference side relates to the previous session's demo where models were exposed as microservices via APIs. If those APIs timeout, that is an inference testing failure. Inference testing can be thought of as a pre-prod to prod scenario — testing how the model will behave when exposed to live users.

Inference testing answers "can the model serve under real conditions?" It verifies how predictions are delivered: speed (low latency — the response arrives in time), format (the JSON/API contract is exactly what the client expects), and stability (the service stays up under load). Constraints flip from training: instead of high throughput you need low latency and real-time response under high concurrency — thousands of simultaneous users. Failure modes flip too: API timeouts (the model took too long) and incompatible input shapes (the caller sent a different schema than the model expects). This is the non-functional side — it checks how well the model's behavior is delivered.

The functional vs non-functional frame. In requirements engineering, functional requirements say what a system must do; non-functional requirements say how well it must do it (speed, reliability, scalability). Training testing is functional — the model must learn (converge on the objective). Inference testing is non-functional — the service must respond fast enough, correctly shaped, and stably. Categorizing your answers this way — functional (training) vs non-functional (inference) — is exactly what earns full marks on this material.

Training testing Inference testing
Question Can it learn? Can it serve?
Goal Learning capability, convergence Speed, format, stability
Compute High throughput, long duration, batch Low latency, real-time, high concurrency
Failure modes Exploding gradients, OOM API timeouts, input-shape errors
Environment Offline, isolated clusters Online, HTTP APIs, production-facing
Category Functional Non-functional

Q: Can inference testing be taken as a pre-prod scenario where we want to move our application to prod? A: Yes, inference testing relates to the pre-prod to prod transition. Production is online-facing, so inference testing verifies how the model behaves when exposed to live users via APIs and HTTP services.

Q: What does "high throughput" mean here? A: Throughput means response time. A model running in different demographic locations (India, UK, Dubai) must consistently return results within a speculated time — a few microseconds. If the same batch processing takes 1 second in India but 5 seconds in Dubai, the model is not maintaining high throughput. The performance must be consistent regardless of location or batch size.

Common pitfalls:

  • Testing training quality only. A converged, accurate model can still fail at inference (timeouts, shape errors) — each phase has its own tests.
  • Assuming "works in my lab" transfers. Offline clusters have no real users; inference testing in the pre-prod environment is what reveals latency and concurrency problems.
  • Ignoring geographic consistency. The professor's rule from the Q&A: high throughput means consistent response time — 1 second in India but 5 seconds in Dubai is a throughput failure even though both "work".

Recap + Exam note: training testing (functional) verifies learning and convergence offline — failures like exploding gradients and OOM; inference testing (non-functional) verifies speed, format, and stability online — failures like API timeouts and shape errors. Exam note: for full marks, categorize each testing concern as functional (training) or non-functional (inference).

12.11 System Quality and Production Experimentation

12.11.1 System Quality: The Holistic View

An ML model is only a small percent — less than 5% — of the total codebase. It interfaces with the UI, databases, network stability, and more. A perfect model with a failing front-end results in zero business value. Clients and stakeholders think in terms of the entire system, not just the model.

System quality requires collaboration between data scientists, software engineers, testers, product managers, and SREs. The system must not compromise its quality at any level.

Hook: The most accurate model in the world is worth nothing behind a broken button. System quality is the shift from "is the model right?" to "is the product right?" — and that shift is measured across three kinds of metrics, not one.

The model is a component, not the system. Less than 5% of the typical production codebase is the ML model itself. The other 95%+ is interfaces: UI, databases, APIs, network, monitoring, config. That means system quality is a whole-team property — data scientists, software engineers, testers, product managers, and SREs (site reliability engineers) must collaborate, and the system must not compromise quality at any level. If any layer fails, the user experience fails — and the business judges the system, never the model in isolation.

12.11.2 Observability in Production: Three Metric Types

Once deployed, the system requires continuous monitoring across three metric dimensions (plus alerting across all):

System metrics (infrastructure): CPU usage, memory consumption, network latencies.

Model metrics (production behavior): Confidence scores, anomaly rates, accuracies, precisions.

Business metrics: Click-through rates, conversion rates, revenue impacts.

Weather.com example: Suppose the model correctly predicts heavy rainfall in a region during monsoon season. But when users click on the interface to see details, they get a 500 HTTP error or the page hangs for 5–10 seconds. Even though the model metrics are good, the system and business metrics are failing — the user experience is ruined.

Alerting holds everywhere — automated thresholds must page engineers when metrics degrade significantly.

The three observability dimensions:

Dimension What it measures Examples
System metrics (infrastructure) Is the machine healthy? CPU usage, memory consumption, network latencies
Model metrics (production behavior) Is the model behaving well? Confidence scores, anomaly rates, accuracies, precisions
Business metrics Is the business winning? Click-through rates, conversion rates, revenue impact

All three must be monitored together, and alerting holds everywhere: automated thresholds page engineers when any metric degrades significantly — not just the model numbers.

Worked diagnosis — the Weather.com scenario.

Monsoon season, coastal region. The model correctly predicts heavy rainfall — model metric ✅. But when users click through for details, they hit an HTTP 500 error or the page hangs 5–10 seconds — system metrics ❌ (latency), and users abandon the site — business metrics ❌ (engagement, revenue).

Metric type Reading Verdict
Model Prediction correct (heavy rainfall)
System 500 errors, 5–10 s hangs
Business Users leave, no engagement

Sense-check: three healthy monitors, one failing component. Only by watching all three can the team see that the problem is the front-end, not the model — and fix the right thing.

12.11.3 Why Offline Testing Is Not Enough

Offline data is static, but user behavior is dynamic and constantly changing. Model changes create feedback loops. Production experimentation provides the final, undeniable proof of business impact. Performance testing (applicable to certain applications) defines how the system performs under real conditions.

Why the lab cannot decide:

  • Offline data is static; users are not. A snapshot of last month's logs cannot predict how users react to the new model today.
  • Feedback loops. Deployed models change user behavior, which changes the next batch of training data — a loop no offline test can capture.
  • Business impact is the final proof. Only experiments on live traffic (A/B, shadow, canary) deliver the undeniable evidence that a model change actually moves the business metric. Performance testing complements this: for latency-sensitive applications it defines how the system must perform under real load.

12.11.4 Traffic Testing Methodologies

Three specific methods for testing traffic in production:

A/B Testing (Split Traffic): Both the current model (version 1.0) and a new model (version 2.0) are exposed to live user traffic simultaneously. Users interact with both versions, and their return predictions are compared. Both models are in production and visible to end users.

Shadow Deployment: The current model serves 100% of user traffic. A shadow model receives copies of the same requests in the backend but is NOT exposed to users. Predictions are logged and compared internally. This is used when stakes are lower or when testing uncertain features. Shadow deployment is not recommended for banking models where features are still being discovered.

Canary Rollout: 99% of traffic goes to the current model. 1% goes to the new model (version 2.0). If the 1% shows positive results, the rollout gradually increases. "Canary" means rolling out bit by bit. This is granular and cautious.

The choice depends on business requirements:

  • A/B testing is used most often across industries.
  • Shadow deployment works for e-commerce and pharmacies but not recommended for banking (where stakes are high and features are still under discovery).
  • Canary rollout is used when small, specific modules need testing with controlled risk.

The three production traffic-testing methods:

A/B testing (split traffic). Both v1.0 and v2.0 serve live users simultaneously; users are randomly split between them, and the outcomes (conversion, clicks, revenue) are compared. Both models are visible to users — so both can affect real customers. Most commonly used across industries.

Shadow deployment. v1.0 serves 100% of traffic. v2.0 silently receives copies of the same requests in the backend and logs its predictions — compared to v1.0's responses internally, after the fact. Users never see v2.0, so no user is ever exposed to a bad v2.0 — but you also cannot measure real user reaction to v2.0's outputs. Best for lower-stakes settings (e-commerce, pharmacies) and uncertain features; not recommended for banking, where the stakes are high and features are still under discovery.

Canary rollout. 1% of traffic goes to v2.0 while 99% stays on v1.0. If the 1% performs well, the share is increased gradually — bit by bit, like a canary carried into a coal mine to detect danger early. Granular, cautious, and used when small specific modules need testing with controlled risk.

Recap + Exam note: system quality monitors three metric types — system (infrastructure), model (production behavior), and business — with alerting on all of them. Offline testing cannot capture live dynamics, so production experimentation closes the loop: A/B testing (both models live, split traffic, most common), shadow deployment (new model in the backend, users unaffected, not for banking), canary rollout (1% → gradually more, granular and cautious). Exam note: know the differences between the three and when each is used, including the industry-specific recommendation against shadow deployment for banking.

12.12 Security for Machine Learning

ML models introduce unique vulnerabilities distinct from traditional web applications. Attackers can manipulate training data or inference requests. Security requires defending both intellectual property (model weights) and data privacy. Threat modeling must be integrated early in the ML lifecycle.

Hook: In a normal web app, an attacker attacks your code. In an ML system, an attacker can attack your model's beliefs — poisoning what it learns, planting hidden triggers, or cloning what it knows — without ever touching your servers.

12.12.1 The Four Major Threats

Data poisoning (data collection phase): Injecting malicious records into the training data. Malicious actors push corrupted or deliberately misleading data during collection, corrupting the model's learned rules.

Backdoor attacks (model training phase): Manipulating algorithms by deliberately pushing certain inputs during training so the model learns incorrect patterns. The manipulators intensively push non-behavioral data to alter the model's precision and algorithm definitions.

Vulnerable libraries (deployment phase): Third-party and open-source libraries (Python packages, open LLM models) may contain vulnerabilities. When deploying, it is critical to verify that all dependencies are secure and do not create attack surfaces.

API serving attacks — adversarial input and model stealing: Malicious actors send unpredicted data to the model's API to discover trends and steal model behavior. They manipulate input data with adversarial effects to reverse-engineer and replicate the model.

Data collection and deployment phases are the most frequently targeted entry points for threat actors — data collection because anyone can inject malicious records, and deployment because open-source libraries are easy to manipulate.

The four major threats, mapped to the ML lifecycle phase they exploit:

Threat Phase How it works
Data poisoning Data collection Malicious actors inject corrupted or deliberately misleading records into the training data, so the model learns corrupted rules — its behavior is wrong from birth
Backdoor attacks Model training Attackers deliberately push specific inputs during training so the model learns hidden incorrect patterns; the model behaves normally in general but misbehaves when the trigger appears
Vulnerable libraries Deployment Third-party and open-source dependencies (Python packages, open LLM models) contain vulnerabilities; deploying them creates attack surfaces
Adversarial input + model stealing API serving Attackers query the model's API with crafted (adversarial) inputs to probe its behavior, discover trends, and reverse-engineer — steal — the model itself

Two assets are defended the whole way: intellectual property (the model weights — the crown jewels a competitor would steal) and data privacy (the training and user data). And the defense is early: threat modeling (thinking about what could be attacked, and how, in each phase) must be integrated at the start of the ML lifecycle, not bolted on at deployment.

Which entry points do attackers actually hit most? The lecture's two most-targeted phases:

  • Data collection — anyone can inject malicious records (e.g., poison a public dataset used for fine-tuning); no server breach required.
  • Deployment — open-source libraries are easy to manipulate or contain known vulnerabilities; supply-chain hygiene (dependency scanning, pinned versions) is the defense.

The training phase is comparatively harder to attack directly — which is exactly why attackers concentrate on the two ends of the pipeline.

Common pitfalls in ML security:

  • Treating ML security like web security. SQL injection and XSS defenses do nothing against poisoned training data or model stealing.
  • Securing only the API. If the training data pipeline is open, attackers do not need the API at all — poisoning beats exploitation.
  • Shipping unverified dependencies. A single vulnerable package (or an untrusted open model) can expose the whole deployment, even with a perfect model inside.
  • Ignoring the model as IP. A cloned model is stolen R&D — model-stealing via API probing is a direct financial attack.

Recap + Exam note: four threats — data poisoning (collection), backdoor attacks (training), vulnerable libraries (deployment), adversarial input/model stealing (API serving). The two most-targeted entry points are data collection and deployment. Defend intellectual property (weights) and data privacy; do threat modeling early. Exam note: be ready to map each threat to its pipeline phase and justify why collection and deployment are the most attacked.

12.13 RAGAS Framework for Evaluating RAG Systems

RAGAS (Retrieval Augmented Generation Assessment) is an automated framework for evaluating RAG pipelines. Traditional metrics like BLEU or ROUGE are inadequate for measuring hallucination and context relevance. RAGAS uses an LLM evaluator to score distinct components of a RAG pipeline without human intervention.

Hook: A RAG system can answer perfectly from memory or lie fluently from nothing — and traditional text metrics cannot tell the difference. RAGAS exists because evaluating a retrieval-and-generate pipeline needs metrics for each of its two halves.

12.13.1 Two Pipeline Architectures

Offline indexing pipeline (data preparation):

  1. Raw data arrives from sources (Wikipedia, project data sets, SharePoint, requirements documents).
  2. Data is broken into chunks.
  3. Chunks are embedded into numerical (vector) form via an embedding model.
  4. Vectors are stored in a vector database.

Online retrieval pipeline (user query):

  1. User submits a query.
  2. The embedding model converts the query into vector form.
  3. Vector search retrieves the top-K matching chunks from the vector database (e.g., top 4–5 matches).
  4. The LLM generator (e.g., GPT-3.5, GPT-4.0) produces the final answer.

The two halves of a RAG system. RAG (Retrieval-Augmented Generation) = retrieve relevant context, then generate the answer from that context. This splits into two pipelines:

  1. Offline indexing pipeline (data preparation). Raw documents (Wikipedia, project data sets, SharePoint, requirements docs) arrive → are chunked into pieces → each chunk is embedded (converted into a numerical vector) by an embedding model → vectors are stored in a vector database. Done once, in the background, before users arrive.
  1. Online retrieval pipeline (user query). User submits a query → the same embedding model converts the query into a vector → the vector database performs a similarity search returning the top-K most matching chunks (e.g., top 4–5) → the LLM generator (GPT-3.5, GPT-4.0, ...) composes the final answer from those chunks.

Everything a RAGAS metric measures belongs to one of these two halves — did we find the right context, and did the model use it well?

12.13.2 RAGAS Core Metrics

The metrics split into two categories — retrieval and generation:

Retrieval metrics:

  • Context precision: Evaluates whether the top retrieved chunks are highly relevant to the query. This is about the precision of the vector search — are the results actually relevant?
  • Context recall: Ensures the retrieval mechanism successfully fetched all necessary facts required to answer the question. This is about completeness — did the search miss anything?

High precision means no irrelevant data in results. High recall means no missing facts.

Generator metrics:

  • Faithfulness: Measures whether the generated answer is strictly grounded in the retrieved context. Detects hallucination — does the LLM stick to what was retrieved, or does it fabricate?
  • Answer relevance: Measures whether the generated answer directly addresses the user's initial query. Does it answer the actual question, or does it provide tangential information?

The four RAGAS metrics — one per failure mode:

Metric Half Question it answers Failure it detects
Context precision Retrieval Of the chunks retrieved, how many are actually relevant? Irrelevant chunks polluting the context
Context recall Retrieval Were all facts needed to answer fetched? Missing facts → incomplete answers
Faithfulness Generation Is the answer strictly grounded in the retrieved context? Hallucination — fabricated claims
Answer relevance Generation Does the answer directly address the user's query? Tangential, off-topic answers

The professor's compact framing: high precision = no irrelevant data in the results; high recall = no missing facts. Traditional metrics like BLEU (n-gram overlap) or ROUGE (recall of n-grams) cannot measure any of this — they compare surface text, so a fluent hallucination can score perfectly. RAGAS instead uses an LLM evaluator (GPT-3.5, GPT-4.0, ...) as an automatic judge — no human intervention needed.

12.13.3 Precision vs Recall: Concrete Intuition

High precision example — spam filter: The spam model must be highly precise. High precision ensures important emails are not incorrectly sent to the spam folder. Every email marked as spam should actually be spam.

High recall example — airport bomb threat: Whether the threat is a hoax or genuine, the system must have high recall — it must catch every potential threat and trigger action. Missing a real threat (low recall) is catastrophic, even if it means investigating some false alarms.

When each matters — the two canonical examples:

  • High precision — spam filter. The cost of a false positive (good email filed as spam) is high — an important client email is lost. So the filter must be strict: everything it flags as spam must actually be spam. Precision is the metric.
  • High recall — airport bomb-threat detection. The cost of a false negative (real threat missed) is catastrophic. So the system must cast a wide net: catch every potential threat and trigger action, even at the price of investigating hoaxes. Recall is the metric.

The general rule: when a missed positive is expensive → maximize recall; when a wrongly-flagged positive is expensive → maximize precision. (See also Lecture 12.9's metrics.)

12.13.4 Worked Example: RAGAS Evaluation

A RAGAS evaluation is run with hardcoded test data. The evaluator uses an LLM (based on an OpenAI API key) to score the pipeline.

Input questions:

  • "What is the capital of France?"
  • "What causes ocean tides?"

Evaluation results:

  • Context precision: 1.0 (perfect — retrieved chunks are all relevant).
  • Context recall: 1.0 (perfect — all necessary facts were retrieved).
  • Faithfulness and answer relevance are also scored.
  • Overall score: 75% (averaged across all metrics).

The framework displays results per question, showing faithfulness, relevance, precision, and recall for each query. This is useful for evaluating how accurately and completely a RAG pipeline performs.

Measurement tools: RAGAS uses foundation models (GPT-3.5, GPT-4.0, etc.) as automatic judges to score outputs.

Worked trace — scoring one question.

Query: "What is the capital of France?"

  1. Retrieval: vector search returns top-4 chunks. All four concern French geography/culture — context precision = 1.0. Among them, the chunk stating "Paris is the capital of France" is present — context recall = 1.0 (no fact needed to answer was missing).
  2. Generation: the LLM answers "Paris." Faithfulness: every claim in the answer appears in the retrieved context → high. Answer relevance: the answer directly addresses the query → high.
  3. Across the two questions, retrieval scores stay 1.0, but generation scores dip slightly on the ocean-tides question (e.g., an answer with a partially tangential sentence), so the overall score averages to 75%.

Sense-check: the per-question, per-metric breakdown is the point of the framework — it tells you which half of the pipeline (retrieval or generation) and which question needs work, something a single BLEU score could never reveal.

Recap + Exam note: RAGAS = automated LLM-judge evaluation of RAG pipelines with four metrics: context precision and context recall (retrieval half — no irrelevant results, no missing facts), faithfulness (grounded in context — catches hallucination) and answer relevance (addresses the query) (generation half). Exam note: be ready to define each metric and apply the precision/recall intuition (spam filter vs airport threat) to the context metrics.

12.14 Version Control and Containers (Introduction)

12.14.1 Git: Version Control

Git is a version control tool that tracks changes over time. Developers check out code from the main branch, work on feature branches, and merge back when done. Multiple developers can work in parallel on different feature branches.

Branching strategies:

  • Never commit directly to the main branch.
  • Use feature branches for active development.
  • Use pull requests for peer reviews before merging.
  • Never commit large data files or heavy model files to Git.

Version control defined. Version control is a tool that tracks every change to code over time, keeping the full history — who changed what, when, and why. Git's model: everyone works from a shared main branch; developers check out the code, do work on their own feature branches in parallel, and merge back when done. The lecture's branching rules are the professional playbook:

  • Never commit directly to the main branch — the main line must stay always-deployable.
  • Use feature branches for active development — parallel work without collisions.
  • Use pull requests for peer reviews before merging — every merge is inspected by another developer.
  • Never commit large data files or heavy model files to Git — Git tracks text diffs efficiently but chokes on big binaries; models and data belong in dedicated artifact stores (this connects to Lecture 12.8's versioned data + model artifacts).

12.14.2 Dependency Management and Packaging

Packaging means bundling code with its dependencies. Python uses requirements.txt (pip-based lists of packages and versions) to manage external libraries. When packaging a Python project:

  • Use proper directory structures.
  • Include metadata (setup.py).
  • Share via private PyPI servers or artifactories.
  • Ensure all external dependencies (e.g., datasets, ragas) are included.

Dependency errors arise when packaged code does not include all required libraries.

Packaging defined. Packaging bundles your code together with everything it needs to run: external libraries, version metadata, and installation instructions. In Python:

  • requirements.txt — the pip-based list of packages and their versions (datasets==2.19.0, ragas==0.1.9); pinning versions is what makes installations reproducible (Lecture 12.8's reproducibility contract).
  • Directory structure + metadata (setup.py) — a proper project layout and the metadata file that describes the package (name, version, entry points).
  • Sharing — via private PyPI servers or artifactories (central repositories).
  • Completeness — every external dependency the code imports (e.g., datasets, ragas) must be listed; a missing one is a dependency error that breaks the consumer's install.

The professor's rule: a package is only as good as its dependency list — "it worked on my machine" becomes "it works in your install" only when every library and version is declared.

12.14.3 Docker: Containers for ML

Docker is a container that bundles everything — code, external dependencies, drivers, OS — into a single image. This eliminates the "it works on my system" problem because the entire environment is packaged together.

A Docker workflow:

  1. Start from a clean Python-based image.
  2. Copy the dependencies file.
  3. Run install commands.
  4. Copy the code.
  5. Define startup commands.
  6. Push the container to the next environment.

Docker ensures reproducibility across development, testing, and production environments. Detailed hands-on work with Docker and Kubernetes will follow in subsequent sessions.

Containers defined. A container (Docker being the industry standard) bundles the code, external dependencies, drivers, and even OS layers into a single image. Where requirements.txt solves library-level consistency, the container solves environment-level consistency: the exact same image runs in development, testing, and production — killing the "it works on my system" problem completely.

The Docker workflow:

  1. Start from a clean Python-based image — a trusted base, e.g., python:3.10.
  2. Copy the dependencies file — bring in requirements.txt.
  3. Run install commandspip install inside the image.
  4. Copy the code — copy your application into the image.
  5. Define startup commands — the command that launches the app when the container starts.
  6. Push the container to the next environment — ship the same image to dev, test, and production.

Why this matters for ML: combined with the versioned data + code + artifacts of Lecture 12.8, a pinned Docker image makes the whole pipeline reproducible end to end. (Kubernetes — container orchestration at scale — is deferred to later sessions; note the connection to Airflow/Kubeflow as orchestrators of pipelines, not containers.)

Pitfalls to avoid:

  • Committing models and data to Git. Large binaries bloat the repository and break versioning; use artifact stores instead.
  • Unpinned dependencies. requirements.txt without versions reproduces nothing — the "same" install differs next month.
  • Building the image ad hoc. Reproducibility comes from the image (steps 1–5 as code), not from running pip install by hand on each machine.
  • Skipping the registry. "Push the container" must target a real repository (registry), or the next environment cannot fetch it.

Recap: Git gives you parallel, reviewed, versioned code history (feature branches + pull requests, never direct commits to main, never large binaries); packaging declares every dependency so installs reproduce; Docker bundles the entire environment into one image so dev, test, and prod behave identically. Together they are the reproducibility toolbox for ML pipelines.

Exam Guidance Summary

Exam note: the professor's exam intel for this lecture, item by item:

  • Precision and recall are extremely common exam questions — understand the formulas, the intuition, and how to compute them from a confusion matrix.
  • F1 score as the balance between precision and recall for imbalanced data sets.
  • Slicing and subpopulation testing — be prepared to explain the iceberg analogy and work through a slicing example.
  • A/B testing vs shadow deployment vs canary rollout — know the differences, when to use each, and industry-specific recommendations (e.g., shadow not recommended for banking).
  • ML Ops control loops — describe the continuous cycle from data validation through monitoring and retraining.
  • Data quality dimensions — accuracy, completeness, consistency, timeliness. Be able to define each with an example.
  • Security threats — data poisoning, backdoor attacks, vulnerable libraries, adversarial input/model stealing. Map each to its pipeline phase.
  • RAGAS metrics — context precision, context recall, faithfulness, answer relevance. Understand what each measures and the precision-vs-recall intuition.
  • Traditional software testing vs ML testing — know the differences in logic source, failure modes, and what is being verified.
  • Categorize answers into functional (training) vs non-functional (inference) aspects for full marks.

Key Industry Applications

  • E-commerce recommendations: The summer/winter wear example illustrates ML testing vs traditional software testing in a real shopping scenario.
  • Face recognition bias: A US firm's model showed 10–15% accuracy drops for darker skin tones, demonstrating why aggregate accuracy is misleading and slicing tests are necessary.
  • Weather.com: A model may predict correctly but the front-end may fail (HTTP 500 errors, latency), showing the importance of system-level metrics beyond model metrics.
  • Banking sector: Shadow deployment is not recommended for banking models where features are still under discovery; stakes are too high.
  • E-commerce and pharmacies: Shadow deployment is acceptable where stakes are lower.
  • Hospital data quality: Mixing Fahrenheit and Celsius across wards degrades model predictions — a concrete example of consistency as a data quality dimension.
  • Airflow and Kubeflow: Industry tools for orchestrating complex ML pipeline dependency graphs.
  • RAGAS framework: Widely used in the market for evaluating RAG pipelines, using LLMs as automated judges (GPT-3.5, GPT-4.0).
  • Docker containers: Industry standard for packaging ML environments to ensure reproducibility across dev, test, and production.
  • Airports and security systems: High-recall systems must catch every potential threat regardless of whether it is a hoax — illustrating the recall concept in a real-world safety context.

SEML Lecture 12 notes

Software Engineering for Machine Learning· postgraduate· 2026-08-01

Sections Breakdown

1OOP Applicability in Agentic AI

Encapsulation, polymorphism, inheritance, and composition applied to agentic AI workflows, illustrated with the Hollywood crew analogy and the paper validation workflow.

2Quality Assurance and System Quality

What QA is, the three property groups, and the dynamic, static, and process-evaluation approaches behind it.

3Traditional Software Testing vs Machine Learning Testing

Where rules come from, how failures differ, and the shopping example separating code bugs from model failures.

4Types of Software and ML Tests

The ML testing pyramid, heuristic tests, and how unit testing shifts from developer-centric to business-centric.

5ML Ops Control Loops

The continuous cycle from data validation through monitoring, drift detection, and retraining.

6Data Quality: The Foundation

Garbage in, garbage out, and the four dimensions of accuracy, completeness, consistency, and timeliness.

7Data Pipeline Validation

Schema, value, label health, and action gates that quarantine bad records before training.

8Pipeline Quality

Reproducibility, orchestration with Airflow and Kubeflow, and CI/CD triggers for ML changes.

9Model Quality

Why aggregate accuracy misleads, precision and recall, F1 score, and slicing for subpopulation testing.

10Testing Model Training vs Model Inference

Functional training testing versus non-functional inference testing with their failure modes.

11System Quality and Production Experimentation

System, model, and business metrics, plus A/B testing, shadow deployment, and canary rollout.

12Security for Machine Learning

Data poisoning, backdoor attacks, vulnerable libraries, and adversarial input and model stealing.

13RAGAS Framework for Evaluating RAG Systems

Context precision, context recall, faithfulness, and answer relevance with an LLM evaluator.

14Version Control and Containers (Introduction)

Git branching, packaging with requirements.txt, and Docker containers for reproducible ML environments.

15Exam Guidance Summary

The professor's exam intel for this lecture, item by item.

16Key Industry Applications

Real-world connections across e-commerce, face recognition, weather services, banking, healthcare, and more.

Postgraduate students in machine learning and software engineering

Exam Revision Notes

Below is the distilled, exam-ready core. Every entry comes from the full explanation above. Use this section for rapid review; return to the main notes when a point needs more context.

OOP Applicability in Agentic AI

Must-know: A monolithic if-else script guiding an LLM is fragile and unscalable; an OOP crew of agents (encapsulation, polymorphism, inheritance, composition) makes agentic workflows replaceable, testable, and scalable.

Top pitfall: Treating a workflow as one big script — no single component can then be scaled, measured, or fixed in isolation.

Self-check: Why is 'one execute method, two behaviors' an example of polymorphism?

Connects to: Section 12.5.

Quality Assurance and System Quality

Must-know: QA = all activities that verify the system meets requirements and user needs: functional correctness, operational efficiency, and usefulness; for ML it extends beyond code to data, model, pipeline, and deployed system.

Top pitfall: Treating QA as a one-time pre-release phase instead of a lifecycle activity that continues through monitoring in production.

Self-check: Name the three broad groups of QA approaches.

Connects to: Section 12.5, Section 12.6.

Traditional Software Testing vs Machine Learning Testing

Must-know: Traditional software: logic explicitly programmed, testing verifies code outputs, fails by identifiable bugs. ML: logic learned from data, testing verifies data integrity + learning process + statistical output, fails silently via drift/corruption/bias.

Top pitfall: Using only code-level tests on an ML system — the model layer (e.g., recommendations) needs its own data and behavior testing.

Self-check: Why is an ML failure 'silent' compared to a traditional bug?

Connects to: Section 12.4, Section 12.6.

Types of Software and ML Tests

Must-know: Pyramid: data set tests (schema, cleansing, features) at the base; model tests (fairness, staleness, overfitting, robustness, scalability, performance) in the middle; infrastructure/system tests (end-to-end, UI, latency) at the top; heuristic rules (e.g., age >= 0) apply across all.

Top pitfall: Testing only the top (system) layer or only the model — each layer catches a different failure class.

Self-check: What does a heuristic test like 'age cannot be negative' belong to, and why?

Connects to: Section 12.3, Section 12.7.

ML Ops Control Loops

Must-know: Continuous loop: raw data → validation gate (quarantine + alert on failure) → feature stores → training orchestrator → model registries/CI-CD → deployment → monitoring for drift → retraining loop; monitoring continues after deployment and triggers the next cycle.

Top pitfall: Treating deployment as the end — monitoring and retraining must continue, otherwise drift silently degrades the model.

Self-check: What happens to data that fails the validation gate?

Connects to: Section 12.1, Section 12.8.

Data Quality: The Foundation

Must-know: Four data quality dimensions: accuracy (matches real-world truth), completeness (no missing/null records), consistency (uniform formats), timeliness (up to date). Garbage in, garbage out — data quality sets the upper bound of model performance.

Top pitfall: Believing more data fixes mixed-unit or inconsistent data — it amplifies the contradiction.

Self-check: Give the Fahrenheit/Celsius example's violation: which dimension fails and why?

Connects to: Section 12.7, Section 12.4.

Data Pipeline Validation

Must-know: Gates in order: schema (missing columns/type changes) → value (impossible ranges, e.g., age >= 0 — heuristic testing) → label health (class imbalance, missing targets) → action gate (auto-quarantine + alert). Validation runs continuously at scale on every batch.

Top pitfall: Assuming validation runs once before training — it must run in iterative loops on every arriving batch, even with lakhs/millions of records.

Self-check: Which gate catches a missing age column, and which catches a negative age?

Connects to: Section 12.4, Section 12.6, Section 12.5.

Pipeline Quality

Must-know: Reproducibility: rerunning with same input yields identical outputs — data, code, artifacts versioned as one linked unit. Orchestration: Airflow/Kubeflow manage dependency graphs. CI/CD triggers: code → syntax+unit tests; architecture → train on small synthetic data; schema → validate against historical data; all pass before artifacts reach the central repo.

Top pitfall: Versioning code but not data (or letting any component change silently) — outputs change with no code change to explain them.

Self-check: What does a data schema update trigger in ML CI/CD?

Connects to: Section 12.5, Section 12.14.

Model Quality

Must-know: Precision = TP/(TP+FP): of predicted positives, how many are right. Recall = TP/(TP+FN): of actual positives, how many are caught. F1 = 2PR/(P+R) harmonic mean. Slicing tests subgroups independently; global 62.5% (5/8) hides desktop 100% vs mobile 25%.

\[F1 = 2 \cdot \frac{\text{Precision} \times \text{Recall}}{\text{Precision} + \text{Recall}}\]

Top pitfall: Trusting aggregate accuracy alone — it hides subgroup failures; compute metrics per slice.

Self-check: With actual [1,0,1,1,1,0,1,0] and mobile predictions [0,1,0,0], what is the mobile slice accuracy?

Connects to: Section 12.4, Section 12.13.

Testing Model Training vs Model Inference

Must-know: Training = functional: verify learning capability + convergence, high throughput/long duration/batch, offline, failures exploding gradients + OOM. Inference = non-functional: verify speed/format/stability, low latency/real-time/high concurrency, online via APIs, failures timeouts + input-shape errors. Categorize answers functional vs non-functional for full marks.

Top pitfall: Testing only training quality — inference failures (timeouts, shape errors) only appear when the model faces live users.

Self-check: Is an API timeout a training or inference testing failure?

Connects to: Section 12.4, Section 12.11.

System Quality and Production Experimentation

Must-know: Three metric types: system (CPU, memory, network latency), model (confidence, anomaly rates, accuracy, precision), business (CTR, conversion, revenue); alert on all. A/B: both models live, split traffic. Shadow: copy traffic in backend, users unaffected, not for banking. Canary: 1% then gradual ramp. Offline testing is not enough — user behavior is dynamic.

Top pitfall: Watching model metrics only — a perfect model behind a failing front-end (HTTP 500) produces zero business value.

Self-check: Why is shadow deployment not recommended for banking?

Connects to: Section 12.5, Section 12.10.

Security for Machine Learning

Must-know: Four threats by phase: data poisoning (collection), backdoor attacks (training), vulnerable libraries (deployment), adversarial input/model stealing (API serving). Most targeted: data collection (anyone can inject records) and deployment (open-source libraries easy to manipulate).

Top pitfall: Treating ML security like traditional web security — attackers can attack the model's learned beliefs (poisoning, backdoors) and clone the model, not just the code.

Self-check: Why are data collection and deployment the most frequently targeted phases?

Connects to: Section 12.6.

RAGAS Framework for Evaluating RAG Systems

Must-know: RAGAS four metrics: context precision (retrieved chunks relevant — no irrelevant data), context recall (all needed facts fetched — no missing facts), faithfulness (answer grounded in retrieved context — detects hallucination), answer relevance (answers the actual query). LLM evaluator scores without human intervention.

Top pitfall: Using BLEU/ROUGE on RAG outputs — surface text overlap cannot measure hallucination or context relevance.

Self-check: Which RAGAS metric detects hallucination, and why?

Connects to: Section 12.9, Section 12.3.

Version Control and Containers (Introduction)

Must-know: Git rules: no direct commits to main, feature branches for development, PRs for peer review, no large data/model files in Git. Packaging: requirements.txt with pinned versions, setup.py metadata, private PyPI/artifactories. Docker: single image with code + deps + drivers + OS; workflow: base image → copy deps → install → copy code → startup command → push to next environment.

Top pitfall: Unpinned dependencies or missing libraries in a package — dependency errors break the consumer's install and reproducibility.

Self-check: Why should model files not be committed to Git?

Connects to: Section 12.8.

Was this lecture useful?

Loading comments…