-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #59 from epignatelli/examples
Add examples and make sure obs match those in minigrid
- Loading branch information
Showing
44 changed files
with
1,746 additions
and
521 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,97 @@ | ||
from dataclasses import asdict, dataclass | ||
import time | ||
import wandb | ||
|
||
import jax | ||
import numpy as np | ||
import jax.numpy as jnp | ||
import flax.linen as nn | ||
from flax.linen.initializers import constant, orthogonal | ||
import tyro | ||
import navix as nx | ||
from navix.environments.environment import Environment | ||
from navix.agents import PPO, PPOHparams, ActorCritic | ||
|
||
|
||
def FlattenObsWrapper(env: Environment): | ||
flatten_obs_fn = lambda x: jnp.ravel(env.observation_fn(x)) | ||
flatten_obs_shape = (int(np.prod(env.observation_space.shape)),) | ||
return env.replace( | ||
observation_fn=flatten_obs_fn, | ||
observation_space=env.observation_space.replace(shape=flatten_obs_shape), | ||
) | ||
|
||
|
||
@dataclass | ||
class Args: | ||
project_name = "navix-baselines" | ||
budget: int = 10_000_000 | ||
seeds_offset: int = 0 | ||
n_seeds: int = 10 | ||
|
||
|
||
if __name__ == "__main__": | ||
args = tyro.cli(Args) | ||
|
||
ppo_hparams = PPOHparams(budget=args.budget) | ||
# create environments | ||
for env_id in nx.registry(): | ||
# init logging | ||
config = {**vars(args), **asdict(ppo_hparams)} | ||
wandb.init(project=args.project_name, config=config) | ||
|
||
# init environment | ||
env = FlattenObsWrapper(nx.make(env_id)) | ||
|
||
# create agent | ||
network = nn.Sequential( | ||
[ | ||
nn.Dense( | ||
64, kernel_init=orthogonal(np.sqrt(2)), bias_init=constant(0.0) | ||
), | ||
nn.tanh, | ||
nn.Dense( | ||
64, kernel_init=orthogonal(np.sqrt(2)), bias_init=constant(0.0) | ||
), | ||
nn.tanh, | ||
] | ||
) | ||
agent = PPO( | ||
hparams=ppo_hparams, | ||
network=ActorCritic(action_dim=len(env.action_set)), | ||
env=env, | ||
) | ||
|
||
# train agent | ||
seeds = range(args.seeds_offset, args.seeds_offset + args.n_seeds) | ||
rngs = jnp.asarray([jax.random.PRNGKey(seed) for seed in seeds]) | ||
train_fn = jax.vmap(agent.train) | ||
|
||
print("Compiling training function...") | ||
start_time = time.time() | ||
train_fn = jax.jit(train_fn).lower(rngs).compile() | ||
compilation_time = time.time() - start_time | ||
print(f"Compilation time cost: {compilation_time}") | ||
|
||
print("Training agent...") | ||
start_time = time.time() | ||
train_state, logs = train_fn(rngs) | ||
training_time = time.time() - start_time | ||
print(f"Training time cost: {training_time}") | ||
|
||
print("Logging final results to wandb...") | ||
start_time = time.time() | ||
# transpose logs tree | ||
logs = jax.tree_map(lambda *args: jnp.stack(args), *logs) | ||
for log in logs: | ||
agent.log_on_train_end(log) | ||
logging_time = time.time() - start_time | ||
print(f"Logging time cost: {logging_time}") | ||
|
||
print("Training complete") | ||
print(f"Compilation time cost: {compilation_time}") | ||
print(f"Training time cost: {training_time}") | ||
total_time = compilation_time + training_time | ||
print(f"Logging time cost: {logging_time}") | ||
total_time += logging_time | ||
print(f"Total time cost: {total_time}") |
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,60 @@ | ||
from dataclasses import dataclass, field | ||
import tyro | ||
import numpy as np | ||
import jax.numpy as jnp | ||
import navix as nx | ||
from navix import observations | ||
from navix.agents import PPO, PPOHparams, ActorCritic | ||
from navix.environments.environment import Environment | ||
|
||
# set persistent compilation cache directory | ||
# jax.config.update("jax_compilation_cache_dir", "/tmp/jax-cache/") | ||
|
||
|
||
@dataclass | ||
class Args: | ||
project_name = "navix-examples" | ||
seeds_offset: int = 0 | ||
n_seeds: int = 1 | ||
# env | ||
env_id: str = "Navix-Empty-Random-5x5-v0" | ||
discount: float = 0.99 | ||
# ppo | ||
ppo_config: PPOHparams = field(default_factory=PPOHparams) | ||
|
||
|
||
if __name__ == "__main__": | ||
args = tyro.cli(Args) | ||
|
||
def FlattenObsWrapper(env: Environment): | ||
flatten_obs_fn = lambda x: jnp.ravel(env.observation_fn(x)) | ||
flatten_obs_shape = (int(np.prod(env.observation_space.shape)),) | ||
return env.replace( | ||
observation_fn=flatten_obs_fn, | ||
observation_space=env.observation_space.replace(shape=flatten_obs_shape), | ||
) | ||
|
||
env = nx.make( | ||
args.env_id, | ||
observation_fn=observations.symbolic_first_person, | ||
gamma=args.discount, | ||
) | ||
env = FlattenObsWrapper(env) | ||
|
||
agent = PPO( | ||
hparams=args.ppo_config, | ||
network=ActorCritic( | ||
action_dim=len(env.action_set), | ||
), | ||
env=env, | ||
) | ||
|
||
experiment = nx.Experiment( | ||
name=args.project_name, | ||
budget=1_000_000, | ||
agent=agent, | ||
env=env, | ||
env_id=args.env_id, | ||
seeds=tuple(range(args.seeds_offset, args.seeds_offset + args.n_seeds)), | ||
) | ||
train_state, logs = experiment.run() |
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,22 @@ | ||
# Copyright 2023 The Navix Authors. | ||
|
||
# Licensed to the Apache Software Foundation (ASF) under one | ||
# or more contributor license agreements. See the NOTICE file | ||
# distributed with this work for additional information | ||
# regarding copyright ownership. The ASF licenses this file | ||
# to you 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. | ||
|
||
|
||
from .ppo import PPO, PPOHparams as PPOHparams | ||
from .models import MLPEncoder, ConvEncoder, ActorCritic |
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,20 @@ | ||
from dataclasses import dataclass | ||
from typing import Dict, Tuple | ||
import jax | ||
from flax import struct | ||
from flax.training.train_state import TrainState | ||
|
||
|
||
@dataclass | ||
class HParams: | ||
debug: bool = False | ||
|
||
|
||
class Agent(struct.PyTreeNode): | ||
hparams: HParams | ||
|
||
def train(self, rng: jax.Array) -> Tuple[TrainState, Dict[str, jax.Array]]: | ||
raise NotImplementedError | ||
|
||
def log_on_train_end(self, logs: Dict[str, jax.Array]): | ||
raise NotImplementedError |
Oops, something went wrong.