控制流和带 JIT 的逻辑运算符#

当以 eager 模式执行(在 jit 之外)时,JAX 代码与 Python 控制流和逻辑运算符的工作方式与 Numpy 代码完全相同。将控制流和逻辑运算符与 jit 结合使用则更为复杂。

简而言之,Python 控制流和逻辑运算符在 JIT 编译时进行求值,因此编译后的函数表示通过控制流图的单条路径(逻辑运算符通过短路影响路径)。如果路径取决于输入的值,则函数(默认情况下)无法进行 JIT 编译。路径可能取决于输入的形状或 dtype,并且每次在具有新形状或 dtype 的输入上调用函数时,都会重新编译该函数。

from jax import grad, jit
import jax.numpy as jnp

例如,这可以工作

@jit
def f(x):
  for i in range(3):
    x = 2 * x
  return x

print(f(3))
24

这个也可以

@jit
def g(x):
  y = 0.
  for i in range(x.shape[0]):
    y = y + x[i]
  return y

print(g(jnp.array([1., 2., 3.])))
6.0

但这个不行,至少默认情况下不行

@jit
def f(x):
  if x < 3:
    return 3. * x ** 2
  else:
    return -4 * x

# This will fail!
f(2)
---------------------------------------------------------------------------
TracerBoolConversionError                 Traceback (most recent call last)
Cell In[4], line 9
      6     return -4 * x
      8 # This will fail!
----> 9 f(2)

    [... skipping hidden 14 frame]

Cell In[4], line 3, in f(x)
      1 @jit
      2 def f(x):
----> 3   if x < 3:
      4     return 3. * x ** 2
      5   else:

    [... skipping hidden 1 frame]

File ~/checkouts/readthedocs.org/user_builds/jax/envs/latest/lib/python3.10/site-packages/jax/_src/core.py:1587, in concretization_function_error.<locals>.error(self, arg)
   1586 def error(self, arg):
-> 1587   raise TracerBoolConversionError(arg)

TracerBoolConversionError: Attempted boolean conversion of traced array with shape bool[].
The error occurred while tracing the function f at /tmp/ipykernel_864/3402096563.py:1 for jit. This concrete value was not available in Python because it depends on the value of the argument x.
See https://docs.jax.dev/en/latest/errors.html#jax.errors.TracerBoolConversionError

这个也不行

@jit
def g(x):
  return (x > 0) and (x < 3)

# This will fail!
g(2)
---------------------------------------------------------------------------
TracerBoolConversionError                 Traceback (most recent call last)
Cell In[5], line 6
      3   return (x > 0) and (x < 3)
      5 # This will fail!
----> 6 g(2)

    [... skipping hidden 14 frame]

Cell In[5], line 3, in g(x)
      1 @jit
      2 def g(x):
----> 3   return (x > 0) and (x < 3)

    [... skipping hidden 1 frame]

File ~/checkouts/readthedocs.org/user_builds/jax/envs/latest/lib/python3.10/site-packages/jax/_src/core.py:1587, in concretization_function_error.<locals>.error(self, arg)
   1586 def error(self, arg):
-> 1587   raise TracerBoolConversionError(arg)

TracerBoolConversionError: Attempted boolean conversion of traced array with shape bool[].
The error occurred while tracing the function g at /tmp/ipykernel_864/543860509.py:1 for jit. This concrete value was not available in Python because it depends on the value of the argument x.
See https://docs.jax.dev/en/latest/errors.html#jax.errors.TracerBoolConversionError

怎么回事!?

当我们 jit-编译一个函数时,我们通常希望编译一个适用于许多不同参数值的函数版本,以便我们可以缓存和重用编译后的代码。这样我们就无需在每次函数求值时重新编译。

例如,如果我们对数组 jnp.array([1., 2., 3.], jnp.float32) 求值一个 @jit 函数,我们可能希望编译可以重用的代码,以求值 jnp.array([4., 5., 6.], jnp.float32) 上的函数,从而节省编译时间。

