CI/CD y Deploy en AWS
6.12.3kata 3 de 5

Model Validation Gate

Comparar métricas del modelo nuevo vs producción antes de desplegar

El model gate es el paso más importante que diferencia un pipeline de ML de uno de software tradicional. Antes de promover un modelo reentrenado a producción, el pipeline debe comparar sus métricas (accuracy, F1, AUC, RMSE) contra el modelo actualmente en producción. Si el nuevo modelo es estadísticamente peor, el pipeline falla y el modelo no llega a usuarios reales.

La comparación debe ser sobre el mismo conjunto de datos de evaluación (holdout set), no sobre el training set. Un modelo que mejora en training pero empeora en el holdout está sobreajustado. El holdout set debe estar versionado en S3 y ser inmutable: si cambia entre entrenamientos, las comparaciones no son válidas.

Los umbrales de validación deben ser conservadores y justificados. Un threshold de 'el nuevo modelo debe ser al menos igual al actual' es el mínimo. Mejor es 'debe ser al menos 0.5% mejor en F1' para evitar que pequeñas variaciones estadísticas bloqueen despliegues legítimos, y que regresiones menores pasen desapercibidas.

El gate también debe validar la distribución del input data (data drift). Si el modelo nuevo fue entrenado con datos de 2023-2024 pero la distribución de inputs en producción ha cambiado significativamente, sus métricas en el holdout no son representativas del comportamiento real en producción.

structure.txt
# scripts/validate_model.py
import boto3
import json
import argparse
import sys
from sklearn.metrics import f1_score, accuracy_score

def get_current_production_metrics(ssm_client, env='prod') -> dict:
    """Retrieve metrics of the currently deployed model."""
    response = ssm_client.get_parameter(
        Name=f'/ml-pipeline/{env}/current-model-metrics'
    )
    return json.loads(response['Parameter']['Value'])

def evaluate_new_model(model_path: str, holdout_path: str) -> dict:
    """Evaluate new model on the frozen holdout set."""
    import joblib
    import pandas as pd

    model = joblib.load(model_path)
    holdout = pd.read_parquet(holdout_path)
    X, y_true = holdout.drop('label', axis=1), holdout['label']
    y_pred = model.predict(X)

    return {
        'accuracy': accuracy_score(y_true, y_pred),
        'f1': f1_score(y_true, y_pred, average='weighted'),
    }

def validate(new_metrics: dict, prod_metrics: dict, min_improvement: float = 0.0) -> bool:
    """Return True if new model passes the gate."""
    checks = {
        'f1_not_worse': new_metrics['f1'] >= prod_metrics['f1'] - min_improvement,
        'accuracy_not_worse': new_metrics['accuracy'] >= prod_metrics['accuracy'] - min_improvement,
    }
    for check, passed in checks.items():
        status = 'PASS' if passed else 'FAIL'
        print(f'[{status}] {check}: new={new_metrics.get(check.split("_")[0]):.4f} prod={prod_metrics.get(check.split("_")[0]):.4f}')
    return all(checks.values())

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--model-path', required=True)
    parser.add_argument('--holdout-path', required=True)
    parser.add_argument('--min-f1', type=float, default=0.85)
    args = parser.parse_args()

    ssm = boto3.client('ssm')
    prod_metrics = get_current_production_metrics(ssm)
    new_metrics = evaluate_new_model(args.model_path, args.holdout_path)

    if not validate(new_metrics, prod_metrics):
        print('MODEL GATE FAILED: new model is worse than production')
        sys.exit(1)  # non-zero exit fails the pipeline step

    # Store new metrics for next comparison
    ssm.put_parameter(
        Name='/ml-pipeline/staging/current-model-metrics',
        Value=json.dumps(new_metrics),
        Type='String',
        Overwrite=True
    )
    print('MODEL GATE PASSED: deploying new model')

Debugging lab

Detecta y corrige el error en el código.

0/3 tests passing0%
  1. 01

    # Validate model with hardcoded threshold (not comparing to prod) def validate_model(metrics): if metrics['accuracy'] >= 0.85: # static threshold return True return False

  2. 02

    # Gate doesn't fail the pipeline on failure def run_gate(): if not validate_model(): print('Model failed validation') # No sys.exit — pipeline continues!

  3. 03

    # Evaluating on training set (not holdout) def evaluate(model, X_train, y_train): # Wrong: evaluating on data the model was trained on return model.score(X_train, y_train) # always high, meaningless