Data I/O methods for PAI-TensorFlow

Updated at:

PAI-TensorFlow can read training data from Object Storage Service (OSS) buckets and MaxCompute tables. The I/O method you choose directly affects GPU utilization — the wrong approach leaves the GPU idle while data loads into memory.

Warning

GPU-accelerated servers will be phased out. Submit TensorFlow tasks on CPU servers. For GPU-based model training, use Deep Learning Containers (DLC) instead. See Submit training jobs.

Choose a data source

If your data is stored as...Use...
Files or directories (images, CSV files, text files)OSS bucket
Structured tablesMaxCompute table

Read OSS data

Set up OSS access

Before you can read from OSS, complete the following setup:

  1. Create an OSS bucket in the same region as your compute cluster. Data transferred over the Alibaba Cloud classic network is not charged for traffic.

    Important

    Do not enable versioning on the bucket.

  2. Create a directory structure and upload your data using the OSS console.

  3. Assign the AliyunODPSPAIDefaultRole role to your account. This role grants PAI read/write access to OSS. The role includes the following permissions: To assign this role, see Grant the permissions required to use Machine Learning Designer. To use a RAM role instead, see the "Grant your RAM user or RAM role the permissions to access OSS" section in the same topic.

    PermissionDescription
    oss:PutObjectUpload an object
    oss:GetObjectQueries an object
    oss:ListObjectsList objects
    oss:DeleteObjectsDelete objects
  4. In Machine Learning Designer, connect the Read File Data component to the TensorFlow component.

Use ops-based reading (recommended)

The I/O method in your training script determines GPU efficiency. The following table summarizes the options:

ApproachHow it worksProblem
Built-in Python file I/O (csv, open)Reads data into memory before computing beginsMemory bottleneck; requires compressing data into a package and uploading to OSS
Third-party libraries (TFLearn, pandas)Wraps data access in a Python packageSame memory bottleneck on PAI
Preloading data before the sessionReads the full dataset into memory, then starts the compute sessionGPU sits idle during the load phase — with 0.1s to load and 0.9s to compute, the GPU is idle 10% of each cycle

Recommended: Convert data to TensorFlow Operations (ops) and call session.run to read data. A dedicated read thread streams data from OSS into a memory queue while the compute thread pulls batches directly from the queue, keeping the GPU continuously occupied.

The following example reads a CSV file from OSS using ops:

import argparse
import tensorflow as tf
import os

FLAGS = None

def main(_):
    # Path to the OSS object — can also be an array of paths
    dirname = os.path.join(FLAGS.buckets, "csvtest.csv")

    # Select a reader type based on your file format
    reader = tf.TextLineReader()

    # Convert the object path into a queue
    filename_queue = tf.train.string_input_producer([dirname])
    key, value = reader.read(filename_queue)

    # Split each row into individual fields
    record_defaults = [[''], [''], [''], [''], ['']]
    d1, d2, d3, d4, d5 = tf.decode_csv(value, record_defaults, ',')

    init = tf.initialize_all_variables()

    with tf.Session() as sess:
        sess.run(init)
        # Required when using ops-based reading
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(sess=sess, coord=coord)
        for i in range(4):
            print(sess.run(d2))
        coord.request_stop()
        coord.join(threads)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--buckets', type=str, default='',
                        help='input data path')
    parser.add_argument('--checkpointDir', type=str, default='',
                        help='output model path')
    FLAGS, _ = parser.parse_known_args()
    tf.app.run(main=main)

Key parameters:

ParameterDescription
dirnamePath to the OSS object. Accepts a single path or an array of paths.
readerReader type. PAI-TensorFlow provides readers for different file formats — choose based on your data format.
tf.train.string_input_producerConverts the object path into a queue for streaming reads.
tf.decode_csvSplits each CSV row into individual fields. Use to extract specific columns.
tf.train.Coordinator()Required for ops-based reading. Coordinates the read and compute threads.
tf.train.start_queue_runnersStarts the background read threads. Must be called inside a session.

Read MaxCompute data

Use the TensorFlow component in Machine Learning Designer to read from and write to MaxCompute tables.

Connect the components

  1. Drag the Read MaxCompute Table component and the TensorFlow component onto the canvas.

  2. Connect them. The TensorFlow component has five ports: For MaxCompute-only workflows, connect only input port 2 and output port 5.

    PortDirectionConnects to
    1InputOSS input
    2InputMaxCompute input
    3InputModel input
    4OutputModel output
    5OutputMaxCompute output

Configure the Read MaxCompute Table component

Click the Read MaxCompute Table component. On the Select Table tab, enter the table name in the Table Name field. For example, to use the iris sample dataset:

pai_online_project.iris_data

Configure the TensorFlow component

Set the following fields:

FieldDescription
Python Code FilesOSS path to your training script. The OSS bucket must be in the same region as the current project.
Checkpoint Output Directory / Modeling Input DirectoryOSS path to store model checkpoints.
MaxCompute output tableName of the output table. The table must already exist, and the name must match the name in your code. For this example, enter iris_output.
SQL create table statementSQL statement to create the output table if it does not exist. For this example: create table iris_output(f1 DOUBLE,f2 DOUBLE,f3 DOUBLE,f4 DOUBLE,f5 STRING);

The equivalent PAI command is:

PAI -name tensorflow180_ext -project algo_public \
  -Doutputs="odps://<project-name>/tables/<output-table>" \
  -DossHost="<oss-host>" \
  -Dtables="odps://<project-name>/tables/<input-table>" \
  -DgpuRequired="<gpu-count>" \
  -Darn="<arn-of-ram-role>" \
  -Dscript="<code-file>";

Replace each <placeholder> with the actual value for your environment.

Read and write MaxCompute data in code

Use TableRecordDataset to read from and write to MaxCompute tables in your training script. See TableRecordDataset for the API reference and examples.

What's next