Search topics and sections

Rematerialization is a compiler technique that recomputes a value when it is needed again, instead of saving it to memory and loading it back later.[1] Compilers for machine learning use the same name for a related trade, where they recompute large arrays of numbers to save memory.[2][3]

It is part of register allocation, the step where a compiler decides which values live in the processor's few fast registers. When there are not enough registers, recomputing a cheap value, such as a constant, can cost less than a round trip through memory.[1]

Why registers run out

A processor computes on values held in registers, and a program usually has more values than the machine has registers. How well a compiler uses the registers has a large effect on how fast the compiled code runs.[4] The demand for registers at a point in a program is called register pressure.

When the compiler cannot find a register for every value, it spills some of them. Spilling means keeping a value in memory instead of a register.[1] A simple spill adds two kinds of instructions.[4]

  • A store after each place where the value is defined, to write it to memory.
  • A load before each place where the value is used, to read it back.

These loads and stores are the cost of spilling. In their measurements, Preston Briggs, Keith Cooper, and Linda Torczon assumed that each load and store takes two cycles and every other instruction takes one.[4]

How rematerialization works

Some values never need to be stored, because the compiler can rebuild them from scratch at any point. For such a value, the allocator adds the instruction that computed it to the code again, right before the value is needed.[4] The question it asks is whether recomputing is cheaper than storing and reloading.[1]

Spilling versus rematerializing a constantOriginalSpill and reloadRematerializemany other valuesneed registersmany other valuesneed registersmany other valuesneed registersx = 8 (load immediate)use xuse xx = 8store x to slotload slot to xuse xload slot to xuse xx = 8x = 8 (recompute)use xx = 8 (recompute)use xmemoryslotmemory accessrecomputed instruction
Spilling a constant adds a store after its definition and a load before each use; rematerializing it reruns the load-immediate instruction instead.

The table compares the two ways of freeing a register for a value that can be recomputed.

Spill and reload Rematerialize
After the definition Store to memory Nothing
Before each use Load from memory Run the defining instruction again
Memory access Yes Only if the recomputing instruction is itself a load
Works for Any value Only values whose inputs are always available

A small worked case shows the gap. Under the cost model above, spilling a value with one definition and three uses inserts one store and three loads, which is 2+3×2=82 + 3 \times 2 = 8 cycles. Rematerializing the same value with a one-cycle instruction inserts three such instructions, which is 3 cycles.

Which values qualify

Gregory Chaitin and his colleagues at IBM noticed that certain values can be recomputed in a single instruction whose operands are always available. Operands are the inputs an instruction uses to compute its result. Chaitin's group called these values never-killed and noted that they should be recalculated instead of spilled and reloaded.[4]

They also noted that an extra copy of a never-killed value can be removed by computing the value straight into the register where it is wanted.[4]

Briggs, Cooper, and Torczon list the common cases in practice.[4]

  • Load-immediate instructions for integer constants, and on some machines for floating-point constants. A load-immediate instruction puts a constant written inside the instruction into a register.
  • Computing a constant offset from the frame pointer or from the pointer to the static data area. The frame pointer is a register that holds the address of the current procedure's stack frame, the block of memory that holds a procedure's local data. The static data area holds global data.
  • Loads from a constant location in the stack frame or the static data area.
  • Loading frame pointers of enclosing procedures from a display, a table of such pointers.

Modern compilers state the same rule in their code. In LLVM, an instruction is trivially rematerializable when it has no side effects and needs no operands that are not always available.[5] A side effect is any change an instruction makes beyond producing its result, such as writing to memory.

LLVM also has a looser test for instructions that can be recomputed wherever all the registers they read are live.[5] A live register is one that holds a value still needed later in the program.

History

Early work

The idea of treating register allocation as graph coloring goes back to work on storage allocation in the early 1960s.[4] Chaitin and his colleagues at IBM built the first global register allocator based on graph coloring, in IBM's PL.8 compiler.[4][6]

Chaitin's allocator

Chaitin and colleagues described rematerialization of never-killed values in a 1981 paper on this allocator.[4][6] Their allocator handled rematerialization correctly only when the spilled variable had a single value. It could not handle a variable built from several values, some of which could be recomputed and some of which could not.[4]

The general solution

Briggs, Cooper, and Torczon gave a general solution at the 1992 ACM SIGPLAN Conference on Programming Language Design and Implementation.[1] It also appeared in Briggs's 1992 PhD thesis at Rice University.[6] Their method found and isolated a larger class of values that can be recomputed.[6]

A 1994 journal paper paired the method with optimistic coloring.[4] Optimistic coloring is a register allocation method that waits to decide whether a value must be spilled until it checks whether the value can still get a register.[4]

Values with several definitions

