Learning path: Serve a Model in Production: Docker, Latency and Scaling · Step 3 of 9
Batch Scoring a Million Rows: Chunks, a Run ID and a Safe Rerun
Score one million rows with a saved model: all at once, then in chunks that use about half the memory with identical answers. Then make the job safe to kill and rerun with a run id, one part file per chunk, and a tmp-then-rename write.
What you will learn
- Score a large CSV in chunks with pandas read_csv(chunksize=...) to cut peak memory
- Measure peak memory and time over several runs instead of one
- Explain why appending to one output file is not safe to rerun
- Write one part file per chunk under a run id, with a tmp-then-rename write, so a rerun skips finished work
Before you start
- Saving and Loading Models with joblib
- Online, Batch or Streaming? Picking the Serving Pattern
When nobody is waiting for an answer, you can score a whole table ahead of time; that's the batch pattern from Online, Batch or Streaming?. Here we do it for real: score a million rows with the saved rain model, in chunks, write the results under a run id, and make a rerun safe.
Print the whole town's bills overnight
Think of a town's electricity bills. You could send a courier to every doorbell: one bill, one trip. Or print them all overnight. The printer fills trays, and by morning everything is ready. A bill is one row, a tray is one chunk, and the night run is one batch job.
A million rows, built from real ones
The model is the rain pipeline from Deploy a Machine Learning Model with FastAPI, which reads five columns. For the input we take the 142,193 real rain rows of the dataset and repeat them until we reach a million. The rows are real; only the size is made up.
import os
import pandas as pd
N = 1_000_000
real = pd.read_csv("rain_source.csv.gz")
passes = -(-N // len(real)) # round up
df = pd.concat([real] * passes, ignore_index=True).head(N)
df.insert(0, "row_id", range(N))
df.to_csv("input.csv", index=False)
mb = os.path.getsize("input.csv") / 2**20
print(f"{len(real):,} real rows x {passes} passes, cut at {N:,}")
print(f"input.csv: {len(df):,} rows, {df.shape[1]} columns, {mb:,.0f} MB")
142,193 real rows x 8 passes, cut at 1,000,000
input.csv: 1,000,000 rows, 25 columns, 114 MB
Every row gets its own row_id, from 0 to 999,999. We'll need it to check the output.
The scoring scripts share a few names from common.py: the five model inputs and the input file.
FEATURES = ["Rainfall", "Humidity3pm", "Cloud9am", "Cloud3pm", "RainToday"]
INPUT = Path("input.csv")
Everything at once
import joblib
import pandas as pd
import meter
from common import FEATURES, INPUT
t0 = meter.start()
model = joblib.load("model.joblib")
df = pd.read_csv(INPUT)
df["rain_probability"] = model.predict_proba(df[FEATURES])[:, 1]
df[["row_id", "rain_probability"]].to_csv("all_at_once.csv", index=False)
meter.report(t0, f"{len(df):,} rows at once: ")
1,000,000 rows at once: took 4.7 s, peak memory 576 MB
All one million rows sit in memory, and so do the inputs and probabilities. For comparison, Python, the libraries and the model with no data at all take about 163 MB. Memory grows with the rows.
The same job, one chunk at a time
read_csv with chunksize hands us the table in pieces, so memory only holds one piece at a time:
import sys
from pathlib import Path
import joblib
import pandas as pd
import meter
from common import FEATURES, INPUT
CHUNK = int(sys.argv[1]) if len(sys.argv) > 1 else 100_000
OUT = Path("scores.csv")
t0 = meter.start()
model = joblib.load("model.joblib")
rows = 0
for chunk in pd.read_csv(INPUT, chunksize=CHUNK):
chunk["rain_probability"] = model.predict_proba(chunk[FEATURES])[:, 1]
chunk[["row_id", "rain_probability"]].to_csv(
OUT, mode="a", header=not OUT.exists(), index=False)
rows += len(chunk)
meter.report(t0, f"{rows:,} rows in chunks of {CHUNK:,}: ")
1,000,000 rows in chunks of 100,000: took 4.9 s, peak memory 271 MB
About the same time, about half the memory. Are the answers the same? compare.py lines up both files:
1,000,000 vs 1,000,000 rows, same ids True, largest difference 0.0
Eight runs each, not one lucky one
One run can mislead, so here's how we measured. meter.py asks the operating system for the most memory the process ever used: the peak working set on Windows, the max resident size on Mac and Linux.
def peak_mb():
if sys.platform == "win32":
return psutil.Process().memory_info().peak_wset / 2**20
import resource # Mac and Linux
peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
return peak / 2**20 if sys.platform == "darwin" else peak / 1024
We ran each case eight times, taking turns, on this machine. Medians:
| Case | Median peak memory | Median time |
|---|---|---|
| All at once | 570 MB | 8.3 s (p95 10.7 s) |
| Chunks of 500,000 | 504 MB | 8.9 s |
| Chunks of 250,000 | 352 MB | 9.7 s |
| Chunks of 100,000 | 269 MB | 9.7 s |
| Chunks of 50,000 | 242 MB | 10.5 s |
| Chunks of 10,000 | 198 MB | 11.3 s |
Now look at the time column. No chunk size beat all at once, and tiny chunks of 10,000 were the slowest, 11.3 s against 8.3 s. Chunks cut the memory. They do not cut the time. (These are this machine's numbers; the single runs above were quicker than the medians, which is exactly why we take several.)
A rerun that writes everything twice
There's a trap in the chunked version. It appends every chunk to one file (mode="a"). We ran it and killed it part way: 508,930 rows were already in scores.csv. Then we ran it again, the way you would. It starts from row 0 and appends a million more rows after the old ones. verify.py counts:
rows 1,508,930 unique ids 1,000,000 duplicates 508,930 missing 0
The rerun made it worse. Appending is not safe to run again.
A run id, and one file per chunk
import sys
from pathlib import Path
import joblib
import pandas as pd
import meter
from common import FEATURES, INPUT, claim_run, write_part
CHUNK = int(sys.argv[2]) if len(sys.argv) > 2 else 100_000
t0 = meter.start()
model = joblib.load("model.joblib")
RUN_ID = sys.argv[1]
out = Path("out") / RUN_ID
claim_run(out, {"run_id": RUN_ID, "chunk": CHUNK})
scored = skipped = 0
for n, chunk in enumerate(pd.read_csv(INPUT, chunksize=CHUNK)):
part = out / f"part-{n:04d}.csv"
if part.exists():
skipped += 1
continue
chunk["rain_probability"] = model.predict_proba(chunk[FEATURES])[:, 1]
write_part(chunk[["row_id", "rain_probability"]], part)
scored += 1
(out / "DONE").write_text(f"{scored + skipped} parts")
meter.report(t0, f"{RUN_ID}: scored {scored}, skipped {skipped}, ")
- The run id comes from the command line, here
r01, and the output goes intoout/r01/. We choose it, so the same id finds the same parts. A random id would start a new run every time. - Each chunk gets a part name from its number:
part-0000.csv,part-0001.csv, and so on. Ten chunks, ten parts. - If the part already exists, it's counted as skipped. That's what a rerun needs.
Finished, or not there at all
How do we know a part is really finished? write_part never writes straight to the part name:
def write_part(frame, part):
tmp = part.with_name(part.name + ".tmp")
frame.to_csv(tmp, index=False)
tmp.replace(part) # a part exists only when it is complete
It writes to a name ending in .tmp, and only when the whole file is written does tmp.replace rename it. If the job is killed in the middle, a half-written .tmp stays behind, but readers only look for part-*.csv, so it's never picked up.
Killed half-way, run again
We started the job and killed it. Six parts were done and part six was only a .tmp stub:
rows 600,000 unique ids 600,000 duplicates 0 missing 400,000
Nothing is wrong; it's just not finished. Same command again:
r01: scored 4, skipped 6, took 12.1 s, peak memory 264 MB
rows 1,000,000 unique ids 1,000,000 duplicates 0 missing 0
fingerprint 591ce5a3
The six earlier parts weren't touched. Only the missing ones were written.
Run it again, nothing changes
A third run:
r01: scored 0, skipped 10, took 8.3 s, peak memory 252 MB
It still takes time because it reads the input again, but it writes nothing. verify.py prints a fingerprint of all the part files, 591ce5a3, the same as before, so nothing changed. And compare.py shows the parts match the all-at-once answers, largest difference 0.0.
One more guard. claim_run writes a settings.json into the run folder:
def claim_run(out, settings):
"""a run id belongs to one set of settings"""
out.mkdir(parents=True, exist_ok=True)
file = out / "settings.json"
if file.exists() and json.loads(file.read_text()) != settings:
sys.exit(f"{out.name} was started with other settings")
file.write_text(json.dumps(settings))
Try the same run id with a chunk size of 50,000 and it stops before writing anything:
r01 was started with other settings
With a different chunk size, part-0003.csv would mean different rows, so mixing them would be wrong.
Common mistakes
- Expecting chunks to be faster. They cut memory. Here, no chunk size beat all at once on time.
- Appending to one output file. A rerun after a crash duplicates everything already written.
- A random run id. Every rerun becomes a new run and finds nothing to skip.
- Writing straight to the final name. A killed job leaves a half file that looks finished.
- Trusting one timing. Run each case several times and compare medians.
Quick recap
| Idea | Code | Real result |
|---|---|---|
| Chunks | pd.read_csv(INPUT, chunksize=CHUNK) | 570 MB down to 269 MB at 100,000, same answers |
| Run id | out = Path("out") / RUN_ID | one folder, ten parts |
| Whole parts only | write .tmp, then tmp.replace(part) | a killed part is never read |
| Safe rerun | if part.exists(): skip | scored 4, skipped 6, duplicates 0 |
| Same id, same settings | claim_run | "r01 was started with other settings" |
Try it yourself
Delete one part file from out/r01 and run python score_chunks.py r01 again. How many parts does it score, and what does verify.py say? The project and the rain data are in the community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →A Production FastAPI for an ML Model: Input Limits, /health, /ready and a Model Version
Next →Docker Essentials for ML: Images, Containers and Volumes with a Model API
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.