TExcelTAD
Home › Deployment & MLOps: Serving, Pipelines, Monitoring › Model Artifacts, Signatures and Metadata

Model Artifacts, Signatures and Metadata

A model file answers one question: "what are the weights?" Production asks many more. Which columns, in which order and with which types, does this model expect? What does it return? Which data was it trained on, with which code and library versions, and how good was it? Is this file the one that was evaluated, or a newer one with the same name? Without answers, a service will happily feed age into the slot that was trained on income, and nobody will notice until the business metrics drop.

The answer is to ship a model as an artifact: a folder (or registry entry) that contains the model file and a machine-readable description of it. This lesson builds one by hand, then shows the same idea in MLflow.

What goes into a model artifact

risk-model / v3 / model filemodel.joblibor model.onnx+ its sha256 signatureinput columnstypes, rangesoutput schema metadataversions, commitdata hashmetrics + split model cardintended uselimits, ownersfairness checks
  • The model file, with its SHA-256 hash (why).
  • The signature: the input schema (column names, order, types, and ideally allowed ranges or categories) and the output schema (a probability between 0 and 1, a label from a known set). It is the model's API contract.
  • Metadata: everything needed to know where the model came from and to rebuild it: library versions, the code version (Git commit), a hash or version of the training data, hyperparameters, and the evaluation metrics with the split and number of rows they were measured on.
  • A model card: the human-readable part, intended use, known limits, owners, fairness and robustness results. The governance lesson covers it.

The signature is checked on every request; the metadata is checked at deployment (versions match the serving image, the hash matches the file) and read during incidents and audits.

From scratch: a signature from the training data

A signature can be inferred from the training frame: names and dtypes, plus the observed ranges as a sanity envelope. Checking a request against it catches the three classic integration bugs: a missing column, columns in the wrong order, and the wrong type.

python · try it yourself
import numpy as np
import pandas as pd
from sklearn.datasets import make_classification

names = ["income", "debt_ratio", "age", "years_employed", "num_accounts",
         "late_payments", "credit_utilisation", "loan_amount"]
X, y = make_classification(n_samples=2000, n_features=8, n_informative=5, random_state=0)
train = pd.DataFrame(X, columns=names)

signature = {
    "inputs": [{"name": c, "type": str(train[c].dtype),
                "min": round(float(train[c].min()), 2), "max": round(float(train[c].max()), 2)} for c in names],
    "output": {"name": "p_default", "type": "float64", "min": 0.0, "max": 1.0},
}

def check(df, sig):
    problems = []
    expected = [col["name"] for col in sig["inputs"]]
    missing = [c for c in expected if c not in df.columns]
    if missing:
        problems.append(f"missing columns {missing}")
    elif list(df.columns) != expected:
        problems.append("columns in a different order (reorder by name before predicting)")
    for col in sig["inputs"]:
        c = col["name"]
        if c in df.columns and str(df[c].dtype) != col["type"]:
            problems.append(f"{c}: type {df[c].dtype}, expected {col['type']}")
    return problems or ["ok"]

print(signature["inputs"][0])
good = train.head(3)
print("training rows:", check(good, signature))
print("reordered:   ", check(good[names[::-1]], signature))
print("missing:     ", check(good.drop(columns="age"), signature))
print("as strings:  ", check(good.astype({"income": str}), signature))
{'name': 'income', 'type': 'float64', 'min': -5.19, 'max': 4.02}
training rows: ['ok']
reordered:    ['columns in a different order (reorder by name before predicting)']
missing:      ["missing columns ['age']"]
as strings:   ['income: type object, expected float64']

All three bugs are caught before the model sees a row. Reordered columns are the most dangerous case, because a model fed a NumPy array would accept them silently and predict garbage. A service should always select columns by name, in the signature's order, never trust the order of the incoming payload.

Pydantic: the signature as executable code

In a Python service, the natural way to write an input schema is a Pydantic model. It validates types, converts compatible values ("42" to 42.0 if allowed), enforces ranges, and produces a JSON Schema that other teams can read or generate clients from. FastAPI uses exactly these models for request validation (next section).

python · try it yourself
import json
from pydantic import BaseModel, Field, ValidationError

class LoanApplication(BaseModel):
    income: float = Field(gt=0, description="monthly income, EUR")
    debt_ratio: float = Field(ge=0, le=5)
    age: int = Field(ge=18, le=100)
    late_payments: int = Field(ge=0)

class RiskPrediction(BaseModel):
    p_default: float = Field(ge=0, le=1)
    model_version: str

