Sign in

Batch

Batch inference (offline scoring)

An offline scorer that runs a model over a large input in ordered chunks, with worker threads, retries and the ability to resume after a crash.

Overview

Some predictions are not needed this second: tomorrow's score for every customer, or a backfill over last year. Batch inference handles these in bulk. The input is cut into chunks, each chunk goes through the model in one call, and the results are put back in the original order. Because a long job may be interrupted, each finished chunk is saved as its own file. When the job is started again, it sees which files exist and only does the missing work.

A short history

Batch processing is as old as commercial computing, where jobs were queued and run overnight on mainframes. It has no single inventor. Its modern large scale form was shaped by MapReduce, described by Jeffrey Dean and Sanjay Ghemawat of Google in 2004, which split work into chunks, retried failed chunks and made reruns safe. Batch scoring of models applies the same ideas: ordered chunks, retries, and outputs written so that a crashed job can resume.

How it works

  1. Wrap any function that maps a chunk of rows to predictions in a BatchScorer.
  2. score cuts the array into chunks of batch_size, scores them on a pool of num_workers threads, and joins the results in row order.
  3. A model call that raises is tried again up to max_retries more times before the chunk fails.
  4. score_to_dir writes one file per chunk. Each file is written under a temporary name and then renamed, so a file that exists is always complete.
  5. On a rerun with resume on, chunks whose file already exists are skipped. A manifest records the row count and batch size and refuses a resume with different ones.
  6. load reads the files back in order, and score_csv streams a CSV file through the model with one chunk in memory at a time.

Watch out for

  • A batch size too large for memory crashes the job, and one too small wastes time on per-call overhead. Measure both before a long run.
  • More threads only help when the model releases Python's global lock (NumPy linear algebra does) or waits on input and output. Pure Python models run no faster.
  • Retries assume the failure is temporary. A chunk with bad data fails every time, so the retries only delay the error.
  • Resuming with a different model but the same output folder mixes old and new predictions, because existing files are trusted as they are.
  • This is a single-process version with threads and local files. It has no job queue or cluster, which large batch systems add.

Use cases

When to use it

For scoring that can wait: nightly predictions, backfills, or a test set too large for one model call. Use score_to_dir when the job is long enough that it may be interrupted.

In industry

Retail and marketing
Every night a retailer scores all customers for churn or next purchase and stores the results in a table that campaigns read the next morning.
Insurance
When a new risk model is approved, the whole book of existing policies is rescored in one long job that must be able to resume after a failure.
Media and recommendation
Recommendations for each user are computed ahead of time in bulk and then served from a lookup store, so no model runs while the user waits.

Choosing it: what must hold

  • Predictions that can wait minutes or hours, with nobody waiting on each one.
  • Inputs known ahead of time, so they can be listed and cut into chunks.
  • A model call that gives the same output when repeated, so retries and resumed runs are safe.
  • Somewhere to store the outputs for later lookup.

When to choose something else

IfUse instead
A user or another service waits for each predictionThe online inference serving lesson
Inputs are not known until the moment of the requestOnline serving, with the serve-time preprocessing lesson for the transforms
The job must run on a timetableThe job scheduling lesson to start this scorer at fixed times

Math foundations

  1. Number of chunks

    K=⌈Nb⌉K = \left\lceil \frac{N}{b} \right\rceil

    Scoring NN rows with batch size bb takes KK model calls. The last chunk holds the remainder.

  2. Chance that a chunk fails for good

    P(chunk fails)=p 1+rP(\text{chunk fails}) = p^{\,1 + r}

    If each model call fails independently with probability pp, a chunk fails only when the first try and all rr retries fail. Retries turn a rare failure into a far rarer one.

  3. Work left after a restart

    Ktodo=K−KdoneK_{\text{todo}} = K - K_{\text{done}}

    With one output file per chunk, a restart costs only the chunks that had not finished. Without that, an interruption costs the whole job again.

Symbols

NN
number of rows to score
bb
batch_size, rows per model call
KK
number of chunks
pp
probability that one model call fails
rr
max_retries, extra attempts per chunk
KdoneK_{\text{done}}
chunks whose output file already exists

Worked by hand

Score 1,000 rows with a batch size of 128. Each call fails with probability 0.1 and max_retries is 2. The job crashes after 5 chunks are written.

K=⌈1000128⌉=8,1000−7×128=104 rows in the last chunkK = \left\lceil \frac{1000}{128} \right\rceil = 8, \qquad 1000 - 7 \times 128 = 104 \text{ rows in the last chunk}
P(chunk fails)=0.1 1+2=0.001P(\text{chunk fails}) = 0.1^{\,1 + 2} = 0.001
Ktodo=8−5=3K_{\text{todo}} = 8 - 5 = 3

Eight chunks, the last with 104 rows. A chunk now fails once in a thousand instead of once in ten, and the restart scores 3 chunks, not 8.

Visual example

Loading the example.

Try this

  • Press Run and let the job crash, then press Run again: with resume on, the files already written are skipped.
  • Turn resume off and rerun after a crash. Count the model calls that were paid for twice.
  • Raise the failure chance to 0.4 with max_retries at 0, then add retries until the job gets through.

