Vertex AI for ML Pipelines on GCP
What You'll Learn
- 1Decide between AutoML, custom training and BigQuery ML for a given dataset
- 2Configure training splits, budget and machine types so a job costs what you expect
- 3Serve features from the Feature Store with point-in-time correctness
- 4Wire monitoring, explanation and batch prediction into one reproducible pipeline
Where Vertex AI Sits in the Stack
Vertex AI is the managed layer that takes a workflow most teams assemble from scratch, a dataset, a training job, a registry entry, an endpoint and a monitoring hook, and gives each step a first class object with an API. That matters for a data engineer because the hand offs become automatable: a Dataflow job publishes features, a pipeline component trains on them, the resulting model registers itself with lineage back to the exact table and query that produced the training set, and deployment becomes a parameter rather than a runbook. The platform deliberately does not force one framework, so the same registry holds an AutoML tabular model, a PyTorch container you built, and a foundation model tuned for your domain, and the endpoint abstraction lets traffic move between them.
The boundary with BigQuery ML is worth stating before any code. Structured data sitting in BigQuery with a SQL friendly problem belongs there, because training is a query and there is nothing to operate. Vertex AI earns its place when training needs a custom loop or a GPU, when inference needs an autoscaling endpoint with traffic splitting, when features must be shared across models, or when several teams need one reproducible pipeline instead of a set of scripts.
Vertex AI Architecture
Vertex AI is Google Cloud's unified AI/ML platform that provides end-to-end tools for building, deploying, and managing ML models. The five objects underneath it form a chain of custody for every model: a dataset with a source, a training job with a configuration, a registry entry with versions, an endpoint with replicas, and a monitoring configuration with thresholds. Losing that chain is what makes model bugs hard to fix, because nobody can answer which data produced the version now serving traffic.
Core Components
Data Layer:
- BigQuery for structured data
- Cloud Storage for unstructured data
- Data labeling services
- Data versioning and lineage
Feature Store:
- Centralized feature repository
- Online and offline serving
- Feature versioning and monitoring
- Point-in-time correctness
Training:
- AutoML for automated model training
- Custom training with your own code
- Distributed training support
- Hyperparameter tuning
Model Registry:
- Model versioning and metadata
- Model lineage tracking
- A/B testing support
- Model approval workflows
Prediction:
- Online prediction endpoints
- Batch prediction jobs
- Auto-scaling and monitoring
- Explainable AI
AutoML
AutoML enables automated model training with minimal code, and it earns its price when the label exists but nobody has time to engineer features. The service tries a set of model families, tunes them against a held out split, and reports the winner with its metrics, which usually lands within a couple of points of a hand tuned gradient boosted model on wide tabular data. The budget is expressed in milli node hours: one thousand of them is a single node hour, and a tabular job often finishes at that level because early stopping cuts the search short. The split fractions are not cosmetic either, because a random split on a time ordered dataset leaks the future into training, and AutoML will happily report a score you cannot reproduce in production.
The choice inside AutoML is between the standard training job and the quick deploy path, which trains a narrower model for far less time when the data is small or the deadline is tight. Whatever you choose, record the dataset version alongside the model: an AutoML model trained on a table that has since been overwritten cannot be retrained identically, which is the first thing anyone asks when a metric drifts.
Creating AutoML Models
from google.cloud import aiplatform
# Initialize Vertex AI
aiplatform.init(
project='my-project',
location='us-central1',
staging_bucket='gs://my-staging-bucket'
)
# Create Tabular Dataset
dataset = aiplatform.TabularDataset.create(
display_name='sales-prediction',
bq_source='bq://my-project.analytics.sales_data'
)
# Train AutoML model
model = aiplatform.AutoMLTabularTrainingJob(
display_name='sales-prediction-model',
optimization_prediction_type='regression',
optimization_objective='minimize-rmse',
).run(
dataset=dataset,
target_column='amount',
training_fraction_split=0.8,
validation_fraction_split=0.1,
test_fraction_split=0.1,
budget_milli_node_hours=1000,
model_display_name='sales-prediction-v1',
disable_early_stopping=False,
)
AutoML Configuration
# AutoML training configuration
training_config = {
'display_name': 'sales-prediction-model',
'dataset_id': 'sales-dataset',
'target_column': 'amount',
'training_fraction_split': 0.8,
'validation_fraction_split': 0.1,
'test_fraction_split': 0.1,
'budget_milli_node_hours': 1000,
'model_display_name': 'sales-prediction-v1',
'optimization_prediction_type': 'regression',
'optimization_objective': 'minimize-rmse',
'early_stopping': True,
'additional_experiments': ['QUICK_DEPLOY'],
}
# Create and run training job
job = aiplatform.AutoMLTabularTrainingJob(
display_name=training_config['display_name'],
optimization_prediction_type=training_config['optimization_prediction_type'],
optimization_objective=training_config['optimization_objective'],
)
model = job.run(
dataset=aiplatform.TabularDataset(training_config['dataset_id']),
target_column=training_config['target_column'],
training_fraction_split=training_config['training_fraction_split'],
validation_fraction_split=training_config['validation_fraction_split'],
test_fraction_split=training_config['test_fraction_split'],
budget_milli_node_hours=training_config['budget_milli_node_hours'],
model_display_name=training_config['model_display_name'],
)
Custom Training
Custom training runs your script on managed infrastructure, which is the right choice when the model architecture, loss function or feature pipeline is part of the product. Four decisions dominate the cost and the outcome. The container decides the framework and its version, so pin it rather than floating on latest. The machine type decides memory and CPU per replica, and a job that swaps memory will crawl regardless of how many nodes you add. The replica count decides whether training is distributed, with one replica for most tabular work and several for image or text workloads. And the arguments array is how configuration stays out of the code, which is what makes the same job runnable against a staging dataset.
Pick the training approach from the constraint rather than from preference, because the four options differ in what they cost and what they let you change.
| Approach | You supply | Cost basis | Best when |
|---|---|---|---|
| BigQuery ML | A SQL query | Bytes processed and storage | Structured data already in BigQuery |
| AutoML tabular | A labelled table and a budget | Milli node hours of training | Fast baseline, no feature engineering time |
| Custom training | Script, container and machine type | Node hours while the job runs | Custom architecture or heavy preprocessing |
| Pretrained or foundation model | Prompt or fine tuning data | Per token or per node hour | Text, image and multimodal problems |
Custom Training Job
from google.cloud import aiplatform
# Define training script
training_script = """
import argparse
import tensorflow as tf
from tensorflow import keras
def train_model(args):
# Load data
train_data = tf.data.experimental.make_csv_dataset(
args.train_data,
batch_size=args.batch_size,
label_name='amount'
)
# Build model
model = keras.Sequential([
keras.layers.Dense(64, activation='relu'),
keras.layers.Dense(32, activation='relu'),
keras.layers.Dense(1)
])
model.compile(
optimizer='adam',
loss='mse',
metrics=['mae']
)
# Train model
model.fit(
train_data,
epochs=args.epochs,
validation_split=0.2
)
# Save model
model.save(args.model_dir)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--train-data', type=str, required=True)
parser.add_argument('--model-dir', type=str, required=True)
parser.add_argument('--batch-size', type=int, default=32)
parser.add_argument('--epochs', type=int, default=10)
args = parser.parse_args()
train_model(args)
"""
# Create custom training job
job = aiplatform.CustomTrainingJob(
display_name='custom-sales-model',
script_path='train.py',
container_uri='us-docker.pkg.dev/vertex-ai/training/tf-gpu.2-12:latest',
requirements=['tensorflow>=2.12'],
model_serving_container_image_uri='us-docker.pkg.dev/vertex-ai/prediction/tf2-cpu.2-12:latest',
)
# Run training job
model = job.run(
replica_count=1,
machine_type='n1-standard-8',
accelerator_type='NVIDIA_TESLA_T4',
accelerator_count=1,
args=['--train-data', 'gs://my-bucket/train.csv', '--model-dir', 'gs://my-bucket/model'],
)
Custom Container Training
# Dockerfile for custom training
FROM us-docker.pkg.dev/vertex-ai/training/tf-gpu.2-12:latest
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY train.py .
COPY config.yaml .
ENTRYPOINT ["python", "train.py"]
# config.yaml
training:
batch_size: 64
epochs: 20
learning_rate: 0.001
validation_split: 0.2
model:
architecture: "resnet50"
pretrained: true
fine_tune_layers: 10
Feature Store
The Feature Store solves two problems that appear as soon as a second model exists: recomputing the same aggregates for every job, and training on values that the serving path cannot reproduce. It keeps an offline store in BigQuery for training reads and an online store in memory for low latency serving, and both are populated from one definition, so the number a model trains on and the number it scores with come from the same code. The critical guarantee is point in time correctness: a training read asks for feature values as they were at a specific timestamp, rather than as they are today, which removes the leakage where future behaviour sneaks into the training set.
Serving is then a lookup rather than a join. An online read returns the current values for a list of entity ids in single digit milliseconds, and a batch serve materialises a table for offline scoring, which is how a nightly job scores a million customers without issuing a million point lookups. Sync to the online store is a separate explicit step, so a feature that has been written offline but not synced will simply be missing at serving time rather than silently stale.
Creating Feature Store
from google.cloud import aiplatform
# Create Feature Store
featurestore = aiplatform.Featurestore.create(
featurestore_id='sales_features',
online_store_fixed_node_count=3,
)
# Create Feature Group
feature_group = featurestore.create_feature_group(
feature_group_id='customer_features',
source=aiplatform.featurestore.FeatureGroupSource(
bigquery_source=aiplatform.featurestore.FeatureGroupSource.BigQuerySource(
input_uri='bq://my-project.analytics.customer_features'
)
),
)
# Create Features
feature_group.create_feature(
feature_id='customer_lifetime_value',
value_type='DOUBLE',
)
feature_group.create_feature(
feature_id='purchase_frequency',
value_type='DOUBLE',
)
# Ingest features
feature_group.ingest_from_bq(
feature_ids=['customer_lifetime_value', 'purchase_frequency'],
feature_time='feature_timestamp',
bq_source_uri='bq://my-project.analytics.customer_features',
)
Feature Serving
# Online feature serving
featurestore = aiplatform.Featurestore('sales_features')
# Get feature values
feature_values = featurestore.read(
entity_type_ids='customers',
feature_ids=['customer_lifetime_value', 'purchase_frequency'],
entity_ids=['customer_123', 'customer_456'],
)
# Batch feature serving
batch_features = featurestore.batch_serve(
entity_type_ids='customers',
feature_ids=['customer_lifetime_value', 'purchase_frequency'],
serving_feature_timestamp=aiplatform.featurestore.FeatureTimestamp(
feature_time='feature_timestamp'
),
)
ML Pipelines
ML Pipelines orchestrate the end-to-end ML workflow as a compiled graph of components, which turns a model retrain from a sequence of manual steps into a single idempotent job. A pipeline is written with the Kubeflow Pipelines domain specific language, compiled to a JSON or YAML package, and submitted as a pipeline job whose every run records the parameters, the outputs and the lineage. That record is what lets you answer which dataset produced the model now in production, and it is also what makes a retrain reproducible when the person who wrote it has moved on.
Two practical rules keep pipelines maintainable. Components should take data references such as BigQuery tables or bucket paths rather than embedding credentials or environment assumptions, so the same graph runs in staging and production with different parameters. And every step that trains should declare its output as a model artifact, because the deployment step downstream needs a typed hand off rather than a path someone copied from a log.
Creating ML Pipelines
from kfp import dsl
from google_cloud_pipeline_components.v1 import (
BigQueryDatasetCreateOp,
TabularTrainingJobPredictHyperparameterTuningOp,
ModelDeployOp,
)
@dsl.pipeline(
name='sales-prediction-pipeline',
description='End-to-end sales prediction pipeline',
)
def sales_prediction_pipeline(
project_id: str,
region: str,
dataset_id: str,
bq_source: str,
target_column: str,
):
# Create BigQuery Dataset
create_dataset = BigQueryDatasetCreateOp(
project=project_id,
dataset_id=dataset_id,
location='US',
)
# Train model with hyperparameter tuning
training_op = TabularTrainingJobPredictHyperparameterTuningOp(
project=project_id,
location=region,
display_name='sales-prediction-training',
dataset=create_dataset.outputs['dataset'],
target_column=target_column,
prediction_type='regression',
optimization_objective='minimize-rmse',
hyperparameter_ranges={
'learning_rate': dsl.V2HyperparameterRange(min_value=0.001, max_value=0.1),
'num_layers': dsl.V2HyperparameterRange(min_value=2, max_value=5),
},
max_trial_count=10,
parallel_trial_count=2,
search_algorithm='RANDOM',
)
# Deploy model to endpoint
deploy_op = ModelDeployOp(
model=training_op.outputs['model'],
endpoint=endpoint,
deployed_model_display_name='sales-prediction-deployed',
machine_type='n1-standard-4',
min_replica_count=1,
max_replica_count=3,
)
# Compile pipeline
from kfp import compiler
compiler.Compiler().compile(
pipeline_func=sales_prediction_pipeline,
package_path='sales_prediction_pipeline.json',
)
Running ML Pipelines
from google.cloud import aiplatform
# Initialize Vertex AI
aiplatform.init(
project='my-project',
location='us-central1',
staging_bucket='gs://my-staging-bucket'
)
# Create pipeline job
job = aiplatform.PipelineJob(
display_name='sales-prediction-run',
template_path='sales_prediction_pipeline.json',
pipeline_root='gs://my-pipeline-root',
parameter_values={
'project_id': 'my-project',
'region': 'us-central1',
'dataset_id': 'sales_dataset',
'bq_source': 'bq://my-project.analytics.sales_data',
'target_column': 'amount',
},
)
# Run pipeline
job.submit()
# Wait for completion
job.wait()
# Check results
print(f'Pipeline state: {job.state}')
print(f'Pipeline resource name: {job.resource_name}')
Model Monitoring
Model monitoring watches for the two ways a deployed model stops being true. Training skew is the gap between the distribution the model learned and the distribution it is being asked to score, which appears when a preprocessing step changes or a new source of data joins the feed. Prediction drift is the gap between yesterday's predictions and today's, which appears when the world moves even though the inputs look plausible. Both are measured per feature with a threshold, and both are computed on a sample of live traffic so the check itself does not cost more than the endpoint.
The configuration decides the alerting, and the interval is a trade-off: hourly monitoring catches a bad release within a working day at almost no cost, while minute level monitoring suits a high stakes financial model but generates the volume that trains people to ignore alerts. Pair every drift alert with a owner and a runbook, because a threshold breach with no responder is telemetry rather than a control. Where the label eventually arrives, such as a churn outcome weeks later, ground truth comparison is a separate check and is the only one that can tell you the model's accuracy actually fell rather than merely its inputs moving.
Setting Up Monitoring
from google.cloud import aiplatform
# Deploy model with monitoring
endpoint = model.deploy(
deployed_model_display_name='sales-prediction-deployed',
machine_type='n1-standard-4',
min_replica_count=1,
max_replica_count=3,
monitoring_config=aiplatform.ModelDeploymentMonitoringConfig(
trigger_config=aiplatform.ModelDeploymentMonitoringTriggerConfig(
monitoring_interval_seconds=3600,
monitoring_alert_config=aiplatform.ModelDeploymentMonitoringAlertConfig(
email_alert_config=aiplatform.ModelDeploymentMonitoringAlertConfig.EmailAlertConfig(
user_emails=['[email protected]']
)
),
),
data_sampling_config=aiplatform.ModelDeploymentMonitoringConfig.DataSamplingConfig(
training_dataset=aiplatform.ModelDeploymentMonitoringConfig.DataSamplingConfig.TrainingDataset(
bq_source='bq://my-project.analytics.training_data'
),
training_prediction_skew_detection_config=aiplatform.ModelDeploymentMonitoringConfig.DataSamplingConfig.TrainingPredictionSkewDetectionConfig(
skew_thresholds={
'feature_1': 0.3,
'feature_2': 0.3,
}
),
prediction_drift_detection_config=aiplatform.ModelDeploymentMonitoringConfig.DataSamplingConfig.PredictionDriftDetectionConfig(
drift_thresholds={
'feature_1': 0.3,
'feature_2': 0.3,
}
),
),
),
)
Monitoring Metrics
# Monitor model metrics
from google.cloud import monitoring_v3
import time
def monitor_model_performance(project_id, endpoint_id):
"""Monitor model performance metrics."""
client = monitoring_v3.MetricServiceClient()
project_name = f"projects/{project_id}"
# Monitor prediction latency
interval = monitoring_v3.TimeInterval()
interval.end_time = time.time()
interval.start_time = time.time() - 3600
results = client.list_time_series(
request={
'name': project_name,
'filter': f'resource.label.endpoint_id = "{endpoint_id}" AND metric.type = "aiplatform.googleapis.com/prediction/latency"',
'interval': interval,
'view': monitoring_v3.ListTimeSeriesRequest.TimeSeriesView.FULL
}
)
for result in results:
print(f'Average latency: {result.points[0].value.double_value}ms')
Explainable AI
Explanation turns a score into a reason, which is what a compliance reviewer or a support agent needs. Feature attribution assigns each input a signed contribution relative to the model's average output, so the attributions for one prediction sum to the difference between that prediction and the baseline. Attributions are model specific: gradient based methods suit neural networks, while tree and tabular models use approaches that do not require gradients, and the explanation you expose must therefore be generated by the same serving path rather than recomputed in a notebook.
Two cautions apply. Explanations describe what the model used, not what is true in the world, so a feature that dominates an attribution may simply be a proxy for something you meant to exclude. And explaining every request adds latency, so many teams explain a sample and store the result with the prediction, which satisfies an audit question without taxing every call.
Getting Explanations
from google.cloud import aiplatform
# Deploy model with explanations
endpoint = model.deploy(
deployed_model_display_name='sales-prediction-explainable',
machine_type='n1-standard-4',
min_replica_count=1,
max_replica_count=3,
explain_config=aiplatform.ExplainConfig(
featured_attributions=aiplatform.ExplainConfig.FeatureAttribution(
top_k_features=10,
),
),
)
# Get prediction with explanation
instances = [
{'feature_1': 1.0, 'feature_2': 2.0, 'feature_3': 3.0}
]
predictions = endpoint.predict(
instances=instances,
parameters={'excluded_features': ['feature_4']},
)
# Access explanations
for prediction in predictions.predictions:
explanation = prediction.explanation
print(f'Attribution scores: {explanation.feature_attributions}')
Batch Prediction
Batch prediction is the path for anything that does not need an answer within a second: scoring a million rows overnight, refreshing a propensity table, or generating embeddings for a catalogue. The job reads from BigQuery or Cloud Storage, scales replicas up while the work exists and back down when it ends, and writes results to the same system it read from, so the output lands where the next pipeline already looks. That closed loop is why batch prediction composes so well with Dataflow and BigQuery jobs: no service is left holding state between runs.
Choose batch over an endpoint whenever the consumer is a table rather than a user, because you pay only while the job runs and you gain a durable, re-readable output instead of a call that must be repeated. Endpoint serving still has a place for interactive features, and the two can coexist on one model version, which is how a nightly batch refresh and a real time lookalike score stay consistent with each other.
Running Batch Prediction
from google.cloud import aiplatform
# Create batch prediction job
job = aiplatform.BatchPredictionJob.create(
display_name='sales-prediction-batch',
model_name=model.resource_name,
instances_format='bigquery',
predictions_format='bigquery',
input_config=aiplatform.BatchPredictionJob.InputConfig(
bigquery_source=aiplatform.BatchPredictionJob.InputConfig.BigQuerySource(
input_uri='bq://my-project.analytics.batch_input'
)
),
output_config=aiplatform.BatchPredictionJob.OutputConfig(
bigquery_destination_prefix='bq://my-project.analytics.batch_output'
),
model_parameters={'confidence_threshold': 0.5},
machine_type='n1-standard-4',
starting_replica_count=1,
max_replica_count=5,
)
# Wait for completion
job.wait()
# Check results
print(f'Job state: {job.state}')
print(f'Output location: {job.output_info.bigquery_output_table}')
Best Practices
The list below is the short version of a longer argument: treat a model like a deployed service with a version history, a health check and an owner. Feature Store centralises the definitions so training and serving agree, pipelines make the retrain repeatable, monitoring supplies the health check, and explanations and versioning supply the answers an incident review will ask for. Cost follows the same discipline, because an endpoint left at three replicas overnight or a training job on a GPU class machine it never uses is money with no reviewer attached.
- Use Feature Store - Centralize feature management
- Implement ML Pipelines - Automate end-to-end workflows
- Enable Model Monitoring - Detect drift and performance issues
- Use Explainable AI - Understand model predictions
- Optimize costs - Use appropriate machine types and auto-scaling
- Version models - Track model lineage and versions
- Implement A/B testing - Compare model performance
Common Mistakes
Training on today's values of a feature that only exists in the future
Fix: Read from the Feature Store with point in time correctness, using the entity timestamp rather than the current snapshot.
Deploying a model with no monitoring configuration
Fix: Attach skew and drift thresholds at deploy time with an owner and a runbook, or the first sign of failure will be a business metric.
Leaving endpoint replicas and GPU machines at their peak setting
Fix: Set minimum replicas to zero or one where latency allows and scale on traffic, since idle prediction capacity is the largest avoidable line item.
Key Takeaways
- BigQuery ML handles SQL friendly tabular problems, while Vertex AI earns its cost when training needs a custom loop, a GPU or a managed endpoint
- Feature Store keeps one definition for offline training reads and online serving lookups, and its point in time correctness prevents label leakage
- Pipelines compile the retrain into a reproducible graph whose run records parameters, outputs and lineage back to the source data
- Monitoring splits into training skew and prediction drift, and batch prediction composes with BigQuery and Dataflow when the consumer is a table
Interview Questions
Q1: When does AutoML beat a hand written model?
When the label exists, the deadline is tight and nobody has time to engineer features: AutoML usually lands within a couple of points of a tuned boosted tree on wide tabular data for a fixed milli node hour budget.
Q2: What problem does point-in-time correctness solve?
It stops future information leaking into training by returning feature values as they were at the entity timestamp, instead of the current snapshot that may already reflect the outcome being predicted.
Q3: Skew or drift: which alert fired?
Skew means live inputs differ from the training distribution, usually a preprocessing or source change; drift means predictions moved over time. Skew points at your pipeline, drift points at the world.
Q4: Batch prediction or an online endpoint?
Batch when the consumer is a table and minutes of latency are fine, because cost stops when the job ends and the output is durable; endpoint when a user or a feature store lookup needs the answer immediately.