Join the SIG TFX-Addons community and help make TFX even better!

Better ML Engineering with ML Metadata

View on Run in Google Colab View source on GitHub

Assume a scenario where you set up a production ML pipeline to classify penguins. The pipeline ingests your training data, trains and evaluates a model, and pushes it to production.

However, when you later try using this model with a larger dataset that contains different kinds of penguins, you observe that your model does not behave as expected and starts classifying the species incorrectly.

At this point, you are interested in knowing:

  • What is the most efficient way to debug the model when the only available artifact is the model in production?
  • Which training dataset was used to train the model?
  • Which training run led to this erroneous model?
  • Where are the model evaluation results?
  • Where to begin debugging?

ML Metadata (MLMD) is a library that leverages the metadata associated with ML models to help you answer these questions and more. A helpful analogy is to think of this metadata as the equivalent of logging in software development. MLMD enables you to reliably track the artifacts and lineage associated with the various components of your ML pipeline.

In this tutorial, you set up a TFX Pipeline to create a model that classifies penguins into three species based on the body mass and the length and depth of their culmens, and the length of their flippers. You then use MLMD to track the lineage of pipeline components.

TFX Pipelines in Colab

Colab is a lightweight development environment which differs significantly from a production environment. In production, you may have various pipeline components like data ingestion, transformation, model training, run histories, etc. across multiple, distributed systems. For this tutorial, you should be aware that siginificant differences exist in Orchestration and Metadata storage - it is all handled locally within Colab. Learn more about TFX in Colab here.


First, we install and import the necessary packages, set up paths, and download data.

Upgrade Pip

To avoid upgrading Pip in a system when running locally, check to make sure that we're running in Colab. Local systems can of course be upgraded separately.

  import colab
  !pip install --upgrade pip

Install and import TFX

pip install -q -U --use-feature=2020-resolver tfx

You must restart the Colab runtime after installing TFX. Select Runtime > Restart runtime from the Colab menu. This is because of the way that Colab loads packages.

Do not proceed with the rest of this tutorial without first restarting the runtime.

Import other libraries

import os
import tempfile
import urllib
import pandas as pd

Import TFX component classes.

from tfx.components.evaluator.component import Evaluator
from tfx.components.example_gen.csv_example_gen.component import CsvExampleGen
from tfx.components.pusher.component import Pusher
from tfx.components.schema_gen.component import SchemaGen
from tfx.components.statistics_gen.component import StatisticsGen
from tfx.components.trainer.component import Trainer
from tfx.components.base import executor_spec
from tfx.components.trainer.executor import GenericExecutor
from tfx.orchestration.experimental.interactive.interactive_context import InteractiveContext
from tfx.proto import evaluator_pb2
from tfx.proto import pusher_pb2
from tfx.proto import trainer_pb2
from tfx.utils.dsl_utils import external_input

from tensorflow_metadata.proto.v0 import anomalies_pb2
from tensorflow_metadata.proto.v0 import schema_pb2
from tensorflow_metadata.proto.v0 import statistics_pb2

import tensorflow_model_analysis as tfma

from tfx.components import ResolverNode
from tfx.dsl.experimental import latest_blessed_model_resolver
from tfx.types import Channel
from tfx.types.standard_artifacts import Model
from tfx.types.standard_artifacts import ModelBlessing

Import the MLMD library.

import ml_metadata as mlmd
from ml_metadata.proto import metadata_store_pb2

Download the dataset

In this colab, we use the Palmer Penguins dataset which can be found on Github. We processed the dataset by leaving out any incomplete records, and drops island and sex columns, and converted labels to int32. The dataset contains 334 records of the body mass and the length and depth of penguins' culmens, and the length of their flippers. You use this data to classify penguins into one of three species.

_data_root = tempfile.mkdtemp(prefix='tfx-data')
_data_filepath = os.path.join(_data_root, "penguins_processed.csv")
urllib.request.urlretrieve(DATA_PATH, _data_filepath)
 <http.client.HTTPMessage at 0x7fe4eef4c160>)

Create an InteractiveContext

To run TFX components interactively in this notebook, create an InteractiveContext. The InteractiveContext uses a temporary directory with an ephemeral MLMD database instance. Note that calls to InteractiveContext are no-ops outside the Colab environment.

In general, it is a good practice to group similar pipeline runs under a Context.

interactive_context = InteractiveContext()
WARNING:absl:InteractiveContext pipeline_root argument not provided: using temporary directory /tmp/tfx-interactive-2021-02-11T13_16_43.521464-6hj93f0i as root for pipeline outputs.
WARNING:absl:InteractiveContext metadata_connection_config not provided: using SQLite ML Metadata database at /tmp/tfx-interactive-2021-02-11T13_16_43.521464-6hj93f0i/metadata.sqlite.

Construct the TFX Pipeline

A TFX pipeline consists of several components that perform different aspects of the ML workflow. In this notebook, you create and run the ExampleGen, StatisticsGen, SchemaGen, and Trainer components and use the Evaluator and Pusher component to evaluate and push the trained model.

