NeurIPS 2026Coming to NeurIPS?Explore papers, orals & directions

Static Automatic Batching In TensorFlow

Ashish AgarwalICML 2019

Introduction

The paper introduces pfor (parallel-for), a new programming abstraction for TensorFlow that performs static automatic batching. By using a graph-rewriting algorithm to "vectorize" loops at compile-time, it allows developers to write simple, per-instance code that achieves the high performance of manually batched implementations. This approach often results in speedups of one to two orders of magnitude over iterative approaches.

The Challenge of Dynamic Models

In modern deep learning, models are becoming increasingly dynamic, processing trees, graphs, or variable-length sequences. While "define-by-run" frameworks like PyTorch make these models easy to write, they often suffer from significant overhead because the host language (e.g., Python) becomes a bottleneck.

To achieve high performance on GPUs, researchers usually resort to manual batching. This involves complex padding and masking logic to group multiple inputs into a single large tensor operation, which is error-prone and obscures the model's core logic. Existing solutions like DyNet perform "auto-batching" at runtime, but this introduces its own management overhead. The authors aim to provide the best of both worlds: the simplicity of writing code for a single example combined with the performance of a manually optimized, batched execution.

Methods: Static Graph Vectorization

The core contribution is a static graph-vectorization algorithm implemented within TensorFlow.

  1. SPMD Abstraction: The authors introduce pfor(loop_body_fn, iters), following the Single Program, Multiple Data (SPMD) model. Users write a function for a single iteration, and pfor treats different iterations as independent program instances.
  2. Graph Rewriting: Instead of running a standard loop, TensorFlow analyzes the computation graph of the loop body. It traverses the nodes in topological order and replaces each operation with its "vectorized" equivalent. For example, a scalar addition inside the loop is rewritten as a vector addition across all iterations.
  3. Loop Invariance Optimization: The system identifies tensors that do not change across iterations (loop invariants). These are not vectorized, saving both memory and computation.
  4. Handling Control Flow: The algorithm handles complex constructs like conditionals (tf.cond) and nested loops (tf.while_loop) by converting them into functional forms and using masking or "stitching" techniques (via TensorArray) to manage active versus inactive iterations.
  5. High-Level Primitives: Built on top of pfor, the authors added tf.jacobian and batch_jacobian for efficient derivative calculations, and vectorized_map for easier batch processing.

Key Insights

  • Vectorization at the Graph Level: By vectorizing at the level of TensorFlow kernels (like tf.matmul) rather than low-level CPU/GPU instructions, the system leverages highly optimized vendor libraries (like cuBLAS) for batched operations.
  • Static vs. Runtime: Unlike DyNet, which decides how to batch operations while the program is running, pfor does this once during graph construction, eliminating runtime decision-making overhead.
  • Mathematical Properties: The vectorizer uses mathematical properties of operations. For instance, vectorizing a matrix multiplication where only one input depends on the loop index can be transformed into a single large matrix multiplication or a batch_matmul, depending on the shapes.

Results and Performance

The approach was evaluated across several model architectures, including Linear Projections, ConvMNIST, VGG16, LSTMs, TreeLSTMs, and GatedGraphNNs, focusing primarily on throughput.

  • Massive Speedups: pfor consistently outperformed sequential loops (tf.while_loop) by 10x to 100x.
  • Matching Manual Performance: In many cases, such as ConvMNIST, the automatically batched code matched the performance of a hand-written, manually batched version.
  • Comparison to DyNet: On tasks like GNNs and TreeLSTMs, pfor significantly outperformed DyNet's runtime auto-batching at larger batch sizes by avoiding runtime graph construction costs.
Performance comparison of pfor, while_loop, and DyNet across different models and hardware
  • Advanced Gradients and Jacobians: The new tf.jacobian implementation was up to 60x faster than the previous iterative approach. Furthermore, for models like LSTMs, pfor computed per-example gradients 38x faster than the iterative method.
Per-example gradient computation speedup using pfor vs while_loop

Limitations and Future Work

  • Memory Usage: Running all iterations in parallel can significantly increase memory consumption. The authors provide a parallel_iterations knob to tile the loop and trade off speed for memory, but finding the optimal balance remains a manual task.
  • Kernel Support: The system requires a "converter" function for every TensorFlow operation. While many are covered, "fused" kernels (like fused Batch Normalization) were noted as experimental or not yet fully supported.
  • Side Effects: The SPMD semantics are strictly enforced. Programs where iterations have complex side-effects (like multiple iterations writing to the same variable) may be flagged as errors.

Summary updated

BibTeX
@inproceedings{agarwal2019static,
  author = {Ashish Agarwal},
  title = {{Static Automatic Batching In TensorFlow}},
  booktitle = {International Conference on Machine Learning},
  year = {2019},
}
Figure