17 minute read

Enzyme is an automatic differentiation project which operates at the LLVM/MLIR level, allowing you to compute the derivatives of any program which lowers to LLVM IR or MLIR. Region Outlining is a pass in EnzymeMLIR which outlines the MLIR region defined in enzyme.fwddiff_region or an enzyme.autodiff_region into its own private function. The region op is replaced by a call to the enzyme.fwddiff or enzyme.autodiff op.

The region op is useful for writing optimizations like removing invariant code from within a differentiated region, or common subexpression elimination(CSE) across repeated invocations of differentiating the same primal code. It looks like this in practice:

// @dsq takes a value x, computes out = x^2, and runs
// backpropagation with input seed dout to compute dx
func.func @dsq(%x : f64, %dout : f64) -> (f64, f64) {
  // the region op takes as arguments x and dout
  %out, %dx = enzyme.autodiff_region(%x, %dout) {
    // the inner basic block just describes y = x * x
    // the autodiff_region op forwards %x to %x2
    ^bb0(%x2 : f64): 
      %y = arith.mulf %x2, %x2 : f64
      enzyme.yield %y : f64 
  } <activity = [#enzyme.activity<enzyme_active>], 
     ret_activity=[#enzyme.activity<enzyme_active>] 
    >: (f64,f64) -> (f64, f64) 

  return %out, %dx : f64, f64
}

Activity tags (like enzyme_active, enzyme_const, enzyme_dup) help Enzyme control which derivative values are needed for the final computation. In this case, we want to compute the value dx, wrt the change dout, so we mark both as enzyme_active.1

Running the region outlining pass(using enzymemlir-opt --outline-enzyme-regions) outlines the differentiated region inside enzyme.autodiff_region into its own function. In this case, we just expect to see a function which squares it’s input and returns the output. The call to enzyme.autodiff_region is replaced by a call to enzyme.autodiff(which is the op used in Enzyme to differentiate a MLIR function)

// Generated MLIR - the function computing out = x * x is outlined
module {
  func.func @dsq(%arg0: f64, %arg1: f64) -> (f64, f64) {
    %0:2 = enzyme.autodiff @dsq_to_diff0(%arg0, %arg1) 
      <activity = [#enzyme.activity<enzyme_active>], 
       ret_activity = [#enzyme.activity<enzyme_active>]
      > : (f64, f64) -> (f64, f64)
    return %0#0, %0#1 : f64, f64
  }
  func.func private @dsq_to_diff0(%arg0: f64) -> f64 {
    %0 = arith.mulf %arg0, %arg0 : f64
    return %0 : f64
  }
}

The main benefit of working with regions is that a lot of analyses and optimizations that would be inter-procedural become intra-procedural(e.g, region code motion, CSE across multiple invocations of autodiff on the same function, and so on). It is also helpful in enabling context-sensitive optimizations, however, that is not the point of this writeup.2

Outlining regions is a bit more of a challenge, for the same reason why regions are beneficial - it is possible to use values defined above a region inside a region. If you are familiar with C++, this is similar to the notion of an implicit capture inside a lambda function, where you can use the value a[0] (and even modify it inside the lambda)

int a[] = {1,2,3};

auto mod_0 = [&](int x){
  a[0] += x;
  return a[0];
};

printf("%d",mod_0(5)); // prints and sets a[0] to 6

The rest of this writeup is on how we handle these implicit captures in Enzyme. However, before we get to that, this is a quick primer on activity tags (since we will repeatedly see enzyme_const/ enzyme_dup / enzyme_active being used henceforth).

Activity Tags

Activity tags tell Enzyme how to handle derivatives of primal inputs and results. For an input x :

  • enzyme_const - treat x as a constant for this derivative
  • enzyme_dup - in the generated derivative function, pass x together with it’s shadow dx3
  • enzyme_active - return the adjoint dx or supply the adjoint dout in reverse mode

There are more activity tags implemented as attributes in Enzyme-MLIR, however, these tags are enough to understand the rest of this article. In @dsq, these tags apply to x and out. Marking both as enzyme_active means the caller supplies the output seed dout and receives dx = 2 * x * dout

Handling Implicit Captures

As alluded to earlier, a value which is used inside a region op but is defined above it is called an implicit capture. During outlining, we create a new function argument for the captured scalar v and tag its activity as enzyme_const wrt differentiation. It is easier to understand this through an example.

function dvsquare(x,dx,v){
  out, dout = fwddiff_region(x, dx){
    lambda(p){
      q = v * p * p
      yield q
    }
  } <activity x = enzyme_dup>
}

The function dvsquare contains a region op which performs forward mode differentiation on a primal function defined in lambda(p). After outlining, this function signature looks like the example below. Note that the number of activity tags increased from 1 to 2(to account for the increase in the function arguments), and the 2nd argument in the outlined func(the captured value v) is tagged as enzyme_const.


function outlined_vsq(p, v){
  q = v * p * p
  return q
}

function dvsquare(x,dx,v){
  out, dout = enzyme.fwddiff @outlined_vsq((x, dx), v)  
              { <activity enzyme_dup,enzyme_const> }
}

During outlining, the captured scalar v gets its own argument in the newly created function, with activity enzyme_const. This is because Enzyme treats an immutable capture as a constant with respect to differentiation (we just need the value to be well defined in the outlined function, and it is easy to pass the value as a function call argument to it).

Primal Value Captures

The set of implicit captures inside a region op can overlap at times with the values being involved in differentiation (the primal values supplied as args to enzyme.*_region). Reconsider the same example from before, but with the following code.

function dvsquare2(x,dx,v){
  out, dout = fwddiff_region(x, dx){
    lambda(p){ 
      q = v * p * x
      yield q
    }
  } <activity enzyme_dup>
}

dvsquare and dvsquare2 both compute out = v x^2. However, both functions compute different derivative values.

  • dvsquare differentiates v * p * p wrt p, which results in the derivative 2 * v * p * dp. Enzyme forwards (x, dx) to (p, dp) during codegen(since x is tagged as enzyme_dup), which results in dout = 2*v*x*dx.
  • dvsquare2 on the other hand, differentiates v * p * x wrt p, where both v and x are now captured constant values. As a result, dout = v * x * dp. Enzyme again forwards (x,dx) to (p,dp), which results in dout = v*x*dx.

Since x is used twice here(once as a p into lambda(p) and once within the body of lambda(p), we will outline 2 copies of x (one corresponding to the primal, the other corresponding to the implicit capture). The outlined region pseudocode looks like this(with 3 activity tags corresponding to p, v and x).

function outlined_vsq2(p, v, x){
  q = v * p * x
  return q
}

function dvsquare2(x,dx,v){
  out, dout = enzyme.fwddiff @outlined_vsq2((x, dx), v, x)  
              { <activity enzyme_dup, enzyme_const, enzyme_const> }
}

The takeaway here is that we should outline captured immutable values as enzyme_const, even if that means passing repeated primal values to the outlined op. Not doing this can result in correctness bugs. This was seen when differentiating a JAX/StableHLO loop4, which was capturing x the variable being differentiated.

jax.lax.while_loop(lambda x: x < 1.0, 
                   lambda x: jax.grad(lambda y: 3.0 * y * x)(x), 
                   0.2)

Let’s unpack the above expression a bit first. If we first browse the documentation for jax.lax.while_loop, we see that it has the following execution semantics5:

def while_loop(cond_fun, body_fun, init_val):
  val = init_val
  while cond_fun(val):
    val = body_fun(val)
  return val

For the while loop here, we have cond_fun = lambda x: x < 1.0 and body_fun = lambda x: jax.grad(lambda y: 3.0 * y * x)(x) body_fun is a nested lambda, where x is both passed as an argument to y and is used as is in the innermost computation in 3.0 * y * x.

The earlier outlining pass was treating x and y both as the same argument, resulting in an incorrect derivative for the inner body. It first rewrote the function as jax.grad(lambda y: 3.0 * y * y)(x), outlines and lowers the function, resulting in body_func = lambda x: (lambda y: 6.0 * y)(x), further simplifying to body_func = (lambda x: 6.0 * x). The loop can be now represented in canonical python as

while x < 1.0:
  x = 6.0 * x

Substituting x = 0.2 here, we get the next iteration’s value of x as 1.2. Since that is greater than 1.0, cond_fun is false and the while loop returns 1.2 (which is inaccurate!).

After accounting for implicit primal capturing, the new simplified derivative is now body_func = (lambda x: 3.0 * x). This simplifies the JAX loop to

while x < 1.0:
  x = 3.0 * x

resulting in a final of x as 1.8 after 2 iterations (which is the expected result).

Mutable Implicit Captured Values

Enzyme also supports automatic differentiation of mutable memory in MLIR (which are represented by memrefs in MLIR, essentially mutable buffers that you can allocate/read/write/free). Any operation in MLIR can express these memory effects using the MemoryEffectsOpInterface6. The catch here, however is that the caller is responsible for managing shadow memory for mutating pointers (Enzyme by itself will not allocate memory for mutable shadows).

Due to the need for explicit shadow memory management, the proposed outlining pass has to decide if it outlines just a captured buffer value v[] (with activity tag enzyme_const) or (v[], dv[]) (with activity tag enzyme_dup). Depending on the case, the pass may also have to allocate/deallocate shadow memory for dv[]

Again, going by example:

function dvsquare3(x,dx){
  v = [2.0, 3.0] // this is a mutable array
  out, dout = fwddiff_region(x, dx){
    lambda(p){
      q = v[0] * p * p
      yield q
    }
  } <activity enzyme_dup>
}

dvsquare3 computes out = v[0]*x*x(unlike the earlier examples, v is an implicitly captured buffer/pointer) and dout = 2*v[0]*x*dx.

For both the primal(out) and the derivative(dout) computation, we read from the same buffer here (v[0]). Since we are only reading values from v[], there is no need for a shadow buffer dv[], so we can simply outline only v[] with activity tag enzyme_const.

What happens if we write to v[] ?

Writes to a captured value necessitates creation of shadow memory for it. Consider the following example, where we write to v[0].

function dvsquare4(x,dx){
  v = [2.0, 3.0]
  out, dout = fwddiff_region(x, dx){
    lambda(p){
      v[0] = p
      q = v[0] * p * p
      yield q
    }
  } <activity enzyme_dup>
}

dvsquare4 writes the value p to v[0] before reading from v[0] again inside lambda(p). The function now computes out = x*x*x, stores v[0]=x and computes dout = 3*x*x*dx.

To figure out if we need dv[] here, let’s walk lambda(p) forwards, applying the chain rule along the way(similar to how Enzyme itself differentiates this function7):

  1. v[0] = p - Since p is active, this also means that v[0] has a defined derivative dv[0]. We store dv[0] = dp
  2. q = v[0]*p*p - We apply the chain rule for multiplication here to get dq = dv[0]*p*p + v[0]*dp*p + v[0]*p*dp = dv[0]*p*p + 2*v[0]*p*dp. From the earlier results, we know that v[0] = p and dv[0] = dp. This simplifies dq = dp*p*p+p*dp*p+p*p*dp = 3*p*p*dp
  3. Once we have the final expression for dq = 3*p*p*dp, since the activity tag for x is enzyme_dup, we forward (x,dx) -> (p,dp) and (q, dq) -> (out, dout), resulting in out = x*x*x and dout = 3*x*x*dx (which is the correct result!)

To be a bit more precise, we need to initialize shadow memory for v[] only because we are writing a active differentiable value to it (in this case p). To make this clear, say, for example, instead of v[0] = p in dvsquare4, we stored a constant value v[0] = 4.5.

  1. v[0] = 4.5 now computes dv[0] = 0.0 instead of dv[0] = dp.
  2. q = v[0]*p*p now computes dq = 2*v[0]*p*dp, which only reads from v[] and doesn’t need dv[]

It is possible to run activity analysis on lambda(p) to figure out if we really need dv[] here. However, for the purposes of outlining, it is correct to always emit dv[] if there is any write to v[]. We can run an optimization pass like EnzymeActivityOpt8 post-outlining to optimize away dv[] with a targeted rewrite and change its activity tag from enzyme_dup to enzyme_const.

To summarize, even if we restrict ourselves to just read and write effects, the outlining algorithm is now just:

for every mutable captured value v:
  e(v) <- collect memory effects inside primal function for v
  if e(v) contains a write:
    allocate storage for dv[] before the region
    initialize dv[] to either 0 or the derivative of the buffer it points to
    outline (v, dv) and mark its activity as enzyme_dup
    deallocate storage for dv[] after autodiff/fwddiff call
  else if e(v) only has reads:
    outline v[] and mark its activity as enzyme_const

Handling Aliasing for Mutable Values

If the captured mutable value does not alias with any of the operands to the region op (i.e, we are not differentiating wrt the value contained in its buffer), then it’s fine to outline the capture according to the previously mentioned outlining algorithm.

However, sometimes, it is possible for the captured values to alias with the operands to the region op. For example:

function dvsquare5(x[],dx[]){
  v <- x // points to x
  out, dout = fwddiff_region(x, dx){
    lambda(p[]){
      v[0] = p[0]*p[0]
      q = v[0] * p[0] * p[0]
      yield q
    }
  } <activity enzyme_dup>
}

In dvsquare5, buffer v[] points to the same underlying storage as x[] (MustAlias(v,x) is true). The function first overwrites the value at v[0] and updates it to x[0]*x[0]. This in turn also updates x[0] itself (since v[] and x[] point to the same location). Say x_old and dx_old are the values of x[0] and dx[0] before the store. We then compute out = x_old^6 with the corresponding derivative dout = 6*x_old^5*dx_old. Since x[0] is mutated, dx[0] = 2*x_old*dx_old after the region op executes.

If we run the outlining algorithm as described earlier, we will allocate a new shadow dv[], which initially copies the value in dx[]. However, allocating a new shadow dv[] for v[] is wrong here, since a write to v[] also ensures a write to x[], but if dv[] and dx[] point to different memory locations, then a write to dv will not be reflected in dx. So in this case, even if we have a write to a captured value, if it aliases with a operand of the region op, we need to reuse the storage for that region op. This can be seen if we work out the execution flow for the derivative step by step here.

  1. v[0]=p[0]*p[0] - We generate dv[0] = 2*p[0]*dp[0].
  2. q = v[0]*p[0]*p[0] - We generate dq = dv[0]*p[0]*p[0] + 2*v[0]*p[0]*dp[0]
  3. Enzyme applies the activity tag enzyme_dup, so (x[],dx[]) -> (p[],dp[]) at the call.
  4. Let x_old and dx_old be the incoming values of x[0] and dx[0]. We execute v[0] = x_old^2 and dv[0] = 2*x_old*dx_old. The next load through p[0] sees x_old^2, since v[] aliases x[]. The next load through dp[0] still sees dx_old, since dv[] has its own storage.
  5. We now execute q = x_old^6 and dq = 2*x_old^5*dx_old + 2*x_old^4*dx_old, which is the wrong derivative!! (for x_old = 2 and dx_old = 1, we expected 192 but got 96).

Now replace the captured v[] with x[] and use dx[] as its shadow.

  1. x[0] = p[0]*p[0] - We generate dx[0] = 2*p[0]*dp[0] using the values before the store.
  2. q = x[0]*p[0]*p[0] - We generate dq = dx[0]*p[0]*p[0] + 2*x[0]*p[0]*dp[0].
  3. Enzyme applies the activity tag enzyme_dup, so (x[],dx[]) -> (p[],dp[]) at the call.
  4. Let x_old and dx_old be the incoming values of x[0] and dx[0]. We execute x[0] = x_old^2 and dx[0] = 2*x_old*dx_old. The next loads through p[0] and dp[0] see those updated values.
  5. We now compute q = (x_old^2)^3 = x_old^6 and dq = 2*x_old^5*dx_old + 4*x_old^5*dx_old = 6*x_old^5*dx_old.

This leads us to the conclusion, that if the captured value v strictly aliases(a must alias check) any operand x, and x is active in differentiation, then we reuse the storage for dx and replace all uses of v with x (it is safe to do so, since they must alias).

When the captured value v may alias (note that this is more relaxed than a must alias check) with an operand x, we can still go ahead with outlining v as enzyme_const, provided that x itself is enzyme_const and both buffers are readonly. If x is differentiable, even a read from v is ambiguous here. For example, yield v[0] gives dout = dx[0] if v[0] and x[0] are the same memory location, and dout = 0 if v is a separate readonly buffer. So we fail outlining in this case. We also fail if either buffer may be written to, since a write through one could be read through the other.

The same strict alias condition also holds true for any pair of captured buffers v and w(disjoint from the region’s operands). Consider the following example

function dvsquare6(x,dx){
  v[] = {2.0}
  w <- v // points to v
  out, dout = fwddiff_region(x, dx){
    lambda(p){
      v[0] = p*p
      yield w[0]
    }
  } <activity enzyme_dup>
}

Since we write to v[], we need to allocate a shadow dv[] for it. However, since v[] and w[] are strict aliases here, this means that they need to share the same storage for both the primal and the shadow, resulting in out = x^2 and dout = 2*x*dx (with v[0]=w[0]=x^2 and dv[0]=dw[0]=2*x*dx).

When v and w may alias, if both v and w are readonly, then we can still go ahead and outline both buffers with activity enzyme_const. If any buffer has a write, then it’s again an ambiguous case (since we are not sure if both v and w should share the same buffer or use separate buffers for dv[] and dw[]).

As before, we only consider read and write effects here. If we cannot determine these effects, if primal operands for the same buffer disagree on its shadow, or if a newly allocated dv[] is still needed after the call, we fail outlining.

The final pseudocode for outlining thus becomes:

for every pair of captured buffers v and w that must alias (the same view):
  replace captured uses of w with v

for every remaining mutable captured value v:
  e(v) <- collect memory effects inside the primal function for v and its aliases
  for every other capture or primal buffer w where alias(v,w) == MayAlias:
    if either buffer has a shadow from a primal operand or either may be written to:
      fail outlining
  if e(v) contains a write and v is also accessed through an enzyme_const primal operand:
    fail outlining

  if v must alias a differentiable primal operand x:
    replace captured uses of v with x and reuse dx[] as the shadow for v
  else if e(v) contains a write:
    allocate storage for dv[] before the region and initialize it to 0
    outline (v, dv) and mark its activity as enzyme_dup
    deallocate storage for dv[] after autodiff/fwddiff call
  else if e(v) only has reads:
    outline v[] and mark its activity as enzyme_const
Cite this article (BibTeX)
@misc{sathia2026regionoutlining,
  author = {Sathia, Vimarsh},
  title  = {An Algorithm for Differentiable Region Outlining in {Enzyme}},
  year   = {2026},
  url    = {https://vimarsh.net/blog/2026/12/02/region-outlining/}
}

Footnotes

  1. Activities can be thought of as a tag which help Enzyme perform activity analysis. At it’s core, activity analysis is a static analysis which identifies which operations would be unnecessary in a generated derivative program(and thus avoids differentiating them). More details on how Enzyme’s activity analysis works(and its formal semantics) are specified in this paper on formalizing activity analysis ↩

  2. A lot of the arguments for why function inlining is beneficial also holds for the region op (with the caveat being that the code inside the region op is the state of the code before differentiation). ↩

  3. shadow here refers to the derivative value (e.g, the shadow of x is dx: the shadow of x[1] is dx[1]…) ↩

  4. https://github.com/EnzymeAD/Enzyme-JAX/issues/3204 ↩

  5. JAX documentation of jax.lax.while_loop ↩

  6. MemoryEffectsOpInterface and other side-effect interfaces are defined in upstream LLVM using TableGen at SideEffectInterfaces.td. ↩

  7. My view of Enzyme is that it is simply an interface which implements the chain rule of differentiation for you (in both forward mode and reverse). You can look at the hot loop where Enzyme walks through all ops serially for forward mode AD here and checks if the current operation we are differentiating implements the AutoDiffOpInterface ↩

  8. The goal of EnzymeActivityOpt is to optimize the assignment of activity tags to a differentiated function in order to optimize the usage of intermedate scratch values during differentiation. It uses various tactics like checking uses, known values and the results of activity analysis to determine an optimal assignment for a primal function. Link to Source code and a talk at LLVMDev-2026 on how it works ↩

Updated: