Export and deploy PAI-TensorFlow models

Updated at:

You can export a trained PAI-TensorFlow model and deploy it to integrate it into an online service, validate its performance, or enable other systems to call it. This topic covers exporting a model in the SavedModel format, saving and restoring checkpoints, and deploying a TensorFlow model to Elastic Algorithm Service (EAS).

Warning

GPU-accelerated servers will be phased out. You can submit TensorFlow tasks that run on CPU servers. If you want to use GPU-accelerated instances for model training, go to Deep Learning Containers (DLC) to submit jobs. For more information, see Create a training job.

Export a SavedModel

  • SavedModel format

    SavedModel is the recommended format for saving models. SessionBundle has been deprecated since TensorFlow 1.0. A SavedModel directory has the following structure:

    assets/assets.extra/variables/ variables.data-xxxxx-of-xxxxx variables.index saved_model.pb

    For more information about the subdirectories and files, see the official TensorFlow SavedModel documentation or this introduction.

  • Export a SavedModel

    Code snippet:

    class Softmax(object):
        def __init__(self):
            self.weights_ = tf.Variable(tf.zeros([FLAGS.image_size, FLAGS.num_classes]),
                    name='weights')
            self.biases_ = tf.Variable(tf.zeros([FLAGS.num_classes]),
                    name='biases')
    
        def signature_def(self):
            images = tf.placeholder(tf.uint8, [None, FLAGS.image_size],
                name='input')
            normalized_images = tf.scalar_mul(1.0 / FLAGS.image_depth,
                tf.to_float(images))
            scores = self.scores(normalized_images)
            tensor_info_x = tf.saved_model.utils.build_tensor_info(images)
            tensor_info_y = tf.saved_model.utils.build_tensor_info(scores)
            return tf.saved_model.signature_def_utils.build_signature_def(
                    inputs={'images': tensor_info_x},
                    outputs={'scores': tensor_info_y},
                    method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME)
        def savedmodel(self, sess, signature, path):
            export_dir = os.path.join(path, str(FLAGS.model_version))
            builder = tf.saved_model.builder.SavedModelBuilder(export_dir)
            builder.add_meta_graph_and_variables(
                sess, [tf.saved_model.tag_constants.SERVING],
                signature_def_map={
                    'predict_images':
                        signature,
                },
                clear_devices=True)
            builder.save()
    
    model = Softmax()
    signature = model.signature_def()
    
    model.savedmodel(sess, signature, mnist.export_path())

    Code description:

    • The Softmax class encapsulates the machine learning model. The primary model parameters are weights and biases.

    • The signature_def method defines the prediction logic. It transforms a placeholder through data normalization and forward computation to produce an output. The inputs and outputs are then used to build a SignatureDef.

    Export the SavedModel to Object Storage Service (OSS):

    Run the following command to train and export the model.

    PAI -name tensorflow
        -Dscript="file://path/to/mnist_savedmodel_oss.py"
        -Dbuckets="oss://mnistdataset/?host=oss-test.aliyun-inc.com&role_arn=acs:ram::127488******:role/odps"
        -DcheckpointDir="oss://mnistdataset/?host=oss-test.aliyun-inc.com&role_arn=acs:ram::127488*********:role/odps";

