Skip to main content
Software Engineering for Machine Learning

Responsible ML Engineering and LLMOps — End-to-End Ops and Quality Attributes

Published: 2026-08-22
Level: postgraduate
Audience: Postgraduate students in Machine Learning

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

  • Deployment Strategies (Kubernetes, Ramped, Blue-Green, Canary) — covered in Lecture 14
  • MLOps Pipelines and Lifecycle — covered in Lectures 2–3
  • RAG Architecture and Retrieval — covered in Lectures 5–6
  • Quality Attributes for ML Systems — covered in Lecture 4
  • Microservices and Orchestration Patterns — covered in Lectures 5–7

# Responsible ML Engineering and LLMOps — End-to-End Ops and Quality Attributes

15.1 Deployment Strategies Recap

15.1.1 Overview of Deployment Strategies

Hook: How do you replace the engine of a plane while it is still flying and carrying passengers? That is exactly what a deployment strategy answers — how to move a new version into production without dropping a single user request.

Intuition — Changing Lanes on a Busy Highway: Imagine a highway bridge that must be resurfaced while traffic keeps flowing. You can close the whole bridge at once (basic replace), you can close one lane at a time and gradually shift cars to the new surface (ramped), you can build a parallel bridge and switch traffic in one go once it is ready (blue-green), or you can open the new bridge to a few cars first to watch for cracks before opening it to everyone (canary). Each choice trades speed, cost, and risk differently. The analogy breaks where software is concerned because in software we can perfectly duplicate environments and roll back in seconds, which you cannot do with concrete.

A deployment strategy is the plan we use to move a new version of an application into production without breaking the service for users. The lecture recaps four patterns and carries the thread from the previous session, where the story stopped just after introducing the canary idea.

The Four Strategies Formalized

  • Basic (recreate) strategy: Stop version , then start . Simplest to reason about, but incurs downtime during the swap. Suitable only when brief unavailability is tolerable.
  • Ramped (incremental, rolling) strategy: Gradually shift capacity from old to new. In Kubernetes this is the default RollingUpdate. You increase replicas of step by step — for example from 1 pod toward 7 pods — while proportionally decreasing replicas of until the old pods are deleted. The system overrides the default only when you explicitly configure maxUnavailable or maxSurge.
  • Blue-green strategy: Keep two full environments, Blue (live) and Green (staging). Green runs with production-like data and is fully warmed. Traffic switches from Blue to Green via a router or label change. Rollback is instant because Blue stays ready. Cost is double infrastructure during the switch window.
  • Canary strategy: Release to a small, explicitly chosen subset of users or traffic (say 2–5%) first. Observe error rates, latency, and user feedback. If the canary sings — no anomaly — promote to 100%. If it fails, route that small cohort back and fix without broad impact.
Dimension Ramped / Rolling Blue-Green Canary
Downtime Near-zero Zero (atomic switch) Zero
Infrastructure cost Low (shared pool) High (2× during switch) Low–medium
Rollback speed Moderate (reverse rollout) Immediate (flip back) Immediate for canary cohort
Risk exposure Gradual but broadens quickly All-or-nothing at switch Minimal, isolated first
When to pick Default for stateless services; Kubernetes-native Need instant rollback with full staging fidelity Need real-user validation before full release

Worked Mini-Example — Ramped Rollout from 1 to 7 Pods

Suppose a Kubernetes Deployment currently runs with 7 pods and we roll out with maxUnavailable=1, maxSurge=1:

  1. Step 0 — 7× old, 0× new (stable).
  2. Step 1 — Create 1 new pod. Now 7 old + 1 new (surge). Probe health.
  3. Step 2 — If new pod is Ready, delete 1 old pod. Now 6 old + 1 new.
  4. Steps 3–8 — Repeat create-then-delete until 0 old + 7 new.
  5. Final state — Only serves traffic.

At no point do available pods drop below , so capacity stays above the availability floor. If any new pod fails its readiness probe, the rollout pauses automatically. Sense-check: This is why ramped is the default — it preserves availability with almost no extra machines, unlike blue-green which would need 14 pods simultaneously.

Scope: Ramped and canary assume the service is stateless or its state is externalized (database, cache) so old and new versions can coexist. If the new version introduces a breaking schema migration, you need additional patterns (expand-contract, dual writes) before any of these strategies is safe. Blue-green also assumes you can route cleanly at the edge (load balancer, service mesh) and that warming the green environment with realistic data is feasible.

Visual intuition: Picture a stacked area chart. The x-axis is time across the rollout, the y-axis is pod count. The area for is a descending staircase from 7 to 0; the area for is the mirror ascending staircase from 0 to 7. In a blue-green diagram the chart looks like two solid rectangles side by side with an instant vertical switch line. In a canary diagram the new colour appears as a thin sliver (5% of width) for a long observation period before expanding to fill the chart. Takeaway: ramped shares capacity over time, blue-green duplicates capacity, canary isolates risk in width.

Pitfalls

  • Treating ramped as zero-risk because it is the Kubernetes default. Default values of maxUnavailable/maxSurge may still briefly reduce capacity. Tune them to your SLO.
  • Forgetting persistent state. Rolling pods does not migrate a database. A rollout that changes the schema without a backward-compatible expand step will break the old pods still serving traffic.
  • Canary without meaningful traffic segmentation. If the 5% canary receives only internal test users, you have not tested real-world diversity.

In the session a 45-minute live demo made these ideas concrete. A full CI/CD pipeline built with GitHub Actions (continuous integration: build, test, containerize on every push) and Argo CD (GitOps continuous delivery: reconcile desired state in Git with the Kubernetes cluster) was shown. The demo executed a ramped rollout live by editing the replica count and watching kubectl get pods as new pods entered Running and old pods moved to Terminating and then disappeared. The demo was deliberately not ML-specific so the mechanics of CI/CD were clear — the same pipeline shape transfers directly into ML workflows where the artifact is a model image rather than a plain web service.

Recap: Basic replaces, ramped increments, blue-green duplicates, canary isolates. When availability and cost matter and state is externalized, ramped is the workhorse; when instant rollback and staging fidelity dominate, pay for blue-green; when you need real-user signal before broad exposure, start with a canary. Next we carry this ops foundation into MLOps, where the thing we roll out is not just code but code plus data plus model together.

15.2 MLOps — The Predictive AI Lifecycle

15.2.1 What MLOps Covers

Hook: In classical DevOps you version code. In ML, the thing that fails in production is rarely code alone — it is a tangle of code, data, and model. How do you operate a system whose behaviour is learned from data you did not write?

MLOps defined. MLOps (machine learning operations) is the end-to-end lifecycle discipline for predictive AI — the world of regression (predict a number) and classification (predict a label). Where DevOps focuses primarily on code and infrastructure, MLOps must jointly manage three interacting entities: code (training scripts, feature pipelines), data (datasets, features, labels), and models (learned parameters and their encodings). A change in any one can silently degrade the others, so design, tracking, and evolution must address all three together.

Input data in this regime is often structured data — tables with named columns and typed rows. A canonical example is a CSV file from Kaggle. The Pima Indian Diabetes dataset is a classic binary classification example (predict diabetes yes/no from tabular clinical features). Regression datasets arrive in the same shape (predict a continuous target from tabular features). This shape matters: it dictates what preprocessing (imputation, normalization, encoding), validation (schema checks, distribution skew), and monitoring (feature drift) the pipeline needs.

MLOps, LLMOps, and AgentOps all borrow from DevOps ideas such as CI/CD and staged rollout, but each adds its own workload-specific pipeline shape and metrics family, as the next two sections make clear.

Scope: This predictive framing assumes supervised learning on tabular-ish inputs with a train/serve split and relatively stable schemas. When schemas drift frequently or labels arrive with long delay (as in fraud or churn), the lifecycle needs extra handling for label lag and feedback loops that a naïve code-only pipeline misses.

Visual intuition: Picture a triangle with vertices Code, Data, Model. Edges are bidirectional arrows: data trains the model via code, code transforms data into features, model behaviour reveals data bugs. A change at any vertex propagates to the other two. Takeaway: operating an ML system means governing the triangle, not a single vertex.

15.2.2 Metrics That Matter in MLOps

The ops signal for predictive models. Once a model is in production, four classification metrics and one system metric form the first dashboard layer.

For a binary classifier, let be true/false positives/negatives.

  • Accuracy — fraction of correct predictions:

  • Precision — of the items we called positive, how many were truly positive:

  • Recall (also sensitivity) — of the truly positive items, how many did we find:

  • F1 score — the harmonic mean of precision () and recall (), which balances false positives against false negatives more honestly than a simple average when one of the two is small:

Every symbol is a count; with 1 being perfect. It punishes a model that is precise but misses many positives, or one that recalls everything but floods with false alarms.

  • Latency — wall-clock time to return a prediction for a request, in seconds or milliseconds. A correct prediction that arrives too late is not useful in a live service (think fraud scoring before the transaction clears).

Worked Mini-Example — F1 from Counts

Suppose a diabetes classifier on 100 patients yields .

If instead you used the arithmetic mean , the difference looks tiny here, but with the arithmetic mean is while , correctly flagging that high precision alone does not compensate for terrible recall.

Latency companion: If s and s, latency is ms. For a fraud check, 85ms fits inside a payment authorization window; ms would not. Sense-check: always lies between and and is closer to the smaller of the two.

Pitfalls

  • Accuracy on imbalanced data. With 95% negatives, a model that always says negative scores 95% accuracy and is useless. Prefer or precision-recall per class.
  • Optimizing latency without watching accuracy. A fast model that skips feature computation wins on latency and loses on . Track both jointly.

15.2.3 Workflow and Tooling in MLOps

Pipeline as the product. A production MLOps workflow is orchestrated as a pipeline triggered from CI. Typical stages in order: data collection (ingest from source), data transformation (clean, normalize, encode, featurize), exploratory data analysis (EDA) and visualization (understand distributions, spot leaks), training (fit and validate), evaluation (hold-out and sliced metrics), deployment (publish model artifact), and monitoring (log predictions and drift). Each stage reports its own metrics, and the whole pipeline is versioned so you can reproduce any past run.

