2022-09-22 12:26:48 -07:00
|
|
|
# Copyright 2021 The JAX Authors.
|
2021-06-03 21:55:39 -07:00
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# https://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
2023-04-05 14:09:46 -07:00
|
|
|
from __future__ import annotations
|
2021-06-03 21:55:39 -07:00
|
|
|
|
2024-06-26 14:44:52 -04:00
|
|
|
from collections.abc import Callable, Iterator, Sequence
|
2022-10-28 14:39:00 -07:00
|
|
|
from functools import partial, reduce
|
2023-02-28 12:40:30 -08:00
|
|
|
import math
|
2022-09-08 13:45:06 -07:00
|
|
|
import operator as op
|
2024-06-26 14:44:52 -04:00
|
|
|
from typing import Any, NamedTuple
|
2021-06-03 21:55:39 -07:00
|
|
|
|
|
|
|
import numpy as np
|
|
|
|
|
2023-09-12 13:46:22 -07:00
|
|
|
import jax
|
2021-06-03 21:55:39 -07:00
|
|
|
from jax import lax
|
|
|
|
from jax import numpy as jnp
|
2023-05-01 14:17:01 -07:00
|
|
|
from jax import tree_util
|
2022-08-22 13:56:50 -07:00
|
|
|
|
2023-10-10 16:15:19 -07:00
|
|
|
from jax._src import api_util
|
2023-04-04 11:41:00 -07:00
|
|
|
from jax._src import api
|
2023-10-09 07:28:18 -07:00
|
|
|
from jax._src import config as config
|
2022-12-16 20:59:41 -08:00
|
|
|
from jax._src import core
|
2022-08-22 13:56:50 -07:00
|
|
|
from jax._src import dispatch
|
|
|
|
from jax._src import dtypes
|
2022-12-16 20:59:41 -08:00
|
|
|
from jax._src import pretty_printer as pp
|
2024-03-21 13:34:26 -07:00
|
|
|
from jax._src import source_info_util
|
2023-09-13 09:43:14 -07:00
|
|
|
from jax._src import tree_util as tree_util_internal
|
2023-04-04 11:41:00 -07:00
|
|
|
from jax._src import typing
|
2021-09-23 06:33:25 -07:00
|
|
|
from jax._src.api import jit, vmap
|
2023-04-04 11:41:00 -07:00
|
|
|
from jax._src.dtypes import float0
|
2023-02-06 22:51:50 -08:00
|
|
|
from jax._src.interpreters import ad
|
2023-02-09 15:11:20 -08:00
|
|
|
from jax._src.interpreters import batching
|
|
|
|
from jax._src.interpreters import mlir
|
|
|
|
from jax._src.interpreters import pxla
|
2023-03-31 08:50:59 -07:00
|
|
|
from jax._src.interpreters import xla
|
2022-03-07 12:25:01 -08:00
|
|
|
from jax._src.lax import lax as lax_internal
|
2024-05-01 10:32:36 -07:00
|
|
|
from jax._src.lib import gpu_prng
|
2023-05-17 14:47:22 -07:00
|
|
|
from jax._src.lib import xla_client as xc
|
2024-05-01 10:32:36 -07:00
|
|
|
from jax._src.lib.mlir import ir
|
2022-12-15 20:59:34 -08:00
|
|
|
from jax._src.lib.mlir.dialects import hlo
|
2023-04-26 11:25:25 -07:00
|
|
|
from jax._src.numpy.array_methods import (
|
|
|
|
_array_operators, _set_array_base_attributes, _IndexUpdateHelper)
|
2023-03-13 08:49:39 -07:00
|
|
|
from jax._src.sharding_impls import (
|
2024-06-03 14:52:08 -07:00
|
|
|
NamedSharding, PmapSharding, physical_sharding, logical_sharding)
|
2023-03-14 08:32:21 -07:00
|
|
|
from jax._src.typing import Array
|
2023-04-24 15:06:22 -07:00
|
|
|
from jax._src.util import safe_map, safe_zip
|
2022-05-05 10:54:53 -07:00
|
|
|
|
2022-08-22 13:56:50 -07:00
|
|
|
map, unsafe_map = safe_map, map
|
|
|
|
zip, unsafe_zip = safe_zip, zip
|
|
|
|
|
2023-05-17 14:47:22 -07:00
|
|
|
Device = xc.Device
|
2023-06-01 04:10:12 -07:00
|
|
|
Shard = Any # TODO(jakevdp): fix circular imports and import Shard
|
2023-07-06 13:23:48 -07:00
|
|
|
Shape = tuple[int, ...]
|
2021-06-03 21:55:39 -07:00
|
|
|
|
|
|
|
UINT_DTYPES = {
|
2024-05-17 09:46:36 +01:00
|
|
|
8: jnp.uint8, 16: jnp.uint16, 32: jnp.uint32, 64: jnp.uint64}
|
2021-06-03 21:55:39 -07:00
|
|
|
|
2022-08-22 13:56:50 -07:00
|
|
|
# -- PRNG implementation interface
|
2021-06-03 21:55:39 -07:00
|
|
|
|
2021-06-08 11:16:33 -07:00
|
|
|
class PRNGImpl(NamedTuple):
|
|
|
|
"""Specifies PRNG key shape and operations.
|
|
|
|
|
|
|
|
A PRNG implementation is determined by a key type ``K`` and a
|
|
|
|
collection of functions that operate on such keys. The key type
|
|
|
|
``K`` is an array type with element type uint32 and shape specified
|
|
|
|
by ``key_shape``. The type signature of each operations is::
|
|
|
|
|
|
|
|
seed :: int[] -> K
|
|
|
|
fold_in :: K -> int[] -> K
|
2023-07-06 13:23:48 -07:00
|
|
|
split[shape] :: K -> K[*shape]
|
|
|
|
random_bits[shape, bit_width] :: K -> uint<bit_width>[*shape]
|
2021-06-08 11:16:33 -07:00
|
|
|
|
|
|
|
A PRNG implementation is adapted to an array-like object of keys
|
|
|
|
``K`` by the ``PRNGKeyArray`` class, which should be created via the
|
2023-10-17 13:18:08 -07:00
|
|
|
``random_seed`` function.
|
2021-06-08 11:16:33 -07:00
|
|
|
"""
|
2023-07-06 13:23:48 -07:00
|
|
|
key_shape: Shape
|
2021-06-08 11:16:33 -07:00
|
|
|
seed: Callable
|
|
|
|
split: Callable
|
|
|
|
random_bits: Callable
|
|
|
|
fold_in: Callable
|
2023-10-03 18:04:14 -07:00
|
|
|
name: str = '<unnamed>'
|
2022-08-22 13:56:50 -07:00
|
|
|
tag: str = '?'
|
|
|
|
|
|
|
|
def __hash__(self) -> int:
|
|
|
|
return hash(self.tag)
|
|
|
|
|
|
|
|
def __str__(self) -> str:
|
|
|
|
return self.tag
|
2021-06-08 11:16:33 -07:00
|
|
|
|
|
|
|
def pprint(self):
|
2023-10-03 18:04:14 -07:00
|
|
|
ty = self.__class__.__name__
|
|
|
|
return (pp.text(f"{ty} [{self.tag}] {{{self.name}}}:") +
|
2021-09-24 22:08:42 -04:00
|
|
|
pp.nest(2, pp.group(pp.brk() + pp.join(pp.brk(), [
|
|
|
|
pp.text(f"{k} = {v}") for k, v in self._asdict().items()
|
|
|
|
]))))
|
2021-06-08 11:16:33 -07:00
|
|
|
|
|
|
|
|
2023-10-03 18:04:14 -07:00
|
|
|
prngs = {}
|
|
|
|
|
|
|
|
def register_prng(impl: PRNGImpl):
|
|
|
|
if impl.name in prngs:
|
|
|
|
raise ValueError(f'PRNG with name {impl.name} already registered: {impl}')
|
|
|
|
prngs[impl.name] = impl
|
|
|
|
|
|
|
|
|
2022-08-22 13:56:50 -07:00
|
|
|
# -- PRNG key arrays
|
2021-06-08 11:16:33 -07:00
|
|
|
|
2023-04-04 11:41:00 -07:00
|
|
|
def _check_prng_key_data(impl, key_data: typing.Array):
|
2021-06-08 11:16:33 -07:00
|
|
|
ndim = len(impl.key_shape)
|
2022-03-04 10:49:29 -08:00
|
|
|
if not all(hasattr(key_data, attr) for attr in ['ndim', 'shape', 'dtype']):
|
|
|
|
raise TypeError("JAX encountered invalid PRNG key data: expected key_data "
|
|
|
|
f"to have ndim, shape, and dtype attributes. Got {key_data}")
|
|
|
|
if key_data.ndim < 1:
|
|
|
|
raise TypeError("JAX encountered invalid PRNG key data: expected "
|
|
|
|
f"key_data.ndim >= 1; got ndim={key_data.ndim}")
|
|
|
|
if key_data.shape[-ndim:] != impl.key_shape:
|
|
|
|
raise TypeError("JAX encountered invalid PRNG key data: expected key_data.shape to "
|
2022-12-01 09:12:01 -08:00
|
|
|
f"end with {impl.key_shape}; got shape={key_data.shape} for {impl=}")
|
2022-03-04 10:49:29 -08:00
|
|
|
if key_data.dtype not in [np.uint32, float0]:
|
|
|
|
raise TypeError("JAX encountered invalid PRNG key data: expected key_data.dtype = uint32; "
|
|
|
|
f"got dtype={key_data.dtype}")
|
|
|
|
|
2021-06-08 11:16:33 -07:00
|
|
|
|
2024-01-26 11:13:04 -08:00
|
|
|
class PRNGKeyArray(jax.Array):
|
2023-04-06 13:27:31 -07:00
|
|
|
"""An array of PRNG keys backed by an RNG implementation.
|
2021-06-08 11:16:33 -07:00
|
|
|
|
|
|
|
This class lifts the definition of a PRNG, provided in the form of a
|
|
|
|
``PRNGImpl``, into an array-like pytree class. Instances of this
|
|
|
|
class behave like an array whose base elements are keys, hiding the
|
|
|
|
fact that keys are typically arrays (of ``uint32`` dtype) themselves.
|
|
|
|
|
|
|
|
PRNGKeyArrays are also restricted relative to JAX arrays in that
|
|
|
|
they do not expose arithmetic operations. They instead expose
|
|
|
|
wrapper methods around the PRNG implementation functions (``split``,
|
|
|
|
``random_bits``, ``fold_in``).
|
|
|
|
"""
|
2024-01-29 12:40:47 -08:00
|
|
|
# TODO(jakevdp): potentially add tolist(), tobytes(),
|
|
|
|
# device_buffer, device_buffers, __cuda_interface__()
|
2021-06-08 11:16:33 -07:00
|
|
|
|
2023-10-17 14:38:00 -07:00
|
|
|
_impl: PRNGImpl
|
2023-04-04 11:41:00 -07:00
|
|
|
_base_array: typing.Array
|
2024-02-29 15:30:19 -08:00
|
|
|
_consumed: bool | np.ndarray # Used in jax.experimental.key_reuse.
|
2024-03-21 13:34:26 -07:00
|
|
|
_source_info: None | source_info_util.SourceInfo = None
|
2021-06-08 11:16:33 -07:00
|
|
|
|
2022-08-22 13:56:50 -07:00
|
|
|
def __init__(self, impl, key_data: Any):
|
|
|
|
assert not isinstance(key_data, core.Tracer)
|
|
|
|
_check_prng_key_data(impl, key_data)
|
2023-10-17 14:38:00 -07:00
|
|
|
self._impl = impl
|
2022-08-22 13:56:50 -07:00
|
|
|
self._base_array = key_data
|
2024-02-29 15:30:19 -08:00
|
|
|
self._consumed = False # TODO(jakevdp): default to True here?
|
2021-10-11 21:21:37 -07:00
|
|
|
|
2022-08-22 13:56:50 -07:00
|
|
|
def block_until_ready(self):
|
|
|
|
_ = self._base_array.block_until_ready()
|
|
|
|
return self
|
2021-08-15 08:09:30 -07:00
|
|
|
|
2023-05-17 14:47:22 -07:00
|
|
|
def copy_to_host_async(self):
|
|
|
|
_ = self._base_array.copy_to_host_async()
|
|
|
|
|
2023-04-21 16:44:32 -07:00
|
|
|
@property
|
|
|
|
def aval(self):
|
2023-10-17 14:38:00 -07:00
|
|
|
return keys_shaped_array(self._impl, self.shape)
|
2023-04-21 16:44:32 -07:00
|
|
|
|
2021-09-10 18:29:39 -07:00
|
|
|
@property
|
2021-06-08 11:16:33 -07:00
|
|
|
def shape(self):
|
2023-10-17 14:38:00 -07:00
|
|
|
return base_arr_shape_to_keys_shape(self._impl, self._base_array.shape)
|
2021-06-08 11:16:33 -07:00
|
|
|
|
2023-04-27 14:06:55 -07:00
|
|
|
@property
|
|
|
|
def size(self):
|
|
|
|
return math.prod(self.shape)
|
|
|
|
|
2022-02-16 20:32:17 -08:00
|
|
|
@property
|
|
|
|
def ndim(self):
|
|
|
|
return len(self.shape)
|
|
|
|
|
2022-08-30 14:05:22 -07:00
|
|
|
@property
|
|
|
|
def dtype(self):
|
2023-10-17 14:38:00 -07:00
|
|
|
return KeyTy(self._impl)
|
2022-08-30 14:05:22 -07:00
|
|
|
|
2023-09-25 08:52:26 -07:00
|
|
|
@property
|
|
|
|
def itemsize(self):
|
|
|
|
return self.dtype.itemsize
|
|
|
|
|
2022-09-08 13:45:06 -07:00
|
|
|
_device = property(op.attrgetter('_base_array._device'))
|
|
|
|
_committed = property(op.attrgetter('_base_array._committed'))
|
2024-05-17 09:46:36 +01:00
|
|
|
device = property(op.attrgetter('_base_array.device'))
|
2023-05-17 14:47:22 -07:00
|
|
|
devices = property(op.attrgetter('_base_array.devices')) # type: ignore[assignment]
|
|
|
|
is_fully_addressable = property(op.attrgetter('_base_array.is_fully_addressable')) # type: ignore[assignment]
|
|
|
|
is_fully_replicated = property(op.attrgetter('_base_array.is_fully_replicated')) # type: ignore[assignment]
|
|
|
|
delete = property(op.attrgetter('_base_array.delete')) # type: ignore[assignment]
|
|
|
|
is_deleted = property(op.attrgetter('_base_array.is_deleted')) # type: ignore[assignment]
|
|
|
|
on_device_size_in_bytes = property(op.attrgetter('_base_array.on_device_size_in_bytes')) # type: ignore[assignment]
|
|
|
|
unsafe_buffer_pointer = property(op.attrgetter('_base_array.unsafe_buffer_pointer')) # type: ignore[assignment]
|
2023-04-05 14:09:46 -07:00
|
|
|
|
2024-01-29 12:40:47 -08:00
|
|
|
def addressable_data(self, index: int) -> PRNGKeyArray:
|
|
|
|
return PRNGKeyArray(self._impl, self._base_array.addressable_data(index))
|
2023-06-01 04:10:12 -07:00
|
|
|
|
|
|
|
@property
|
2023-06-23 15:11:37 -07:00
|
|
|
def addressable_shards(self) -> list[Shard]:
|
2023-06-01 04:10:12 -07:00
|
|
|
return [
|
|
|
|
type(s)(
|
|
|
|
device=s._device,
|
|
|
|
sharding=s._sharding,
|
|
|
|
global_shape=s._global_shape,
|
2024-01-29 12:40:47 -08:00
|
|
|
data=PRNGKeyArray(self._impl, s._data),
|
2023-06-01 04:10:12 -07:00
|
|
|
)
|
|
|
|
for s in self._base_array.addressable_shards
|
|
|
|
]
|
|
|
|
|
|
|
|
@property
|
2023-06-23 15:11:37 -07:00
|
|
|
def global_shards(self) -> list[Shard]:
|
2023-06-01 04:10:12 -07:00
|
|
|
return [
|
|
|
|
type(s)(
|
|
|
|
device=s._device,
|
|
|
|
sharding=s._sharding,
|
|
|
|
global_shape=s._global_shape,
|
2024-01-29 12:40:47 -08:00
|
|
|
data=PRNGKeyArray(self._impl, s._data),
|
2023-06-01 04:10:12 -07:00
|
|
|
)
|
|
|
|
for s in self._base_array.global_shards
|
|
|
|
]
|
|
|
|
|
2023-04-05 14:09:46 -07:00
|
|
|
@property
|
|
|
|
def sharding(self):
|
2024-06-03 14:52:08 -07:00
|
|
|
return logical_sharding(self.aval, self._base_array.sharding)
|
2022-09-08 13:45:06 -07:00
|
|
|
|
2024-10-15 19:45:25 -07:00
|
|
|
@property
|
|
|
|
def committed(self):
|
|
|
|
return self._base_array.committed
|
|
|
|
|
2021-08-15 08:09:30 -07:00
|
|
|
def _is_scalar(self):
|
2023-10-17 14:38:00 -07:00
|
|
|
base_ndim = len(self._impl.key_shape)
|
2022-08-22 13:56:50 -07:00
|
|
|
return self._base_array.ndim == base_ndim
|
2021-08-15 08:09:30 -07:00
|
|
|
|
|
|
|
def __len__(self):
|
|
|
|
if self._is_scalar():
|
|
|
|
raise TypeError('len() of unsized object')
|
2022-08-22 13:56:50 -07:00
|
|
|
return len(self._base_array)
|
2021-08-15 08:09:30 -07:00
|
|
|
|
2024-01-29 12:40:47 -08:00
|
|
|
def __iter__(self) -> Iterator[PRNGKeyArray]:
|
2021-08-15 08:09:30 -07:00
|
|
|
if self._is_scalar():
|
2022-08-22 13:56:50 -07:00
|
|
|
raise TypeError('iteration over a 0-d key array')
|
|
|
|
# TODO(frostig): we may want to avoid iteration by slicing because
|
|
|
|
# a very common use of iteration is `k1, k2 = split(key)`, and
|
|
|
|
# slicing/indexing may be trickier to track for linearity checking
|
|
|
|
# purposes. Maybe we can:
|
|
|
|
# * introduce an unpack primitive+traceable (also allow direct use)
|
|
|
|
# * unpack upfront into shape[0] many keyarray slices
|
|
|
|
# * return iter over these unpacked slices
|
|
|
|
# Whatever we do, we'll want to do it by overriding
|
2022-08-30 14:47:15 -07:00
|
|
|
# ShapedArray._iter when the element type is KeyTy...
|
2024-01-29 12:40:47 -08:00
|
|
|
return (PRNGKeyArray(self._impl, k) for k in iter(self._base_array))
|
2022-08-22 13:56:50 -07:00
|
|
|
|
2021-06-08 11:16:33 -07:00
|
|
|
def __repr__(self):
|
2023-08-14 12:47:48 -07:00
|
|
|
return (f'Array({self.shape}, dtype={self.dtype.name}) overlaying:\n'
|
|
|
|
f'{self._base_array}')
|
2022-08-22 13:56:50 -07:00
|
|
|
|
|
|
|
def pprint(self):
|
|
|
|
pp_keys = pp.text('shape = ') + pp.text(str(self.shape))
|
2023-10-17 14:38:00 -07:00
|
|
|
pp_impl = pp.text('impl = ') + self._impl.pprint()
|
2021-09-24 22:08:42 -04:00
|
|
|
return str(pp.group(
|
|
|
|
pp.text('PRNGKeyArray:') +
|
|
|
|
pp.nest(2, pp.brk() + pp_keys + pp.brk() + pp_impl)))
|
2021-06-08 11:16:33 -07:00
|
|
|
|
2023-05-12 15:50:22 -07:00
|
|
|
def copy(self):
|
2024-02-29 15:30:19 -08:00
|
|
|
out = self.__class__(self._impl, self._base_array.copy())
|
|
|
|
out._consumed = self._consumed # TODO(jakevdp): is this correct?
|
|
|
|
return out
|
2023-05-12 15:50:22 -07:00
|
|
|
|
2023-05-17 14:47:22 -07:00
|
|
|
__hash__ = None # type: ignore[assignment]
|
|
|
|
__array_priority__ = 100
|
|
|
|
|
2024-11-05 09:26:42 -08:00
|
|
|
def __array__(self, dtype: np.dtype | None = None, copy: bool | None = None) -> np.ndarray:
|
|
|
|
raise TypeError("JAX array with PRNGKey dtype cannot be converted to a NumPy array."
|
|
|
|
" Use jax.random.key_data(arr) if you wish to extract the underlying"
|
|
|
|
" integer array.")
|
|
|
|
|
2023-04-06 13:27:31 -07:00
|
|
|
# Overwritten immediately below
|
2022-08-22 13:56:50 -07:00
|
|
|
@property
|
2023-09-12 13:46:22 -07:00
|
|
|
def at(self) -> _IndexUpdateHelper: assert False # type: ignore[override]
|
2023-04-25 15:54:33 -07:00
|
|
|
@property
|
2023-04-05 14:09:46 -07:00
|
|
|
def T(self) -> PRNGKeyArray: assert False
|
|
|
|
def __getitem__(self, _) -> PRNGKeyArray: assert False
|
2023-04-25 15:54:33 -07:00
|
|
|
def flatten(self, *_, **__) -> PRNGKeyArray: assert False
|
2023-04-05 14:09:46 -07:00
|
|
|
def ravel(self, *_, **__) -> PRNGKeyArray: assert False
|
2023-04-25 15:54:33 -07:00
|
|
|
def reshape(self, *_, **__) -> PRNGKeyArray: assert False
|
2023-04-05 14:09:46 -07:00
|
|
|
def squeeze(self, *_, **__) -> PRNGKeyArray: assert False
|
|
|
|
def swapaxes(self, *_, **__) -> PRNGKeyArray: assert False
|
|
|
|
def take(self, *_, **__) -> PRNGKeyArray: assert False
|
|
|
|
def transpose(self, *_, **__) -> PRNGKeyArray: assert False
|
2022-08-22 13:56:50 -07:00
|
|
|
|
2024-01-29 12:40:47 -08:00
|
|
|
_set_array_base_attributes(PRNGKeyArray, include=[
|
2023-04-26 11:25:25 -07:00
|
|
|
*(f"__{op}__" for op in _array_operators),
|
|
|
|
'at', 'flatten', 'ravel', 'reshape',
|
2023-04-25 15:54:33 -07:00
|
|
|
'squeeze', 'swapaxes', 'take', 'transpose', 'T'])
|
2022-08-22 13:56:50 -07:00
|
|
|
|
2024-01-29 12:40:47 -08:00
|
|
|
api_util._shaped_abstractify_handlers[PRNGKeyArray] = op.attrgetter('aval')
|
2023-05-16 17:05:21 -07:00
|
|
|
|
2024-01-29 12:40:47 -08:00
|
|
|
def prngkeyarray_flatten(x):
|
2023-10-17 14:38:00 -07:00
|
|
|
return (x._base_array,), x._impl
|
2023-09-13 09:43:14 -07:00
|
|
|
|
2024-01-29 12:40:47 -08:00
|
|
|
def prngkeyarray_unflatten(impl, children):
|
2023-09-13 09:43:14 -07:00
|
|
|
base_array, = children
|
2024-01-29 12:40:47 -08:00
|
|
|
return PRNGKeyArray(impl, base_array)
|
2023-09-13 09:43:14 -07:00
|
|
|
|
|
|
|
tree_util_internal.dispatch_registry.register_node(
|
2024-01-29 12:40:47 -08:00
|
|
|
PRNGKeyArray, prngkeyarray_flatten, prngkeyarray_unflatten)
|
2023-09-13 09:43:14 -07:00
|
|
|
|
2022-08-22 13:56:50 -07:00
|
|
|
|
|
|
|
# TODO(frostig): remove, rerouting callers directly to random_seed
|
2024-01-29 12:40:47 -08:00
|
|
|
def seed_with_impl(impl: PRNGImpl, seed: int | typing.ArrayLike) -> PRNGKeyArray:
|
2022-08-22 13:56:50 -07:00
|
|
|
return random_seed(seed, impl=impl)
|
|
|
|
|
|
|
|
|
|
|
|
def keys_shaped_array(impl, shape):
|
|
|
|
return core.ShapedArray(shape, KeyTy(impl))
|
|
|
|
|
|
|
|
def base_arr_shape_to_keys_shape(impl, base_arr_shape):
|
|
|
|
base_ndim = len(impl.key_shape)
|
|
|
|
return base_arr_shape[:-base_ndim]
|
2021-06-08 11:16:33 -07:00
|
|
|
|
2024-03-15 16:01:13 -07:00
|
|
|
|
2022-08-30 13:25:49 -07:00
|
|
|
class KeyTyRules:
|
simplify conversion logic involving extended dtypes
Previously, the idea was that we would use the `convert_element_type` primitive
to cast to/from extended dtypes. Extended dtype rules specified
`convert_from(dtype1, dtype2) -> bool` and `convert_to(dtype1, dtype2) -> bool`
functions. They were meant to do something like indicate whether a
convert_element_type was legal. But I'm not sure if they really made sense.
The implementation was certainly buggy for non-scalar representation types
(physical element types).
This PR simplifies and fixes things:
1. Instead of overloading the `convert_element_type_p` primitive with more cases
involving casts to/from extended dtypes, let's just have distinct `to_edtype_p`
and `from_edtype_p` primitives, which can be much simpler. We still reuse the
`jax.lax.convert_element_type` API function, so there's no API change to the
few existing users who know about this stuff.
2. Instead of extended dtype rules including `convert_from`/`convert_to`
functions with questionable semantics, let's only allow casts to/from the
representation type, which is already specified by the rules'
`physical_element_aval`. (Indeed that should be roughly _all_ we need, and this
PR is just one step towards realizing that goal.) We still have a boolean
`allow_conversion` on extended dtype rules just so we can handle the PRNGKey
case, where we don't want to allow any casts.
3. Fix the conversion logic to handle non-scalar representation types (physical
element types).
2024-09-20 22:58:01 +00:00
|
|
|
allow_conversion: bool = False
|
2022-08-22 13:56:50 -07:00
|
|
|
|
2023-05-17 09:04:50 -07:00
|
|
|
@staticmethod
|
|
|
|
def full(shape, fill_value, dtype):
|
2023-10-17 14:38:00 -07:00
|
|
|
physical_shape = (*shape, *dtype._impl.key_shape)
|
2023-07-21 09:48:38 -07:00
|
|
|
if hasattr(fill_value, 'dtype') and jnp.issubdtype(fill_value.dtype, dtypes.prng_key):
|
2023-05-17 09:04:50 -07:00
|
|
|
key_data = jnp.broadcast_to(random_unwrap(fill_value), physical_shape)
|
|
|
|
else:
|
|
|
|
key_data = lax.full(physical_shape, fill_value, dtype=np.dtype('uint32'))
|
|
|
|
# TODO(frostig,mattjj,vanderplas,lenamartens): consider this consumed from
|
|
|
|
# the outset.
|
2023-10-17 14:38:00 -07:00
|
|
|
return random_wrap(key_data, impl=dtype._impl)
|
2023-05-17 09:04:50 -07:00
|
|
|
|
2022-08-22 13:56:50 -07:00
|
|
|
@staticmethod
|
2023-05-10 19:13:29 -07:00
|
|
|
def physical_element_aval(dtype) -> core.ShapedArray:
|
2023-10-17 14:38:00 -07:00
|
|
|
return core.ShapedArray(dtype._impl.key_shape, jnp.dtype('uint32'))
|
2022-08-22 13:56:50 -07:00
|
|
|
|
2023-05-04 14:22:15 -07:00
|
|
|
@staticmethod
|
|
|
|
def physical_const(val) -> Array:
|
2023-09-13 16:33:21 -07:00
|
|
|
return val._base_array
|
2023-05-04 14:22:15 -07:00
|
|
|
|
2022-08-22 13:56:50 -07:00
|
|
|
@staticmethod
|
|
|
|
def result_handler(sticky_device, aval):
|
|
|
|
def handler(_, buf):
|
|
|
|
buf.aval = core.ShapedArray(buf.shape, buf.dtype)
|
2024-01-29 12:40:47 -08:00
|
|
|
return PRNGKeyArray(aval.dtype._impl, buf)
|
2022-08-22 13:56:50 -07:00
|
|
|
return handler
|
|
|
|
|
|
|
|
@staticmethod
|
2022-08-24 19:48:36 -07:00
|
|
|
def local_sharded_result_handler(aval, sharding, indices):
|
2023-05-10 19:13:29 -07:00
|
|
|
phys_aval = core.physical_aval(aval)
|
2023-10-17 14:38:00 -07:00
|
|
|
key_shape = aval.dtype._impl.key_shape
|
2023-03-20 09:09:15 -07:00
|
|
|
phys_handler_maker = pxla.local_result_handlers[core.ShapedArray]
|
2022-08-24 19:48:36 -07:00
|
|
|
|
|
|
|
# set up a grounded sharding (with a grounded sharding spec)
|
2023-03-02 13:28:25 -08:00
|
|
|
if isinstance(sharding, (PmapSharding, NamedSharding)):
|
2024-06-03 14:52:08 -07:00
|
|
|
phys_sharding = physical_sharding(aval, sharding)
|
2022-08-25 17:13:33 -07:00
|
|
|
else:
|
|
|
|
assert False, f'impossible sharding {sharding} in local sharded result handler'
|
2022-08-24 19:48:36 -07:00
|
|
|
|
|
|
|
# set up grounded indices
|
|
|
|
trailing_inds = [slice(None)] * len(key_shape)
|
|
|
|
phys_indices = [(*inds, *trailing_inds) for inds in indices]
|
|
|
|
|
|
|
|
# make a physical handler
|
|
|
|
phys_handler = phys_handler_maker(phys_aval, phys_sharding, phys_indices)
|
|
|
|
|
|
|
|
# set up a handler that calls the physical one and wraps back up
|
2022-08-22 13:56:50 -07:00
|
|
|
def handler(bufs):
|
2024-01-29 12:40:47 -08:00
|
|
|
return PRNGKeyArray(aval.dtype._impl, phys_handler(bufs))
|
2022-08-24 19:48:36 -07:00
|
|
|
|
2022-08-22 13:56:50 -07:00
|
|
|
return handler
|
|
|
|
|
2022-08-24 19:48:36 -07:00
|
|
|
@staticmethod
|
2024-02-28 15:21:50 -08:00
|
|
|
def global_sharded_result_handler(aval, out_sharding, committed):
|
2023-05-10 19:13:29 -07:00
|
|
|
phys_aval = core.physical_aval(aval)
|
2023-03-20 09:09:15 -07:00
|
|
|
phys_handler_maker = pxla.global_result_handlers[core.ShapedArray]
|
2022-08-25 12:22:42 -07:00
|
|
|
|
2024-06-03 14:52:08 -07:00
|
|
|
phys_sharding = physical_sharding(aval, out_sharding)
|
2024-02-28 15:21:50 -08:00
|
|
|
phys_handler = phys_handler_maker(phys_aval, phys_sharding, committed)
|
2022-08-25 12:22:42 -07:00
|
|
|
def handler(bufs):
|
2024-01-29 12:40:47 -08:00
|
|
|
return PRNGKeyArray(aval.dtype._impl, phys_handler(bufs))
|
2022-08-25 12:22:42 -07:00
|
|
|
return handler
|
2022-08-24 19:48:36 -07:00
|
|
|
|
2023-05-04 16:32:49 -07:00
|
|
|
@staticmethod
|
|
|
|
def make_sharded_array(aval, sharding, arrays, committed):
|
2023-05-10 19:13:29 -07:00
|
|
|
phys_aval = core.physical_aval(aval)
|
2023-05-04 16:32:49 -07:00
|
|
|
phys_handler_maker = pxla.global_result_handlers[core.ShapedArray]
|
|
|
|
phys_arrays = [random_unwrap(arr) for arr in arrays]
|
|
|
|
|
2024-06-03 14:52:08 -07:00
|
|
|
phys_sharding = physical_sharding(aval, sharding)
|
2024-02-28 15:21:50 -08:00
|
|
|
phys_handler = phys_handler_maker(phys_aval, phys_sharding, committed)
|
2023-05-04 16:32:49 -07:00
|
|
|
phys_result = phys_handler(phys_arrays)
|
2024-01-29 12:40:47 -08:00
|
|
|
return PRNGKeyArray(aval.dtype._impl, phys_result)
|
2023-05-04 16:32:49 -07:00
|
|
|
|
2024-10-30 15:12:04 -07:00
|
|
|
@staticmethod
|
|
|
|
def device_get(val):
|
|
|
|
buffer = api.device_get(random_unwrap(val))
|
|
|
|
return random_wrap(buffer, impl=val.dtype._impl)
|
|
|
|
|
2023-05-01 14:17:01 -07:00
|
|
|
@staticmethod
|
|
|
|
def device_put_sharded(vals, aval, sharding, devices):
|
2023-10-17 15:47:32 -07:00
|
|
|
physical_aval = core.physical_aval(aval)
|
2023-05-01 14:17:01 -07:00
|
|
|
physical_buffers = tree_util.tree_map(random_unwrap, vals)
|
2024-06-03 14:52:08 -07:00
|
|
|
phys_sharding = physical_sharding(aval, sharding)
|
|
|
|
physical_result = pxla.batched_device_put(physical_aval, phys_sharding,
|
|
|
|
physical_buffers, list(devices))
|
2023-10-17 14:38:00 -07:00
|
|
|
return random_wrap(physical_result, impl=aval.dtype._impl)
|
2023-05-01 14:17:01 -07:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def device_put_replicated(val, aval, sharding, devices):
|
2023-10-17 15:47:32 -07:00
|
|
|
physical_aval = core.physical_aval(aval)
|
2023-05-01 14:17:01 -07:00
|
|
|
assert len(xla.aval_to_xla_shapes(physical_aval)) == 1
|
|
|
|
physical_buf = random_unwrap(val)
|
2024-06-03 14:52:08 -07:00
|
|
|
phys_sharding = physical_sharding(aval, sharding)
|
|
|
|
physical_result = pxla.batched_device_put(
|
|
|
|
physical_aval, phys_sharding, [physical_buf] * len(devices), devices)
|
2023-10-17 14:38:00 -07:00
|
|
|
return random_wrap(physical_result, impl=aval.dtype._impl)
|
2023-05-01 14:17:01 -07:00
|
|
|
|
2023-12-20 21:00:08 -08:00
|
|
|
@staticmethod
|
2023-12-20 12:47:43 -08:00
|
|
|
def tangent_dtype(_):
|
|
|
|
return dtypes.float0
|
2023-11-10 11:16:23 -08:00
|
|
|
|
2023-12-20 21:00:08 -08:00
|
|
|
# TODO(mattjj,frostig): even though the key dtype shouldn't appear in
|
|
|
|
# tangents, our ad.replace_float0s in custom_jvp/vjp means passing in zeros
|
|
|
|
# like the primal to user rules
|
|
|
|
@staticmethod
|
2023-12-21 17:43:31 -08:00
|
|
|
def zero(_):
|
|
|
|
return np.zeros((), dtypes.float0)
|
|
|
|
|
2023-11-10 11:16:23 -08:00
|
|
|
|
2023-07-24 14:29:37 -07:00
|
|
|
class KeyTy(dtypes.ExtendedDType):
|
2023-10-17 14:38:00 -07:00
|
|
|
_impl: PRNGImpl # TODO(mattjj,frostig): protocol really
|
2022-08-30 13:25:49 -07:00
|
|
|
_rules = KeyTyRules
|
2023-07-21 09:48:38 -07:00
|
|
|
type = dtypes.prng_key
|
2022-08-30 13:25:49 -07:00
|
|
|
|
|
|
|
def __init__(self, impl):
|
2023-10-17 14:38:00 -07:00
|
|
|
self._impl = impl
|
2022-08-30 13:25:49 -07:00
|
|
|
|
|
|
|
@property
|
|
|
|
def name(self) -> str:
|
2023-10-17 14:38:00 -07:00
|
|
|
return f'key<{self._impl.tag}>'
|
2022-08-30 13:25:49 -07:00
|
|
|
|
2023-04-27 15:59:53 -07:00
|
|
|
@property
|
|
|
|
def itemsize(self) -> int:
|
2023-10-17 14:38:00 -07:00
|
|
|
return math.prod(self._impl.key_shape) * np.dtype('uint32').itemsize
|
2023-04-27 15:59:53 -07:00
|
|
|
|
2022-08-30 13:25:49 -07:00
|
|
|
def __repr__(self) -> str:
|
|
|
|
return self.name
|
|
|
|
|
|
|
|
def __eq__(self, other):
|
2023-10-17 14:38:00 -07:00
|
|
|
return type(other) is KeyTy and self._impl == other._impl
|
2022-08-30 13:25:49 -07:00
|
|
|
|
|
|
|
def __hash__(self) -> int:
|
2023-10-17 14:38:00 -07:00
|
|
|
return hash((self.__class__, self._impl))
|
2022-08-30 13:25:49 -07:00
|
|
|
|
|
|
|
|
2024-01-29 12:40:47 -08:00
|
|
|
core.pytype_aval_mappings[PRNGKeyArray] = lambda x: x.aval
|
|
|
|
xla.pytype_aval_mappings[PRNGKeyArray] = lambda x: x.aval
|
2022-08-22 13:56:50 -07:00
|
|
|
|
2024-01-29 12:40:47 -08:00
|
|
|
xla.canonicalize_dtype_handlers[PRNGKeyArray] = lambda x: x
|
2022-08-22 13:56:50 -07:00
|
|
|
|
2023-03-02 13:28:25 -08:00
|
|
|
|
2024-08-19 15:10:00 -07:00
|
|
|
def key_array_shard_arg_handler(xs: Sequence[PRNGKeyArray], shardings, layouts):
|
2024-06-13 13:09:35 -07:00
|
|
|
arrs = [x._base_array for x in xs]
|
|
|
|
phys_shardings = [physical_sharding(x.aval, sharding)
|
|
|
|
for x, sharding in zip(xs, shardings)]
|
2024-08-19 15:10:00 -07:00
|
|
|
# TODO(yashkatariya): `layouts` should be converted to physical layouts.
|
|
|
|
return pxla.shard_args(phys_shardings, layouts, arrs)
|
2023-03-02 13:28:25 -08:00
|
|
|
|
|
|
|
|
2024-01-29 12:40:47 -08:00
|
|
|
pxla.shard_arg_handlers[PRNGKeyArray] = key_array_shard_arg_handler
|
2022-08-22 13:56:50 -07:00
|
|
|
|
2022-08-31 22:53:32 -07:00
|
|
|
|
2023-08-17 06:43:31 -07:00
|
|
|
def key_array_constant_handler(x):
|
2023-09-13 16:33:21 -07:00
|
|
|
arr = x._base_array
|
2023-08-17 06:43:31 -07:00
|
|
|
return mlir.get_constant_handler(type(arr))(arr)
|
2024-01-29 12:40:47 -08:00
|
|
|
mlir.register_constant_handler(PRNGKeyArray, key_array_constant_handler)
|
2022-08-22 13:56:50 -07:00
|
|
|
|
|
|
|
|
|
|
|
# -- primitives
|
|
|
|
|
|
|
|
def iterated_vmap_unary(n, f):
|
|
|
|
for _ in range(n):
|
2023-04-04 11:41:00 -07:00
|
|
|
f = api.vmap(f)
|
2022-08-22 13:56:50 -07:00
|
|
|
return f
|
|
|
|
|
|
|
|
# TODO(frostig): Revise the following two functions? These basically
|
|
|
|
# undo the singleton dimensions added by `batching.defbroadcasting`.
|
|
|
|
# It works, but introduces some possibly-redundant squeezes. Can we
|
|
|
|
# borrow from other broadcasting primitives instead?
|
|
|
|
|
|
|
|
def squeeze_vmap(f, left):
|
|
|
|
def squeeze_vmap_f(x, y):
|
|
|
|
if left:
|
|
|
|
x = jnp.squeeze(x, axis=0)
|
|
|
|
axes = (None, 0)
|
|
|
|
else:
|
|
|
|
y = jnp.squeeze(y, axis=0)
|
|
|
|
axes = (0, None)
|
2023-04-04 11:41:00 -07:00
|
|
|
return api.vmap(f, in_axes=axes, out_axes=0)(x, y)
|
2022-08-22 13:56:50 -07:00
|
|
|
return squeeze_vmap_f
|
|
|
|
|
|
|
|
def iterated_vmap_binary_bcast(shape1, shape2, f):
|
|
|
|
ndim1, ndim2 = len(shape1), len(shape2)
|
|
|
|
if ndim1 == ndim2 == 0:
|
|
|
|
return f
|
|
|
|
if 0 in [ndim1, ndim2]:
|
|
|
|
if ndim1 == 0:
|
|
|
|
return lambda x, y: iterated_vmap_unary(ndim2, lambda y: f(x, y))(y)
|
|
|
|
else:
|
|
|
|
return lambda x, y: iterated_vmap_unary(ndim1, lambda x: f(x, y))(x)
|
|
|
|
assert len(shape1) == len(shape2)
|
|
|
|
for sz1, sz2 in reversed(zip(shape1, shape2)):
|
|
|
|
if sz1 == sz2:
|
2023-04-04 11:41:00 -07:00
|
|
|
f = api.vmap(f, out_axes=0)
|
2022-08-22 13:56:50 -07:00
|
|
|
else:
|
|
|
|
assert sz1 == 1 or sz2 == 1, (sz1, sz2)
|
|
|
|
f = squeeze_vmap(f, sz1 == 1)
|
|
|
|
return f
|
|
|
|
|
|
|
|
|
2024-01-29 12:40:47 -08:00
|
|
|
def random_seed(seeds: int | typing.ArrayLike, impl: PRNGImpl) -> PRNGKeyArray:
|
2022-08-22 13:56:50 -07:00
|
|
|
# Avoid overflow error in X32 mode by first converting ints to int64.
|
|
|
|
# This breaks JIT invariance for large ints, but supports the common
|
|
|
|
# use-case of instantiating with Python hashes in X32 mode.
|
|
|
|
if isinstance(seeds, int):
|
|
|
|
seeds_arr = jnp.asarray(np.int64(seeds))
|
|
|
|
else:
|
|
|
|
seeds_arr = jnp.asarray(seeds)
|
2023-12-12 18:31:07 -08:00
|
|
|
if config.random_seed_offset.value:
|
|
|
|
seeds_arr += config.random_seed_offset.value
|
2022-08-22 13:56:50 -07:00
|
|
|
return random_seed_p.bind(seeds_arr, impl=impl)
|
|
|
|
|
|
|
|
random_seed_p = core.Primitive('random_seed')
|
|
|
|
ad.defjvp_zero(random_seed_p)
|
|
|
|
batching.defvectorized(random_seed_p)
|
|
|
|
|
|
|
|
@random_seed_p.def_abstract_eval
|
|
|
|
def random_seed_abstract_eval(seeds_aval, *, impl):
|
|
|
|
return keys_shaped_array(impl, seeds_aval.shape)
|
|
|
|
|
|
|
|
@random_seed_p.def_impl
|
|
|
|
def random_seed_impl(seeds, *, impl):
|
|
|
|
base_arr = random_seed_impl_base(seeds, impl=impl)
|
2024-01-29 12:40:47 -08:00
|
|
|
return PRNGKeyArray(impl, base_arr)
|
2022-08-22 13:56:50 -07:00
|
|
|
|
|
|
|
def random_seed_impl_base(seeds, *, impl):
|
2023-10-24 11:23:49 -07:00
|
|
|
seed = iterated_vmap_unary(np.ndim(seeds), impl.seed)
|
2022-08-22 13:56:50 -07:00
|
|
|
return seed(seeds)
|
|
|
|
|
|
|
|
def random_seed_lowering(ctx, seeds, *, impl):
|
|
|
|
aval, = ctx.avals_in
|
|
|
|
seed = iterated_vmap_unary(aval.ndim, impl.seed)
|
|
|
|
seed_lowering = mlir.lower_fun(seed, multiple_results=False)
|
|
|
|
return mlir.delegate_lowering(
|
|
|
|
ctx, seed_lowering, seeds,
|
2023-10-17 15:47:32 -07:00
|
|
|
avals_out=map(core.physical_aval, ctx.avals_out))
|
2022-08-22 13:56:50 -07:00
|
|
|
|
|
|
|
mlir.register_lowering(random_seed_p, random_seed_lowering)
|
|
|
|
|
|
|
|
|
2023-07-06 13:23:48 -07:00
|
|
|
def random_split(keys, shape: Shape):
|
|
|
|
return random_split_p.bind(keys, shape=shape)
|
2022-08-22 13:56:50 -07:00
|
|
|
|
|
|
|
random_split_p = core.Primitive('random_split')
|
|
|
|
ad.defjvp_zero(random_split_p)
|
|
|
|
batching.defvectorized(random_split_p)
|
|
|
|
|
|
|
|
@random_split_p.def_abstract_eval
|
2023-07-06 13:23:48 -07:00
|
|
|
def random_split_abstract_eval(keys_aval, *, shape):
|
2023-10-17 14:38:00 -07:00
|
|
|
return keys_shaped_array(keys_aval.dtype._impl, (*keys_aval.shape, *shape))
|
2022-08-22 13:56:50 -07:00
|
|
|
|
|
|
|
@random_split_p.def_impl
|
2023-07-06 13:23:48 -07:00
|
|
|
def random_split_impl(keys, *, shape):
|
2022-08-22 13:56:50 -07:00
|
|
|
base_arr = random_split_impl_base(
|
2023-10-17 14:38:00 -07:00
|
|
|
keys._impl, keys._base_array, keys.ndim, shape=shape)
|
2024-01-29 12:40:47 -08:00
|
|
|
return PRNGKeyArray(keys._impl, base_arr)
|
2022-08-22 13:56:50 -07:00
|
|
|
|
2023-07-06 13:23:48 -07:00
|
|
|
def random_split_impl_base(impl, base_arr, keys_ndim, *, shape):
|
|
|
|
split = iterated_vmap_unary(keys_ndim, lambda k: impl.split(k, shape))
|
2022-08-22 13:56:50 -07:00
|
|
|
return split(base_arr)
|
|
|
|
|
2023-07-06 13:23:48 -07:00
|
|
|
def random_split_lowering(ctx, keys, *, shape):
|
2022-08-22 13:56:50 -07:00
|
|
|
aval, = ctx.avals_in
|
2023-10-17 14:38:00 -07:00
|
|
|
impl = aval.dtype._impl
|
2023-07-06 13:23:48 -07:00
|
|
|
split = iterated_vmap_unary(aval.ndim, lambda k: impl.split(k, shape))
|
2022-08-22 13:56:50 -07:00
|
|
|
split_lowering = mlir.lower_fun(split, multiple_results=False)
|
|
|
|
return mlir.delegate_lowering(
|
|
|
|
ctx, split_lowering, keys,
|
2023-10-17 15:47:32 -07:00
|
|
|
avals_in=[core.physical_aval(aval)],
|
|
|
|
avals_out=map(core.physical_aval, ctx.avals_out))
|
2022-08-22 13:56:50 -07:00
|
|
|
|
|
|
|
mlir.register_lowering(random_split_p, random_split_lowering)
|
|
|
|
|
|
|
|
|
|
|
|
def random_fold_in(keys, msgs):
|
|
|
|
return random_fold_in_p.bind(keys, jnp.asarray(msgs))
|
|
|
|
|
|
|
|
random_fold_in_p = core.Primitive('random_fold_in')
|
|
|
|
ad.defjvp_zero(random_fold_in_p)
|
|
|
|
batching.defbroadcasting(random_fold_in_p)
|
|
|
|
|
|
|
|
@random_fold_in_p.def_abstract_eval
|
|
|
|
def random_fold_in_abstract_eval(keys_aval, msgs_aval):
|
|
|
|
shape = lax_internal.broadcasting_shape_rule(
|
|
|
|
'random_fold_in', keys_aval, msgs_aval)
|
2024-07-25 00:02:55 +00:00
|
|
|
return core.ShapedArray(shape, keys_aval.dtype)
|
2022-08-22 13:56:50 -07:00
|
|
|
|
|
|
|
@random_fold_in_p.def_impl
|
|
|
|
def random_fold_in_impl(keys, msgs):
|
|
|
|
base_arr = random_fold_in_impl_base(
|
2023-10-17 14:38:00 -07:00
|
|
|
keys._impl, keys._base_array, msgs, keys.shape)
|
2024-01-29 12:40:47 -08:00
|
|
|
return PRNGKeyArray(keys._impl, base_arr)
|
2022-08-22 13:56:50 -07:00
|
|
|
|
|
|
|
def random_fold_in_impl_base(impl, base_arr, msgs, keys_shape):
|
|
|
|
fold_in = iterated_vmap_binary_bcast(
|
|
|
|
keys_shape, np.shape(msgs), impl.fold_in)
|
|
|
|
return fold_in(base_arr, msgs)
|
|
|
|
|
|
|
|
def random_fold_in_lowering(ctx, keys, msgs):
|
|
|
|
keys_aval, msgs_aval = ctx.avals_in
|
2023-10-17 14:38:00 -07:00
|
|
|
impl = keys_aval.dtype._impl
|
2022-08-22 13:56:50 -07:00
|
|
|
fold_in = iterated_vmap_binary_bcast(
|
|
|
|
keys_aval.shape, msgs_aval.shape, impl.fold_in)
|
|
|
|
fold_in_lowering = mlir.lower_fun(fold_in, multiple_results=False)
|
|
|
|
return mlir.delegate_lowering(
|
|
|
|
ctx, fold_in_lowering, keys, msgs,
|
2023-10-17 15:47:32 -07:00
|
|
|
avals_in=[core.physical_aval(keys_aval), msgs_aval],
|
|
|
|
avals_out=map(core.physical_aval, ctx.avals_out))
|
2022-08-22 13:56:50 -07:00
|
|
|
|
|
|
|
mlir.register_lowering(random_fold_in_p, random_fold_in_lowering)
|
|
|
|
|
|
|
|
|
|
|
|
def random_bits(keys, bit_width, shape):
|
2024-07-25 00:02:55 +00:00
|
|
|
return random_bits_p.bind(keys, bit_width=bit_width, shape=shape)
|
2022-08-22 13:56:50 -07:00
|
|
|
|
|
|
|
random_bits_p = core.Primitive('random_bits')
|
|
|
|
ad.defjvp_zero(random_bits_p)
|
|
|
|
batching.defvectorized(random_bits_p)
|
|
|
|
|
|
|
|
@random_bits_p.def_abstract_eval
|
|
|
|
def random_bits_abstract_eval(keys_aval, *, bit_width, shape):
|
|
|
|
out_shape = (*keys_aval.shape, *shape)
|
|
|
|
out_dtype = dtypes.dtype(f'uint{bit_width}')
|
|
|
|
return core.ShapedArray(out_shape, out_dtype)
|
|
|
|
|
|
|
|
@random_bits_p.def_impl
|
|
|
|
def random_bits_impl(keys, *, bit_width, shape):
|
2023-10-17 14:38:00 -07:00
|
|
|
return random_bits_impl_base(keys._impl, keys._base_array, keys.ndim,
|
2022-08-22 13:56:50 -07:00
|
|
|
bit_width=bit_width, shape=shape)
|
|
|
|
|
|
|
|
def random_bits_impl_base(impl, base_arr, keys_ndim, *, bit_width, shape):
|
|
|
|
bits = iterated_vmap_unary(
|
|
|
|
keys_ndim, lambda k: impl.random_bits(k, bit_width, shape))
|
|
|
|
return bits(base_arr)
|
|
|
|
|
|
|
|
def random_bits_lowering(ctx, keys, *, bit_width, shape):
|
|
|
|
aval, = ctx.avals_in
|
2023-10-17 14:38:00 -07:00
|
|
|
impl = aval.dtype._impl
|
2022-08-22 13:56:50 -07:00
|
|
|
bits = iterated_vmap_unary(
|
|
|
|
aval.ndim, lambda k: impl.random_bits(k, bit_width, shape))
|
|
|
|
bits_lowering = mlir.lower_fun(bits, multiple_results=False)
|
2023-10-17 15:47:32 -07:00
|
|
|
ctx_new = ctx.replace(avals_in=[core.physical_aval(aval)])
|
2022-08-22 13:56:50 -07:00
|
|
|
out = bits_lowering(ctx_new, keys)
|
|
|
|
ctx.set_tokens_out(ctx_new.tokens_out)
|
|
|
|
return out
|
|
|
|
|
|
|
|
mlir.register_lowering(random_bits_p, random_bits_lowering)
|
|
|
|
|
|
|
|
|
|
|
|
# The following wrap/unwrap primitives are at least a stopgap for
|
|
|
|
# backwards compatibility, namely when `config.jax_enable_custom_prng`
|
|
|
|
# is False. We need to convert key arrays to and from underlying
|
|
|
|
# uint32 base array, and we may need to do so under a jit. For
|
|
|
|
# example, we want to support:
|
|
|
|
#
|
|
|
|
# keys = jax.jit(random.split)(key)
|
|
|
|
#
|
|
|
|
# where `key` and `keys` are both acceptably old-style uint32 arrays
|
|
|
|
# so long as enable_custom_prng is False. The way we handle this is
|
|
|
|
# that `random.split` adapts the input/output by converting to/from
|
|
|
|
# key arrays across its call to `random_split`. So we rely on these
|
|
|
|
# wrap/unwrap casting primitives to allow that conversion under jit.
|
|
|
|
#
|
|
|
|
# We may want to keep both around for testing and debugging escape
|
|
|
|
# hatches. We can rename them `unsafe` for emphasis, and/or issue a
|
|
|
|
# warning on entry to the traceable.
|
|
|
|
#
|
|
|
|
# TODO(frostig): Consider removal once we always enable_custom_prng.
|
|
|
|
|
|
|
|
def random_wrap(base_arr, *, impl):
|
|
|
|
_check_prng_key_data(impl, base_arr)
|
|
|
|
return random_wrap_p.bind(base_arr, impl=impl)
|
|
|
|
|
|
|
|
random_wrap_p = core.Primitive('random_wrap')
|
|
|
|
ad.defjvp_zero(random_wrap_p)
|
|
|
|
|
|
|
|
@random_wrap_p.def_abstract_eval
|
|
|
|
def random_wrap_abstract_eval(base_arr_aval, *, impl):
|
|
|
|
shape = base_arr_shape_to_keys_shape(impl, base_arr_aval.shape)
|
|
|
|
return keys_shaped_array(impl, shape)
|
|
|
|
|
|
|
|
@random_wrap_p.def_impl
|
|
|
|
def random_wrap_impl(base_arr, *, impl):
|
2024-01-29 12:40:47 -08:00
|
|
|
return PRNGKeyArray(impl, base_arr)
|
2022-08-22 13:56:50 -07:00
|
|
|
|
|
|
|
def random_wrap_lowering(ctx, base_arr, *, impl):
|
|
|
|
return [base_arr]
|
|
|
|
|
|
|
|
def random_wrap_batch_rule(batched_args, batch_dims, *, impl):
|
|
|
|
x, = batched_args
|
|
|
|
d, = batch_dims
|
|
|
|
x = batching.bdim_at_front(x, d, 1)
|
|
|
|
return random_wrap(x, impl=impl), 0
|
|
|
|
|
|
|
|
mlir.register_lowering(random_wrap_p, random_wrap_lowering)
|
|
|
|
batching.primitive_batchers[random_wrap_p] = random_wrap_batch_rule
|
|
|
|
|
|
|
|
|
|
|
|
def random_unwrap(keys):
|
2023-07-21 09:48:38 -07:00
|
|
|
if not jnp.issubdtype(keys.dtype, dtypes.prng_key):
|
|
|
|
raise TypeError(f'random_unwrap takes key array operand, got {keys.dtype=}')
|
2022-08-22 13:56:50 -07:00
|
|
|
return random_unwrap_p.bind(keys)
|
|
|
|
|
|
|
|
random_unwrap_p = core.Primitive('random_unwrap')
|
|
|
|
ad.defjvp_zero(random_unwrap_p)
|
|
|
|
batching.defvectorized(random_unwrap_p)
|
|
|
|
|
|
|
|
@random_unwrap_p.def_abstract_eval
|
|
|
|
def random_unwrap_abstract_eval(keys_aval):
|
2023-10-17 15:47:32 -07:00
|
|
|
return core.physical_aval(keys_aval)
|
2022-08-22 13:56:50 -07:00
|
|
|
|
|
|
|
@random_unwrap_p.def_impl
|
|
|
|
def random_unwrap_impl(keys):
|
2023-09-13 16:33:21 -07:00
|
|
|
return keys._base_array
|
2022-08-22 13:56:50 -07:00
|
|
|
|
|
|
|
def random_unwrap_lowering(ctx, keys):
|
|
|
|
return [keys]
|
|
|
|
|
|
|
|
mlir.register_lowering(random_unwrap_p, random_unwrap_lowering)
|
|
|
|
|
|
|
|
|
|
|
|
# -- threefry2x32 PRNG implementation
|
2021-06-08 11:16:33 -07:00
|
|
|
|
|
|
|
|
2023-04-04 11:41:00 -07:00
|
|
|
def _is_threefry_prng_key(key: typing.Array) -> bool:
|
2021-06-08 11:16:33 -07:00
|
|
|
try:
|
|
|
|
return key.shape == (2,) and key.dtype == np.uint32
|
|
|
|
except AttributeError:
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
2023-04-04 11:41:00 -07:00
|
|
|
def threefry_seed(seed: typing.Array) -> typing.Array:
|
2022-08-22 13:56:50 -07:00
|
|
|
"""Create a single raw threefry PRNG key from an integer seed.
|
2021-06-03 21:55:39 -07:00
|
|
|
|
|
|
|
Args:
|
|
|
|
seed: a 64- or 32-bit integer used as the value of the key.
|
|
|
|
|
|
|
|
Returns:
|
2021-06-08 11:16:33 -07:00
|
|
|
The PRNG key contents, modeled as an array of shape (2,) and dtype
|
|
|
|
uint32. The key is constructed from a 64-bit seed by effectively
|
|
|
|
bit-casting to a pair of uint32 values (or from a 32-bit seed by
|
|
|
|
first padding out with zeros).
|
2021-06-03 21:55:39 -07:00
|
|
|
"""
|
2023-04-15 09:51:12 -07:00
|
|
|
return _threefry_seed(seed)
|
|
|
|
|
|
|
|
@partial(jit, inline=True)
|
|
|
|
def _threefry_seed(seed: typing.Array) -> typing.Array:
|
2022-08-22 13:56:50 -07:00
|
|
|
if seed.shape:
|
2021-06-08 11:16:33 -07:00
|
|
|
raise TypeError(f"PRNG key seed must be a scalar; got {seed!r}.")
|
2022-08-22 13:56:50 -07:00
|
|
|
if not np.issubdtype(seed.dtype, np.integer):
|
2021-06-08 11:16:33 -07:00
|
|
|
raise TypeError(f"PRNG key seed must be an integer; got {seed!r}")
|
2023-11-16 01:15:48 +00:00
|
|
|
convert = lambda k: lax.expand_dims(lax.convert_element_type(k, np.uint32), [0])
|
2022-03-07 12:25:01 -08:00
|
|
|
k1 = convert(
|
2022-08-22 13:56:50 -07:00
|
|
|
lax.shift_right_logical(seed, lax_internal._const(seed, 32)))
|
2023-10-09 07:28:18 -07:00
|
|
|
with config.numpy_dtype_promotion('standard'):
|
2022-05-27 11:12:39 -07:00
|
|
|
# TODO(jakevdp): in X64 mode, this can generate 64-bit computations for 32-bit
|
|
|
|
# inputs. We should avoid this.
|
2022-08-22 13:56:50 -07:00
|
|
|
k2 = convert(jnp.bitwise_and(seed, np.uint32(0xFFFFFFFF)))
|
2021-06-03 21:55:39 -07:00
|
|
|
return lax.concatenate([k1, k2], 0)
|
|
|
|
|
|
|
|
|
|
|
|
def _make_rotate_left(dtype):
|
|
|
|
if not jnp.issubdtype(dtype, np.integer):
|
|
|
|
raise TypeError("_rotate_left only accepts integer dtypes.")
|
|
|
|
nbits = np.array(jnp.iinfo(dtype).bits, dtype)
|
|
|
|
|
|
|
|
def _rotate_left(x, d):
|
|
|
|
if lax.dtype(d) != dtype:
|
|
|
|
d = lax.convert_element_type(d, dtype)
|
|
|
|
if lax.dtype(x) != dtype:
|
|
|
|
x = lax.convert_element_type(x, dtype)
|
|
|
|
return lax.shift_left(x, d) | lax.shift_right_logical(x, nbits - d)
|
|
|
|
return _rotate_left
|
|
|
|
|
|
|
|
|
|
|
|
### hash function and split
|
|
|
|
|
|
|
|
def _threefry2x32_abstract_eval(*args):
|
|
|
|
if any(a.dtype != jnp.uint32 for a in args):
|
|
|
|
raise TypeError("Arguments to threefry2x32 must have uint32 type, got {}"
|
|
|
|
.format(args))
|
|
|
|
if all(isinstance(arg, core.ShapedArray) for arg in args):
|
2022-08-22 13:56:50 -07:00
|
|
|
shape = lax_internal.broadcasting_shape_rule(*args)
|
2024-07-25 00:02:55 +00:00
|
|
|
aval = core.ShapedArray(shape, jnp.dtype(jnp.uint32))
|
2021-06-03 21:55:39 -07:00
|
|
|
else:
|
2024-10-30 18:53:16 -07:00
|
|
|
raise TypeError(f"Arguments to threefry2x32 must all be arrays, got {args}")
|
2021-06-03 21:55:39 -07:00
|
|
|
return (aval,) * 2
|
|
|
|
|
|
|
|
|
|
|
|
rotate_left = _make_rotate_left(np.uint32)
|
|
|
|
|
|
|
|
|
|
|
|
def apply_round(v, rot):
|
|
|
|
v = v[:]
|
|
|
|
v[0] = v[0] + v[1]
|
|
|
|
v[1] = rotate_left(v[1], rot)
|
|
|
|
v[1] = v[0] ^ v[1]
|
|
|
|
return v
|
|
|
|
|
|
|
|
|
|
|
|
def rotate_list(xs):
|
|
|
|
return xs[1:] + xs[:1]
|
|
|
|
|
|
|
|
|
|
|
|
def rolled_loop_step(i, state):
|
|
|
|
x, ks, rotations = state
|
|
|
|
for r in rotations[0]:
|
|
|
|
x = apply_round(x, r)
|
|
|
|
new_x = [x[0] + ks[0], x[1] + ks[1] + jnp.asarray(i + 1, dtype=np.uint32)]
|
|
|
|
return new_x, rotate_list(ks), rotate_list(rotations)
|
|
|
|
|
|
|
|
|
|
|
|
def _threefry2x32_lowering(key1, key2, x1, x2, use_rolled_loops=True):
|
|
|
|
"""Apply the Threefry 2x32 hash.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
keypair: a pair of 32bit unsigned integers used for the key.
|
|
|
|
count: an array of dtype uint32 used for the counts.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
An array of dtype uint32 with the same shape as `count`.
|
|
|
|
"""
|
|
|
|
x = [x1, x2]
|
|
|
|
|
|
|
|
rotations = [np.array([13, 15, 26, 6], dtype=np.uint32),
|
|
|
|
np.array([17, 29, 16, 24], dtype=np.uint32)]
|
|
|
|
ks = [key1, key2, key1 ^ key2 ^ np.uint32(0x1BD11BDA)]
|
|
|
|
|
|
|
|
x[0] = x[0] + ks[0]
|
|
|
|
x[1] = x[1] + ks[1]
|
|
|
|
|
|
|
|
if use_rolled_loops:
|
|
|
|
x, _, _ = lax.fori_loop(0, 5, rolled_loop_step, (x, rotate_list(ks), rotations))
|
|
|
|
|
|
|
|
else:
|
|
|
|
for r in rotations[0]:
|
|
|
|
x = apply_round(x, r)
|
|
|
|
x[0] = x[0] + ks[1]
|
|
|
|
x[1] = x[1] + ks[2] + np.uint32(1)
|
|
|
|
|
|
|
|
for r in rotations[1]:
|
|
|
|
x = apply_round(x, r)
|
|
|
|
x[0] = x[0] + ks[2]
|
|
|
|
x[1] = x[1] + ks[0] + np.uint32(2)
|
|
|
|
|
|
|
|
for r in rotations[0]:
|
|
|
|
x = apply_round(x, r)
|
|
|
|
x[0] = x[0] + ks[0]
|
|
|
|
x[1] = x[1] + ks[1] + np.uint32(3)
|
|
|
|
|
|
|
|
for r in rotations[1]:
|
|
|
|
x = apply_round(x, r)
|
|
|
|
x[0] = x[0] + ks[1]
|
|
|
|
x[1] = x[1] + ks[2] + np.uint32(4)
|
|
|
|
|
|
|
|
for r in rotations[0]:
|
|
|
|
x = apply_round(x, r)
|
|
|
|
x[0] = x[0] + ks[2]
|
|
|
|
x[1] = x[1] + ks[0] + np.uint32(5)
|
|
|
|
|
|
|
|
return tuple(x)
|
|
|
|
|
|
|
|
|
2024-05-01 10:32:36 -07:00
|
|
|
_threefry2x32_lowering_rule = mlir.lower_fun(
|
|
|
|
partial(_threefry2x32_lowering, use_rolled_loops=False),
|
|
|
|
multiple_results=True)
|
|
|
|
|
|
|
|
_threefry2x32_cpu_lowering_rule = mlir.lower_fun(
|
|
|
|
partial(_threefry2x32_lowering, use_rolled_loops=True),
|
|
|
|
multiple_results=True)
|
|
|
|
|
|
|
|
|
|
|
|
def _threefry2x32_gpu_lowering_rule(lowering_func, ctx, k1, k2, x1, x2):
|
|
|
|
if not config.threefry_gpu_kernel_lowering.value: # back to default lowering
|
|
|
|
return _threefry2x32_lowering_rule(ctx, k1, k2, x1, x2)
|
|
|
|
|
|
|
|
aval_out, aval_out_2 = ctx.avals_out
|
|
|
|
assert aval_out == aval_out_2
|
|
|
|
k1_aval, k2_aval, x1_aval, x2_aval = ctx.avals_in
|
|
|
|
rank = len(aval_out.shape)
|
|
|
|
if 0 in aval_out.shape:
|
|
|
|
zeros = mlir.full_like_aval(ctx, 0, aval_out)
|
|
|
|
return [zeros, zeros]
|
|
|
|
def _broadcast(x, aval):
|
|
|
|
return mlir.broadcast_in_dim(ctx, x, aval_out,
|
|
|
|
broadcast_dimensions=range(rank - len(aval.shape), rank))
|
|
|
|
|
|
|
|
out_len = reduce(op.mul, aval_out.shape, 1)
|
|
|
|
if not core.is_constant_dim(out_len):
|
|
|
|
length = mlir.eval_dynamic_shape_as_tensor(ctx, [out_len])
|
|
|
|
length = mlir.hlo.convert(
|
|
|
|
ir.RankedTensorType.get((1,), ir.IntegerType.get_signless(64)),
|
|
|
|
length)
|
|
|
|
output_shape = mlir.eval_dynamic_shape_as_tensor(ctx, aval_out.shape)
|
|
|
|
else:
|
|
|
|
length = int(out_len) # will be passed statically
|
|
|
|
output_shape = None
|
|
|
|
|
2024-07-31 08:09:28 -07:00
|
|
|
return lowering_func(
|
|
|
|
(_broadcast(k1, k1_aval), _broadcast(k2, k2_aval)),
|
|
|
|
(_broadcast(x1, x1_aval), _broadcast(x2, x2_aval)), length,
|
|
|
|
output_shape,
|
|
|
|
False, # forward_compatibility_mode
|
|
|
|
)
|
|
|
|
|
2024-05-01 10:32:36 -07:00
|
|
|
|
2021-06-03 21:55:39 -07:00
|
|
|
threefry2x32_p = core.Primitive("threefry2x32")
|
|
|
|
threefry2x32_p.multiple_results = True
|
2023-03-31 08:50:59 -07:00
|
|
|
threefry2x32_p.def_impl(partial(dispatch.apply_primitive, threefry2x32_p))
|
2021-06-03 21:55:39 -07:00
|
|
|
threefry2x32_p.def_abstract_eval(_threefry2x32_abstract_eval)
|
|
|
|
batching.defbroadcasting(threefry2x32_p)
|
2024-05-01 10:32:36 -07:00
|
|
|
mlir.register_lowering(
|
|
|
|
threefry2x32_p, _threefry2x32_lowering_rule)
|
|
|
|
mlir.register_lowering(
|
|
|
|
threefry2x32_p, _threefry2x32_cpu_lowering_rule, platform='cpu')
|
|
|
|
mlir.register_lowering(
|
|
|
|
threefry2x32_p,
|
|
|
|
partial(_threefry2x32_gpu_lowering_rule, gpu_prng.cuda_threefry2x32),
|
|
|
|
platform='cuda')
|
|
|
|
mlir.register_lowering(
|
|
|
|
threefry2x32_p,
|
|
|
|
partial(_threefry2x32_gpu_lowering_rule, gpu_prng.rocm_threefry2x32),
|
|
|
|
platform='rocm')
|
2022-05-05 10:54:53 -07:00
|
|
|
|
2021-06-03 21:55:39 -07:00
|
|
|
|
2022-12-05 11:09:56 -08:00
|
|
|
def iota_2x32_shape(shape):
|
2022-12-05 09:15:27 -08:00
|
|
|
"""Reshaped ``uint64`` iota, as two parallel ``uint32`` arrays.
|
|
|
|
|
|
|
|
Setting aside representation, this function essentially computes the
|
|
|
|
equivalent of::
|
|
|
|
|
2023-04-13 11:48:11 -07:00
|
|
|
jax.lax.iota(dtype=np.uint64, size=math.prod(shape)).reshape(shape)
|
2022-12-05 09:15:27 -08:00
|
|
|
|
|
|
|
However:
|
|
|
|
|
|
|
|
* It returns two parallel ``uint32`` arrays instead of one
|
|
|
|
``uint64`` array. This renders it invariant under either setting of
|
|
|
|
the system-wide ``jax_enable_x64`` configuration flag.
|
|
|
|
|
|
|
|
* It lowers in a way such that the compiler's automatic SPMD
|
|
|
|
partitioner recognizes its partitionability.
|
|
|
|
|
|
|
|
For example::
|
|
|
|
|
|
|
|
>>> import numpy as np
|
|
|
|
>>> from jax import lax
|
|
|
|
>>> from jax._src import prng
|
|
|
|
|
2022-12-05 11:09:56 -08:00
|
|
|
>>> prng.iota_2x32_shape((3, 4))
|
2022-12-05 09:15:27 -08:00
|
|
|
[Array([[0, 0, 0, 0],
|
|
|
|
[0, 0, 0, 0],
|
|
|
|
[0, 0, 0, 0]], dtype=uint32),
|
|
|
|
Array([[ 0, 1, 2, 3],
|
|
|
|
[ 4, 5, 6, 7],
|
|
|
|
[ 8, 9, 10, 11]], dtype=uint32)]
|
|
|
|
|
|
|
|
>>> def reshaped_iota(shape):
|
2023-04-13 11:48:11 -07:00
|
|
|
... return lax.iota(size=math.prod(shape), dtype=np.uint32).reshape(shape)
|
2022-12-05 09:15:27 -08:00
|
|
|
...
|
|
|
|
>>> reshaped_iota((3, 4))
|
|
|
|
Array([[ 0, 1, 2, 3],
|
|
|
|
[ 4, 5, 6, 7],
|
|
|
|
[ 8, 9, 10, 11]], dtype=uint32)
|
|
|
|
|
|
|
|
Args:
|
|
|
|
shape: the output shape
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
A pair of ``uint32`` arrays ``(counts_hi, counts_lo)``, both of
|
|
|
|
shape ``shape``, representing the higher-order and lower-order 32
|
|
|
|
bits of the 64 bit unsigned iota.
|
|
|
|
"""
|
2022-10-28 14:17:34 -07:00
|
|
|
if len(shape) == 0:
|
|
|
|
return (jnp.zeros((), np.dtype('uint32')),) * 2
|
2022-12-05 11:09:56 -08:00
|
|
|
return iota_2x32_shape_p.bind(shape=shape)
|
2022-10-28 14:17:34 -07:00
|
|
|
|
2022-12-05 11:09:56 -08:00
|
|
|
iota_2x32_shape_p = core.Primitive('iota_2x32_shape')
|
|
|
|
iota_2x32_shape_p.multiple_results = True
|
2023-03-31 08:50:59 -07:00
|
|
|
iota_2x32_shape_p.def_impl(partial(dispatch.apply_primitive, iota_2x32_shape_p))
|
2022-10-28 14:17:34 -07:00
|
|
|
|
2022-12-05 11:09:56 -08:00
|
|
|
@iota_2x32_shape_p.def_abstract_eval
|
|
|
|
def iota_2x32_shape_abstract_eval(*, shape):
|
2022-10-28 14:17:34 -07:00
|
|
|
return (core.ShapedArray(shape, np.dtype('uint32')),) * 2
|
|
|
|
|
2023-05-04 09:52:21 +02:00
|
|
|
def bcast_iotas_to_reshaped_iota(
|
2023-05-09 17:55:13 +02:00
|
|
|
add: Callable[[ir.Value, ir.Value], ir.Value],
|
|
|
|
mul: Callable[[core.DimSize, ir.Value], ir.Value],
|
2023-05-04 09:52:21 +02:00
|
|
|
shape: core.Shape,
|
2023-05-09 17:55:13 +02:00
|
|
|
iotas: Sequence[ir.Value]) -> ir.Value:
|
2024-05-17 09:46:36 +01:00
|
|
|
strides: core.Shape = (*(np.cumprod(shape[1:][::-1])[::-1]), 1)
|
|
|
|
return reduce(add, [mul(s, i) for i, s in zip(iotas, strides)])
|
2022-12-05 09:16:19 -08:00
|
|
|
|
2022-12-05 11:09:56 -08:00
|
|
|
def iota_2x32_shape_lowering(ctx, *, shape):
|
2023-05-04 09:52:21 +02:00
|
|
|
aval_out, _ = ctx.avals_out
|
|
|
|
aval_u64 = core.ShapedArray(shape, np.dtype('uint64'))
|
|
|
|
|
2023-05-09 17:55:13 +02:00
|
|
|
def _add(x: ir.Value, y: ir.Value) -> ir.Value:
|
2023-11-17 11:46:24 -08:00
|
|
|
return mlir.hlo.add(x, y)
|
2022-10-28 14:17:34 -07:00
|
|
|
|
2023-05-09 17:55:13 +02:00
|
|
|
def _mul(x: core.DimSize, y: ir.Value) -> ir.Value:
|
2023-05-04 09:52:21 +02:00
|
|
|
if core.is_constant_dim(x):
|
2023-08-17 06:43:31 -07:00
|
|
|
x_const = mlir.ir_constant(np.array(x, np.dtype('uint64')))
|
2023-05-04 09:52:21 +02:00
|
|
|
else:
|
2024-05-16 15:10:01 +01:00
|
|
|
x_shape, = mlir.eval_dynamic_shape(ctx, (x,))
|
2023-11-17 11:46:24 -08:00
|
|
|
x_const = hlo.convert(
|
2023-05-09 17:55:13 +02:00
|
|
|
ir.RankedTensorType.get(
|
2024-05-16 15:10:01 +01:00
|
|
|
[],
|
|
|
|
mlir.dtype_to_ir_type(np.dtype('uint64'))), x_shape)
|
2023-05-04 09:52:21 +02:00
|
|
|
x_bcast = mlir.broadcast_in_dim(ctx, x_const, aval_u64,
|
|
|
|
broadcast_dimensions=[])
|
2023-11-17 11:46:24 -08:00
|
|
|
return mlir.hlo.multiply(x_bcast, y)
|
2022-10-28 14:17:34 -07:00
|
|
|
|
|
|
|
assert len(shape) > 0
|
2023-05-04 09:52:21 +02:00
|
|
|
|
|
|
|
iotas = [mlir.iota(ctx, aval_u64, dimension=dimension)
|
2022-10-28 14:17:34 -07:00
|
|
|
for dimension in range(len(shape))]
|
2022-12-05 09:16:19 -08:00
|
|
|
counts = bcast_iotas_to_reshaped_iota(_add, _mul, shape, iotas)
|
2023-08-17 06:43:31 -07:00
|
|
|
shift = mlir.ir_constant(np.array(32, np.dtype('uint64')))
|
2023-05-04 09:52:21 +02:00
|
|
|
shift = mlir.broadcast_in_dim(ctx, shift, aval_u64,
|
|
|
|
broadcast_dimensions=[])
|
2023-11-17 11:46:24 -08:00
|
|
|
counts_shifted = mlir.hlo.shift_right_logical(counts, shift)
|
|
|
|
counts_lo = mlir.hlo.convert(mlir.aval_to_ir_type(aval_out), counts)
|
|
|
|
counts_hi = mlir.hlo.convert(mlir.aval_to_ir_type(aval_out), counts_shifted)
|
2022-12-05 09:16:19 -08:00
|
|
|
return counts_hi, counts_lo
|
2022-12-05 11:09:56 -08:00
|
|
|
mlir.register_lowering(iota_2x32_shape_p, iota_2x32_shape_lowering)
|
2022-10-28 14:17:34 -07:00
|
|
|
|
|
|
|
|
2021-08-20 13:43:38 -07:00
|
|
|
@partial(jit, inline=True)
|
2021-06-03 21:55:39 -07:00
|
|
|
def threefry_2x32(keypair, count):
|
|
|
|
"""Apply the Threefry 2x32 hash.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
keypair: a pair of 32bit unsigned integers used for the key.
|
|
|
|
count: an array of dtype uint32 used for the counts.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
An array of dtype uint32 with the same shape as `count`.
|
|
|
|
"""
|
|
|
|
key1, key2 = keypair
|
|
|
|
if not lax.dtype(key1) == lax.dtype(key2) == lax.dtype(count) == np.uint32:
|
|
|
|
msg = "threefry_2x32 requires uint32 arguments, got {}"
|
|
|
|
raise TypeError(msg.format([lax.dtype(x) for x in [key1, key2, count]]))
|
|
|
|
|
2023-01-18 12:27:02 +02:00
|
|
|
odd_size = count.size % 2
|
|
|
|
if not isinstance(odd_size, int):
|
2024-10-24 13:07:33 +02:00
|
|
|
msg = ("jax.random functions have limited support for shape polymorphism "
|
|
|
|
"when using threefry. "
|
|
|
|
f"In particular, the array size ({count.size}) must be even.")
|
2023-01-18 12:27:02 +02:00
|
|
|
raise core.InconclusiveDimensionOperation(msg)
|
2021-06-03 21:55:39 -07:00
|
|
|
|
|
|
|
if odd_size:
|
|
|
|
x = list(jnp.split(jnp.concatenate([count.ravel(), np.uint32([0])]), 2))
|
|
|
|
else:
|
|
|
|
x = list(jnp.split(count.ravel(), 2))
|
|
|
|
|
|
|
|
x = threefry2x32_p.bind(key1, key2, x[0], x[1])
|
|
|
|
out = jnp.concatenate(x)
|
|
|
|
assert out.dtype == np.uint32
|
|
|
|
return lax.reshape(out[:-1] if odd_size else out, count.shape)
|
|
|
|
|
|
|
|
|
2023-07-06 13:23:48 -07:00
|
|
|
def threefry_split(key: typing.Array, shape: Shape) -> typing.Array:
|
|
|
|
shape = tuple(unsafe_map(core.concrete_dim_or_error, shape))
|
|
|
|
return _threefry_split(key, shape)
|
2023-06-26 11:52:55 -07:00
|
|
|
|
|
|
|
@partial(jit, static_argnums=(1,))
|
2023-07-06 13:23:48 -07:00
|
|
|
def _threefry_split(key, shape) -> typing.Array:
|
2023-10-09 07:28:18 -07:00
|
|
|
if config.threefry_partitionable.value:
|
2024-05-17 09:46:36 +01:00
|
|
|
return _threefry_split_foldlike(key, shape)
|
2022-11-21 14:35:13 -08:00
|
|
|
else:
|
2024-05-17 09:46:36 +01:00
|
|
|
return _threefry_split_original(key, shape)
|
2021-06-03 21:55:39 -07:00
|
|
|
|
2021-08-20 13:43:38 -07:00
|
|
|
@partial(jit, static_argnums=(1,), inline=True)
|
2023-07-06 13:23:48 -07:00
|
|
|
def _threefry_split_original(key, shape) -> typing.Array:
|
|
|
|
num = math.prod(shape)
|
2021-06-03 21:55:39 -07:00
|
|
|
counts = lax.iota(np.uint32, num * 2)
|
2023-07-06 13:23:48 -07:00
|
|
|
return lax.reshape(threefry_2x32(key, counts), (*shape, 2))
|
2021-06-03 21:55:39 -07:00
|
|
|
|
2022-11-21 14:35:13 -08:00
|
|
|
@partial(jit, static_argnums=(1,), inline=True)
|
2023-07-06 13:23:48 -07:00
|
|
|
def _threefry_split_foldlike(key, shape) -> typing.Array:
|
2022-11-21 14:35:13 -08:00
|
|
|
k1, k2 = key
|
2023-07-06 13:23:48 -07:00
|
|
|
counts1, counts2 = iota_2x32_shape(shape)
|
2022-11-21 14:35:13 -08:00
|
|
|
bits1, bits2 = threefry2x32_p.bind(k1, k2, counts1, counts2)
|
2023-07-06 13:23:48 -07:00
|
|
|
return jnp.stack([bits1, bits2], axis=bits1.ndim)
|
2022-11-21 14:35:13 -08:00
|
|
|
|
2021-06-03 21:55:39 -07:00
|
|
|
|
2023-04-04 11:41:00 -07:00
|
|
|
def threefry_fold_in(key: typing.Array, data: typing.Array) -> typing.Array:
|
2022-08-22 13:56:50 -07:00
|
|
|
assert not data.shape
|
2021-06-08 11:16:33 -07:00
|
|
|
return _threefry_fold_in(key, jnp.uint32(data))
|
2021-06-03 21:55:39 -07:00
|
|
|
|
2023-06-26 11:52:55 -07:00
|
|
|
@jit
|
2021-06-08 11:16:33 -07:00
|
|
|
def _threefry_fold_in(key, data):
|
|
|
|
return threefry_2x32(key, threefry_seed(data))
|
2021-06-03 21:55:39 -07:00
|
|
|
|
|
|
|
|
2023-04-04 11:41:00 -07:00
|
|
|
def threefry_random_bits(key: typing.Array, bit_width, shape):
|
2021-06-03 21:55:39 -07:00
|
|
|
"""Sample uniform random bits of given width and shape using PRNG key."""
|
2021-06-08 11:16:33 -07:00
|
|
|
if not _is_threefry_prng_key(key):
|
2021-10-01 18:15:00 -07:00
|
|
|
raise TypeError("threefry_random_bits got invalid prng key.")
|
2021-06-03 21:55:39 -07:00
|
|
|
if bit_width not in (8, 16, 32, 64):
|
|
|
|
raise TypeError("requires 8-, 16-, 32- or 64-bit field width.")
|
2022-10-25 08:13:55 -07:00
|
|
|
|
2023-10-09 07:28:18 -07:00
|
|
|
if config.threefry_partitionable.value:
|
2022-10-25 08:13:55 -07:00
|
|
|
return _threefry_random_bits_partitionable(key, bit_width, shape)
|
|
|
|
else:
|
|
|
|
return _threefry_random_bits_original(key, bit_width, shape)
|
|
|
|
|
2023-04-04 11:41:00 -07:00
|
|
|
def _threefry_random_bits_partitionable(key: typing.Array, bit_width, shape):
|
2023-02-28 12:40:30 -08:00
|
|
|
if all(core.is_constant_dim(d) for d in shape) and math.prod(shape) > 2 ** 64:
|
2022-10-25 08:13:55 -07:00
|
|
|
raise NotImplementedError('random bits array of size exceeding 2 ** 64')
|
|
|
|
|
|
|
|
k1, k2 = key
|
2022-12-05 11:09:56 -08:00
|
|
|
counts1, counts2 = iota_2x32_shape(shape)
|
2022-10-28 14:39:00 -07:00
|
|
|
bits1, bits2 = threefry2x32_p.bind(k1, k2, counts1, counts2)
|
2022-10-25 08:13:55 -07:00
|
|
|
|
|
|
|
dtype = UINT_DTYPES[bit_width]
|
|
|
|
if bit_width == 64:
|
2022-10-28 14:39:00 -07:00
|
|
|
bits_hi = lax.convert_element_type(bits1, dtype)
|
|
|
|
bits_lo = lax.convert_element_type(bits2, dtype)
|
|
|
|
return lax.shift_left(bits_hi, dtype(32)) | bits_lo
|
|
|
|
elif bit_width == 32:
|
|
|
|
return bits1 ^ bits2
|
2022-10-25 08:13:55 -07:00
|
|
|
else:
|
2022-10-28 14:39:00 -07:00
|
|
|
return lax.convert_element_type(bits1 ^ bits2, dtype)
|
2022-10-25 08:13:55 -07:00
|
|
|
|
|
|
|
@partial(jit, static_argnums=(1, 2), inline=True)
|
2023-04-04 11:41:00 -07:00
|
|
|
def _threefry_random_bits_original(key: typing.Array, bit_width, shape):
|
2023-02-28 12:40:30 -08:00
|
|
|
size = math.prod(shape)
|
2021-06-03 21:55:39 -07:00
|
|
|
# Compute ceil(bit_width * size / 32) in a way that is friendly to shape
|
|
|
|
# polymorphism
|
|
|
|
max_count, r = divmod(bit_width * size, 32)
|
|
|
|
if r > 0:
|
|
|
|
max_count += 1
|
|
|
|
|
|
|
|
if core.is_constant_dim(max_count):
|
|
|
|
nblocks, rem = divmod(max_count, jnp.iinfo(np.uint32).max)
|
|
|
|
else:
|
|
|
|
nblocks, rem = 0, max_count
|
|
|
|
|
|
|
|
if not nblocks:
|
|
|
|
bits = threefry_2x32(key, lax.iota(np.uint32, rem))
|
|
|
|
else:
|
2023-07-06 13:23:48 -07:00
|
|
|
keys = threefry_split(key, (nblocks + 1,))
|
2021-06-03 21:55:39 -07:00
|
|
|
subkeys, last_key = keys[:-1], keys[-1]
|
|
|
|
blocks = vmap(threefry_2x32, in_axes=(0, None))(subkeys, lax.iota(np.uint32, jnp.iinfo(np.uint32).max))
|
|
|
|
last = threefry_2x32(last_key, lax.iota(np.uint32, rem))
|
|
|
|
bits = lax.concatenate([blocks.ravel(), last], 0)
|
|
|
|
|
|
|
|
dtype = UINT_DTYPES[bit_width]
|
|
|
|
if bit_width == 64:
|
|
|
|
bits = [lax.convert_element_type(x, dtype) for x in jnp.split(bits, 2)]
|
|
|
|
bits = lax.shift_left(bits[0], dtype(32)) | bits[1]
|
|
|
|
elif bit_width in [8, 16]:
|
|
|
|
# this is essentially bits.view(dtype)[:size]
|
|
|
|
bits = lax.bitwise_and(
|
|
|
|
np.uint32(np.iinfo(dtype).max),
|
|
|
|
lax.shift_right_logical(
|
|
|
|
lax.broadcast(bits, (1,)),
|
|
|
|
lax.mul(
|
|
|
|
np.uint32(bit_width),
|
|
|
|
lax.broadcasted_iota(np.uint32, (32 // bit_width, 1), 0)
|
|
|
|
)
|
|
|
|
)
|
|
|
|
)
|
2022-06-20 10:48:15 +02:00
|
|
|
bits = lax.reshape(bits, ((max_count * 32 // bit_width),), (1, 0))
|
2021-06-03 21:55:39 -07:00
|
|
|
bits = lax.convert_element_type(bits, dtype)[:size]
|
|
|
|
return lax.reshape(bits, shape)
|
2021-06-08 11:16:33 -07:00
|
|
|
|
|
|
|
|
|
|
|
threefry_prng_impl = PRNGImpl(
|
|
|
|
key_shape=(2,),
|
|
|
|
seed=threefry_seed,
|
|
|
|
split=threefry_split,
|
|
|
|
random_bits=threefry_random_bits,
|
2022-08-22 13:56:50 -07:00
|
|
|
fold_in=threefry_fold_in,
|
2023-10-03 18:04:14 -07:00
|
|
|
name='threefry2x32',
|
2022-08-22 13:56:50 -07:00
|
|
|
tag='fry')
|
2021-10-01 18:15:00 -07:00
|
|
|
|
2023-10-03 18:04:14 -07:00
|
|
|
register_prng(threefry_prng_impl)
|
|
|
|
|
2021-10-01 18:15:00 -07:00
|
|
|
|
2022-08-22 13:56:50 -07:00
|
|
|
# -- RngBitGenerator PRNG implementation
|
2021-10-01 18:15:00 -07:00
|
|
|
|
|
|
|
# This code is experimental!
|
|
|
|
# https://www.tensorflow.org/xla/operation_semantics#rngbitgenerator
|
|
|
|
# Notice that the RngBitGenerator operations are not guaranteed to be
|
|
|
|
# stable/deterministic across backends or compiler versions. Correspondingly, we
|
|
|
|
# reserve the right to change any of these implementations at any time!
|
|
|
|
|
2023-04-04 11:41:00 -07:00
|
|
|
def _rbg_seed(seed: typing.Array) -> typing.Array:
|
2022-08-22 13:56:50 -07:00
|
|
|
assert not seed.shape
|
2021-10-01 18:15:00 -07:00
|
|
|
halfkey = threefry_seed(seed)
|
Revert: https://github.com/google/jax/pull/10221 (2nd revert)
Prefer jnp.tile over concatenate.
jnp.tile generates a jaxpr like the following:
```
{ lambda ; a:i32[720192]. let
b:i32[1,720192] = reshape[dimensions=None new_sizes=(1, 720192)] a
c:i32[720192] = squeeze[dimensions=(0,)] b
d:i32[2,720192] = broadcast_in_dim[
broadcast_dimensions=(1,)
shape=(2, 720192)
] c
e:i32[1440384] = reshape[dimensions=None new_sizes=(1440384,)] d
in (e,) }
```
whereas lax.concatenate generates the following jaxpr:
```
{ lambda ; a:i32[720192]. let
b:i32[1440384] = concatenate[dimension=0] a a
in (b,) }
```
It seems the TPU compiler isn't doing as good a job with laying out memory for the formulation with `jnp.tile`. `reshape` in particular can be difficult for it to handle well, and it's best to avoid it when possible.
Since the benefit was marginal (a simpler jaxpr... but is it? Really?) and the cost is real (a user's model broke), we should revert this change.
PiperOrigin-RevId: 444287005
2022-04-25 09:15:25 -07:00
|
|
|
return jnp.concatenate([halfkey, halfkey])
|
2021-10-01 18:15:00 -07:00
|
|
|
|
2023-07-06 13:23:48 -07:00
|
|
|
def _rbg_split(key: typing.Array, shape: Shape) -> typing.Array:
|
2023-10-09 07:28:18 -07:00
|
|
|
if config.threefry_partitionable.value:
|
2022-11-21 14:35:13 -08:00
|
|
|
_threefry_split = _threefry_split_foldlike
|
|
|
|
else:
|
|
|
|
_threefry_split = _threefry_split_original
|
2023-07-06 13:23:48 -07:00
|
|
|
halfkeys = key.reshape(2, 2)
|
2022-11-21 14:35:13 -08:00
|
|
|
return vmap(
|
2023-07-06 13:23:48 -07:00
|
|
|
_threefry_split, (0, None), len(shape))(halfkeys, shape).reshape(
|
|
|
|
*shape, 4)
|
2021-10-06 21:54:22 -07:00
|
|
|
|
2023-04-04 11:41:00 -07:00
|
|
|
def _rbg_fold_in(key: typing.Array, data: typing.Array) -> typing.Array:
|
2022-08-22 13:56:50 -07:00
|
|
|
assert not data.shape
|
2021-10-07 21:19:06 -07:00
|
|
|
return vmap(_threefry_fold_in, (0, None), 0)(key.reshape(2, 2), data).reshape(4)
|
2021-10-01 18:15:00 -07:00
|
|
|
|
2023-04-04 11:41:00 -07:00
|
|
|
def _rbg_random_bits(key: typing.Array, bit_width: int, shape: Sequence[int]
|
|
|
|
) -> typing.Array:
|
2021-10-01 18:15:00 -07:00
|
|
|
if not key.shape == (4,) and key.dtype == jnp.dtype('uint32'):
|
|
|
|
raise TypeError("_rbg_random_bits got invalid prng key.")
|
|
|
|
if bit_width not in (8, 16, 32, 64):
|
|
|
|
raise TypeError("requires 8-, 16-, 32- or 64-bit field width.")
|
|
|
|
_, bits = lax.rng_bit_generator(key, shape, dtype=UINT_DTYPES[bit_width])
|
|
|
|
return bits
|
|
|
|
|
|
|
|
rbg_prng_impl = PRNGImpl(
|
|
|
|
key_shape=(4,),
|
|
|
|
seed=_rbg_seed,
|
|
|
|
split=_rbg_split,
|
|
|
|
random_bits=_rbg_random_bits,
|
2022-08-22 13:56:50 -07:00
|
|
|
fold_in=_rbg_fold_in,
|
2023-10-03 18:04:14 -07:00
|
|
|
name='rbg',
|
2022-08-22 13:56:50 -07:00
|
|
|
tag='rbg')
|
2021-10-06 21:54:22 -07:00
|
|
|
|
2023-10-03 18:04:14 -07:00
|
|
|
register_prng(rbg_prng_impl)
|
|
|
|
|
|
|
|
|
2023-07-06 13:23:48 -07:00
|
|
|
def _unsafe_rbg_split(key: typing.Array, shape: Shape) -> typing.Array:
|
2021-10-06 21:54:22 -07:00
|
|
|
# treat 10 iterations of random bits as a 'hash function'
|
2023-07-06 13:23:48 -07:00
|
|
|
num = math.prod(shape)
|
2021-10-06 21:54:22 -07:00
|
|
|
_, keys = lax.rng_bit_generator(key, (10 * num, 4), dtype='uint32')
|
2023-07-06 13:23:48 -07:00
|
|
|
return lax.slice_in_dim(
|
|
|
|
keys, start_index=None, limit_index=None, stride=10).reshape(*shape, 4)
|
2021-10-06 21:54:22 -07:00
|
|
|
|
2023-04-04 11:41:00 -07:00
|
|
|
def _unsafe_rbg_fold_in(key: typing.Array, data: typing.Array) -> typing.Array:
|
2022-08-22 13:56:50 -07:00
|
|
|
assert not data.shape
|
2021-10-06 21:54:22 -07:00
|
|
|
_, random_bits = lax.rng_bit_generator(_rbg_seed(data), (10, 4), dtype='uint32')
|
|
|
|
return key ^ random_bits[-1]
|
|
|
|
|
|
|
|
unsafe_rbg_prng_impl = PRNGImpl(
|
|
|
|
key_shape=(4,),
|
|
|
|
seed=_rbg_seed,
|
|
|
|
split=_unsafe_rbg_split,
|
|
|
|
random_bits=_rbg_random_bits,
|
2022-08-22 13:56:50 -07:00
|
|
|
fold_in=_unsafe_rbg_fold_in,
|
2023-10-03 18:04:14 -07:00
|
|
|
name='unsafe_rbg',
|
2022-08-22 13:56:50 -07:00
|
|
|
tag='urbg')
|
2023-10-03 18:04:14 -07:00
|
|
|
|
|
|
|
register_prng(unsafe_rbg_prng_impl)
|