marcuskeenton's picture
Add sentiment demo, integration tests and README
06d6eb0 verified
|
Raw History Blame Contribute Delete
6.45 kB
---
title: Inference API Integration Tests
colorFrom: blue
colorTo: gray
sdk: static
app_file: index.html
pinned: false
license: mit
short_description: Integration tests for a small sentiment inference app
---
**The label that changed and nobody's tests noticed**
We swapped the checkpoint behind a sentiment endpoint on a Thursday. Same architecture, slightly better accuracy on our eval set, a two-line change in the config. Every test passed. On Friday the dashboard that reads from that endpoint showed zero positive reviews for the whole day.
The new checkpoint had been saved without an `id2label` mapping, so the pipeline started returning `LABEL_0` and `LABEL_1` instead of `POSITIVE` and `NEGATIVE`. Our tests never saw it, because every one of them mocked the pipeline call and returned a nicely formatted dict we'd written by hand. The dashboard filtered on `"positive"`, found nothing, and drew a flat line.
That's the kind of bug this Space is about. It's a tiny browser app (`index.html`) and a short test file (`tests/test_app.py`) that checks the whole path: raw text in, cleanup, model, JSON out.
## Why ML apps break between the pieces
Most of us test models and test code, but separately. The model gets an eval notebook with accuracy numbers. The code gets unit tests with the model mocked out. What falls through is the seam in the middle: the shape of what the pipeline returns, how the tokenizer handles odd input, what the API layer does with an exception.
For the general picture, there's a good write-up on [what is integration testing](https://keploy.io/blog/community/integration-testing-a-comprehensive-guide) that I'd point a new teammate to. For ML apps I think of it more narrowly. Send the request a real client would send, let it pass through the real preprocessing and the real model, and check the response the real client would read. No mocks in the middle.
The second bug that pushed us here was dumber. Someone pasted a whole product manual into the text box. Without `truncation=True`, the model got more than 512 tokens and the request died with an index error. Unit tests never fed it anything longer than a sentence, so of course they passed.
## What the app does
The app is deliberately small. `preprocess` collapses whitespace, rejects empty input and caps length at 1000 characters. `classify` runs a DistilBERT model fine-tuned on SST-2 and returns three fields: `label`, `score` and `chars_used`. That last one exists mostly so tests can see what preprocessing actually did.
Everything runs in the browser through Transformers.js, so the button on the page is the only entry point, and it's exactly what the tests press.
## The tests
The test file serves the page on a local port and drives it with Playwright in headless Chromium. That means each test goes through the page, preprocessing, the tokenizer and the model before the assertion runs.
```python
@pytest.fixture(scope="module")
def page():
handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=ROOT)
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto(f"http://127.0.0.1:{server.server_port}/index.html")
page.wait_for_selector("#run:not([disabled])", timeout=180_000)
yield page
browser.close()
server.shutdown()
def classify(page, text):
page.fill("#text", text)
page.click("#run")
page.wait_for_selector('#output[data-ready="true"]', timeout=30_000)
return json.loads(page.inner_text("#output"))
def test_positive_text_round_trip(page):
out = classify(page, " I really enjoyed this film.\n\n")
assert set(out) == {"label", "score", "chars_used"}
assert out["label"] == "positive"
assert 0.5 < out["score"] <= 1.0
assert out["chars_used"] == len("I really enjoyed this film.")
def test_long_input_is_trimmed_not_rejected(page):
assert classify(page, "good " * 2000)["chars_used"] == 1000
```
A few choices here are on purpose.
The first assertion checks the set of keys, not just one value. If someone adds a field or renames `score` to `confidence`, this fails before a downstream consumer does.
The label check uses an obvious sentence. I don't assert exact scores, ever. They drift a little across library versions and hardware, and a test that fails because 0.9998 became 0.9997 teaches people to ignore red builds. A threshold is enough.
The long-input test is the one that would have caught the manual-paste crash. It also confirms that trimming happens before the model, which matters if you're paying per token anywhere downstream.
There's also a test that sends only whitespace and expects an error. Boring, but empty strings are the most common bad input we see in logs.
To run them locally or in a CI job:
```bash
pip install pytest playwright
playwright install chromium
python -m pytest -q tests
```
The first run downloads the model, so it's slow. After that the whole file takes around 10 seconds on a laptop CPU.
## Things I'd skip
I wouldn't spin up a GPU just for these. A small checkpoint on CPU gives you the same response shapes, and that's what you're testing here. Save the expensive hardware for eval runs.
I'd also skip snapshot testing full model outputs. It sounds thorough, and then every dependency bump rewrites fifty snapshots and someone approves them without reading. Pick the handful of properties a client actually depends on and assert those.
And I'm not a fan of mocking the pipeline "to keep tests fast" in the one place where the pipeline's output format is the thing that matters. Keep unit tests for your own logic. Let at least one test go all the way through.
## When the model lives somewhere else
If your model sits behind a separate inference server, the same idea holds, with one twist. Pin the model revision in your config and run these tests against that exact revision in CI. Our label bug came from pulling a newer checkpoint without anyone noticing. A pinned revision turns that into a deliberate change, and a deliberate change gets a test run.
Before you change a model ID, run the integration tests against the new checkpoint first. It takes a couple of minutes, and it's a lot cheaper than finding out from a flat line on a dashboard.