Refer to the components tutorial for more information on TFX pipeline components.

Instantiate and run the ExampleGen Component

input_data = external_input(_data_root)
example_gen = CsvExampleGen(input=input_data)
WARNING:absl:From <ipython-input-1-e4ef519b0b92>:1: external_input (from tfx.utils.dsl_utils) is deprecated and will be removed in a future version.
Instructions for updating:
external_input is deprecated, directly pass the uri to ExampleGen.
WARNING:absl:The "input" argument to the CsvExampleGen component has been deprecated by "input_base". Please update your usage as support for this argument will be removed soon.
WARNING:apache_beam.runners.interactive.interactive_environment:Dependencies required for Interactive Beam PCollection visualization are not available, please use: `pip install apache-beam[interactive]` to install necessary dependencies to enable all data visualization features.'t find python-snappy so the implementation of _TFRecordUtil._masked_crc32c is not as fast as it could be.

Instantiate and run the StatisticsGen Component

statistics_gen = StatisticsGen(examples=example_gen.outputs['examples'])

Instantiate and run the SchemaGen Component

infer_schema = SchemaGen(
    statistics=statistics_gen.outputs['statistics'], infer_feature_shape=True)
WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow_data_validation/utils/ tf_record_iterator (from is deprecated and will be removed in a future version.
Instructions for updating:
Use eager execution and: 
WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow_data_validation/utils/ tf_record_iterator (from is deprecated and will be removed in a future version.
Instructions for updating:
Use eager execution and: 

Instantiate and run the Trainer Component

# Define the module file for the Trainer component
trainer_module_file = ''
%%writefile {trainer_module_file}

# Define the training algorithm for the Trainer module file
import os
from typing import List, Text

import tensorflow as tf
from tensorflow import keras

from tfx.components.trainer.executor import TrainerFnArgs
from tfx.components.trainer.fn_args_utils import FnArgs

# Features used for classification - culmen length and depth, flipper length,
# body mass, and species.

    'culmen_length_mm':[], dtype=tf.float32),
    'culmen_depth_mm':[], dtype=tf.float32),
    'flipper_length_mm':[], dtype=tf.float32),
    'body_mass_g':[], dtype=tf.float32),
    'species':[], dtype=tf.int64)

_LABEL_KEY = 'species'

    'culmen_length_mm', 'culmen_depth_mm', 'flipper_length_mm', 'body_mass_g'

def _gzip_reader_fn(filenames):
  return, compression_type='GZIP')

def _input_fn(file_pattern: List[Text], batch_size: int = 200):
  dataset =

  return dataset

def _build_keras_model():
  inputs = [keras.layers.Input(shape=(1,), name=f) for f in _FEATURE_KEYS]
  d = keras.layers.concatenate(inputs)
  d = keras.layers.Dense(8, activation='relu')(d)
  d = keras.layers.Dense(8, activation='relu')(d)
  outputs = keras.layers.Dense(3, activation='softmax')(d)
  model = keras.Model(inputs=inputs, outputs=outputs)
  return model

def run_fn(fn_args: TrainerFnArgs):
  train_dataset = _input_fn(fn_args.train_files, batch_size=10)
  eval_dataset = _input_fn(fn_args.eval_files, batch_size=10)
  model = _build_keras_model()
      epochs=int(fn_args.train_steps / 20),
      validation_steps=fn_args.eval_steps), save_format='tf')

Run the Trainer component.

trainer = Trainer(
WARNING:absl:From <ipython-input-1-d2af3312f9a2>:3: The name tfx.components.base.executor_spec.ExecutorClassSpec is deprecated. Please use tfx.dsl.components.base.executor_spec.ExecutorClassSpec instead.
Epoch 1/5
20/20 [==============================] - 1s 33ms/step - loss: 1.0484 - sparse_categorical_accuracy: 0.4277 - val_loss: 1.0130 - val_sparse_categorical_accuracy: 0.4700
Epoch 2/5
20/20 [==============================] - 0s 8ms/step - loss: 1.0075 - sparse_categorical_accuracy: 0.4838 - val_loss: 0.9657 - val_sparse_categorical_accuracy: 0.6900
Epoch 3/5
20/20 [==============================] - 0s 8ms/step - loss: 0.9473 - sparse_categorical_accuracy: 0.7441 - val_loss: 0.9347 - val_sparse_categorical_accuracy: 0.7700
Epoch 4/5
20/20 [==============================] - 0s 8ms/step - loss: 0.8869 - sparse_categorical_accuracy: 0.8405 - val_loss: 0.9047 - val_sparse_categorical_accuracy: 0.7700
Epoch 5/5
20/20 [==============================] - 0s 8ms/step - loss: 0.8597 - sparse_categorical_accuracy: 0.8060 - val_loss: 0.8736 - val_sparse_categorical_accuracy: 0.7700
INFO:tensorflow:Assets written to: /tmp/tfx-interactive-2021-02-11T13_16_43.521464-6hj93f0i/Trainer/model/4/serving_model_dir/assets
INFO:tensorflow:Assets written to: /tmp/tfx-interactive-2021-02-11T13_16_43.521464-6hj93f0i/Trainer/model/4/serving_model_dir/assets

Evaluate and push the model

Use the Evaluator component to evaluate and 'bless' the model before using the Pusher component to push the model to a serving directory.

_serving_model_dir = os.path.join(tempfile.mkdtemp(),
eval_config = tfma.EvalConfig(
        tfma.ModelSpec(label_key='species', signature_name='serving_default')
                        lower_bound={'value': 0.6})))