Code sample

import tempfile
import numpy as np
from impl import BatchScorer
from config import BatchInferenceConfig

weights = np.array([0.5, -1.0, 2.0])
model = lambda X: X @ weights                       # any function from a chunk of rows to predictions

X = np.random.default_rng(0).normal(size=(1000, 3))
scorer = BatchScorer(model, BatchInferenceConfig(batch_size=128, num_workers=4))
predictions = scorer.score(X)                       # shape (1000,), same order as X

out_dir = tempfile.mkdtemp()
print(scorer.score_to_dir(X, out_dir))              # 8 chunks scored
print(scorer.score_to_dir(X, out_dir))              # 8 chunks skipped: the job was already done
print(np.allclose(scorer.load(out_dir), predictions))
Read the implementation (174 lines)
"""Offline batch scoring: run a model over a large input in chunks, in order, with workers, retries and resume.

Standard library and NumPy only. The model is any function `predict(X_chunk) -> predictions` where X_chunk
has shape (rows, ...) and the result has `rows` as its first dimension. Three entry points:
    score         array in, array out
    score_to_dir  array in, one .npy file per chunk out, restartable
    score_csv     CSV file in, CSV file out, streamed so the input never sits in memory whole
"""
from __future__ import annotations

import csv
import json
import os
from concurrent.futures import ThreadPoolExecutor
from typing import Callable, Iterator

import numpy as np

try:
    from .config import BatchInferenceConfig
except ImportError:  # run from the template's own folder
    from config import BatchInferenceConfig

MANIFEST = "manifest.json"