Tooling is modular:

  • Experiment tracking: MLflow — log parameters, metrics, and model artifacts per run; compare runs on a dashboard. Used in the earlier MLOps demo.
  • Managed pipelines: SageMaker Pipelines — define, schedule, and execute stages on AWS with lineage tracking (shown in a webinar demo).
  • Orchestration (the conductor): Apache Airflow and Prefect — define the pipeline as a directed acyclic graph (DAG) of tasks and invoke it from CI; Kubeflow Pipelines — same idea natively on Kubernetes with containerized steps. Google Ngram was named as an available resource for language-adjacent exploration but is not a pipeline orchestrator.
  • LLM-adjacent toolkit: LangChain — named as the primary LLM tooling for the session; it reappears centrally in LLMOps rather than in the tabular predictive path.

These orchestrators stitch data, code, and model steps into one runnable workflow and capture metrics at each stage, so a failure can be traced to the exact stage and commit that produced it.

Everyday analogy — Assembly Line with Inspectors: Think of a car assembly line. Raw material enters at one end; each station (stamping, painting, engine) adds value and has its own quality gauge; inspectors at every station log measurements. If a car rattles at the end, you do not blame the whole line — you look at which station's gauge went off. MLOps pipelines are that line for models.

Real-world connection: In an online marketplace predicting home prices from structured listings, the pipeline runs nightly on new sales data, the Airflow DAG validates the incoming CSV schema before featurization, MLflow records which feature set gave the best validation , and deployment promotes the winning model image only if the canary cohort's latency SLO holds.

Pitfalls

  • Notebook-to-pipeline gap. Code that works in a one-off notebook often hard-codes paths, sample sizes, or manual cleaning that breaks on the next day's data. Productionize early.
  • Not versioning data. You pin code in Git but fetch latest.csv by URL. Re-running last week's pipeline on this week's file is not reproducibility — pin the dataset version too.

Recap: MLOps governs the code–data–model triangle for predictive (tabular) AI. Its first dashboard is for correctness and latency for usefulness, and its backbone is a versioned, orchestrated pipeline built with tools like MLflow, Airflow/Prefect, and Kubeflow. That same pipeline instinct carries forward, but the data shape changes entirely when we move to generative AI.

15.3 LLMOps — The Generative AI Lifecycle

15.3.1 What Changes When We Move to Generative AI

Hook: What if your training data is not a neat CSV but a pile of PDFs, slide decks, and photos — and your model does not predict a label but writes the answer in its own words? The whole pipeline shape has to change.

LLMOps is the ops discipline for generative AI (produce text, images, or other content), while MLOps handles predictive AI and AgentOps handles agentic AI. They all borrow CI/CD and staged rollout from DevOps, but the workload and therefore the pipeline differ.

The input shape flips from structured to unstructured. In MLOps a typical input is a CSV with typed columns. In LLMOps the input is unstructured documents — PDFs, PowerPoint decks, Word files, images, and other free-form content — where meaning is not in column positions but in language and layout.

The leading application pattern is a RAG pipeline (retrieval-augmented generation), which accepts almost any unstructured format. Two steps appear that have no counterpart in the tabular world:

  1. Vector embeddings — an embedding is a dense numerical vector, say with or , that encodes the meaning of a chunk of text so that chunks with similar meaning sit near each other in vector space under cosine or dot-product similarity.
  2. Vector database — a store optimized to index and retrieve those vectors by nearest-neighbour search at query time.

A full RAG workflow therefore has its own pipeline shape: ingest unstructured documents, split (chunk) them, embed each chunk, store in the vector database, retrieve the top- chunks most similar to the query, and generate the answer by calling a language model with the query plus retrieved context. That entire workflow — documents, splitter settings, embedding model version, vector index, retriever, and generator — is versioned and monitored.

Where a language model is used it appears in two places: once as the embedding model and once as the final generation model. Either can be a small language model (SLM) or a large language model (LLM). Each call adds cost, latency, and a chance of hallucination (fluent but ungrounded text), which is why the metrics and knobs in the next two subsections matter.

Analogy — Library with a Semantic Card Catalogue: Imagine a vast library where every paragraph is photocopied onto a card and filed not alphabetically but by meaning: cards about "feline diseases" sit next to "cat health" even if they share no words. A question walks in, you find the nearest cards by meaning, lay them on the table, and then ask a resident expert to write an answer using only what is on those cards. Embeddings are the filing rule, the vector database is the catalogue, retrieval is finding the nearest cards, and the LLM is the expert who must stay grounded in the cards you gave. The analogy breaks because embeddings compress meaning lossily — two paragraphs that feel synonymous to a human may still be far apart to a given embedding model.

Scope: RAG grounds answers in supplied documents. Where no relevant document exists, retrieval returns weak neighbours and the generator is tempted to hallucinate. Understanding that boundary is why hallucination rate and temperature belong on the ops dashboard alongside tokens and latency.

15.3.2 Key Application Metrics for LLMOps

The session framed ops metrics in two families that recur across MLOps, LLMOps, and AgentOps: system metrics (CPU, memory, tied to where the app runs, for example a Kubernetes pod on a VM) and application metrics (specific to the AI workload). The LLMOps demo focused on the application family; system metrics were flagged as the natural extension.

Hallucination rate, bias, tokens, and latency.

  • **Hallucination rate — central to LLMOps.* A hallucination* is a fluent answer that is not grounded in the provided context or facts. Measuring it was posed as an open question in the session. Two directions were named: human review, including human-in-the-loop at any stage, and a relevance / faithfulness metric that checks whether the answer stays true to the retrieved context. In today’s evaluations this is often operationalized as an LLM-as-judge or entailment check, but the session left the exact metric open.
  • **Bias measurement — flagged as important. Bias can enter through the dataset (what documents you indexed), the model (what it learned in pretraining), and use** (how you prompt, retrieve, and present). The session deferred the deep treatment to the responsible AI portion rather than handling it fully under LLMOps.
  • **Token usage — pay-per-use cost driver.** Total tokens for a request decomposes as:

where input tokens are the user's prompt, context tokens are the retrieved document chunks supplied alongside, and output tokens are the generated answer. Example from the session: the question "Who is the Prime Minister of India?" counts as input tokens, the answer "The Prime Minister of India is Narendra Modi." counts as output tokens, and a retrieved chunk counts as context tokens. Providers meter by tokens — calls to OpenAI, Gemini, and others are pay-per-use, and model tiers labelled nano or mini versus larger tiers carry different per-token prices. Token usage therefore maps directly to cost.

  • **Latency — wall-clock generation time for a prompt.** Formalized in the demo as in seconds.

The summary slide listed more metrics beyond these, but the live demo treated tokens and latency as the entry point — "the tip of the iceberg."

15.3.3 Hyperparameters That Control Hallucination — Temperature and Top-p

Because hallucination is tied to how the model samples its next token, the discussion moved to the two sampling hyperparameters that every LLM/SLM exposes regardless of vendor (Grok, OpenAI, Claude, Gemini, and others).

Temperature — determinism versus imagination.

Temperature, denoted , is a sampling hyperparameter with

where is fully deterministic (always pick the most likely next token) and is maximally generative under this simplified framing used in the lecture. In fuller textbook treatments temperature divides the logits before the softmax, but this lecture compresses the idea to the operating range.

  • — factual, deterministic behaviour. Arithmetic such as should return , never a creative alternative.
  • — imaginative, generative behaviour. A poem, essay, or marketing slogan benefits from higher .

Concretely: for fact-based tasks set or or even ; for open-ended creative tasks set or ; for a RAG pipeline where the answer must stay grounded in a supplied document, keep to at most so the model does not hallucinate beyond the provided context; for a catchy slogan, push toward .

How this is set in consumer products has evolved. Programmatically we set ourselves in code based on the use case. On portals such as ChatGPT or Claude, behaviour around 2022 when public chat products first appeared typically defaulted to , the "middle path" that balanced every prompt the same way. Today the setting is effectively prompt-adaptive and auto-selected: a prompt that says "this is a math problem, please solve it" leans the system toward ; a prompt that asks for a 1,000-line poem leans toward high . The product infers intent and adjusts the hyperparameter behind the scenes.

Top-p (nucleus sampling) — breadth of the answer.

Top-p, written top_p in code and also called nucleus sampling, controls how much of the token distribution the model may draw from when no explicit length constraint is given. The lecture's plain-language framing: it governs breadth — whether the same question yields a terse one-line answer or a multi-paragraph elaboration.

  • If you say "give me the answer in 50 words" you have set a hard length limit (an instruction, not top-p).
  • If you say "give me the answer" with no limit, top-p governs the free-form breadth. A value such as or or even lets in more of the distribution; smaller values narrow it.

Together, temperature and top-p are the primary knobs for controlling hallucination: lower and narrower settings reduce hallucination on factual and RAG tasks. In the session's shorthand: temperature sets the "factual versus creative" dial, top-p sets the "how much breadth" dial.

Visual — Sampling shape: Imagine the next-token probability distribution as a hillside. Low sharpens the peak — the tallest point dominates. High flattens the hill — many tokens share probability. Low top-p cuts the hillside at a narrow contour and samples only within that summit; high top-p includes the lower slopes. Takeaway: to stay factual, sharpen and narrow; to be creative, flatten and widen.

Scope and nuance: In production APIs temperature often ranges up to 2.0 and top-p is defined strictly as a cumulative-probability cutoff, not a word-count limit. The lecture compresses both to and to "breadth" language for intuition; the textbook definition — sample from the smallest set whose cumulative probability exceeds — is the precise form to carry into exams and docs.

