TensorFlow DataSet from_generator with variable batch size
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 is useful when data loading logic is easier in Python than in pure TensorFlow ops. Variable batch size is common when last batch is smaller or when upstream producer emits adaptive chunks. The key to making this stable is a correct output_signature with flexible batch axis and strict consistency for all other dimensions.
Define a Precise Generator Contract
Before creating the dataset, define exactly what each yield returns:
- Structure, such as tuple of features and labels.
- Dtype for each tensor.
- Which dimensions may vary.
Example generator that emits different batch sizes:
If you skip this contract step, shape and dtype errors appear later and are harder to trace.
Use None for Variable Leading Axis
Declare flexible batch dimension in TensorSpec.
Only the leading axis should usually be flexible. Feature dimension and label dimension should remain fixed unless your model supports variable-length inputs explicitly.
Decide Where Batching Happens
Two valid patterns exist:
- Generator yields full batches.
- Generator yields single examples and dataset does
.batch.
Do not mix both accidentally. Double-batching is a common source of rank errors.
Single-example generator pattern:
Keep one batching stage for predictable shapes.
Variable Batch Size vs Variable Sequence Length
These are different concerns:
- Variable batch size means first axis changes.
- Variable sequence length means inner time dimension changes.
If sequences vary in length, use padding or ragged handling.
Treating variable sequence length as variable batch size leads to incorrect model input handling.
Improve Throughput and Stability
Python generators run on host side, so heavy logic can bottleneck training. Keep generator minimal and move transform-heavy steps to tf.data ops when possible.
Add prefetch for pipeline overlap:
Also cast values inside generator to avoid dtype drift from mixed sources.
Validation Before Training
Before feeding into model:
- Iterate through a few batches.
- Print shapes and dtypes.
- Confirm last partial batch behavior.
- Validate label alignment.
Quick check:
This catches most contract mismatches early.
Common Pitfalls
- Declaring fixed batch size in signature while yielding variable sizes. Fix by using
Nonefor leading axis. - Applying
.batchto data already batched by generator. Fix by choosing one batching strategy. - Mixing variable sequence length without padding. Fix with
padded_batchor ragged tensors. - Yielding inconsistent dtypes across iterations. Fix by explicit casting in generator.
- Putting expensive preprocessing inside Python generator. Fix by moving transforms into
tf.datapipeline ops.
Summary
- Variable batch size works with
from_generatorwhenoutput_signatureis defined correctly. - Keep non-batch dimensions and dtypes consistent.
- Separate batching responsibilities clearly to avoid rank bugs.
- Handle variable sequence length with padding strategies, not ad hoc shape changes.
- Validate shapes early and tune pipeline throughput with prefetch.
Related reading
- TensorFlow Dataset Generator With Mixed Datatypes
- Tensorflow Dataset .map API
- TensorFlow Dataset Shuffle Each Epoch
- tensorflow dataset shuffle then batch or batch then shuffle
- tensorflow deep neural network for regression always predict same results in one batch
- Tensorflow dense gradient explanation?
- Tensorflow Dataset.from_generator fails with pyfunc exception
- Tensorflow DecodeJpeg method gives different pixel values on desktop and mobile for the same image
.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.