Overlap input work with model execution
Training input pipelines
TensorFlow · Module
Dataset.prefetch buffers upcoming dataset elements so they can be prepared while current elements are processed. It can improve pipeline latency and throughput, with additional memory use; tf.data.AUTOTUNE can tune the buffer size.
Calling prefetch adds an internal buffer that prepares upcoming dataset elements before they are requested. This can overlap input preparation with model work, improving pipeline throughput while consuming additional memory; tf.data.AUTOTUNE can select the buffer size dynamically.
prefetch(buffer_size, name=None) -> 'DatasetV2'| Name | Type | Description |
|---|---|---|
buffer_size | tf.int64 scalar tf.Tensor | Maximum number of dataset elements to buffer; tf.data.AUTOTUNE enables dynamic tuning. |
name | string | Optional name for the dataset operation. |
A DatasetV2 containing the prefetched elements.
import tensorflow as tf
dataset = tf.data.Dataset.range(3)
dataset = dataset.prefetch(tf.data.AUTOTUNE)
print(list(dataset.as_numpy_iterator()))Creates a range dataset and lets TensorFlow choose the prefetch buffer size automatically.
Training input pipelines
Variable pipeline workloads
Batched datasets
prefetch prepares future dataset elements in an internal buffer so production can overlap with consumption. This can reduce input latency and improve throughput.
Follow-up: How can the buffer size be selected dynamically? Pass tf.data.AUTOTUNE so the tf.data runtime tunes it during execution.
The argument specifies the maximum number of input elements buffered. If it is tf.data.AUTOTUNE, TensorFlow tunes that capacity at runtime.
Follow-up: What does the count represent after batching? It represents batches, because each batch is one dataset element.
Prefetching can improve latency and throughput, but buffered elements require additional memory. The trade-off should be considered when choosing a fixed buffer size.
Follow-up: Why might prefetch(2) behave differently before and after batch(20)? Before batching it buffers two examples; after batching it buffers two batches.
tf.data.Dataset.batchtf.data.Dataset.maptf.data.AUTOTUNEtf.data.Dataset