ok = LoanApplication(income=3200, debt_ratio=0.4, age=37, late_payments=0)
print(ok)
try:
    LoanApplication(income=-10, debt_ratio=0.4, age=17, late_payments=0)
except ValidationError as e:
    for err in e.errors():
        print("rejected:", err["loc"][0], "-", err["msg"])
schema = LoanApplication.model_json_schema()
print("JSON Schema fields:", json.dumps(schema["properties"]["age"]))
print(RiskPrediction(p_default=0.12, model_version="3").model_dump_json())
income=3200.0 debt_ratio=0.4 age=37 late_payments=0
rejected: income - Input should be greater than 0
rejected: age - Input should be greater than or equal to 18
JSON Schema fields: {"maximum": 100, "minimum": 18, "title": "Age", "type": "integer"}
{"p_default":0.12,"model_version":"3"}

The invalid application is rejected with one message per field (income not greater than 0, age below 18), and the JSON Schema carries the same limits for other teams. The inferred signature and the Pydantic model describe the same contract at two levels: the first in terms of the training data (types, observed ranges), the second in terms of the business domain (an applicant cannot be 17, income must be positive). A service needs both: the domain rules to reject invalid requests, and the data envelope to flag valid but unusual ones (an age of 99 is allowed, but if the training data stopped at 75, predictions for it are an extrapolation, worth logging and monitoring for drift).

Metadata, hashes and the artifact folder

Now the full artifact: train, evaluate on a held-out split, and write the model, signature and metadata next to each other. The training data hash is a SHA-256 over the raw bytes of the training matrix and labels, so a retraining on different data produces a different hash even if the row count is the same.

python · try it yourself
import hashlib, json, os, platform, tempfile
import joblib, numpy as np, sklearn
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score

X, y = make_classification(n_samples=2000, n_features=8, n_informative=5, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0)
model = make_pipeline(StandardScaler(), LogisticRegression(C=1.0)).fit(X_tr, y_tr)

def sha256_bytes(*arrays):
    h = hashlib.sha256()
    for a in arrays:
        h.update(np.ascontiguousarray(a).tobytes())
    return h.hexdigest()

with tempfile.TemporaryDirectory() as d:
    path = os.path.join(d, "risk-model", "v3")
    os.makedirs(path)
    joblib.dump(model, os.path.join(path, "model.joblib"))
    with open(os.path.join(path, "model.joblib"), "rb") as f:
        model_hash = hashlib.sha256(f.read()).hexdigest()
    metadata = {
        "name": "risk-model", "version": "3",
        "framework": {"python": platform.python_version(), "numpy": np.__version__, "scikit-learn": sklearn.__version__},
        "training_data": {"rows": len(X_tr), "sha256": sha256_bytes(X_tr, y_tr)[:16]},
        "hyperparameters": {"C": 1.0, "scaler": "StandardScaler"},
        "metrics": {"split": "random 25 % holdout", "n": len(y_te),
                    "accuracy": round(model.score(X_te, y_te), 3),
                    "roc_auc": round(roc_auc_score(y_te, model.predict_proba(X_te)[:, 1]), 3)},
        "model_sha256": model_hash[:16],
    }
    with open(os.path.join(path, "metadata.json"), "w") as f:
        json.dump(metadata, f, indent=1)
    print(sorted(os.listdir(path)))
    print(json.dumps({k: metadata[k] for k in ("framework", "training_data", "metrics")}, indent=1))
    print("same data -> same hash:", sha256_bytes(X_tr, y_tr) == sha256_bytes(X_tr.copy(), y_tr.copy()))
    print("one row changed -> new hash:", sha256_bytes(X_tr, y_tr) != sha256_bytes(np.r_[X_tr[:-1], X_tr[:1]], y_tr))
['metadata.json', 'model.joblib']
{
 "framework": {
  "python": "3.13.2",
  "numpy": "2.2.5",
  "scikit-learn": "1.7.0"
 },
 "training_data": {
  "rows": 1500,
  "sha256": "5a2a8c0c6396e087"
 },
 "metrics": {
  "split": "random 25 % holdout",
  "n": 500,
  "accuracy": 0.864,
  "roc_auc": 0.928
 }
}
same data -> same hash: True
one row changed -> new hash: True

The folder holds the model and its metadata; the metrics say what they were measured on (accuracy 0.864 and ROC AUC 0.928 on a random holdout of 500 rows), and the data hash is stable for the same data and changes when a single row changes. In practice the code commit comes from git rev-parse HEAD in the training job, and a data version from your data versioning tool (DVC) instead of a hash you compute yourself. The point is the same: every number in metrics has the split and n next to it, and every input that shaped the model has an identifier.

