TExcelTAD
Home › Deployment & MLOps: Serving, Pipelines, Monitoring › Deployment & MLOps Exercises

Deployment & MLOps Exercises

Twelve exercises across the whole course, from packaging to governance. Try each one before opening the answer. The runnable ones work in your browser; change the numbers and run them again.

1. What to ship

A data scientist saves only the fitted LogisticRegression with joblib and writes the scaling step into the README: "standardise income and age with mean and std from training". The model will be served by another team.

a) What failure does this invite? b) What should be saved instead? c) Give two pieces of metadata that should travel with the file.

Answer

a) Training-serving skew: the serving team reimplements the scaling, perhaps with different statistics, units or column order, and the model silently gets inputs it was not trained on. b) The whole fitted Pipeline (scaler + model) as one object, or an ONNX graph that contains the scaler (saving models, ONNX). c) For example: the library versions it was saved with (a pickle needs a compatible scikit-learn), the input schema (feature names, types, ranges), the training data version or hash, the evaluation metrics and the file's SHA-256 (artifacts and signatures).

2. Batch or real time?

Choose batch or real-time inference for each, and say why: a) next-week demand forecasts for 20,000 products, b) fraud scoring of a card payment before it is approved, c) a nightly "customers likely to churn" list for the sales team, d) autocomplete suggestions while typing.

Answer

a) Batch: the inputs are known in advance, nobody waits for the answer, and a nightly job is cheaper and easier to retry. b) Real time: the decision must be made within the payment's latency budget (tens of milliseconds) using features of this payment. c) Batch: a list produced once a day. d) Real time, and very low latency (each keystroke), often on the edge or with heavy caching. See batch, real-time and streaming inference.

3. How many replicas?