Save and restore checkpoints

  • Save a checkpoint

    The following code shows how to save a model in a non-interactive TensorFlow session:

    # -*- coding: utf-8 -*-
    # usage
    # pai -name tensorflow -DcheckpointDir="oss://tftest/examples/?host=oss-test.aliyun-inc.com&role_arn=acs:ram::****:role/odps" -Dscript="file:///path/to/save_model.py";
    import tensorflow as tf
    import json
    import os
    tf.app.flags.DEFINE_string("checkpointDir", "", "oss info")
    FLAGS = tf.app.flags.FLAGS
    print("checkpoint dir:" + FLAGS.checkpointDir)
    # Define variables.
    counter = tf.Variable(1, name="counter")
    one = tf.constant(2)
    sum = tf.add(counter, one)
    new_counter = tf.assign(counter, sum)
    saver = tf.train.Saver()
    init_op = tf.global_variables_initializer()
    with tf.Session() as sess:
        sess.run(init_op)
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)
        ret = sess.run(new_counter)
        print("Counter:%d" % ret)
        ckp_path = os.path.join(FLAGS.checkpointDir, "model.ckpt")
        save_path = saver.save(sess, ckp_path)
        print("Model saved in file: %s" % save_path)
        coord.request_stop()
        coord.join(threads)

    Use tf.app.flags.DEFINE_string() and tf.app.flags.FLAGS to obtain the checkpointDir parameter from the PAI command. This parameter specifies the OSS path where the model is saved.

    The following code computes new_counter and saves the variable named counter with a value of 3 to the model. The save_path = saver.save(sess, ckp_path) call writes the model to the specified OSS path:

    ret = sess.run(new_counter)
    print("Counter:%d" % ret)
    ckp_path = os.path.join(FLAGS.checkpointDir, "model.ckpt")
    save_path = saver.save(sess, ckp_path)
    print("Model saved in file: %s" % save_path)
  • Restore from a checkpoint

    You can also use the TensorFlow Saver class to restore a model:

    # -*- coding: utf-8 -*-
    # usage
    # pai -name tensorflow -Dbuckets="oss://tftest/examples/?host=oss-test.aliyun-inc.com&role_arn=acs:ram::***:role/odps" -Dscript="file:///path/to/restore_model.py";
    import tensorflow as tf
    import json
    import os
    tf.app.flags.DEFINE_string("buckets", "", "oss info")
    FLAGS = tf.app.flags.FLAGS
    print("buckets:" + FLAGS.buckets)
    # Define variables.
    counter = tf.Variable(1, name="counter")
    saver = tf.train.Saver()
    init_op = tf.global_variables_initializer()
    with tf.Session() as sess:
        sess.run(init_op)
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)
        ret = sess.run(counter)
        print("Before restore counter:%d" % ret)
        print("Model restore from file")
        ckp_path = os.path.join(FLAGS.buckets, "model.ckpt")
        saver.restore(sess, ckp_path)
        ret = sess.run(counter)
        print("After restore counter:%d" % ret)
        coord.request_stop()
        coord.join(threads)

    Use tf.app.flags.DEFINE_string() and tf.app.flags.FLAGS to obtain the buckets parameter from the PAI command. This parameter specifies the OSS path from which to restore the model.

    In the following code, a variable named counter is defined with an initial value of 1. Then, saver.restore(sess, ckp_path) is called to restore the saved model from the specified OSS path. Finally, ret = sess.run(counter) is executed. The value of the restored variable is 3.

    ret = sess.run(counter)
    print("Before restore counter:%d" % ret)
    print("Model restore from file")
    ckp_path = os.path.join(FLAGS.buckets, "model.ckpt")
    saver.restore(sess, ckp_path)
    ret = sess.run(counter)
    print("After restore counter:%d" % ret)

Deploy a TensorFlow model to EAS

EAS is a model deployment tool developed by PAI that supports models from deep learning frameworks, especially TensorFlow models in the SavedModel format. EAS provides two deployment methods: using the EAS online service or the local client (EASCMD).

Deploy using online service

  1. Store the model in OSS. For more information, see Upload objects.

  2. Log on to the PAI console. Select a region on the top of the page. Then, select the desired workspace and click Enter Elastic Algorithm Service (EAS).

  3. On the Elastic Algorithm Service (EAS) page, click Deployment services. In the Custom Model Deployment section, click Custom Deployment.

  4. On the Custom Deployment page, configure the following key parameters. For more information about other parameters, see Custom Deployment.

    • Deployment Method: Select Processor-based Deployment.

    • Model config: Select OSS and specify the OSS path to the model file.

    • Processor Type: Select TensorFlow1.12 or TensorFlow1.14.

  5. Click Deploy.

    The system packages and uploads the TensorFlow model in the SavedModel format to deploy the model service.

Deploy using EASCMD

For more information, see Deploy a service using a local client (EASCMD).