From 69b3235e4b814310aae4e8a6c8fbef3213fcdb20 Mon Sep 17 00:00:00 2001 From: emme1t <149944796+emme1t@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:42:29 -0800 Subject: [PATCH] Preserve typed PRNG keys when serializing Flax state --- flax/serialization.py | 20 ++++++++++++++- tests/serialization_test.py | 49 +++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/flax/serialization.py b/flax/serialization.py index 05b4565e4..cb2cc1cc9 100644 --- a/flax/serialization.py +++ b/flax/serialization.py @@ -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. @@ -87,6 +93,8 @@ 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): @@ -94,12 +102,22 @@ def from_state_dict(target, state: dict[str, Any], name: str = '.'): 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] diff --git a/tests/serialization_test.py b/tests/serialization_test.py index 5e275eb8c..3d873179e 100644 --- a/tests/serialization_test.py +++ b/tests/serialization_test.py @@ -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 @@ -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())