Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion flax/serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,12 @@ def _is_namedtuple(x):
return isinstance(x, tuple) and hasattr(x, '_fields')


def _is_prng_key(x):
return isinstance(x, jax.Array) and jax.dtypes.issubdtype(
x.dtype, jax.dtypes.prng_key
)


def from_state_dict(target, state: dict[str, Any], name: str = '.'):
"""Restores the state of the given target using a state dict.

Expand All @@ -87,19 +93,31 @@ def from_state_dict(target, state: dict[str, Any], name: str = '.'):
else:
ty = type(target)
if ty not in _STATE_DICT_REGISTRY:
if _is_prng_key(target) and isinstance(state, dict):
return jax.random.wrap_key_data(state['data'], impl=state['impl'])
return state
ty_from_state_dict = _STATE_DICT_REGISTRY[ty][1]
with _record_path(name):
return ty_from_state_dict(target, state)


def to_state_dict(target) -> dict[str, Any]:
"""Returns a dictionary with the state of the given target."""
"""Returns a dictionary with the state of the given target.

Typed JAX PRNG keys store their registered implementation name and key data.
"""
if _is_namedtuple(target):
ty = _NamedTuple
else:
ty = type(target)
if ty not in _STATE_DICT_REGISTRY:
if _is_prng_key(target):
impl = jax.random.key_impl(target)
if not isinstance(impl, str):
raise ValueError(
'Serializing a PRNG key requires a JAX-registered PRNG implementation.'
)
return {'impl': impl, 'data': jax.random.key_data(target)}
return target

ty_to_state_dict = _STATE_DICT_REGISTRY[ty][0]
Expand Down
49 changes: 49 additions & 0 deletions tests/serialization_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import pytest
from absl.testing import absltest, parameterized
from jax import random
from jax.extend import random as extend_random
from jax.tree_util import Partial

from flax import linen as nn
Expand Down Expand Up @@ -136,6 +137,54 @@ def test_pass_through_serialization(self):
expected_box = Box(value=123)
self.assertEqual(restored_box, expected_box)

@parameterized.product(impl=['threefry2x32', 'rbg'], shape=[(), (2, 3)])
def test_dataclass_with_typed_prng_key(self, impl, shape):
@struct.dataclass
class WithKey:
key: jax.Array

saved = WithKey(random.split(random.key(42, impl=impl), shape))
target = WithKey(random.split(random.key(0, impl=impl), shape))
restored = serialization.from_bytes(target, serialization.to_bytes(saved))

self.assertEqual(restored.key.dtype, saved.key.dtype)
np.testing.assert_array_equal(
random.key_data(restored.key), random.key_data(saved.key)
)
self.assertIs(
serialization.from_state_dict(target, {'key': saved.key}).key, saved.key
)

def test_typed_prng_key_keeps_saved_implementation(self):
saved = random.key(42, impl='rbg')
target = random.key(0, impl='unsafe_rbg')
restored = serialization.from_bytes(target, serialization.to_bytes(saved))
self.assertEqual(restored.dtype, saved.dtype)
np.testing.assert_array_equal(
random.key_data(random.split(restored)),
random.key_data(random.split(saved)),
)

def test_unregistered_prng_implementation(self):
base = extend_random.threefry_prng_impl
impl = extend_random.define_prng_impl(
key_shape=base.key_shape,
seed=base.seed,
split=base.split,
random_bits=base.random_bits,
fold_in=base.fold_in,
name='test_unregistered',
)
with self.assertRaisesRegex(ValueError, 'JAX-registered PRNG'):
serialization.to_bytes(random.key(42, impl=impl))

def test_legacy_prng_key_stays_uint32(self):
saved = random.PRNGKey(42)
for target in (random.PRNGKey(0), random.key(0)):
restored = serialization.from_bytes(target, serialization.to_bytes(saved))
self.assertEqual(restored.dtype, saved.dtype)
np.testing.assert_array_equal(restored, saved)

def test_model_serialization(self):
rng = random.key(0)
module = nn.Dense(features=1, kernel_init=nn.initializers.ones_init())
Expand Down