A model service handles one request in 25 ms of CPU time per worker, and the peak load is 400 requests per second. How many single-worker replicas do you need if each should stay at or below 70 % utilisation? How many requests are in the system on average at peak (Little's law, L=λWL = \lambda W), if the mean time in the system is 40 ms?

python · try it yourself
import math

peak_rps = 400          # lambda, requests per second
service_s = 0.025       # time one worker needs per request
target_util = 0.70

per_worker = 1 / service_s                       # requests per second one worker can do
needed = math.ceil(peak_rps / (per_worker * target_util))
print(f"one worker: {per_worker:.0f} req/s; replicas at <= {target_util:.0%}: {needed}")
print(f"utilisation with {needed} replicas: {peak_rps / (needed * per_worker):.1%}")
print(f"Little's law: L = {peak_rps} * 0.040 = {peak_rps * 0.040:.0f} requests in the system")
one worker: 40 req/s; replicas at <= 70%: 15
utilisation with 15 replicas: 66.7%
Little's law: L = 400 * 0.040 = 16 requests in the system
Answer

One worker does 40 requests per second, so 400 req/s needs 10 workers at 100 % and ⌈400/(40⋅0.7)⌉=15\lceil 400 / (40 \cdot 0.7) \rceil = 15 at 70 %, which runs them at 66.7 %. Little's law gives 16 requests in flight on average. The headroom matters because queueing delay grows sharply as utilisation approaches 100 % (latency and batching, Kubernetes and scaling).

4. A validated endpoint

Extend the endpoint so that age must be between 18 and 100 and income must be positive. Requests that break the rule must get HTTP 422 without reaching the model.

python · try it yourself
import asyncio
import httpx
from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI()

class Applicant(BaseModel):
    age: int = Field(ge=18, le=100)
    income: float = Field(gt=0)

@app.post("/predict")
async def predict(a: Applicant):
    score = min(1.0, a.income / 100_000) * (1 - a.age / 200)   # stand-in for a real model
    return {"score": round(score, 3)}

async def main():
    transport = httpx.ASGITransport(app=app)
    async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
        for body in ({"age": 40, "income": 52000}, {"age": 12, "income": 52000}, {"age": 40, "income": -5}):
            r = await client.post("/predict", json=body)
            if r.status_code == 200:
                print(r.status_code, r.json())
            else:
                err = r.json()["detail"][0]
                print(r.status_code, err["loc"], err["msg"])

asyncio.run(main())
200 {'score': 0.416}
422 ['body', 'age'] Input should be greater than or equal to 18
422 ['body', 'income'] Input should be greater than 0
Answer

Field(ge=18, le=100) and Field(gt=0) put the rules into the request schema, so FastAPI rejects bad requests with 422 and a message that names the field, before your function runs. Validation at the edge is the first line of data validation and of security. The endpoint is async def because the browser has no threads (FastAPI basics).

5. Int8 by hand

Quantize the weights [-0.82, -0.10, 0.03, 0.47, 1.20] to int8 with symmetric per-tensor quantization: s=max⁡∣w∣/127s = \max\lvert w \rvert / 127, q=round⁡(w/s)q = \operatorname{round}(w / s), w^=s q\hat w = s\,q. What is the largest error, and how does it compare with the bound s/2s/2?

python · try it yourself
import numpy as np

w = np.array([-0.82, -0.10, 0.03, 0.47, 1.20])
s = np.abs(w).max() / 127
q = np.round(w / s).astype(np.int8)
w_hat = s * q
print("scale s   :", round(float(s), 6))
print("int8 q    :", q.tolist())
print("dequant   :", np.round(w_hat, 4).tolist())
print("max error :", round(float(np.abs(w - w_hat).max()), 6), " bound s/2 =", round(float(s / 2), 6))
scale s   : 0.009449
int8 q    : [-87, -11, 3, 50, 127]
dequant   : [-0.822, -0.1039, 0.0283, 0.4724, 1.2]
max error : 0.003937  bound s/2 = 0.004724
Answer

s=1.20/127≈0.009449s = 1.20/127 \approx 0.009449, the codes are [−87,−11,3,50,127][-87, -11, 3, 50, 127] and the largest rounding error is 0.003937 (−0.10 comes back as −0.1039), below the bound s/2≈0.004724s/2 \approx 0.004724 that rounding to the nearest step guarantees. One large weight sets the scale for all of them, which is why outliers hurt per-tensor quantization and per-channel scales help (quantization).

6. Soft targets

A teacher's logits for one image are [4.0,2.5,0.5][4.0, 2.5, 0.5]. Compute the softmax at temperature T=1T = 1 and T=4T = 4. Why does distillation use the second?

python · try it yourself
import numpy as np

def softmax(z, T):
    e = np.exp((z - z.max()) / T)
    return e / e.sum()

z = np.array([4.0, 2.5, 0.5])
for T in (1, 4):
    print(f"T = {T}:", np.round(softmax(z, T), 3).tolist())
T = 1: [0.798, 0.178, 0.024]
T = 4: [0.475, 0.327, 0.198]
Answer

At T=1T = 1 the teacher says "class 0" with 0.798 and the other classes almost vanish. At T=4T = 4 the distribution is softer (0.475, 0.327, 0.198) and shows that class 1 is much more similar to class 0 than class 2 is. That ranking of the wrong classes is the extra information a student learns from soft targets (distillation).

7. Is the canary worse?

The current model has an error rate of 2.0 % on 20,000 requests; the canary, on 5 % of traffic, has 2.6 % on 2,000. Is the difference significant at the 5 % level (two-proportion z-test)? What would you do?

python · try it yourself
import math
from scipy.stats import norm

x1, n1 = 400, 20000      # current model: 2.0 % errors
x2, n2 = 52, 2000        # canary: 2.6 % errors
p1, p2 = x1 / n1, x2 / n2
p = (x1 + x2) / (n1 + n2)
z = (p2 - p1) / math.sqrt(p * (1 - p) * (1 / n1 + 1 / n2))
print(f"p1 = {p1:.3f}, p2 = {p2:.3f}, z = {z:.2f}, two-sided p = {2 * norm.sf(abs(z)):.3f}")
p1 = 0.020, p2 = 0.026, z = 1.80, two-sided p = 0.071
Answer

z=1.80z = 1.80, p=0.071p = 0.071: not significant at 5 %, but not reassuring either, because 2,000 canary requests give little power to see a 0.6-point difference. Keep the canary at its small share and collect more traffic (or decide in advance on a sample size for the effect you care about) before promoting; roll back at once if the guard metric crosses a hard limit (deployment strategies, testing two proportions).

8. What does DVC put in Git?

You add a 2 GB data/train.parquet with DVC and commit. a) What goes into Git? b) A colleague changes three rows and runs dvc add again. What changes in Git? c) How do you get last month's version back?

Answer

a) A small data/train.parquet.dvc file with the content hash (md5), the size and the path, plus a .gitignore entry; the data itself goes to the DVC cache and, after dvc push, to remote storage. b) Only the hash and size in the .dvc file; the new content is stored under its new hash. c) git checkout <last month's commit> -- data/train.parquet.dvc and dvc checkout (or check out the whole commit): the .dvc file names the old hash, and DVC restores that content from the cache or remote (DVC).

