Kubeflow Pipelines & Experiment Tracking: MLflow to Production Model Registry
Production guide to running containerized ML pipelines on Kubernetes using Kubeflow Pipelines (KFP), tracking metrics with MLflow, and automating model promotion through an enterprise Model Registry.
Kubeflow Pipelines & Experiment Tracking: MLflow to Production Model Registry
Section titled βKubeflow Pipelines & Experiment Tracking: MLflow to Production Model RegistryβIn research environments, data scientists train models locally across disparate Jupyter Notebooks. Without centralized tracking and orchestration, critical operational questions become impossible to answer:
- Which dataset trained the model currently running in production?
- What hyperparameters produced this checkpoint?
- Why did the staging candidate perform better than last weekβs build?
To turn ad-hoc experiments into reliable engineering pipelines, enterprises combine Kubeflow Pipelines (KFP) for containerized DAG workflow execution and MLflow for experiment tracking, metric visualization, and formal Model Registry governance.
1. Declarative Containerized Pipelines with Kubeflow (KFP)
Section titled β1. Declarative Containerized Pipelines with Kubeflow (KFP)βKubeflow Pipelines models an ML workflow as a Directed Acyclic Graph (DAG) of containerized tasks running natively on top of Kubernetes and Argo Workflows. Each step (Data Ingestion β Preprocessing β Training β Evaluation β Model Registration) runs in its own isolated container with dedicated compute and memory requests.
1.1 Python KFP v2 Pipeline Definition
Section titled β1.1 Python KFP v2 Pipeline Definitionβfrom kfp import dslfrom kfp.dsl import Input, Output, Dataset, Model, Metrics
# Step 1: Preprocess Data Component@dsl.component( base_image="python:3.11-slim", packages_to_install=["pandas", "scikit-learn"])def preprocess_data( raw_data_url: str, processed_dataset: Output[Dataset]): import pandas as pd df = pd.read_parquet(raw_data_url) # Perform feature transformations df_clean = df.dropna().reset_index(drop=True) df_clean.to_parquet(processed_dataset.path)
# Step 2: GPU Training Component@dsl.component( base_image="pytorch/pytorch:2.2.0-cuda12.1-cudnn8-runtime", packages_to_install=["mlflow", "scikit-learn"])def train_model( dataset: Input[Dataset], learning_rate: float, trained_model: Output[Model], training_metrics: Output[Metrics]): import mlflow import torch
mlflow.set_tracking_uri("http://mlflow-server.mlops.svc.cluster.local:5000") with mlflow.start_run(run_name="kfp-distributed-step"): mlflow.log_param("lr", learning_rate)
# Simulated training loop loss = 0.042 accuracy = 0.965
mlflow.log_metric("loss", loss) mlflow.log_metric("accuracy", accuracy) training_metrics.log_metric("accuracy", accuracy)
# Save PyTorch model artifact torch.save({"weights": [1, 2, 3]}, trained_model.path) mlflow.log_artifact(trained_model.path, artifact_path="model")
# Step 3: End-to-End Orchestrated Pipeline@dsl.pipeline(name="enterprise-fraud-detection-pipeline")def fraud_detection_pipeline(data_url: str, lr: float = 0.001): prep_step = preprocess_data(raw_data_url=data_url)
train_step = train_model( dataset=prep_step.outputs["processed_dataset"], learning_rate=lr ) # Request dedicated GPU for training step train_step.set_gpu_limit("1") train_step.set_memory_limit("16Gi")2. Centralized Experiment Tracking with MLflow
Section titled β2. Centralized Experiment Tracking with MLflowβWhile Kubeflow orchestrates where and when tasks run, MLflow tracks what happened during every training run.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ MLflow Tracking Server (EKS Pod) ββ ββ ββββββββββββββββββββββββββββ ββββββββββββββββββββββ ββ β Backend Store (Postgres) β β Artifact Store(S3) β ββ β β’ Parameters (lr, batch) β β β’ Model Weights β ββ β β’ Metrics over time β β β’ ONNX graphs β ββ β β’ Git Commit & Tags β β β’ Confusion Matrix β ββ ββββββββββββββββββββββββββββ ββββββββββββββββββββββ βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ2.1 Logging Parameters, Metrics, and Artifacts
Section titled β2.1 Logging Parameters, Metrics, and Artifactsβimport mlflowimport mlflow.sklearnfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.metrics import accuracy_score, f1_score
mlflow.set_experiment("production-churn-prediction")
with mlflow.start_run(run_name="random-forest-v3"): n_estimators = 200 max_depth = 12
# 1. Log Hyperparameters mlflow.log_param("n_estimators", n_estimators) mlflow.log_param("max_depth", max_depth)
clf = RandomForestClassifier(n_estimators=n_estimators, max_depth=max_depth) clf.fit(X_train, y_train)
predictions = clf.predict(X_test) acc = accuracy_score(y_test, predictions) f1 = f1_score(y_test, predictions)
# 2. Log Evaluation Metrics mlflow.log_metric("accuracy", acc) mlflow.log_metric("f1_score", f1)
# 3. Log Model Artifact to S3 mlflow.sklearn.log_model( sk_model=clf, artifact_path="model", registered_model_name="CustomerChurnPredictor" )3. The Production Model Registry: Quality Gates & Promotion
Section titled β3. The Production Model Registry: Quality Gates & PromotionβA raw model file (model.pt or model.pkl) sitting in an S3 bucket is not ready for production. The MLflow Model Registry acts as a centralized store for managing a modelβs full lifecycle through formalized staging gates:
[ Research Runs ] ββ> [ Staging Candidate ] ββ> [ Automated Test Gate ] ββ> [ Production Deployment ] (100s of runs) (Version 4) (Latency & Acc Tests) (KServe)3.1 Automated CI/CD Model Promotion Script
Section titled β3.1 Automated CI/CD Model Promotion Scriptβfrom mlflow.tracking import MlflowClient
client = MlflowClient()model_name = "CustomerChurnPredictor"
# 1. Fetch latest model version registered in Staginglatest_version = client.get_latest_versions(model_name, stages=["Staging"])[0]
# 2. Automated Quality Gate: Assert accuracy meets minimum production SLArun_data = client.get_run(latest_version.run_id)accuracy = run_data.data.metrics["accuracy"]
if accuracy >= 0.95: print(f"PASS: Model v{latest_version.version} meets SLA ({accuracy:.3f}). Promoting to Production.")
# Transition old production model to Archived current_prod = client.get_latest_versions(model_name, stages=["Production"]) for m in current_prod: client.transition_model_version_stage( name=model_name, version=m.version, stage="Archived" )
# Promote new model to Production client.transition_model_version_stage( name=model_name, version=latest_version.version, stage="Production" )else: raise ValueError(f"FAIL: Accuracy {accuracy:.3f} below 0.95 threshold. Rejecting promotion.")4. Key Takeaways for Platform Engineers
Section titled β4. Key Takeaways for Platform Engineersβ- Keep Pipeline Steps Stateless: Every Kubeflow component must write its outputs to object storage (S3) or persistent volumes. Never rely on in-memory handoffs between container steps.
- Back MLflow with Managed Cloud Infrastructure: Run MLflowβs backend store on Amazon RDS PostgreSQL and its artifact store on AWS S3 with bucket lifecycle policies (e.g., transition old training runs to S3 Glacier after 90 days).
- Automate Promotion via Webhooks: Integrate MLflow Model Registry events with ArgoCD or GitHub Actions so that transitioning a model to
Productionautomatically triggers an updated GitOps deployment.