-
Notifications
You must be signed in to change notification settings - Fork 271
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
PiperOrigin-RevId: 723378503 Change-Id: I1b63d2f9dc5f49009bbafe4875baadfe51ed9afd
- Loading branch information
Showing
7 changed files
with
379 additions
and
89 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
# Copyright 2024 The Brax 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 | ||
# | ||
# http://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. | ||
|
||
"""Checkpointing for SAC.""" | ||
|
||
import json | ||
from typing import Any, Union | ||
|
||
from brax.training import checkpoint | ||
from brax.training import types | ||
from brax.training.agents.sac import networks as sac_networks | ||
from etils import epath | ||
from ml_collections import config_dict | ||
|
||
_CONFIG_FNAME = 'sac_network_config.json' | ||
|
||
|
||
def save( | ||
path: Union[str, epath.Path], | ||
step: int, | ||
params: Any, | ||
config: config_dict.ConfigDict, | ||
): | ||
"""Saves a checkpoint.""" | ||
return checkpoint.save(path, step, params, config, _CONFIG_FNAME) | ||
|
||
|
||
def load( | ||
path: Union[str, epath.Path], | ||
): | ||
"""Loads SAC checkpoint.""" | ||
return checkpoint.load(path) | ||
|
||
|
||
def network_config( | ||
observation_size: types.ObservationSize, | ||
action_size: int, | ||
normalize_observations: bool, | ||
network_factory: types.NetworkFactory[sac_networks.SACNetworks], | ||
) -> config_dict.ConfigDict: | ||
"""Returns a config dict for re-creating a network from a checkpoint.""" | ||
return checkpoint.network_config( | ||
observation_size, action_size, normalize_observations, network_factory | ||
) | ||
|
||
|
||
def _get_network( | ||
config: config_dict.ConfigDict, | ||
network_factory: types.NetworkFactory[sac_networks.SACNetworks], | ||
) -> sac_networks.SACNetworks: | ||
"""Generates a SAC network given config.""" | ||
return checkpoint.get_network(config, network_factory) # pytype: disable=bad-return-type | ||
|
||
|
||
def load_policy( | ||
path: Union[str, epath.Path], | ||
network_factory: types.NetworkFactory[ | ||
sac_networks.SACNetworks | ||
] = sac_networks.make_sac_networks, | ||
deterministic: bool = True, | ||
): | ||
"""Loads policy inference function from SAC checkpoint.""" | ||
path = epath.Path(path) | ||
|
||
config_path = path.parent / _CONFIG_FNAME | ||
if not config_path.exists(): | ||
raise ValueError(f'SAC config file not found at {config_path.as_posix()}') | ||
|
||
config = config_dict.create(**json.loads(config_path.read_text())) | ||
|
||
params = load(path) | ||
sac_network = _get_network(config, network_factory) | ||
make_inference_fn = sac_networks.make_inference_fn(sac_network) | ||
|
||
return make_inference_fn(params, deterministic=deterministic) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
# Copyright 2024 The Brax 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 | ||
# | ||
# http://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. | ||
|
||
"""Test PPO checkpointing.""" | ||
|
||
import functools | ||
|
||
from absl import flags | ||
from absl.testing import absltest | ||
from brax.training.acme import running_statistics | ||
from brax.training.agents.sac import checkpoint | ||
from brax.training.agents.sac import losses as sac_losses | ||
from brax.training.agents.sac import networks as sac_networks | ||
from etils import epath | ||
import jax | ||
from jax import numpy as jp | ||
|
||
|
||
class CheckpointTest(absltest.TestCase): | ||
|
||
def setUp(self): | ||
super().setUp() | ||
flags.FLAGS.mark_as_parsed() | ||
|
||
def test_sac_params_config(self): | ||
network_factory = functools.partial( | ||
sac_networks.make_sac_networks, | ||
hidden_layer_sizes=(16, 21, 13), | ||
) | ||
config = checkpoint.network_config( | ||
action_size=3, | ||
observation_size=1, | ||
normalize_observations=True, | ||
network_factory=network_factory, | ||
) | ||
self.assertEqual( | ||
config.network_factory_kwargs.to_dict()["hidden_layer_sizes"], | ||
(16, 21, 13), | ||
) | ||
self.assertEqual(config.action_size, 3) | ||
self.assertEqual(config.observation_size, 1) | ||
|
||
def test_save_and_load_checkpoint(self): | ||
path = self.create_tempdir("test") | ||
network_factory = functools.partial( | ||
sac_networks.make_sac_networks, | ||
hidden_layer_sizes=(16, 21, 13), | ||
) | ||
config = checkpoint.network_config( | ||
observation_size=1, | ||
action_size=3, | ||
normalize_observations=True, | ||
network_factory=network_factory, | ||
) | ||
|
||
# Generate network params for saving a dummy checkpoint. | ||
normalize = lambda x, y: x | ||
if config.normalize_observations: | ||
normalize = running_statistics.normalize | ||
sac_network = network_factory( | ||
config.observation_size, | ||
config.action_size, | ||
preprocess_observations_fn=normalize, | ||
**config.network_factory_kwargs, | ||
) | ||
dummy_key = jax.random.PRNGKey(0) | ||
normalizer_params = running_statistics.init_state( | ||
jax.tree_util.tree_map(jp.zeros, config.observation_size) | ||
) | ||
params = (normalizer_params, sac_network.policy_network.init(dummy_key)) | ||
|
||
# Save and load a checkpoint. | ||
checkpoint.save( | ||
path.full_path, | ||
step=1, | ||
params=params, | ||
config=config, | ||
) | ||
|
||
policy_fn = checkpoint.load_policy( | ||
epath.Path(path.full_path) / "000000000001", | ||
) | ||
out = policy_fn(jp.zeros(1), jax.random.PRNGKey(0)) | ||
self.assertEqual(out[0].shape, (3,)) | ||
|
||
|
||
if __name__ == "__main__": | ||
absltest.main() |
Oops, something went wrong.