9. PSI by hand

Reference shares in five bins: [0.2,0.2,0.2,0.2,0.2][0.2, 0.2, 0.2, 0.2, 0.2]; this week: [0.10,0.15,0.20,0.25,0.30][0.10, 0.15, 0.20, 0.25, 0.30]. Compute PSI=∑(ai−ei)ln⁡(ai/ei)\text{PSI} = \sum (a_i - e_i) \ln(a_i / e_i). Is the shift large by the usual rule of thumb?

python · try it yourself
import numpy as np

e = np.array([0.2, 0.2, 0.2, 0.2, 0.2])
a = np.array([0.10, 0.15, 0.20, 0.25, 0.30])
terms = (a - e) * np.log(a / e)
print("terms:", np.round(terms, 4).tolist())
print(f"PSI = {terms.sum():.4f}")
terms: [0.0693, 0.0144, 0.0, 0.0112, 0.0405]
PSI = 0.1354
Answer

PSI = 0.135: between 0.1 and 0.25, a "moderate shift, investigate" by the common rule of thumb. Every term is non-negative, and the emptiest bin (0.10 against 0.20) contributes the most. The thresholds are conventions, not statistical tests; with small windows PSI is noisy (try the drift lab with n=50n = 50) (data drift).

10. Stable inputs, falling accuracy

Input drift monitors (PSI on every feature) have been quiet for two months, but the accuracy measured on labels that arrive 30 days late has fallen from 0.91 to 0.84. What kind of drift is this, why did the input monitors miss it, and what do you do?

Answer

Concept drift: P(y∣x)P(y \mid x) changed while P(x)P(x) did not, so monitors that only look at inputs cannot see it. In the drift lab, the "concept" pattern shows exactly this: PSI misses it and Page-Hinkley on the error rate catches it. Act on the labelled signal: retrain on recent labelled data (a window that starts after the change), evaluate the challenger against the champion on the most recent labelled period, and shorten the label delay or add proxy signals for next time (concept drift, retraining).

11. A bad release at 3 a.m.

Version 14 of a model went live at 01:00 by moving the registry alias champion from version 13 to 14. At 03:00 the share of rejected applications doubles. List the steps of a good response, in order.

Answer
  1. Roll back first, investigate later: move champion back to version 13 (or redeploy the previous image) and confirm the rejection share returns to normal. 2. Open an incident with a timeline. 3. Keep version 14 and its logs for the investigation; compare its input data, features and predictions with version 13 on the same requests. 4. Find the cause (data, features, training, configuration) and add a gate or test that would have caught it (for example a check on the predicted class shares in the canary). 5. Write a blameless postmortem (rollback and incidents, model registry, postmortems).

12. Three security holes

A team publishes a model API that returns full probability vectors, accepts unlimited requests per key, and loads model files that users upload as pickles. Name the attack each design choice enables and one mitigation for each.

Answer

Full probability vectors with unlimited queries enable model extraction (training a copy from query results) and make membership inference easier: return labels or rounded scores, and rate-limit and monitor per-key query volume. Unlimited requests also enable denial of service and cheap adversarial search. Loading user-uploaded pickles is remote code execution: unpickling runs code chosen by the file's author; accept only safe formats (ONNX, safetensors, JSON weights), verify hashes and signatures of your own artifacts, and never unpickle untrusted data (security).

Test yourself

Which ships the preprocessing together with the model?

  1. Saving only the classifier and documenting the scaling
  2. Saving the fitted Pipeline (scaler + model) as one artifact
  3. Recomputing the scaler statistics in the service
  4. Storing the scaler in a README

With symmetric int8 quantization and scale s, what is the largest possible rounding error for a weight inside the range?

  1. s
  2. s/2
  3. 2s
  4. 127s

A canary's error rate is 2.6 % on 2,000 requests against 2.0 % on 20,000 for the current model (p = 0.071). What is the best reading?

  1. The canary is proven worse
  2. The canary is proven as good
  3. The data are not conclusive; collect more canary traffic before promoting
  4. Promote it immediately

PSI on every input is stable, but delayed-label accuracy falls. What is it most likely?

  1. Data (covariate) drift
  2. Concept drift
  3. A latency problem
  4. Training-serving skew in the label