Pitfalls

  • High temperature on a RAG task. You supplied perfect context and then let the model improvise past it. Ground your RAG calls at low .
  • Treating top-p as a word limit. A 50-word instruction and top-p are different mechanisms. One is a prompt constraint; the other shapes the sampling distribution. Use both explicitly where needed.
  • Assuming 2022 defaults still apply. Portals now auto-select temperature from intent. If you bypass the portal via API, you own the setting again.

15.3.4 LLMOps Demo — Document Chatbot With Measured Ops Metrics

The LLMOps demo was marked as additional material added at the last minute for this cohort — not part of the official 16-session slide deck shared with other instructors' batches, but shared with attendees of this session. It serves as the minimal metering template for LLMOps: a document-grounded chatbot that measures application metrics for every request-response pair.

Demo Setup — Document-Grounded Chatbot (Single-Turn)

  • Context: A Word document titled Virtual Machines, about ten paragraphs covering virtualization, virtual machines, hypervisors, isolation, and encapsulation. Any document would work; the topic is interchangeable.
  • Libraries: A Word-to-text package (doc-to-text style: for example python-docx for .docx, with analogous PDF packages like PyPDF2/pdfplumber and PPT packages like python-pptx for other formats) plus MLflow for metric logging. The choice of MLflow is deliberate for continuity with earlier demos — it was already the experiment tracker in the MLOps portion.
  • RAG readiness: This trimmed demo is not yet a full RAG pipeline — it loads one document as context and answers strictly from it, without a splitter, embeddings, or vector database. A fuller deployment would branch on file extension (if file.endswith('.pdf') versus .doc/.docx) and add retrieval over embeddings.
  • Runtime flow: Prompt the user for a Word document path, load it as context, then enter a chat loop. Example prompt: "What are virtual machines? Answer in 50 words." Response (about 40 words, within the limit): "Virtual machines are tightly isolated software containers..." — drawn only from the uploaded document, not the external web.
  • Logs: Three application metrics per prompt-response pair, written to /content/mlflow-logs.zip in the demo environment.

Measured Application Metrics — Definitions

  • Latency — elapsed wall-clock time per request:

where is the time just before the model call and is just after the response returns. Unit is seconds. Sample run: s.

  • Question (input) token count — in this demo, one word equals one token. In code: question.split() then len(words). Punctuation is stripped so trailing ? does not create an extra token. Example: "What are virtual machines? Answer in 50 words." counts as 8 tokens when split on whitespace in this toy tokenizer (the session's logged JSON label: question_token_count = 8).
  • Context token count — same word-split rule applied to the loaded Word document. Demo: context_token_length = 548. This stays fixed for every prompt as long as the same document is loaded and no caching or accumulation is applied.
  • Response (output) token count — same rule on the generated answer. Demo: response_token_length = 285; the actual answer text was 40 words for the 50-word capped request.
  • Total tokens and estimated cost:

The demo multiplies total tokens by a per-token price for the illustrative tier labelled GPT-5.4 nano in the log to produce a dollar/cent figure. The absolute number is hypothetical — the session cautioned not to over-interpret it — but the mechanism (sum of all three token families times price) is exactly what a billable provider does behind the scenes for every user and every prompt.

  • System metrics (not captured in the trimmed demo): CPU usage, memory usage — important when a user uploads a 3–10 GB PDF/PPT and the model must scan large context.

Worked Trace — One Prompt-Response Pair

Given: question "What are virtual machines? Answer in 50 words." → input tokens; context document → context tokens; response → output tokens (toy word-split counts); latency s.

  1. Total tokens: tokens.
  2. Illustrative cost: if dollars per token for a nano tier, dollars (about 2 cents). Change the tier price and the same request costs differently — this is why model selection is a cost knob.
  3. Latency: if and , latency is s.

Port the same prompt to a production subword tokenizer (for example NLTK's wordpiece or a provider's tokenizer) and the count shifts: "virtual" might become one token, "virtualization" might become two or three, punctuation becomes its own token, and 8 can become 10–14. The session explicitly flagged this gap — the toy rule teaches the accounting, but real metering uses subword counts.

Sense-check: Context dominates the total here (). In single-turn mode that cost is paid once per prompt. In multi-turn mode it is paid repeatedly and grows.

Two framings introduced alongside the demo are worth keeping separate in your mental model.

System versus Application Metrics. System metrics (CPU, memory) are fairly constant across MLOps, LLMOps, and AgentOps — they depend on where the app runs (Kubernetes pod, VM, private cloud). Application metrics (token counts, cost, latency) are workload-specific. The LLMOps demo logged only the application family; the system family was flagged as a natural extension that would matter for large-document prompts.

Single-Turn versus Multi-Turn Conversations. The demo is single-turn: supply a document, ask a question, get an answer, end of transaction. No history is carried. This contrasts with ChatGPT-style multi-turn where turn two may say "summarize that answer" and context accumulates. In multi-turn, context_tokens grows over turns; in the demo it stays at . Concatenating context = context + new_document to grow the knowledge boundary within one conversation is an intentional design choice; the robust architecture for that growth is the full RAG pipeline (splitter plus embeddings plus vector database plus retriever).

Pitfalls

  • Shipping the toy tokenizer. word.split() is a teaching stand-in. In production replace it with the provider's tokenizer (for example tiktoken for OpenAI-compatible APIs or the model's own tokenizer) or ask the API's usage field for the authoritative count.
  • Treating total tokens as input only. For RAG, forgetting context_tokens dramatically underestimates cost and can silently exceed the model's context window.
  • Carrying forward stale context in multi-turn. Appending every prior turn without a budget evicts the new relevant chunk out of the window. Budget and compress.

Q: We got the document from Hugging Face, right? And is this sample context we created — can we pass PDFs or images — and is this basically RAG? So why call it LLMOps?

A: The document was created for this demo, not pulled from Hugging Face, and yes any format can be handled by adding the right libraries and branching on file extension. This is backed by a RAG-style idea — answering from supplied context — but the label LLMOps refers to the operations layer on top: measuring input, context, and output tokens, the derived cost, and the latency for every request-response pair, and tracking them over time. RAG is the application pattern; measuring and tracking those metrics in production — that is LLMOps. [Maps to 15.3.qna.1]

Q: Are token counts, context size, cost, and latency the only metrics under LLMOps?

A: No — they are a few salient application metrics highlighted here. LLMOps, like any ops discipline, also has system metrics (CPU, memory) and a broader application set that appears on the summary slide (including hallucination rate, bias, relevance, and others not wired into this trimmed demo). This demo is the tip of the iceberg. [Maps to 15.3.qna.2]

Q: How is the question token count of 8 and context 548 computed? Will context stay at 548 every prompt?

A: One word equals one token in this demo via question.split() and len(), with punctuation such as ? excluded before the count. Context 548 is the Word document's word count by the same method; response 285 and the 40-word answer were counted identically. Yes, context stays at 548 as long as the same document is used and there is no caching or accumulation — it is fixed because the loaded document does not change between prompts. In a multi-turn session the context would grow as history is carried forward. [Maps to 15.3.qna.3, 15.3.qna.4]

Q: Can we extend the Word handler to PDFs and PPTs or images?

A: Yes — add the appropriate libraries (for example PyPDF2/pdfplumber for PDFs, python-pptx for PPTs) and branch on the file extension, for example if file.endswith('.pdf') versus .doc/.docx, dispatching each format to its loader. That conditional makes the chatbot handle multiple formats. [Maps to 15.3.qna.7]

Q: Who actually calculates these metrics — does MLflow calculate them or does it call ChatGPT behind the scenes? Where does the JSON number come from?

A: MLflow is only the logger here, not the calculator. Latency is computed locally as via the system time function. Token counts are computed by local split() logic under the toy one-word-equals-one-token rule. In production LLMs use subword tokenization, so that local rule must be replaced by a proper tokenizer for accurate counts — the simple count is a stand-in to convey the accounting. MLflow then persists the numbers and can surface them in its UI, while the session showed them as a JSON file. You could even just print() them — MLflow's role is persistence and comparison, not measurement. [Maps to 15.3.qna.5]

Q: In production, if I call a ChatGPT API, will ChatGPT itself report tokens so I do not have to recalculate?

A: Behind the scenes a billable provider must calculate input, context, and output tokens for every prompt for every user — otherwise it cannot bill or enforce limits or do provider-side token billing per request. Whether the API surfaces that count to the caller is a product decision that varies by model, tier (free versus paid), and provider. Student questions in this segment specifically probed MLflow logging versus ChatGPT API behavior — does MLflow compute tokens or does the provider call ChatGPT behind the scenes for billing, and can you verify token counts via the API. MLflow here is only the logger: the provider does the metering. Free tiers still meter but may throttle by a max-token limit rather than billing; paid tiers map measured tokens to a per-token price by model tier. A practical check shared in the session: paste the earlier prompt and ask the model "how many input plus context plus output tokens did you process?" and compare answers across tiers and providers — some models reveal counts, some do not. [Maps to 15.3.qna.6]

Q: We omitted LLM metrics like confidence score or bias — on purpose or irrelevant?

A: They are very important and omitted only because this demo was intentionally minimal. Confidence and bias metrics are relevant LLMOps application metrics and appear on the fuller summary slide; they were simply not wired into this trimmed illustration. [Maps to follow-up Q&A on omitted metrics]

Q: Screenshots showed 1,100 input tokens for a tiny prompt — how is that possible? And Gemini sometimes answers token counts, sometimes says it has no access — why the gap?

A: 1,100 tokens for a short sentence is too high even under subword tokenization and was flagged as surprising (the presenter had not seen it with Gemini). Two hypotheses were offered: the count may include accumulated multi-turn history or hidden system instructions added by the provider, or the provider may be counting at a finer subword granularity than expected. 120 output tokens is more plausible under subword counting. No definitive answer was given — it was marked as exploratory, with pointers to subword tokenization references such as NLTK tokenizers for hands-on intuition. Similarly, whether a model reveals counts when asked "how many tokens did you process?" varies by model and tier (free versus premium) and is a product decision often undocumented — students were encouraged to experiment across providers and compare. [Maps to 15.3.qna.8]