A variable in source code can hold different values at different points. The allocator works on live ranges, where a live range is the stretch of a program over which a value must be kept, and one live range may combine several values joined by common uses.[4] For such a live range, the allocator must separate the values it can recompute from the rest. Otherwise it spills the whole range, as Chaitin's allocator does.[4]

A motivating example

Briggs, Cooper, and Torczon used a pointer p that starts as a fixed address and is then used in two loops.[4]

  • In the first loop, p does not change, so it can be rebuilt with a load-immediate instruction before each use.
  • In the second loop, p is increased by one on each pass, so it changes and cannot be rebuilt that way.
  • The two definitions merge at the head of the second loop.

The ideal code reloads p with a load-immediate instruction just before it is needed in the first loop, and again just before the second loop. A Chaitin-style allocator instead spills the whole live range, with stores after definitions and loads before uses.[4]

Live range of a pointer split for rematerializationp0 = LabelinstLoop 1use pp does not changesplit (copy)Loop 2 header⊥p1 = φ(p0, p2)Loop 2 body⊥use p1p2 = p1 + 1p2rematerialize:reissue load immediatejoined into onelive range
The pointer pp has one value that can be recomputed and two that cannot. A single split separates them so only the cheap value p0p_0 is rematerialized, and p1p_1 and p2p_2, both tagged ⊥\bot, are joined.

The method in steps

The Briggs method has three main steps.[4]

  1. Split each live range into its separate values, using the procedure's static single-assignment (SSA) graph, where each use refers to exactly one definition.
  2. Tag each value with rematerialization information and spread the tags through the SSA graph.
  3. Rebuild live ranges by joining connected values that have identical tags.

Two later phases of the allocator then use the tags.[4]

  • The spill cost phase uses them to estimate costs more accurately.
  • The spill code phase uses them to produce the right code.

Tags and how they combine

Each tag is one of three kinds, arranged as a lattice, an ordering of tags in which any two tags combine into a single result, called their meet. The same kind of lattice is used in constant propagation.[4]

  • Top (⊤\top) means nothing is known yet. Values defined by a copy or by a φ-node (an SSA merge point) start here.
  • An instruction tag (inst\text{inst}) means the value is never-killed and can be recomputed by running that instruction again.
  • Bottom (⊥\bot) means the value must be spilled and reloaded in the normal way.
Rematerialization tag lattice⊤⊥inst₁inst₂inst₃…unknownspillrecompute
Rematerialization tags: ⊤\top (unknown), one tag per recomputable instruction, and ⊥\bot (must spill). Two different instruction tags meet at ⊥\bot.

The tags spread with a version of Wegman and Zadeck's sparse simple constant algorithm, a constant-propagation method that passes facts along the edges of the SSA graph.[1][4] It is related to sparse conditional constant propagation. Where values meet, their tags combine with this rule.[4]