为了获得适用于许多不同参数值的 Python 代码视图,JAX 使用 ShapedArray 抽象作为输入来追踪它,其中每个抽象值表示具有固定形状和 dtype 的所有数组值的集合。例如,如果我们使用抽象值 ShapedArray((3,), jnp.float32) 进行追踪,我们将获得一个函数视图,该视图可以重用于相应数组集合中的任何具体值。这意味着我们可以节省编译时间。

但是这里有一个权衡:如果我们追踪一个 Python 函数,该函数在 ShapedArray((), jnp.float32) 上没有提交给特定的具体值,当我们命中像 if x < 3 这样的行时,表达式 x < 3 求值为抽象的 ShapedArray((), jnp.bool_),它表示集合 {True, False}。当 Python 尝试将其强制转换为具体的 TrueFalse 时,我们会收到错误:我们不知道要采用哪个分支,并且无法继续追踪!权衡是,通过更高级别的抽象,我们获得了 Python 代码的更通用视图(从而节省了重新编译),但是我们需要对 Python 代码施加更多约束才能完成追踪。

好消息是,您可以自己控制这种权衡。通过让 jit 在更精细的抽象值上进行追踪,您可以放宽可追踪性约束。例如,使用 jitstatic_argnames(或 static_argnums)参数,我们可以指定追踪某些参数的具体值。这是再次出现的示例函数

def f(x):
  if x < 3:
    return 3. * x ** 2
  else:
    return -4 * x

f = jit(f, static_argnames='x')

print(f(2.))
12.0

这是另一个示例,这次涉及循环

def f(x, n):
  y = 0.
  for i in range(n):
    y = y + x[i]
  return y

f = jit(f, static_argnames='n')

f(jnp.array([2., 3., 4.]), 2)
Array(5., dtype=float32)

实际上,循环被静态展开了。JAX 也可以在更高的抽象级别(例如 Unshaped)进行追踪,但这目前不是任何转换的默认设置

️⚠️ 具有参数-相关形状的函数

这些控制流问题也以更微妙的方式出现:我们想要 jit 的数值函数不能专门化内部数组的形状以适应参数(专门化参数形状是可以的)。作为一个简单的例子,让我们创建一个函数,其输出恰好取决于输入变量 length

def example_fun(length, val):
  return jnp.ones((length,)) * val
# un-jit'd works fine
print(example_fun(5, 4))
[4. 4. 4. 4. 4.]
bad_example_jit = jit(example_fun)
# this will fail:
bad_example_jit(10, 4)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[9], line 3
      1 bad_example_jit = jit(example_fun)
      2 # this will fail:
----> 3 bad_example_jit(10, 4)

    [... skipping hidden 14 frame]

Cell In[8], line 2, in example_fun(length, val)
      1 def example_fun(length, val):
----> 2   return jnp.ones((length,)) * val

File ~/checkouts/readthedocs.org/user_builds/jax/envs/latest/lib/python3.10/site-packages/jax/_src/numpy/array_creation.py:115, in ones(shape, dtype, device)
    113   raise TypeError("expected sequence object with len >= 0 or a single integer")
    114 if (m := _check_forgot_shape_tuple("ones", shape, dtype)): raise TypeError(m)
--> 115 shape = canonicalize_shape(shape)
    116 dtypes.check_user_dtype_supported(dtype, "ones")
    117 return lax.full(shape, 1, dtypes.jax_dtype(dtype), sharding=util.normalize_device_to_sharding(device))

File ~/checkouts/readthedocs.org/user_builds/jax/envs/latest/lib/python3.10/site-packages/jax/_src/numpy/array_creation.py:41, in canonicalize_shape(shape, context)
     39   return core.canonicalize_shape((shape,), context)
     40 else:
---> 41   return core.canonicalize_shape(shape, context)