Q: Can I append more context later to grow the chatbot's knowledge boundary?

A: Yes — context = context + new_document (or equivalent concatenation of another upload) grows the knowledge boundary within the same session. Increasing the range improves coverage but also grows tokens, cost, and latency and pressures the context window. For a sustained solution the proper architecture is the full RAG pipeline — splitter plus embedding model plus vector database plus retriever — which retrieves only the relevant chunks instead of carrying the whole concatenated history. [Maps to 15.3.qna.9]

Real-world connection: A company help-desk chatbot grounded in Word/PDF runbooks uses exactly this pattern: every ticket prompt logs input, retrieved context, and output tokens plus latency to MLflow; an SLO alerts when latency exceeds 2s or when hallucination rate (flagged by a judge model comparing answer to retrieved context) crosses a threshold, at which point temperature is lowered from to and top-p tightened. The same plumbing scales to hospitals grounding answers in discharge summaries and to law firms grounding in case bundles — any Word document is just the minimal example.

Recap: LLMOps adds unstructured inputs, embeddings, and vector retrieval to the pipeline. Its ops focus shifts to hallucination rate, token accounting (input + context + output), cost, and latency — and to the sampling knobs temperature and top-p that shape hallucination. The Virtual Machines chatbot demo is the minimal template: single document in, strict context grounding, with every turn measured locally and logged. Next we meet AgentOps, where the system does not just answer but acts.

15.4 AgentOps — Operations for Agentic AI

15.4.1 Goals and Metrics for Agentic Systems

Hook: When an AI no longer just predicts a number or writes an answer but books the flight, calls the tool, and spends your money, what does "correct" even mean — and how do you know whether it did the right thing in the right way?

AgentOps was introduced as still upcoming and less mature than MLOps or LLMOps. Sessions on agentic AI and agent tool knowledge set the conceptual stage, but the ops metrics — what to measure and how to define "good" — are still being negotiated in the research literature.

The AgentOps idea. Where MLOps operates predictive models (regression, classification on structured tables) and LLMOps operates generative models (RAG over unstructured documents with token/cost/latency signals), AgentOps operates agentic systems — LLMs wrapped with goals, memory, and tools that act in an environment. The defining shift is from produce an output to pursue a goal through a sequence of tool-using steps.

The pattern emphasized across paradigms is that metrics differ by paradigm: what counts as a failure for a classifier (wrong label) is not what counts for a generator (hallucinated sentence) nor for an agent (wrong tool with wrong arguments that books the wrong flight). You cannot reuse the MLOps dashboard unchanged.

Three representative — and explicitly not comprehensive — metrics were named:

  • **Goal achievement — did the agent accomplish the assigned objective?** Example objective: "book a flight from Bangalore to New Delhi." Success is end-to-end: the right flight is actually booked under the stated constraints. Partial progress (found options but did not book) is not success under this metric.
  • **Task success rate — proportion of tasks that succeed versus fail across runs.** If the agent attempts tasks and succeed, . This is the aggregate view of goal achievement over a workload, analogous to accuracy but at the task level.
  • **Tool call correctness — did the agent call the right tool with the right arguments among the multiple tools it is allowed to invoke?** An agent may have tools such as search_flights, book_flight, cancel_booking, check_budget. Calling search_flights with {from:"BLR", to:"DEL", date:"2026-08-23"} when that matches intent is correct; calling book_flight before searching, or with a missing date, is incorrect even if the final answer sounds plausible.

These three were flagged as representative, not exhaustive — expect additional metrics around cost per task (tokens plus tool fees), latency to goal, safety/permission violations, and reproducibility to appear as the field stabilizes.

Tooling for building and operating agents. Frameworks that were named for AgentOps orchestration all carry ops-side features (logging, tracing, evaluation):

  • CrewAI — orchestrate role-based agent crews with task handoffs and tool scopes.
  • AutoGen — multi-agent conversation patterns with tool use and human-in-the-loop hooks.
  • LangGraph — graph-based agent orchestration (stateful, cyclic workflows) built on LangChain, with checkpointing and observability primitives.

The same frameworks that help you build an agent increasingly help you operate it — trace every tool call, replay a failed trajectory, and score task success.

Analogy — Travel Agent versus Travel Agency Manager: An LLM is like a talented travel agent who can write a beautiful itinerary (generate text). An agentic system is the agent plus the authority to actually call the airline, swipe the card, and rebook when a flight cancels. MLOps would evaluate whether the itinerary price prediction was accurate; LLMOps would evaluate whether the description was grounded and how much it cost to generate; AgentOps evaluates whether the trip got booked correctly and whether the right calls were made with the right arguments along the way. The analogy breaks because unlike a human agent, an AI agent can attempt dozens of tool calls per second, so the blast radius of a wrong tool call policy is much larger.

Scope: Because agentic behaviour depends on external tool state (airline inventory, payment gateways, calendars), strict output reproducibility in AgentOps is nuanced. The same open-ended goal run days later may legitimately produce a different booking even with identical agent code — a theme picked up in the reproducibility discussion ahead.

Visual intuition: Picture a trajectory trace: nodes are agent turns, edges are tool calls with arguments, and the final node is marked success or failure against the goal. A dashboard aggregates many such traces into a success-rate bar and a tool-correctness confusion matrix. Takeaway: AgentOps observes paths, not just final answers.

Pitfalls

  • Judging an agent by answer fluency. A beautifully written summary that booked the wrong date scores zero on goal achievement.
  • Ignoring tool argument quality. Calling the right tool with a hallucinated argument (wrong airport code, missing constraint) is still a failure — audit arguments, not just tool names.
  • Assuming MLOps metrics transfer. Do not apply to an agent's tool trace; design task-level success criteria instead.

Real-world connection: A corporate travel agent that automates "book the cheapest morning flight under budget with a changeable fare" is measured by goal achievement (was a compliant ticket issued?), task success rate over hundreds of requests, and tool call correctness (did it call search before book, with the right airport codes and fare-class filter?). Frameworks like CrewAI and LangGraph provide the trace that makes those three numbers computable — and the same trace is what you need to debug why Tuesday's run booked the wrong airline.

Recap: AgentOps is the newest of the three Ops flavours. Its primitive is a tool-using agent pursuing a goal, and its first representative signals are goal achievement, task success rate, and tool call correctness — measured over trajectories, not single predictions. Like MLOps and LLMOps it borrows CI/CD discipline from DevOps, but its metrics are its own. Next we step back from any single paradigm and ask what quality means when any of these systems can cause real harm.

15.5 Responsible ML Engineering — Quality Attributes Beyond Functionality

15.5.1 Why This Section Exists

So far the course has delivered functionality: architecture, design, development, ops, and their metrics across 14 sessions. The final stretch turns to quality attributes — also called non-functional requirements — the qualities that determine whether functionality does more good than harm once deployed.

Hook: A model can be 99% accurate, ship on time, and still ruin lives. When does "it works" stop being enough?

Quality attributes for ML. In classical software engineering the headline quality attributes are often scalability and performance. In ML engineering a parallel set applies, and the session made the stakes explicit: these attributes can cause real harm if ignored, and harm scales with model deployment.

Each attribute in this section — explainability, fairness, safety, security, privacy, and others — could fill two full sessions with tools and deeper techniques. This course compresses them into the final sessions to give a software engineering grounding for what each term means, why it matters differently in predictive, generative, and agentic AI, and how to reason about it before adding specialist tooling. The treatment here stays at a conceptual level plus textbook grounding, with the promise that future iterations will add more hands-on demos.

The textbook grounding for this responsibility portion is Chapters 23 through 28 of textbook one, which map to: responsible engineering, versioning/provenance/reproducibility, explainability, fairness, safety, and security and privacy. Students were asked what they already knew about these terms from other courses, and that prior knowledge shaped the discussion that followed.

The set of principles presented as the pillars of responsible AI in this lecture is: versioning, provenance, reproducibility, explainability, fairness, safety, security, and privacy. The session worked through the first three (15.5.5) in detail and left the remaining five to start from the next session, noting that about five minutes remained and that explainability would open the next class.

Scope: This is a grounding pass, not a specialist deep dive. Expect conceptual definitions, harm taxonomy, and the first pillar (versioning/provenance/reproducibility) here; expect tooling for explainability, fairness, and the others to follow. The exam posture for this lecture is therefore conceptual understanding plus applied ops metrics, not a checklist of chapter numbers.

15.5.2 Software Can Cause Real Harm — Before We Even Add ML

Traditional software without any ML has already caused severe harm. Four cases were used to anchor why quality and responsibility matter — and why ML makes the blast radius larger, not smaller.

