Control Flow Operators in PyTorch

Yidi Wu, Thomas Ortner, Richard Zou, Edward Z. Yang, Adnan Akhundov, Horace He, Yanan CaoCODEML @ ICML 2025

TL;DR

This paper introduces a new library of control flow operators for PyTorch, enabling the PyTorch 2 compiler (PT2) to handle dynamic control flow more effectively. By providing operators like cond, while_loop, map, scan, and associative_scan, the library allows for more efficient compilation, reduced memory usage, and better handling of data-dependent control flow, which was previously a bottleneck.

What Problem Does This Paper Address?

Machine learning (ML) compilers often struggle with representing and optimizing control flow in programs. Many compilers opt to avoid it altogether by tracing models and generating a static, straight-line computational graph. This is typically achieved by specializing conditional branches or unrolling loops. While this works for static control flow, it leads to performance issues, long compilation times, and is problematic when control flow depends on data or dynamic shapes. This limitation hinders the ability to compile and optimize complex ML models efficiently, especially for scenarios like dynamic inference or edge deployments where a Python runtime might not be available.

Methods

The paper introduces five new control flow operators to PyTorch:

  • cond(pred, true_fn, false_fn): Selects and executes one of two functions based on a boolean predicate.
  • while_loop(cond_fn, body_fn, operands): Implements a traditional while loop, executing a body function repeatedly as long as a condition function returns true.
  • map(fn, xs): Applies a function fn to each element of an input xs and stacks the results.
  • scan(combine_fn, init, xs): Performs a cumulative operation over a sequence xs, maintaining a carry value.
  • associative_scan(combine_fn, xs): Similar to scan but requires an associative combine_fn, allowing for more optimization opportunities.

These operators are integrated into PyTorch's autograd system and the PT2 compiler. Restrictions are imposed to ensure compatibility with the compiler's IR, such as structure matching for inputs/outputs and tensor metadata consistency. The paper also details the autograd implementation for these operators, leveraging existing PyTorch mechanisms.

Datasets

Not discussed in the paper.

Key Insights and Ideas

  • Dynamic control flow is a critical bottleneck: The paper highlights that static tracing and unrolling, while common, fail to address dynamic control flow, leading to graph breaks and fallback to Python, which limits deployment options.
  • A unified operator library simplifies compilation: Introducing a set of well-defined control flow operators provides a structured way for the compiler to understand and optimize these constructs, rather than relying on ad-hoc Python tracing.
  • Scan and associative_scan offer significant memory and compilation benefits: For sequential operations like RNNs or chunked computations, these operators drastically reduce compilation time and peak memory usage compared to naive loop implementations.
  • Autograd symmetry simplifies implementation: The paper notes that for many control flow operators, the backward pass exhibits a symmetry with the forward pass, allowing for reuse of existing autograd infrastructure.

Key Results

The paper demonstrates significant improvements across various use cases:

  • Reduced Compilation Time and Memory: For chunked loss computation, using scan reduced compilation time and peak memory usage compared to a naive loop implementation (Figure 1). Similarly, RNNs implemented with scan showed substantial savings in compile time and memory consumption compared to eager PyTorch (Figure 5).
  • Efficient Handling of Dynamic Control Flow: The cond operator is shown to be useful for shape-dependent branching in LLMs. The while_loop operator is proposed for data-dependent loops like early stopping in language model generation.
  • Optimized State-Space Models: The associative_scan operator is demonstrated to be well-suited for State-Space Models (SSMs), enabling efficient implementation and potentially outperforming eager PyTorch in compile time for certain layers (Figure 2).

Limitations and Future Work

  • while_loop Autograd: The autograd implementation for while_loop is noted as a work in progress due to challenges in storing intermediate outputs for an undetermined number of loop iterations. The authors are exploring ways to store "dynamic" intermediates within the IR.
  • Data-dependent intermediate activations for cond and while_loop: While checkpointing strategies can be integrated with most operators, those with data-dependent intermediate activations for cond and while_loop present challenges that are left for future work.
  • Performance compared to hand-written kernels: The paper states that the objective is to demonstrate benefits over native PyTorch implementations, not necessarily to achieve state-of-the-art performance compared to manually optimized kernels. However, they believe their techniques can be incorporated into PT2 to achieve comparable or better performance.

Summary updated

BibTeX
@inproceedings{wu2025control,
  author = {Yidi Wu and Thomas Ortner and Richard Zou and Edward Z. Yang and Adnan Akhundov and Horace He and Yanan Cao},
  title = {{Control Flow Operators in PyTorch}},
  booktitle = {CODEML @ ICML},
  year = {2025},
  url = {https://openreview.net/forum?id=GMFG27v26J},
}
Figure