File ~/checkouts/readthedocs.org/user_builds/jax/envs/latest/lib/python3.10/site-packages/jax/_src/core.py:1739, in canonicalize_shape(shape, context)
   1737 except TypeError:
   1738   pass
-> 1739 raise _invalid_shape_error(shape, context)

TypeError: Shapes must be 1D sequences of concrete values of integer type, got (Traced<ShapedArray(int32[], weak_type=True)>with<DynamicJaxprTrace>,).
If using `jit`, try using `static_argnums` or applying `jit` to smaller subfunctions.
The error occurred while tracing the function example_fun at /tmp/ipykernel_864/1210496444.py:1 for jit. This concrete value was not available in Python because it depends on the value of the argument length.
# static_argnames tells JAX to recompile on changes at these argument positions:
good_example_jit = jit(example_fun, static_argnames='length')
# first compile
print(good_example_jit(10, 4))
# recompiles
print(good_example_jit(5, 4))
[4. 4. 4. 4. 4. 4. 4. 4. 4. 4.]
[4. 4. 4. 4. 4.]

如果示例中的 length 很少更改,则 static_argnames 可能会很方便,但是如果它经常更改,那将是灾难性的!

最后,如果您的函数具有全局副作用,则 JAX 的追踪器可能会导致奇怪的事情发生。一个常见的陷阱是尝试在 jit 函数内部打印数组

@jit
def f(x):
  print(x)
  y = 2 * x
  print(y)
  return y
f(2)
Traced<ShapedArray(int32[], weak_type=True)>with<DynamicJaxprTrace>
Traced<ShapedArray(int32[], weak_type=True)>with<DynamicJaxprTrace>
Array(4, dtype=int32, weak_type=True)

结构化控制流原语#

JAX 中有更多控制流选项。假设您要避免重新编译,但仍然想使用可追踪的控制流,并避免展开大型循环。那么您可以使用以下 4 个结构化控制流原语

  • lax.cond 可微分

  • lax.while_loop 前向模式可微分

  • lax.fori_loop 通常是前向模式可微分的;如果端点是静态的,则是前向和反向模式可微分的。

  • lax.scan 可微分

cond#

python 等价物

def cond(pred, true_fun, false_fun, operand):
  if pred:
    return true_fun(operand)
  else:
    return false_fun(operand)
from jax import lax

operand = jnp.array([0.])
lax.cond(True, lambda x: x+1, lambda x: x-1, operand)
# --> array([1.], dtype=float32)
lax.cond(False, lambda x: x+1, lambda x: x-1, operand)
# --> array([-1.], dtype=float32)
Array([-1.], dtype=float32)

jax.lax 提供了另外两个函数,允许在动态谓词上进行分支

  • lax.select 类似于 lax.cond 的批量版本,选择表示为预先计算的数组,而不是函数。

  • lax.switch 类似于 lax.cond,但允许在任意数量的可调用选择之间切换。

此外,jax.numpy 提供了这些函数的几个 numpy 风格的接口

  • jnp.where 与三个参数是 lax.select 的 numpy 风格的包装器。

  • jnp.piecewiselax.switch 的 numpy 风格的包装器,但它在一系列布尔条件而不是单个标量索引上切换。

  • jnp.select 具有类似于 jnp.piecewise 的 API,但选择是作为预先计算的数组而不是函数给出。它通过多次调用 lax.select 来实现。

while_loop#

python 等价物

def while_loop(cond_fun, body_fun, init_val):
  val = init_val
  while cond_fun(val):
    val = body_fun(val)
  return val
init_val = 0
cond_fun = lambda x: x < 10
body_fun = lambda x: x+1
lax.while_loop(cond_fun, body_fun, init_val)
# --> array(10, dtype=int32)
Array(10, dtype=int32, weak_type=True)

fori_loop#

python 等价物

def fori_loop(start, stop, body_fun, init_val):
  val = init_val
  for i in range(start, stop):
    val = body_fun(i, val)
  return val
