Skip to content

Commit

Permalink
Add test of NNX with orbax.checkpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
jakevdp committed Aug 21, 2024
1 parent fc4a574 commit 3d8162d
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
3 changes: 3 additions & 0 deletions jax_ml_stack/tests/test_nnx_with_optax.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,6 @@ def loss(model, x=x, y=y):
final_loss = loss(model)

self.assertNotAlmostEqual(initial_loss, final_loss)

if __name__ == '__main__':
unittest.main()
70 changes: 70 additions & 0 deletions jax_ml_stack/tests/test_nnx_with_orbax.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# Copyright 2024 The JAX Authors.
#
# 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.


import unittest
import numpy as np
import jax
import jax.numpy as jnp
from flax import nnx
import orbax.checkpoint as ocp


class SimpleModel(nnx.Module):

def __init__(self, rngs):
self.layer1 = nnx.Linear(2, 5, rngs=rngs)
self.layer2 = nnx.Linear(5, 3, rngs=rngs)

def __call__(self, x):
for layer in [self.layer1, self.layer2]:
x = layer(x)
return x


class NNXOrbaxTest(unittest.TestCase):

def setUp(self):
options = ocp.CheckpointManagerOptions(
create=True, max_to_keep=3, keep_period=2, step_prefix='test')
self.manager = ocp.CheckpointManager(
ocp.test_utils.erase_and_create_empty('/tmp/test-checkpoint/'),
ocp.Checkpointer(ocp.PyTreeCheckpointHandler()),
options=options
)

def test_nnx_orbax_checkpoint(self):
key = jax.random.key(1701)
x = jax.random.normal(key, (1, 2))
y = jnp.ones((1, 3))

model = SimpleModel(nnx.Rngs(0))

# Create the checkpoint
graphdef, state = nnx.split(model)
abstract_state = jax.tree.map(ocp.utils.to_shape_dtype_struct, state)

restore_args = ocp.checkpoint_utils.construct_restore_args(abstract_state)
self.manager.save(0, state)
self.manager.wait_until_finished()

restored_state = self.manager.restore(
0, items=abstract_state, restore_kwargs={'restore_args': restore_args})
restored_model = nnx.merge(graphdef, restored_state)

self.assertEqual(type(model), type(restored_model))
jax.tree.map(np.testing.assert_array_equal, state, restored_state)

if __name__ == '__main__':
unittest.main()

0 comments on commit 3d8162d

Please sign in to comment.