The same idea in MLflow

MLflow packages models in the same way. infer_signature builds a signature from example inputs and outputs, and log_model stores it in an MLmodel file next to the model, together with the Python environment. When the model is later loaded through MLflow's generic pyfunc interface, the signature is enforced: a missing column is an error. Experiment tracking with MLflow is the subject of its own lesson; here only the signature part:

python · try it yourself
import logging
import pandas as pd
import mlflow
from mlflow.models import infer_signature
from sklearn.datasets import make_classification
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
logging.getLogger("mlflow").setLevel(logging.ERROR)

names = ["income", "debt_ratio", "age", "years_employed", "num_accounts",
         "late_payments", "credit_utilisation", "loan_amount"]
X, y = make_classification(n_samples=2000, n_features=8, n_informative=5, random_state=0)
df = pd.DataFrame(X, columns=names)
model = make_pipeline(StandardScaler(), LogisticRegression()).fit(df, y)

signature = infer_signature(df, model.predict_proba(df)[:, 1])
print(signature.inputs.input_names())
print("output:", signature.outputs.to_dict())

mlflow.set_tracking_uri("sqlite:///mlflow.db")
with mlflow.start_run():
    info = mlflow.sklearn.log_model(model, name="model", signature=signature, input_example=df.head(2),
                                    pip_requirements=["scikit-learn==1.7.0"])
loaded = mlflow.pyfunc.load_model(info.model_uri)
print("pyfunc predict (labels) on 2 rows:", [int(p) for p in loaded.predict(df.head(2))])
try:
    loaded.predict(df.head(2).drop(columns="age"))
except Exception as e:
    print(type(e).__name__ + ":", str(e).split("Error: ")[-1])
['income', 'debt_ratio', 'age', 'years_employed', 'num_accounts', 'late_payments', 'credit_utilisation', 'loan_amount']
output: [{'type': 'tensor', 'tensor-spec': {'dtype': 'float64', 'shape': (-1,)}}]
pyfunc predict (labels) on 2 rows: [1, 0]
MlflowException: Model is missing inputs ['age'].

The loaded model checks the columns against the stored signature and refuses the frame without age ("Model is missing inputs ['age']"). One detail to notice: the signature's output was inferred from predict_proba, but the generic pyfunc wrapper of a scikit-learn model calls predict and returns labels ([1, 0]). Infer the output schema from what the served function really returns, or the documented contract and the behaviour disagree.

Pitfalls

  • Positional inputs. A NumPy array has no column names; select columns by name from the signature, every time.
  • Metrics without context. "AUC 0.93" without the split, n and data version cannot be compared with anything.
  • Metadata written by hand. Generate it in the training job from the real objects, or it drifts from the truth.
  • A signature that only checks types. Add domain rules (ranges, allowed categories) and log out-of-envelope values.
  • Several files under one name. model_latest.joblib overwritten by every run; use immutable versions and hashes.

Practice

  1. A client sends the eight features as a JSON list instead of an object with names. What risk does that create, and how does the signature help?
  2. Two runs report "accuracy 0.86" and "accuracy 0.88". Which metadata fields do you need before concluding that the second model is better?
  3. Why store a hash of the training data rather than only the file name of the CSV?
Answers
  1. A list is positional, so any change in order on either side silently swaps features. Require named fields (the Pydantic model), and build the model input by taking the columns in the signature's order.
  2. The split and number of rows (same holdout?), the data version or hash (same data?), and ideally a confidence interval or repeated runs; differences of 0.02 on a few hundred rows can be noise (classification metrics).
  3. A file name says nothing about its content: the file can be regenerated or edited under the same name. A hash identifies the exact bytes, so two models with the same data hash were trained on the same data.

Test yourself

What is a model signature?

  1. A cryptographic signature of the model file
  2. The model's input and output schema: names, types (and ideally ranges) of inputs and outputs
  3. The author's name
  4. The training loss curve

Why is a request with the right columns in a different order dangerous for a model fed NumPy arrays?

  1. It raises an error
  2. The model predicts on swapped features without any error
  3. It is slower
  4. It is not dangerous

Which of these belongs in a model's metadata?

  1. Only the accuracy
  2. Library versions, code commit, training data hash or version, hyperparameters, and metrics with their split and n
  3. The full training dataset
  4. The server's IP address

What does MLflow do with a logged signature when the model is loaded as a pyfunc?

  1. Nothing, it is documentation only
  2. It enforces it: inputs missing a required column are rejected
  3. It retrains the model
  4. It converts the model to ONNX