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

当即时执行时(在 jit 之外),JAX 代码与 Numpy 代码一样,可以使用 Python 控制流和逻辑运算符。但在 jit 中使用控制流和逻辑运算符会更复杂。

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

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
      5   else:
      6     return -4 * x
      7 
      8 # This will fail!
----> 9 f(2)

    [... skipping hidden 5 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:
      6     return -4 * x

    [... skipping hidden 1 frame]

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

TracerBoolConversionError: Attempted boolean conversion of traced array with shape bool[].
The error occurred while tracing the function f at /tmp/ipykernel_1620/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
      2 def g(x):
      3   return (x > 0) and (x < 3)
      4 
      5 # This will fail!
----> 6 g(2)

    [... skipping hidden 5 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.12/site-packages/jax/_src/core.py:1891, in concretization_function_error.<locals>.error(self, arg)
   1890 def error(self, arg):
-> 1891   raise TracerBoolConversionError(arg)

TracerBoolConversionError: Attempted boolean conversion of traced array with shape bool[].
The error occurred while tracing the function g at /tmp/ipykernel_1620/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 抽象作为输入对其进行追踪,其中每个抽象值代表了所有具有固定形状和数据类型的数组值的集合。例如,如果我们使用抽象值 ShapedArray((3,), jnp.float32) 进行追踪,我们将得到一个可用于相应数组集合中任何具体值的函数视图。这意味着我们可以节省编译时间。

但这里存在一个权衡:如果我们对一个未指定具体值的 ShapedArray((), jnp.float32) 追踪一个 Python 函数,当遇到类似 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 5 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.12/site-packages/jax/_src/numpy/array_creation.py:138, in ones(shape, dtype, device, out_sharding)
    136   raise TypeError("expected sequence object with len >= 0 or a single integer")
    137 if (m := _check_forgot_shape_tuple("ones", shape, dtype)): raise TypeError(m)
--> 138 shape = canonicalize_shape(shape)
    139 dtype = dtypes.check_and_canonicalize_user_dtype(
    140     float if dtype is None else dtype, "ones")
    141 sharding = util.choose_device_or_out_sharding(
    142     device, out_sharding, 'jnp.ones')

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

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

TypeError: Shapes must be 1D sequences of concrete values of integer type, got (JitTracer(~int32[]),).
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_1620/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)
JitTracer(~int32[])
JitTracer(~int32[])
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 的 API 类似于 jnp.piecewise,但选择项是作为预先计算好的数组提供的,而不是函数。它是通过多次调用 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{结构} & \textrm{jit} & \textrm{grad} \\ \hline \ \textrm{if} & ❌ & ✔ \\ \textrm{for} & ✔* & ✔\\ \textrm{while} & ✔* & ✔\\ \textrm{lax.cond} & ✔ & ✔\\ \textrm{lax.while_loop} & ✔ & \textrm{前向}\\ \textrm{lax.fori_loop} & ✔ & \textrm{前向}\\ \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)
      1 def 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.12/site-packages/jax/_src/array.py:295, in ArrayImpl.__bool__(self)
    294 def __bool__(self):
--> 295   core.check_bool_conversion(self)
    296   return bool(self._value)

File ~/checkouts/readthedocs.org/user_builds/jax/envs/latest/lib/python3.12/site-packages/jax/_src/core.py:869, in check_bool_conversion(arr)
    866   raise ValueError("The truth value of an empty array is ambiguous. Use"
    867                    " `array.size > 0` to check that an array is not empty.")
    868 if arr.size > 1:
--> 869   raise ValueError("The truth value of an array with more than one element"
    870                    " 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