Something went wrong. Try again.
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768import loggingimport os
import jaxfrom rejax import PPO
from viberl.env import render_gymnaxfrom viberl.utils import ( argparser, build_eval_callback, create_checkpointer_from_config, create_eval_logger, create_mlflow_logger, generate_experiment_config, setup_logger, tree_unstack,)
parser = argparser()args = parser.parse_args()config = generate_experiment_config(args.config_file)
setup_logger(config)_LOGGER = logging.getLogger(__name__)
# wandb.init(# project="rl-sandbox",# group=config["experiment"]["experiment_name"],# tags=config["experiment"]["tags"],# config=config# )# JAX handles reproducablity through the key system. Starting from a root key (can be thought of as a seed)# keys can be split to control PRNG across a vector of agents# Here we create N splits of the root key, one for each agent we will train# Under the hood, each PPO instance will also split their key M times for each of the envs it will train acrossroot_key = jax.random.key(config["experiment"]["root_seed"])agent_keys = jax.random.split(root_key, config["experiment"]["num_agent_seeds"])
# Here we create a vector of N agents that we will train seeded with their own key derived from the root keyalgo = PPO.create(**config["algorithm"])# We then insert the callbacks for logging and reporting on training process into each agent# These transforms are functional so you get a new agent out instead of modifying in placealgo = algo.replace( eval_callback=build_eval_callback( algo, [ create_eval_logger(), create_mlflow_logger(config), create_checkpointer_from_config(config), ], ))
# We then can vectorize across NxM instances of agents and envs and train these in parallel# This can just be run as JIT, but further gains can be gotten from lowering and AOT compiling the training function_LOGGER.info("Compiling training function...")vmap_train = jax.jit(jax.vmap(algo.train)).lower(agent_keys).compile()
_LOGGER.info("Training...")train_states, results = vmap_train(agent_keys)print(results)agent_ts = tree_unstack(train_states)
policy = algo.make_act(agent_ts[0])jit_policy = jax.jit(policy)vis, reward = render_gymnax(jit_policy, config, root_key)vis.animate(f"{os.getcwd()}/{config['experiment']['results_dir']}/train_ppo.gif")