parallelising tf.data.Dataset.from_generator
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
tf.data.Dataset.from_generator runs a Python generator in a single thread, making it a bottleneck in training pipelines. To parallelize it, use tf.data.Dataset.interleave with multiple generator instances, or restructure your pipeline to use tf.data.Dataset.map with num_parallel_calls for the heavy processing after the generator yields file paths or indices. For maximum performance, convert your data to TFRecord format and use tf.data.TFRecordDataset with parallel reads instead of generators.
The Problem
The generator runs in the Python GIL, producing one sample at a time. Even with .prefetch(), the generator itself cannot be parallelized directly.
Method 1: Interleave Multiple Generators
Create multiple generator instances and interleave their outputs:
interleave runs multiple generators simultaneously in separate threads.
Method 2: Generator for Paths, Map for Processing
Move heavy processing out of the generator into a parallelizable map function:
The generator is now trivially fast, and all heavy I/O and preprocessing happens in the parallel map.
Method 3: tf.py_function in Map
If preprocessing requires Python libraries (OpenCV, PIL, custom code):
tf.py_function wraps Python code to run in TensorFlow's data pipeline, bypassing the GIL for I/O-bound operations.
Method 4: Convert to TFRecords (Fastest)
For maximum performance, preprocess data once and store as TFRecords:
Complete Optimized Pipeline
Common Pitfalls
- Putting heavy processing inside the generator: The generator runs in a single Python thread. Move I/O and preprocessing into
.map()withnum_parallel_calls=tf.data.AUTOTUNEso TensorFlow can parallelize it. - Forgetting
prefetch(tf.data.AUTOTUNE): Without prefetch, the GPU idles while waiting for the next batch.prefetchoverlaps data preparation with model training, keeping the GPU busy. - Using
deterministic=Truewith interleave: Settingdeterministic=True(the default) forces interleave to return elements in order, which serializes the generators and reduces parallelism. Setdeterministic=Falsefor training where order does not matter. - Not setting output shapes after
tf.py_function:tf.py_functionreturns tensors with unknown shapes. Calltensor.set_shape(...)after the function to restore shape information, otherwise downstream operations (batching, model layers) may fail. - Generator not being re-entrant: TensorFlow may call the generator multiple times across epochs. If the generator uses external state (file handles, database connections), ensure it reinitializes properly. Use a factory function that returns a fresh generator each time.
Summary
from_generatoris single-threaded — move heavy processing to.map()withnum_parallel_calls- Use
interleavewith multiple generator instances for parallel data loading - Keep generators lightweight (yield paths/indices) and parallelize processing in
map - Convert data to TFRecords for maximum I/O performance
- Always use
.prefetch(tf.data.AUTOTUNE)to overlap data loading and training
Related reading
- Passing in training labels to tf.keras.preprocessing.image_dataset_from_directory doesn't work
- Passing trainingtrue when using Tensorflow 2's Keras Functional API
- Permission denied when installing Tensorflow
- pip install tensorflow cannot find file called client_load_reporting_filter.h
- Parallelism behaviour of stream processing engines
- Parallelization strategies for deep learning
- Plot custom data with Tensorboard
- Plot multiple graphs in one plot using Tensorboard
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.