jax.lax.while_loop#
- jax.lax.while_loop(cond_fun, body_fun, init_val)[源代码]#
当
cond_fun
为 True 时,在循环中重复调用body_fun
。简而言之,类似于 Haskell 的类型签名是
while_loop :: (a -> Bool) -> (a -> a) -> a -> a
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
与 Python 版本不同,
while_loop
是一个 JAX 原语,并被降低为单个 WhileOp。这使得它对于减少 jit 编译函数的编译时间很有用,因为@jit
函数中的原生 Python 循环结构会被展开,从而导致大型 XLA 计算。同样与 Python 版本不同,循环携带的值
val
在所有迭代中必须保持固定的形状和 dtype(而不仅仅是在 NumPy 秩/形状广播和 dtype 提升规则下保持一致)。换句话说,上面的类型签名中的类型a
表示具有固定形状和 dtype 的数组(或具有固定结构和叶子处具有固定形状和 dtype 数组的嵌套元组/列表/字典容器数据结构)。与使用 Python 原生循环结构相比,另一个不同之处在于
while_loop
不支持反向模式求导,因为 XLA 计算需要在内存需求上具有静态边界。注意
while_loop()
会编译cond_fun
和body_fun
,因此虽然它可以与jit()
结合使用,但通常是不必要的。- 参数:
cond_fun (Callable[[T], BooleanNumeric]) – 类型为
a -> Bool
的函数。body_fun (Callable[[T], T]) – 类型为
a -> a
的函数。init_val (T) – 类型为
a
的值,该类型可以是标量、数组或任何 pytree(嵌套的 Python 元组/列表/字典),表示初始循环携带值。
- 返回:
来自 body_fun 最后一次迭代的输出,类型为
a
。- 返回类型:
T