Data I/O methods for PAI-TensorFlow
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.
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 tables | MaxCompute table |
Read OSS data
Set up OSS access
Before you can read from OSS, complete the following setup:
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.
ImportantDo not enable versioning on the bucket.
Create a directory structure and upload your data using the OSS console.
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.
Permission Description oss:PutObjectUpload an object oss:GetObjectQueries an object oss:ListObjectsList objects oss:DeleteObjectsDelete objects 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:
| Approach | How it works | Problem |
|---|---|---|
Built-in Python file I/O (csv, open) | Reads data into memory before computing begins | Memory bottleneck; requires compressing data into a package and uploading to OSS |
| Third-party libraries (TFLearn, pandas) | Wraps data access in a Python package | Same memory bottleneck on PAI |
| Preloading data before the session | Reads the full dataset into memory, then starts the compute session | GPU 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:
| Parameter | Description |
|---|---|
dirname | Path to the OSS object. Accepts a single path or an array of paths. |
reader | Reader type. PAI-TensorFlow provides readers for different file formats — choose based on your data format. |
tf.train.string_input_producer | Converts the object path into a queue for streaming reads. |
tf.decode_csv | Splits 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_runners | Starts 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
Drag the Read MaxCompute Table component and the TensorFlow component onto the canvas.
Connect them. The TensorFlow component has five ports: For MaxCompute-only workflows, connect only input port 2 and output port 5.
Port Direction Connects to 1 Input OSS input 2 Input MaxCompute input 3 Input Model input 4 Output Model output 5 Output MaxCompute 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_dataConfigure the TensorFlow component
Set the following fields:
| Field | Description |
|---|---|
| Python Code Files | OSS path to your training script. The OSS bucket must be in the same region as the current project. |
| Checkpoint Output Directory / Modeling Input Directory | OSS path to store model checkpoints. |
| MaxCompute output table | Name 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 statement | SQL 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
TableRecordDataset — API reference for reading and writing MaxCompute data
Submit training jobs — Run GPU-based training jobs in DLC
Grant the permissions required to use Machine Learning Designer — Set up RAM roles for OSS access