class BatchScorer:
    """Score data in chunks with `predict_fn`.

    stats_ describes the latest run: "rows", "chunks_total", "chunks_scored", "chunks_skipped" (already
    done, resume) and "retries".
    """

    def __init__(self, predict_fn: Callable, config: BatchInferenceConfig | None = None) -> None:
        self.predict_fn = predict_fn
        self.config = config or BatchInferenceConfig()
        self.stats_: dict = {}

    # ------------------------------------------------------------------------------------------ helpers
    def _bounds(self, n_rows: int) -> list[tuple[int, int]]:
        """(start, stop) row ranges of the chunks."""
        size = self.config.batch_size
        return [(start, min(start + size, n_rows)) for start in range(0, n_rows, size)]

    def _predict(self, chunk: np.ndarray) -> np.ndarray:
        """One model call with retries and a check that the model returned one prediction per row."""
        attempt = 0
        while True:
            try:
                out = np.asarray(self.predict_fn(chunk))
                break
            except Exception:
                if attempt >= self.config.max_retries:
                    raise
                attempt += 1
                self.stats_["retries"] += 1
        if out.shape[:1] != (len(chunk),):
            raise ValueError(f"the model returned shape {out.shape} for {len(chunk)} rows")
        return out

    def _reset(self, n_rows: int, n_chunks: int) -> None:
        self.stats_ = {"rows": n_rows, "chunks_total": n_chunks, "chunks_scored": 0, "chunks_skipped": 0,
                       "retries": 0}

    # ------------------------------------------------------------------------------------- array -> array
    def score(self, X) -> np.ndarray:
        """Predictions for X, shape (n_rows, ...), in the order of the rows. Returns shape (n_rows, ...)."""
        X = np.asarray(X)
        bounds = self._bounds(len(X))
        self._reset(len(X), len(bounds))
        if not bounds:
            return np.asarray(self.predict_fn(X))
        with ThreadPoolExecutor(max_workers=self.config.num_workers) as pool:
            # map returns results in the order of the inputs, whatever order the threads finish in
            parts = list(pool.map(lambda b: self._predict(X[b[0]: b[1]]), bounds))
        self.stats_["chunks_scored"] = len(parts)
        return np.concatenate(parts, axis=0)

    # ------------------------------------------------------------------------------------- array -> files
    def _part_path(self, out_dir: str, index: int) -> str:
        return os.path.join(out_dir, f"{self.config.prefix}-{index:05d}.npy")

    def score_to_dir(self, X, out_dir: str) -> dict:
        """Score X and write one file per chunk into out_dir. Returns stats_.

        Each file is written under a temporary name and then renamed, so a file that exists is complete.
        With resume on, existing chunk files are kept and only the missing chunks are scored. A manifest
        records the row count and batch size; resuming with different ones is refused.
        """
        X = np.asarray(X)
        cfg = self.config
        bounds = self._bounds(len(X))
        self._reset(len(X), len(bounds))
        os.makedirs(out_dir, exist_ok=True)
        manifest_path = os.path.join(out_dir, MANIFEST)
        manifest = {"rows": len(X), "batch_size": cfg.batch_size, "chunks": len(bounds), "prefix": cfg.prefix}
        if cfg.resume and os.path.exists(manifest_path):
            with open(manifest_path, encoding="utf-8") as handle:
                previous = json.load(handle)
            if previous != manifest:
                raise ValueError(f"{out_dir} holds a different job ({previous}), cannot resume as {manifest}")
        with open(manifest_path, "w", encoding="utf-8") as handle:
            json.dump(manifest, handle)

        todo = []
        for index, bound in enumerate(bounds):
            if cfg.resume and os.path.exists(self._part_path(out_dir, index)):
                self.stats_["chunks_skipped"] += 1
            else:
                todo.append((index, bound))

        def work(item) -> None:
            index, (start, stop) = item
            out = self._predict(X[start:stop])
            final = self._part_path(out_dir, index)
            with open(final + ".tmp", "wb") as handle:
                np.save(handle, out)
            os.replace(final + ".tmp", final)  # atomic: readers never see a half-written chunk

        with ThreadPoolExecutor(max_workers=cfg.num_workers) as pool:
            futures = [pool.submit(work, item) for item in todo]
            errors = [f.exception() for f in futures]
        self.stats_["chunks_scored"] = sum(error is None for error in errors)
        for error in errors:
            if error is not None:
                raise error  # the chunks that did finish stay on disk for the next run
        return self.stats_

    def load(self, out_dir: str) -> np.ndarray:
        """Read the predictions written by `score_to_dir`, in row order. Fails if any chunk is missing."""
        with open(os.path.join(out_dir, MANIFEST), encoding="utf-8") as handle:
            manifest = json.load(handle)
        paths = [os.path.join(out_dir, f"{manifest['prefix']}-{i:05d}.npy") for i in range(manifest["chunks"])]
        missing = [os.path.basename(p) for p in paths if not os.path.exists(p)]
        if missing:
            raise FileNotFoundError(f"job in {out_dir} is incomplete, missing {missing}")
        return np.concatenate([np.load(p) for p in paths], axis=0)

    # ----------------------------------------------------------------------------------------- csv -> csv
    def _csv_chunks(self, reader: Iterator[dict], features: list[str], id_column: str | None):
        """Yield (ids, feature array of shape (rows, n_features)) for batch_size rows at a time."""
        ids, rows = [], []
        for number, record in enumerate(reader):
            ids.append(record[id_column] if id_column else str(number))
            rows.append([float(record[name]) for name in features])
            if len(rows) == self.config.batch_size:
                yield ids, np.array(rows)
                ids, rows = [], []
        if rows:
            yield ids, np.array(rows)

    def score_csv(self, in_path: str, out_path: str, features: list[str], id_column: str | None = None) -> dict:
        """Stream a CSV file with a header through the model and write "id,prediction" rows.

        features:  names of the numeric columns that form the model input, in order.
        id_column: column copied to the output to identify each row. Default: the row number.
        Only one chunk is in memory at a time. The output appears under its final name only when the
        whole file has been scored. Returns stats_.
        """
        self._reset(0, 0)
        tmp_path = out_path + ".tmp"
        with open(in_path, newline="", encoding="utf-8") as source, \
                open(tmp_path, "w", newline="", encoding="utf-8") as sink:
            writer = csv.writer(sink)
            writer.writerow(["id", "prediction"])
            for ids, chunk in self._csv_chunks(csv.DictReader(source), features, id_column):
                predictions = self._predict(chunk).reshape(len(ids), -1)
                for row_id, prediction in zip(ids, predictions):
                    writer.writerow([row_id] + [repr(float(v)) for v in prediction])
                self.stats_["rows"] += len(ids)
                self.stats_["chunks_total"] += 1
                self.stats_["chunks_scored"] += 1
        os.replace(tmp_path, out_path)
        return self.stats_
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
7, run with python3 -m unittest -v

Practice

Make a predict_fn that raises an error on its third call. Run BatchScorer(predict_fn, BatchInferenceConfig(batch_size=128)).score_to_dir(X, out_dir) on 1,000 rows and catch the error. Run it again, read stats_["chunks_skipped"] and stats_["chunks_scored"], and check load(out_dir) against a direct model call.

Check on learning

  1. Why is each chunk file written under a temporary name and then renamed, instead of written directly under its final name?
    A way to think about it

    Picture a crash halfway through writing a file. Ask what the resume logic concludes when it finds that file on the next run.

  2. With 4 workers the job is 3.5 times faster for a NumPy model and no faster for a model written in pure Python loops. Explain the difference.
    A way to think about it

    Only one thread runs Python code at a time. Find out which of the two models spends its time outside that restriction.

  3. You retrain the model and rerun the batch job into the same folder with resume on. The stats say every chunk was skipped. What happened, and how would you prevent it?
    A way to think about it

    The scorer decides by whether a file exists, not by which model wrote it. Think about what should be part of the output location.

  4. One chunk fails on every retry while the others succeed. What does that pattern suggest about the cause, and what is the right response?
    A way to think about it

    Separate failures of the environment, which come and go, from failures tied to particular rows. Decide which kind repeats exactly.

  5. When would you pick batch inference over an online server for the same model, and what do you give up?
    A way to think about it

    Compare cost per prediction and how fresh the answer is. Ask what happens for an input that did not exist when the nightly job ran.