any∧⊤=any,any∧⊥=⊥,insti∧instj={instiif insti=instj⊥if insti≠instj\text{any} \wedge \top = \text{any}, \qquad \text{any} \wedge \bot = \bot, \qquad \text{inst}_i \wedge \text{inst}_j = \begin{cases} \text{inst}_i & \text{if } \text{inst}_i = \text{inst}_j \\ \bot & \text{if } \text{inst}_i \neq \text{inst}_j \end{cases}

Here ∧\wedge is the meet, and two instruction tags are equal only if their instructions match operand by operand.[4] A copy takes the tag of the value flowing into it. A φ-node gets an instruction tag only if every value flowing into it has the same instruction tag, and gets ⊥\bot otherwise.[4]

Splitting and cleaning up

After tagging, the φ-nodes are removed. Where an incoming value has the same tag as the φ-node's result, the two are joined, and where the tags differ, the allocator inserts a split, a special copy instruction, in the predecessor block.[4] A predecessor block is a block of the program from which control flows into the current block.

In the pointer example, a single copy isolates the never-killed starting address from the other values of p.[4]

Some of these splits turn out to be useless once registers are assigned. The allocator removes them with conservative coalescing, which merges two live ranges only when that cannot make coloring fail, and with biased coloring, which tries to give split partners the same register.[4]

Costs and limits

Rematerialization is not free, and it does not always help.

  • It needs the recomputed value's inputs at the point of use. Moving a longer chain of instructions to the use adds instructions there and can raise register use at that point.[7]
  • Some cases are clearly profitable. A GNU Compiler Collection (GCC) proposal noted that a value rebuilt by one instruction cannot cost more than a spill, because a store and a reload together need at least two instructions.[7]
  • In Briggs, Cooper, and Torczon's measurements, support for rematerialization could require a small amount of additional compile time.[4]
  • It works against common subexpression elimination, which removes repeated computations. A comment in the rematerialization pass of the XLA machine-learning compiler warns that running common subexpression elimination after rematerialization undoes it.[2]

Use in compilers

LLVM and GCC both include rematerialization in their register allocators.[5][8] LLVM lets each target describe which instructions can be recomputed, and it provides a hook that reissues an original instruction at a new place with a new destination register.[5]

In GCC, a 2004 paper noted that the then-new graph-coloring allocator rematerialized only values defined by moving an immediate constant into a register. It proposed finding a wider set of never-killed values during data-flow analysis, the compiler's analysis of where each value is defined and used. Examples include address calculations relative to the frame pointer.[7]

GCC 5 added a sub-pass to its local register allocator (LRA), controlled by the -flra-remat option. It recalculates a value instead of spilling and restoring it when that is profitable, and it takes the program's control flow into account.[8] The release notes report that it improved code for the SPEC2000 benchmarks by 1% on ARM and 0.5% on x86-64.[8]

Rematerialization in machine learning

The same name is used for trading computation for memory when training neural networks. A neural network is a computing system made of connected stages that learns patterns from examples.

Here the scarce resource is the memory on a graphics processing unit (GPU), a chip designed to handle many calculations at once, or a similar chip used for training. The values are large arrays, ordered collections of values, instead of single numbers.

The XLA compiler has a rematerialization pass. It recomputes selected expressions to reduce the memory pressure caused by array values that stay live for a long time.[9] XLA's documentation says this can reduce memory use by tens of percent and is required to run many large models.[9]

Gradient checkpointing

A network is built from layers, where a layer is a stage that transforms values and passes them on. Training runs a forward pass, which computes outputs layer by layer, and then a backward pass, which computes gradients in reverse order using backpropagation. Gradients measure how changing a model's values changes its output or error.

Most gradient steps need outputs from the forward pass, so training normally keeps every layer's output until the backward pass uses it.[10] Gradient checkpointing keeps only some outputs and recomputes the rest from the nearest kept one when needed.[10]

Chen and colleagues proposed in 2016 splitting an nn-layer network into kk segments and storing only each segment's output.[10]

Gradient checkpointing with three segmentsforward passrecompute from kept outputL1L2L3L4L5L6L7L8L9discardedkeptsegment 1segment 2segment 3backward pass
Gradient checkpointing keeps only segment outputs and recomputes the inside of each segment during the backward pass. With nn layers in k=nk=\sqrt{n} segments, memory is O(n)O(\sqrt{n}) for about one extra forward pass.

Their estimate of the memory cost has two parts.[10]

memory=O ⁣(nk)+O(k)\text{memory} = O\!\left(\frac{n}{k}\right) + O(k)

The first term is the memory to run the backward pass on one segment, and the second is the memory to store the outputs between segments. Choosing k=nk = \sqrt{n} gives O(n)O(\sqrt{n}) memory, at the cost of about one extra forward pass per mini-batch, the small group of examples used for one training step.[10]

They cut the memory for a 1,000-layer residual network, a deep network design with shortcut connections between layers, from 48 GB to 7 GB.[10] In their speed tests, the method added roughly 30 percent to running time.[10]

Optimal schedules

Later work treats the choice of what to keep and what to recompute as an optimization problem. The Checkmate system calls it the tensor rematerialization problem, a broader version of earlier checkpointing strategies.[3] A tensor here is an array of numbers that can have more than one dimension.

Checkmate solves the problem with mixed integer linear programming, an optimization method that picks yes-or-no choices, here whether to keep or recompute each value, to minimize compute time while staying within a memory budget.[3] Its authors reported training real networks with inputs up to 5.1 times larger.[3]

References

  1. Rematerialization, Preston Briggs, Keith D. Cooper, Linda Torczon, Proceedings of PLDI '92 (ACM SIGPLAN Notices 27(7)), 1992.
  2. hlo_rematerialization.h, OpenXLA Project.
  3. Checkmate: Breaking the Memory Wall with Optimal Tensor Rematerialization, Paras Jain et al., MLSys, 2020.
  4. Improvements to Graph Coloring Register Allocation, Preston Briggs, Keith D. Cooper, Linda Torczon, ACM Transactions on Programming Languages and Systems 16(3), 1994.
  5. llvm::TargetInstrInfo Class Reference, LLVM Project.
  6. Register Allocation via Graph Coloring, Preston Briggs, PhD thesis, Rice University, 1992.
  7. Register Rematerialization in GCC, GCC Developers' Summit, 2004.
  8. GCC 5 Release Series: Changes, New Features, and Fixes, GNU Project.
  9. HLO Passes, OpenXLA Project, 2025.
  10. Training Deep Nets with Sublinear Memory Cost, Tianqi Chen, Bing Xu, Chiyuan Zhang, Carlos Guestrin, arXiv, 2016.

Figure