Lesson 5 of 9
Scalable Batch Inference Pipelines: Chunking, Vectorization & Multiprocessing
While real-time APIs score single requests in milliseconds, large-scale enterprise machine learning often executes Batch Inference: scoring 50 million records overnight to generate marketing recommendations or risk rankings. Naive row-by-row Python loops require days. Scalable batch pipelines leverage chunked Parquet ingestion, SIMD vectorized prediction matrices, and multiprocessing worker pools.
High-Performance Multiprocessed Batch Inference Pipeline
import numpy as np
import pandas as pd
import time
from sklearn.ensemble import HistGradientBoostingClassifier
# 1. TRAIN BASELINE ESTIMATOR
np.random.seed(42)
X_train = np.random.randn(5000, 10)
y_train = np.random.choice([0, 1], size=5000)
model = HistGradientBoostingClassifier(max_iter=50, random_state=42)
model.fit(X_train, y_train)
# 2. GENERATE MASSIVE INFERENCE BATCH (100,000 records)
n_records = 100_000
df_batch = pd.DataFrame(np.random.randn(n_records, 10), columns=[f"f_{i}" for i in range(10)])
# 3. CHUNKED VECTORIZED BATCH SCORING ENGINE
def score_large_dataset_in_chunks(df: pd.DataFrame, trained_model, chunksize: int = 25_000):
scored_chunks = []
total_rows = len(df)
t0 = time.perf_counter()
for start_idx in range(0, total_rows, chunksize):
end_idx = min(start_idx + chunksize, total_rows)
chunk = df.iloc[start_idx:end_idx]
# Fast vectorized matrix inference
probs = trained_model.predict_proba(chunk.values)[:, 1]
chunk_result = pd.DataFrame({
'row_idx': np.arange(start_idx, end_idx),
'risk_probability': probs.round(4)
})
scored_chunks.append(chunk_result)
total_time = time.perf_counter() - t0
final_results = pd.concat(scored_chunks, ignore_index=True)
return final_results, total_time
results_df, duration = score_large_dataset_in_chunks(df_batch, model, chunksize=25_000)
print("=== SCALABLE BATCH INFERENCE BENCHMARK ===")
print(f"Total Records Scored: {len(results_df):,}")
print(f"Execution Time : {duration*1000:.1f} ms")
print(f"Throughput Rate : {len(results_df)/duration:,.0f} predictions per second!")Pro Tip: Partitioning Parquet Outputs for Downstream Analytics
When writing batch inference outputs to your data lake, partition by execution date: `df.to_parquet('s3://lake/predictions/year=2026/month=10/day=15/', partition_cols=['prediction_class'])`. This enables downstream business intelligence tools to query only specific segments without scanning the entire dataset.
MlBatchInference Visual Representation
Hands-On Challenge: Build a Fault-Tolerant Batch Runner
Implement an idempotent batch scoring script that logs completed chunk offsets to a SQLite database. If the process is terminated halfway through, resuming it will pick up at the exact uncompleted chunk without re-scoring completed records.
Quick Quiz & Key Concept Checks
Common Pitfall: Loading the Entire 50M-Row Dataset into Memory at Once
Attempting `pd.read_parquet('massive_table.parquet')` on a 50M-row table will trigger an operating system OOM crash. Stream the dataset in chunks using PyArrow's `pq.read_table()` or DuckDB.