netket.jax.apply_packed

Contents

netket.jax.apply_packed#

netket.jax.apply_packed(f, pars, x, where, fill, *, chunk_size, min_chunk_size=None, axis_0_is_sharded=None)[source]#

Row-wise jnp.where(where, f(pars, x), fill), evaluating f only on the rows where where is True.

Warning

This function is experimental: it is public, but it can change in a minor release of NetKet, with a note in the changelog.

The selected rows are packed into chunks of a few static sizes, so that a number of selected rows that changes from call to call does not trigger a recompilation. f must be row-wise: the rows of its output must only depend on the corresponding rows of its input. It does not need to be defined on the rows that are not selected.

If where has shape (n, m), every row of x has m slots, and f(pars, x_rows, slots) is evaluated on the selected pairs of a row and a slot, with slots the integer indices of the slots. This evaluates functions of the pairs that are cheaper to compute on the fly than to store, such as the connected configurations of an operator.

The function is differentiable.

Parameters:
  • f (Callable) – the function to evaluate, f(pars, x_rows) or f(pars, x_rows, slots).

  • pars (Any) – the arguments of f that are the same for all rows.

  • x (Any) – a pytree of arrays with n rows.

  • where (Union[ndarray, Array]) – the boolean mask, of shape (n,) or (n, m), of the rows (or of the pairs of a row and a slot) on which f is evaluated.

  • fill (Any) – the values of the other rows, a pytree like the output of f whose leaves are broadcastable to the output.

  • chunk_size (int | None) – the number of rows on which f is evaluated at once (where.size / 16 if None).

  • min_chunk_size (int | None) – the size of the smallest chunk (chunk_size // 8 if None). Every chunk size is compiled separately.

  • axis_0_is_sharded (bool | None) – whether axis 0 of x, where and fill is sharded among the devices, and every device should pack its own rows. Defaults to netket.config.netket_sharding.

Return type:

Any

Returns:

A pytree like the output of f, with leaves of shape where.shape + leaf.shape[1:].

Examples

Scale the sum of every row, evaluating f only on the first and the last row, and setting the others to zero:

>>> import jax.numpy as jnp
>>> import netket as nk
>>> def f(pars, x):
...     return pars * x.sum(axis=-1)
>>> x = jnp.arange(8.0).reshape(4, 2)
>>> where = jnp.array([True, False, False, True])
>>> nk.jax.apply_packed(f, 2.0, x, where, 0.0, chunk_size=2)
Array([ 2.,  0.,  0., 26.], dtype=float64)