Four Anchoring Cases — Physical, Financial, and Reputational Harm

  1. Radiation therapy machine (1985) — Therac-25-style software fault. Instead of delivering a prescribed dose of say units, the machine delivered a higher dose such as units due to a software logic fault and race condition, causing fatal overexposure. Three people died in 1985. The failure was purely in software logic, not hardware.
  1. Ariane-family rocket — reused code, unchecked assumption. Code reused from a prior successful launch was carried into a new vehicle without thorough end-to-end re-testing. An unhandled assumption (a value that fit in the old vehicle's range but overflowed in the new one) destroyed the rocket 37 seconds after launch, with a loss cited as 500 billion in the session's units. Even if the currency or magnitude is recalled loosely across retellings, the lesson is fixed: reuse is not free.
  1. Knight Capital Group — faulty deployment (2012). A trading software deployment pushed a latent bug into production. The bug triggered unintended trades, and the firm lost 460 million dollars in about 45 minutes before it could roll back to a stable version. This is a deployment and testing failure, not a model failure — and exactly the kind of failure a canary or blue-green strategy is designed to contain.
  1. Horizon accounting software — UK Post Office (1996–2018 era). Data and error-handling bugs in the Horizon system used by UK postal workers led to 540 workers being wrongly convicted of fraud. The harm was not to the company's balance sheet but to people: lives and careers ruined, reputations lost, with convictions overturned only after lengthy legal proceedings.

Takeaway: Harm can be physical and fatal, financial and massive, or reputational and life-altering — even before any ML is in the loop. ML amplifies each because a flawed model acts at scale and on every decision.

Sense-check: Every case above traces to a quality attribute failure — insufficient testing, unsafe reuse, unchecked deployment, poor error handling — not to a missing feature.

15.5.3 Categories of Harm in ML Systems

The textbook organizes ML harms into several categories and each was discussed with examples. The whole taxonomy was summarized on a single slide and students were given a pause to read it before diving into definitions.

A Harm Taxonomy for ML Systems

  • **Safety — physical harm to people.** Three examples were given: a delivery robot that blocks a wheelchair user at a crosswalk, a self-driving car that misinterprets a stop sign and causes a crash, and medical device software that delivers an incorrect dosage. This connects back to the self-driving Apollo case study from the second session. In safety analysis, the object of harm travels with the human body.
  • **Manipulation and addiction — exploiting how we interact with software.* The infinite scroll and autoplay patterns on Facebook and Instagram were the opening example. The scroll keeps users engaged for hours by recommending new posts based on addiction mechanisms. A design detail was stressed: when smartphones first appeared the dominant scroll was left to right, but most apps shifted to top-to-bottom, which studies cited in the session link to longer hooked sessions. Personalized ads are a second example: the system learns that a user shops frequently at a sports retailer and then exploits that vulnerability to drive impulsive buying. The mental model to keep straight: addiction is the user's hooked state; manipulation* is the intended design choice that creates it.
  • **Polarization and mental health — division and distress as side effects.** Polarized news and social feeds can divide people into opposing ideological camps, feeding each side content that hardens the split. Students were reminded not to fixate on one country — the pattern is global. Excessive exposure is linked in the discussion to anxiety, depression, and low self-esteem, even when the surface metric ("more engagement") looks positive. Students were invited, without any political framing, to share examples they had seen in the chat.
  • **Job loss, weapons, and surveillance — scary, fast-moving, deliberately not dwelt on. One example named was mass facial recognition in railway stations and other large crowds. Contrast was drawn: facial recognition for attendance inside a college campus is bounded and consent-scoped, while city-wide mass recognition tracks people across spaces without meaningful consent. An agentic example was also sketched: autonomous robots deployed in the field** that must make their own decisions when connectivity drops in difficult terrain. Giving a system permission to operate autonomously without a network link creates risks that are hard to bound.
  • **Discrimination — given its own treatment because it is often unintentional and therefore easy to miss.* Polarization is intentional — someone wants to split opinion. Discrimination can happen even when no one intends it*, because biased data or flawed models silently produce unfair outcomes. The canonical example was the Amazon automatic hiring system (circa 2013). Training data at that time consisted mainly of male profiles with very few female profiles. When resumes were processed the model selected about 78% of male applicants and rejected many highly qualified female applicants — not because of any explicit rule, but because the model had not seen enough female examples to learn from. That is discrimination via data bias and model flaw, not via intent. More examples were promised in later slides.

Q: What is the difference between manipulation and addiction? And between polarization and discrimination?

A: Manipulation is the designer's intent (infinite scroll, autoplay placed to hook you); addiction is the user's state (the hooked, hard-to-stop scrolling). Similarly, polarization is an intentional strategy to split opinion (feed each side what hardens the split), while discrimination in the Amazon hiring sense was unintentional — no engineer wrote "prefer men," but biased training data plus a model that amplifies what it has seen produced systematically unfair outcomes. The practical consequence: you cannot catch unintentional discrimination by checking intent; you have to measure outcomes. [Maps to 15.5.moment.3, 15.5.moment.5]

Visual intuition: Picture a harm ladder. At the bottom rung is a single-user harm (wrong loan denial); in the middle is a community harm (polarized feed); at the top is a societal harm (wrongful convictions at scale, autonomous weapons). A single quality failure — a biased dataset, a reused assumption — climbs the ladder when the system scales. Takeaway: quality attributes are not polish; they bound how far a defect can climb.

Pitfalls

  • Treating engagement as a success metric without a harm counter-metric. More scroll time can mean more addiction, not more value.
  • Checking only for intentional bias. The most dangerous discrimination in ML is the unintentional kind that passes code review because no line of code looks biased.

Real-world connection: Content ranking for a social feed, diagnostic support in a hospital, and resume screening for hiring map one-to-one onto manipulation/addiction, safety, and discrimination. The same pipeline that improves click-through by 2% can, without a harm review, also increase harmful exposure — which is why responsible engineering is framed as quality attributes alongside functionality, not after it.

15.5.4 What Responsible AI Means and Who Is Responsible

Responsibility spans all levels. A definition attributed to IBM was shown and students were asked to consider: is responsible AI the job of an individual, an organization, a country, or the world? The answer emphasized was all levels at once. Whether we work as a developer, tester, product owner, or researcher, and whether we ship predictive, generative, or agentic AI, each of us is individually responsible — as is the organization, the country, and collectively the world.

In software engineering terms these responsibilities are quality attributes that sit alongside functionality. The pipeline and metrics we saw for 14 sessions deliver functionality (does it predict, generate, act correctly and quickly?); this section asks whether that functionality is also explainable, fair, safe, secure, and private when it reaches real users.

The eight pillars listed for responsible AI in this lecture are:

The session worked through versioning, provenance, and reproducibility in detail (next subsection) and left explainability, fairness, safety, security, and privacy to start from the next session, noting that about five minutes remained and that explainability would open the next class.

Q: We meet explainability, fairness, and safety in other courses — how do you see them in ML?

A: This exchange opened the responsible AI segment. Students noted that in finance, clients often ask "how did you reach this conclusion?" and want traceability. Complex models such as XGBoost were contrasted with more interpretable models such as decision trees and random forests, where at least the path can be explained. Bank loan decisions were highlighted as the anchor where the system must explain why an application was denied. The discussion then broadened to the point that explainability even has its own global conferences, for example the World Conference on Explainable AI, underscoring that these are established research and practice areas, not side topics. [Maps to Q&A opening 15.5 — finance/loan traceability]

15.5.5 Versioning, Provenance, Reproducibility — The First Pillar

#### Why Versioning Matters in ML More Than in Classical Software

Version four things, not one. In classical software we version code (day to day, Git). In ML we must version four things together: code, dataset, model, and pipeline. The reason is traceability under dispute. You need to reconstruct exactly what happened, not what happens today when you re-run today's artifact.

The loan decision example and the Apple Card controversy (2019) made this concrete. A person submits data to a lending model; the model returns approve or deny. Suppose a highly qualified applicant — strong income and credit history — is denied and brings a legal challenge. To investigate, you must replay the decision as it happened.

  • In a classical software system there are two variables: the database content and the application code. Go to production, reproduce the fault, trace to a line of code or stored procedure.
  • In an ML system there are at least three to four moving parts. In the loan example, three interacting models together scored risk and limit and then produced the final decision, each reading different inputs like income or credit history and applying its own algorithm. Data sources, model versions, and the pipeline that wired them together can all have changed since the decision. You may be on model version 20 today while the decision used model version 11.1. Re-running today's model on today's data proves nothing. You need the pipeline that pins the same data source version as it looked on that date, the same model versions as they were then, and the same pipeline wiring — all in sync.

Analogy — Crime Scene versus Lab Notebook: Classical debugging is like revisiting a crime scene that is still cordoned off — the evidence is there. ML debugging without versioning is like returning to the scene after the furniture has been rearranged, the witnesses have moved, and the lab notebook has been overwritten. Versioning the pipeline is the promise that every exhibit is bagged and labelled by date so the scene can be reconstrued exactly.

#### Five Strategies for Versioning Large Datasets

Large dataset versioning is a storage versus compute (time) trade-off. The lecture presented five patterns, each suited to a different shape of data and access pattern. The running example is a customer transaction dataset sized at 500 GB.

Strategy 1 — Store the full copy per version. Version 1 is the full GB snapshot on 22 August. On 23 August GB of new data arrives so version 2 is the full GB snapshot, and so on. Any dated complaint maps directly to one full snapshot you can retrieve. The drawback is storage cost: keeping a full copy for every version is memory-intensive and only workable with abundant storage. Implementable as a naming convention (customer_profiles_v435.csv.gz, customer_profiles_v436.csv.gz) and mirrored internally by Git's copy model.

Strategy 2 — Store the delta (diff/patch). Keep one base version with GB and each day store only the change (say GB per day via diff/patch). To reconstruct version 3, combine base plus day-one delta plus day-two delta plus day-three delta. To diagnose a problem tied to version 1, apply only the day-one delta to the base. Space-efficient when changes are small relative to the base; retrieval cost grows with the number of patches to apply. Internally this is how RCS and Mercurial work. Tooling: diff/patch, versioned object stores.

Strategy 3 — Offsets in append-only data. Suited to real-time event data such as logs, clickstreams, and IoT events including Kafka topics. Such data is append-only: records are added and rarely deleted. Think of an IoT temperature sensor in New Delhi writing every hour: 12:00, 1:00, and so on over years. Versioning is by offsets in the event stream: time zero is the start, events mark version 1, events mark version 2, and so on. To answer "what was the temperature five days ago at this hour" map the request to the offset range covering that window and read from the stream. Boundaries need not be day-based; they can be count-based depending on generation speed — fast-generating data such as Instagram posts hits events quickly while slow-generating data such as census data takes longer. The pairing is always offset plus timestamp so a named version maps to a concrete slice and the consumer reads until that offset. Implemented in streaming systems like Apache Kafka (offsets) and lakehouse tools like lakeFS/Dolt. This pattern does not generalize to datasets where deletion is expected; that is what event sourcing (amending by appending) handles.

Strategy 4 — Change history per individual record (row-level versioning). Suited to entity-oriented data such as products or customers. Instead of versioning the whole dataset, version each record's history. A customer record with a customer ID is illustrative: version 1 might hold {balance: 1200, status: success} on a given date; a transfer of rupees creates version 2 with {balance: 1500, status: success}; a later failed operation creates version 3 with {balance: 1500, status: failed}. Every change becomes a new version for that customer. You can then query any customer at any point in time. Implementable as per-record files under Git, per-key versioning in key-value stores (Amazon S3 buckets version per key), or database edit-history features. Mirrors the "change history per record" idea in DVC and lakehouse per-row audit logs.

Strategy 5 — Version the pipeline (holistic, preferred for ML). The pipeline itself becomes the versioned artifact and it pins the versions of everything inside it. The example pipeline shown combines raw transactions at version , EDA/ETL/feature-engineering code at version , configuration at version , and training dataset at version . The assembled pipeline is then labelled version 12. Any output of that pipeline can be regenerated by re-running pipeline version 12, which pulls exactly those pinned versions. This is why MLOps platforms, including SageMaker, show a version for the entire pipeline, not just for code. Trade-off is compute time: re-running over a large dataset may take minutes or longer. Advice: prefer pipeline versioning for analytics and ML applications while still understanding the other four patterns and when each applies.

Worked Comparison — Full Copy versus Delta versus Pipeline Pin

Take the 500 GB transaction dataset over 10 days with GB new per day.

  • Strategy 1 (full copies): Store objects totalling about GB. Retrieval of any dated version is one fetch — fastest, most storage.
  • Strategy 2 (deltas): Store GB base plus GB of deltas = GB total. Reconstructing day 10 requires applying 9 patches — cheapest storage, higher reconstruction time.
  • Strategy 5 (pipeline pin): Store pipeline version 12 that records raw@v3, code@v5, config@v2, train@v7. No duplicate data beyond what the other strategies already store; reproducibility comes from re-executing the pipeline. Cost shifts from storage to compute (re-run time).

How to pick: If storage is abundant and you need instant point-in-time queries, use Strategy 1. If changes are small and old-version access is rare, use Strategy 2. If data is an append-only stream, use Strategy 3. If edits are per-entity and sparse, use Strategy 4. If the artifact is an ML result that must be reproducible end to end, use Strategy 5 as the umbrella that pins whichever of 1–4 the data uses.

Sense-check: Strategies 1–4 answer "how do I keep the data over time?"; Strategy 5 answers "how do I keep the derivation so any past result can be rebuilt from its pinned data and code?"

Strategy Best for Storage Retrieval When to pick
Full copy Small-to-medium data, frequent point-in-time reads High Fastest (one fetch) Need instant dated snapshots
Delta Large data, small daily changes Low Slower (apply patches) Storage-constrained, rare historical reads
Offsets (append-only) Logs, Kafka, IoT streams Minimal Range read by offset Data never deleted
Per-record history Entity data (customer, product) Proportional to churn Per-key lookup Sparse, per-entity edits
Pipeline pin ML result reproducibility Depends on 1–4 Re-run pipeline Need end-to-end rebuild

Students were given two to three minutes to read the five-strategy slide and told a break would follow.

#### Data Provenance Versus Data Lineage

Provenance is source trust; lineage is movement and transformation.

  • **Data provenance — source and trust.** Where did this data come from, who created it, who modified it, when, and what is its history? The data could be internal or external (even public sources like Twitter data). Trust, integrity, and authenticity hinge on provenance. Key questions: What source produced this row? Who created or changed it and when? Provenance answers those, often requiring row-level edit history and authentication for every create/edit.
  • **Data lineage — movement and quality drift through a pipeline.** Lineage tracks the data as it passes through systems and stages: created → extracted → transformed → loaded → staged → consumed. It answers: was the data fine when raw but broken after some transformation?

Canonical lineage example: An IoT sensor reports temperature correctly as C as raw data. A transformation stage that should convert Celsius to Fahrenheit contains a bug. Correct conversion is

so C should become F. The buggy code instead does F or drops the scaling entirely. The raw value was correct; the Fahrenheit value downstream is wrong for every consumer table. Without lineage you do not know where quality broke. With lineage you trace stage by stage, identify the conversion code as the culprit, enumerate which tables and consumers now hold the wrong values, and fix the right place.

Lineage Trace — Celsius to Fahrenheit Bug

Raw topic: sensor payloads {time: 2026-08-16T14:00Z, T_C: 90} correct.

  1. Stage A (extract) — read from Kafka, write to staging.raw_temps — values still .
  2. Stage B (transform) — F = C * 9/5 + 32 — expected F, but code at commit abc12 wrote F = C + 32F into staging.temps_f.
  3. Stage C (aggregate) — downstream dashboard averages temps_f and reports a plausible-but-wrong F.

Lineage metadata records: staging.temps_f row lineage = raw_temps offset 41,203 + code version abc12 of c_to_f.py + config scale: 1.8 offset: 32. Checking lineage, the on-call engineer sees that scale is logged as not and patches c_to_f.py. Sense-check: Provenance would tell you the sensor in New Delhi is a trusted source; lineage tells you where the trusted value was broken.

Pitfalls

  • Collecting provenance only inside the pipeline. If you trace only file-to-file inside training but not who edited the label upstream or which user created the row, you cannot answer the judge's or auditor's question.
  • Forgetting row-level provenance for edits. File-level versioning tells you the dataset changed; row-level provenance tells you which customer's record changed and by whom — critical for GDPR-style deletion and bias audits.

#### Reproducibility — Can We Recreate the Same Experiment and Get Consistent Results

Reproducibility defined. Reproducibility — can we recreate an ML experiment with the same code, same data, same configuration, same dependencies, and same environment and achieve consistent results? Pipeline versioning is the mechanism: with the same data source version, same feature-engineering code version, same configuration, same training dataset, and same library pins, the same outcome should be reproducible even if we run the pipeline 100 times.

Many things break reproducibility: different Python library versions, a different dataset version as new data is appended, a different train-test split (say 70/30 in pipeline v11 versus 80/20 in v12), changed preprocessing logic, and different hyperparameters such as temperature and top-p and their interaction with growing datasets.

The cost of reproducibility is again compute time: reproducing requires re-running the pinned pipeline over large data, which may take minutes or longer and must be budgeted, just as with Strategy 5 above.

Reproducibility versus replicability (exam-useful distinction): Replicability (exact bit-for-bit identical results from the same experiment) is a stricter subset of reproducibility (comparable results under minor variations, such as the same method on fresh data). Determinism of data transforms and model inference helps replicability; controlling library versions, data versions, and seeds helps reproducibility. The textbook notes that strict bit-for-bit replicability of models is rarely the goal in production — some nondeterminism in training is accepted and versioned.

Visual — Reproducibility ladder: Imagine a ladder with rungs: documented manual steps → automated pipeline → versioned code + data → pinned dependencies → fixed seeds + deterministic ops. Each rung reduces nondeterminism. The top rung gives bit-for-bit replicability but is the most expensive. Takeaway: climb as high as your audit and debugging needs require, but do not pay for a higher rung than you need.

#### Reproducibility Across Predictive, Generative, and Agentic AI — A Nuance

Temperature decides whether reproducibility is even desirable.

  • In predictive AI reproducibility is straightforward. Given the same input, same model version, and same pipeline version, expect the same output every time. Non-determinism here is a bug.
  • In generative AI the same input can legitimately produce different outputs by design when we are on the generative side of the temperature scale. If , the output is deterministic and factual and the same prompt should give the same answer (and a RAG pipeline grounded in a fixed document should be reproducible under pinned retrieval and ). If and we ask for a catchy marketing phrase, asking twice should give two different phrases — variation is the point. In that regime insisting on identical text misunderstands the goal.
  • In agentic AI the same pivot applies. "Book me a flight from Bangalore to Delhi" with no constraints run today versus five days later may choose Air India one time and Indigo the next because prices, schedules, and API state have changed and the prompt is open-ended. With pinned constraints (budget, evening only) and pinned external factors as far as possible, reproducibility returns in the sense that the same constrained request should produce the same booking. After days have passed not all external conditions can be pinned, so strict sentence-level reproducibility is not the right expectation.

The deeper point: versioning, provenance, and lineage remain important for generative and agentic systems — you must version the data source, the vector database (embedding model + index), and the agent code and tool permissions — even when strict output reproducibility is not expected. Provenance and lineage are intact even when the text varies.

Q: Generative models give different answers for the same prompt — how does reproducibility apply to LLMs?

A: Temperature decides. Factual and math-style prompts at low reproduce the same output; creative prompts at high intentionally do not. For generative and agentic systems, strict replicability of the exact text is not a useful requirement when you are asking for imagination or open-ended tool use. What remains critical is that you version everything that went into the generation — data source version, vector database version, model and prompt version, agent tool permissions — so provenance and lineage are intact even when the words differ. [Maps to 15.5.qna.1]

Q: If we build a RAG chatbot like the Virtual Machines demo, shouldn't "what is a virtual machine?" always give the same answer from the same document?

A: Under the same conditions, yes — if the document, the retrieval (same top- chunks, same embedding model), and hyperparameters like are pinned, a grounded RAG chatbot should be reproducible. Variation becomes expected only when you intentionally vary conditions or broaden the task to free-form generation where diversity is wanted. Judge reproducibility against the task contract: grounded QA expects the same factual answer, creative generation expects variety. [Maps to 15.5.qna.2]

Q: In an agentic booking flow on a fixed site with the same workflow, shouldn't it be reproducible?

A: Workflow reproducibility — did it follow the same governed steps in the same order with the same tool policy — is reproducible. Outcome reproducibility — did it produce the identical ticket — may not be, because flight data changes over time. With pinned constraints the agent can still hit a different available flight five days later. Distinguish the two. [Maps to 15.5.qna.3]

Q: When we change prompts, temperature, tools, or models, should each change create a new version? Which changes deserve versioning?

A: In the LLM era, versioning is primarily driven by data and model changes, not by every prompt tweak. ChatGPT's public history is illustrative: versions 3.5, 4, 4.1, 5.4, 5.6, nano, mini are documented on model cards (here illustrative labels for the point). The change that justifies a new version is typically new data being fed and trained on, or a new domain or capability added. A small language model that only answers finance questions might become version 2 when it gains e-commerce data and answers two domains more robustly. Prompt variations and simple token-counting changes alone do not typically warrant a new model version — every model tier already has its own sub-versions for its evolution. That said, for reproducibility you still log prompts, , top-p, tool sets, and system instructions per run; you just do not mint a new model version for each. [Maps to 15.5.qna.4]

Q: How is timestamp-based versioning done in the append-only offset approach (Strategy 3)?

A: Append-only data such as hourly temperature readings from a sensor in New Delhi is written and never deleted. Define versions by event counts or time windows: events as version 1, as version 2, and so on — each version carries a timestamp (for example version 3 dated 22 August) alongside its offset. To answer "what was the temperature at the sensor three days ago" look up the version whose offset and timestamp cover that event window and read the corresponding records. Boundaries can be count-based rather than day-based; fast versus slow generation rates determine how quickly you hit the next offset threshold. The segmentation is purely a grouping mechanism; for mutable data you would use a different strategy. [Maps to 15.5.qna.5]

Pitfalls

  • Re-running today's pipeline to debug last week's decision. Without pinning, you prove nothing about last week's data and code.
  • Versioning code but not the feature store or vector index. An embedding model upgrade can change every retrieval result while your git log looks unchanged.
  • Expecting creative outputs to be bit-for-bit identical. Low- grounded QA should be; high- marketing copy should not — set the expectation by task.

Real-world connection: The Apple Card incident pattern and the Therac-25, Knight Capital, and Horizon cases from 15.5.2 are the reason regulators and auditors ask for pipeline version 12, not just model version 20. A bank that can produce "on 2019-08-15 we ran pipeline v11.1 on data v7 with model v11 and config v4" can answer the judge; one that can only produce today's model cannot.

Recap: Versioning, provenance, and reproducibility are the first quality pillar — the infrastructure that makes responsibility possible. Pin code plus data plus model plus pipeline; choose the dataset strategy that matches access shape (full copy, delta, offsets, per-record, or holistic pipeline pin); keep provenance for source trust and lineage for transformation debugging; and judge reproducibility by the AI paradigm and by temperature — determinism where you need auditability, deliberate variation where you asked for creativity. With that foundation laid, the next pillar is explainability and accountability.

15.6 Explainability and Accountability — Why It Matters

15.6.1 The Explainability Pillar

Hook: A model denies a loan in 40 milliseconds. The applicant asks "why?" — and the only honest answer your system can give is "because the model said so." Is that good enough for a courtroom?

Explainability asks whether a prediction is intelligible. Explainability is the quality attribute that asks: can we trace why the system predicted what it predicted, in terms that a relevant stakeholder — developer, auditor, or affected user — can understand and act on?

The textbook treats explainability and accountability together: the ability to explain is what makes it possible to hold someone accountable for a decision. The bank loan decision is again the anchor. Functionality delivers a decision — approve or deny. Explainability requires that the system can articulate why that decision follows from the inputs — which features pushed it over the threshold, what rule or learned pattern fired, and what would need to change for a different outcome.

Why this is not a side topic:

  • Interpretable versus opaque models. A decision tree can be read as a path: "income > 80k and credit score > 720 → approve." A random forest aggregates many such paths and remains somewhat inspectable. A model like XGBoost (gradient-boosted trees) or a deep network can be far more accurate but is harder to explain — the trade-off between performance and intelligibility is itself a design decision that the Q&A opened.
  • Domain demand. In finance, clients and regulators routinely ask "how did you reach this conclusion?" and expect traceability, not just a score. The same expectation appears in healthcare (why this diagnosis?), hiring (why was this resume rejected?), and any high-stakes allocation.
  • Field maturity. Explainability is established enough to have its own global venues — the World Conference on Explainable AI was cited as evidence — and its own textbooks and tooling ecosystems. It is not a passing concern but a sub-discipline with methods ranging from inherently interpretable models to post-hoc explanations (feature attributions, counterfactuals, local surrogates).

Scope: This lecture names the pillar and frames why it matters; it explicitly defers detailed techniques and tooling for explainability — and for the remaining pillars fairness, safety, security, and privacy — to the next session, because only about five minutes remained. The promise was to start the next class with explainability itself and then move through the other pillars. This is a deliberate "conceptual grounding now, hands-on later" pacing.

What counts as an explanation depends on the audience. A developer needs a feature-path trace to debug; a regulator needs a reproducible audit trail (linking back to pipeline versioning in 15.5.5); an affected user needs a plain-language reason plus a recourse statement ("your application was denied because debt-to-income exceeded 40%; it would be approved if that ratio were below 35%"). One explanation does not serve all three.

Visual intuition: Picture two side-by-side panels for the same loan denial. Left panel: a decision-tree path highlighted from root to leaf — three branching checks, each with the applicant's value and the threshold, ending in "deny." Right panel: a bar chart of feature contributions (income negative, credit history negative, employment length slightly positive) that sum to the model's score below the approval threshold. Both convey "why" but at different granularities. Takeaway: explainability is not one picture — it is the ability to produce the right picture for the right stakeholder.

Pitfalls

  • Collecting an accuracy metric but no explanation artifact. If you log only the prediction and not the contributing features, you cannot answer the applicant or the auditor a week later.
  • Assuming explainability is only for deep learning. A tabular XGBoost model with 200 features is just as opaque to an end user as a neural net — plan for explanations regardless of model family.
  • Confusing explainability with transparency of code. Publishing the model weights is not an explanation; a stakeholder needs a reason in the decision's terms.

Real-world connection: Textbook one Chapters 23–28 ground this pillar sequence, and LangChain was named among the tooling references that sit alongside the responsible AI discussion — as LLM apps add RAG and agent steps, the explanation must cover not just the final model's score but also which retrieved documents and which tool outputs contributed to the answer. A RAG chatbot that cites "the answer came from paragraph 3 of the uploaded Virtual Machines document, chunk 4 of 10" is already practicing a minimal form of explainability.

Recap: Explainability is the next pillar — the bridge from "the model said so" to "here is why, and here is what would change the outcome." The session framed its importance, its tie to accountability, and its audience dependence, and deferred the how to the next lecture where explainability opens the class. Bring the loan-decision and XGBoost-versus-tree intuition with you.

15.7 Single-Turn and Multi-Turn Context Handling — A Practical Note

15.7.1 Context Growth Patterns

Hook: One question, one document, one answer — simple to meter. Now let the conversation continue for ten turns, each time adding a new file and remembering what was said. What happens to your token bill and your context window?

The session reinforced a practical design note that recurs in RAG and agent design — how context grows and how to manage it — beyond the dedicated metrics section in 15.3.

Single-turn fixes the boundary; multi-turn grows it.

  • **Single-turn interaction** — the mode of the LLMOps demo. You load one Word document as context, ask one question, get one answer, and the transaction ends. The knowledge boundary is fixed to that document load. Token accounting is simple: is a constant (548 in the demo) added once per request. Cost and latency are predictable.
  • **Multi-turn interaction — the mode typical of ChatGPT. Turn one may include a PDF; turn two says "summarize that"; turn three says "but also use this new file I just uploaded." The system carries forward prior context and prior reasoning, so the boundary grows. increases with every turn, which grows cost and latency and pressures the model's context window** (the maximum tokens the model can attend to at once). Caching, compression, and window management become first-class concerns.

Two ways to grow the boundary, one preferred:

  1. Naïve concatenationcontext = context + new_document in code. Explicitly appending another upload into the same session. Works for a quick demo and makes the trade-off visible: more information improves coverage but also grows tokens and can push older relevant chunks out of the window.
  1. Robust architecture: full RAG pipelinesplitter → embedding model → vector database → retriever → generator. Instead of carrying the whole concatenated history, retrieve only the top- most relevant chunks for the current query. That caps at roughly rather than letting it grow with every turn. The same pipeline, together with its pinned versions (document version, splitter settings, embedding model, vector index, retriever policy), is what LLMOps tracks.

Cost implication directly: In single-turn with the demo numbers, a second question costs another tokens. In naïve multi-turn where you append a second 548-token document, the second turn costs tokens — a 65% jump just from carrying history. With RAG retrieval capped at, say, chunks of tokens each, the second turn costs tokens — actually cheaper than naïve single-turn while staying more relevant.

Worked Comparison — Naïve Multi-Turn versus RAG Multi-Turn

Assume toy word-split counts and a 50-word capped answer (~40 words → ~285 tokens as in the demo's scale).

  • Turn 1 (single document): tokens.
  • Turn 2 naïve (append second document): , tokens.
  • Turn 2 RAG (retrieve 4 chunks × 128 tokens): , tokens.

Push this to 10 turns naively and grows linearly toward — you hit the context window and the provider rejects or truncates mid-thought. With RAG the per-turn context stays near regardless of history length; the vector database scales, not the prompt.

Sense-check: If your per-turn latency was s at 841 tokens, do not be surprised when naïve multi-turn turn 5 takes 4–6s. The bill and the latency both follow the context.

Scope: This is a practical note, not a full context-engineering lecture. The session flagged that caching and window management are important but did not wire them into the demo. In production, add prompt compression, summarization of stale history, and retrieval budget as explicit pipeline stages.

Assumptions & failure modes: The RAG-capped calculation assumes the retriever actually finds the right chunks. If retrieval misses, you pay less and answer worse — a reminder that retrieval quality (recall@k) belongs on the dashboard alongside tokens.

Visual intuition: Draw a stacking diagram. X-axis is turn number, Y-axis is tokens in the prompt. Naïve multi-turn is a staircase that climbs every turn. RAG multi-turn is a staircase that climbs once and then stays flat, with a thin "retrieved" band that flickers to different document colours each turn. Takeaway: naïve growth is additive in history; RAG growth is constant in .

Pitfalls

  • Shipping naïve concatenation to production. It passes a two-turn demo and fails on the tenth real conversation when the context window overflows.
  • Forgetting that retrieved context is versioned. Swapping the embedding model can change which chunks are retrieved even when the documents have not changed — pin the vector index and embedding version (link to 15.5.5 Strategy 5).
  • Treating multi-turn as only a token problem. Carrying forward prior reasoning (not just documents) can also reintroduce hallucinations from earlier turns — scope history explicitly.

Real-world connection: A help-desk bot that starts with one runbook but later pulls in ticket history and a second manual is exactly where this note bites: without a retriever, every prior turn inflates the next bill and slows the answer; with a RAG pipeline and a pinned vector index, the bot stays within budget and latency SLO while answering from the right paragraph.

Recap: Single-turn fixes the knowledge boundary and keeps metering simple; multi-turn grows it and demands budgeting, caching, and above all a RAG pipeline that retrieves only what matters. Pin the pipeline that decides what context is carried, not just the code that concatenates it — then the LLMOps dashboard (tokens, cost, latency) stays honest as conversations lengthen.

Exam Guidance Summary

  • The watermarked PDF containing all 16 session PPTs has been uploaded to the Taxila portal. No further changes will be made to that consolidated file. An announcement was sent the prior day. For printing, one slide per A4 page and two slides per page were called readable. Four slides per page was described as very cumbersome and hard to read in the exam hall. Provision for one, two, and four per page will be made available by Tuesday or Wednesday, coordinated with the lead faculty, and students may choose the format they prefer.
  • Assignment 1 evaluation is complete. Assignment 2 has been submitted and evaluation was in progress to complete by Monday. A Taxila portal announcement will follow. Queries about assignment evaluation should go to the respective evaluating faculty or to the lead faculty who will redirect.
  • Situated learning forms have been collected for course feedback to frame future situated learning questions for upcoming batches.
  • The 16th session is a review session with no new content and will devote 30 to 45 minutes to comprehensive exam questions. Students were asked to bring exam questions there. Sample questions from the midterm will be shared in the coming week.
  • The course is offered for the first time; the exam format discussion will therefore draw on those shared samples rather than on a long prior-year pattern.
  • No specific mark distribution, question-type breakdown, or chapter-wise weightage was announced in this session. The emphasis in this lecture was on conceptual understanding plus applied ops metrics rather than on a chapter-number checklist.

Key Industry Applications

  • Real-world: a full CI/CD pipeline built with GitHub Actions and Argo CD illustrates the ramped deployment strategy in action by scaling replicas from one to seven and deleting pods when the replica count is lowered.
  • Real-world: ChatGPT, Claude, Grok, OpenAI models, and Google Gemini expose temperature and top-p as hyperparameters that control determinism versus creativity and response breadth; consumer portals now auto-select temperature prompt-adaptively.
  • Real-world: RAG chatbots grounded in company Word documents, PDFs, and PPTs power question answering that must stay inside the document context with temperature kept low around 0.1 to 0.2 to prevent hallucination; a demo chatbot for Virtual Machines paragraphs was shown as the minimal LLMOps metering template.
  • Real-world: MLflow, SageMaker Pipelines, Apache Airflow, Prefect, and Kubeflow Pipelines are used to define, trigger, and track ML and LLM workflows and to log metrics per stage.
  • Real-world: Infectious disease prediction pipelines and hospital forecasting use medical metrics such as latency and accuracy alongside safety accountability because dosage and triage errors are fatal.
  • Real-world: Facebook and Instagram infinite scroll and autoplay as engagement mechanisms illustrate manipulation versus addiction as an ML harm; personalized ads illustrate impulsive purchase exploitation driven by learned behaviour signals.
  • Real-world: Mass facial recognition in railway stations and public crowds illustrates the privacy pillar, contrasted with narrow-scope campus attendance recognition; autonomous field robots operating without connectivity illustrate safety and surveillance risks.
  • Real-world: The Amazon hiring system circa 2013 illustrates unintended discrimination from biased training data where about 78 percent of male applicants were selected and many qualified female applicants were rejected.

SEML Lecture 15 notes · Responsible ML Engineering and LLMOps — End-to-End Ops and Quality Attributes

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

Sections Breakdown

1Deployment Strategies Recap

Four deployment strategies — basic, ramped, blue-green, canary — and their trade-offs, anchored by a live GitHub Actions plus Argo CD demo of a Kubernetes ramped rollout.

2MLOps — The Predictive AI Lifecycle

Code plus data plus models triangle for structured predictive AI, with F1 and latency as first-class production signals and an orchestrated CI-triggered pipeline stitched with MLflow, SageMaker Pipelines, and Airflow/Prefect/Kubeflow.

3LLMOps — The Generative AI Lifecycle

Generative-AI ops for unstructured RAG pipelines: hallucination rate, token and cost accounting, latency, temperature and top-p sampling controls, and a single-turn Word-document chatbot demo that logs per-turn application metrics.

4AgentOps — Operations for Agentic AI

Agentic ops as an emerging discipline: goal achievement, task success rate, and tool call correctness as trajectory-level signals, with CrewAI, AutoGen, and LangGraph as orchestration substrates.

5Responsible ML Engineering — Quality Attributes Beyond Functionality

Harm taxonomy from classical software through ML, responsibility across individual to world, and deep dive into versioning five strategies, provenance versus lineage, and paradigm-dependent reproducibility.

6Explainability and Accountability — Why It Matters

Explainability as the quality attribute that makes predictions intelligible to the right stakeholder, tied to accountability and anchored by the loan decision, with techniques and the remaining pillars deferred to next session.

7Single-Turn and Multi-Turn Context Handling — A Practical Note

Single-turn fixes context to one document; multi-turn grows it over turns, so naïve concatenation inflates cost and latency while a RAG retriever caps context at top-k chunks.

Postgraduate students in Machine Learning

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.

Deployment Strategies Recap

Must-know: Name and contrast the four deployment strategies and know ramped is the Kubernetes default; describe how GitHub Actions plus Argo CD automate CI/CD for a ramped rollout.

Top pitfall: Assuming ramped is zero-risk or forgetting that rolling pods does not migrate a backing database schema.

Self-check: When would you prefer blue-green over canary, and what is the cost of that choice?

Connects to: 15.2, 15.3

MLOps — The Predictive AI Lifecycle

Must-know: Contrast MLOps with DevOps focus and state the F1 formula and why accuracy alone misleads on imbalanced data.

Top pitfall: Tracking accuracy without precision/recall on imbalanced classes, or pinning code but not dataset version.

Self-check: Given TP=40 FP=10 FN=20 compute P, R, and F1 and explain why F1 punishes the lower of P and R.

Connects to: 15.1, 15.3

LLMOps — The Generative AI Lifecycle

Must-know: Decompose total tokens into input plus context plus output and map to cost; state temperature range and when to set low versus high; distinguish RAG pattern from LLMOps measurement layer; describe demo metrics and why word-split is a toy tokenizer.

Top pitfall: Using high temperature for RAG grounding, treating top-p as a word limit, or shipping word-split tokenization to production.

Self-check: A single-turn prompt logs 8 input, 548 context, 285 output tokens with 2.58 s latency. What is the total and what dominates? How would multi-turn change 548?

Connects to: 15.2, 15.4, 15.5

AgentOps — Operations for Agentic AI

Must-know: Name the three representative AgentOps metrics and explain why MLOps metrics like F1 do not transfer to agentic evaluation.

Top pitfall: Scoring an agent by fluency instead of goal achievement or auditing tool name without auditing arguments.

Self-check: An agent had search, book, and cancel tools and was told to book Bangalore to Delhi. Which metric checks whether it called search before book with the right date?

Connects to: 15.3, 15.5

Responsible ML Engineering — Quality Attributes Beyond Functionality

Must-know: State the eight responsible AI pillars taught here; contrast provenance versus lineage with the Celsius to Fahrenheit bug; list the five dataset versioning strategies and when each fits; explain why high-temperature generative outputs should not be judged reproducible.

Top pitfall: Re-running today's model on today's data to debug last week's decision, or expecting high-temperature creative outputs to match exactly.

Self-check: A loan decision from pipeline v11.1 is disputed. What four pinned versions must you produce? When is delta better than full copy?

Connects to: 15.3, 15.4, 15.6

Explainability and Accountability — Why It Matters

Must-know: Define explainability and its link to accountability; explain why a decision-tree path counts as more interpretable than XGBoost and who needs which form of explanation.

Top pitfall: Logging only the prediction without the contributing features or retrieved context needed to explain it later.

Self-check: A loan was denied. What would a developer, a regulator, and the applicant each need in the explanation?

Connects to: 15.5

Single-Turn and Multi-Turn Context Handling — A Practical Note

Must-know: Contrast single-turn versus multi-turn context growth and explain why RAG retrieval caps tokens while naïve concatenation does not.

Top pitfall: Appending every prior document naively and overflowing the context window after a few turns.

Self-check: Two-turn naïve versus RAG: which keeps total tokens near constant and why?

Connects to: 15.3, 15.5

Was this lecture useful?

Loading comments…
🤖

BitsNotes AI Assistant

Subject Notes Assistant

Configure AI Chat

Choose how to access the chatbot
Have your own API key?

Switch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.

🔑 Enter API key above to fetch live models from provider, or enter model name manually.
OpenAI-Compatible API Support

Choose any provider preset (Gemini, DeepSeek, Kimi, GLM, MiniMax, Qwen, OpenAI, Groq, Ollama, etc.) or enter a custom endpoint URL.

Security & Privacy First

Your API key is sent directly from your browser to your specified provider. BitsNotes servers never store or see your key.