file_path
stringlengths
21
224
content
stringlengths
0
80.8M
Toni-SM/skrl/docs/source/examples/isaacgym/jax_anymal_terrain_ppo.py
import isaacgym import flax.linen as nn import jax import jax.numpy as jnp # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.jax import load_isaacgym_env_preview4 from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.resources.schedulers.jax import KLAdaptiveRL from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "jax" # or "numpy" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(512)(inputs["states"])) x = nn.elu(nn.Dense(256)(x)) x = nn.elu(nn.Dense(128)(x)) x = nn.Dense(self.num_actions)(x) log_std = self.param("log_std", lambda _: jnp.zeros(self.num_actions)) return x, log_std, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(512)(inputs["states"])) x = nn.elu(nn.Dense(256)(x)) x = nn.elu(nn.Dense(128)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the Isaac Gym environment env = load_isaacgym_env_preview4(task_name="AnymalTerrain") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=24, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) models["value"] = Value(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 24 # memory_size cfg["learning_epochs"] = 5 cfg["mini_batches"] = 6 # 24 * 4096 / 16384 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 3e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.001 cfg["value_loss_scale"] = 1.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = None cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 180 cfg["experiment"]["checkpoint_interval"] = 1800 cfg["experiment"]["directory"] = "runs/jax/AnymalTerrain" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 36000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train() # # --------------------------------------------------------- # # comment the code above: `trainer.train()`, and... # # uncomment the following lines to evaluate a trained agent # # --------------------------------------------------------- # from skrl.utils.huggingface import download_model_from_huggingface # # download the trained agent's checkpoint from Hugging Face Hub and load it # path = download_model_from_huggingface("skrl/IsaacGymEnvs-AnymalTerrain-PPO", filename="agent.pickle") # agent.load(path) # # start evaluation # trainer.eval()
Toni-SM/skrl/docs/source/examples/isaacgym/jax_ball_balance_ppo.py
import isaacgym import flax.linen as nn import jax import jax.numpy as jnp # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.jax import load_isaacgym_env_preview4 from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.resources.schedulers.jax import KLAdaptiveRL from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "jax" # or "numpy" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(128)(inputs["states"])) x = nn.elu(nn.Dense(64)(x)) x = nn.elu(nn.Dense(32)(x)) x = nn.Dense(self.num_actions)(x) log_std = self.param("log_std", lambda _: jnp.zeros(self.num_actions)) return x, log_std, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(128)(inputs["states"])) x = nn.elu(nn.Dense(64)(x)) x = nn.elu(nn.Dense(32)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the Isaac Gym environment env = load_isaacgym_env_preview4(task_name="BallBalance") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=16, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) models["value"] = Value(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 16 # memory_size cfg["learning_epochs"] = 8 cfg["mini_batches"] = 8 # 16 * 4096 / 8192 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 3e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 2.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.1 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 20 cfg["experiment"]["checkpoint_interval"] = 200 cfg["experiment"]["directory"] = "runs/jax/BallBalance" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 4000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train() # # --------------------------------------------------------- # # comment the code above: `trainer.train()`, and... # # uncomment the following lines to evaluate a trained agent # # --------------------------------------------------------- # from skrl.utils.huggingface import download_model_from_huggingface # # download the trained agent's checkpoint from Hugging Face Hub and load it # path = download_model_from_huggingface("skrl/IsaacGymEnvs-BallBalance-PPO", filename="agent.pickle") # agent.load(path) # # start evaluation # trainer.eval()
Toni-SM/skrl/docs/source/examples/isaacgym/jax_ant_ddpg.py
import isaacgym import flax.linen as nn import jax import jax.numpy as jnp # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ddpg import DDPG, DDPG_DEFAULT_CONFIG from skrl.envs.loaders.jax import load_isaacgym_env_preview4 from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, Model from skrl.resources.noises.jax import OrnsteinUhlenbeckNoise from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "jax" # or "numpy" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (deterministic models) using mixins class DeterministicActor(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) @nn.compact def __call__(self, inputs, role): x = nn.relu(nn.Dense(512)(inputs["states"])) x = nn.relu(nn.Dense(256)(x)) x = nn.Dense(self.num_actions)(x) return nn.tanh(x), {} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = jnp.concatenate([inputs["states"], inputs["taken_actions"]], axis=-1) x = nn.relu(nn.Dense(512)(x)) x = nn.relu(nn.Dense(256)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the Isaac Gym environment env = load_isaacgym_env_preview4(task_name="Ant", num_envs=64) env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=15625, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # DDPG requires 4 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#models models = {} models["policy"] = DeterministicActor(env.observation_space, env.action_space, device) models["target_policy"] = DeterministicActor(env.observation_space, env.action_space, device) models["critic"] = Critic(env.observation_space, env.action_space, device) models["target_critic"] = Critic(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#configuration-and-hyperparameters cfg = DDPG_DEFAULT_CONFIG.copy() cfg["exploration"]["noise"] = OrnsteinUhlenbeckNoise(theta=0.15, sigma=0.1, base_scale=0.5, device=device) cfg["gradient_steps"] = 1 cfg["batch_size"] = 4096 cfg["discount_factor"] = 0.99 cfg["polyak"] = 0.005 cfg["actor_learning_rate"] = 5e-4 cfg["critic_learning_rate"] = 5e-4 cfg["random_timesteps"] = 80 cfg["learning_starts"] = 80 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 800 cfg["experiment"]["checkpoint_interval"] = 8000 cfg["experiment"]["directory"] = "runs/jax/Ant" agent = DDPG(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 160000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/isaacgym/jax_allegro_hand_ppo.py
import isaacgym import isaacgymenvs import flax.linen as nn import jax import jax.numpy as jnp # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.resources.schedulers.jax import KLAdaptiveRL from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "jax" # or "numpy" # seed for reproducibility seed = set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(512)(inputs["states"])) x = nn.elu(nn.Dense(256)(x)) x = nn.elu(nn.Dense(128)(x)) x = nn.Dense(self.num_actions)(x) log_std = self.param("log_std", lambda _: jnp.zeros(self.num_actions)) return x, log_std, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(512)(inputs["states"])) x = nn.elu(nn.Dense(256)(x)) x = nn.elu(nn.Dense(128)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the Isaac Gym environment using the easy-to-use API from NVIDIA env = isaacgymenvs.make(seed=seed, task="AllegroHand", num_envs=16384, sim_device="cuda:0", rl_device="cuda:0", graphics_device_id=0, headless=True) env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=8, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) models["value"] = Value(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 8 # memory_size cfg["learning_epochs"] = 5 cfg["mini_batches"] = 4 # 8 * 16384 / 32768 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 5e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.016} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 2.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.01 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 200 cfg["experiment"]["checkpoint_interval"] = 2000 cfg["experiment"]["directory"] = "runs/jax/AllegroHand" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 40000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/isaacgym/torch_anymal_terrain_ppo.py
import isaacgym import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_isaacgym_env_preview4 from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.resources.schedulers.torch import KLAdaptiveRL from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.net = nn.Sequential(nn.Linear(self.num_observations, 512), nn.ELU(), nn.Linear(512, 256), nn.ELU(), nn.Linear(256, 128), nn.ELU(), nn.Linear(128, self.num_actions)) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def compute(self, inputs, role): return self.net(inputs["states"]), self.log_std_parameter, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 512), nn.ELU(), nn.Linear(512, 256), nn.ELU(), nn.Linear(256, 128), nn.ELU(), nn.Linear(128, 1)) def compute(self, inputs, role): return self.net(inputs["states"]), {} # load and wrap the Isaac Gym environment env = load_isaacgym_env_preview4(task_name="AnymalTerrain") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=24, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) models["value"] = Value(env.observation_space, env.action_space, device) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 24 # memory_size cfg["learning_epochs"] = 5 cfg["mini_batches"] = 6 # 24 * 4096 / 16384 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 3e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.001 cfg["value_loss_scale"] = 1.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = None cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 180 cfg["experiment"]["checkpoint_interval"] = 1800 cfg["experiment"]["directory"] = "runs/torch/AnymalTerrain" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 36000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train() # # --------------------------------------------------------- # # comment the code above: `trainer.train()`, and... # # uncomment the following lines to evaluate a trained agent # # --------------------------------------------------------- # from skrl.utils.huggingface import download_model_from_huggingface # # download the trained agent's checkpoint from Hugging Face Hub and load it # path = download_model_from_huggingface("skrl/IsaacGymEnvs-AnymalTerrain-PPO", filename="agent.pt") # agent.load(path) # # start evaluation # trainer.eval()
Toni-SM/skrl/docs/source/examples/isaacgym/jax_franka_cube_stack_ppo.py
import isaacgym import flax.linen as nn import jax import jax.numpy as jnp # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.jax import load_isaacgym_env_preview4 from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.resources.schedulers.jax import KLAdaptiveRL from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "jax" # or "numpy" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(256)(inputs["states"])) x = nn.elu(nn.Dense(128)(x)) x = nn.elu(nn.Dense(64)(x)) x = nn.Dense(self.num_actions)(x) log_std = self.param("log_std", lambda _: jnp.zeros(self.num_actions)) return x, log_std, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(256)(inputs["states"])) x = nn.elu(nn.Dense(128)(x)) x = nn.elu(nn.Dense(64)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the Isaac Gym environment env = load_isaacgym_env_preview4(task_name="FrankaCubeStack") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=32, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) models["value"] = Value(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 32 # memory_size cfg["learning_epochs"] = 5 cfg["mini_batches"] = 16 # 32 * 8192 / 16384 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 5e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 2.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = None cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 1600 cfg["experiment"]["checkpoint_interval"] = 16000 cfg["experiment"]["directory"] = "runs/jax/FrankaCubeStack" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 320000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/isaacgym/torch_trifinger_ppo.py
import isaacgym import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_isaacgym_env_preview4 from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.resources.schedulers.torch import KLAdaptiveRL from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define shared model (stochastic and deterministic models) using mixins class Shared(GaussianMixin, DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 256), nn.ELU(), nn.Linear(256, 256), nn.ELU(), nn.Linear(256, 128), nn.ELU(), nn.Linear(128, 128), nn.ELU()) self.mean_layer = nn.Linear(128, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) self.value_layer = nn.Linear(128, 1) def act(self, inputs, role): if role == "policy": return GaussianMixin.act(self, inputs, role) elif role == "value": return DeterministicMixin.act(self, inputs, role) def compute(self, inputs, role): if role == "policy": return self.mean_layer(self.net(inputs["states"])), self.log_std_parameter, {} elif role == "value": return self.value_layer(self.net(inputs["states"])), {} # load and wrap the Isaac Gym environment env = load_isaacgym_env_preview4(task_name="Trifinger") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=8, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Shared(env.observation_space, env.action_space, device) models["value"] = models["policy"] # same instance: shared model # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 8 # memory_size cfg["learning_epochs"] = 4 cfg["mini_batches"] = 8 # 8 * 16384 / 16384 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 3e-4 cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 2.0 cfg["kl_threshold"] = 0.016 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.01 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 800 cfg["experiment"]["checkpoint_interval"] = 8000 cfg["experiment"]["directory"] = "runs/torch/Trifinger" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 160000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/isaacgym/jax_humanoid_ppo.py
import isaacgym import flax.linen as nn import jax import jax.numpy as jnp # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.jax import load_isaacgym_env_preview4 from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.resources.schedulers.jax import KLAdaptiveRL from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "jax" # or "numpy" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(400)(inputs["states"])) x = nn.elu(nn.Dense(200)(x)) x = nn.elu(nn.Dense(100)(x)) x = nn.Dense(self.num_actions)(x) log_std = self.param("log_std", lambda _: jnp.zeros(self.num_actions)) return x, log_std, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(400)(inputs["states"])) x = nn.elu(nn.Dense(200)(x)) x = nn.elu(nn.Dense(100)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the Isaac Gym environment env = load_isaacgym_env_preview4(task_name="Humanoid") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=32, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) models["value"] = Value(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 32 # memory_size cfg["learning_epochs"] = 5 cfg["mini_batches"] = 4 # 32 * 4096 / 32768 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 5e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 2.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.01 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 160 cfg["experiment"]["checkpoint_interval"] = 1600 cfg["experiment"]["directory"] = "runs/jax/Humanoid" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 32000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train() # # --------------------------------------------------------- # # comment the code above: `trainer.train()`, and... # # uncomment the following lines to evaluate a trained agent # # --------------------------------------------------------- # from skrl.utils.huggingface import download_model_from_huggingface # # download the trained agent's checkpoint from Hugging Face Hub and load it # path = download_model_from_huggingface("skrl/IsaacGymEnvs-Humanoid-PPO", filename="agent.pickle") # agent.load(path) # # start evaluation # trainer.eval()
Toni-SM/skrl/docs/source/examples/isaacgym/torch_shadow_hand_ppo.py
import isaacgym import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_isaacgym_env_preview4 from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.resources.schedulers.torch import KLAdaptiveRL from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define shared model (stochastic and deterministic models) using mixins class Shared(GaussianMixin, DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 512), nn.ELU(), nn.Linear(512, 512), nn.ELU(), nn.Linear(512, 256), nn.ELU(), nn.Linear(256, 128), nn.ELU()) self.mean_layer = nn.Linear(128, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) self.value_layer = nn.Linear(128, 1) def act(self, inputs, role): if role == "policy": return GaussianMixin.act(self, inputs, role) elif role == "value": return DeterministicMixin.act(self, inputs, role) def compute(self, inputs, role): if role == "policy": return self.mean_layer(self.net(inputs["states"])), self.log_std_parameter, {} elif role == "value": return self.value_layer(self.net(inputs["states"])), {} # load and wrap the Isaac Gym environment env = load_isaacgym_env_preview4(task_name="ShadowHand") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=8, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Shared(env.observation_space, env.action_space, device) models["value"] = models["policy"] # same instance: shared model # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 8 # memory_size cfg["learning_epochs"] = 5 cfg["mini_batches"] = 4 # 8 * 16384 / 32768 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 5e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.016} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 2.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.01 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 200 cfg["experiment"]["checkpoint_interval"] = 2000 cfg["experiment"]["directory"] = "runs/torch/ShadowHand" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 40000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/isaacgym/torch_franka_cabinet_ppo.py
import isaacgym import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_isaacgym_env_preview4 from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.resources.schedulers.torch import KLAdaptiveRL from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define shared model (stochastic and deterministic models) using mixins class Shared(GaussianMixin, DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 256), nn.ELU(), nn.Linear(256, 128), nn.ELU(), nn.Linear(128, 64), nn.ELU()) self.mean_layer = nn.Linear(64, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) self.value_layer = nn.Linear(64, 1) def act(self, inputs, role): if role == "policy": return GaussianMixin.act(self, inputs, role) elif role == "value": return DeterministicMixin.act(self, inputs, role) def compute(self, inputs, role): if role == "policy": return self.mean_layer(self.net(inputs["states"])), self.log_std_parameter, {} elif role == "value": return self.value_layer(self.net(inputs["states"])), {} # load and wrap the Isaac Gym environment env = load_isaacgym_env_preview4(task_name="FrankaCabinet") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=16, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Shared(env.observation_space, env.action_space, device) models["value"] = models["policy"] # same instance: shared model # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 16 # memory_size cfg["learning_epochs"] = 8 cfg["mini_batches"] = 8 # 16 * 4096 / 8192 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 5e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 2.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.01 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 120 cfg["experiment"]["checkpoint_interval"] = 1200 cfg["experiment"]["directory"] = "runs/torch/FrankaCabinet" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 24000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train() # # --------------------------------------------------------- # # comment the code above: `trainer.train()`, and... # # uncomment the following lines to evaluate a trained agent # # --------------------------------------------------------- # from skrl.utils.huggingface import download_model_from_huggingface # # download the trained agent's checkpoint from Hugging Face Hub and load it # path = download_model_from_huggingface("skrl/IsaacGymEnvs-FrankaCabinet-PPO", filename="agent.pt") # agent.load(path) # # start evaluation # trainer.eval()
Toni-SM/skrl/docs/source/examples/isaacgym/jax_quadcopter_ppo.py
import isaacgym import flax.linen as nn import jax import jax.numpy as jnp # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.jax import load_isaacgym_env_preview4 from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.resources.schedulers.jax import KLAdaptiveRL from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "jax" # or "numpy" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(256)(inputs["states"])) x = nn.elu(nn.Dense(256)(x)) x = nn.elu(nn.Dense(128)(x)) x = nn.Dense(self.num_actions)(x) log_std = self.param("log_std", lambda _: jnp.zeros(self.num_actions)) return x, log_std, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(256)(inputs["states"])) x = nn.elu(nn.Dense(256)(x)) x = nn.elu(nn.Dense(128)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the Isaac Gym environment env = load_isaacgym_env_preview4(task_name="Quadcopter") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=8, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) models["value"] = Value(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 8 # memory_size cfg["learning_epochs"] = 8 cfg["mini_batches"] = 4 # 8 * 8192 / 16384 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 1e-3 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.016} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 1.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.1 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 20 cfg["experiment"]["checkpoint_interval"] = 200 cfg["experiment"]["directory"] = "runs/jax/Quadcopter" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 4000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train() # # --------------------------------------------------------- # # comment the code above: `trainer.train()`, and... # # uncomment the following lines to evaluate a trained agent # # --------------------------------------------------------- # from skrl.utils.huggingface import download_model_from_huggingface # # download the trained agent's checkpoint from Hugging Face Hub and load it # path = download_model_from_huggingface("skrl/IsaacGymEnvs-Quadcopter-PPO", filename="agent.pickle") # agent.load(path) # # start evaluation # trainer.eval()
Toni-SM/skrl/docs/source/examples/isaacgym/jax_anymal_ppo.py
import isaacgym import flax.linen as nn import jax import jax.numpy as jnp # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.jax import load_isaacgym_env_preview4 from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.resources.schedulers.jax import KLAdaptiveRL from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "jax" # or "numpy" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(256)(inputs["states"])) x = nn.elu(nn.Dense(128)(x)) x = nn.elu(nn.Dense(64)(x)) x = nn.Dense(self.num_actions)(x) log_std = self.param("log_std", lambda _: jnp.zeros(self.num_actions)) return x, log_std, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(256)(inputs["states"])) x = nn.elu(nn.Dense(128)(x)) x = nn.elu(nn.Dense(64)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the Isaac Gym environment env = load_isaacgym_env_preview4(task_name="Anymal") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=24, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) models["value"] = Value(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 24 # memory_size cfg["learning_epochs"] = 5 cfg["mini_batches"] = 3 # 24 * 4096 / 32768 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 3e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 1.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = None cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 120 cfg["experiment"]["checkpoint_interval"] = 1200 cfg["experiment"]["directory"] = "runs/jax/Anymal" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 24000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train() # # --------------------------------------------------------- # # comment the code above: `trainer.train()`, and... # # uncomment the following lines to evaluate a trained agent # # --------------------------------------------------------- # from skrl.utils.huggingface import download_model_from_huggingface # # download the trained agent's checkpoint from Hugging Face Hub and load it # path = download_model_from_huggingface("skrl/IsaacGymEnvs-Anymal-PPO", filename="agent.pickle") # agent.load(path) # # start evaluation # trainer.eval()
Toni-SM/skrl/docs/source/examples/isaacgym/torch_ball_balance_ppo.py
import isaacgym import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_isaacgym_env_preview4 from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.resources.schedulers.torch import KLAdaptiveRL from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define shared model (stochastic and deterministic models) using mixins class Shared(GaussianMixin, DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 128), nn.ELU(), nn.Linear(128, 64), nn.ELU(), nn.Linear(64, 32), nn.ELU()) self.mean_layer = nn.Linear(32, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) self.value_layer = nn.Linear(32, 1) def act(self, inputs, role): if role == "policy": return GaussianMixin.act(self, inputs, role) elif role == "value": return DeterministicMixin.act(self, inputs, role) def compute(self, inputs, role): if role == "policy": return self.mean_layer(self.net(inputs["states"])), self.log_std_parameter, {} elif role == "value": return self.value_layer(self.net(inputs["states"])), {} # load and wrap the Isaac Gym environment env = load_isaacgym_env_preview4(task_name="BallBalance") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=16, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Shared(env.observation_space, env.action_space, device) models["value"] = models["policy"] # same instance: shared model # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 16 # memory_size cfg["learning_epochs"] = 8 cfg["mini_batches"] = 8 # 16 * 4096 / 8192 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 3e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 2.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.1 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 20 cfg["experiment"]["checkpoint_interval"] = 200 cfg["experiment"]["directory"] = "runs/torch/BallBalance" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 4000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train() # # --------------------------------------------------------- # # comment the code above: `trainer.train()`, and... # # uncomment the following lines to evaluate a trained agent # # --------------------------------------------------------- # from skrl.utils.huggingface import download_model_from_huggingface # # download the trained agent's checkpoint from Hugging Face Hub and load it # path = download_model_from_huggingface("skrl/IsaacGymEnvs-BallBalance-PPO", filename="agent.pt") # agent.load(path) # # start evaluation # trainer.eval()
Toni-SM/skrl/docs/source/examples/isaacgym/jax_franka_cabinet_ppo.py
import isaacgym import flax.linen as nn import jax import jax.numpy as jnp # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.jax import load_isaacgym_env_preview4 from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.resources.schedulers.jax import KLAdaptiveRL from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "jax" # or "numpy" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(256)(inputs["states"])) x = nn.elu(nn.Dense(128)(x)) x = nn.elu(nn.Dense(64)(x)) x = nn.Dense(self.num_actions)(x) log_std = self.param("log_std", lambda _: jnp.zeros(self.num_actions)) return x, log_std, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(256)(inputs["states"])) x = nn.elu(nn.Dense(128)(x)) x = nn.elu(nn.Dense(64)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the Isaac Gym environment env = load_isaacgym_env_preview4(task_name="FrankaCabinet") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=16, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) models["value"] = Value(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 16 # memory_size cfg["learning_epochs"] = 8 cfg["mini_batches"] = 8 # 16 * 4096 / 8192 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 5e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 2.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.01 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 120 cfg["experiment"]["checkpoint_interval"] = 1200 cfg["experiment"]["directory"] = "runs/jax/FrankaCabinet" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 24000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train() # # --------------------------------------------------------- # # comment the code above: `trainer.train()`, and... # # uncomment the following lines to evaluate a trained agent # # --------------------------------------------------------- # from skrl.utils.huggingface import download_model_from_huggingface # # download the trained agent's checkpoint from Hugging Face Hub and load it # path = download_model_from_huggingface("skrl/IsaacGymEnvs-FrankaCabinet-PPO", filename="agent.pickle") # agent.load(path) # # start evaluation # trainer.eval()
Toni-SM/skrl/docs/source/examples/isaacgym/torch_ant_ddpg.py
import isaacgym import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ddpg import DDPG, DDPG_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_isaacgym_env_preview4 from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, Model from skrl.resources.noises.torch import OrnsteinUhlenbeckNoise from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (deterministic models) using mixins class DeterministicActor(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 512), nn.ReLU(), nn.Linear(512, 256), nn.ReLU(), nn.Linear(256, self.num_actions), nn.Tanh()) def compute(self, inputs, role): return self.net(inputs["states"]), {} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations + self.num_actions, 512), nn.ReLU(), nn.Linear(512, 256), nn.ReLU(), nn.Linear(256, 1)) def compute(self, inputs, role): return self.net(torch.cat([inputs["states"], inputs["taken_actions"]], dim=1)), {} # load and wrap the Isaac Gym environment env = load_isaacgym_env_preview4(task_name="Ant", num_envs=64) env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=15625, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # DDPG requires 4 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#models models = {} models["policy"] = DeterministicActor(env.observation_space, env.action_space, device) models["target_policy"] = DeterministicActor(env.observation_space, env.action_space, device) models["critic"] = Critic(env.observation_space, env.action_space, device) models["target_critic"] = Critic(env.observation_space, env.action_space, device) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#configuration-and-hyperparameters cfg = DDPG_DEFAULT_CONFIG.copy() cfg["exploration"]["noise"] = OrnsteinUhlenbeckNoise(theta=0.15, sigma=0.1, base_scale=0.5, device=device) cfg["gradient_steps"] = 1 cfg["batch_size"] = 4096 cfg["discount_factor"] = 0.99 cfg["polyak"] = 0.005 cfg["actor_learning_rate"] = 5e-4 cfg["critic_learning_rate"] = 5e-4 cfg["random_timesteps"] = 80 cfg["learning_starts"] = 80 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 800 cfg["experiment"]["checkpoint_interval"] = 8000 cfg["experiment"]["directory"] = "runs/torch/Ant" agent = DDPG(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 160000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/isaacgym/torch_allegro_kuka_ppo.py
import isaacgym import isaacgymenvs import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.resources.schedulers.torch import KLAdaptiveRL from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility seed = set_seed() # e.g. `set_seed(42)` for fixed seed # define shared model (stochastic and deterministic models) using mixins class Shared(GaussianMixin, DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 1024), nn.ELU(), nn.Linear(1024, 1024), nn.ELU(), nn.Linear(1024, 512), nn.ELU(), nn.Linear(512, 512), nn.ELU()) self.mean_layer = nn.Linear(512, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) self.value_layer = nn.Linear(512, 1) def act(self, inputs, role): if role == "policy": return GaussianMixin.act(self, inputs, role) elif role == "value": return DeterministicMixin.act(self, inputs, role) def compute(self, inputs, role): if role == "policy": return self.mean_layer(self.net(inputs["states"])), self.log_std_parameter, {} elif role == "value": return self.value_layer(self.net(inputs["states"])), {} # load and wrap the Isaac Gym environment using the easy-to-use API from NVIDIA env = isaacgymenvs.make(seed=seed, task="AllegroKuka", num_envs=8192, sim_device="cuda:0", rl_device="cuda:0", graphics_device_id=0, headless=True) env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=16, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Shared(env.observation_space, env.action_space, device) models["value"] = models["policy"] # same instance: shared model # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 16 # memory_size cfg["learning_epochs"] = 4 cfg["mini_batches"] = 4 # 16 * 8192 / 32768 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 1e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.016} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.1 cfg["value_clip"] = 0.1 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 2.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.01 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 200 cfg["experiment"]["checkpoint_interval"] = 2000 cfg["experiment"]["directory"] = "runs/torch/AllegroKuka" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 1600000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/isaacgym/jax_factory_task_nut_bolt_screw_ppo.py
import isaacgym import flax.linen as nn import jax import jax.numpy as jnp # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.jax import load_isaacgym_env_preview4 from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "jax" # or "numpy" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(256)(inputs["states"])) x = nn.elu(nn.Dense(128)(x)) x = nn.elu(nn.Dense(64)(x)) x = nn.Dense(self.num_actions)(x) log_std = self.param("log_std", lambda _: jnp.zeros(self.num_actions)) return x, log_std, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(256)(inputs["states"])) x = nn.elu(nn.Dense(128)(x)) x = nn.elu(nn.Dense(64)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the Isaac Gym environment env = load_isaacgym_env_preview4(task_name="FactoryTaskNutBoltScrew") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=128, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) models["value"] = Value(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 128 # memory_size cfg["learning_epochs"] = 8 cfg["mini_batches"] = 32 # 128 * 128 / 512 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 1e-4 cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 1.0 cfg["kl_threshold"] = 0.016 cfg["rewards_shaper"] = None cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 614 cfg["experiment"]["checkpoint_interval"] = 6144 cfg["experiment"]["directory"] = "runs/jax/FactoryTaskNutBoltScrew" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 122880, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train() # # --------------------------------------------------------- # # comment the code above: `trainer.train()`, and... # # uncomment the following lines to evaluate a trained agent # # --------------------------------------------------------- # from skrl.utils.huggingface import download_model_from_huggingface # # download the trained agent's checkpoint from Hugging Face Hub and load it # path = download_model_from_huggingface("skrl/IsaacGymEnvs-FactoryTaskNutBoltScrew-PPO", filename="agent.pickle") # agent.load(path) # # start evaluation # trainer.eval()
Toni-SM/skrl/docs/source/examples/isaacgym/jax_ant_ppo.py
import isaacgym import flax.linen as nn import jax import jax.numpy as jnp # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.jax import load_isaacgym_env_preview4 from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.resources.schedulers.jax import KLAdaptiveRL from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "jax" # or "numpy" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(256)(inputs["states"])) x = nn.elu(nn.Dense(128)(x)) x = nn.elu(nn.Dense(64)(x)) x = nn.Dense(self.num_actions)(x) log_std = self.param("log_std", lambda _: jnp.zeros(self.num_actions)) return x, log_std, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(256)(inputs["states"])) x = nn.elu(nn.Dense(128)(x)) x = nn.elu(nn.Dense(64)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the Isaac Gym environment env = load_isaacgym_env_preview4(task_name="Ant") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=16, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) models["value"] = Value(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 16 # memory_size cfg["learning_epochs"] = 4 cfg["mini_batches"] = 2 # 16 * 4096 / 32768 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 3e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 1.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.01 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 40 cfg["experiment"]["checkpoint_interval"] = 400 cfg["experiment"]["directory"] = "runs/jax/Ant" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 8000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train() # # --------------------------------------------------------- # # comment the code above: `trainer.train()`, and... # # uncomment the following lines to evaluate a trained agent # # --------------------------------------------------------- # from skrl.utils.huggingface import download_model_from_huggingface # # download the trained agent's checkpoint from Hugging Face Hub and load it # path = download_model_from_huggingface("skrl/IsaacGymEnvs-Ant-PPO", filename="agent.pickle") # agent.load(path) # # start evaluation # trainer.eval()
Toni-SM/skrl/docs/source/examples/isaacgym/torch_anymal_ppo.py
import isaacgym import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_isaacgym_env_preview4 from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.resources.schedulers.torch import KLAdaptiveRL from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define shared model (stochastic and deterministic models) using mixins class Shared(GaussianMixin, DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 256), nn.ELU(), nn.Linear(256, 128), nn.ELU(), nn.Linear(128, 64), nn.ELU()) self.mean_layer = nn.Linear(64, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) self.value_layer = nn.Linear(64, 1) def act(self, inputs, role): if role == "policy": return GaussianMixin.act(self, inputs, role) elif role == "value": return DeterministicMixin.act(self, inputs, role) def compute(self, inputs, role): if role == "policy": return self.mean_layer(self.net(inputs["states"])), self.log_std_parameter, {} elif role == "value": return self.value_layer(self.net(inputs["states"])), {} # load and wrap the Isaac Gym environment env = load_isaacgym_env_preview4(task_name="Anymal") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=24, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Shared(env.observation_space, env.action_space, device) models["value"] = models["policy"] # same instance: shared model # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 24 # memory_size cfg["learning_epochs"] = 5 cfg["mini_batches"] = 3 # 24 * 4096 / 32768 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 3e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 1.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = None cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 120 cfg["experiment"]["checkpoint_interval"] = 1200 cfg["experiment"]["directory"] = "runs/torch/Anymal" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 24000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train() # # --------------------------------------------------------- # # comment the code above: `trainer.train()`, and... # # uncomment the following lines to evaluate a trained agent # # --------------------------------------------------------- # from skrl.utils.huggingface import download_model_from_huggingface # # download the trained agent's checkpoint from Hugging Face Hub and load it # path = download_model_from_huggingface("skrl/IsaacGymEnvs-Anymal-PPO", filename="agent.pt") # agent.load(path) # # start evaluation # trainer.eval()
Toni-SM/skrl/docs/source/examples/isaacgym/torch_ant_ddpg_td3_sac_sequential_unshared_memory.py
import isaacgym import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ddpg import DDPG, DDPG_DEFAULT_CONFIG from skrl.agents.torch.sac import SAC, SAC_DEFAULT_CONFIG from skrl.agents.torch.td3 import TD3, TD3_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_isaacgym_env_preview4 from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.noises.torch import GaussianNoise, OrnsteinUhlenbeckNoise from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class StochasticActor(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-5, max_log_std=2): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std) self.net = nn.Sequential(nn.Linear(self.num_observations, 512), nn.ReLU(), nn.Linear(512, 256), nn.ReLU(), nn.Linear(256, self.num_actions), nn.Tanh()) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def compute(self, inputs, role): return self.net(inputs["states"]), self.log_std_parameter, {} class DeterministicActor(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 512), nn.ReLU(), nn.Linear(512, 256), nn.ReLU(), nn.Linear(256, self.num_actions), nn.Tanh()) def compute(self, inputs, role): return self.net(inputs["states"]), {} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations + self.num_actions, 512), nn.ReLU(), nn.Linear(512, 256), nn.ReLU(), nn.Linear(256, 1)) def compute(self, inputs, role): return self.net(torch.cat([inputs["states"], inputs["taken_actions"]], dim=1)), {} # load and wrap the Isaac Gym environment env = load_isaacgym_env_preview4(task_name="Ant", num_envs=192) env = wrap_env(env) device = env.device # instantiate memories as experience replay (unique for each agents). # scopes (192 envs): DDPG 64, TD3 64 and SAC 64 memory_ddpg = RandomMemory(memory_size=15625, num_envs=64, device=device) memory_td3 = RandomMemory(memory_size=15625, num_envs=64, device=device) memory_sac = RandomMemory(memory_size=15625, num_envs=64, device=device) # instantiate the agents' models (function approximators). # DDPG requires 4 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#models models_ddpg = {} models_ddpg["policy"] = DeterministicActor(env.observation_space, env.action_space, device) models_ddpg["target_policy"] = DeterministicActor(env.observation_space, env.action_space, device) models_ddpg["critic"] = Critic(env.observation_space, env.action_space, device) models_ddpg["target_critic"] = Critic(env.observation_space, env.action_space, device) # TD3 requires 6 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/td3.html#models models_td3 = {} models_td3["policy"] = DeterministicActor(env.observation_space, env.action_space, device) models_td3["target_policy"] = DeterministicActor(env.observation_space, env.action_space, device) models_td3["critic_1"] = Critic(env.observation_space, env.action_space, device) models_td3["critic_2"] = Critic(env.observation_space, env.action_space, device) models_td3["target_critic_1"] = Critic(env.observation_space, env.action_space, device) models_td3["target_critic_2"] = Critic(env.observation_space, env.action_space, device) # SAC requires 5 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/sac.html#models models_sac = {} models_sac["policy"] = StochasticActor(env.observation_space, env.action_space, device, clip_actions=True) models_sac["critic_1"] = Critic(env.observation_space, env.action_space, device) models_sac["critic_2"] = Critic(env.observation_space, env.action_space, device) models_sac["target_critic_1"] = Critic(env.observation_space, env.action_space, device) models_sac["target_critic_2"] = Critic(env.observation_space, env.action_space, device) # configure and instantiate the agents (visit their documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#configuration-and-hyperparameters cfg_ddpg = DDPG_DEFAULT_CONFIG.copy() cfg_ddpg["exploration"]["noise"] = OrnsteinUhlenbeckNoise(theta=0.15, sigma=0.1, base_scale=0.5, device=device) cfg_ddpg["gradient_steps"] = 1 cfg_ddpg["batch_size"] = 4096 cfg_ddpg["discount_factor"] = 0.99 cfg_ddpg["polyak"] = 0.005 cfg_ddpg["actor_learning_rate"] = 5e-4 cfg_ddpg["critic_learning_rate"] = 5e-4 cfg_ddpg["random_timesteps"] = 80 cfg_ddpg["learning_starts"] = 80 cfg_ddpg["state_preprocessor"] = RunningStandardScaler cfg_ddpg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg_ddpg["experiment"]["write_interval"] = 800 cfg_ddpg["experiment"]["checkpoint_interval"] = 8000 cfg_ddpg["experiment"]["directory"] = "runs/torch/Ant" # https://skrl.readthedocs.io/en/latest/api/agents/td3.html#configuration-and-hyperparameters cfg_td3 = TD3_DEFAULT_CONFIG.copy() cfg_td3["exploration"]["noise"] = GaussianNoise(0, 0.1, device=device) cfg_td3["smooth_regularization_noise"] = GaussianNoise(0, 0.2, device=device) cfg_td3["smooth_regularization_clip"] = 0.5 cfg_td3["gradient_steps"] = 1 cfg_td3["batch_size"] = 4096 cfg_td3["discount_factor"] = 0.99 cfg_td3["polyak"] = 0.005 cfg_td3["actor_learning_rate"] = 5e-4 cfg_td3["critic_learning_rate"] = 5e-4 cfg_td3["random_timesteps"] = 80 cfg_td3["learning_starts"] = 80 cfg_td3["state_preprocessor"] = RunningStandardScaler cfg_td3["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg_td3["experiment"]["write_interval"] = 800 cfg_td3["experiment"]["checkpoint_interval"] = 8000 cfg_td3["experiment"]["directory"] = "runs/torch/Ant" # https://skrl.readthedocs.io/en/latest/api/agents/sac.html#configuration-and-hyperparameters cfg_sac = SAC_DEFAULT_CONFIG.copy() cfg_sac["gradient_steps"] = 1 cfg_sac["batch_size"] = 4096 cfg_sac["discount_factor"] = 0.99 cfg_sac["polyak"] = 0.005 cfg_sac["actor_learning_rate"] = 5e-4 cfg_sac["critic_learning_rate"] = 5e-4 cfg_sac["random_timesteps"] = 80 cfg_sac["learning_starts"] = 80 cfg_sac["grad_norm_clip"] = 0 cfg_sac["learn_entropy"] = True cfg_sac["entropy_learning_rate"] = 5e-3 cfg_sac["initial_entropy_value"] = 1.0 cfg_sac["state_preprocessor"] = RunningStandardScaler cfg_sac["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg_sac["experiment"]["write_interval"] = 800 cfg_sac["experiment"]["checkpoint_interval"] = 8000 cfg_sac["experiment"]["directory"] = "runs/torch/Ant" agent_ddpg = DDPG(models=models_ddpg, memory=memory_ddpg, cfg=cfg_ddpg, observation_space=env.observation_space, action_space=env.action_space, device=device) agent_td3 = TD3(models=models_td3, memory=memory_td3, cfg=cfg_td3, observation_space=env.observation_space, action_space=env.action_space, device=device) agent_sac = SAC(models=models_sac, memory=memory_sac, cfg=cfg_sac, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer and define the agent scopes cfg_trainer = {"timesteps": 160000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent_ddpg, agent_td3, agent_sac], agents_scope=[64, 64, 64]) # scopes (192 envs): DDPG 64, TD3 64 and SAC 64 # start training trainer.train()
Toni-SM/skrl/docs/source/examples/isaacgym/jax_ant_td3.py
import isaacgym import flax.linen as nn import jax import jax.numpy as jnp # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.td3 import TD3, TD3_DEFAULT_CONFIG from skrl.envs.loaders.jax import load_isaacgym_env_preview4 from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, Model from skrl.resources.noises.jax import GaussianNoise from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "jax" # or "numpy" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (deterministic models) using mixins class DeterministicActor(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) @nn.compact def __call__(self, inputs, role): x = nn.relu(nn.Dense(512)(inputs["states"])) x = nn.relu(nn.Dense(256)(x)) x = nn.Dense(self.num_actions)(x) return nn.tanh(x), {} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = jnp.concatenate([inputs["states"], inputs["taken_actions"]], axis=-1) x = nn.relu(nn.Dense(512)(x)) x = nn.relu(nn.Dense(256)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the Isaac Gym environment env = load_isaacgym_env_preview4(task_name="Ant", num_envs=64) env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=15625, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # TD3 requires 6 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/td3.html#models models = {} models["policy"] = DeterministicActor(env.observation_space, env.action_space, device) models["target_policy"] = DeterministicActor(env.observation_space, env.action_space, device) models["critic_1"] = Critic(env.observation_space, env.action_space, device) models["critic_2"] = Critic(env.observation_space, env.action_space, device) models["target_critic_1"] = Critic(env.observation_space, env.action_space, device) models["target_critic_2"] = Critic(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/td3.html#configuration-and-hyperparameters cfg = TD3_DEFAULT_CONFIG.copy() cfg["exploration"]["noise"] = GaussianNoise(0, 0.1, device=device) cfg["smooth_regularization_noise"] = GaussianNoise(0, 0.1, device=device) cfg["smooth_regularization_clip"] = 0.5 cfg["gradient_steps"] = 1 cfg["batch_size"] = 4096 cfg["discount_factor"] = 0.99 cfg["polyak"] = 0.005 cfg["actor_learning_rate"] = 5e-4 cfg["critic_learning_rate"] = 5e-4 cfg["random_timesteps"] = 80 cfg["learning_starts"] = 80 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 800 cfg["experiment"]["checkpoint_interval"] = 8000 cfg["experiment"]["directory"] = "runs/jax/Ant" agent = TD3(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 160000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/isaacgym/torch_humanoid_amp.py
import isaacgym import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.amp import AMP, AMP_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_isaacgym_env_preview4 from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins # - Policy: takes as input the environment's observation/state and returns an action # - Value: takes the state as input and provides a value to guide the policy # - Discriminator: differentiate between police-generated behaviors and behaviors from the motion dataset class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std) self.net = nn.Sequential(nn.Linear(self.num_observations, 1024), nn.ReLU(), nn.Linear(1024, 512), nn.ReLU(), nn.Linear(512, self.num_actions)) # set a fixed log standard deviation for the policy self.log_std_parameter = nn.Parameter(torch.full((self.num_actions,), fill_value=-2.9), requires_grad=False) def compute(self, inputs, role): return torch.tanh(self.net(inputs["states"])), self.log_std_parameter, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 1024), nn.ReLU(), nn.Linear(1024, 512), nn.ReLU(), nn.Linear(512, 1)) def compute(self, inputs, role): return self.net(inputs["states"]), {} class Discriminator(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 1024), nn.ReLU(), nn.Linear(1024, 512), nn.ReLU(), nn.Linear(512, 1)) def compute(self, inputs, role): return self.net(inputs["states"]), {} # load and wrap the Isaac Gym environment env = load_isaacgym_env_preview4(task_name="HumanoidAMP") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=16, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # AMP requires 3 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/amp.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) models["value"] = Value(env.observation_space, env.action_space, device) models["discriminator"] = Discriminator(env.amp_observation_space, env.action_space, device) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/amp.html#configuration-and-hyperparameters cfg = AMP_DEFAULT_CONFIG.copy() cfg["rollouts"] = 16 # memory_size cfg["learning_epochs"] = 6 cfg["mini_batches"] = 2 # 16 * 4096 / 32768 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 5e-5 cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = False cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 2.5 cfg["discriminator_loss_scale"] = 5.0 cfg["amp_batch_size"] = 512 cfg["task_reward_weight"] = 0.0 cfg["style_reward_weight"] = 1.0 cfg["discriminator_batch_size"] = 4096 cfg["discriminator_reward_scale"] = 2 cfg["discriminator_logit_regularization_scale"] = 0.05 cfg["discriminator_gradient_penalty_scale"] = 5 cfg["discriminator_weight_decay_scale"] = 0.0001 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} cfg["amp_state_preprocessor"] = RunningStandardScaler cfg["amp_state_preprocessor_kwargs"] = {"size": env.amp_observation_space, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 160 cfg["experiment"]["checkpoint_interval"] = 4000 cfg["experiment"]["directory"] = "runs/torch/HumanoidAMP" agent = AMP(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device, amp_observation_space=env.amp_observation_space, motion_dataset=RandomMemory(memory_size=200000, device=device), reply_buffer=RandomMemory(memory_size=1000000, device=device), collect_reference_motions=lambda num_samples: env.fetch_amp_obs_demo(num_samples), collect_observation=lambda: env.reset_done()[0]["obs"]) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 80000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/isaacgym/torch_cartpole_ppo.py
import isaacgym import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_isaacgym_env_preview4 from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.resources.schedulers.torch import KLAdaptiveRL from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(40)` for fixed seed # define shared model (stochastic and deterministic models) using mixins class Shared(GaussianMixin, DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 32), nn.ELU(), nn.Linear(32, 32), nn.ELU()) self.mean_layer = nn.Linear(32, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) self.value_layer = nn.Linear(32, 1) def act(self, inputs, role): if role == "policy": return GaussianMixin.act(self, inputs, role) elif role == "value": return DeterministicMixin.act(self, inputs, role) def compute(self, inputs, role): if role == "policy": return self.mean_layer(self.net(inputs["states"])), self.log_std_parameter, {} elif role == "value": return self.value_layer(self.net(inputs["states"])), {} # load and wrap the Isaac Gym environment env = load_isaacgym_env_preview4(task_name="Cartpole") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=16, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Shared(env.observation_space, env.action_space, device) models["value"] = models["policy"] # same instance: shared model # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 16 # memory_size cfg["learning_epochs"] = 8 cfg["mini_batches"] = 1 # 16 * 512 / 8192 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 3e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 2.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.1 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 16 cfg["experiment"]["checkpoint_interval"] = 80 cfg["experiment"]["directory"] = "runs/torch/Cartpole" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 1600, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train() # # --------------------------------------------------------- # # comment the code above: `trainer.train()`, and... # # uncomment the following lines to evaluate a trained agent # # --------------------------------------------------------- # from skrl.utils.huggingface import download_model_from_huggingface # # download the trained agent's checkpoint from Hugging Face Hub and load it # path = download_model_from_huggingface("skrl/IsaacGymEnvs-Cartpole-PPO", filename="agent.pt") # agent.load(path) # # start evaluation # trainer.eval()
Toni-SM/skrl/docs/source/examples/isaacgym/torch_quadcopter_ppo.py
import isaacgym import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_isaacgym_env_preview4 from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.resources.schedulers.torch import KLAdaptiveRL from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define shared model (stochastic and deterministic models) using mixins class Shared(GaussianMixin, DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 256), nn.ELU(), nn.Linear(256, 256), nn.ELU(), nn.Linear(256, 128), nn.ELU()) self.mean_layer = nn.Linear(128, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) self.value_layer = nn.Linear(128, 1) def act(self, inputs, role): if role == "policy": return GaussianMixin.act(self, inputs, role) elif role == "value": return DeterministicMixin.act(self, inputs, role) def compute(self, inputs, role): if role == "policy": return self.mean_layer(self.net(inputs["states"])), self.log_std_parameter, {} elif role == "value": return self.value_layer(self.net(inputs["states"])), {} # load and wrap the Isaac Gym environment env = load_isaacgym_env_preview4(task_name="Quadcopter") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=8, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Shared(env.observation_space, env.action_space, device) models["value"] = models["policy"] # same instance: shared model # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 8 # memory_size cfg["learning_epochs"] = 8 cfg["mini_batches"] = 4 # 8 * 8192 / 16384 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 1e-3 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.016} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 1.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.1 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 20 cfg["experiment"]["checkpoint_interval"] = 200 cfg["experiment"]["directory"] = "runs/torch/Quadcopter" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 4000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train() # # --------------------------------------------------------- # # comment the code above: `trainer.train()`, and... # # uncomment the following lines to evaluate a trained agent # # --------------------------------------------------------- # from skrl.utils.huggingface import download_model_from_huggingface # # download the trained agent's checkpoint from Hugging Face Hub and load it # path = download_model_from_huggingface("skrl/IsaacGymEnvs-Quadcopter-PPO", filename="agent.pt") # agent.load(path) # # start evaluation # trainer.eval()
Toni-SM/skrl/docs/source/examples/isaacgym/jax_factory_task_nut_bolt_pick_ppo.py
import isaacgym import flax.linen as nn import jax import jax.numpy as jnp # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.jax import load_isaacgym_env_preview4 from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "jax" # or "numpy" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(256)(inputs["states"])) x = nn.elu(nn.Dense(128)(x)) x = nn.elu(nn.Dense(64)(x)) x = nn.Dense(self.num_actions)(x) log_std = self.param("log_std", lambda _: jnp.zeros(self.num_actions)) return x, log_std, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(256)(inputs["states"])) x = nn.elu(nn.Dense(128)(x)) x = nn.elu(nn.Dense(64)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the Isaac Gym environment env = load_isaacgym_env_preview4(task_name="FactoryTaskNutBoltPick") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=120, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) models["value"] = Value(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 120 # memory_size cfg["learning_epochs"] = 8 cfg["mini_batches"] = 30 # 120 * 128 / 512 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 1e-4 cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 1.0 cfg["kl_threshold"] = 0.016 cfg["rewards_shaper"] = None cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 614 cfg["experiment"]["checkpoint_interval"] = 6144 cfg["experiment"]["directory"] = "runs/jax/FactoryTaskNutBoltPick" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 122880, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train() # # --------------------------------------------------------- # # comment the code above: `trainer.train()`, and... # # uncomment the following lines to evaluate a trained agent # # --------------------------------------------------------- # from skrl.utils.huggingface import download_model_from_huggingface # # download the trained agent's checkpoint from Hugging Face Hub and load it # path = download_model_from_huggingface("skrl/IsaacGymEnvs-FactoryTaskNutBoltPick-PPO", filename="agent.pickle") # agent.load(path) # # start evaluation # trainer.eval()
Toni-SM/skrl/docs/source/examples/isaacgym/torch_factory_task_nut_bolt_place_ppo.py
import isaacgym import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_isaacgym_env_preview4 from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.resources.schedulers.torch import KLAdaptiveRL from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define shared model (stochastic and deterministic models) using mixins class Shared(GaussianMixin, DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 256), nn.ELU(), nn.Linear(256, 128), nn.ELU(), nn.Linear(128, 64), nn.ELU()) self.mean_layer = nn.Linear(64, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) self.value_layer = nn.Linear(64, 1) def act(self, inputs, role): if role == "policy": return GaussianMixin.act(self, inputs, role) elif role == "value": return DeterministicMixin.act(self, inputs, role) def compute(self, inputs, role): if role == "policy": return self.mean_layer(self.net(inputs["states"])), self.log_std_parameter, {} elif role == "value": return self.value_layer(self.net(inputs["states"])), {} # load and wrap the Isaac Gym environment env = load_isaacgym_env_preview4(task_name="FactoryTaskNutBoltPlace") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=120, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Shared(env.observation_space, env.action_space, device) models["value"] = models["policy"] # same instance: shared model # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 120 # memory_size cfg["learning_epochs"] = 8 cfg["mini_batches"] = 30 # 120 * 128 / 512 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 1e-4 cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 1.0 cfg["kl_threshold"] = 0.016 cfg["rewards_shaper"] = None cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 614 cfg["experiment"]["checkpoint_interval"] = 6144 cfg["experiment"]["directory"] = "runs/torch/FactoryTaskNutBoltPlace" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 122880, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train() # # --------------------------------------------------------- # # comment the code above: `trainer.train()`, and... # # uncomment the following lines to evaluate a trained agent # # --------------------------------------------------------- # from skrl.utils.huggingface import download_model_from_huggingface # # download the trained agent's checkpoint from Hugging Face Hub and load it # path = download_model_from_huggingface("skrl/IsaacGymEnvs-FactoryTaskNutBoltPlace-PPO", filename="agent.pt") # agent.load(path) # # start evaluation # trainer.eval()
Toni-SM/skrl/docs/source/examples/isaacgym/torch_factory_task_nut_bolt_screw_ppo.py
import isaacgym import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_isaacgym_env_preview4 from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.resources.schedulers.torch import KLAdaptiveRL from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define shared model (stochastic and deterministic models) using mixins class Shared(GaussianMixin, DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 256), nn.ELU(), nn.Linear(256, 128), nn.ELU(), nn.Linear(128, 64), nn.ELU()) self.mean_layer = nn.Linear(64, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) self.value_layer = nn.Linear(64, 1) def act(self, inputs, role): if role == "policy": return GaussianMixin.act(self, inputs, role) elif role == "value": return DeterministicMixin.act(self, inputs, role) def compute(self, inputs, role): if role == "policy": return self.mean_layer(self.net(inputs["states"])), self.log_std_parameter, {} elif role == "value": return self.value_layer(self.net(inputs["states"])), {} # load and wrap the Isaac Gym environment env = load_isaacgym_env_preview4(task_name="FactoryTaskNutBoltScrew") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=128, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Shared(env.observation_space, env.action_space, device) models["value"] = models["policy"] # same instance: shared model # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 128 # memory_size cfg["learning_epochs"] = 8 cfg["mini_batches"] = 32 # 128 * 128 / 512 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 1e-4 cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 1.0 cfg["kl_threshold"] = 0.016 cfg["rewards_shaper"] = None cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 614 cfg["experiment"]["checkpoint_interval"] = 6144 cfg["experiment"]["directory"] = "runs/torch/FactoryTaskNutBoltScrew" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 122880, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train() # # --------------------------------------------------------- # # comment the code above: `trainer.train()`, and... # # uncomment the following lines to evaluate a trained agent # # --------------------------------------------------------- # from skrl.utils.huggingface import download_model_from_huggingface # # download the trained agent's checkpoint from Hugging Face Hub and load it # path = download_model_from_huggingface("skrl/IsaacGymEnvs-FactoryTaskNutBoltScrew-PPO", filename="agent.pt") # agent.load(path) # # start evaluation # trainer.eval()
Toni-SM/skrl/docs/source/examples/deepmind/dm_suite_cartpole_swingup_ddpg.py
from dm_control import suite import torch import torch.nn as nn import torch.nn.functional as F # Import the skrl components to build the RL system from skrl.models.torch import Model, DeterministicMixin from skrl.memories.torch import RandomMemory from skrl.agents.torch.ddpg import DDPG, DDPG_DEFAULT_CONFIG from skrl.resources.noises.torch import OrnsteinUhlenbeckNoise from skrl.trainers.torch import SequentialTrainer from skrl.envs.torch import wrap_env # Define the models (deterministic models) for the DDPG agent using mixins # and programming with two approaches (torch functional and torch.nn.Sequential class). # - Actor (policy): takes as input the environment's observation/state and returns an action # - Critic: takes the state and action as input and provides a value to guide the policy class DeterministicActor(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.linear_layer_1 = nn.Linear(self.num_observations, 400) self.linear_layer_2 = nn.Linear(400, 300) self.action_layer = nn.Linear(300, self.num_actions) def compute(self, inputs, role): x = F.relu(self.linear_layer_1(inputs["states"])) x = F.relu(self.linear_layer_2(x)) return torch.tanh(self.action_layer(x)), {} class DeterministicCritic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations + self.num_actions, 400), nn.ReLU(), nn.Linear(400, 300), nn.ReLU(), nn.Linear(300, 1)) def compute(self, inputs, role): return self.net(torch.cat([inputs["states"], inputs["taken_actions"]], dim=1)), {} # Load and wrap the DeepMind environment env = suite.load(domain_name="cartpole", task_name="swingup") env = wrap_env(env) device = env.device # Instantiate a RandomMemory (without replacement) as experience replay memory memory = RandomMemory(memory_size=25000, num_envs=env.num_envs, device=device, replacement=False) # Instantiate the agent's models (function approximators). # DDPG requires 4 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/modules/skrl.agents.ddpg.html#spaces-and-models models_ddpg = {} models_ddpg["policy"] = DeterministicActor(env.observation_space, env.action_space, device, clip_actions=True) models_ddpg["target_policy"] = DeterministicActor(env.observation_space, env.action_space, device, clip_actions=True) models_ddpg["critic"] = DeterministicCritic(env.observation_space, env.action_space, device) models_ddpg["target_critic"] = DeterministicCritic(env.observation_space, env.action_space, device) # Initialize the models' parameters (weights and biases) using a Gaussian distribution for model in models_ddpg.values(): model.init_parameters(method_name="normal_", mean=0.0, std=0.1) # Configure and instantiate the agent. # Only modify some of the default configuration, visit its documentation to see all the options # https://skrl.readthedocs.io/en/latest/modules/skrl.agents.ddpg.html#configuration-and-hyperparameters cfg_ddpg = DDPG_DEFAULT_CONFIG.copy() cfg_ddpg["exploration"]["noise"] = OrnsteinUhlenbeckNoise(theta=0.15, sigma=0.1, base_scale=1.0, device=device) cfg_ddpg["batch_size"] = 100 cfg_ddpg["random_timesteps"] = 100 cfg_ddpg["learning_starts"] = 100 # logging to TensorBoard and write checkpoints each 1000 and 5000 timesteps respectively cfg_ddpg["experiment"]["write_interval"] = 1000 cfg_ddpg["experiment"]["checkpoint_interval"] = 5000 agent_ddpg = DDPG(models=models_ddpg, memory=memory, cfg=cfg_ddpg, observation_space=env.observation_space, action_space=env.action_space, device=device) # Configure and instantiate the RL trainer cfg_trainer = {"timesteps": 50000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent_ddpg) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/deepmind/dm_manipulation_stack_sac.py
from dm_control import manipulation import torch import torch.nn as nn # Import the skrl components to build the RL system from skrl.models.torch import Model, GaussianMixin, DeterministicMixin from skrl.memories.torch import RandomMemory from skrl.agents.torch.sac import SAC, SAC_DEFAULT_CONFIG from skrl.trainers.torch import SequentialTrainer from skrl.envs.torch import wrap_env # Define the models (stochastic and deterministic models) for the SAC agent using the mixins. # - StochasticActor (policy): takes as input the environment's observation/state and returns an action # - Critic: takes the state and action as input and provides a value to guide the policy class StochasticActor(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std) self.features_extractor = nn.Sequential(nn.Conv2d(3, 32, kernel_size=8, stride=3), nn.ReLU(), nn.Conv2d(32, 64, kernel_size=4, stride=2), nn.ReLU(), nn.Conv2d(64, 64, kernel_size=2, stride=1), nn.ReLU(), nn.Flatten(), nn.Linear(7744, 512), nn.ReLU(), nn.Linear(512, 8), nn.Tanh()) self.net = nn.Sequential(nn.Linear(26, 32), nn.ReLU(), nn.Linear(32, 32), nn.ReLU(), nn.Linear(32, self.num_actions)) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def compute(self, inputs, role): states = inputs["states"] # The dm_control.manipulation tasks have as observation/state spec a `collections.OrderedDict` object as follows: # OrderedDict([('front_close', BoundedArray(shape=(1, 84, 84, 3), dtype=dtype('uint8'), name='front_close', minimum=0, maximum=255)), # ('jaco_arm/joints_pos', Array(shape=(1, 6, 2), dtype=dtype('float64'), name='jaco_arm/joints_pos')), # ('jaco_arm/joints_torque', Array(shape=(1, 6), dtype=dtype('float64'), name='jaco_arm/joints_torque')), # ('jaco_arm/joints_vel', Array(shape=(1, 6), dtype=dtype('float64'), name='jaco_arm/joints_vel')), # ('jaco_arm/jaco_hand/joints_pos', Array(shape=(1, 3), dtype=dtype('float64'), name='jaco_arm/jaco_hand/joints_pos')), # ('jaco_arm/jaco_hand/joints_vel', Array(shape=(1, 3), dtype=dtype('float64'), name='jaco_arm/jaco_hand/joints_vel')), # ('jaco_arm/jaco_hand/pinch_site_pos', Array(shape=(1, 3), dtype=dtype('float64'), name='jaco_arm/jaco_hand/pinch_site_pos')), # ('jaco_arm/jaco_hand/pinch_site_rmat', Array(shape=(1, 9), dtype=dtype('float64'), name='jaco_arm/jaco_hand/pinch_site_rmat'))]) # This spec is converted to a `gym.spaces.Dict` space by the `wrap_env` function as follows: # Dict(front_close: Box(0, 255, (1, 84, 84, 3), uint8), # jaco_arm/jaco_hand/joints_pos: Box(-inf, inf, (1, 3), float64), # jaco_arm/jaco_hand/joints_vel: Box(-inf, inf, (1, 3), float64), # jaco_arm/jaco_hand/pinch_site_pos: Box(-inf, inf, (1, 3), float64), # jaco_arm/jaco_hand/pinch_site_rmat: Box(-inf, inf, (1, 9), float64), # jaco_arm/joints_pos: Box(-inf, inf, (1, 6, 2), float64), # jaco_arm/joints_torque: Box(-inf, inf, (1, 6), float64), # jaco_arm/joints_vel: Box(-inf, inf, (1, 6), float64)) # The `spaces` parameter is a flat tensor of the flattened observation/state space with shape (batch_size, size_of_flat_space). # Using the model's method `tensor_to_space` we can convert the flattened tensor to the original space. # https://skrl.readthedocs.io/en/latest/modules/skrl.models.base_class.html#skrl.models.torch.base.Model.tensor_to_space space = self.tensor_to_space(states, self.observation_space) # For this case, the `space` variable is a Python dictionary with the following structure and shapes: # {'front_close': torch.Tensor(shape=[batch_size, 1, 84, 84, 3], dtype=torch.float32), # 'jaco_arm/jaco_hand/joints_pos': torch.Tensor(shape=[batch_size, 1, 3], dtype=torch.float32) # 'jaco_arm/jaco_hand/joints_vel': torch.Tensor(shape=[batch_size, 1, 3], dtype=torch.float32) # 'jaco_arm/jaco_hand/pinch_site_pos': torch.Tensor(shape=[batch_size, 1, 3], dtype=torch.float32) # 'jaco_arm/jaco_hand/pinch_site_rmat': torch.Tensor(shape=[batch_size, 1, 9], dtype=torch.float32) # 'jaco_arm/joints_pos': torch.Tensor(shape=[batch_size, 1, 6, 2], dtype=torch.float32) # 'jaco_arm/joints_torque': torch.Tensor(shape=[batch_size, 1, 6], dtype=torch.float32) # 'jaco_arm/joints_vel': torch.Tensor(shape=[batch_size, 1, 6], dtype=torch.float32)} # permute and normalize the images (samples, width, height, channels) -> (samples, channels, width, height) features = self.features_extractor(space['front_close'][:,0].permute(0, 3, 1, 2) / 255.0) mean_actions = torch.tanh(self.net(torch.cat([features, space["jaco_arm/joints_pos"].view(states.shape[0], -1), space["jaco_arm/joints_vel"].view(states.shape[0], -1)], dim=-1))) return mean_actions, self.log_std_parameter, {} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.features_extractor = nn.Sequential(nn.Conv2d(3, 32, kernel_size=8, stride=3), nn.ReLU(), nn.Conv2d(32, 64, kernel_size=4, stride=2), nn.ReLU(), nn.Conv2d(64, 64, kernel_size=2, stride=1), nn.ReLU(), nn.Flatten(), nn.Linear(7744, 512), nn.ReLU(), nn.Linear(512, 8), nn.Tanh()) self.net = nn.Sequential(nn.Linear(26 + self.num_actions, 32), nn.ReLU(), nn.Linear(32, 32), nn.ReLU(), nn.Linear(32, 1)) def compute(self, inputs, role): states = inputs["states"] # map the observations/states to the original space. # See the explanation above (StochasticActor.compute) space = self.tensor_to_space(states, self.observation_space) # permute and normalize the images (samples, width, height, channels) -> (samples, channels, width, height) features = self.features_extractor(space['front_close'][:,0].permute(0, 3, 1, 2) / 255.0) return self.net(torch.cat([features, space["jaco_arm/joints_pos"].view(states.shape[0], -1), space["jaco_arm/joints_vel"].view(states.shape[0], -1), inputs["taken_actions"]], dim=-1)), {} # Load and wrap the DeepMind environment env = manipulation.load("reach_site_vision") env = wrap_env(env) device = env.device # Instantiate a RandomMemory (without replacement) as experience replay memory memory = RandomMemory(memory_size=50000, num_envs=env.num_envs, device=device, replacement=False) # Instantiate the agent's models (function approximators). # SAC requires 5 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/modules/skrl.agents.sac.html#spaces-and-models models_sac = {} models_sac["policy"] = StochasticActor(env.observation_space, env.action_space, device, clip_actions=True) models_sac["critic_1"] = Critic(env.observation_space, env.action_space, device) models_sac["critic_2"] = Critic(env.observation_space, env.action_space, device) models_sac["target_critic_1"] = Critic(env.observation_space, env.action_space, device) models_sac["target_critic_2"] = Critic(env.observation_space, env.action_space, device) # Initialize the models' parameters (weights and biases) using a Gaussian distribution for model in models_sac.values(): model.init_parameters(method_name="normal_", mean=0.0, std=0.1) # Configure and instantiate the agent. # Only modify some of the default configuration, visit its documentation to see all the options # https://skrl.readthedocs.io/en/latest/modules/skrl.agents.sac.html#configuration-and-hyperparameters cfg_sac = SAC_DEFAULT_CONFIG.copy() cfg_sac["gradient_steps"] = 1 cfg_sac["batch_size"] = 256 cfg_sac["random_timesteps"] = 0 cfg_sac["learning_starts"] = 10000 cfg_sac["learn_entropy"] = True # logging to TensorBoard and write checkpoints each 1000 and 5000 timesteps respectively cfg_sac["experiment"]["write_interval"] = 1000 cfg_sac["experiment"]["checkpoint_interval"] = 5000 agent_sac = SAC(models=models_sac, memory=memory, cfg=cfg_sac, observation_space=env.observation_space, action_space=env.action_space, device=device) # Configure and instantiate the RL trainer cfg_trainer = {"timesteps": 100000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent_sac) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/robosuite/td3_robosuite_two_arm_lift.py
import robosuite from robosuite.controllers import load_controller_config import torch import torch.nn as nn import torch.nn.functional as F # Import the skrl components to build the RL system from skrl.models.torch import Model, DeterministicMixin from skrl.memories.torch import RandomMemory from skrl.agents.torch.td3 import TD3, TD3_DEFAULT_CONFIG from skrl.resources.noises.torch import GaussianNoise from skrl.trainers.torch import SequentialTrainer from skrl.envs.torch import wrap_env # Define the models (deterministic models) for the TD3 agent using mixins # and programming with two approaches (torch functional and torch.nn.Sequential class). # - Actor (policy): takes as input the environment's observation/state and returns an action # - Critic: takes the state and action as input and provides a value to guide the policy class DeterministicActor(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.linear_layer_1 = nn.Linear(self.num_observations, 400) self.linear_layer_2 = nn.Linear(400, 300) self.action_layer = nn.Linear(300, self.num_actions) def compute(self, inputs, role): x = F.relu(self.linear_layer_1(inputs["states"])) x = F.relu(self.linear_layer_2(x)) return torch.tanh(self.action_layer(x)), {} class DeterministicCritic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations + self.num_actions, 400), nn.ReLU(), nn.Linear(400, 300), nn.ReLU(), nn.Linear(300, 1)) def compute(self, inputs, role): return self.net(torch.cat([inputs["states"], inputs["taken_actions"]], dim=1)), {} # Load and wrap the DeepMind robosuite environment controller_config = load_controller_config(default_controller="OSC_POSE") env = robosuite.make("TwoArmLift", robots=["Sawyer", "Panda"], # load a Sawyer robot and a Panda robot gripper_types="default", # use default grippers per robot arm controller_configs=controller_config, # each arm is controlled using OSC env_configuration="single-arm-opposed", # (two-arm envs only) arms face each other has_renderer=True, # on-screen rendering render_camera="frontview", # visualize the "frontview" camera has_offscreen_renderer=False, # no off-screen rendering control_freq=20, # 20 hz control for applied actions horizon=200, # each episode terminates after 200 steps use_object_obs=True, # provide object observations to agent use_camera_obs=False, # don't provide image observations to agent reward_shaping=True) # use a dense reward signal for learning env = wrap_env(env) device = env.device # Instantiate a RandomMemory (without replacement) as experience replay memory memory = RandomMemory(memory_size=25000, num_envs=env.num_envs, device=device, replacement=False) # Instantiate the agent's models (function approximators). # TD3 requires 6 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/modules/skrl.agents.td3.html#spaces-and-models models = {} models["policy"] = DeterministicActor(env.observation_space, env.action_space, device) models["target_policy"] = DeterministicActor(env.observation_space, env.action_space, device) models["critic_1"] = DeterministicCritic(env.observation_space, env.action_space, device) models["critic_2"] = DeterministicCritic(env.observation_space, env.action_space, device) models["target_critic_1"] = DeterministicCritic(env.observation_space, env.action_space, device) models["target_critic_2"] = DeterministicCritic(env.observation_space, env.action_space, device) # Initialize the models' parameters (weights and biases) using a Gaussian distribution for model in models.values(): model.init_parameters(method_name="normal_", mean=0.0, std=0.1) # Configure and instantiate the agent. # Only modify some of the default configuration, visit its documentation to see all the options # https://skrl.readthedocs.io/en/latest/modules/skrl.agents.td3.html#configuration-and-hyperparameters cfg_agent = TD3_DEFAULT_CONFIG.copy() cfg_agent["exploration"]["noise"] = GaussianNoise(0, 0.1, device=device) cfg_agent["smooth_regularization_noise"] = GaussianNoise(0, 0.2, device=device) cfg_agent["smooth_regularization_clip"] = 0.5 cfg_agent["batch_size"] = 100 cfg_agent["random_timesteps"] = 100 cfg_agent["learning_starts"] = 100 # logging to TensorBoard and write checkpoints each 1000 and 5000 timesteps respectively cfg_agent["experiment"]["write_interval"] = 1000 cfg_agent["experiment"]["checkpoint_interval"] = 5000 agent = TD3(models=models, memory=memory, cfg=cfg_agent, observation_space=env.observation_space, action_space=env.action_space, device=device) # Configure and instantiate the RL trainer cfg_trainer = {"timesteps": 50000, "headless": False} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_pendulumnovel_sac_gru.py
import gymnasium as gym import numpy as np import torch import torch.nn as nn import torch.nn.functional as F # import the skrl components to build the RL system from skrl.agents.torch.sac import SAC_DEFAULT_CONFIG from skrl.agents.torch.sac import SAC_RNN as SAC from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Actor(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", num_envs=1, num_layers=1, hidden_size=400, sequence_length=20): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hout self.sequence_length = sequence_length self.gru = nn.GRU(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.linear_layer_1 = nn.Linear(self.hidden_size, 400) self.linear_layer_2 = nn.Linear(400, 300) self.action_layer = nn.Linear(300, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size)]}} # hidden states (D ∗ num_layers, N, Hout) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states = inputs["rnn"][0] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) # get the hidden states corresponding to the initial sequence hidden_states = hidden_states[:,:,0,:].contiguous() # (D * num_layers, N, Hout) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, hidden_states = self.gru(rnn_input[:,i0:i1,:], hidden_states) hidden_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, hidden_states = self.gru(rnn_input, hidden_states) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, hidden_states = self.gru(rnn_input, hidden_states) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) x = F.relu(self.linear_layer_1(rnn_output)) x = F.relu(self.linear_layer_2(x)) # Pendulum-v1 action_space is -2 to 2 return 2 * torch.tanh(self.action_layer(x)), self.log_std_parameter, {"rnn": [hidden_states]} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, num_envs=1, num_layers=1, hidden_size=400, sequence_length=20): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hout self.sequence_length = sequence_length self.gru = nn.GRU(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.linear_layer_1 = nn.Linear(self.hidden_size + self.num_actions, 400) self.linear_layer_2 = nn.Linear(400, 300) self.linear_layer_3 = nn.Linear(300, 1) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size)]}} # hidden states (D ∗ num_layers, N, Hout) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states = inputs["rnn"][0] # critic is only used during training rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) # get the hidden states corresponding to the initial sequence sequence_index = 1 if role in ["target_critic_1", "target_critic_2"] else 0 # target networks act on the next state of the environment hidden_states = hidden_states[:,:,sequence_index,:].contiguous() # (D * num_layers, N, Hout) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, hidden_states = self.gru(rnn_input[:,i0:i1,:], hidden_states) hidden_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, hidden_states = self.gru(rnn_input, hidden_states) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) x = F.relu(self.linear_layer_1(torch.cat([rnn_output, inputs["taken_actions"]], dim=1))) x = F.relu(self.linear_layer_2(x)) return self.linear_layer_3(x), {"rnn": [hidden_states]} # environment observation wrapper used to mask velocity. Adapted from rl_zoo3 (rl_zoo3/wrappers.py) class NoVelocityWrapper(gym.ObservationWrapper): def observation(self, observation): # observation: x, y, angular velocity return observation * np.array([1, 1, 0]) gym.envs.registration.register(id="PendulumNoVel-v1", entry_point=lambda: NoVelocityWrapper(gym.make("Pendulum-v1"))) # load and wrap the gymnasium environment env = gym.make("PendulumNoVel-v1") env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=20000, num_envs=env.num_envs, device=device, replacement=False) # instantiate the agent's models (function approximators). # SAC requires 5 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/sac.html#models models = {} models["policy"] = Actor(env.observation_space, env.action_space, device, clip_actions=True, num_envs=env.num_envs) models["critic_1"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["critic_2"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["target_critic_1"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["target_critic_2"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal_", mean=0.0, std=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/sac.html#configuration-and-hyperparameters cfg = SAC_DEFAULT_CONFIG.copy() cfg["discount_factor"] = 0.98 cfg["batch_size"] = 100 cfg["random_timesteps"] = 0 cfg["learning_starts"] = 1000 cfg["learn_entropy"] = True # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 75 cfg["experiment"]["checkpoint_interval"] = 750 cfg["experiment"]["directory"] = "runs/torch/PendulumNoVel" agent = SAC(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 15000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_taxi_vector_sarsa.py
import gymnasium as gym import torch # import the skrl components to build the RL system from skrl.agents.torch.sarsa import SARSA, SARSA_DEFAULT_CONFIG from skrl.envs.wrappers.torch import wrap_env from skrl.models.torch import Model, TabularMixin from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define model (tabular model) using mixin class EpilonGreedyPolicy(TabularMixin, Model): def __init__(self, observation_space, action_space, device, num_envs=1, epsilon=0.1): Model.__init__(self, observation_space, action_space, device) TabularMixin.__init__(self, num_envs) self.epsilon = epsilon self.q_table = torch.ones((num_envs, self.num_observations, self.num_actions), dtype=torch.float32, device=self.device) def compute(self, inputs, role): actions = torch.argmax(self.q_table[torch.arange(self.num_envs).view(-1, 1), inputs["states"]], dim=-1, keepdim=True).view(-1,1) # choose random actions for exploration according to epsilon indexes = (torch.rand(inputs["states"].shape[0], device=self.device) < self.epsilon).nonzero().view(-1) if indexes.numel(): actions[indexes] = torch.randint(self.num_actions, (indexes.numel(), 1), device=self.device) return actions, {} # load and wrap the gymnasium environment. # note: the environment version may change depending on the gymnasium version try: env = gym.vector.make("Taxi-v3", num_envs=10, asynchronous=False) except (gym.error.DeprecatedEnv, gym.error.VersionNotFound) as e: env_id = [spec for spec in gym.envs.registry if spec.startswith("Taxi-v")][0] print("Taxi-v3 not found. Trying {}".format(env_id)) env = gym.vector.make(env_id, num_envs=10, asynchronous=False) env = wrap_env(env) device = env.device # instantiate the agent's model (table) # SARSA requires 1 model, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/sarsa.html#models models = {} models["policy"] = EpilonGreedyPolicy(env.observation_space, env.action_space, device, num_envs=env.num_envs, epsilon=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/sarsa.html#configuration-and-hyperparameters cfg = SARSA_DEFAULT_CONFIG.copy() cfg["discount_factor"] = 0.999 cfg["alpha"] = 0.4 # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 1600 cfg["experiment"]["checkpoint_interval"] = 8000 cfg["experiment"]["directory"] = "runs/torch/Taxi" agent = SARSA(models=models, memory=None, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 80000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_taxi_sarsa.py
import gymnasium as gym import torch # import the skrl components to build the RL system from skrl.agents.torch.sarsa import SARSA, SARSA_DEFAULT_CONFIG from skrl.envs.wrappers.torch import wrap_env from skrl.models.torch import Model, TabularMixin from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define model (tabular model) using mixin class EpilonGreedyPolicy(TabularMixin, Model): def __init__(self, observation_space, action_space, device, num_envs=1, epsilon=0.1): Model.__init__(self, observation_space, action_space, device) TabularMixin.__init__(self, num_envs) self.epsilon = epsilon self.q_table = torch.ones((num_envs, self.num_observations, self.num_actions), dtype=torch.float32, device=self.device) def compute(self, inputs, role): actions = torch.argmax(self.q_table[torch.arange(self.num_envs).view(-1, 1), inputs["states"]], dim=-1, keepdim=True).view(-1,1) # choose random actions for exploration according to epsilon indexes = (torch.rand(inputs["states"].shape[0], device=self.device) < self.epsilon).nonzero().view(-1) if indexes.numel(): actions[indexes] = torch.randint(self.num_actions, (indexes.numel(), 1), device=self.device) return actions, {} # load and wrap the gymnasium environment. # note: the environment version may change depending on the gymnasium version try: env = gym.make("Taxi-v3") except (gym.error.DeprecatedEnv, gym.error.VersionNotFound) as e: env_id = [spec for spec in gym.envs.registry if spec.startswith("Taxi-v")][0] print("Taxi-v3 not found. Trying {}".format(env_id)) env = gym.make(env_id) env = wrap_env(env) device = env.device # instantiate the agent's model (table) # SARSA requires 1 model, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/sarsa.html#models models = {} models["policy"] = EpilonGreedyPolicy(env.observation_space, env.action_space, device, num_envs=env.num_envs, epsilon=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/sarsa.html#configuration-and-hyperparameters cfg = SARSA_DEFAULT_CONFIG.copy() cfg["discount_factor"] = 0.999 cfg["alpha"] = 0.4 # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 1600 cfg["experiment"]["checkpoint_interval"] = 8000 cfg["experiment"]["directory"] = "runs/torch/Taxi" agent = SARSA(models=models, memory=None, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 80000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_pendulumnovel_ddpg_rnn.py
import gymnasium as gym import numpy as np import torch import torch.nn as nn import torch.nn.functional as F # import the skrl components to build the RL system from skrl.agents.torch.ddpg import DDPG_DEFAULT_CONFIG from skrl.agents.torch.ddpg import DDPG_RNN as DDPG from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, Model from skrl.resources.noises.torch import OrnsteinUhlenbeckNoise from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (deterministic models) using mixin class Actor(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, num_envs=1, num_layers=1, hidden_size=400, sequence_length=20): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hout self.sequence_length = sequence_length self.rnn = nn.RNN(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.linear_layer_1 = nn.Linear(self.hidden_size, 400) self.linear_layer_2 = nn.Linear(400, 300) self.action_layer = nn.Linear(300, self.num_actions) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size)]}} # hidden states (D ∗ num_layers, N, Hout) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states = inputs["rnn"][0] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) # get the hidden states corresponding to the initial sequence sequence_index = 1 if role == "target_policy" else 0 # target networks act on the next state of the environment hidden_states = hidden_states[:,:,sequence_index,:].contiguous() # (D * num_layers, N, Hout) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, hidden_states = self.rnn(rnn_input[:,i0:i1,:], hidden_states) hidden_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, hidden_states = self.rnn(rnn_input, hidden_states) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, hidden_states = self.rnn(rnn_input, hidden_states) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) x = F.relu(self.linear_layer_1(rnn_output)) x = F.relu(self.linear_layer_2(x)) # Pendulum-v1 action_space is -2 to 2 return 2 * torch.tanh(self.action_layer(x)), {"rnn": [hidden_states]} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, num_envs=1, num_layers=1, hidden_size=400, sequence_length=20): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hout self.sequence_length = sequence_length self.rnn = nn.RNN(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.linear_layer_1 = nn.Linear(self.hidden_size + self.num_actions, 400) self.linear_layer_2 = nn.Linear(400, 300) self.linear_layer_3 = nn.Linear(300, 1) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size)]}} # hidden states (D ∗ num_layers, N, Hout) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states = inputs["rnn"][0] # critic is only used during training rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) # get the hidden states corresponding to the initial sequence sequence_index = 1 if role == "target_critic" else 0 # target networks act on the next state of the environment hidden_states = hidden_states[:,:,sequence_index,:].contiguous() # (D * num_layers, N, Hout) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, hidden_states = self.rnn(rnn_input[:,i0:i1,:], hidden_states) hidden_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, hidden_states = self.rnn(rnn_input, hidden_states) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) x = F.relu(self.linear_layer_1(torch.cat([rnn_output, inputs["taken_actions"]], dim=1))) x = F.relu(self.linear_layer_2(x)) return self.linear_layer_3(x), {"rnn": [hidden_states]} # environment observation wrapper used to mask velocity. Adapted from rl_zoo3 (rl_zoo3/wrappers.py) class NoVelocityWrapper(gym.ObservationWrapper): def observation(self, observation): # observation: x, y, angular velocity return observation * np.array([1, 1, 0]) gym.envs.registration.register(id="PendulumNoVel-v1", entry_point=lambda: NoVelocityWrapper(gym.make("Pendulum-v1"))) # load and wrap the gymnasium environment env = gym.make("PendulumNoVel-v1") env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=20000, num_envs=env.num_envs, device=device, replacement=False) # instantiate the agent's models (function approximators). # DDPG requires 4 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#models models = {} models["policy"] = Actor(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["target_policy"] = Actor(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["critic"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["target_critic"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal_", mean=0.0, std=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#configuration-and-hyperparameters cfg = DDPG_DEFAULT_CONFIG.copy() cfg["exploration"]["noise"] = OrnsteinUhlenbeckNoise(theta=0.15, sigma=0.1, base_scale=1.0, device=device) cfg["discount_factor"] = 0.98 cfg["batch_size"] = 100 cfg["random_timesteps"] = 0 cfg["learning_starts"] = 1000 # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 75 cfg["experiment"]["checkpoint_interval"] = 750 cfg["experiment"]["directory"] = "runs/torch/PendulumNoVel" agent = DDPG(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 15000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_cartpole_vector_dqn.py
import gymnasium as gym # import the skrl components to build the RL system from skrl.agents.torch.dqn import DQN, DQN_DEFAULT_CONFIG from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed from skrl.utils.model_instantiators.torch import Shape, deterministic_model # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # load and wrap the gymnasium environment. # note: the environment version may change depending on the gymnasium version try: env = gym.vector.make("CartPole-v1", num_envs=5, asynchronous=False) except (gym.error.DeprecatedEnv, gym.error.VersionNotFound) as e: env_id = [spec for spec in gym.envs.registry if spec.startswith("CartPole-v")][0] print("CartPole-v0 not found. Trying {}".format(env_id)) env = gym.vector.make(env_id, num_envs=5, asynchronous=False) env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=200000, num_envs=env.num_envs, device=device, replacement=False) # instantiate the agent's models (function approximators) using the model instantiator utility. # DQN requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/dqn.html#models models = {} models["q_network"] = deterministic_model(observation_space=env.observation_space, action_space=env.action_space, device=device, clip_actions=False, input_shape=Shape.OBSERVATIONS, hiddens=[64, 64], hidden_activation=["relu", "relu"], output_shape=Shape.ACTIONS, output_activation=None, output_scale=1.0) models["target_q_network"] = deterministic_model(observation_space=env.observation_space, action_space=env.action_space, device=device, clip_actions=False, input_shape=Shape.OBSERVATIONS, hiddens=[64, 64], hidden_activation=["relu", "relu"], output_shape=Shape.ACTIONS, output_activation=None, output_scale=1.0) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal_", mean=0.0, std=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/dqn.html#configuration-and-hyperparameters cfg = DQN_DEFAULT_CONFIG.copy() cfg["learning_starts"] = 100 cfg["exploration"]["final_epsilon"] = 0.04 cfg["exploration"]["timesteps"] = 1500 # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 1000 cfg["experiment"]["checkpoint_interval"] = 5000 cfg["experiment"]["directory"] = "runs/torch/CartPole" agent = DQN(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 50000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_pendulumnovel_ppo_gru.py
import gymnasium as gym import numpy as np import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO_DEFAULT_CONFIG from skrl.agents.torch.ppo import PPO_RNN as PPO from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.resources.schedulers.torch import KLAdaptiveRL from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", num_envs=1, num_layers=1, hidden_size=64, sequence_length=128): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hout self.sequence_length = sequence_length self.gru = nn.GRU(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.net = nn.Sequential(nn.Linear(self.hidden_size, 64), nn.ReLU(), nn.Linear(64, self.num_actions)) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size)]}} # hidden states (D ∗ num_layers, N, Hout) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states = inputs["rnn"][0] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) # get the hidden states corresponding to the initial sequence hidden_states = hidden_states[:,:,0,:].contiguous() # (D * num_layers, N, Hout) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, hidden_states = self.gru(rnn_input[:,i0:i1,:], hidden_states) hidden_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, hidden_states = self.gru(rnn_input, hidden_states) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, hidden_states = self.gru(rnn_input, hidden_states) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) # Pendulum-v1 action_space is -2 to 2 return 2 * torch.tanh(self.net(rnn_output)), self.log_std_parameter, {"rnn": [hidden_states]} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, num_envs=1, num_layers=1, hidden_size=64, sequence_length=128): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hout self.sequence_length = sequence_length self.gru = nn.GRU(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.net = nn.Sequential(nn.Linear(self.hidden_size, 64), nn.ReLU(), nn.Linear(64, 1)) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size)]}} # hidden states (D ∗ num_layers, N, Hout) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states = inputs["rnn"][0] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) # get the hidden states corresponding to the initial sequence hidden_states = hidden_states[:,:,0,:].contiguous() # (D * num_layers, N, Hout) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, hidden_states = self.gru(rnn_input[:,i0:i1,:], hidden_states) hidden_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, hidden_states = self.gru(rnn_input, hidden_states) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, hidden_states = self.gru(rnn_input, hidden_states) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) return self.net(rnn_output), {"rnn": [hidden_states]} # environment observation wrapper used to mask velocity. Adapted from rl_zoo3 (rl_zoo3/wrappers.py) class NoVelocityWrapper(gym.ObservationWrapper): def observation(self, observation): # observation: x, y, angular velocity return observation * np.array([1, 1, 0]) gym.envs.registration.register(id="PendulumNoVel-v1", entry_point=lambda: NoVelocityWrapper(gym.make("Pendulum-v1"))) # load and wrap the gymnasium environment env = gym.vector.make("PendulumNoVel-v1", num_envs=4, asynchronous=False) env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=1024, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device, clip_actions=True, num_envs=env.num_envs) models["value"] = Value(env.observation_space, env.action_space, device, num_envs=env.num_envs) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 1024 # memory_size cfg["learning_epochs"] = 10 cfg["mini_batches"] = 32 cfg["discount_factor"] = 0.9 cfg["lambda"] = 0.95 cfg["learning_rate"] = 1e-3 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["grad_norm_clip"] = 0.5 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = False cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 0.5 cfg["kl_threshold"] = 0 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 500 cfg["experiment"]["checkpoint_interval"] = 5000 cfg["experiment"]["directory"] = "runs/torch/PendulumNoVel" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 100000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_pendulum_vector_ddpg.py
import gymnasium as gym import torch import torch.nn as nn import torch.nn.functional as F # import the skrl components to build the RL system from skrl.agents.torch.ddpg import DDPG, DDPG_DEFAULT_CONFIG from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, Model from skrl.resources.noises.torch import OrnsteinUhlenbeckNoise from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (deterministic models) using mixin class Actor(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.linear_layer_1 = nn.Linear(self.num_observations, 400) self.linear_layer_2 = nn.Linear(400, 300) self.action_layer = nn.Linear(300, self.num_actions) def compute(self, inputs, role): x = F.relu(self.linear_layer_1(inputs["states"])) x = F.relu(self.linear_layer_2(x)) # Pendulum-v1 action_space is -2 to 2 return 2 * torch.tanh(self.action_layer(x)), {} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.linear_layer_1 = nn.Linear(self.num_observations + self.num_actions, 400) self.linear_layer_2 = nn.Linear(400, 300) self.linear_layer_3 = nn.Linear(300, 1) def compute(self, inputs, role): x = F.relu(self.linear_layer_1(torch.cat([inputs["states"], inputs["taken_actions"]], dim=1))) x = F.relu(self.linear_layer_2(x)) return self.linear_layer_3(x), {} # load and wrap the gymnasium environment. # note: the environment version may change depending on the gymnasium version try: env = gym.vector.make("Pendulum-v1", num_envs=10, asynchronous=False) except (gym.error.DeprecatedEnv, gym.error.VersionNotFound) as e: env_id = [spec for spec in gym.envs.registry if spec.startswith("Pendulum-v")][0] print("Pendulum-v1 not found. Trying {}".format(env_id)) env = gym.vector.make(env_id, num_envs=10, asynchronous=False) env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=100000, num_envs=env.num_envs, device=device, replacement=False) # instantiate the agent's models (function approximators). # DDPG requires 4 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#models models = {} models["policy"] = Actor(env.observation_space, env.action_space, device) models["target_policy"] = Actor(env.observation_space, env.action_space, device) models["critic"] = Critic(env.observation_space, env.action_space, device) models["target_critic"] = Critic(env.observation_space, env.action_space, device) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal_", mean=0.0, std=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#configuration-and-hyperparameters cfg = DDPG_DEFAULT_CONFIG.copy() cfg["exploration"]["noise"] = OrnsteinUhlenbeckNoise(theta=0.15, sigma=0.1, base_scale=1.0, device=device) cfg["batch_size"] = 100 cfg["random_timesteps"] = 100 cfg["learning_starts"] = 100 # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 1000 cfg["experiment"]["checkpoint_interval"] = 1000 cfg["experiment"]["directory"] = "runs/torch/Pendulum" agent = DDPG(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 15000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_pendulumnovel_td3_gru.py
import gymnasium as gym import numpy as np import torch import torch.nn as nn import torch.nn.functional as F # import the skrl components to build the RL system from skrl.agents.torch.td3 import TD3_DEFAULT_CONFIG from skrl.agents.torch.td3 import TD3_RNN as TD3 from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, Model from skrl.resources.noises.torch import GaussianNoise from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (deterministic models) using mixin class Actor(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, num_envs=1, num_layers=1, hidden_size=400, sequence_length=20): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hout self.sequence_length = sequence_length self.gru = nn.GRU(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.linear_layer_1 = nn.Linear(self.hidden_size, 400) self.linear_layer_2 = nn.Linear(400, 300) self.action_layer = nn.Linear(300, self.num_actions) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size)]}} # hidden states (D ∗ num_layers, N, Hout) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states = inputs["rnn"][0] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) # get the hidden states corresponding to the initial sequence sequence_index = 1 if role == "target_policy" else 0 # target networks act on the next state of the environment hidden_states = hidden_states[:,:,sequence_index,:].contiguous() # (D * num_layers, N, Hout) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, hidden_states = self.gru(rnn_input[:,i0:i1,:], hidden_states) hidden_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, hidden_states = self.gru(rnn_input, hidden_states) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, hidden_states = self.gru(rnn_input, hidden_states) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) x = F.relu(self.linear_layer_1(rnn_output)) x = F.relu(self.linear_layer_2(x)) # Pendulum-v1 action_space is -2 to 2 return 2 * torch.tanh(self.action_layer(x)), {"rnn": [hidden_states]} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, num_envs=1, num_layers=1, hidden_size=400, sequence_length=20): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hout self.sequence_length = sequence_length self.gru = nn.GRU(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.linear_layer_1 = nn.Linear(self.hidden_size + self.num_actions, 400) self.linear_layer_2 = nn.Linear(400, 300) self.linear_layer_3 = nn.Linear(300, 1) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size)]}} # hidden states (D ∗ num_layers, N, Hout) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states = inputs["rnn"][0] # critic is only used during training rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) # get the hidden states corresponding to the initial sequence sequence_index = 1 if role in ["target_critic_1", "target_critic_2"] else 0 # target networks act on the next state of the environment hidden_states = hidden_states[:,:,sequence_index,:].contiguous() # (D * num_layers, N, Hout) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, hidden_states = self.gru(rnn_input[:,i0:i1,:], hidden_states) hidden_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, hidden_states = self.gru(rnn_input, hidden_states) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) x = F.relu(self.linear_layer_1(torch.cat([rnn_output, inputs["taken_actions"]], dim=1))) x = F.relu(self.linear_layer_2(x)) return self.linear_layer_3(x), {"rnn": [hidden_states]} # environment observation wrapper used to mask velocity. Adapted from rl_zoo3 (rl_zoo3/wrappers.py) class NoVelocityWrapper(gym.ObservationWrapper): def observation(self, observation): # observation: x, y, angular velocity return observation * np.array([1, 1, 0]) gym.envs.registration.register(id="PendulumNoVel-v1", entry_point=lambda: NoVelocityWrapper(gym.make("Pendulum-v1"))) # load and wrap the gymnasium environment env = gym.make("PendulumNoVel-v1") env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=20000, num_envs=env.num_envs, device=device, replacement=False) # instantiate the agent's models (function approximators). # TD3 requires 6 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/td3.html#models models = {} models["policy"] = Actor(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["target_policy"] = Actor(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["critic_1"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["critic_2"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["target_critic_1"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["target_critic_2"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal_", mean=0.0, std=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/td3.html#configuration-and-hyperparameters cfg = TD3_DEFAULT_CONFIG.copy() cfg["exploration"]["noise"] = GaussianNoise(0, 0.1, device=device) cfg["smooth_regularization_noise"] = GaussianNoise(0, 0.2, device=device) cfg["smooth_regularization_clip"] = 0.5 cfg["discount_factor"] = 0.98 cfg["batch_size"] = 100 cfg["random_timesteps"] = 0 cfg["learning_starts"] = 1000 # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 75 cfg["experiment"]["checkpoint_interval"] = 750 cfg["experiment"]["directory"] = "runs/torch/PendulumNoVel" agent = TD3(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 15000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_pendulumnovel_sac_lstm.py
import gymnasium as gym import numpy as np import torch import torch.nn as nn import torch.nn.functional as F # import the skrl components to build the RL system from skrl.agents.torch.sac import SAC_DEFAULT_CONFIG from skrl.agents.torch.sac import SAC_RNN as SAC from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Actor(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", num_envs=1, num_layers=1, hidden_size=400, sequence_length=20): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hcell (Hout is Hcell because proj_size = 0) self.sequence_length = sequence_length self.lstm = nn.LSTM(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.linear_layer_1 = nn.Linear(self.hidden_size, 400) self.linear_layer_2 = nn.Linear(400, 300) self.action_layer = nn.Linear(300, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size), # hidden states (D ∗ num_layers, N, Hout) (self.num_layers, self.num_envs, self.hidden_size)]}} # cell states (D ∗ num_layers, N, Hcell) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states, cell_states = inputs["rnn"][0], inputs["rnn"][1] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) cell_states = cell_states.view(self.num_layers, -1, self.sequence_length, cell_states.shape[-1]) # (D * num_layers, N, L, Hcell) # get the hidden/cell states corresponding to the initial sequence hidden_states = hidden_states[:,:,0,:].contiguous() # (D * num_layers, N, Hout) cell_states = cell_states[:,:,0,:].contiguous() # (D * num_layers, N, Hcell) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, (hidden_states, cell_states) = self.lstm(rnn_input[:,i0:i1,:], (hidden_states, cell_states)) hidden_states[:, (terminated[:,i1-1]), :] = 0 cell_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_states = (hidden_states, cell_states) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, rnn_states = self.lstm(rnn_input, (hidden_states, cell_states)) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, rnn_states = self.lstm(rnn_input, (hidden_states, cell_states)) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) x = F.relu(self.linear_layer_1(rnn_output)) x = F.relu(self.linear_layer_2(x)) # Pendulum-v1 action_space is -2 to 2 return 2 * torch.tanh(self.action_layer(x)), self.log_std_parameter, {"rnn": [rnn_states[0], rnn_states[1]]} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, num_envs=1, num_layers=1, hidden_size=400, sequence_length=20): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hcell (Hout is Hcell because proj_size = 0) self.sequence_length = sequence_length self.lstm = nn.LSTM(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.linear_layer_1 = nn.Linear(self.hidden_size + self.num_actions, 400) self.linear_layer_2 = nn.Linear(400, 300) self.linear_layer_3 = nn.Linear(300, 1) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size), # hidden states (D ∗ num_layers, N, Hout) (self.num_layers, self.num_envs, self.hidden_size)]}} # cell states (D ∗ num_layers, N, Hcell) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states, cell_states = inputs["rnn"][0], inputs["rnn"][1] # critic is only used during training rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) cell_states = cell_states.view(self.num_layers, -1, self.sequence_length, cell_states.shape[-1]) # (D * num_layers, N, L, Hcell) # get the hidden/cell states corresponding to the initial sequence sequence_index = 1 if role in ["target_critic_1", "target_critic_2"] else 0 # target networks act on the next state of the environment hidden_states = hidden_states[:,:,sequence_index,:].contiguous() # (D * num_layers, N, Hout) cell_states = cell_states[:,:,sequence_index,:].contiguous() # (D * num_layers, N, Hcell) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, (hidden_states, cell_states) = self.lstm(rnn_input[:,i0:i1,:], (hidden_states, cell_states)) hidden_states[:, (terminated[:,i1-1]), :] = 0 cell_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_states = (hidden_states, cell_states) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, rnn_states = self.lstm(rnn_input, (hidden_states, cell_states)) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) x = F.relu(self.linear_layer_1(torch.cat([rnn_output, inputs["taken_actions"]], dim=1))) x = F.relu(self.linear_layer_2(x)) return self.linear_layer_3(x), {"rnn": [rnn_states[0], rnn_states[1]]} # environment observation wrapper used to mask velocity. Adapted from rl_zoo3 (rl_zoo3/wrappers.py) class NoVelocityWrapper(gym.ObservationWrapper): def observation(self, observation): # observation: x, y, angular velocity return observation * np.array([1, 1, 0]) gym.envs.registration.register(id="PendulumNoVel-v1", entry_point=lambda: NoVelocityWrapper(gym.make("Pendulum-v1"))) # load and wrap the gymnasium environment env = gym.make("PendulumNoVel-v1") env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=20000, num_envs=env.num_envs, device=device, replacement=False) # instantiate the agent's models (function approximators). # SAC requires 5 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/sac.html#models models = {} models["policy"] = Actor(env.observation_space, env.action_space, device, clip_actions=True, num_envs=env.num_envs) models["critic_1"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["critic_2"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["target_critic_1"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["target_critic_2"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal_", mean=0.0, std=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/sac.html#configuration-and-hyperparameters cfg = SAC_DEFAULT_CONFIG.copy() cfg["discount_factor"] = 0.98 cfg["batch_size"] = 100 cfg["random_timesteps"] = 0 cfg["learning_starts"] = 1000 cfg["learn_entropy"] = True # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 75 cfg["experiment"]["checkpoint_interval"] = 750 cfg["experiment"]["directory"] = "runs/torch/PendulumNoVel" agent = SAC(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 15000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_pendulumnovel_trpo_gru.py
import gymnasium as gym import numpy as np import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.trpo import TRPO_DEFAULT_CONFIG from skrl.agents.torch.trpo import TRPO_RNN as TRPO from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", num_envs=1, num_layers=1, hidden_size=64, sequence_length=128): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hout self.sequence_length = sequence_length self.gru = nn.GRU(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.net = nn.Sequential(nn.Linear(self.hidden_size, 64), nn.ReLU(), nn.Linear(64, self.num_actions)) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size)]}} # hidden states (D ∗ num_layers, N, Hout) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states = inputs["rnn"][0] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) # get the hidden states corresponding to the initial sequence hidden_states = hidden_states[:,:,0,:].contiguous() # (D * num_layers, N, Hout) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, hidden_states = self.gru(rnn_input[:,i0:i1,:], hidden_states) hidden_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, hidden_states = self.gru(rnn_input, hidden_states) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, hidden_states = self.gru(rnn_input, hidden_states) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) # Pendulum-v1 action_space is -2 to 2 return 2 * torch.tanh(self.net(rnn_output)), self.log_std_parameter, {"rnn": [hidden_states]} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, num_envs=1, num_layers=1, hidden_size=64, sequence_length=128): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hout self.sequence_length = sequence_length self.gru = nn.GRU(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.net = nn.Sequential(nn.Linear(self.hidden_size, 64), nn.ReLU(), nn.Linear(64, 1)) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size)]}} # hidden states (D ∗ num_layers, N, Hout) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states = inputs["rnn"][0] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) # get the hidden states corresponding to the initial sequence hidden_states = hidden_states[:,:,0,:].contiguous() # (D * num_layers, N, Hout) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, hidden_states = self.gru(rnn_input[:,i0:i1,:], hidden_states) hidden_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, hidden_states = self.gru(rnn_input, hidden_states) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, hidden_states = self.gru(rnn_input, hidden_states) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) return self.net(rnn_output), {"rnn": [hidden_states]} # environment observation wrapper used to mask velocity. Adapted from rl_zoo3 (rl_zoo3/wrappers.py) class NoVelocityWrapper(gym.ObservationWrapper): def observation(self, observation): # observation: x, y, angular velocity return observation * np.array([1, 1, 0]) gym.envs.registration.register(id="PendulumNoVel-v1", entry_point=lambda: NoVelocityWrapper(gym.make("Pendulum-v1"))) # load and wrap the gymnasium environment env = gym.vector.make("PendulumNoVel-v1", num_envs=4, asynchronous=False) env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=1024, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # TRPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/trpo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device, clip_actions=True, num_envs=env.num_envs) models["value"] = Value(env.observation_space, env.action_space, device, num_envs=env.num_envs) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/trpo.html#configuration-and-hyperparameters cfg = TRPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 1024 # memory_size cfg["learning_epochs"] = 10 cfg["mini_batches"] = 32 cfg["discount_factor"] = 0.9 cfg["lambda"] = 0.95 cfg["learning_rate"] = 1e-3 cfg["grad_norm_clip"] = 0.5 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 500 cfg["experiment"]["checkpoint_interval"] = 5000 cfg["experiment"]["directory"] = "runs/torch/PendulumNoVel" agent = TRPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 100000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_pendulumnovel_td3_lstm.py
import gymnasium as gym import numpy as np import torch import torch.nn as nn import torch.nn.functional as F # import the skrl components to build the RL system from skrl.agents.torch.td3 import TD3_DEFAULT_CONFIG from skrl.agents.torch.td3 import TD3_RNN as TD3 from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, Model from skrl.resources.noises.torch import GaussianNoise from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (deterministic models) using mixin class Actor(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, num_envs=1, num_layers=1, hidden_size=400, sequence_length=20): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hcell (Hout is Hcell because proj_size = 0) self.sequence_length = sequence_length self.lstm = nn.LSTM(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.linear_layer_1 = nn.Linear(self.hidden_size, 400) self.linear_layer_2 = nn.Linear(400, 300) self.action_layer = nn.Linear(300, self.num_actions) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size), # hidden states (D ∗ num_layers, N, Hout) (self.num_layers, self.num_envs, self.hidden_size)]}} # cell states (D ∗ num_layers, N, Hcell) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states, cell_states = inputs["rnn"][0], inputs["rnn"][1] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) cell_states = cell_states.view(self.num_layers, -1, self.sequence_length, cell_states.shape[-1]) # (D * num_layers, N, L, Hcell) # get the hidden/cell states corresponding to the initial sequence sequence_index = 1 if role == "target_policy" else 0 # target networks act on the next state of the environment hidden_states = hidden_states[:,:,sequence_index,:].contiguous() # (D * num_layers, N, Hout) cell_states = cell_states[:,:,sequence_index,:].contiguous() # (D * num_layers, N, Hcell) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, (hidden_states, cell_states) = self.lstm(rnn_input[:,i0:i1,:], (hidden_states, cell_states)) hidden_states[:, (terminated[:,i1-1]), :] = 0 cell_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_states = (hidden_states, cell_states) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, rnn_states = self.lstm(rnn_input, (hidden_states, cell_states)) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, rnn_states = self.lstm(rnn_input, (hidden_states, cell_states)) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) x = F.relu(self.linear_layer_1(rnn_output)) x = F.relu(self.linear_layer_2(x)) # Pendulum-v1 action_space is -2 to 2 return 2 * torch.tanh(self.action_layer(x)), {"rnn": [rnn_states[0], rnn_states[1]]} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, num_envs=1, num_layers=1, hidden_size=400, sequence_length=20): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hcell (Hout is Hcell because proj_size = 0) self.sequence_length = sequence_length self.lstm = nn.LSTM(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.linear_layer_1 = nn.Linear(self.hidden_size + self.num_actions, 400) self.linear_layer_2 = nn.Linear(400, 300) self.linear_layer_3 = nn.Linear(300, 1) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size), # hidden states (D ∗ num_layers, N, Hout) (self.num_layers, self.num_envs, self.hidden_size)]}} # cell states (D ∗ num_layers, N, Hcell) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states, cell_states = inputs["rnn"][0], inputs["rnn"][1] # critic is only used during training rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) cell_states = cell_states.view(self.num_layers, -1, self.sequence_length, cell_states.shape[-1]) # (D * num_layers, N, L, Hcell) # get the hidden/cell states corresponding to the initial sequence sequence_index = 1 if role in ["target_critic_1", "target_critic_2"] else 0 # target networks act on the next state of the environment hidden_states = hidden_states[:,:,sequence_index,:].contiguous() # (D * num_layers, N, Hout) cell_states = cell_states[:,:,sequence_index,:].contiguous() # (D * num_layers, N, Hcell) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, (hidden_states, cell_states) = self.lstm(rnn_input[:,i0:i1,:], (hidden_states, cell_states)) hidden_states[:, (terminated[:,i1-1]), :] = 0 cell_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_states = (hidden_states, cell_states) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, rnn_states = self.lstm(rnn_input, (hidden_states, cell_states)) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) x = F.relu(self.linear_layer_1(torch.cat([rnn_output, inputs["taken_actions"]], dim=1))) x = F.relu(self.linear_layer_2(x)) return self.linear_layer_3(x), {"rnn": [rnn_states[0], rnn_states[1]]} # environment observation wrapper used to mask velocity. Adapted from rl_zoo3 (rl_zoo3/wrappers.py) class NoVelocityWrapper(gym.ObservationWrapper): def observation(self, observation): # observation: x, y, angular velocity return observation * np.array([1, 1, 0]) gym.envs.registration.register(id="PendulumNoVel-v1", entry_point=lambda: NoVelocityWrapper(gym.make("Pendulum-v1"))) # load and wrap the gymnasium environment env = gym.make("PendulumNoVel-v1") env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=20000, num_envs=env.num_envs, device=device, replacement=False) # instantiate the agent's models (function approximators). # TD3 requires 6 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/td3.html#models models = {} models["policy"] = Actor(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["target_policy"] = Actor(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["critic_1"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["critic_2"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["target_critic_1"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["target_critic_2"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal_", mean=0.0, std=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/td3.html#configuration-and-hyperparameters cfg = TD3_DEFAULT_CONFIG.copy() cfg["exploration"]["noise"] = GaussianNoise(0, 0.1, device=device) cfg["smooth_regularization_noise"] = GaussianNoise(0, 0.2, device=device) cfg["smooth_regularization_clip"] = 0.5 cfg["discount_factor"] = 0.98 cfg["batch_size"] = 100 cfg["random_timesteps"] = 0 cfg["learning_starts"] = 1000 # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 75 cfg["experiment"]["checkpoint_interval"] = 750 cfg["experiment"]["directory"] = "runs/torch/PendulumNoVel" agent = TD3(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 15000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_pendulumnovel_ppo_lstm.py
import gymnasium as gym import numpy as np import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO_DEFAULT_CONFIG from skrl.agents.torch.ppo import PPO_RNN as PPO from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.resources.schedulers.torch import KLAdaptiveRL from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", num_envs=1, num_layers=1, hidden_size=64, sequence_length=128): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hcell (Hout is Hcell because proj_size = 0) self.sequence_length = sequence_length self.lstm = nn.LSTM(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.net = nn.Sequential(nn.Linear(self.hidden_size, 64), nn.ReLU(), nn.Linear(64, self.num_actions)) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size), # hidden states (D ∗ num_layers, N, Hout) (self.num_layers, self.num_envs, self.hidden_size)]}} # cell states (D ∗ num_layers, N, Hcell) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states, cell_states = inputs["rnn"][0], inputs["rnn"][1] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) cell_states = cell_states.view(self.num_layers, -1, self.sequence_length, cell_states.shape[-1]) # (D * num_layers, N, L, Hcell) # get the hidden/cell states corresponding to the initial sequence hidden_states = hidden_states[:,:,0,:].contiguous() # (D * num_layers, N, Hout) cell_states = cell_states[:,:,0,:].contiguous() # (D * num_layers, N, Hcell) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, (hidden_states, cell_states) = self.lstm(rnn_input[:,i0:i1,:], (hidden_states, cell_states)) hidden_states[:, (terminated[:,i1-1]), :] = 0 cell_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_states = (hidden_states, cell_states) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, rnn_states = self.lstm(rnn_input, (hidden_states, cell_states)) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, rnn_states = self.lstm(rnn_input, (hidden_states, cell_states)) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) # Pendulum-v1 action_space is -2 to 2 return 2 * torch.tanh(self.net(rnn_output)), self.log_std_parameter, {"rnn": [rnn_states[0], rnn_states[1]]} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, num_envs=1, num_layers=1, hidden_size=64, sequence_length=128): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hcell (Hout is Hcell because proj_size = 0) self.sequence_length = sequence_length self.lstm = nn.LSTM(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.net = nn.Sequential(nn.Linear(self.hidden_size, 64), nn.ReLU(), nn.Linear(64, 1)) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size), # hidden states (D ∗ num_layers, N, Hout) (self.num_layers, self.num_envs, self.hidden_size)]}} # cell states (D ∗ num_layers, N, Hcell) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states, cell_states = inputs["rnn"][0], inputs["rnn"][1] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) cell_states = cell_states.view(self.num_layers, -1, self.sequence_length, cell_states.shape[-1]) # (D * num_layers, N, L, Hcell) # get the hidden/cell states corresponding to the initial sequence hidden_states = hidden_states[:,:,0,:].contiguous() # (D * num_layers, N, Hout) cell_states = cell_states[:,:,0,:].contiguous() # (D * num_layers, N, Hcell) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, (hidden_states, cell_states) = self.lstm(rnn_input[:,i0:i1,:], (hidden_states, cell_states)) hidden_states[:, (terminated[:,i1-1]), :] = 0 cell_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_states = (hidden_states, cell_states) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, rnn_states = self.lstm(rnn_input, (hidden_states, cell_states)) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, rnn_states = self.lstm(rnn_input, (hidden_states, cell_states)) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) return self.net(rnn_output), {"rnn": [rnn_states[0], rnn_states[1]]} # environment observation wrapper used to mask velocity. Adapted from rl_zoo3 (rl_zoo3/wrappers.py) class NoVelocityWrapper(gym.ObservationWrapper): def observation(self, observation): # observation: x, y, angular velocity return observation * np.array([1, 1, 0]) gym.envs.registration.register(id="PendulumNoVel-v1", entry_point=lambda: NoVelocityWrapper(gym.make("Pendulum-v1"))) # load and wrap the gymnasium environment env = gym.vector.make("PendulumNoVel-v1", num_envs=4, asynchronous=False) env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=1024, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device, clip_actions=True, num_envs=env.num_envs) models["value"] = Value(env.observation_space, env.action_space, device, num_envs=env.num_envs) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 1024 # memory_size cfg["learning_epochs"] = 10 cfg["mini_batches"] = 32 cfg["discount_factor"] = 0.9 cfg["lambda"] = 0.95 cfg["learning_rate"] = 1e-3 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["grad_norm_clip"] = 0.5 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = False cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 0.5 cfg["kl_threshold"] = 0 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 500 cfg["experiment"]["checkpoint_interval"] = 5000 cfg["experiment"]["directory"] = "runs/torch/PendulumNoVel" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 100000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_pendulum_trpo.py
import gymnasium as gym import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.trpo import TRPO, TRPO_DEFAULT_CONFIG from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.net = nn.Sequential(nn.Linear(self.num_observations, 64), nn.ReLU(), nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, self.num_actions)) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def compute(self, inputs, role): # Pendulum-v1 action_space is -2 to 2 return 2 * torch.tanh(self.net(inputs["states"])), self.log_std_parameter, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 64), nn.ReLU(), nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 1)) def compute(self, inputs, role): return self.net(inputs["states"]), {} # load and wrap the gymnasium environment. # note: the environment version may change depending on the gymnasium version try: env = gym.vector.make("Pendulum-v1", num_envs=4, asynchronous=False) except (gym.error.DeprecatedEnv, gym.error.VersionNotFound) as e: env_id = [spec for spec in gym.envs.registry if spec.startswith("Pendulum-v")][0] print("Pendulum-v1 not found. Trying {}".format(env_id)) env = gym.vector.make(env_id, num_envs=4, asynchronous=False) env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=1024, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # TRPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/trpo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device, clip_actions=True) models["value"] = Value(env.observation_space, env.action_space, device) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/trpo.html#configuration-and-hyperparameters cfg = TRPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 1024 # memory_size cfg["learning_epochs"] = 10 cfg["mini_batches"] = 32 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 1e-3 cfg["grad_norm_clip"] = 0.5 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 500 cfg["experiment"]["checkpoint_interval"] = 5000 cfg["experiment"]["directory"] = "runs/torch/Pendulum" agent = TRPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 100000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_pendulumnovel_trpo_rnn.py
import gymnasium as gym import numpy as np import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.trpo import TRPO_DEFAULT_CONFIG from skrl.agents.torch.trpo import TRPO_RNN as TRPO from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", num_envs=1, num_layers=1, hidden_size=64, sequence_length=128): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hout self.sequence_length = sequence_length self.rnn = nn.RNN(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.net = nn.Sequential(nn.Linear(self.hidden_size, 64), nn.ReLU(), nn.Linear(64, self.num_actions)) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size)]}} # hidden states (D ∗ num_layers, N, Hout) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states = inputs["rnn"][0] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) # get the hidden states corresponding to the initial sequence hidden_states = hidden_states[:,:,0,:].contiguous() # (D * num_layers, N, Hout) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, hidden_states = self.rnn(rnn_input[:,i0:i1,:], hidden_states) hidden_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, hidden_states = self.rnn(rnn_input, hidden_states) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, hidden_states = self.rnn(rnn_input, hidden_states) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) # Pendulum-v1 action_space is -2 to 2 return 2 * torch.tanh(self.net(rnn_output)), self.log_std_parameter, {"rnn": [hidden_states]} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, num_envs=1, num_layers=1, hidden_size=64, sequence_length=128): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hout self.sequence_length = sequence_length self.rnn = nn.RNN(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.net = nn.Sequential(nn.Linear(self.hidden_size, 64), nn.ReLU(), nn.Linear(64, 1)) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size)]}} # hidden states (D ∗ num_layers, N, Hout) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states = inputs["rnn"][0] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) # get the hidden states corresponding to the initial sequence hidden_states = hidden_states[:,:,0,:].contiguous() # (D * num_layers, N, Hout) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, hidden_states = self.rnn(rnn_input[:,i0:i1,:], hidden_states) hidden_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, hidden_states = self.rnn(rnn_input, hidden_states) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, hidden_states = self.rnn(rnn_input, hidden_states) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) return self.net(rnn_output), {"rnn": [hidden_states]} # environment observation wrapper used to mask velocity. Adapted from rl_zoo3 (rl_zoo3/wrappers.py) class NoVelocityWrapper(gym.ObservationWrapper): def observation(self, observation): # observation: x, y, angular velocity return observation * np.array([1, 1, 0]) gym.envs.registration.register(id="PendulumNoVel-v1", entry_point=lambda: NoVelocityWrapper(gym.make("Pendulum-v1"))) # load and wrap the gymnasium environment env = gym.vector.make("PendulumNoVel-v1", num_envs=4, asynchronous=False) env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=1024, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # TRPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/trpo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device, clip_actions=True, num_envs=env.num_envs) models["value"] = Value(env.observation_space, env.action_space, device, num_envs=env.num_envs) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/trpo.html#configuration-and-hyperparameters cfg = TRPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 1024 # memory_size cfg["learning_epochs"] = 10 cfg["mini_batches"] = 32 cfg["discount_factor"] = 0.9 cfg["lambda"] = 0.95 cfg["learning_rate"] = 1e-3 cfg["grad_norm_clip"] = 0.5 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 500 cfg["experiment"]["checkpoint_interval"] = 5000 cfg["experiment"]["directory"] = "runs/torch/PendulumNoVel" agent = TRPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 100000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_cartpole_cem.py
import gymnasium as gym import torch.nn as nn import torch.nn.functional as F # import the skrl components to build the RL system from skrl.agents.torch.cem import CEM, CEM_DEFAULT_CONFIG from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import CategoricalMixin, Model from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define model (categorical model) using mixin class Policy(CategoricalMixin, Model): def __init__(self, observation_space, action_space, device, unnormalized_log_prob=True): Model.__init__(self, observation_space, action_space, device) CategoricalMixin.__init__(self, unnormalized_log_prob) self.linear_layer_1 = nn.Linear(self.num_observations, 64) self.linear_layer_2 = nn.Linear(64, 64) self.output_layer = nn.Linear(64, self.num_actions) def compute(self, inputs, role): x = F.relu(self.linear_layer_1(inputs["states"])) x = F.relu(self.linear_layer_2(x)) return self.output_layer(x), {} # load and wrap the gymnasium environment. # note: the environment version may change depending on the gymnasium version try: env = gym.make("CartPole-v1") except (gym.error.DeprecatedEnv, gym.error.VersionNotFound) as e: env_id = [spec for spec in gym.envs.registry if spec.startswith("CartPole-v")][0] print("CartPole-v0 not found. Trying {}".format(env_id)) env = gym.make(env_id) env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=1000, num_envs=env.num_envs, device=device, replacement=False) # instantiate the agent's model (function approximator). # CEM requires 1 model, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/cem.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal_", mean=0.0, std=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/cem.html#configuration-and-hyperparameters cfg = CEM_DEFAULT_CONFIG.copy() cfg["rollouts"] = 1000 cfg["learning_starts"] = 100 # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 1000 cfg["experiment"]["checkpoint_interval"] = 5000 cfg["experiment"]["directory"] = "runs/torch/CartPole" agent = CEM(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 100000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/jax_gymnasium_pendulum_sac.py
import gymnasium as gym import flax.linen as nn import jax import jax.numpy as jnp # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.sac import SAC, SAC_DEFAULT_CONFIG from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, GaussianMixin, Model from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "numpy" # or "jax" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Actor(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-5, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.relu(nn.Dense(400)(inputs["states"])) x = nn.relu(nn.Dense(300)(x)) x = nn.Dense(self.num_actions)(x) log_std = self.param("log_std", lambda _: jnp.zeros(self.num_actions)) # Pendulum-v1 action_space is -2 to 2 return 2 * nn.tanh(x), log_std, {} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = jnp.concatenate([inputs["states"], inputs["taken_actions"]], axis=-1) x = nn.relu(nn.Dense(400)(x)) x = nn.relu(nn.Dense(300)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the gymnasium environment. # note: the environment version may change depending on the gymnasium version try: env = gym.make("Pendulum-v1") except (gym.error.DeprecatedEnv, gym.error.VersionNotFound) as e: env_id = [spec for spec in gym.envs.registry if spec.startswith("Pendulum-v")][0] print("Pendulum-v1 not found. Trying {}".format(env_id)) env = gym.make(env_id) env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=20000, num_envs=env.num_envs, device=device, replacement=False) # instantiate the agent's models (function approximators). # SAC requires 5 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/sac.html#models models = {} models["policy"] = Actor(env.observation_space, env.action_space, device, clip_actions=True) models["critic_1"] = Critic(env.observation_space, env.action_space, device) models["critic_2"] = Critic(env.observation_space, env.action_space, device) models["target_critic_1"] = Critic(env.observation_space, env.action_space, device) models["target_critic_2"] = Critic(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal", stddev=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/sac.html#configuration-and-hyperparameters cfg = SAC_DEFAULT_CONFIG.copy() cfg["discount_factor"] = 0.98 cfg["batch_size"] = 100 cfg["random_timesteps"] = 0 cfg["learning_starts"] = 1000 cfg["learn_entropy"] = True # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 75 cfg["experiment"]["checkpoint_interval"] = 750 cfg["experiment"]["directory"] = "runs/jax/Pendulum" agent = SAC(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 15000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/jax_gymnasium_cartpole_cem.py
import gymnasium as gym import flax.linen as nn import jax import jax.numpy as jnp # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.cem import CEM, CEM_DEFAULT_CONFIG from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import CategoricalMixin, Model from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "numpy" # or "jax" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define model (categorical model) using mixin class Policy(CategoricalMixin, Model): def __init__(self, observation_space, action_space, device=None, unnormalized_log_prob=True, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) CategoricalMixin.__init__(self, unnormalized_log_prob) @nn.compact def __call__(self, inputs, role): x = nn.relu(nn.Dense(64)(inputs["states"])) x = nn.relu(nn.Dense(64)(x)) x = nn.Dense(self.num_actions)(x) return x, {} # load and wrap the gymnasium environment. # note: the environment version may change depending on the gymnasium version try: env = gym.make("CartPole-v1") except (gym.error.DeprecatedEnv, gym.error.VersionNotFound) as e: env_id = [spec for spec in gym.envs.registry if spec.startswith("CartPole-v")][0] print("CartPole-v0 not found. Trying {}".format(env_id)) env = gym.make(env_id) env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=1000, num_envs=env.num_envs, device=device, replacement=False) # instantiate the agent's model (function approximator). # CEM requires 1 model, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/cem.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal", stddev=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/cem.html#configuration-and-hyperparameters cfg = CEM_DEFAULT_CONFIG.copy() cfg["rollouts"] = 1000 cfg["learning_starts"] = 100 # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 1000 cfg["experiment"]["checkpoint_interval"] = 5000 cfg["experiment"]["directory"] = "runs/jax/CartPole" agent = CEM(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 100000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/jax_gymnasium_pendulum_ppo.py
import gymnasium as gym import flax.linen as nn import jax import jax.numpy as jnp # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.resources.schedulers.jax import KLAdaptiveRL from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "numpy" # or "jax" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.relu(nn.Dense(64)(inputs["states"])) x = nn.relu(nn.Dense(64)(x)) x = nn.Dense(self.num_actions)(x) log_std = self.param("log_std", lambda _: jnp.zeros(self.num_actions)) # Pendulum-v1 action_space is -2 to 2 return 2 * nn.tanh(x), log_std, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.relu(nn.Dense(64)(inputs["states"])) x = nn.relu(nn.Dense(64)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the gymnasium environment. # note: the environment version may change depending on the gymnasium version try: env = gym.vector.make("Pendulum-v1", num_envs=4, asynchronous=False) except (gym.error.DeprecatedEnv, gym.error.VersionNotFound) as e: env_id = [spec for spec in gym.envs.registry if spec.startswith("Pendulum-v")][0] print("Pendulum-v1 not found. Trying {}".format(env_id)) env = gym.vector.make(env_id, num_envs=4, asynchronous=False) env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=1024, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device, clip_actions=True) models["value"] = Value(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 1024 # memory_size cfg["learning_epochs"] = 10 cfg["mini_batches"] = 32 cfg["discount_factor"] = 0.9 cfg["lambda"] = 0.95 cfg["learning_rate"] = 1e-3 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["grad_norm_clip"] = 0.5 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = False cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 0.5 cfg["kl_threshold"] = 0 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 500 cfg["experiment"]["checkpoint_interval"] = 5000 cfg["experiment"]["directory"] = "runs/jax/Pendulum" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 100000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_cartpole_dqn.py
import gymnasium as gym # import the skrl components to build the RL system from skrl.agents.torch.dqn import DQN, DQN_DEFAULT_CONFIG from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed from skrl.utils.model_instantiators.torch import Shape, deterministic_model # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # load and wrap the gymnasium environment. # note: the environment version may change depending on the gymnasium version try: env = gym.make("CartPole-v1") except (gym.error.DeprecatedEnv, gym.error.VersionNotFound) as e: env_id = [spec for spec in gym.envs.registry if spec.startswith("CartPole-v")][0] print("CartPole-v0 not found. Trying {}".format(env_id)) env = gym.make(env_id) env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=50000, num_envs=env.num_envs, device=device, replacement=False) # instantiate the agent's models (function approximators) using the model instantiator utility. # DQN requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/dqn.html#models models = {} models["q_network"] = deterministic_model(observation_space=env.observation_space, action_space=env.action_space, device=device, clip_actions=False, input_shape=Shape.OBSERVATIONS, hiddens=[64, 64], hidden_activation=["relu", "relu"], output_shape=Shape.ACTIONS, output_activation=None, output_scale=1.0) models["target_q_network"] = deterministic_model(observation_space=env.observation_space, action_space=env.action_space, device=device, clip_actions=False, input_shape=Shape.OBSERVATIONS, hiddens=[64, 64], hidden_activation=["relu", "relu"], output_shape=Shape.ACTIONS, output_activation=None, output_scale=1.0) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal_", mean=0.0, std=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/dqn.html#configuration-and-hyperparameters cfg = DQN_DEFAULT_CONFIG.copy() cfg["learning_starts"] = 100 cfg["exploration"]["final_epsilon"] = 0.04 cfg["exploration"]["timesteps"] = 1500 # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 1000 cfg["experiment"]["checkpoint_interval"] = 5000 cfg["experiment"]["directory"] = "runs/torch/CartPole" agent = DQN(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 50000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_pendulumnovel_ppo_rnn.py
import gymnasium as gym import numpy as np import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO_DEFAULT_CONFIG from skrl.agents.torch.ppo import PPO_RNN as PPO from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.resources.schedulers.torch import KLAdaptiveRL from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", num_envs=1, num_layers=1, hidden_size=64, sequence_length=128): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hout self.sequence_length = sequence_length self.rnn = nn.RNN(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.net = nn.Sequential(nn.Linear(self.hidden_size, 64), nn.ReLU(), nn.Linear(64, self.num_actions)) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size)]}} # hidden states (D ∗ num_layers, N, Hout) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states = inputs["rnn"][0] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) # get the hidden states corresponding to the initial sequence hidden_states = hidden_states[:,:,0,:].contiguous() # (D * num_layers, N, Hout) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, hidden_states = self.rnn(rnn_input[:,i0:i1,:], hidden_states) hidden_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, hidden_states = self.rnn(rnn_input, hidden_states) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, hidden_states = self.rnn(rnn_input, hidden_states) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) # Pendulum-v1 action_space is -2 to 2 return 2 * torch.tanh(self.net(rnn_output)), self.log_std_parameter, {"rnn": [hidden_states]} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, num_envs=1, num_layers=1, hidden_size=64, sequence_length=128): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hout self.sequence_length = sequence_length self.rnn = nn.RNN(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.net = nn.Sequential(nn.Linear(self.hidden_size, 64), nn.ReLU(), nn.Linear(64, 1)) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size)]}} # hidden states (D ∗ num_layers, N, Hout) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states = inputs["rnn"][0] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) # get the hidden states corresponding to the initial sequence hidden_states = hidden_states[:,:,0,:].contiguous() # (D * num_layers, N, Hout) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, hidden_states = self.rnn(rnn_input[:,i0:i1,:], hidden_states) hidden_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, hidden_states = self.rnn(rnn_input, hidden_states) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, hidden_states = self.rnn(rnn_input, hidden_states) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) return self.net(rnn_output), {"rnn": [hidden_states]} # environment observation wrapper used to mask velocity. Adapted from rl_zoo3 (rl_zoo3/wrappers.py) class NoVelocityWrapper(gym.ObservationWrapper): def observation(self, observation): # observation: x, y, angular velocity return observation * np.array([1, 1, 0]) gym.envs.registration.register(id="PendulumNoVel-v1", entry_point=lambda: NoVelocityWrapper(gym.make("Pendulum-v1"))) # load and wrap the gymnasium environment env = gym.vector.make("PendulumNoVel-v1", num_envs=4, asynchronous=False) env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=1024, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device, clip_actions=True, num_envs=env.num_envs) models["value"] = Value(env.observation_space, env.action_space, device, num_envs=env.num_envs) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 1024 # memory_size cfg["learning_epochs"] = 10 cfg["mini_batches"] = 32 cfg["discount_factor"] = 0.9 cfg["lambda"] = 0.95 cfg["learning_rate"] = 1e-3 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["grad_norm_clip"] = 0.5 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = False cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 0.5 cfg["kl_threshold"] = 0 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 500 cfg["experiment"]["checkpoint_interval"] = 5000 cfg["experiment"]["directory"] = "runs/torch/PendulumNoVel" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 100000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_pendulumnovel_sac.py
import gymnasium as gym import numpy as np import torch import torch.nn as nn import torch.nn.functional as F # import the skrl components to build the RL system from skrl.agents.torch.sac import SAC, SAC_DEFAULT_CONFIG from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Actor(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.linear_layer_1 = nn.Linear(self.num_observations, 400) self.linear_layer_2 = nn.Linear(400, 300) self.action_layer = nn.Linear(300, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def compute(self, inputs, role): x = F.relu(self.linear_layer_1(inputs["states"])) x = F.relu(self.linear_layer_2(x)) # Pendulum-v1 action_space is -2 to 2 return 2 * torch.tanh(self.action_layer(x)), self.log_std_parameter, {} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.linear_layer_1 = nn.Linear(self.num_observations + self.num_actions, 400) self.linear_layer_2 = nn.Linear(400, 300) self.linear_layer_3 = nn.Linear(300, 1) def compute(self, inputs, role): x = F.relu(self.linear_layer_1(torch.cat([inputs["states"], inputs["taken_actions"]], dim=1))) x = F.relu(self.linear_layer_2(x)) return self.linear_layer_3(x), {} # environment observation wrapper used to mask velocity. Adapted from rl_zoo3 (rl_zoo3/wrappers.py) class NoVelocityWrapper(gym.ObservationWrapper): def observation(self, observation): # observation: x, y, angular velocity return observation * np.array([1, 1, 0]) gym.envs.registration.register(id="PendulumNoVel-v1", entry_point=lambda: NoVelocityWrapper(gym.make("Pendulum-v1"))) # load and wrap the gymnasium environment env = gym.make("PendulumNoVel-v1") env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=20000, num_envs=env.num_envs, device=device, replacement=False) # instantiate the agent's models (function approximators). # SAC requires 5 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/sac.html#models models = {} models["policy"] = Actor(env.observation_space, env.action_space, device, clip_actions=True) models["critic_1"] = Critic(env.observation_space, env.action_space, device) models["critic_2"] = Critic(env.observation_space, env.action_space, device) models["target_critic_1"] = Critic(env.observation_space, env.action_space, device) models["target_critic_2"] = Critic(env.observation_space, env.action_space, device) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal_", mean=0.0, std=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/sac.html#configuration-and-hyperparameters cfg = SAC_DEFAULT_CONFIG.copy() cfg["discount_factor"] = 0.98 cfg["batch_size"] = 100 cfg["random_timesteps"] = 0 cfg["learning_starts"] = 1000 cfg["learn_entropy"] = True # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 75 cfg["experiment"]["checkpoint_interval"] = 750 cfg["experiment"]["directory"] = "runs/torch/PendulumNoVel" agent = SAC(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 15000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_pendulumnovel_ddpg_lstm.py
import gymnasium as gym import numpy as np import torch import torch.nn as nn import torch.nn.functional as F # import the skrl components to build the RL system from skrl.agents.torch.ddpg import DDPG_DEFAULT_CONFIG from skrl.agents.torch.ddpg import DDPG_RNN as DDPG from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, Model from skrl.resources.noises.torch import OrnsteinUhlenbeckNoise from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (deterministic models) using mixin class Actor(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, num_envs=1, num_layers=1, hidden_size=400, sequence_length=20): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hcell (Hout is Hcell because proj_size = 0) self.sequence_length = sequence_length self.lstm = nn.LSTM(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.linear_layer_1 = nn.Linear(self.hidden_size, 400) self.linear_layer_2 = nn.Linear(400, 300) self.action_layer = nn.Linear(300, self.num_actions) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size), # hidden states (D ∗ num_layers, N, Hout) (self.num_layers, self.num_envs, self.hidden_size)]}} # cell states (D ∗ num_layers, N, Hcell) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states, cell_states = inputs["rnn"][0], inputs["rnn"][1] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) cell_states = cell_states.view(self.num_layers, -1, self.sequence_length, cell_states.shape[-1]) # (D * num_layers, N, L, Hcell) # get the hidden/cell states corresponding to the initial sequence sequence_index = 1 if role == "target_policy" else 0 # target networks act on the next state of the environment hidden_states = hidden_states[:,:,sequence_index,:].contiguous() # (D * num_layers, N, Hout) cell_states = cell_states[:,:,sequence_index,:].contiguous() # (D * num_layers, N, Hcell) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, (hidden_states, cell_states) = self.lstm(rnn_input[:,i0:i1,:], (hidden_states, cell_states)) hidden_states[:, (terminated[:,i1-1]), :] = 0 cell_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_states = (hidden_states, cell_states) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, rnn_states = self.lstm(rnn_input, (hidden_states, cell_states)) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, rnn_states = self.lstm(rnn_input, (hidden_states, cell_states)) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) x = F.relu(self.linear_layer_1(rnn_output)) x = F.relu(self.linear_layer_2(x)) # Pendulum-v1 action_space is -2 to 2 return 2 * torch.tanh(self.action_layer(x)), {"rnn": [rnn_states[0], rnn_states[1]]} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, num_envs=1, num_layers=1, hidden_size=400, sequence_length=20): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hcell (Hout is Hcell because proj_size = 0) self.sequence_length = sequence_length self.lstm = nn.LSTM(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.linear_layer_1 = nn.Linear(self.hidden_size + self.num_actions, 400) self.linear_layer_2 = nn.Linear(400, 300) self.linear_layer_3 = nn.Linear(300, 1) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size), # hidden states (D ∗ num_layers, N, Hout) (self.num_layers, self.num_envs, self.hidden_size)]}} # cell states (D ∗ num_layers, N, Hcell) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states, cell_states = inputs["rnn"][0], inputs["rnn"][1] # critic is only used during training rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) cell_states = cell_states.view(self.num_layers, -1, self.sequence_length, cell_states.shape[-1]) # (D * num_layers, N, L, Hcell) # get the hidden/cell states corresponding to the initial sequence sequence_index = 1 if role == "target_critic" else 0 # target networks act on the next state of the environment hidden_states = hidden_states[:,:,sequence_index,:].contiguous() # (D * num_layers, N, Hout) cell_states = cell_states[:,:,sequence_index,:].contiguous() # (D * num_layers, N, Hcell) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, (hidden_states, cell_states) = self.lstm(rnn_input[:,i0:i1,:], (hidden_states, cell_states)) hidden_states[:, (terminated[:,i1-1]), :] = 0 cell_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_states = (hidden_states, cell_states) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, rnn_states = self.lstm(rnn_input, (hidden_states, cell_states)) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) x = F.relu(self.linear_layer_1(torch.cat([rnn_output, inputs["taken_actions"]], dim=1))) x = F.relu(self.linear_layer_2(x)) return self.linear_layer_3(x), {"rnn": [rnn_states[0], rnn_states[1]]} # environment observation wrapper used to mask velocity. Adapted from rl_zoo3 (rl_zoo3/wrappers.py) class NoVelocityWrapper(gym.ObservationWrapper): def observation(self, observation): # observation: x, y, angular velocity return observation * np.array([1, 1, 0]) gym.envs.registration.register(id="PendulumNoVel-v1", entry_point=lambda: NoVelocityWrapper(gym.make("Pendulum-v1"))) # load and wrap the gymnasium environment env = gym.make("PendulumNoVel-v1") env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=20000, num_envs=env.num_envs, device=device, replacement=False) # instantiate the agent's models (function approximators). # DDPG requires 4 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#models models = {} models["policy"] = Actor(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["target_policy"] = Actor(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["critic"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["target_critic"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal_", mean=0.0, std=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#configuration-and-hyperparameters cfg = DDPG_DEFAULT_CONFIG.copy() cfg["exploration"]["noise"] = OrnsteinUhlenbeckNoise(theta=0.15, sigma=0.1, base_scale=1.0, device=device) cfg["discount_factor"] = 0.98 cfg["batch_size"] = 100 cfg["random_timesteps"] = 0 cfg["learning_starts"] = 1000 # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 75 cfg["experiment"]["checkpoint_interval"] = 750 cfg["experiment"]["directory"] = "runs/torch/PendulumNoVel" agent = DDPG(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 15000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_frozen_lake_q_learning.py
import gymnasium as gym import torch # import the skrl components to build the RL system from skrl.agents.torch.q_learning import Q_LEARNING, Q_LEARNING_DEFAULT_CONFIG from skrl.envs.wrappers.torch import wrap_env from skrl.models.torch import Model, TabularMixin from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define model (tabular model) using mixin class EpilonGreedyPolicy(TabularMixin, Model): def __init__(self, observation_space, action_space, device, num_envs=1, epsilon=0.1): Model.__init__(self, observation_space, action_space, device) TabularMixin.__init__(self, num_envs) self.epsilon = epsilon self.q_table = torch.ones((num_envs, self.num_observations, self.num_actions), dtype=torch.float32, device=self.device) def compute(self, inputs, role): actions = torch.argmax(self.q_table[torch.arange(self.num_envs).view(-1, 1), inputs["states"]], dim=-1, keepdim=True).view(-1,1) # choose random actions for exploration according to epsilon indexes = (torch.rand(inputs["states"].shape[0], device=self.device) < self.epsilon).nonzero().view(-1) if indexes.numel(): actions[indexes] = torch.randint(self.num_actions, (indexes.numel(), 1), device=self.device) return actions, {} # load and wrap the gymnasium environment. # note: the environment version may change depending on the gymnasium version try: env = gym.make("FrozenLake-v0") except (gym.error.DeprecatedEnv, gym.error.VersionNotFound) as e: env_id = [spec for spec in gym.envs.registry if spec.startswith("FrozenLake-v")][0] print("FrozenLake-v0 not found. Trying {}".format(env_id)) env = gym.make(env_id) env = wrap_env(env) device = env.device # instantiate the agent's model (table) # Q-learning requires 1 model, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/q_learning.html#models models = {} models["policy"] = EpilonGreedyPolicy(env.observation_space, env.action_space, device, num_envs=env.num_envs, epsilon=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/q_learning.html#configuration-and-hyperparameters cfg = Q_LEARNING_DEFAULT_CONFIG.copy() cfg["discount_factor"] = 0.999 cfg["alpha"] = 0.4 # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 1600 cfg["experiment"]["checkpoint_interval"] = 8000 cfg["experiment"]["directory"] = "runs/torch/FrozenLake" agent = Q_LEARNING(models=models, memory=None, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 80000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_pendulumnovel_trpo.py
import gymnasium as gym import numpy as np import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.trpo import TRPO, TRPO_DEFAULT_CONFIG from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.net = nn.Sequential(nn.Linear(self.num_observations, 64), nn.ReLU(), nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, self.num_actions)) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def compute(self, inputs, role): # Pendulum-v1 action_space is -2 to 2 return 2 * torch.tanh(self.net(inputs["states"])), self.log_std_parameter, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 64), nn.ReLU(), nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 1)) def compute(self, inputs, role): return self.net(inputs["states"]), {} # environment observation wrapper used to mask velocity. Adapted from rl_zoo3 (rl_zoo3/wrappers.py) class NoVelocityWrapper(gym.ObservationWrapper): def observation(self, observation): # observation: x, y, angular velocity return observation * np.array([1, 1, 0]) gym.envs.registration.register(id="PendulumNoVel-v1", entry_point=lambda: NoVelocityWrapper(gym.make("Pendulum-v1"))) # load and wrap the gymnasium environment env = gym.vector.make("PendulumNoVel-v1", num_envs=4, asynchronous=False) env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=1024, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # TRPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/trpo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device, clip_actions=True) models["value"] = Value(env.observation_space, env.action_space, device) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/trpo.html#configuration-and-hyperparameters cfg = TRPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 1024 # memory_size cfg["learning_epochs"] = 10 cfg["mini_batches"] = 32 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 1e-3 cfg["grad_norm_clip"] = 0.5 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 500 cfg["experiment"]["checkpoint_interval"] = 5000 cfg["experiment"]["directory"] = "runs/torch/PendulumNoVel" agent = TRPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 100000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_pendulumnovel_sac_rnn.py
import gymnasium as gym import numpy as np import torch import torch.nn as nn import torch.nn.functional as F # import the skrl components to build the RL system from skrl.agents.torch.sac import SAC_DEFAULT_CONFIG from skrl.agents.torch.sac import SAC_RNN as SAC from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Actor(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", num_envs=1, num_layers=1, hidden_size=400, sequence_length=20): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hout self.sequence_length = sequence_length self.rnn = nn.RNN(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.linear_layer_1 = nn.Linear(self.hidden_size, 400) self.linear_layer_2 = nn.Linear(400, 300) self.action_layer = nn.Linear(300, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size)]}} # hidden states (D ∗ num_layers, N, Hout) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states = inputs["rnn"][0] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) # get the hidden states corresponding to the initial sequence hidden_states = hidden_states[:,:,0,:].contiguous() # (D * num_layers, N, Hout) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, hidden_states = self.rnn(rnn_input[:,i0:i1,:], hidden_states) hidden_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, hidden_states = self.rnn(rnn_input, hidden_states) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, hidden_states = self.rnn(rnn_input, hidden_states) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) x = F.relu(self.linear_layer_1(rnn_output)) x = F.relu(self.linear_layer_2(x)) # Pendulum-v1 action_space is -2 to 2 return 2 * torch.tanh(self.action_layer(x)), self.log_std_parameter, {"rnn": [hidden_states]} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, num_envs=1, num_layers=1, hidden_size=400, sequence_length=20): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hout self.sequence_length = sequence_length self.rnn = nn.RNN(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.linear_layer_1 = nn.Linear(self.hidden_size + self.num_actions, 400) self.linear_layer_2 = nn.Linear(400, 300) self.linear_layer_3 = nn.Linear(300, 1) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size)]}} # hidden states (D ∗ num_layers, N, Hout) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states = inputs["rnn"][0] # critic is only used during training rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) # get the hidden states corresponding to the initial sequence sequence_index = 1 if role in ["target_critic_1", "target_critic_2"] else 0 # target networks act on the next state of the environment hidden_states = hidden_states[:,:,sequence_index,:].contiguous() # (D * num_layers, N, Hout) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, hidden_states = self.rnn(rnn_input[:,i0:i1,:], hidden_states) hidden_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, hidden_states = self.rnn(rnn_input, hidden_states) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) x = F.relu(self.linear_layer_1(torch.cat([rnn_output, inputs["taken_actions"]], dim=1))) x = F.relu(self.linear_layer_2(x)) return self.linear_layer_3(x), {"rnn": [hidden_states]} # environment observation wrapper used to mask velocity. Adapted from rl_zoo3 (rl_zoo3/wrappers.py) class NoVelocityWrapper(gym.ObservationWrapper): def observation(self, observation): # observation: x, y, angular velocity return observation * np.array([1, 1, 0]) gym.envs.registration.register(id="PendulumNoVel-v1", entry_point=lambda: NoVelocityWrapper(gym.make("Pendulum-v1"))) # load and wrap the gymnasium environment env = gym.make("PendulumNoVel-v1") env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=20000, num_envs=env.num_envs, device=device, replacement=False) # instantiate the agent's models (function approximators). # SAC requires 5 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/sac.html#models models = {} models["policy"] = Actor(env.observation_space, env.action_space, device, clip_actions=True, num_envs=env.num_envs) models["critic_1"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["critic_2"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["target_critic_1"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["target_critic_2"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal_", mean=0.0, std=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/sac.html#configuration-and-hyperparameters cfg = SAC_DEFAULT_CONFIG.copy() cfg["discount_factor"] = 0.98 cfg["batch_size"] = 100 cfg["random_timesteps"] = 0 cfg["learning_starts"] = 1000 cfg["learn_entropy"] = True # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 75 cfg["experiment"]["checkpoint_interval"] = 750 cfg["experiment"]["directory"] = "runs/torch/PendulumNoVel" agent = SAC(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 15000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/jax_gymnasium_cartpole_dqn.py
import gymnasium as gym # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.dqn import DQN, DQN_DEFAULT_CONFIG from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed from skrl.utils.model_instantiators.jax import Shape, deterministic_model config.jax.backend = "numpy" # or "jax" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # load and wrap the gymnasium environment. # note: the environment version may change depending on the gymnasium version try: env = gym.make("CartPole-v1") except (gym.error.DeprecatedEnv, gym.error.VersionNotFound) as e: env_id = [spec for spec in gym.envs.registry if spec.startswith("CartPole-v")][0] print("CartPole-v0 not found. Trying {}".format(env_id)) env = gym.make(env_id) env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=50000, num_envs=env.num_envs, device=device, replacement=False) # instantiate the agent's models (function approximators) using the model instantiator utility. # DQN requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/dqn.html#models models = {} models["q_network"] = deterministic_model(observation_space=env.observation_space, action_space=env.action_space, device=device, clip_actions=False, input_shape=Shape.OBSERVATIONS, hiddens=[64, 64], hidden_activation=["relu", "relu"], output_shape=Shape.ACTIONS, output_activation=None, output_scale=1.0) models["target_q_network"] = deterministic_model(observation_space=env.observation_space, action_space=env.action_space, device=device, clip_actions=False, input_shape=Shape.OBSERVATIONS, hiddens=[64, 64], hidden_activation=["relu", "relu"], output_shape=Shape.ACTIONS, output_activation=None, output_scale=1.0) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal", stddev=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/dqn.html#configuration-and-hyperparameters cfg = DQN_DEFAULT_CONFIG.copy() cfg["learning_starts"] = 100 cfg["exploration"]["final_epsilon"] = 0.04 cfg["exploration"]["timesteps"] = 1500 # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 1000 cfg["experiment"]["checkpoint_interval"] = 5000 cfg["experiment"]["directory"] = "runs/jax/CartPole" agent = DQN(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 50000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_pendulumnovel_ppo.py
import gymnasium as gym import numpy as np import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.resources.schedulers.torch import KLAdaptiveRL from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.net = nn.Sequential(nn.Linear(self.num_observations, 64), nn.ReLU(), nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, self.num_actions)) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def compute(self, inputs, role): # Pendulum-v1 action_space is -2 to 2 return 2 * torch.tanh(self.net(inputs["states"])), self.log_std_parameter, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 64), nn.ReLU(), nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 1)) def compute(self, inputs, role): return self.net(inputs["states"]), {} # environment observation wrapper used to mask velocity. Adapted from rl_zoo3 (rl_zoo3/wrappers.py) class NoVelocityWrapper(gym.ObservationWrapper): def observation(self, observation): # observation: x, y, angular velocity return observation * np.array([1, 1, 0]) gym.envs.registration.register(id="PendulumNoVel-v1", entry_point=lambda: NoVelocityWrapper(gym.make("Pendulum-v1"))) # load and wrap the gymnasium environment env = gym.vector.make("PendulumNoVel-v1", num_envs=4, asynchronous=False) env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=1024, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device, clip_actions=True) models["value"] = Value(env.observation_space, env.action_space, device) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 1024 # memory_size cfg["learning_epochs"] = 10 cfg["mini_batches"] = 32 cfg["discount_factor"] = 0.9 cfg["lambda"] = 0.95 cfg["learning_rate"] = 1e-3 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["grad_norm_clip"] = 0.5 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = False cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 0.5 cfg["kl_threshold"] = 0 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 500 cfg["experiment"]["checkpoint_interval"] = 5000 cfg["experiment"]["directory"] = "runs/torch/PendulumNoVel" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 100000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/jax_gymnasium_pendulum_td3.py
import gymnasium as gym import flax.linen as nn import jax import jax.numpy as jnp # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.td3 import TD3, TD3_DEFAULT_CONFIG from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, Model from skrl.resources.noises.jax import GaussianNoise from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "numpy" # or "jax" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (deterministic models) using mixin class Actor(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) @nn.compact def __call__(self, inputs, role): x = nn.relu(nn.Dense(400)(inputs["states"])) x = nn.relu(nn.Dense(300)(x)) x = nn.Dense(self.num_actions)(x) # Pendulum-v1 action_space is -2 to 2 return 2 * nn.tanh(x), {} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = jnp.concatenate([inputs["states"], inputs["taken_actions"]], axis=-1) x = nn.relu(nn.Dense(400)(x)) x = nn.relu(nn.Dense(300)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the gymnasium environment. # note: the environment version may change depending on the gymnasium version try: env = gym.make("Pendulum-v1") except (gym.error.DeprecatedEnv, gym.error.VersionNotFound) as e: env_id = [spec for spec in gym.envs.registry if spec.startswith("Pendulum-v")][0] print("Pendulum-v1 not found. Trying {}".format(env_id)) env = gym.make(env_id) env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=20000, num_envs=env.num_envs, device=device, replacement=False) # instantiate the agent's models (function approximators). # TD3 requires 6 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/td3.html#models models = {} models["policy"] = Actor(env.observation_space, env.action_space, device) models["target_policy"] = Actor(env.observation_space, env.action_space, device) models["critic_1"] = Critic(env.observation_space, env.action_space, device) models["critic_2"] = Critic(env.observation_space, env.action_space, device) models["target_critic_1"] = Critic(env.observation_space, env.action_space, device) models["target_critic_2"] = Critic(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal", stddev=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/td3.html#configuration-and-hyperparameters cfg = TD3_DEFAULT_CONFIG.copy() cfg["exploration"]["noise"] = GaussianNoise(0, 0.1, device=device) cfg["smooth_regularization_noise"] = GaussianNoise(0, 0.2, device=device) cfg["smooth_regularization_clip"] = 0.5 cfg["discount_factor"] = 0.98 cfg["batch_size"] = 100 cfg["random_timesteps"] = 1000 cfg["learning_starts"] = 1000 # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 75 cfg["experiment"]["checkpoint_interval"] = 750 cfg["experiment"]["directory"] = "runs/jax/Pendulum" agent = TD3(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 15000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_pendulumnovel_ddpg.py
import gymnasium as gym import numpy as np import torch import torch.nn as nn import torch.nn.functional as F # import the skrl components to build the RL system from skrl.agents.torch.ddpg import DDPG, DDPG_DEFAULT_CONFIG from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, Model from skrl.resources.noises.torch import OrnsteinUhlenbeckNoise from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (deterministic models) using mixin class Actor(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.linear_layer_1 = nn.Linear(self.num_observations, 400) self.linear_layer_2 = nn.Linear(400, 300) self.action_layer = nn.Linear(300, self.num_actions) def compute(self, inputs, role): x = F.relu(self.linear_layer_1(inputs["states"])) x = F.relu(self.linear_layer_2(x)) # Pendulum-v1 action_space is -2 to 2 return 2 * torch.tanh(self.action_layer(x)), {} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.linear_layer_1 = nn.Linear(self.num_observations + self.num_actions, 400) self.linear_layer_2 = nn.Linear(400, 300) self.linear_layer_3 = nn.Linear(300, 1) def compute(self, inputs, role): x = F.relu(self.linear_layer_1(torch.cat([inputs["states"], inputs["taken_actions"]], dim=1))) x = F.relu(self.linear_layer_2(x)) return self.linear_layer_3(x), {} # environment observation wrapper used to mask velocity. Adapted from rl_zoo3 (rl_zoo3/wrappers.py) class NoVelocityWrapper(gym.ObservationWrapper): def observation(self, observation): # observation: x, y, angular velocity return observation * np.array([1, 1, 0]) gym.envs.registration.register(id="PendulumNoVel-v1", entry_point=lambda: NoVelocityWrapper(gym.make("Pendulum-v1"))) # load and wrap the gymnasium environment env = gym.make("PendulumNoVel-v1") env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=20000, num_envs=env.num_envs, device=device, replacement=False) # instantiate the agent's models (function approximators). # DDPG requires 4 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#models models = {} models["policy"] = Actor(env.observation_space, env.action_space, device) models["target_policy"] = Actor(env.observation_space, env.action_space, device) models["critic"] = Critic(env.observation_space, env.action_space, device) models["target_critic"] = Critic(env.observation_space, env.action_space, device) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal_", mean=0.0, std=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#configuration-and-hyperparameters cfg = DDPG_DEFAULT_CONFIG.copy() cfg["exploration"]["noise"] = OrnsteinUhlenbeckNoise(theta=0.15, sigma=0.1, base_scale=1.0, device=device) cfg["discount_factor"] = 0.98 cfg["batch_size"] = 100 cfg["random_timesteps"] = 1000 cfg["learning_starts"] = 1000 # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 75 cfg["experiment"]["checkpoint_interval"] = 750 cfg["experiment"]["directory"] = "runs/torch/PendulumNoVel" agent = DDPG(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 15000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_frozen_lake_vector_q_learning.py
import gymnasium as gym import torch # import the skrl components to build the RL system from skrl.agents.torch.q_learning import Q_LEARNING, Q_LEARNING_DEFAULT_CONFIG from skrl.envs.wrappers.torch import wrap_env from skrl.models.torch import Model, TabularMixin from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define model (tabular model) using mixin class EpilonGreedyPolicy(TabularMixin, Model): def __init__(self, observation_space, action_space, device, num_envs=1, epsilon=0.1): Model.__init__(self, observation_space, action_space, device) TabularMixin.__init__(self, num_envs) self.epsilon = epsilon self.q_table = torch.ones((num_envs, self.num_observations, self.num_actions), dtype=torch.float32, device=self.device) def compute(self, inputs, role): actions = torch.argmax(self.q_table[torch.arange(self.num_envs).view(-1, 1), inputs["states"]], dim=-1, keepdim=True).view(-1,1) # choose random actions for exploration according to epsilon indexes = (torch.rand(inputs["states"].shape[0], device=self.device) < self.epsilon).nonzero().view(-1) if indexes.numel(): actions[indexes] = torch.randint(self.num_actions, (indexes.numel(), 1), device=self.device) return actions, {} # load and wrap the gymnasium environment. # note: the environment version may change depending on the gymnasium version try: env = gym.vector.make("FrozenLake-v0", num_envs=10, asynchronous=False) except (gym.error.DeprecatedEnv, gym.error.VersionNotFound) as e: env_id = [spec for spec in gym.envs.registry if spec.startswith("FrozenLake-v")][0] print("FrozenLake-v0 not found. Trying {}".format(env_id)) env = gym.vector.make(env_id, num_envs=10, asynchronous=False) env = wrap_env(env) device = env.device # instantiate the agent's model (table) # Q-learning requires 1 model, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/q_learning.html#models models = {} models["policy"] = EpilonGreedyPolicy(env.observation_space, env.action_space, device, num_envs=env.num_envs, epsilon=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/q_learning.html#configuration-and-hyperparameters cfg = Q_LEARNING_DEFAULT_CONFIG.copy() cfg["discount_factor"] = 0.999 cfg["alpha"] = 0.4 # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 1600 cfg["experiment"]["checkpoint_interval"] = 8000 cfg["experiment"]["directory"] = "runs/torch/FrozenLake" agent = Q_LEARNING(models=models, memory=None, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 80000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/jax_gymnasium_cartpole_vector_dqn.py
import gymnasium as gym # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.dqn import DQN, DQN_DEFAULT_CONFIG from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed from skrl.utils.model_instantiators.jax import Shape, deterministic_model config.jax.backend = "numpy" # or "jax" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # load and wrap the gymnasium environment. # note: the environment version may change depending on the gymnasium version try: env = gym.vector.make("CartPole-v1", num_envs=5, asynchronous=False) except (gym.error.DeprecatedEnv, gym.error.VersionNotFound) as e: env_id = [spec for spec in gym.envs.registry if spec.startswith("CartPole-v")][0] print("CartPole-v0 not found. Trying {}".format(env_id)) env = gym.vector.make(env_id, num_envs=5, asynchronous=False) env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=200000, num_envs=env.num_envs, device=device, replacement=False) # instantiate the agent's models (function approximators) using the model instantiator utility. # DQN requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/dqn.html#models models = {} models["q_network"] = deterministic_model(observation_space=env.observation_space, action_space=env.action_space, device=device, clip_actions=False, input_shape=Shape.OBSERVATIONS, hiddens=[64, 64], hidden_activation=["relu", "relu"], output_shape=Shape.ACTIONS, output_activation=None, output_scale=1.0) models["target_q_network"] = deterministic_model(observation_space=env.observation_space, action_space=env.action_space, device=device, clip_actions=False, input_shape=Shape.OBSERVATIONS, hiddens=[64, 64], hidden_activation=["relu", "relu"], output_shape=Shape.ACTIONS, output_activation=None, output_scale=1.0) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal", stddev=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/dqn.html#configuration-and-hyperparameters cfg = DQN_DEFAULT_CONFIG.copy() cfg["learning_starts"] = 100 cfg["exploration"]["final_epsilon"] = 0.04 cfg["exploration"]["timesteps"] = 1500 # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 1000 cfg["experiment"]["checkpoint_interval"] = 5000 cfg["experiment"]["directory"] = "runs/jax/CartPole" agent = DQN(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 50000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_pendulumnovel_td3.py
import gymnasium as gym import numpy as np import torch import torch.nn as nn import torch.nn.functional as F # import the skrl components to build the RL system from skrl.agents.torch.td3 import TD3, TD3_DEFAULT_CONFIG from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, Model from skrl.resources.noises.torch import GaussianNoise from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (deterministic models) using mixin class Actor(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.linear_layer_1 = nn.Linear(self.num_observations, 400) self.linear_layer_2 = nn.Linear(400, 300) self.action_layer = nn.Linear(300, self.num_actions) def compute(self, inputs, role): x = F.relu(self.linear_layer_1(inputs["states"])) x = F.relu(self.linear_layer_2(x)) # Pendulum-v1 action_space is -2 to 2 return 2 * torch.tanh(self.action_layer(x)), {} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.linear_layer_1 = nn.Linear(self.num_observations + self.num_actions, 400) self.linear_layer_2 = nn.Linear(400, 300) self.linear_layer_3 = nn.Linear(300, 1) def compute(self, inputs, role): x = F.relu(self.linear_layer_1(torch.cat([inputs["states"], inputs["taken_actions"]], dim=1))) x = F.relu(self.linear_layer_2(x)) return self.linear_layer_3(x), {} # environment observation wrapper used to mask velocity. Adapted from rl_zoo3 (rl_zoo3/wrappers.py) class NoVelocityWrapper(gym.ObservationWrapper): def observation(self, observation): # observation: x, y, angular velocity return observation * np.array([1, 1, 0]) gym.envs.registration.register(id="PendulumNoVel-v1", entry_point=lambda: NoVelocityWrapper(gym.make("Pendulum-v1"))) # load and wrap the gymnasium environment env = gym.make("PendulumNoVel-v1") env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=20000, num_envs=env.num_envs, device=device, replacement=False) # instantiate the agent's models (function approximators). # TD3 requires 6 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/td3.html#models models = {} models["policy"] = Actor(env.observation_space, env.action_space, device) models["target_policy"] = Actor(env.observation_space, env.action_space, device) models["critic_1"] = Critic(env.observation_space, env.action_space, device) models["critic_2"] = Critic(env.observation_space, env.action_space, device) models["target_critic_1"] = Critic(env.observation_space, env.action_space, device) models["target_critic_2"] = Critic(env.observation_space, env.action_space, device) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal_", mean=0.0, std=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/td3.html#configuration-and-hyperparameters cfg = TD3_DEFAULT_CONFIG.copy() cfg["exploration"]["noise"] = GaussianNoise(0, 0.1, device=device) cfg["smooth_regularization_noise"] = GaussianNoise(0, 0.2, device=device) cfg["smooth_regularization_clip"] = 0.5 cfg["discount_factor"] = 0.98 cfg["batch_size"] = 100 cfg["random_timesteps"] = 1000 cfg["learning_starts"] = 1000 # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 75 cfg["experiment"]["checkpoint_interval"] = 750 cfg["experiment"]["directory"] = "runs/torch/PendulumNoVel" agent = TD3(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 15000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_pendulum_ppo.py
import gymnasium as gym import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.resources.schedulers.torch import KLAdaptiveRL from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.net = nn.Sequential(nn.Linear(self.num_observations, 64), nn.ReLU(), nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, self.num_actions)) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def compute(self, inputs, role): # Pendulum-v1 action_space is -2 to 2 return 2 * torch.tanh(self.net(inputs["states"])), self.log_std_parameter, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 64), nn.ReLU(), nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 1)) def compute(self, inputs, role): return self.net(inputs["states"]), {} # load and wrap the gymnasium environment. # note: the environment version may change depending on the gymnasium version try: env = gym.vector.make("Pendulum-v1", num_envs=4, asynchronous=False) except (gym.error.DeprecatedEnv, gym.error.VersionNotFound) as e: env_id = [spec for spec in gym.envs.registry if spec.startswith("Pendulum-v")][0] print("Pendulum-v1 not found. Trying {}".format(env_id)) env = gym.vector.make(env_id, num_envs=4, asynchronous=False) env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=1024, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device, clip_actions=True) models["value"] = Value(env.observation_space, env.action_space, device) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 1024 # memory_size cfg["learning_epochs"] = 10 cfg["mini_batches"] = 32 cfg["discount_factor"] = 0.9 cfg["lambda"] = 0.95 cfg["learning_rate"] = 1e-3 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["grad_norm_clip"] = 0.5 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = False cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 0.5 cfg["kl_threshold"] = 0 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 500 cfg["experiment"]["checkpoint_interval"] = 5000 cfg["experiment"]["directory"] = "runs/torch/Pendulum" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 100000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_pendulumnovel_trpo_lstm.py
import gymnasium as gym import numpy as np import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.trpo import TRPO_DEFAULT_CONFIG from skrl.agents.torch.trpo import TRPO_RNN as TRPO from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", num_envs=1, num_layers=1, hidden_size=64, sequence_length=128): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hcell (Hout is Hcell because proj_size = 0) self.sequence_length = sequence_length self.lstm = nn.LSTM(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.net = nn.Sequential(nn.Linear(self.hidden_size, 64), nn.ReLU(), nn.Linear(64, self.num_actions)) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size), # hidden states (D ∗ num_layers, N, Hout) (self.num_layers, self.num_envs, self.hidden_size)]}} # cell states (D ∗ num_layers, N, Hcell) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states, cell_states = inputs["rnn"][0], inputs["rnn"][1] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) cell_states = cell_states.view(self.num_layers, -1, self.sequence_length, cell_states.shape[-1]) # (D * num_layers, N, L, Hcell) # get the hidden/cell states corresponding to the initial sequence hidden_states = hidden_states[:,:,0,:].contiguous() # (D * num_layers, N, Hout) cell_states = cell_states[:,:,0,:].contiguous() # (D * num_layers, N, Hcell) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, (hidden_states, cell_states) = self.lstm(rnn_input[:,i0:i1,:], (hidden_states, cell_states)) hidden_states[:, (terminated[:,i1-1]), :] = 0 cell_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_states = (hidden_states, cell_states) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, rnn_states = self.lstm(rnn_input, (hidden_states, cell_states)) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, rnn_states = self.lstm(rnn_input, (hidden_states, cell_states)) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) # Pendulum-v1 action_space is -2 to 2 return 2 * torch.tanh(self.net(rnn_output)), self.log_std_parameter, {"rnn": [rnn_states[0], rnn_states[1]]} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, num_envs=1, num_layers=1, hidden_size=64, sequence_length=128): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hcell (Hout is Hcell because proj_size = 0) self.sequence_length = sequence_length self.lstm = nn.LSTM(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.net = nn.Sequential(nn.Linear(self.hidden_size, 64), nn.ReLU(), nn.Linear(64, 1)) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size), # hidden states (D ∗ num_layers, N, Hout) (self.num_layers, self.num_envs, self.hidden_size)]}} # cell states (D ∗ num_layers, N, Hcell) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states, cell_states = inputs["rnn"][0], inputs["rnn"][1] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) cell_states = cell_states.view(self.num_layers, -1, self.sequence_length, cell_states.shape[-1]) # (D * num_layers, N, L, Hcell) # get the hidden/cell states corresponding to the initial sequence hidden_states = hidden_states[:,:,0,:].contiguous() # (D * num_layers, N, Hout) cell_states = cell_states[:,:,0,:].contiguous() # (D * num_layers, N, Hcell) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, (hidden_states, cell_states) = self.lstm(rnn_input[:,i0:i1,:], (hidden_states, cell_states)) hidden_states[:, (terminated[:,i1-1]), :] = 0 cell_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_states = (hidden_states, cell_states) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, rnn_states = self.lstm(rnn_input, (hidden_states, cell_states)) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, rnn_states = self.lstm(rnn_input, (hidden_states, cell_states)) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) return self.net(rnn_output), {"rnn": [rnn_states[0], rnn_states[1]]} # environment observation wrapper used to mask velocity. Adapted from rl_zoo3 (rl_zoo3/wrappers.py) class NoVelocityWrapper(gym.ObservationWrapper): def observation(self, observation): # observation: x, y, angular velocity return observation * np.array([1, 1, 0]) gym.envs.registration.register(id="PendulumNoVel-v1", entry_point=lambda: NoVelocityWrapper(gym.make("Pendulum-v1"))) # load and wrap the gymnasium environment env = gym.vector.make("PendulumNoVel-v1", num_envs=4, asynchronous=False) env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=1024, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # TRPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/trpo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device, clip_actions=True, num_envs=env.num_envs) models["value"] = Value(env.observation_space, env.action_space, device, num_envs=env.num_envs) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/trpo.html#configuration-and-hyperparameters cfg = TRPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 1024 # memory_size cfg["learning_epochs"] = 10 cfg["mini_batches"] = 32 cfg["discount_factor"] = 0.9 cfg["lambda"] = 0.95 cfg["learning_rate"] = 1e-3 cfg["grad_norm_clip"] = 0.5 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 500 cfg["experiment"]["checkpoint_interval"] = 5000 cfg["experiment"]["directory"] = "runs/torch/PendulumNoVel" agent = TRPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 100000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_pendulumnovel_td3_rnn.py
import gymnasium as gym import numpy as np import torch import torch.nn as nn import torch.nn.functional as F # import the skrl components to build the RL system from skrl.agents.torch.td3 import TD3_DEFAULT_CONFIG from skrl.agents.torch.td3 import TD3_RNN as TD3 from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, Model from skrl.resources.noises.torch import GaussianNoise from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (deterministic models) using mixin class Actor(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, num_envs=1, num_layers=1, hidden_size=400, sequence_length=20): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hout self.sequence_length = sequence_length self.rnn = nn.RNN(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.linear_layer_1 = nn.Linear(self.hidden_size, 400) self.linear_layer_2 = nn.Linear(400, 300) self.action_layer = nn.Linear(300, self.num_actions) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size)]}} # hidden states (D ∗ num_layers, N, Hout) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states = inputs["rnn"][0] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) # get the hidden states corresponding to the initial sequence sequence_index = 1 if role == "target_policy" else 0 # target networks act on the next state of the environment hidden_states = hidden_states[:,:,sequence_index,:].contiguous() # (D * num_layers, N, Hout) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, hidden_states = self.rnn(rnn_input[:,i0:i1,:], hidden_states) hidden_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, hidden_states = self.rnn(rnn_input, hidden_states) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, hidden_states = self.rnn(rnn_input, hidden_states) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) x = F.relu(self.linear_layer_1(rnn_output)) x = F.relu(self.linear_layer_2(x)) # Pendulum-v1 action_space is -2 to 2 return 2 * torch.tanh(self.action_layer(x)), {"rnn": [hidden_states]} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, num_envs=1, num_layers=1, hidden_size=400, sequence_length=20): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hout self.sequence_length = sequence_length self.rnn = nn.RNN(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.linear_layer_1 = nn.Linear(self.hidden_size + self.num_actions, 400) self.linear_layer_2 = nn.Linear(400, 300) self.linear_layer_3 = nn.Linear(300, 1) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size)]}} # hidden states (D ∗ num_layers, N, Hout) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states = inputs["rnn"][0] # critic is only used during training rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) # get the hidden states corresponding to the initial sequence sequence_index = 1 if role in ["target_critic_1", "target_critic_2"] else 0 # target networks act on the next state of the environment hidden_states = hidden_states[:,:,sequence_index,:].contiguous() # (D * num_layers, N, Hout) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, hidden_states = self.rnn(rnn_input[:,i0:i1,:], hidden_states) hidden_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, hidden_states = self.rnn(rnn_input, hidden_states) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) x = F.relu(self.linear_layer_1(torch.cat([rnn_output, inputs["taken_actions"]], dim=1))) x = F.relu(self.linear_layer_2(x)) return self.linear_layer_3(x), {"rnn": [hidden_states]} # environment observation wrapper used to mask velocity. Adapted from rl_zoo3 (rl_zoo3/wrappers.py) class NoVelocityWrapper(gym.ObservationWrapper): def observation(self, observation): # observation: x, y, angular velocity return observation * np.array([1, 1, 0]) gym.envs.registration.register(id="PendulumNoVel-v1", entry_point=lambda: NoVelocityWrapper(gym.make("Pendulum-v1"))) # load and wrap the gymnasium environment env = gym.make("PendulumNoVel-v1") env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=20000, num_envs=env.num_envs, device=device, replacement=False) # instantiate the agent's models (function approximators). # TD3 requires 6 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/td3.html#models models = {} models["policy"] = Actor(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["target_policy"] = Actor(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["critic_1"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["critic_2"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["target_critic_1"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["target_critic_2"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal_", mean=0.0, std=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/td3.html#configuration-and-hyperparameters cfg = TD3_DEFAULT_CONFIG.copy() cfg["exploration"]["noise"] = GaussianNoise(0, 0.1, device=device) cfg["smooth_regularization_noise"] = GaussianNoise(0, 0.2, device=device) cfg["smooth_regularization_clip"] = 0.5 cfg["discount_factor"] = 0.98 cfg["batch_size"] = 100 cfg["random_timesteps"] = 0 cfg["learning_starts"] = 1000 # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 75 cfg["experiment"]["checkpoint_interval"] = 750 cfg["experiment"]["directory"] = "runs/torch/PendulumNoVel" agent = TD3(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 15000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_pendulum_ddpg.py
import gymnasium as gym import torch import torch.nn as nn import torch.nn.functional as F # import the skrl components to build the RL system from skrl.agents.torch.ddpg import DDPG, DDPG_DEFAULT_CONFIG from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, Model from skrl.resources.noises.torch import OrnsteinUhlenbeckNoise from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (deterministic models) using mixin class Actor(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.linear_layer_1 = nn.Linear(self.num_observations, 400) self.linear_layer_2 = nn.Linear(400, 300) self.action_layer = nn.Linear(300, self.num_actions) def compute(self, inputs, role): x = F.relu(self.linear_layer_1(inputs["states"])) x = F.relu(self.linear_layer_2(x)) # Pendulum-v1 action_space is -2 to 2 return 2 * torch.tanh(self.action_layer(x)), {} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.linear_layer_1 = nn.Linear(self.num_observations + self.num_actions, 400) self.linear_layer_2 = nn.Linear(400, 300) self.linear_layer_3 = nn.Linear(300, 1) def compute(self, inputs, role): x = F.relu(self.linear_layer_1(torch.cat([inputs["states"], inputs["taken_actions"]], dim=1))) x = F.relu(self.linear_layer_2(x)) return self.linear_layer_3(x), {} # load and wrap the gymnasium environment. # note: the environment version may change depending on the gymnasium version try: env = gym.make("Pendulum-v1") except (gym.error.DeprecatedEnv, gym.error.VersionNotFound) as e: env_id = [spec for spec in gym.envs.registry if spec.startswith("Pendulum-v")][0] print("Pendulum-v1 not found. Trying {}".format(env_id)) env = gym.make(env_id) env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=15000, num_envs=env.num_envs, device=device, replacement=False) # instantiate the agent's models (function approximators). # DDPG requires 4 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#models models = {} models["policy"] = Actor(env.observation_space, env.action_space, device) models["target_policy"] = Actor(env.observation_space, env.action_space, device) models["critic"] = Critic(env.observation_space, env.action_space, device) models["target_critic"] = Critic(env.observation_space, env.action_space, device) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal_", mean=0.0, std=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#configuration-and-hyperparameters cfg = DDPG_DEFAULT_CONFIG.copy() cfg["exploration"]["noise"] = OrnsteinUhlenbeckNoise(theta=0.15, sigma=0.1, base_scale=1.0, device=device) cfg["batch_size"] = 100 cfg["random_timesteps"] = 100 cfg["learning_starts"] = 100 # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 75 cfg["experiment"]["checkpoint_interval"] = 750 cfg["experiment"]["directory"] = "runs/torch/Pendulum" agent = DDPG(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 15000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_pendulum_sac.py
import gymnasium as gym import torch import torch.nn as nn import torch.nn.functional as F # import the skrl components to build the RL system from skrl.agents.torch.sac import SAC, SAC_DEFAULT_CONFIG from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Actor(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.linear_layer_1 = nn.Linear(self.num_observations, 400) self.linear_layer_2 = nn.Linear(400, 300) self.action_layer = nn.Linear(300, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def compute(self, inputs, role): x = F.relu(self.linear_layer_1(inputs["states"])) x = F.relu(self.linear_layer_2(x)) # Pendulum-v1 action_space is -2 to 2 return 2 * torch.tanh(self.action_layer(x)), self.log_std_parameter, {} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.linear_layer_1 = nn.Linear(self.num_observations + self.num_actions, 400) self.linear_layer_2 = nn.Linear(400, 300) self.linear_layer_3 = nn.Linear(300, 1) def compute(self, inputs, role): x = F.relu(self.linear_layer_1(torch.cat([inputs["states"], inputs["taken_actions"]], dim=1))) x = F.relu(self.linear_layer_2(x)) return self.linear_layer_3(x), {} # load and wrap the gymnasium environment. # note: the environment version may change depending on the gymnasium version try: env = gym.make("Pendulum-v1") except (gym.error.DeprecatedEnv, gym.error.VersionNotFound) as e: env_id = [spec for spec in gym.envs.registry if spec.startswith("Pendulum-v")][0] print("Pendulum-v1 not found. Trying {}".format(env_id)) env = gym.make(env_id) env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=20000, num_envs=env.num_envs, device=device, replacement=False) # instantiate the agent's models (function approximators). # SAC requires 5 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/sac.html#models models = {} models["policy"] = Actor(env.observation_space, env.action_space, device, clip_actions=True) models["critic_1"] = Critic(env.observation_space, env.action_space, device) models["critic_2"] = Critic(env.observation_space, env.action_space, device) models["target_critic_1"] = Critic(env.observation_space, env.action_space, device) models["target_critic_2"] = Critic(env.observation_space, env.action_space, device) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal_", mean=0.0, std=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/sac.html#configuration-and-hyperparameters cfg = SAC_DEFAULT_CONFIG.copy() cfg["discount_factor"] = 0.98 cfg["batch_size"] = 100 cfg["random_timesteps"] = 0 cfg["learning_starts"] = 1000 cfg["learn_entropy"] = True # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 75 cfg["experiment"]["checkpoint_interval"] = 750 cfg["experiment"]["directory"] = "runs/torch/Pendulum" agent = SAC(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 15000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/jax_gymnasium_pendulum_vector_ddpg.py
import gymnasium as gym import flax.linen as nn import jax import jax.numpy as jnp # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ddpg import DDPG, DDPG_DEFAULT_CONFIG from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, Model from skrl.resources.noises.jax import OrnsteinUhlenbeckNoise from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "numpy" # or "jax" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (deterministic models) using mixins class Actor(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) @nn.compact def __call__(self, inputs, role): x = nn.relu(nn.Dense(400)(inputs["states"])) x = nn.relu(nn.Dense(300)(x)) x = nn.Dense(self.num_actions)(x) # Pendulum-v1 action_space is -2 to 2 return 2 * nn.tanh(x), {} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = jnp.concatenate([inputs["states"], inputs["taken_actions"]], axis=-1) x = nn.relu(nn.Dense(400)(x)) x = nn.relu(nn.Dense(300)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the gymnasium environment. # note: the environment version may change depending on the gymnasium version try: env = gym.vector.make("Pendulum-v1", num_envs=10, asynchronous=False) except (gym.error.DeprecatedEnv, gym.error.VersionNotFound) as e: env_id = [spec for spec in gym.envs.registry if spec.startswith("Pendulum-v")][0] print("Pendulum-v1 not found. Trying {}".format(env_id)) env = gym.vector.make(env_id, num_envs=10, asynchronous=False) env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=100000, num_envs=env.num_envs, device=device, replacement=False) # instantiate the agent's models (function approximators). # DDPG requires 4 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#models models = {} models["policy"] = Actor(env.observation_space, env.action_space, device) models["target_policy"] = Actor(env.observation_space, env.action_space, device) models["critic"] = Critic(env.observation_space, env.action_space, device) models["target_critic"] = Critic(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal", stddev=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#configuration-and-hyperparameters cfg = DDPG_DEFAULT_CONFIG.copy() cfg["exploration"]["noise"] = OrnsteinUhlenbeckNoise(theta=0.15, sigma=0.1, base_scale=1.0, device=device) cfg["batch_size"] = 100 cfg["random_timesteps"] = 100 cfg["learning_starts"] = 100 # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 75 cfg["experiment"]["checkpoint_interval"] = 750 cfg["experiment"]["directory"] = "runs/jax/Pendulum" agent = DDPG(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 15000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_pendulumnovel_ddpg_gru.py
import gymnasium as gym import numpy as np import torch import torch.nn as nn import torch.nn.functional as F # import the skrl components to build the RL system from skrl.agents.torch.ddpg import DDPG_DEFAULT_CONFIG from skrl.agents.torch.ddpg import DDPG_RNN as DDPG from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, Model from skrl.resources.noises.torch import OrnsteinUhlenbeckNoise from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (deterministic models) using mixin class Actor(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, num_envs=1, num_layers=1, hidden_size=400, sequence_length=20): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hout self.sequence_length = sequence_length self.gru = nn.GRU(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.linear_layer_1 = nn.Linear(self.hidden_size, 400) self.linear_layer_2 = nn.Linear(400, 300) self.action_layer = nn.Linear(300, self.num_actions) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size)]}} # hidden states (D ∗ num_layers, N, Hout) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states = inputs["rnn"][0] # training if self.training: rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) # get the hidden states corresponding to the initial sequence sequence_index = 1 if role == "target_policy" else 0 # target networks act on the next state of the environment hidden_states = hidden_states[:,:,sequence_index,:].contiguous() # (D * num_layers, N, Hout) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, hidden_states = self.gru(rnn_input[:,i0:i1,:], hidden_states) hidden_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, hidden_states = self.gru(rnn_input, hidden_states) # rollout else: rnn_input = states.view(-1, 1, states.shape[-1]) # (N, L, Hin): N=num_envs, L=1 rnn_output, hidden_states = self.gru(rnn_input, hidden_states) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) x = F.relu(self.linear_layer_1(rnn_output)) x = F.relu(self.linear_layer_2(x)) # Pendulum-v1 action_space is -2 to 2 return 2 * torch.tanh(self.action_layer(x)), {"rnn": [hidden_states]} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, num_envs=1, num_layers=1, hidden_size=400, sequence_length=20): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.num_envs = num_envs self.num_layers = num_layers self.hidden_size = hidden_size # Hout self.sequence_length = sequence_length self.gru = nn.GRU(input_size=self.num_observations, hidden_size=self.hidden_size, num_layers=self.num_layers, batch_first=True) # batch_first -> (batch, sequence, features) self.linear_layer_1 = nn.Linear(self.hidden_size + self.num_actions, 400) self.linear_layer_2 = nn.Linear(400, 300) self.linear_layer_3 = nn.Linear(300, 1) def get_specification(self): # batch size (N) is the number of envs return {"rnn": {"sequence_length": self.sequence_length, "sizes": [(self.num_layers, self.num_envs, self.hidden_size)]}} # hidden states (D ∗ num_layers, N, Hout) def compute(self, inputs, role): states = inputs["states"] terminated = inputs.get("terminated", None) hidden_states = inputs["rnn"][0] # critic is only used during training rnn_input = states.view(-1, self.sequence_length, states.shape[-1]) # (N, L, Hin): N=batch_size, L=sequence_length hidden_states = hidden_states.view(self.num_layers, -1, self.sequence_length, hidden_states.shape[-1]) # (D * num_layers, N, L, Hout) # get the hidden states corresponding to the initial sequence sequence_index = 1 if role == "target_critic" else 0 # target networks act on the next state of the environment hidden_states = hidden_states[:,:,sequence_index,:].contiguous() # (D * num_layers, N, Hout) # reset the RNN state in the middle of a sequence if terminated is not None and torch.any(terminated): rnn_outputs = [] terminated = terminated.view(-1, self.sequence_length) indexes = [0] + (terminated[:,:-1].any(dim=0).nonzero(as_tuple=True)[0] + 1).tolist() + [self.sequence_length] for i in range(len(indexes) - 1): i0, i1 = indexes[i], indexes[i + 1] rnn_output, hidden_states = self.gru(rnn_input[:,i0:i1,:], hidden_states) hidden_states[:, (terminated[:,i1-1]), :] = 0 rnn_outputs.append(rnn_output) rnn_output = torch.cat(rnn_outputs, dim=1) # no need to reset the RNN state in the sequence else: rnn_output, hidden_states = self.gru(rnn_input, hidden_states) # flatten the RNN output rnn_output = torch.flatten(rnn_output, start_dim=0, end_dim=1) # (N, L, D ∗ Hout) -> (N * L, D ∗ Hout) x = F.relu(self.linear_layer_1(torch.cat([rnn_output, inputs["taken_actions"]], dim=1))) x = F.relu(self.linear_layer_2(x)) return self.linear_layer_3(x), {"rnn": [hidden_states]} # environment observation wrapper used to mask velocity. Adapted from rl_zoo3 (rl_zoo3/wrappers.py) class NoVelocityWrapper(gym.ObservationWrapper): def observation(self, observation): # observation: x, y, angular velocity return observation * np.array([1, 1, 0]) gym.envs.registration.register(id="PendulumNoVel-v1", entry_point=lambda: NoVelocityWrapper(gym.make("Pendulum-v1"))) # load and wrap the gymnasium environment env = gym.make("PendulumNoVel-v1") env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=20000, num_envs=env.num_envs, device=device, replacement=False) # instantiate the agent's models (function approximators). # DDPG requires 4 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#models models = {} models["policy"] = Actor(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["target_policy"] = Actor(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["critic"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) models["target_critic"] = Critic(env.observation_space, env.action_space, device, num_envs=env.num_envs) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal_", mean=0.0, std=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#configuration-and-hyperparameters cfg = DDPG_DEFAULT_CONFIG.copy() cfg["exploration"]["noise"] = OrnsteinUhlenbeckNoise(theta=0.15, sigma=0.1, base_scale=1.0, device=device) cfg["discount_factor"] = 0.98 cfg["batch_size"] = 100 cfg["random_timesteps"] = 0 cfg["learning_starts"] = 1000 # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 75 cfg["experiment"]["checkpoint_interval"] = 750 cfg["experiment"]["directory"] = "runs/torch/PendulumNoVel" agent = DDPG(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 15000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/torch_gymnasium_pendulum_td3.py
import gymnasium as gym import torch import torch.nn as nn import torch.nn.functional as F # import the skrl components to build the RL system from skrl.agents.torch.td3 import TD3, TD3_DEFAULT_CONFIG from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, Model from skrl.resources.noises.torch import GaussianNoise from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (deterministic models) using mixin class Actor(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.linear_layer_1 = nn.Linear(self.num_observations, 400) self.linear_layer_2 = nn.Linear(400, 300) self.action_layer = nn.Linear(300, self.num_actions) def compute(self, inputs, role): x = F.relu(self.linear_layer_1(inputs["states"])) x = F.relu(self.linear_layer_2(x)) # Pendulum-v1 action_space is -2 to 2 return 2 * torch.tanh(self.action_layer(x)), {} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.linear_layer_1 = nn.Linear(self.num_observations + self.num_actions, 400) self.linear_layer_2 = nn.Linear(400, 300) self.linear_layer_3 = nn.Linear(300, 1) def compute(self, inputs, role): x = F.relu(self.linear_layer_1(torch.cat([inputs["states"], inputs["taken_actions"]], dim=1))) x = F.relu(self.linear_layer_2(x)) return self.linear_layer_3(x), {} # load and wrap the gymnasium environment. # note: the environment version may change depending on the gymnasium version try: env = gym.make("Pendulum-v1") except (gym.error.DeprecatedEnv, gym.error.VersionNotFound) as e: env_id = [spec for spec in gym.envs.registry if spec.startswith("Pendulum-v")][0] print("Pendulum-v1 not found. Trying {}".format(env_id)) env = gym.make(env_id) env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=20000, num_envs=env.num_envs, device=device, replacement=False) # instantiate the agent's models (function approximators). # TD3 requires 6 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/td3.html#models models = {} models["policy"] = Actor(env.observation_space, env.action_space, device) models["target_policy"] = Actor(env.observation_space, env.action_space, device) models["critic_1"] = Critic(env.observation_space, env.action_space, device) models["critic_2"] = Critic(env.observation_space, env.action_space, device) models["target_critic_1"] = Critic(env.observation_space, env.action_space, device) models["target_critic_2"] = Critic(env.observation_space, env.action_space, device) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal_", mean=0.0, std=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/td3.html#configuration-and-hyperparameters cfg = TD3_DEFAULT_CONFIG.copy() cfg["exploration"]["noise"] = GaussianNoise(0, 0.1, device=device) cfg["smooth_regularization_noise"] = GaussianNoise(0, 0.2, device=device) cfg["smooth_regularization_clip"] = 0.5 cfg["discount_factor"] = 0.98 cfg["batch_size"] = 100 cfg["random_timesteps"] = 1000 cfg["learning_starts"] = 1000 # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 75 cfg["experiment"]["checkpoint_interval"] = 750 cfg["experiment"]["directory"] = "runs/torch/Pendulum" agent = TD3(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 15000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/gymnasium/jax_gymnasium_pendulum_ddpg.py
import gymnasium as gym import flax.linen as nn import jax import jax.numpy as jnp # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ddpg import DDPG, DDPG_DEFAULT_CONFIG from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, Model from skrl.resources.noises.jax import OrnsteinUhlenbeckNoise from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "numpy" # or "jax" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (deterministic models) using mixins class Actor(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) @nn.compact def __call__(self, inputs, role): x = nn.relu(nn.Dense(400)(inputs["states"])) x = nn.relu(nn.Dense(300)(x)) x = nn.Dense(self.num_actions)(x) # Pendulum-v1 action_space is -2 to 2 return 2 * nn.tanh(x), {} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = jnp.concatenate([inputs["states"], inputs["taken_actions"]], axis=-1) x = nn.relu(nn.Dense(400)(x)) x = nn.relu(nn.Dense(300)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the gymnasium environment. # note: the environment version may change depending on the gymnasium version try: env = gym.make("Pendulum-v1") except (gym.error.DeprecatedEnv, gym.error.VersionNotFound) as e: env_id = [spec for spec in gym.envs.registry if spec.startswith("Pendulum-v")][0] print("Pendulum-v1 not found. Trying {}".format(env_id)) env = gym.make(env_id) env = wrap_env(env) device = env.device # instantiate a memory as experience replay memory = RandomMemory(memory_size=15000, num_envs=env.num_envs, device=device, replacement=False) # instantiate the agent's models (function approximators). # DDPG requires 4 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#models models = {} models["policy"] = Actor(env.observation_space, env.action_space, device) models["target_policy"] = Actor(env.observation_space, env.action_space, device) models["critic"] = Critic(env.observation_space, env.action_space, device) models["target_critic"] = Critic(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal", stddev=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#configuration-and-hyperparameters cfg = DDPG_DEFAULT_CONFIG.copy() cfg["exploration"]["noise"] = OrnsteinUhlenbeckNoise(theta=0.15, sigma=0.1, base_scale=1.0, device=device) cfg["batch_size"] = 100 cfg["random_timesteps"] = 100 cfg["learning_starts"] = 100 # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 75 cfg["experiment"]["checkpoint_interval"] = 750 cfg["experiment"]["directory"] = "runs/jax/Pendulum" agent = DDPG(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 15000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/isaacsim/torch_isaacsim_cartpole_ppo.py
# Omniverse Isaac Sim tutorial: Creating New RL Environment # https://docs.omniverse.nvidia.com/isaacsim/latest/tutorial_gym_new_rl_example.html # instantiate the VecEnvBase and create the task from omni.isaac.gym.vec_env import VecEnvBase # isort: skip env = VecEnvBase(headless=True) from cartpole_task import CartpoleTask # isort: skip task = CartpoleTask(name="Cartpole") env.set_task(task, backend="torch") import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.net = nn.Sequential(nn.Linear(self.num_observations, 64), nn.Tanh(), nn.Linear(64, 64), nn.Tanh(), nn.Linear(64, self.num_actions)) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def compute(self, inputs, role): return torch.tanh(self.net(inputs["states"])), self.log_std_parameter, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 64), nn.Tanh(), nn.Linear(64, 64), nn.Tanh(), nn.Linear(64, 1)) def compute(self, inputs, role): return self.net(inputs["states"]), {} # load and wrap the environment env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=1000, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device, clip_actions=True) models["value"] = Value(env.observation_space, env.action_space, device) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal_", mean=0.0, std=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 1000 # memory_size cfg["learning_epochs"] = 20 cfg["mini_batches"] = 1 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 1e-3 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = False cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 0.5 cfg["kl_threshold"] = 0 # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 1000 cfg["experiment"]["checkpoint_interval"] = 10000 cfg["experiment"]["directory"] = "runs/torch/Cartpole" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 100000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/isaacsim/torch_isaacsim_jetbot_ppo.py
# import JetBot environment from env import JetBotEnv import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.net = nn.Sequential(nn.Conv2d(3, 32, kernel_size=8, stride=4), nn.ReLU(), nn.Conv2d(32, 64, kernel_size=4, stride=2), nn.ReLU(), nn.Conv2d(64, 64, kernel_size=3, stride=1), nn.ReLU(), nn.Flatten(), nn.Linear(9216, 512), nn.ReLU(), nn.Linear(512, 16), nn.Tanh(), nn.Linear(16, 64), nn.Tanh(), nn.Linear(64, 32), nn.Tanh(), nn.Linear(32, self.num_actions)) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def compute(self, inputs, role): # view (samples, width * height * channels) -> (samples, width, height, channels) # permute (samples, width, height, channels) -> (samples, channels, width, height) x = self.net(inputs["states"].view(-1, *self.observation_space.shape).permute(0, 3, 1, 2)) return 10 * torch.tanh(x), self.log_std_parameter, {} # JetBotEnv action_space is -10 to 10 class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Conv2d(3, 32, kernel_size=8, stride=4), nn.ReLU(), nn.Conv2d(32, 64, kernel_size=4, stride=2), nn.ReLU(), nn.Conv2d(64, 64, kernel_size=3, stride=1), nn.ReLU(), nn.Flatten(), nn.Linear(9216, 512), nn.ReLU(), nn.Linear(512, 16), nn.Tanh(), nn.Linear(16, 64), nn.Tanh(), nn.Linear(64, 32), nn.Tanh(), nn.Linear(32, 1)) def compute(self, inputs, role): # view (samples, width * height * channels) -> (samples, width, height, channels) # permute (samples, width, height, channels) -> (samples, channels, width, height) return self.net(inputs["states"].view(-1, *self.observation_space.shape).permute(0, 3, 1, 2)), {} # load and wrap the environment env = JetBotEnv(headless=True) env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=10000, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device, clip_actions=True) models["value"] = Value(env.observation_space, env.action_space, device) # initialize models' parameters (weights and biases) for model in models.values(): model.init_parameters(method_name="normal_", mean=0.0, std=0.1) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 10000 cfg["learning_epochs"] = 10 cfg["mini_batches"] = 10 cfg["discount_factor"] = 0.9995 cfg["lambda"] = 0.95 cfg["policy_learning_rate"] = 2.5e-4 cfg["value_learning_rate"] = 2.5e-4 cfg["grad_norm_clip"] = 10 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = False cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 0.5 cfg["kl_threshold"] = 0 # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 10000 cfg["experiment"]["checkpoint_interval"] = 10000 cfg["experiment"]["directory"] = "runs/torch/JetBotEnv" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 500000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/omniisaacgym/torch_ingenuity_ppo.py
import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_omniverse_isaacgym_env from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.resources.schedulers.torch import KLAdaptiveRL from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define shared model (stochastic and deterministic models) using mixins class Shared(GaussianMixin, DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 256), nn.ELU(), nn.Linear(256, 256), nn.ELU(), nn.Linear(256, 128), nn.ELU()) self.mean_layer = nn.Linear(128, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) self.value_layer = nn.Linear(128, 1) def act(self, inputs, role): if role == "policy": return GaussianMixin.act(self, inputs, role) elif role == "value": return DeterministicMixin.act(self, inputs, role) def compute(self, inputs, role): if role == "policy": return self.mean_layer(self.net(inputs["states"])), self.log_std_parameter, {} elif role == "value": return self.value_layer(self.net(inputs["states"])), {} # load and wrap the Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="Ingenuity") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=16, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Shared(env.observation_space, env.action_space, device) models["value"] = models["policy"] # same instance: shared model # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 16 # memory_size cfg["learning_epochs"] = 8 cfg["mini_batches"] = 4 # 16 * 4096 / 16384 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 1e-3 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.016} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 1.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.01 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 32 cfg["experiment"]["checkpoint_interval"] = 320 cfg["experiment"]["directory"] = "runs/torch/Ingenuity" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 6400, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train() # # --------------------------------------------------------- # # comment the code above: `trainer.train()`, and... # # uncomment the following lines to evaluate a trained agent # # --------------------------------------------------------- # from skrl.utils.huggingface import download_model_from_huggingface # # download the trained agent's checkpoint from Hugging Face Hub and load it # path = download_model_from_huggingface("skrl/OmniIsaacGymEnvs-Ingenuity-PPO", filename="agent.pt") # agent.load(path) # # start evaluation # trainer.eval()
Toni-SM/skrl/docs/source/examples/omniisaacgym/torch_factory_task_nut_bolt_pick_ppo.py
import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_omniverse_isaacgym_env from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define shared model (stochastic and deterministic models) using mixins class Shared(GaussianMixin, DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 256), nn.ELU(), nn.Linear(256, 128), nn.ELU(), nn.Linear(128, 64), nn.ELU()) self.mean_layer = nn.Linear(64, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) self.value_layer = nn.Linear(64, 1) def act(self, inputs, role): if role == "policy": return GaussianMixin.act(self, inputs, role) elif role == "value": return DeterministicMixin.act(self, inputs, role) def compute(self, inputs, role): if role == "policy": return self.mean_layer(self.net(inputs["states"])), self.log_std_parameter, {} elif role == "value": return self.value_layer(self.net(inputs["states"])), {} # load and wrap the Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="FactoryTaskNutBoltPick") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=240, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Shared(env.observation_space, env.action_space, device) models["value"] = models["policy"] # same instance: shared model # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 240 # memory_size cfg["learning_epochs"] = 8 cfg["mini_batches"] = 60 # 240 * 128 / 512 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 1e-4 cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 1.0 cfg["kl_threshold"] = 0.016 cfg["rewards_shaper"] = None cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 614 cfg["experiment"]["checkpoint_interval"] = 6144 cfg["experiment"]["directory"] = "runs/torch/FactoryTaskNutBoltPick" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 120000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/omniisaacgym/torch_ant_ddpg_td3_sac_parallel_unshared_memory.py
import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ddpg import DDPG, DDPG_DEFAULT_CONFIG from skrl.agents.torch.sac import SAC, SAC_DEFAULT_CONFIG from skrl.agents.torch.td3 import TD3, TD3_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_omniverse_isaacgym_env from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.noises.torch import GaussianNoise, OrnsteinUhlenbeckNoise from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.trainers.torch import ParallelTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class StochasticActor(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-5, max_log_std=2): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std) self.net = nn.Sequential(nn.Linear(self.num_observations, 512), nn.ReLU(), nn.Linear(512, 256), nn.ReLU(), nn.Linear(256, self.num_actions), nn.Tanh()) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def compute(self, inputs, role): return self.net(inputs["states"]), self.log_std_parameter, {} class DeterministicActor(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 512), nn.ReLU(), nn.Linear(512, 256), nn.ReLU(), nn.Linear(256, self.num_actions), nn.Tanh()) def compute(self, inputs, role): return self.net(inputs["states"]), {} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations + self.num_actions, 512), nn.ReLU(), nn.Linear(512, 256), nn.ReLU(), nn.Linear(256, 1)) def compute(self, inputs, role): return self.net(torch.cat([inputs["states"], inputs["taken_actions"]], dim=1)), {} if __name__ == '__main__': # load and wrap the Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="Ant", num_envs=192) env = wrap_env(env) device = env.device # instantiate memories as experience replay (unique for each agents). # scopes (192 envs): DDPG 64, TD3 64 and SAC 64 memory_ddpg = RandomMemory(memory_size=15625, num_envs=64, device=device) memory_td3 = RandomMemory(memory_size=15625, num_envs=64, device=device) memory_sac = RandomMemory(memory_size=15625, num_envs=64, device=device) # instantiate the agents' models (function approximators). # DDPG requires 4 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#models models_ddpg = {} models_ddpg["policy"] = DeterministicActor(env.observation_space, env.action_space, device) models_ddpg["target_policy"] = DeterministicActor(env.observation_space, env.action_space, device) models_ddpg["critic"] = Critic(env.observation_space, env.action_space, device) models_ddpg["target_critic"] = Critic(env.observation_space, env.action_space, device) # TD3 requires 6 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/td3.html#models models_td3 = {} models_td3["policy"] = DeterministicActor(env.observation_space, env.action_space, device) models_td3["target_policy"] = DeterministicActor(env.observation_space, env.action_space, device) models_td3["critic_1"] = Critic(env.observation_space, env.action_space, device) models_td3["critic_2"] = Critic(env.observation_space, env.action_space, device) models_td3["target_critic_1"] = Critic(env.observation_space, env.action_space, device) models_td3["target_critic_2"] = Critic(env.observation_space, env.action_space, device) # SAC requires 5 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/sac.html#models models_sac = {} models_sac["policy"] = StochasticActor(env.observation_space, env.action_space, device, clip_actions=True) models_sac["critic_1"] = Critic(env.observation_space, env.action_space, device) models_sac["critic_2"] = Critic(env.observation_space, env.action_space, device) models_sac["target_critic_1"] = Critic(env.observation_space, env.action_space, device) models_sac["target_critic_2"] = Critic(env.observation_space, env.action_space, device) # configure and instantiate the agents (visit their documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#configuration-and-hyperparameters cfg_ddpg = DDPG_DEFAULT_CONFIG.copy() cfg_ddpg["exploration"]["noise"] = OrnsteinUhlenbeckNoise(theta=0.15, sigma=0.1, base_scale=0.5, device=device) cfg_ddpg["gradient_steps"] = 1 cfg_ddpg["batch_size"] = 4096 cfg_ddpg["discount_factor"] = 0.99 cfg_ddpg["polyak"] = 0.005 cfg_ddpg["actor_learning_rate"] = 5e-4 cfg_ddpg["critic_learning_rate"] = 5e-4 cfg_ddpg["random_timesteps"] = 80 cfg_ddpg["learning_starts"] = 80 cfg_ddpg["state_preprocessor"] = RunningStandardScaler cfg_ddpg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg_ddpg["experiment"]["write_interval"] = 800 cfg_ddpg["experiment"]["checkpoint_interval"] = 8000 cfg_ddpg["experiment"]["directory"] = "runs/torch/Ant" # https://skrl.readthedocs.io/en/latest/api/agents/td3.html#configuration-and-hyperparameters cfg_td3 = TD3_DEFAULT_CONFIG.copy() cfg_td3["exploration"]["noise"] = GaussianNoise(0, 0.1, device=device) cfg_td3["smooth_regularization_noise"] = GaussianNoise(0, 0.2, device=device) cfg_td3["smooth_regularization_clip"] = 0.5 cfg_td3["gradient_steps"] = 1 cfg_td3["batch_size"] = 4096 cfg_td3["discount_factor"] = 0.99 cfg_td3["polyak"] = 0.005 cfg_td3["actor_learning_rate"] = 5e-4 cfg_td3["critic_learning_rate"] = 5e-4 cfg_td3["random_timesteps"] = 80 cfg_td3["learning_starts"] = 80 cfg_td3["state_preprocessor"] = RunningStandardScaler cfg_td3["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg_td3["experiment"]["write_interval"] = 800 cfg_td3["experiment"]["checkpoint_interval"] = 8000 cfg_td3["experiment"]["directory"] = "runs/torch/Ant" # https://skrl.readthedocs.io/en/latest/api/agents/sac.html#configuration-and-hyperparameters cfg_sac = SAC_DEFAULT_CONFIG.copy() cfg_sac["gradient_steps"] = 1 cfg_sac["batch_size"] = 4096 cfg_sac["discount_factor"] = 0.99 cfg_sac["polyak"] = 0.005 cfg_sac["actor_learning_rate"] = 5e-4 cfg_sac["critic_learning_rate"] = 5e-4 cfg_sac["random_timesteps"] = 80 cfg_sac["learning_starts"] = 80 cfg_sac["grad_norm_clip"] = 0 cfg_sac["learn_entropy"] = True cfg_sac["entropy_learning_rate"] = 5e-3 cfg_sac["initial_entropy_value"] = 1.0 cfg_sac["state_preprocessor"] = RunningStandardScaler cfg_sac["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg_sac["experiment"]["write_interval"] = 800 cfg_sac["experiment"]["checkpoint_interval"] = 8000 cfg_sac["experiment"]["directory"] = "runs/torch/Ant" agent_ddpg = DDPG(models=models_ddpg, memory=memory_ddpg, cfg=cfg_ddpg, observation_space=env.observation_space, action_space=env.action_space, device=device) agent_td3 = TD3(models=models_td3, memory=memory_td3, cfg=cfg_td3, observation_space=env.observation_space, action_space=env.action_space, device=device) agent_sac = SAC(models=models_sac, memory=memory_sac, cfg=cfg_sac, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer and define the agent scopes cfg_trainer = {"timesteps": 160000, "headless": True} trainer = ParallelTrainer(cfg=cfg_trainer, env=env, agents=[agent_ddpg, agent_td3, agent_sac], agents_scope=[64, 64, 64]) # scopes (192 envs): DDPG 64, TD3 64 and SAC 64 # start training trainer.train()
Toni-SM/skrl/docs/source/examples/omniisaacgym/torch_ant_td3.py
import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.td3 import TD3, TD3_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_omniverse_isaacgym_env from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, Model from skrl.resources.noises.torch import GaussianNoise from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (deterministic models) using mixins class DeterministicActor(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 512), nn.ReLU(), nn.Linear(512, 256), nn.ReLU(), nn.Linear(256, self.num_actions), nn.Tanh()) def compute(self, inputs, role): return self.net(inputs["states"]), {} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations + self.num_actions, 512), nn.ReLU(), nn.Linear(512, 256), nn.ReLU(), nn.Linear(256, 1)) def compute(self, inputs, role): return self.net(torch.cat([inputs["states"], inputs["taken_actions"]], dim=1)), {} # load and wrap the Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="Ant", num_envs=64) env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=15625, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # TD3 requires 5 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/td3.html#models models = {} models["policy"] = DeterministicActor(env.observation_space, env.action_space, device) models["target_policy"] = DeterministicActor(env.observation_space, env.action_space, device) models["critic_1"] = Critic(env.observation_space, env.action_space, device) models["critic_2"] = Critic(env.observation_space, env.action_space, device) models["target_critic_1"] = Critic(env.observation_space, env.action_space, device) models["target_critic_2"] = Critic(env.observation_space, env.action_space, device) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/td3.html#configuration-and-hyperparameters cfg = TD3_DEFAULT_CONFIG.copy() cfg["exploration"]["noise"] = GaussianNoise(0, 0.1, device=device) cfg["smooth_regularization_noise"] = GaussianNoise(0, 0.2, device=device) cfg["smooth_regularization_clip"] = 0.5 cfg["gradient_steps"] = 1 cfg["batch_size"] = 4096 cfg["discount_factor"] = 0.99 cfg["polyak"] = 0.005 cfg["actor_learning_rate"] = 5e-4 cfg["critic_learning_rate"] = 5e-4 cfg["random_timesteps"] = 80 cfg["learning_starts"] = 80 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 800 cfg["experiment"]["checkpoint_interval"] = 8000 cfg["experiment"]["directory"] = "runs/torch/Ant" agent = TD3(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 160000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/omniisaacgym/jax_ant_mt_ppo.py
""" Notes for Isaac Sim 2022.2.1 or earlier (Python 3.7 environment): * Python 3.7 is only supported up to jax<=0.3.25. See: https://github.com/google/jax/blob/main/CHANGELOG.md#jaxlib-041-dec-13-2022. * Builds for jaxlib<=0.3.25 are only available up to NVIDIA CUDA 11 and cuDNN 8.2 versions. See: https://storage.googleapis.com/jax-releases/jax_cuda_releases.html and search for `cuda11/jaxlib-0.3.25+cuda11.cudnn82-cp37-cp37m-manylinux2014_x86_64.whl`. * The `jax.Device = jax.xla.Device` statement is required by skrl to support jax<0.4.3. * Models require overloading the `__hash__` method to avoid "TypeError: Failed to hash Flax Module". """ import threading import flax.linen as nn import jax import jax.numpy as jnp jax.Device = jax.xla.Device # for Isaac Sim 2022.2.1 or earlier # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.jax import load_omniverse_isaacgym_env from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.resources.schedulers.jax import KLAdaptiveRL from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "jax" # or "numpy" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) def __hash__(self): # for Isaac Sim 2022.2.1 or earlier return id(self) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(256)(inputs["states"])) x = nn.elu(nn.Dense(128)(x)) x = nn.elu(nn.Dense(64)(x)) x = nn.Dense(self.num_actions)(x) log_std = self.param("log_std", lambda _: jnp.zeros(self.num_actions)) return x, log_std, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) def __hash__(self): # for Isaac Sim 2022.2.1 or earlier return id(self) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(256)(inputs["states"])) x = nn.elu(nn.Dense(128)(x)) x = nn.elu(nn.Dense(64)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the multi-threaded Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="Ant", multi_threaded=True, timeout=30) env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=16, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) models["value"] = Value(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 16 # memory_size cfg["learning_epochs"] = 4 cfg["mini_batches"] = 2 # 16 * 4096 / 32768 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 3e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 1.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.01 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 40 cfg["experiment"]["checkpoint_interval"] = 400 cfg["experiment"]["directory"] = "runs/jax/Ant" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 8000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training in a separate thread threading.Thread(target=trainer.train).start() # run the simulation in the main thread env.run()
Toni-SM/skrl/docs/source/examples/omniisaacgym/jax_cartpole_ppo.py
""" Notes for Isaac Sim 2022.2.1 or earlier (Python 3.7 environment): * Python 3.7 is only supported up to jax<=0.3.25. See: https://github.com/google/jax/blob/main/CHANGELOG.md#jaxlib-041-dec-13-2022. * Builds for jaxlib<=0.3.25 are only available up to NVIDIA CUDA 11 and cuDNN 8.2 versions. See: https://storage.googleapis.com/jax-releases/jax_cuda_releases.html and search for `cuda11/jaxlib-0.3.25+cuda11.cudnn82-cp37-cp37m-manylinux2014_x86_64.whl`. * The `jax.Device = jax.xla.Device` statement is required by skrl to support jax<0.4.3. * Models require overloading the `__hash__` method to avoid "TypeError: Failed to hash Flax Module". """ import flax.linen as nn import jax import jax.numpy as jnp jax.Device = jax.xla.Device # for Isaac Sim 2022.2.1 or earlier # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.jax import load_omniverse_isaacgym_env from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.resources.schedulers.jax import KLAdaptiveRL from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "jax" # or "numpy" # seed for reproducibility set_seed() # e.g. `set_seed(40)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) def __hash__(self): # for Isaac Sim 2022.2.1 or earlier return id(self) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(32)(inputs["states"])) x = nn.elu(nn.Dense(32)(x)) x = nn.Dense(self.num_actions)(x) log_std = self.param("log_std", lambda _: jnp.zeros(self.num_actions)) return x, log_std, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) def __hash__(self): # for Isaac Sim 2022.2.1 or earlier return id(self) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(32)(inputs["states"])) x = nn.elu(nn.Dense(32)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="Cartpole") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=16, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) models["value"] = Value(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 16 # memory_size cfg["learning_epochs"] = 8 cfg["mini_batches"] = 1 # 16 * 512 / 8192 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 3e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 2.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.1 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 16 cfg["experiment"]["checkpoint_interval"] = 80 cfg["experiment"]["directory"] = "runs/jax/Cartpole" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 1600, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/omniisaacgym/jax_shadow_hand_ppo.py
""" Notes for Isaac Sim 2022.2.1 or earlier (Python 3.7 environment): * Python 3.7 is only supported up to jax<=0.3.25. See: https://github.com/google/jax/blob/main/CHANGELOG.md#jaxlib-041-dec-13-2022. * Builds for jaxlib<=0.3.25 are only available up to NVIDIA CUDA 11 and cuDNN 8.2 versions. See: https://storage.googleapis.com/jax-releases/jax_cuda_releases.html and search for `cuda11/jaxlib-0.3.25+cuda11.cudnn82-cp37-cp37m-manylinux2014_x86_64.whl`. * The `jax.Device = jax.xla.Device` statement is required by skrl to support jax<0.4.3. * Models require overloading the `__hash__` method to avoid "TypeError: Failed to hash Flax Module". """ import flax.linen as nn import jax import jax.numpy as jnp jax.Device = jax.xla.Device # for Isaac Sim 2022.2.1 or earlier # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.jax import load_omniverse_isaacgym_env from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.resources.schedulers.jax import KLAdaptiveRL from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "jax" # or "numpy" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) def __hash__(self): # for Isaac Sim 2022.2.1 or earlier return id(self) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(512)(inputs["states"])) x = nn.elu(nn.Dense(512)(x)) x = nn.elu(nn.Dense(256)(x)) x = nn.elu(nn.Dense(128)(x)) x = nn.Dense(self.num_actions)(x) log_std = self.param("log_std", lambda _: jnp.zeros(self.num_actions)) return x, log_std, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) def __hash__(self): # for Isaac Sim 2022.2.1 or earlier return id(self) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(512)(inputs["states"])) x = nn.elu(nn.Dense(512)(x)) x = nn.elu(nn.Dense(256)(x)) x = nn.elu(nn.Dense(128)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="ShadowHand") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=16, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) models["value"] = Value(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 16 # memory_size cfg["learning_epochs"] = 5 cfg["mini_batches"] = 4 # 16 * 8192 / 32768 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 5e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.016} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 2.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.01 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 800 cfg["experiment"]["checkpoint_interval"] = 8000 cfg["experiment"]["directory"] = "runs/jax/ShadowHand" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 160000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/omniisaacgym/torch_allegro_hand_ppo.py
import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_omniverse_isaacgym_env from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.resources.schedulers.torch import KLAdaptiveRL from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define shared model (stochastic and deterministic models) using mixins class Shared(GaussianMixin, DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 512), nn.ELU(), nn.Linear(512, 256), nn.ELU(), nn.Linear(256, 128), nn.ELU()) self.mean_layer = nn.Linear(128, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) self.value_layer = nn.Linear(128, 1) def act(self, inputs, role): if role == "policy": return GaussianMixin.act(self, inputs, role) elif role == "value": return DeterministicMixin.act(self, inputs, role) def compute(self, inputs, role): if role == "policy": return self.mean_layer(self.net(inputs["states"])), self.log_std_parameter, {} elif role == "value": return self.value_layer(self.net(inputs["states"])), {} # load and wrap the Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="AllegroHand") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=16, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Shared(env.observation_space, env.action_space, device) models["value"] = models["policy"] # same instance: shared model # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 16 # memory_size cfg["learning_epochs"] = 5 cfg["mini_batches"] = 4 # 16 * 8192 / 32768 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 5e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.02} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 2.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.01 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 800 cfg["experiment"]["checkpoint_interval"] = 8000 cfg["experiment"]["directory"] = "runs/torch/AllegroHand" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 160000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train() # # --------------------------------------------------------- # # comment the code above: `trainer.train()`, and... # # uncomment the following lines to evaluate a trained agent # # --------------------------------------------------------- # from skrl.utils.huggingface import download_model_from_huggingface # # download the trained agent's checkpoint from Hugging Face Hub and load it # path = download_model_from_huggingface("skrl/OmniIsaacGymEnvs-AllegroHand-PPO", filename="agent.pt") # agent.load(path) # # start evaluation # trainer.eval()
Toni-SM/skrl/docs/source/examples/omniisaacgym/torch_humanoid_ppo.py
import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_omniverse_isaacgym_env from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.resources.schedulers.torch import KLAdaptiveRL from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define shared model (stochastic and deterministic models) using mixins class Shared(GaussianMixin, DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 400), nn.ELU(), nn.Linear(400, 200), nn.ELU(), nn.Linear(200, 100), nn.ELU()) self.mean_layer = nn.Linear(100, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) self.value_layer = nn.Linear(100, 1) def act(self, inputs, role): if role == "policy": return GaussianMixin.act(self, inputs, role) elif role == "value": return DeterministicMixin.act(self, inputs, role) def compute(self, inputs, role): if role == "policy": return self.mean_layer(self.net(inputs["states"])), self.log_std_parameter, {} elif role == "value": return self.value_layer(self.net(inputs["states"])), {} # load and wrap the Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="Humanoid") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=32, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Shared(env.observation_space, env.action_space, device) models["value"] = models["policy"] # same instance: shared model # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 32 # memory_size cfg["learning_epochs"] = 5 cfg["mini_batches"] = 4 # 32 * 4096 / 32768 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 5e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 2.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.01 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 160 cfg["experiment"]["checkpoint_interval"] = 1600 cfg["experiment"]["directory"] = "runs/torch/Humanoid" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 32000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train() # # --------------------------------------------------------- # # comment the code above: `trainer.train()`, and... # # uncomment the following lines to evaluate a trained agent # # --------------------------------------------------------- # from skrl.utils.huggingface import download_model_from_huggingface # # download the trained agent's checkpoint from Hugging Face Hub and load it # path = download_model_from_huggingface("skrl/OmniIsaacGymEnvs-Humanoid-PPO", filename="agent.pt") # agent.load(path) # # start evaluation # trainer.eval()
Toni-SM/skrl/docs/source/examples/omniisaacgym/jax_ant_sac.py
""" Notes for Isaac Sim 2022.2.1 or earlier (Python 3.7 environment): * Python 3.7 is only supported up to jax<=0.3.25. See: https://github.com/google/jax/blob/main/CHANGELOG.md#jaxlib-041-dec-13-2022. * Builds for jaxlib<=0.3.25 are only available up to NVIDIA CUDA 11 and cuDNN 8.2 versions. See: https://storage.googleapis.com/jax-releases/jax_cuda_releases.html and search for `cuda11/jaxlib-0.3.25+cuda11.cudnn82-cp37-cp37m-manylinux2014_x86_64.whl`. * The `jax.Device = jax.xla.Device` statement is required by skrl to support jax<0.4.3. * Models require overloading the `__hash__` method to avoid "TypeError: Failed to hash Flax Module". """ import flax.linen as nn import jax import jax.numpy as jnp jax.Device = jax.xla.Device # for Isaac Sim 2022.2.1 or earlier # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.sac import SAC, SAC_DEFAULT_CONFIG from skrl.envs.loaders.jax import load_omniverse_isaacgym_env from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "jax" # or "numpy" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class StochasticActor(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-5, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) def __hash__(self): # for Isaac Sim 2022.2.1 or earlier return id(self) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.relu(nn.Dense(512)(inputs["states"])) x = nn.relu(nn.Dense(256)(x)) x = nn.Dense(self.num_actions)(x) log_std = self.param("log_std", lambda _: jnp.zeros(self.num_actions)) return nn.tanh(x), log_std, {} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) def __hash__(self): # for Isaac Sim 2022.2.1 or earlier return id(self) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = jnp.concatenate([inputs["states"], inputs["taken_actions"]], axis=-1) x = nn.relu(nn.Dense(512)(x)) x = nn.relu(nn.Dense(256)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="Ant", num_envs=64) env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=15625, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # SAC requires 5 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/sac.html#models models = {} models["policy"] = StochasticActor(env.observation_space, env.action_space, device) models["critic_1"] = Critic(env.observation_space, env.action_space, device) models["critic_2"] = Critic(env.observation_space, env.action_space, device) models["target_critic_1"] = Critic(env.observation_space, env.action_space, device) models["target_critic_2"] = Critic(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/sac.html#configuration-and-hyperparameters cfg = SAC_DEFAULT_CONFIG.copy() cfg["gradient_steps"] = 1 cfg["batch_size"] = 4096 cfg["discount_factor"] = 0.99 cfg["polyak"] = 0.005 cfg["actor_learning_rate"] = 5e-4 cfg["critic_learning_rate"] = 5e-4 cfg["random_timesteps"] = 80 cfg["learning_starts"] = 80 cfg["grad_norm_clip"] = 0 cfg["learn_entropy"] = True cfg["entropy_learning_rate"] = 5e-3 cfg["initial_entropy_value"] = 1.0 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 800 cfg["experiment"]["checkpoint_interval"] = 8000 cfg["experiment"]["directory"] = "runs/jax/Ant" agent = SAC(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 160000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/omniisaacgym/jax_ingenuity_ppo.py
""" Notes for Isaac Sim 2022.2.1 or earlier (Python 3.7 environment): * Python 3.7 is only supported up to jax<=0.3.25. See: https://github.com/google/jax/blob/main/CHANGELOG.md#jaxlib-041-dec-13-2022. * Builds for jaxlib<=0.3.25 are only available up to NVIDIA CUDA 11 and cuDNN 8.2 versions. See: https://storage.googleapis.com/jax-releases/jax_cuda_releases.html and search for `cuda11/jaxlib-0.3.25+cuda11.cudnn82-cp37-cp37m-manylinux2014_x86_64.whl`. * The `jax.Device = jax.xla.Device` statement is required by skrl to support jax<0.4.3. * Models require overloading the `__hash__` method to avoid "TypeError: Failed to hash Flax Module". """ import flax.linen as nn import jax import jax.numpy as jnp jax.Device = jax.xla.Device # for Isaac Sim 2022.2.1 or earlier # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.jax import load_omniverse_isaacgym_env from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.resources.schedulers.jax import KLAdaptiveRL from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "jax" # or "numpy" # seed for reproducibility seed = set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) def __hash__(self): # for Isaac Sim 2022.2.1 or earlier return id(self) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(256)(inputs["states"])) x = nn.elu(nn.Dense(256)(x)) x = nn.elu(nn.Dense(128)(x)) x = nn.Dense(self.num_actions)(x) log_std = self.param("log_std", lambda _: jnp.zeros(self.num_actions)) return x, log_std, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) def __hash__(self): # for Isaac Sim 2022.2.1 or earlier return id(self) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(256)(inputs["states"])) x = nn.elu(nn.Dense(256)(x)) x = nn.elu(nn.Dense(128)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="Ingenuity") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=16, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) models["value"] = Value(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 16 # memory_size cfg["learning_epochs"] = 8 cfg["mini_batches"] = 4 # 16 * 4096 / 16384 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 1e-3 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.016} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 1.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.01 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 32 cfg["experiment"]["checkpoint_interval"] = 320 cfg["experiment"]["directory"] = "runs/jax/Ingenuity" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 6400, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/omniisaacgym/torch_ant_sac.py
import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.sac import SAC, SAC_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_omniverse_isaacgym_env from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class StochasticActor(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-5, max_log_std=2): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std) self.net = nn.Sequential(nn.Linear(self.num_observations, 512), nn.ReLU(), nn.Linear(512, 256), nn.ReLU(), nn.Linear(256, self.num_actions), nn.Tanh()) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def compute(self, inputs, role): return self.net(inputs["states"]), self.log_std_parameter, {} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations + self.num_actions, 512), nn.ReLU(), nn.Linear(512, 256), nn.ReLU(), nn.Linear(256, 1)) def compute(self, inputs, role): return self.net(torch.cat([inputs["states"], inputs["taken_actions"]], dim=1)), {} # load and wrap the Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="Ant", num_envs=64) env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=15625, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # SAC requires 5 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/sac.html#models models = {} models["policy"] = StochasticActor(env.observation_space, env.action_space, device) models["critic_1"] = Critic(env.observation_space, env.action_space, device) models["critic_2"] = Critic(env.observation_space, env.action_space, device) models["target_critic_1"] = Critic(env.observation_space, env.action_space, device) models["target_critic_2"] = Critic(env.observation_space, env.action_space, device) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/sac.html#configuration-and-hyperparameters cfg = SAC_DEFAULT_CONFIG.copy() cfg["gradient_steps"] = 1 cfg["batch_size"] = 4096 cfg["discount_factor"] = 0.99 cfg["polyak"] = 0.005 cfg["actor_learning_rate"] = 5e-4 cfg["critic_learning_rate"] = 5e-4 cfg["random_timesteps"] = 80 cfg["learning_starts"] = 80 cfg["grad_norm_clip"] = 0 cfg["learn_entropy"] = True cfg["entropy_learning_rate"] = 5e-3 cfg["initial_entropy_value"] = 1.0 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 800 cfg["experiment"]["checkpoint_interval"] = 8000 cfg["experiment"]["directory"] = "runs/torch/Ant" agent = SAC(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 160000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/omniisaacgym/torch_ant_ppo.py
import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_omniverse_isaacgym_env from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.resources.schedulers.torch import KLAdaptiveRL from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define shared model (stochastic and deterministic models) using mixins class Shared(GaussianMixin, DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 256), nn.ELU(), nn.Linear(256, 128), nn.ELU(), nn.Linear(128, 64), nn.ELU()) self.mean_layer = nn.Linear(64, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) self.value_layer = nn.Linear(64, 1) def act(self, inputs, role): if role == "policy": return GaussianMixin.act(self, inputs, role) elif role == "value": return DeterministicMixin.act(self, inputs, role) def compute(self, inputs, role): if role == "policy": return self.mean_layer(self.net(inputs["states"])), self.log_std_parameter, {} elif role == "value": return self.value_layer(self.net(inputs["states"])), {} # load and wrap the Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="Ant") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=16, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Shared(env.observation_space, env.action_space, device) models["value"] = models["policy"] # same instance: shared model # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 16 # memory_size cfg["learning_epochs"] = 4 cfg["mini_batches"] = 2 # 16 * 4096 / 32768 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 3e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 1.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.01 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 40 cfg["experiment"]["checkpoint_interval"] = 400 cfg["experiment"]["directory"] = "runs/torch/Ant" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 8000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train() # # --------------------------------------------------------- # # comment the code above: `trainer.train()`, and... # # uncomment the following lines to evaluate a trained agent # # --------------------------------------------------------- # from skrl.utils.huggingface import download_model_from_huggingface # # download the trained agent's checkpoint from Hugging Face Hub and load it # path = download_model_from_huggingface("skrl/OmniIsaacGymEnvs-Ant-PPO", filename="agent.pt") # agent.load(path) # # start evaluation # trainer.eval()
Toni-SM/skrl/docs/source/examples/omniisaacgym/torch_ant_ddpg_td3_sac_sequential_shared_memory.py
import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ddpg import DDPG, DDPG_DEFAULT_CONFIG from skrl.agents.torch.sac import SAC, SAC_DEFAULT_CONFIG from skrl.agents.torch.td3 import TD3, TD3_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_omniverse_isaacgym_env from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.noises.torch import GaussianNoise, OrnsteinUhlenbeckNoise from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class StochasticActor(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-5, max_log_std=2): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std) self.net = nn.Sequential(nn.Linear(self.num_observations, 512), nn.ReLU(), nn.Linear(512, 256), nn.ReLU(), nn.Linear(256, self.num_actions), nn.Tanh()) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def compute(self, inputs, role): return self.net(inputs["states"]), self.log_std_parameter, {} class DeterministicActor(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 512), nn.ReLU(), nn.Linear(512, 256), nn.ReLU(), nn.Linear(256, self.num_actions), nn.Tanh()) def compute(self, inputs, role): return self.net(inputs["states"]), {} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations + self.num_actions, 512), nn.ReLU(), nn.Linear(512, 256), nn.ReLU(), nn.Linear(256, 1)) def compute(self, inputs, role): return self.net(torch.cat([inputs["states"], inputs["taken_actions"]], dim=1)), {} # load and wrap the Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="Ant", num_envs=64) env = wrap_env(env) device = env.device # instantiate a memory as experience replay (unique to all agents) memory = RandomMemory(memory_size=15625, num_envs=env.num_envs, device=device) # instantiate the agents' models (function approximators). # DDPG requires 4 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#models models_ddpg = {} models_ddpg["policy"] = DeterministicActor(env.observation_space, env.action_space, device) models_ddpg["target_policy"] = DeterministicActor(env.observation_space, env.action_space, device) models_ddpg["critic"] = Critic(env.observation_space, env.action_space, device) models_ddpg["target_critic"] = Critic(env.observation_space, env.action_space, device) # TD3 requires 6 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/td3.html#models models_td3 = {} models_td3["policy"] = DeterministicActor(env.observation_space, env.action_space, device) models_td3["target_policy"] = DeterministicActor(env.observation_space, env.action_space, device) models_td3["critic_1"] = Critic(env.observation_space, env.action_space, device) models_td3["critic_2"] = Critic(env.observation_space, env.action_space, device) models_td3["target_critic_1"] = Critic(env.observation_space, env.action_space, device) models_td3["target_critic_2"] = Critic(env.observation_space, env.action_space, device) # SAC requires 5 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/sac.html#models models_sac = {} models_sac["policy"] = StochasticActor(env.observation_space, env.action_space, device, clip_actions=True) models_sac["critic_1"] = Critic(env.observation_space, env.action_space, device) models_sac["critic_2"] = Critic(env.observation_space, env.action_space, device) models_sac["target_critic_1"] = Critic(env.observation_space, env.action_space, device) models_sac["target_critic_2"] = Critic(env.observation_space, env.action_space, device) # configure and instantiate the agents (visit their documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#configuration-and-hyperparameters cfg_ddpg = DDPG_DEFAULT_CONFIG.copy() cfg_ddpg["exploration"]["noise"] = OrnsteinUhlenbeckNoise(theta=0.15, sigma=0.1, base_scale=0.5, device=device) cfg_ddpg["gradient_steps"] = 1 cfg_ddpg["batch_size"] = 4096 cfg_ddpg["discount_factor"] = 0.99 cfg_ddpg["polyak"] = 0.005 cfg_ddpg["actor_learning_rate"] = 5e-4 cfg_ddpg["critic_learning_rate"] = 5e-4 cfg_ddpg["random_timesteps"] = 80 cfg_ddpg["learning_starts"] = 80 cfg_ddpg["state_preprocessor"] = RunningStandardScaler cfg_ddpg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg_ddpg["experiment"]["write_interval"] = 800 cfg_ddpg["experiment"]["checkpoint_interval"] = 8000 cfg_ddpg["experiment"]["directory"] = "runs/torch/Ant" # https://skrl.readthedocs.io/en/latest/api/agents/td3.html#configuration-and-hyperparameters cfg_td3 = TD3_DEFAULT_CONFIG.copy() cfg_td3["exploration"]["noise"] = GaussianNoise(0, 0.1, device=device) cfg_td3["smooth_regularization_noise"] = GaussianNoise(0, 0.2, device=device) cfg_td3["smooth_regularization_clip"] = 0.5 cfg_td3["gradient_steps"] = 1 cfg_td3["batch_size"] = 4096 cfg_td3["discount_factor"] = 0.99 cfg_td3["polyak"] = 0.005 cfg_td3["actor_learning_rate"] = 5e-4 cfg_td3["critic_learning_rate"] = 5e-4 cfg_td3["random_timesteps"] = 80 cfg_td3["learning_starts"] = 80 cfg_td3["state_preprocessor"] = RunningStandardScaler cfg_td3["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg_td3["experiment"]["write_interval"] = 800 cfg_td3["experiment"]["checkpoint_interval"] = 8000 cfg_td3["experiment"]["directory"] = "runs/torch/Ant" # https://skrl.readthedocs.io/en/latest/api/agents/sac.html#configuration-and-hyperparameters cfg_sac = SAC_DEFAULT_CONFIG.copy() cfg_sac["gradient_steps"] = 1 cfg_sac["batch_size"] = 4096 cfg_sac["discount_factor"] = 0.99 cfg_sac["polyak"] = 0.005 cfg_sac["actor_learning_rate"] = 5e-4 cfg_sac["critic_learning_rate"] = 5e-4 cfg_sac["random_timesteps"] = 80 cfg_sac["learning_starts"] = 80 cfg_sac["grad_norm_clip"] = 0 cfg_sac["learn_entropy"] = True cfg_sac["entropy_learning_rate"] = 5e-3 cfg_sac["initial_entropy_value"] = 1.0 cfg_sac["state_preprocessor"] = RunningStandardScaler cfg_sac["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg_sac["experiment"]["write_interval"] = 800 cfg_sac["experiment"]["checkpoint_interval"] = 8000 cfg_sac["experiment"]["directory"] = "runs/torch/Ant" agent_ddpg = DDPG(models=models_ddpg, memory=memory, # shared memory cfg=cfg_ddpg, observation_space=env.observation_space, action_space=env.action_space, device=device) agent_td3 = TD3(models=models_td3, memory=memory, # shared memory cfg=cfg_td3, observation_space=env.observation_space, action_space=env.action_space, device=device) agent_sac = SAC(models=models_sac, memory=memory, # shared memory cfg=cfg_sac, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 160000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent_ddpg, agent_td3, agent_sac], agents_scope=[]) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/omniisaacgym/jax_anymal_terrain_ppo.py
""" Notes for Isaac Sim 2022.2.1 or earlier (Python 3.7 environment): * Python 3.7 is only supported up to jax<=0.3.25. See: https://github.com/google/jax/blob/main/CHANGELOG.md#jaxlib-041-dec-13-2022. * Builds for jaxlib<=0.3.25 are only available up to NVIDIA CUDA 11 and cuDNN 8.2 versions. See: https://storage.googleapis.com/jax-releases/jax_cuda_releases.html and search for `cuda11/jaxlib-0.3.25+cuda11.cudnn82-cp37-cp37m-manylinux2014_x86_64.whl`. * The `jax.Device = jax.xla.Device` statement is required by skrl to support jax<0.4.3. * Models require overloading the `__hash__` method to avoid "TypeError: Failed to hash Flax Module". """ import flax.linen as nn import jax import jax.numpy as jnp jax.Device = jax.xla.Device # for Isaac Sim 2022.2.1 or earlier # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.jax import load_omniverse_isaacgym_env from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.resources.schedulers.jax import KLAdaptiveRL from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "jax" # or "numpy" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) def __hash__(self): # for Isaac Sim 2022.2.1 or earlier return id(self) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(512)(inputs["states"])) x = nn.elu(nn.Dense(256)(x)) x = nn.elu(nn.Dense(128)(x)) x = nn.Dense(self.num_actions)(x) log_std = self.param("log_std", lambda _: jnp.zeros(self.num_actions)) return x, log_std, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) def __hash__(self): # for Isaac Sim 2022.2.1 or earlier return id(self) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(512)(inputs["states"])) x = nn.elu(nn.Dense(256)(x)) x = nn.elu(nn.Dense(128)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="AnymalTerrain") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=48, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) models["value"] = Value(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 48 # memory_size cfg["learning_epochs"] = 5 cfg["mini_batches"] = 6 # 48 * 2048 / 16384 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 3e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.001 cfg["value_loss_scale"] = 1.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = None cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 480 cfg["experiment"]["checkpoint_interval"] = 4800 cfg["experiment"]["directory"] = "runs/jax/AnymalTerrain" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 96000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/omniisaacgym/torch_crazyflie_ppo.py
import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_omniverse_isaacgym_env from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.resources.schedulers.torch import KLAdaptiveRL from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define shared model (stochastic and deterministic models) using mixins class Shared(GaussianMixin, DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 256), nn.Tanh(), nn.Linear(256, 256), nn.Tanh(), nn.Linear(256, 128), nn.Tanh()) self.mean_layer = nn.Linear(128, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) self.value_layer = nn.Linear(128, 1) def act(self, inputs, role): if role == "policy": return GaussianMixin.act(self, inputs, role) elif role == "value": return DeterministicMixin.act(self, inputs, role) def compute(self, inputs, role): if role == "policy": return self.mean_layer(self.net(inputs["states"])), self.log_std_parameter, {} elif role == "value": return self.value_layer(self.net(inputs["states"])), {} # load and wrap the Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="Crazyflie") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=16, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Shared(env.observation_space, env.action_space, device) models["value"] = models["policy"] # same instance: shared model # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 16 # memory_size cfg["learning_epochs"] = 8 cfg["mini_batches"] = 4 # 16 * 4096 / 16384 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 1e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.016} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 1.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.01 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 80 cfg["experiment"]["checkpoint_interval"] = 800 cfg["experiment"]["directory"] = "runs/torch/Crazyflie" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 16000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train() # # --------------------------------------------------------- # # comment the code above: `trainer.train()`, and... # # uncomment the following lines to evaluate a trained agent # # --------------------------------------------------------- # from skrl.utils.huggingface import download_model_from_huggingface # # download the trained agent's checkpoint from Hugging Face Hub and load it # path = download_model_from_huggingface("skrl/OmniIsaacGymEnvs-Crazyflie-PPO", filename="agent.pt") # agent.load(path) # # start evaluation # trainer.eval()
Toni-SM/skrl/docs/source/examples/omniisaacgym/jax_ball_balance_ppo.py
""" Notes for Isaac Sim 2022.2.1 or earlier (Python 3.7 environment): * Python 3.7 is only supported up to jax<=0.3.25. See: https://github.com/google/jax/blob/main/CHANGELOG.md#jaxlib-041-dec-13-2022. * Builds for jaxlib<=0.3.25 are only available up to NVIDIA CUDA 11 and cuDNN 8.2 versions. See: https://storage.googleapis.com/jax-releases/jax_cuda_releases.html and search for `cuda11/jaxlib-0.3.25+cuda11.cudnn82-cp37-cp37m-manylinux2014_x86_64.whl`. * The `jax.Device = jax.xla.Device` statement is required by skrl to support jax<0.4.3. * Models require overloading the `__hash__` method to avoid "TypeError: Failed to hash Flax Module". """ import flax.linen as nn import jax import jax.numpy as jnp jax.Device = jax.xla.Device # for Isaac Sim 2022.2.1 or earlier # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.jax import load_omniverse_isaacgym_env from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.resources.schedulers.jax import KLAdaptiveRL from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "jax" # or "numpy" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) def __hash__(self): # for Isaac Sim 2022.2.1 or earlier return id(self) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(128)(inputs["states"])) x = nn.elu(nn.Dense(64)(x)) x = nn.elu(nn.Dense(32)(x)) x = nn.Dense(self.num_actions)(x) log_std = self.param("log_std", lambda _: jnp.zeros(self.num_actions)) return x, log_std, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) def __hash__(self): # for Isaac Sim 2022.2.1 or earlier return id(self) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(128)(inputs["states"])) x = nn.elu(nn.Dense(64)(x)) x = nn.elu(nn.Dense(32)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="BallBalance") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=16, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) models["value"] = Value(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 16 # memory_size cfg["learning_epochs"] = 8 cfg["mini_batches"] = 8 # 16 * 4096 / 8192 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 3e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 2.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.1 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 20 cfg["experiment"]["checkpoint_interval"] = 200 cfg["experiment"]["directory"] = "runs/jax/BallBalance" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 4000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/omniisaacgym/jax_ant_ddpg.py
""" Notes for Isaac Sim 2022.2.1 or earlier (Python 3.7 environment): * Python 3.7 is only supported up to jax<=0.3.25. See: https://github.com/google/jax/blob/main/CHANGELOG.md#jaxlib-041-dec-13-2022. * Builds for jaxlib<=0.3.25 are only available up to NVIDIA CUDA 11 and cuDNN 8.2 versions. See: https://storage.googleapis.com/jax-releases/jax_cuda_releases.html and search for `cuda11/jaxlib-0.3.25+cuda11.cudnn82-cp37-cp37m-manylinux2014_x86_64.whl`. * The `jax.Device = jax.xla.Device` statement is required by skrl to support jax<0.4.3. * Models require overloading the `__hash__` method to avoid "TypeError: Failed to hash Flax Module". """ import flax.linen as nn import jax import jax.numpy as jnp jax.Device = jax.xla.Device # for Isaac Sim 2022.2.1 or earlier # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ddpg import DDPG, DDPG_DEFAULT_CONFIG from skrl.envs.loaders.jax import load_omniverse_isaacgym_env from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, Model from skrl.resources.noises.jax import OrnsteinUhlenbeckNoise from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "jax" # or "numpy" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (deterministic models) using mixins class DeterministicActor(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) def __hash__(self): # for Isaac Sim 2022.2.1 or earlier return id(self) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.relu(nn.Dense(512)(inputs["states"])) x = nn.relu(nn.Dense(256)(x)) x = nn.Dense(self.num_actions)(x) return nn.tanh(x), {} class Critic(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) def __hash__(self): # for Isaac Sim 2022.2.1 or earlier return id(self) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = jnp.concatenate([inputs["states"], inputs["taken_actions"]], axis=-1) x = nn.relu(nn.Dense(512)(x)) x = nn.relu(nn.Dense(256)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="Ant", num_envs=64) env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=15625, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # DDPG requires 4 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#models models = {} models["policy"] = DeterministicActor(env.observation_space, env.action_space, device) models["target_policy"] = DeterministicActor(env.observation_space, env.action_space, device) models["critic"] = Critic(env.observation_space, env.action_space, device) models["target_critic"] = Critic(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ddpg.html#configuration-and-hyperparameters cfg = DDPG_DEFAULT_CONFIG.copy() cfg["exploration"]["noise"] = OrnsteinUhlenbeckNoise(theta=0.15, sigma=0.1, base_scale=0.5, device=device) cfg["gradient_steps"] = 1 cfg["batch_size"] = 4096 cfg["discount_factor"] = 0.99 cfg["polyak"] = 0.005 cfg["actor_learning_rate"] = 5e-4 cfg["critic_learning_rate"] = 5e-4 cfg["random_timesteps"] = 80 cfg["learning_starts"] = 80 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 800 cfg["experiment"]["checkpoint_interval"] = 8000 cfg["experiment"]["directory"] = "runs/jax/Ant" agent = DDPG(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 160000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/omniisaacgym/jax_allegro_hand_ppo.py
""" Notes for Isaac Sim 2022.2.1 or earlier (Python 3.7 environment): * Python 3.7 is only supported up to jax<=0.3.25. See: https://github.com/google/jax/blob/main/CHANGELOG.md#jaxlib-041-dec-13-2022. * Builds for jaxlib<=0.3.25 are only available up to NVIDIA CUDA 11 and cuDNN 8.2 versions. See: https://storage.googleapis.com/jax-releases/jax_cuda_releases.html and search for `cuda11/jaxlib-0.3.25+cuda11.cudnn82-cp37-cp37m-manylinux2014_x86_64.whl`. * The `jax.Device = jax.xla.Device` statement is required by skrl to support jax<0.4.3. * Models require overloading the `__hash__` method to avoid "TypeError: Failed to hash Flax Module". """ import flax.linen as nn import jax import jax.numpy as jnp jax.Device = jax.xla.Device # for Isaac Sim 2022.2.1 or earlier # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.jax import load_omniverse_isaacgym_env from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.resources.schedulers.jax import KLAdaptiveRL from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "jax" # or "numpy" # seed for reproducibility seed = set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) def __hash__(self): # for Isaac Sim 2022.2.1 or earlier return id(self) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(512)(inputs["states"])) x = nn.elu(nn.Dense(256)(x)) x = nn.elu(nn.Dense(128)(x)) x = nn.Dense(self.num_actions)(x) log_std = self.param("log_std", lambda _: jnp.zeros(self.num_actions)) return x, log_std, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) def __hash__(self): # for Isaac Sim 2022.2.1 or earlier return id(self) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(512)(inputs["states"])) x = nn.elu(nn.Dense(256)(x)) x = nn.elu(nn.Dense(128)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="AllegroHand") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=16, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) models["value"] = Value(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 16 # memory_size cfg["learning_epochs"] = 5 cfg["mini_batches"] = 4 # 16 * 8192 / 32768 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 5e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.02} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 2.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.01 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 800 cfg["experiment"]["checkpoint_interval"] = 8000 cfg["experiment"]["directory"] = "runs/jax/AllegroHand" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 160000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/omniisaacgym/torch_anymal_terrain_ppo.py
import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_omniverse_isaacgym_env from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.resources.schedulers.torch import KLAdaptiveRL from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) self.net = nn.Sequential(nn.Linear(self.num_observations, 512), nn.ELU(), nn.Linear(512, 256), nn.ELU(), nn.Linear(256, 128), nn.ELU(), nn.Linear(128, self.num_actions)) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) def compute(self, inputs, role): return self.net(inputs["states"]), self.log_std_parameter, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False): Model.__init__(self, observation_space, action_space, device) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 512), nn.ELU(), nn.Linear(512, 256), nn.ELU(), nn.Linear(256, 128), nn.ELU(), nn.Linear(128, 1)) def compute(self, inputs, role): return self.net(inputs["states"]), {} # load and wrap the Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="AnymalTerrain") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=48, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) models["value"] = Value(env.observation_space, env.action_space, device) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 48 # memory_size cfg["learning_epochs"] = 5 cfg["mini_batches"] = 6 # 48 * 2048 / 16384 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 3e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.001 cfg["value_loss_scale"] = 1.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = None cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 480 cfg["experiment"]["checkpoint_interval"] = 4800 cfg["experiment"]["directory"] = "runs/torch/AnymalTerrain" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 96000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train() # # --------------------------------------------------------- # # comment the code above: `trainer.train()`, and... # # uncomment the following lines to evaluate a trained agent # # --------------------------------------------------------- # from skrl.utils.huggingface import download_model_from_huggingface # # download the trained agent's checkpoint from Hugging Face Hub and load it # path = download_model_from_huggingface("skrl/OmniIsaacGymEnvs-AnymalTerrain-PPO", filename="agent.pt") # agent.load(path) # # start evaluation # trainer.eval()
Toni-SM/skrl/docs/source/examples/omniisaacgym/torch_cartpole_mt_ppo.py
import threading import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_omniverse_isaacgym_env from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.resources.schedulers.torch import KLAdaptiveRL from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(40)` for fixed seed # define shared model (stochastic and deterministic models) using mixins class Shared(GaussianMixin, DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 32), nn.ELU(), nn.Linear(32, 32), nn.ELU()) self.mean_layer = nn.Linear(32, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) self.value_layer = nn.Linear(32, 1) def act(self, inputs, role): if role == "policy": return GaussianMixin.act(self, inputs, role) elif role == "value": return DeterministicMixin.act(self, inputs, role) def compute(self, inputs, role): if role == "policy": return self.mean_layer(self.net(inputs["states"])), self.log_std_parameter, {} elif role == "value": return self.value_layer(self.net(inputs["states"])), {} # load and wrap the multi-threaded Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="Cartpole", multi_threaded=True, timeout=30) env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=16, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Shared(env.observation_space, env.action_space, device) models["value"] = models["policy"] # same instance: shared model # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 16 # memory_size cfg["learning_epochs"] = 8 cfg["mini_batches"] = 1 # 16 * 512 / 8192 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 3e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 2.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.1 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 16 cfg["experiment"]["checkpoint_interval"] = 80 cfg["experiment"]["directory"] = "runs/torch/Cartpole" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 1600, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training in a separate thread threading.Thread(target=trainer.train).start() # run the simulation in the main thread env.run()
Toni-SM/skrl/docs/source/examples/omniisaacgym/jax_humanoid_ppo.py
""" Notes for Isaac Sim 2022.2.1 or earlier (Python 3.7 environment): * Python 3.7 is only supported up to jax<=0.3.25. See: https://github.com/google/jax/blob/main/CHANGELOG.md#jaxlib-041-dec-13-2022. * Builds for jaxlib<=0.3.25 are only available up to NVIDIA CUDA 11 and cuDNN 8.2 versions. See: https://storage.googleapis.com/jax-releases/jax_cuda_releases.html and search for `cuda11/jaxlib-0.3.25+cuda11.cudnn82-cp37-cp37m-manylinux2014_x86_64.whl`. * The `jax.Device = jax.xla.Device` statement is required by skrl to support jax<0.4.3. * Models require overloading the `__hash__` method to avoid "TypeError: Failed to hash Flax Module". """ import flax.linen as nn import jax import jax.numpy as jnp jax.Device = jax.xla.Device # for Isaac Sim 2022.2.1 or earlier # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.jax import load_omniverse_isaacgym_env from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.resources.schedulers.jax import KLAdaptiveRL from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "jax" # or "numpy" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) def __hash__(self): # for Isaac Sim 2022.2.1 or earlier return id(self) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(400)(inputs["states"])) x = nn.elu(nn.Dense(200)(x)) x = nn.elu(nn.Dense(100)(x)) x = nn.Dense(self.num_actions)(x) log_std = self.param("log_std", lambda _: jnp.zeros(self.num_actions)) return x, log_std, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) def __hash__(self): # for Isaac Sim 2022.2.1 or earlier return id(self) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(400)(inputs["states"])) x = nn.elu(nn.Dense(200)(x)) x = nn.elu(nn.Dense(100)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="Humanoid") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=32, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) models["value"] = Value(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 32 # memory_size cfg["learning_epochs"] = 5 cfg["mini_batches"] = 4 # 32 * 4096 / 32768 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 5e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 2.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.01 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 160 cfg["experiment"]["checkpoint_interval"] = 1600 cfg["experiment"]["directory"] = "runs/jax/Humanoid" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 32000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/omniisaacgym/torch_shadow_hand_ppo.py
import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_omniverse_isaacgym_env from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.resources.schedulers.torch import KLAdaptiveRL from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define shared model (stochastic and deterministic models) using mixins class Shared(GaussianMixin, DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 512), nn.ELU(), nn.Linear(512, 512), nn.ELU(), nn.Linear(512, 256), nn.ELU(), nn.Linear(256, 128), nn.ELU()) self.mean_layer = nn.Linear(128, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) self.value_layer = nn.Linear(128, 1) def act(self, inputs, role): if role == "policy": return GaussianMixin.act(self, inputs, role) elif role == "value": return DeterministicMixin.act(self, inputs, role) def compute(self, inputs, role): if role == "policy": return self.mean_layer(self.net(inputs["states"])), self.log_std_parameter, {} elif role == "value": return self.value_layer(self.net(inputs["states"])), {} # load and wrap the Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="ShadowHand") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=16, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Shared(env.observation_space, env.action_space, device) models["value"] = models["policy"] # same instance: shared model # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 16 # memory_size cfg["learning_epochs"] = 5 cfg["mini_batches"] = 4 # 16 * 8192 / 32768 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 5e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.016} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 2.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.01 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 800 cfg["experiment"]["checkpoint_interval"] = 8000 cfg["experiment"]["directory"] = "runs/torch/ShadowHand" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 160000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train() # # --------------------------------------------------------- # # comment the code above: `trainer.train()`, and... # # uncomment the following lines to evaluate a trained agent # # --------------------------------------------------------- # from skrl.utils.huggingface import download_model_from_huggingface # # download the trained agent's checkpoint from Hugging Face Hub and load it # path = download_model_from_huggingface("skrl/OmniIsaacGymEnvs-ShadowHand-PPO", filename="agent.pt") # agent.load(path) # # start evaluation # trainer.eval()
Toni-SM/skrl/docs/source/examples/omniisaacgym/torch_franka_cabinet_ppo.py
import torch import torch.nn as nn # import the skrl components to build the RL system from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.torch import load_omniverse_isaacgym_env from skrl.envs.wrappers.torch import wrap_env from skrl.memories.torch import RandomMemory from skrl.models.torch import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.torch import RunningStandardScaler from skrl.resources.schedulers.torch import KLAdaptiveRL from skrl.trainers.torch import SequentialTrainer from skrl.utils import set_seed # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define shared model (stochastic and deterministic models) using mixins class Shared(GaussianMixin, DeterministicMixin, Model): def __init__(self, observation_space, action_space, device, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"): Model.__init__(self, observation_space, action_space, device) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) DeterministicMixin.__init__(self, clip_actions) self.net = nn.Sequential(nn.Linear(self.num_observations, 256), nn.ELU(), nn.Linear(256, 128), nn.ELU(), nn.Linear(128, 64), nn.ELU()) self.mean_layer = nn.Linear(64, self.num_actions) self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions)) self.value_layer = nn.Linear(64, 1) def act(self, inputs, role): if role == "policy": return GaussianMixin.act(self, inputs, role) elif role == "value": return DeterministicMixin.act(self, inputs, role) def compute(self, inputs, role): if role == "policy": return self.mean_layer(self.net(inputs["states"])), self.log_std_parameter, {} elif role == "value": return self.value_layer(self.net(inputs["states"])), {} # load and wrap the Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="FrankaCabinet") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=16, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Shared(env.observation_space, env.action_space, device) models["value"] = models["policy"] # same instance: shared model # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 16 # memory_size cfg["learning_epochs"] = 8 cfg["mini_batches"] = 8 # 16 * 4096 / 8192 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 5e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 2.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.01 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 120 cfg["experiment"]["checkpoint_interval"] = 1200 cfg["experiment"]["directory"] = "runs/torch/FrankaCabinet" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 24000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train() # # --------------------------------------------------------- # # comment the code above: `trainer.train()`, and... # # uncomment the following lines to evaluate a trained agent # # --------------------------------------------------------- # from skrl.utils.huggingface import download_model_from_huggingface # # download the trained agent's checkpoint from Hugging Face Hub and load it # path = download_model_from_huggingface("skrl/OmniIsaacGymEnvs-FrankaCabinet-PPO", filename="agent.pt") # agent.load(path) # # start evaluation # trainer.eval()
Toni-SM/skrl/docs/source/examples/omniisaacgym/jax_quadcopter_ppo.py
""" Notes for Isaac Sim 2022.2.1 or earlier (Python 3.7 environment): * Python 3.7 is only supported up to jax<=0.3.25. See: https://github.com/google/jax/blob/main/CHANGELOG.md#jaxlib-041-dec-13-2022. * Builds for jaxlib<=0.3.25 are only available up to NVIDIA CUDA 11 and cuDNN 8.2 versions. See: https://storage.googleapis.com/jax-releases/jax_cuda_releases.html and search for `cuda11/jaxlib-0.3.25+cuda11.cudnn82-cp37-cp37m-manylinux2014_x86_64.whl`. * The `jax.Device = jax.xla.Device` statement is required by skrl to support jax<0.4.3. * Models require overloading the `__hash__` method to avoid "TypeError: Failed to hash Flax Module". """ import flax.linen as nn import jax import jax.numpy as jnp jax.Device = jax.xla.Device # for Isaac Sim 2022.2.1 or earlier # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.jax import load_omniverse_isaacgym_env from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.resources.schedulers.jax import KLAdaptiveRL from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "jax" # or "numpy" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) def __hash__(self): # for Isaac Sim 2022.2.1 or earlier return id(self) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(256)(inputs["states"])) x = nn.elu(nn.Dense(256)(x)) x = nn.elu(nn.Dense(128)(x)) x = nn.Dense(self.num_actions)(x) log_std = self.param("log_std", lambda _: jnp.zeros(self.num_actions)) return x, log_std, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) def __hash__(self): # for Isaac Sim 2022.2.1 or earlier return id(self) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(256)(inputs["states"])) x = nn.elu(nn.Dense(256)(x)) x = nn.elu(nn.Dense(128)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="Quadcopter") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=16, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) models["value"] = Value(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 16 # memory_size cfg["learning_epochs"] = 8 cfg["mini_batches"] = 4 # 16 * 4096 / 16384 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 1e-3 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.016} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 1.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.1 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 80 cfg["experiment"]["checkpoint_interval"] = 800 cfg["experiment"]["directory"] = "runs/jax/Quadcopter" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 16000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/omniisaacgym/jax_anymal_ppo.py
""" Notes for Isaac Sim 2022.2.1 or earlier (Python 3.7 environment): * Python 3.7 is only supported up to jax<=0.3.25. See: https://github.com/google/jax/blob/main/CHANGELOG.md#jaxlib-041-dec-13-2022. * Builds for jaxlib<=0.3.25 are only available up to NVIDIA CUDA 11 and cuDNN 8.2 versions. See: https://storage.googleapis.com/jax-releases/jax_cuda_releases.html and search for `cuda11/jaxlib-0.3.25+cuda11.cudnn82-cp37-cp37m-manylinux2014_x86_64.whl`. * The `jax.Device = jax.xla.Device` statement is required by skrl to support jax<0.4.3. * Models require overloading the `__hash__` method to avoid "TypeError: Failed to hash Flax Module". """ import flax.linen as nn import jax import jax.numpy as jnp jax.Device = jax.xla.Device # for Isaac Sim 2022.2.1 or earlier # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.jax import load_omniverse_isaacgym_env from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.resources.schedulers.jax import KLAdaptiveRL from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "jax" # or "numpy" # seed for reproducibility set_seed() # e.g. `set_seed(42)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) def __hash__(self): # for Isaac Sim 2022.2.1 or earlier return id(self) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(256)(inputs["states"])) x = nn.elu(nn.Dense(128)(x)) x = nn.elu(nn.Dense(64)(x)) x = nn.Dense(self.num_actions)(x) log_std = self.param("log_std", lambda _: jnp.zeros(self.num_actions)) return x, log_std, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) def __hash__(self): # for Isaac Sim 2022.2.1 or earlier return id(self) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(256)(inputs["states"])) x = nn.elu(nn.Dense(128)(x)) x = nn.elu(nn.Dense(64)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="Anymal") env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=24, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) models["value"] = Value(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 24 # memory_size cfg["learning_epochs"] = 5 cfg["mini_batches"] = 3 # 24 * 4096 / 32768 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 3e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 1.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = None cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 120 cfg["experiment"]["checkpoint_interval"] = 1200 cfg["experiment"]["directory"] = "runs/jax/Anymal" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 24000, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training trainer.train()
Toni-SM/skrl/docs/source/examples/omniisaacgym/jax_cartpole_mt_ppo.py
""" Notes for Isaac Sim 2022.2.1 or earlier (Python 3.7 environment): * Python 3.7 is only supported up to jax<=0.3.25. See: https://github.com/google/jax/blob/main/CHANGELOG.md#jaxlib-041-dec-13-2022. * Builds for jaxlib<=0.3.25 are only available up to NVIDIA CUDA 11 and cuDNN 8.2 versions. See: https://storage.googleapis.com/jax-releases/jax_cuda_releases.html and search for `cuda11/jaxlib-0.3.25+cuda11.cudnn82-cp37-cp37m-manylinux2014_x86_64.whl`. * The `jax.Device = jax.xla.Device` statement is required by skrl to support jax<0.4.3. * Models require overloading the `__hash__` method to avoid "TypeError: Failed to hash Flax Module". """ import threading import flax.linen as nn import jax import jax.numpy as jnp jax.Device = jax.xla.Device # for Isaac Sim 2022.2.1 or earlier # import the skrl components to build the RL system from skrl import config from skrl.agents.jax.ppo import PPO, PPO_DEFAULT_CONFIG from skrl.envs.loaders.jax import load_omniverse_isaacgym_env from skrl.envs.wrappers.jax import wrap_env from skrl.memories.jax import RandomMemory from skrl.models.jax import DeterministicMixin, GaussianMixin, Model from skrl.resources.preprocessors.jax import RunningStandardScaler from skrl.resources.schedulers.jax import KLAdaptiveRL from skrl.trainers.jax import SequentialTrainer from skrl.utils import set_seed config.jax.backend = "jax" # or "numpy" # seed for reproducibility set_seed() # e.g. `set_seed(40)` for fixed seed # define models (stochastic and deterministic models) using mixins class Policy(GaussianMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum", **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction) def __hash__(self): # for Isaac Sim 2022.2.1 or earlier return id(self) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(32)(inputs["states"])) x = nn.elu(nn.Dense(32)(x)) x = nn.Dense(self.num_actions)(x) log_std = self.param("log_std", lambda _: jnp.zeros(self.num_actions)) return x, log_std, {} class Value(DeterministicMixin, Model): def __init__(self, observation_space, action_space, device=None, clip_actions=False, **kwargs): Model.__init__(self, observation_space, action_space, device, **kwargs) DeterministicMixin.__init__(self, clip_actions) def __hash__(self): # for Isaac Sim 2022.2.1 or earlier return id(self) @nn.compact # marks the given module method allowing inlined submodules def __call__(self, inputs, role): x = nn.elu(nn.Dense(32)(inputs["states"])) x = nn.elu(nn.Dense(32)(x)) x = nn.Dense(1)(x) return x, {} # load and wrap the multi-threaded Omniverse Isaac Gym environment env = load_omniverse_isaacgym_env(task_name="Cartpole", multi_threaded=True, timeout=30) env = wrap_env(env) device = env.device # instantiate a memory as rollout buffer (any memory can be used for this) memory = RandomMemory(memory_size=16, num_envs=env.num_envs, device=device) # instantiate the agent's models (function approximators). # PPO requires 2 models, visit its documentation for more details # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models models = {} models["policy"] = Policy(env.observation_space, env.action_space, device) models["value"] = Value(env.observation_space, env.action_space, device) # instantiate models' state dict for role, model in models.items(): model.init_state_dict(role) # configure and instantiate the agent (visit its documentation to see all the options) # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters cfg = PPO_DEFAULT_CONFIG.copy() cfg["rollouts"] = 16 # memory_size cfg["learning_epochs"] = 8 cfg["mini_batches"] = 1 # 16 * 512 / 8192 cfg["discount_factor"] = 0.99 cfg["lambda"] = 0.95 cfg["learning_rate"] = 3e-4 cfg["learning_rate_scheduler"] = KLAdaptiveRL cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008} cfg["random_timesteps"] = 0 cfg["learning_starts"] = 0 cfg["grad_norm_clip"] = 1.0 cfg["ratio_clip"] = 0.2 cfg["value_clip"] = 0.2 cfg["clip_predicted_values"] = True cfg["entropy_loss_scale"] = 0.0 cfg["value_loss_scale"] = 2.0 cfg["kl_threshold"] = 0 cfg["rewards_shaper"] = lambda rewards, timestep, timesteps: rewards * 0.1 cfg["state_preprocessor"] = RunningStandardScaler cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device} cfg["value_preprocessor"] = RunningStandardScaler cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device} # logging to TensorBoard and write checkpoints (in timesteps) cfg["experiment"]["write_interval"] = 16 cfg["experiment"]["checkpoint_interval"] = 80 cfg["experiment"]["directory"] = "runs/jax/Cartpole" agent = PPO(models=models, memory=memory, cfg=cfg, observation_space=env.observation_space, action_space=env.action_space, device=device) # configure and instantiate the RL trainer cfg_trainer = {"timesteps": 1600, "headless": True} trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=agent) # start training in a separate thread threading.Thread(target=trainer.train).start() # run the simulation in the main thread env.run()