PeaBox Lab › PeaLang › Learn › Chapter 19 › Lesson 6

Part IV — Expert Production Engineering · Chapter 19 · Lesson 6 of 7 · 6 min read

Lesson 6: Pipelines, Persistence, Schema Validation, and Reproducibility

Lesson level: Advanced

Purpose: Package preprocessing, model, calibration, and decision rules into one artifact that validates its inputs, can be saved and reloaded safely, and can be rebuilt bit-for-bit from recorded inputs.

Learning objectives

By the end of this lesson you will be able to:

6.1 Why pipelines

Lessons 1 to 5 built a chain: impute, scale, encode, fit a model, calibrate, apply a threshold. Done as separate steps, the chain is easy to break — a step can be fitted on the wrong data, skipped in production, or applied in a different order. A pipeline makes the chain one object with one fit and one predict:

6.2 Column-wise preprocessing

Real tables mix types. A column transformer sends numeric columns to imputation and scaling, categorical columns to encoding, and drops or passes through the rest, then joins the results in a fixed, documented order.

Illustrative listing.

from pealang.ml import (Pipeline, ColumnTransformer, SimpleImputer,
                        StandardScaler, OneHotEncoder, LogisticRegression)

numeric = Pipeline([("impute", SimpleImputer(strategy="median", add_indicator=True)),
                    ("scale",  StandardScaler())])
categorical = OneHotEncoder(handle_unknown="unknown_bucket", min_frequency=20)

prep = ColumnTransformer([
    ("num", numeric,     ["age", "tenure_days", "monthly_spend", "tickets_90d"]),
    ("cat", categorical, ["region", "plan", "channel"]),
], remainder="drop")

churn_pipe = Pipeline([("prep", prep),
                       ("model", LogisticRegression(penalty="l2", seed=42))])

Use remainder="drop" deliberately: a new column that appears upstream should not silently enter the model. Adding a feature is a model change that deserves review and retraining.

6.3 Input schema validation

A fitted pipeline assumes a particular input shape. Make that assumption explicit with a schema — the data foundation's Schema and Field types from Chapter 16 — and check it at both fit time and predict time.

Decide what a violation does. For batch scoring, reject offending rows and report them with reasons; for an online service, return a clear validation error rather than a prediction from malformed input. Never let a model score data it was not designed for and present the result as normal. The rejection rate per field is one of the best early warnings of upstream change, and Chapter 20 monitors it.

Illustrative listing.

from pealang.data import Schema, Field, DataType

INPUT_SCHEMA = Schema([
    Field("customer_id",   DataType.STRING,  nullable=False),
    Field("age",           DataType.INT64,   nullable=True,  min=18, max=120),
    Field("tenure_days",   DataType.INT64,   nullable=False, min=0),
    Field("monthly_spend", DataType.FLOAT64, nullable=True,  min=0),
    Field("tickets_90d",   DataType.INT64,   nullable=False, min=0),
    Field("region",        DataType.STRING,  nullable=False),
    Field("plan",          DataType.STRING,  nullable=False),
    Field("channel",       DataType.STRING,  nullable=True),
])

report = INPUT_SCHEMA.validate(batch)
valid_rows, rejected = report.valid, report.rejected

6.4 Persisting a fitted pipeline

A saved model is more than its weights. Persist the fitted pipeline together with the metadata that makes it understandable and safe to load:

MetadataExample
IdentityModel name, version, creation time (UTC)
InputsInput schema, feature list in order, target definition
Training dataDataset identifier, row count, date range, content hash
ConfigurationHyperparameters, seeds, split strategy, threshold and decision policy
EnvironmentPeaLang version, host package version, dependency versions
EvaluationCross-validation and test metrics, calibration summary, segment results
IntegrityHash of the serialized artifact

Load only trusted artifacts. Some general-purpose serialization formats can execute code while loading, so a tampered model file can be an attack vector. Prefer the serialization format provided by the ML layer, verify the artifact hash before loading, and load only from controlled locations. Chapter 20 adds integrity-checked bundles, registries, signing, and encryption on top of these basics.

Illustrative listing.

from pealang.ml import save_pipeline, load_pipeline

meta = {"name": "churn", "version": "1.0.0", "seed": 42,
        "threshold": 0.09, "train_rows": X_train.height,
        "data_hash": data_hash, "metrics": test_metrics}
path = save_pipeline(churn_pipe, "models/churn-1.0.0", metadata=meta,
                     schema=INPUT_SCHEMA)

loaded = load_pipeline("models/churn-1.0.0", expected_hash=artifact_hash)
assert loaded.predict_proba(X_test) == churn_pipe.predict_proba(X_test)

6.5 Reproducibility

A model is reproducible when someone else, later, can rebuild it from recorded inputs and obtain the same artifact and the same predictions. That requires controlling every source of variation:

Treat exact equality as the goal and a documented tolerance as the fallback. Some numerical libraries produce tiny differences across hardware or thread counts; if so, record the tolerance and test against it.

6.6 Testing the pipeline

Apply the testing discipline of Chapter 10 to the model artifact:

Common mistakes

Guided practice

Hands-on lab: A reproducible model artifact

Review questions

Applied challenge

A model trained six months ago is producing different predictions after a platform upgrade, and nobody can say why. Write the reproducibility runbook that would have prevented this: what is recorded at training time, where it is stored, how a rebuild is run, and which tests must pass before an upgraded environment may serve the model.

Lesson summary

A pipeline turns preprocessing, model, calibration, and decision policy into one artifact with one fit and one predict. Enforce an explicit input schema at both ends, drop unknown columns, persist the fitted pipeline with full metadata and an integrity hash, load only trusted artifacts, and record code, data, seeds, and environment so the model can be rebuilt and tested exactly.

Lesson status: Ready for review.

← Previous Next →