init_val = 0
start = 0
stop = 10
body_fun = lambda i,x: x+i
lax.fori_loop(start, stop, body_fun, init_val)
# --> array(45, dtype=int32)
Array(45, dtype=int32, weak_type=True)

总结#

\[\begin{split} \begin{array} {r|rr} \hline \ \textrm{construct} & \textrm{jit} & \textrm{grad} \\ \hline \ \textrm{if} & ❌ & ✔ \\ \textrm{for} & ✔* & ✔\\ \textrm{while} & ✔* & ✔\\ \textrm{lax.cond} & ✔ & ✔\\ \textrm{lax.while_loop} & ✔ & \textrm{fwd}\\ \textrm{lax.fori_loop} & ✔ & \textrm{fwd}\\ \textrm{lax.scan} & ✔ & ✔\\ \hline \end{array} \end{split}\]

\(\ast\) = 参数--独立的循环条件 - 展开循环

逻辑运算符#

jax.numpy 提供了 logical_andlogical_orlogical_not,它们在数组上逐元素操作,并且可以在 jit 下求值而无需重新编译。与它们的 Numpy 对应物一样,二元运算符不短路。按位运算符(&|~)也可以与 jit 一起使用。

例如,考虑一个函数,该函数检查其输入是否为正偶数整数。当输入为标量时,纯 Python 和 JAX 版本给出相同的答案。

def python_check_positive_even(x):
  is_even = x % 2 == 0
  # `and` short-circults, so when `is_even` is `False`, `x > 0` is not evaluated.
  return is_even and (x > 0)

@jit
def jax_check_positive_even(x):
  is_even = x % 2 == 0
  # `logical_and` does not short circuit, so `x > 0` is always evaluated.
  return jnp.logical_and(is_even, x > 0)

print(python_check_positive_even(24))
print(jax_check_positive_even(24))
True
True

当具有 logical_and 的 JAX 版本应用于数组时,它返回逐元素的值。

x = jnp.array([-1, 2, 5])
print(jax_check_positive_even(x))
[False  True False]

即使没有 jit,Python 逻辑运算符在应用于多个元素的 JAX 数组时也会出错。这复制了 NumPy 的行为。

print(python_check_positive_even(x))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[17], line 1
----> 1 print(python_check_positive_even(x))

Cell In[15], line 4, in python_check_positive_even(x)
      2 is_even = x % 2 == 0
      3 # `and` short-circults, so when `is_even` is `False`, `x > 0` is not evaluated.
----> 4 return is_even and (x > 0)

File ~/checkouts/readthedocs.org/user_builds/jax/envs/latest/lib/python3.10/site-packages/jax/_src/array.py:306, in ArrayImpl.__bool__(self)
    305 def __bool__(self):
--> 306   core.check_bool_conversion(self)
    307   return bool(self._value)

File ~/checkouts/readthedocs.org/user_builds/jax/envs/latest/lib/python3.10/site-packages/jax/_src/core.py:716, in check_bool_conversion(arr)
    713   raise ValueError("The truth value of an empty array is ambiguous. Use"
    714                    " `array.size > 0` to check that an array is not empty.")
    715 if arr.size > 1:
--> 716   raise ValueError("The truth value of an array with more than one element"
    717                    " is ambiguous. Use a.any() or a.all()")

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Python 控制流 + 自动微分#

请记住,以上关于控制流和逻辑运算符的约束仅与 jit 相关。如果您只想将 grad 应用于您的 python 函数,而无需 jit,则可以使用常规的 Python 控制流结构,而不会出现问题,就像您在使用 Autograd(或 Pytorch 或 TF Eager)一样。

def f(x):
  if x < 3:
    return 3. * x ** 2
  else:
    return -4 * x

print(grad(f)(2.))  # ok!
print(grad(f)(4.))  # ok!
12.0
-4.0