evaluator = Evaluator(
pusher = Pusher(

Running the TFX pipeline populates the MLMD Database. In the next section, you use the MLMD API to query this database for metadata information.

Query the MLMD Database

The MLMD database stores three types of metadata:

  • Metadata about the pipeline and lineage information associated with the pipeline components
  • Metadata about artifacts that were generated during the pipeline run
  • Metadata about the executions of the pipeline

A typical production environment pipeline serves multiple models as new data arrives. When you encounter erroneous results in served models, you can query the MLMD database to isolate the erroneous models. You can then trace the lineage of the pipeline components that correspond to these models to debug your models

Set up the metadata (MD) store with the InteractiveContext defined previously to query the MLMD database.

connection_config = interactive_context.metadata_connection_config
store = mlmd.MetadataStore(connection_config)

# All TFX artifacts are stored in the base directory
base_dir = connection_config.sqlite.filename_uri.split('metadata.sqlite')[0]

Create some helper functions to view the data from the MD store.

def display_types(types):
  # Helper function to render dataframes for the artifact and execution types
  table = {'id': [], 'name': []}
  for a_type in types:
  return pd.DataFrame(data=table)
def display_artifacts(store, artifacts):
  # Helper function to render dataframes for the input artifacts
  table = {'artifact id': [], 'type': [], 'uri': []}
  for a in artifacts:
    table['artifact id'].append(
    artifact_type = store.get_artifact_types_by_id([a.type_id])[0]
    table['uri'].append(a.uri.replace(base_dir, './'))
  return pd.DataFrame(data=table)
def display_properties(store, node):
  # Helper function to render dataframes for artifact and execution properties
  table = {'property': [], 'value': []}
  for k, v in
        v.string_value if v.HasField('string_value') else v.int_value)
  for k, v in node.custom_properties.items():
        v.string_value if v.HasField('string_value') else v.int_value)
  return pd.DataFrame(data=table)

First, query the MD store for a list of all its stored ArtifactTypes.


Next, query all PushedModel artifacts.

pushed_models = store.get_artifacts_by_type("PushedModel")
display_artifacts(store, pushed_models)

Query the MD store for the latest pushed model. This tutorial has only one pushed model.

pushed_model = pushed_models[-1]
display_properties(store, pushed_model)

One of the first steps in debugging a pushed model is to look at which trained model is pushed and to see which training data is used to train that model.

MLMD provides traversal APIs to walk through the provenance graph, which you can use to analyze the model provenance.

def get_one_hop_parent_artifacts(store, artifacts):
  # Get a list of artifacts within a 1-hop of the artifacts of interest
  artifact_ids = [ for artifact in artifacts]
  executions_ids = set(
      for event in store.get_events_by_artifact_ids(artifact_ids)
      if event.type == metadata_store_pb2.Event.OUTPUT)
  artifacts_ids = set(
      for event in store.get_events_by_execution_ids(executions_ids)
      if event.type == metadata_store_pb2.Event.INPUT) 
  return [artifact for artifact in store.get_artifacts_by_id(artifacts_ids)]

Query the parent artifacts for the pushed model.

parent_artifacts = get_one_hop_parent_artifacts(store, [pushed_model])
display_artifacts(store, parent_artifacts)

Query the properties for the model.

exported_model = parent_artifacts[0]
display_properties(store, exported_model)

Query the upstream artifacts for the model.

model_parents = get_one_hop_parent_artifacts(store, [exported_model])
display_artifacts(store, model_parents)

Get the training data the model trained with.

used_data = model_parents[0]
display_properties(store, used_data)

Now that you have the training data that the model trained with, query the database again to find the training step (execution). Query the MD store for a list of the registered execution types.


The training step is the ExecutionType named tfx.components.trainer.component.Trainer. Traverse the MD store to get the trainer run that corresponds to the pushed model.

def find_producer_execution(store, artifact):
  executions_ids = set(
      for event in store.get_events_by_artifact_ids([])
      if event.type == metadata_store_pb2.Event.OUTPUT)
  return store.get_executions_by_id(executions_ids)[0]

trainer = find_producer_execution(store, exported_model)
display_properties(store, trainer)


In this tutorial, you learned about how you can leverage MLMD to trace the lineage of your TFX pipeline components and resolve issues.

To learn more about how to use MLMD, check out these additional resources: