diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63518c7244b2866ab26e2b9d8689cb47fccdd8d6 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/attention_net_supervised.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/attention_net_supervised.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73c01d9b14258876d0511b2c5e30543e749c0823 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/attention_net_supervised.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/complex_struct_space.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/complex_struct_space.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7063c3d98313c0bb4419ae3f9181b73604464b7a Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/complex_struct_space.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/custom_keras_model.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/custom_keras_model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c985427c7236246e4b1ba865fe01bbc6fe65fdce Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/custom_keras_model.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/parametric_actions_cartpole.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/parametric_actions_cartpole.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aff219e185e0ff8b190a4a1ba737e527d7d156ef Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/parametric_actions_cartpole.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/parametric_actions_cartpole_embeddings_learnt_by_model.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/parametric_actions_cartpole_embeddings_learnt_by_model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3e0b9690de2743ed0c462cbea43041e4f70189e Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/parametric_actions_cartpole_embeddings_learnt_by_model.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/remote_base_env_with_custom_api.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/remote_base_env_with_custom_api.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b68fd55076bfb7c2ed51972d9870f2b72138792c Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/remote_base_env_with_custom_api.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/remote_envs_with_inference_done_on_main_node.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/remote_envs_with_inference_done_on_main_node.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5c8b6cf5fac0d749cb8fe4451fd01c1ce544c0c Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/remote_envs_with_inference_done_on_main_node.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/sb2rllib_rllib_example.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/sb2rllib_rllib_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1efede89aab4887d6d8fd23ea7ed26332662ed7 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/sb2rllib_rllib_example.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/sb2rllib_sb_example.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/sb2rllib_sb_example.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4071d569da0456b4e664944b469ab67f78250fe7 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/sb2rllib_sb_example.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/action_mask_model.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/action_mask_model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a83b63a5006ea6dcde7c6d798503a0a9f9bc528a Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/action_mask_model.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/batch_norm_model.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/batch_norm_model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26dd6c09f42cfa48ecfb0bf656f2e6f2dbe4e46c Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/batch_norm_model.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/centralized_critic_models.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/centralized_critic_models.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c737cd15cfcaf661d6cbfac123483d9372625c4 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/centralized_critic_models.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/custom_loss_model.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/custom_loss_model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f33d2a2ab9cad2f5cc5f2b57025211c158c89e8a Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/custom_loss_model.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/custom_model_api.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/custom_model_api.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be83dcf4306ecea460d34072f60611a70f84fc1d Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/custom_model_api.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/eager_model.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/eager_model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6485320cd07da0c774fc77c6e593e8894300d9b Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/eager_model.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/mobilenet_v2_encoder.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/mobilenet_v2_encoder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bad8d8973fae81a2f643c8b60004593168903156 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/mobilenet_v2_encoder.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/mobilenet_v2_with_lstm_models.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/mobilenet_v2_with_lstm_models.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b2fd12b263b1536794f0256c61663cbff1082d9 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/mobilenet_v2_with_lstm_models.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/parametric_actions_model.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/parametric_actions_model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa1fc810cf4dc3ae0c91d3168da4817b75b8cac0 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/parametric_actions_model.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/shared_weights_model.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/shared_weights_model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf531000334b771e2a1b38a76a3f422771496b4c Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/shared_weights_model.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/simple_rpg_model.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/simple_rpg_model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c401684c7553a50f46e36ebccebad5d815d42ed2 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/simple_rpg_model.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/trajectory_view_utilizing_models.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/trajectory_view_utilizing_models.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..117871b70068dd6eade5c73d339649210a925950 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/trajectory_view_utilizing_models.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__init__.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bc29b48ddf7ad8efc03b08f139797ca15e6da34 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/cliff_walking_wall_policy.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/cliff_walking_wall_policy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0bee8c79c29d18864015e5f0c159a5bf55c5550 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/cliff_walking_wall_policy.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/episode_env_aware_policy.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/episode_env_aware_policy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16d9f80c2b590bb4b925538779dca8136e243e5f Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/episode_env_aware_policy.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/memory_leaking_policy.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/memory_leaking_policy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb2ec957d313a11c66d1599f6a22552f21725ce4 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/memory_leaking_policy.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/random_policy.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/random_policy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9235534c7e81029010e2fa3cbcf42451b9cf643b Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/random_policy.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/rock_paper_scissors_dummies.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/rock_paper_scissors_dummies.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ca36773eaa541bb4aa7460a82db4962d927cae3 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/rock_paper_scissors_dummies.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/cliff_walking_wall_policy.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/cliff_walking_wall_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c9a4758f81ea427f577c6e8004e4ffeb8f3bef06 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/cliff_walking_wall_policy.py @@ -0,0 +1,100 @@ +# @OldAPIStack +import gymnasium as gym +from typing import Dict, Union, List, Tuple, Optional +import numpy as np + +from ray.rllib.policy.policy import Policy, ViewRequirement +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.models.torch.torch_action_dist import TorchCategorical +from ray.rllib.utils.typing import AlgorithmConfigDict, TensorStructType, TensorType +from ray.rllib.utils.annotations import override +from ray.rllib.utils.debug import update_global_seed_if_necessary + + +class CliffWalkingWallPolicy(Policy): + """Optimal RLlib policy for the CliffWalkingWallEnv environment, defined in + ray/rllib/examples/env/cliff_walking_wall_env.py, with epsilon-greedy exploration. + + The policy takes a random action with probability epsilon, specified + by `config["epsilon"]`, and the optimal action with probability 1 - epsilon. + """ + + @override(Policy) + def __init__( + self, + observation_space: gym.Space, + action_space: gym.Space, + config: AlgorithmConfigDict, + ): + update_global_seed_if_necessary(seed=config.get("seed")) + super().__init__(observation_space, action_space, config) + + # Known optimal action dist for each of the 48 states and 4 actions + self.action_dist = np.zeros((48, 4), dtype=float) + # Starting state: go up + self.action_dist[36] = (1, 0, 0, 0) + # Cliff + Goal: never actually used, set to random + self.action_dist[37:] = (0.25, 0.25, 0.25, 0.25) + # Row 2; always go right + self.action_dist[24:36] = (0, 1, 0, 0) + # Row 0 and Row 1; go down or go right + self.action_dist[0:24] = (0, 0.5, 0.5, 0) + # Col 11; always go down, supercedes previous values + self.action_dist[[11, 23, 35]] = (0, 0, 1, 0) + assert np.allclose(self.action_dist.sum(-1), 1) + + # Epsilon-Greedy action selection + epsilon = config.get("epsilon", 0.0) + self.action_dist = self.action_dist * (1 - epsilon) + epsilon / 4 + assert np.allclose(self.action_dist.sum(-1), 1) + + # Attributes required for RLlib; note that while CliffWalkingWallPolicy + # inherits from Policy, it actually implements TorchPolicyV2. + self.view_requirements[SampleBatch.ACTION_PROB] = ViewRequirement() + self.device = "cpu" + self.model = None + self.dist_class = TorchCategorical + + @override(Policy) + def compute_actions( + self, + obs_batch: Union[List[TensorStructType], TensorStructType], + state_batches: Optional[List[TensorType]] = None, + **kwargs, + ) -> Tuple[TensorType, List[TensorType], Dict[str, TensorType]]: + obs = np.array(obs_batch, dtype=int) + action_probs = self.action_dist[obs] + actions = np.zeros(len(obs), dtype=int) + for i in range(len(obs)): + actions[i] = np.random.choice(4, p=action_probs[i]) + return ( + actions, + [], + {SampleBatch.ACTION_PROB: action_probs[np.arange(len(obs)), actions]}, + ) + + @override(Policy) + def compute_log_likelihoods( + self, + actions: Union[List[TensorType], TensorType], + obs_batch: Union[List[TensorType], TensorType], + **kwargs, + ) -> TensorType: + obs = np.array(obs_batch, dtype=int) + actions = np.array(actions, dtype=int) + # Compute action probs for all possible actions + action_probs = self.action_dist[obs] + # Take the action_probs corresponding to the specified actions + action_probs = action_probs[np.arange(len(obs)), actions] + # Ignore RuntimeWarning thrown by np.log(0) if action_probs is 0 + with np.errstate(divide="ignore"): + return np.log(action_probs) + + def action_distribution_fn( + self, model, obs_batch: TensorStructType, **kwargs + ) -> Tuple[TensorType, type, List[TensorType]]: + obs = np.array(obs_batch[SampleBatch.OBS], dtype=int) + action_probs = self.action_dist[obs] + # Ignore RuntimeWarning thrown by np.log(0) if action_probs is 0 + with np.errstate(divide="ignore"): + return np.log(action_probs), TorchCategorical, None diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/episode_env_aware_policy.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/episode_env_aware_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..f33197eed96c5c94571f6d3316798c4ba10e3fe9 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/episode_env_aware_policy.py @@ -0,0 +1,134 @@ +# @OldAPIStack +import numpy as np +from gymnasium.spaces import Box + +from ray.rllib.core.columns import Columns +from ray.rllib.examples._old_api_stack.policy.random_policy import RandomPolicy +from ray.rllib.examples.rl_modules.classes.random_rlm import StatefulRandomRLModule +from ray.rllib.policy.policy import Policy +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.view_requirement import ViewRequirement +from ray.rllib.utils.annotations import override + + +class StatefulRandomPolicy(RandomPolicy): + """A Policy that has acts randomly and has stateful view requirements.""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.model = StatefulRandomRLModule( + action_space=self.action_space, + model_config={ + "max_seq_len": 50, + "lstm_use_prev_action": False, + "lstm_use_prev_reward": False, + }, + ) + + self.view_requirements = self.model.update_default_view_requirements( + self.view_requirements + ) + + @override(Policy) + def is_recurrent(self): + return True + + @override(Policy) + def postprocess_trajectory( + self, sample_batch, other_agent_batches=None, episode=None + ): + sample_batch["2xobs"] = sample_batch["obs"] * 2.0 + return sample_batch + + @override(Policy) + def compute_actions_from_input_dict(self, input_dict, *args, **kwargs): + fwd_out = self.model.forward_exploration(input_dict) + actions = fwd_out[SampleBatch.ACTIONS] + state_out = fwd_out[Columns.STATE_OUT] + return actions, state_out, {} + + +class EpisodeEnvAwareAttentionPolicy(RandomPolicy): + """A Policy that always knows the current EpisodeID and EnvID and + returns these in its actions.""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.state_space = Box(-1.0, 1.0, (1,)) + self.config["model"] = {"max_seq_len": 50} + + class _fake_model: + def __init__(self, state_space, config): + self.state_space = state_space + self.view_requirements = { + SampleBatch.AGENT_INDEX: ViewRequirement(), + SampleBatch.EPS_ID: ViewRequirement(), + "env_id": ViewRequirement(), + "t": ViewRequirement(), + SampleBatch.OBS: ViewRequirement(), + "state_in_0": ViewRequirement( + "state_out_0", + # Provide state outs -50 to -1 as "state-in". + shift="-50:-1", + # Repeat the incoming state every n time steps (usually max seq + # len). + batch_repeat_value=config["model"]["max_seq_len"], + space=state_space, + ), + "state_out_0": ViewRequirement( + space=state_space, used_for_compute_actions=False + ), + } + + def compile(self, *args, **kwargs): + """Dummy method for compatibility with TorchRLModule. + + This is hit when RolloutWorker tries to compile TorchRLModule.""" + pass + + # We need to provide at least an initial state if we want agent collector + # to build episodes with state_in_ and state_out_ + def get_initial_state(self): + return [self.state_space.sample()] + + self.model = _fake_model(self.state_space, self.config) + + self.view_requirements = dict( + super()._get_default_view_requirements(), **self.model.view_requirements + ) + + @override(Policy) + def get_initial_state(self): + return self.model.get_initial_state() + + @override(Policy) + def is_recurrent(self): + return True + + @override(Policy) + def compute_actions_from_input_dict( + self, input_dict, explore=None, timestep=None, **kwargs + ): + ts = input_dict["t"] + print(ts) + # Always return [episodeID, envID] as actions. + actions = np.array( + [ + [ + input_dict[SampleBatch.AGENT_INDEX][i], + input_dict[SampleBatch.EPS_ID][i], + input_dict["env_id"][i], + ] + for i, _ in enumerate(input_dict["obs"]) + ] + ) + states = [np.array([[ts[i]] for i in range(len(input_dict["obs"]))])] + self.global_timestep += 1 + return actions, states, {} + + @override(Policy) + def postprocess_trajectory( + self, sample_batch, other_agent_batches=None, episode=None + ): + sample_batch["3xobs"] = sample_batch["obs"] * 3.0 + return sample_batch diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/memory_leaking_policy.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/memory_leaking_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..3a5fa13ed509169a4b959d6ef81517bc64675ce2 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/memory_leaking_policy.py @@ -0,0 +1,60 @@ +# @OldAPIStack +import gymnasium as gym + +from ray.rllib.examples._old_api_stack.policy.random_policy import RandomPolicy +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import AlgorithmConfigDict + + +class MemoryLeakingPolicy(RandomPolicy): + """A Policy that leaks very little memory. + + Useful for proving that our memory-leak tests can catch the + slightest leaks. + """ + + def __init__( + self, + observation_space: gym.Space, + action_space: gym.Space, + config: AlgorithmConfigDict, + ): + super().__init__(observation_space, action_space, config) + self._leakage_size = config.get("leakage_size", "small") + self._leak = [] + + @override(RandomPolicy) + def compute_actions(self, *args, **kwargs): + # Leak. + if self._leakage_size == "small": + self._leak.append(1.5) + else: + self._leak.append([1.5] * 100) + return super().compute_actions(*args, **kwargs) + + @override(RandomPolicy) + def compute_actions_from_input_dict(self, *args, **kwargs): + # Leak. + if self._leakage_size == "small": + self._leak.append(1) + else: + self._leak.append([1] * 100) + return super().compute_actions_from_input_dict(*args, **kwargs) + + @override(RandomPolicy) + def learn_on_batch(self, samples): + # Leak. + if self._leakage_size == "small": + self._leak.append(False) + else: + self._leak.append([False] * 100) + return super().learn_on_batch(samples) + + @override(RandomPolicy) + def compute_log_likelihoods(self, *args, **kwargs): + # Leak. + if self._leakage_size == "small": + self._leak.append("test") + else: + self._leak.append(["test"] * 100) + return super().compute_log_likelihoods(*args, **kwargs) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/random_policy.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/random_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c410ba0ec464e73fe380741180e71b56c9967a5b --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/random_policy.py @@ -0,0 +1,101 @@ +# @OldAPIStack +from gymnasium.spaces import Box +import numpy as np +import random +import tree # pip install dm_tree +from typing import ( + List, + Optional, + Union, +) + +from ray.rllib.policy.policy import Policy +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import ModelWeights, TensorStructType, TensorType + + +class RandomPolicy(Policy): + """Hand-coded policy that returns random actions.""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + # Whether for compute_actions, the bounds given in action_space + # should be ignored (default: False). This is to test action-clipping + # and any Env's reaction to bounds breaches. + if self.config.get("ignore_action_bounds", False) and isinstance( + self.action_space, Box + ): + self.action_space_for_sampling = Box( + -float("inf"), + float("inf"), + shape=self.action_space.shape, + dtype=self.action_space.dtype, + ) + else: + self.action_space_for_sampling = self.action_space + + @override(Policy) + def init_view_requirements(self): + super().init_view_requirements() + # Disable for_training and action attributes for SampleBatch.INFOS column + # since it can not be properly batched. + vr = self.view_requirements[SampleBatch.INFOS] + vr.used_for_training = False + vr.used_for_compute_actions = False + + @override(Policy) + def compute_actions( + self, + obs_batch: Union[List[TensorStructType], TensorStructType], + state_batches: Optional[List[TensorType]] = None, + prev_action_batch: Union[List[TensorStructType], TensorStructType] = None, + prev_reward_batch: Union[List[TensorStructType], TensorStructType] = None, + **kwargs, + ): + # Alternatively, a numpy array would work here as well. + # e.g.: np.array([random.choice([0, 1])] * len(obs_batch)) + obs_batch_size = len(tree.flatten(obs_batch)[0]) + return ( + [self.action_space_for_sampling.sample() for _ in range(obs_batch_size)], + [], + {}, + ) + + @override(Policy) + def learn_on_batch(self, samples): + """No learning.""" + return {} + + @override(Policy) + def compute_log_likelihoods( + self, + actions, + obs_batch, + state_batches=None, + prev_action_batch=None, + prev_reward_batch=None, + **kwargs, + ): + return np.array([random.random()] * len(obs_batch)) + + @override(Policy) + def get_weights(self) -> ModelWeights: + """No weights to save.""" + return {} + + @override(Policy) + def set_weights(self, weights: ModelWeights) -> None: + """No weights to set.""" + pass + + @override(Policy) + def _get_dummy_batch_from_view_requirements(self, batch_size: int = 1): + return SampleBatch( + { + SampleBatch.OBS: tree.map_structure( + lambda s: s[None], self.observation_space.sample() + ), + } + ) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/rock_paper_scissors_dummies.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/rock_paper_scissors_dummies.py new file mode 100644 index 0000000000000000000000000000000000000000..dbaa0e401038303a30e6520d5228e1512448c0d7 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/rock_paper_scissors_dummies.py @@ -0,0 +1,96 @@ +# @OldAPIStack +import gymnasium as gym +import numpy as np +import random +from ray.rllib.policy.policy import Policy +from ray.rllib.policy.view_requirement import ViewRequirement + +ROCK = 0 +PAPER = 1 +SCISSORS = 2 + + +class AlwaysSameHeuristic(Policy): + """Pick a random move and stick with it for the entire episode.""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.exploration = self._create_exploration() + self.view_requirements.update( + { + "state_in_0": ViewRequirement( + "state_out_0", + shift=-1, + space=gym.spaces.Box(ROCK, SCISSORS, shape=(1,), dtype=np.int32), + ) + } + ) + + def get_initial_state(self): + return [random.choice([ROCK, PAPER, SCISSORS])] + + def is_recurrent(self) -> bool: + return True + + def compute_actions( + self, + obs_batch, + state_batches=None, + prev_action_batch=None, + prev_reward_batch=None, + info_batch=None, + episodes=None, + **kwargs + ): + return [state_batches[0][0] for x in obs_batch], state_batches, {} + + +class BeatLastHeuristic(Policy): + """Play the move that would beat the last move of the opponent.""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.exploration = self._create_exploration() + + def compute_actions( + self, + obs_batch, + state_batches=None, + prev_action_batch=None, + prev_reward_batch=None, + info_batch=None, + episodes=None, + **kwargs + ): + def successor(x): + # Make this also work w/o one-hot preprocessing. + if isinstance(self.observation_space, gym.spaces.Discrete): + if x == ROCK: + return PAPER + elif x == PAPER: + return SCISSORS + elif x == SCISSORS: + return ROCK + else: + return random.choice([ROCK, PAPER, SCISSORS]) + # One-hot (auto-preprocessed) inputs. + else: + if x[ROCK] == 1: + return PAPER + elif x[PAPER] == 1: + return SCISSORS + elif x[SCISSORS] == 1: + return ROCK + elif x[-1] == 1: + return random.choice([ROCK, PAPER, SCISSORS]) + + return [successor(x) for x in obs_batch], [], {} + + def learn_on_batch(self, samples): + pass + + def get_weights(self): + pass + + def set_weights(self, weights): + pass diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__init__.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8cfe32330adf2aa81bb9c1cfe7aa2f542882ab2c Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/cartpole_dqn_export.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/cartpole_dqn_export.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..214d20f793663fc0126d1c6cb59c013403485e57 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/cartpole_dqn_export.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/checkpoint_by_custom_criteria.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/checkpoint_by_custom_criteria.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89b96e775b04257672b2808794d3d89b0a7aeb6c Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/checkpoint_by_custom_criteria.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/continue_training_from_checkpoint.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/continue_training_from_checkpoint.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a85102a42217805232cc9e12ae0535eafa43f84 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/continue_training_from_checkpoint.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/onnx_tf.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/onnx_tf.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e073eeaec3ccc3c55e33bdad41824b1fa7f4ba3 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/onnx_tf.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/onnx_torch.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/onnx_torch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..854e10d42d8f543687c49fc74da7f9389a68a70b Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/onnx_torch.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/onnx_torch_lstm.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/onnx_torch_lstm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1dacacf5347ee8adc2072a2452343c123635439b Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/onnx_torch_lstm.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/restore_1_of_n_agents_from_checkpoint.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/restore_1_of_n_agents_from_checkpoint.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fd5161a78b83c7a7e58659c7febe7b8c06fd7b2 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/restore_1_of_n_agents_from_checkpoint.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/cartpole_dqn_export.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/cartpole_dqn_export.py new file mode 100644 index 0000000000000000000000000000000000000000..86a623d012d9a1493d9cdd5481ad91e1932eae9d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/cartpole_dqn_export.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python + +# @OldAPIStack + +import numpy as np +import os +import ray + +from ray.rllib.policy.policy import Policy +from ray.rllib.utils.framework import try_import_tf +from ray.tune.registry import get_trainable_cls + +tf1, tf, tfv = try_import_tf() + +ray.init() + + +def train_and_export_policy_and_model(algo_name, num_steps, model_dir, ckpt_dir): + cls = get_trainable_cls(algo_name) + config = cls.get_default_config() + config.api_stack( + enable_rl_module_and_learner=False, + enable_env_runner_and_connector_v2=False, + ) + # This Example is only for tf. + config.framework("tf") + # Set exporting native (DL-framework) model files to True. + config.export_native_model_files = True + config.env = "CartPole-v1" + alg = config.build() + for _ in range(num_steps): + alg.train() + + # Export Policy checkpoint. + alg.export_policy_checkpoint(ckpt_dir) + # Export tensorflow keras Model for online serving + alg.export_policy_model(model_dir) + + +def restore_saved_model(export_dir): + signature_key = ( + tf1.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY + ) + g = tf1.Graph() + with g.as_default(): + with tf1.Session(graph=g) as sess: + meta_graph_def = tf1.saved_model.load( + sess, [tf1.saved_model.tag_constants.SERVING], export_dir + ) + print("Model restored!") + print("Signature Def Information:") + print(meta_graph_def.signature_def[signature_key]) + print("You can inspect the model using TensorFlow SavedModel CLI.") + print("https://www.tensorflow.org/guide/saved_model") + + +def restore_policy_from_checkpoint(export_dir): + # Load the model from the checkpoint. + policy = Policy.from_checkpoint(export_dir) + # Perform a dummy (CartPole) forward pass. + test_obs = np.array([0.1, 0.2, 0.3, 0.4]) + results = policy.compute_single_action(test_obs) + # Check results for correctness. + assert len(results) == 3 + assert results[0].shape == () # pure single action (int) + assert results[1] == [] # RNN states + assert results[2]["action_dist_inputs"].shape == (2,) # categorical inputs + + +if __name__ == "__main__": + algo = "PPO" + model_dir = os.path.join(ray._private.utils.get_user_temp_dir(), "model_export_dir") + ckpt_dir = os.path.join(ray._private.utils.get_user_temp_dir(), "ckpt_export_dir") + num_steps = 1 + train_and_export_policy_and_model(algo, num_steps, model_dir, ckpt_dir) + restore_saved_model(model_dir) + restore_policy_from_checkpoint(ckpt_dir) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/checkpoint_by_custom_criteria.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/checkpoint_by_custom_criteria.py new file mode 100644 index 0000000000000000000000000000000000000000..33204e52d5e94c601e27972b3c3c0ce2f5d5cb3a --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/checkpoint_by_custom_criteria.py @@ -0,0 +1,146 @@ +"""Example extracting a checkpoint from n trials using one or more custom criteria. + +This example: + - runs a CartPole experiment with three different learning rates (three tune + "trials"). During the experiment, for each trial, we create a checkpoint at each + iteration. + - at the end of the experiment, we compare the trials and pick the one that + performed best, based on the criterion: Lowest episode count per single iteration + (for CartPole, a low episode count means the episodes are very long and thus the + reward is also very high). + - from that best trial (with the lowest episode count), we then pick those + checkpoints that a) have the lowest policy loss (good) and b) have the highest value + function loss (bad). + + +How to run this script +---------------------- +`python [script file name].py --enable-new-api-stack` + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +In the console output, you can see the performance of the three different learning +rates used here: + ++-----------------------------+------------+-----------------+--------+--------+ +| Trial name | status | loc | lr | iter | +|-----------------------------+------------+-----------------+--------+--------+ +| PPO_CartPole-v1_d7dbe_00000 | TERMINATED | 127.0.0.1:98487 | 0.01 | 17 | +| PPO_CartPole-v1_d7dbe_00001 | TERMINATED | 127.0.0.1:98488 | 0.001 | 8 | +| PPO_CartPole-v1_d7dbe_00002 | TERMINATED | 127.0.0.1:98489 | 0.0001 | 9 | ++-----------------------------+------------+-----------------+--------+--------+ + ++------------------+-------+----------+----------------------+----------------------+ +| total time (s) | ts | reward | episode_reward_max | episode_reward_min | +|------------------+-------+----------+----------------------+----------------------+ +| 28.1068 | 39797 | 151.11 | 500 | 12 | +| 13.304 | 18728 | 158.91 | 500 | 15 | +| 14.8848 | 21069 | 167.36 | 500 | 13 | ++------------------+-------+----------+----------------------+----------------------+ + ++--------------------+ +| episode_len_mean | +|--------------------| +| 151.11 | +| 158.91 | +| 167.36 | ++--------------------+ +""" + +from ray import tune +from ray.rllib.core import DEFAULT_MODULE_ID +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + LEARNER_RESULTS, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls + +parser = add_rllib_example_script_args( + default_reward=450.0, default_timesteps=100000, default_iters=200 +) + + +if __name__ == "__main__": + args = parser.parse_args() + + # Force-set `args.checkpoint_freq` to 1. + args.checkpoint_freq = 1 + + # Simple generic config. + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment("CartPole-v1") + # Run 3 trials, each w/ a different learning rate. + .training(lr=tune.grid_search([0.01, 0.001, 0.0001]), train_batch_size=2341) + ) + # Run tune for some iterations and generate checkpoints. + results = run_rllib_example_script_experiment(base_config, args) + + # Get the best of the 3 trials by using some metric. + # NOTE: Choosing the min `episodes_this_iter` automatically picks the trial + # with the best performance (over the entire run (scope="all")): + # The fewer episodes, the longer each episode lasted, the more reward we + # got each episode. + # Setting scope to "last", "last-5-avg", or "last-10-avg" will only compare + # (using `mode=min|max`) the average values of the last 1, 5, or 10 + # iterations with each other, respectively. + # Setting scope to "avg" will compare (using `mode`=min|max) the average + # values over the entire run. + metric = "env_runners/num_episodes" + # notice here `scope` is `all`, meaning for each trial, + # all results (not just the last one) will be examined. + best_result = results.get_best_result(metric=metric, mode="min", scope="all") + value_best_metric = best_result.metrics_dataframe[metric].min() + best_return_best = best_result.metrics_dataframe[ + f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}" + ].max() + print( + f"Best trial was the one with lr={best_result.metrics['config']['lr']}. " + f"Reached lowest episode count ({value_best_metric}) in a single iteration and " + f"an average return of {best_return_best}." + ) + + # Confirm, we picked the right trial. + + assert ( + value_best_metric + == results.get_dataframe(filter_metric=metric, filter_mode="min")[metric].min() + ) + + # Get the best checkpoints from the trial, based on different metrics. + # Checkpoint with the lowest policy loss value: + if args.enable_new_api_stack: + policy_loss_key = f"{LEARNER_RESULTS}/{DEFAULT_MODULE_ID}/policy_loss" + else: + policy_loss_key = "info/learner/default_policy/learner_stats/policy_loss" + best_result = results.get_best_result(metric=policy_loss_key, mode="min") + ckpt = best_result.checkpoint + lowest_policy_loss = best_result.metrics_dataframe[policy_loss_key].min() + print(f"Checkpoint w/ lowest policy loss ({lowest_policy_loss}): {ckpt}") + + # Checkpoint with the highest value-function loss: + if args.enable_new_api_stack: + vf_loss_key = f"{LEARNER_RESULTS}/{DEFAULT_MODULE_ID}/vf_loss" + else: + vf_loss_key = "info/learner/default_policy/learner_stats/vf_loss" + best_result = results.get_best_result(metric=vf_loss_key, mode="max") + ckpt = best_result.checkpoint + highest_value_fn_loss = best_result.metrics_dataframe[vf_loss_key].max() + print(f"Checkpoint w/ highest value function loss: {ckpt}") + print(f"Highest value function loss: {highest_value_fn_loss}") diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/continue_training_from_checkpoint.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/continue_training_from_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..6fff3d43287844a56a94307561666133698afabd --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/continue_training_from_checkpoint.py @@ -0,0 +1,268 @@ +"""Example showing how to restore an Algorithm from a checkpoint and resume training. + +Use the setup shown in this script if your experiments tend to crash after some time, +and you would therefore like to make your setup more robust and fault-tolerant. + +This example: + - runs a single- or multi-agent CartPole experiment (for multi-agent, we use + different learning rates) thereby checkpointing the state of the Algorithm every n + iterations. + - stops the experiment due to an expected crash in the algorithm's main process + after a certain number of iterations. + - just for testing purposes, restores the entire algorithm from the latest + checkpoint and checks, whether the state of the restored algo exactly match the + state of the crashed one. + - then continues training with the restored algorithm until the desired final + episode return is reached. + + +How to run this script +---------------------- +`python [script file name].py --enable-new-api-stack --num-agents=[0 or 2] +--stop-reward-crash=[the episode return after which the algo should crash] +--stop-reward=[the final episode return to achieve after(!) restoration from the +checkpoint] +` + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +First, you should see the initial tune.Tuner do it's thing: + +Trial status: 1 RUNNING +Current time: 2024-06-03 12:03:39. Total running time: 30s +Logical resource usage: 3.0/12 CPUs, 0/0 GPUs +╭──────────────────────────────────────────────────────────────────────── +│ Trial name status iter total time (s) +├──────────────────────────────────────────────────────────────────────── +│ PPO_CartPole-v1_7b1eb_00000 RUNNING 6 15.362 +╰──────────────────────────────────────────────────────────────────────── +───────────────────────────────────────────────────────────────────────╮ +..._sampled_lifetime ..._trained_lifetime ...episodes_lifetime │ +───────────────────────────────────────────────────────────────────────┤ + 24000 24000 340 │ +───────────────────────────────────────────────────────────────────────╯ +... + +then, you should see the experiment crashing as soon as the `--stop-reward-crash` +has been reached: + +```RuntimeError: Intended crash after reaching trigger return.``` + +At some point, the experiment should resume exactly where it left off (using +the checkpoint and restored Tuner): + +Trial status: 1 RUNNING +Current time: 2024-06-03 12:05:00. Total running time: 1min 0s +Logical resource usage: 3.0/12 CPUs, 0/0 GPUs +╭──────────────────────────────────────────────────────────────────────── +│ Trial name status iter total time (s) +├──────────────────────────────────────────────────────────────────────── +│ PPO_CartPole-v1_7b1eb_00000 RUNNING 27 66.1451 +╰──────────────────────────────────────────────────────────────────────── +───────────────────────────────────────────────────────────────────────╮ +..._sampled_lifetime ..._trained_lifetime ...episodes_lifetime │ +───────────────────────────────────────────────────────────────────────┤ + 108000 108000 531 │ +───────────────────────────────────────────────────────────────────────╯ + +And if you are using the `--as-test` option, you should see a finel message: + +``` +`env_runners/episode_return_mean` of 500.0 reached! ok +``` +""" +import re +import time + +from ray import train, tune +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig +from ray.rllib.algorithms.callbacks import DefaultCallbacks +from ray.rllib.examples.envs.classes.multi_agent import MultiAgentCartPole +from ray.rllib.policy.policy import PolicySpec +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + check_learning_achieved, +) +from ray.tune.registry import get_trainable_cls, register_env +from ray.air.integrations.wandb import WandbLoggerCallback + + +parser = add_rllib_example_script_args( + default_reward=500.0, default_timesteps=10000000, default_iters=2000 +) +parser.add_argument( + "--stop-reward-crash", + type=float, + default=200.0, + help="Mean episode return after which the Algorithm should crash.", +) +# By default, set `args.checkpoint_freq` to 1 and `args.checkpoint_at_end` to True. +parser.set_defaults(checkpoint_freq=1, checkpoint_at_end=True) + + +class CrashAfterNIters(DefaultCallbacks): + """Callback that makes the algo crash after a certain avg. return is reached.""" + + def __init__(self): + super().__init__() + # We have to delay crashing by one iteration just so the checkpoint still + # gets created by Tune after(!) we have reached the trigger avg. return. + self._should_crash = False + + def on_train_result(self, *, algorithm, metrics_logger, result, **kwargs): + # We had already reached the mean-return to crash, the last checkpoint written + # (the one from the previous iteration) should yield that exact avg. return. + if self._should_crash: + raise RuntimeError("Intended crash after reaching trigger return.") + # Reached crashing criterion, crash on next iteration. + elif result[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] >= args.stop_reward_crash: + print( + "Reached trigger return of " + f"{result[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN]}" + ) + self._should_crash = True + + +if __name__ == "__main__": + args = parser.parse_args() + + register_env( + "ma_cart", lambda cfg: MultiAgentCartPole({"num_agents": args.num_agents}) + ) + + # Simple generic config. + config = ( + get_trainable_cls(args.algo) + .get_default_config() + .api_stack( + enable_rl_module_and_learner=args.enable_new_api_stack, + enable_env_runner_and_connector_v2=args.enable_new_api_stack, + ) + .environment("CartPole-v1" if args.num_agents == 0 else "ma_cart") + .env_runners(create_env_on_local_worker=True) + .training(lr=0.0001) + .callbacks(CrashAfterNIters) + ) + + # Tune config. + # Need a WandB callback? + tune_callbacks = [] + if args.wandb_key: + project = args.wandb_project or ( + args.algo.lower() + "-" + re.sub("\\W+", "-", str(config.env).lower()) + ) + tune_callbacks.append( + WandbLoggerCallback( + api_key=args.wandb_key, + project=args.wandb_project, + upload_checkpoints=False, + **({"name": args.wandb_run_name} if args.wandb_run_name else {}), + ) + ) + + # Setup multi-agent, if required. + if args.num_agents > 0: + config.multi_agent( + policies={ + f"p{aid}": PolicySpec( + config=AlgorithmConfig.overrides( + lr=5e-5 + * (aid + 1), # agent 1 has double the learning rate as 0. + ) + ) + for aid in range(args.num_agents) + }, + policy_mapping_fn=lambda aid, *a, **kw: f"p{aid}", + ) + + # Define some stopping criterion. Note that this criterion is an avg episode return + # to be reached. The stop criterion does not consider the built-in crash we are + # triggering through our callback. + stop = { + f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": args.stop_reward, + } + + # Run tune for some iterations and generate checkpoints. + tuner = tune.Tuner( + trainable=config.algo_class, + param_space=config, + run_config=train.RunConfig( + callbacks=tune_callbacks, + checkpoint_config=train.CheckpointConfig( + checkpoint_frequency=args.checkpoint_freq, + checkpoint_at_end=args.checkpoint_at_end, + ), + stop=stop, + ), + ) + tuner_results = tuner.fit() + + # Perform a very quick test to make sure our algo (upon restoration) did not lose + # its ability to perform well in the env. + # - Extract the best checkpoint. + metric = f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}" + best_result = tuner_results.get_best_result(metric=metric, mode="max") + assert ( + best_result.metrics[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] + >= args.stop_reward_crash + ) + # - Change our config, such that the restored algo will have an env on the local + # EnvRunner (to perform evaluation) and won't crash anymore (remove the crashing + # callback). + config.callbacks(None) + # Rebuild the algorithm (just for testing purposes). + test_algo = config.build() + # Load algo's state from best checkpoint. + test_algo.restore(best_result.checkpoint) + # Perform some checks on the restored state. + assert test_algo.training_iteration > 0 + # Evaluate on the restored algorithm. + test_eval_results = test_algo.evaluate() + assert ( + test_eval_results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] + >= args.stop_reward_crash + ), test_eval_results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] + # Train one iteration to make sure, the performance does not collapse (e.g. due + # to the optimizer weights not having been restored properly). + test_results = test_algo.train() + assert ( + test_results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] >= args.stop_reward_crash + ), test_results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] + # Stop the test algorithm again. + test_algo.stop() + + # Create a new Tuner from the existing experiment path (which contains the tuner's + # own checkpoint file). Note that even the WandB logging will be continued without + # creating a new WandB run name. + restored_tuner = tune.Tuner.restore( + path=tuner_results.experiment_path, + trainable=config.algo_class, + param_space=config, + # Important to set this to True b/c the previous trial had failed (due to our + # `CrashAfterNIters` callback). + resume_errored=True, + ) + # Continue the experiment exactly where we left off. + tuner_results = restored_tuner.fit() + + # Not sure, whether this is really necessary, but we have observed the WandB + # logger sometimes not logging some of the last iterations. This sleep here might + # give it enough time to do so. + time.sleep(20) + + if args.as_test: + check_learning_achieved(tuner_results, args.stop_reward, metric=metric) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/onnx_tf.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/onnx_tf.py new file mode 100644 index 0000000000000000000000000000000000000000..19fb7f3760328985de89edba7aee837cd569895f --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/onnx_tf.py @@ -0,0 +1,91 @@ +# @OldAPIStack +import argparse +import numpy as np +import onnxruntime +import os +import shutil + +import ray +import ray.rllib.algorithms.ppo as ppo + +parser = argparse.ArgumentParser() + +parser.add_argument( + "--framework", + choices=["tf", "tf2"], + default="tf2", + help="The TF framework specifier (either 'tf' or 'tf2').", +) + + +if __name__ == "__main__": + + args = parser.parse_args() + + # Configure our PPO Algorithm. + config = ( + ppo.PPOConfig() + .api_stack( + enable_env_runner_and_connector_v2=False, + enable_rl_module_and_learner=False, + ) + .env_runners(num_env_runners=1) + .framework(args.framework) + ) + + outdir = "export_tf" + if os.path.exists(outdir): + shutil.rmtree(outdir) + + np.random.seed(1234) + + # We will run inference with this test batch + test_data = { + "obs": np.random.uniform(0, 1.0, size=(10, 4)).astype(np.float32), + } + + # Start Ray and initialize a PPO Algorithm + ray.init() + algo = config.build(env="CartPole-v1") + + # You could train the model here via: + # algo.train() + + # Let's run inference on the tensorflow model + policy = algo.get_policy() + result_tf, _ = policy.model(test_data) + + # Evaluate tensor to fetch numpy array. + if args.framework == "tf": + with policy.get_session().as_default(): + result_tf = result_tf.eval() + + # This line will export the model to ONNX. + policy.export_model(outdir, onnx=11) + # Equivalent to: + # algo.export_policy_model(outdir, onnx=11) + + # Import ONNX model. + exported_model_file = os.path.join(outdir, "model.onnx") + + # Start an inference session for the ONNX model + session = onnxruntime.InferenceSession(exported_model_file, None) + + # Pass the same test batch to the ONNX model (rename to match tensor names) + onnx_test_data = {f"default_policy/{k}:0": v for k, v in test_data.items()} + + # Tf2 model stored differently from tf (static graph) model. + if args.framework == "tf2": + result_onnx = session.run(["fc_out"], {"observations": test_data["obs"]}) + else: + result_onnx = session.run( + ["default_policy/model/fc_out/BiasAdd:0"], + onnx_test_data, + ) + + # These results should be equal! + print("TENSORFLOW", result_tf) + print("ONNX", result_onnx) + + assert np.allclose(result_tf, result_onnx), "Model outputs are NOT equal. FAILED" + print("Model outputs are equal. PASSED") diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/onnx_torch.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/onnx_torch.py new file mode 100644 index 0000000000000000000000000000000000000000..b7d39cc9225a79f73e9077c9207ed2f39237068d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/onnx_torch.py @@ -0,0 +1,79 @@ +# @OldAPIStack + +from packaging.version import Version +import numpy as np +import ray +import ray.rllib.algorithms.ppo as ppo +import onnxruntime +import os +import shutil +import torch + +if __name__ == "__main__": + # Configure our PPO Algorithm. + config = ( + ppo.PPOConfig() + .api_stack( + enable_env_runner_and_connector_v2=False, + enable_rl_module_and_learner=False, + ) + .env_runners(num_env_runners=1) + .framework("torch") + ) + + outdir = "export_torch" + if os.path.exists(outdir): + shutil.rmtree(outdir) + + np.random.seed(1234) + + # We will run inference with this test batch + test_data = { + "obs": np.random.uniform(0, 1.0, size=(10, 4)).astype(np.float32), + "state_ins": np.array([0.0], dtype=np.float32), + } + + # Start Ray and initialize a PPO Algorithm. + ray.init() + algo = config.build(env="CartPole-v1") + + # You could train the model here + # algo.train() + + # Let's run inference on the torch model + policy = algo.get_policy() + result_pytorch, _ = policy.model( + { + "obs": torch.tensor(test_data["obs"]), + } + ) + + # Evaluate tensor to fetch numpy array + result_pytorch = result_pytorch.detach().numpy() + + # This line will export the model to ONNX. + policy.export_model(outdir, onnx=11) + # Equivalent to: + # algo.export_policy_model(outdir, onnx=11) + + # Import ONNX model. + exported_model_file = os.path.join(outdir, "model.onnx") + + # Start an inference session for the ONNX model + session = onnxruntime.InferenceSession(exported_model_file, None) + + # Pass the same test batch to the ONNX model + if Version(torch.__version__) < Version("1.9.0"): + # In torch < 1.9.0 the second input/output name gets mixed up + test_data["state_outs"] = test_data.pop("state_ins") + + result_onnx = session.run(["output"], test_data) + + # These results should be equal! + print("PYTORCH", result_pytorch) + print("ONNX", result_onnx) + + assert np.allclose( + result_pytorch, result_onnx + ), "Model outputs are NOT equal. FAILED" + print("Model outputs are equal. PASSED") diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/onnx_torch_lstm.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/onnx_torch_lstm.py new file mode 100644 index 0000000000000000000000000000000000000000..d95a282a3a30d036afe39573850661c860df2740 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/onnx_torch_lstm.py @@ -0,0 +1,136 @@ +# @OldAPIStack + +import numpy as np +import onnxruntime + +import ray +import ray.rllib.algorithms.ppo as ppo +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.test_utils import add_rllib_example_script_args, check +from ray.rllib.utils.torch_utils import convert_to_torch_tensor + +torch, _ = try_import_torch() + +parser = add_rllib_example_script_args() +parser.set_defaults(num_env_runners=1) + + +class ONNXCompatibleWrapper(torch.nn.Module): + def __init__(self, original_model): + super(ONNXCompatibleWrapper, self).__init__() + self.original_model = original_model + + def forward(self, a, b0, b1, c): + # Convert the separate tensor inputs back into the list format + # expected by the original model's forward method. + b = [b0, b1] + ret = self.original_model({"obs": a}, b, c) + # results, state_out_0, state_out_1 + return ret[0], ret[1][0], ret[1][1] + + +if __name__ == "__main__": + args = parser.parse_args() + + assert ( + not args.enable_new_api_stack + ), "Must NOT set --enable-new-api-stack when running this script!" + + ray.init(local_mode=args.local_mode) + + # Configure our PPO Algorithm. + config = ( + ppo.PPOConfig() + # ONNX is not supported by RLModule API yet. + .api_stack( + enable_rl_module_and_learner=args.enable_new_api_stack, + enable_env_runner_and_connector_v2=args.enable_new_api_stack, + ) + .environment("CartPole-v1") + .env_runners(num_env_runners=args.num_env_runners) + .training(model={"use_lstm": True}) + ) + + B = 3 + T = 5 + LSTM_CELL = 256 + + # Input data for a python inference forward call. + test_data_python = { + "obs": np.random.uniform(0, 1.0, size=(B * T, 4)).astype(np.float32), + "state_ins": [ + np.random.uniform(0, 1.0, size=(B, LSTM_CELL)).astype(np.float32), + np.random.uniform(0, 1.0, size=(B, LSTM_CELL)).astype(np.float32), + ], + "seq_lens": np.array([T] * B, np.float32), + } + # Input data for the ONNX session. + test_data_onnx = { + "obs": test_data_python["obs"], + "state_in_0": test_data_python["state_ins"][0], + "state_in_1": test_data_python["state_ins"][1], + "seq_lens": test_data_python["seq_lens"], + } + + # Input data for compiling the ONNX model. + test_data_onnx_input = convert_to_torch_tensor(test_data_onnx) + + # Initialize a PPO Algorithm. + algo = config.build() + + # You could train the model here + # algo.train() + + # Let's run inference on the torch model + policy = algo.get_policy() + result_pytorch, _ = policy.model( + { + "obs": torch.tensor(test_data_python["obs"]), + }, + [ + torch.tensor(test_data_python["state_ins"][0]), + torch.tensor(test_data_python["state_ins"][1]), + ], + torch.tensor(test_data_python["seq_lens"]), + ) + + # Evaluate tensor to fetch numpy array + result_pytorch = result_pytorch.detach().numpy() + + # Wrap the actual ModelV2 with the torch wrapper above to make this all work with + # LSTMs (extra `state` in- and outputs and `seq_lens` inputs). + onnx_compatible = ONNXCompatibleWrapper(policy.model) + exported_model_file = "model.onnx" + input_names = [ + "obs", + "state_in_0", + "state_in_1", + "seq_lens", + ] + + # This line will export the model to ONNX. + torch.onnx.export( + onnx_compatible, + tuple(test_data_onnx_input[n] for n in input_names), + exported_model_file, + export_params=True, + opset_version=11, + do_constant_folding=True, + input_names=input_names, + output_names=[ + "output", + "state_out_0", + "state_out_1", + ], + dynamic_axes={k: {0: "batch_size"} for k in input_names}, + ) + # Start an inference session for the ONNX model. + session = onnxruntime.InferenceSession(exported_model_file, None) + result_onnx = session.run(["output"], test_data_onnx) + + # These results should be equal! + print("PYTORCH", result_pytorch) + print("ONNX", result_onnx[0]) + + check(result_pytorch, result_onnx[0]) + print("Model outputs are equal. PASSED") diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/restore_1_of_n_agents_from_checkpoint.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/restore_1_of_n_agents_from_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..737b12ee313eeed42bbf9804b8d8b1edca4612ec --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/restore_1_of_n_agents_from_checkpoint.py @@ -0,0 +1,160 @@ +"""An example script showing how to load module weights for 1 of n agents +from checkpoint. + +This example: + - Runs a multi-agent `Pendulum-v1` experiment with >= 2 policies. + - Saves a checkpoint of the `MultiRLModule` used every `--checkpoint-freq` + iterations. + - Stops the experiments after the agents reach a combined return of -800. + - Picks the best checkpoint by combined return and restores policy 0 from it. + - Runs a second experiment with the restored `RLModule` for policy 0 and + a fresh `RLModule` for the other policies. + - Stops the second experiment after the agents reach a combined return of -800. + + +How to run this script +---------------------- +`python [script file name].py --enable-new-api-stack --num-agents=2 +--checkpoint-freq=20 --checkpoint-at-end` + +Control the number of agents and policies (RLModules) via --num-agents and +--num-policies. + +Control the number of checkpoints by setting `--checkpoint-freq` to a value > 0. +Note that the checkpoint frequency is per iteration and this example needs at +least a single checkpoint to load the RLModule weights for policy 0. +If `--checkpoint-at-end` is set, a checkpoint will be saved at the end of the +experiment. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +You should expect a reward of -400.0 eventually being achieved by a simple +single PPO policy (no tuning, just using RLlib's default settings). In the +second run of the experiment, the MultiRLModule weights for policy 0 are +restored from the checkpoint of the first run. The reward for a single agent +should be -400.0 again, but the training time should be shorter (around 30 +iterations instead of 190). +""" + +import os +from ray.air.constants import TRAINING_ITERATION +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec +from ray.rllib.examples.envs.classes.multi_agent import MultiAgentPendulum +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + NUM_ENV_STEPS_SAMPLED_LIFETIME, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls, register_env + +parser = add_rllib_example_script_args( + default_iters=200, + default_timesteps=100000, + default_reward=-400.0, +) +parser.set_defaults( + checkpoint_freq=1, + num_agents=2, +) +# TODO (sven): This arg is currently ignored (hard-set to 2). +parser.add_argument("--num-policies", type=int, default=2) + + +if __name__ == "__main__": + args = parser.parse_args() + + # Register our environment with tune. + if args.num_agents > 1: + register_env( + "env", + lambda _: MultiAgentPendulum(config={"num_agents": args.num_agents}), + ) + else: + raise ValueError( + f"`num_agents` must be > 1, but is {args.num_agents}." + "Read the script docstring for more information." + ) + + assert args.checkpoint_freq > 0, ( + "This example requires at least one checkpoint to load the RLModule " + "weights for policy 0." + ) + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment("env") + .training( + train_batch_size_per_learner=512, + minibatch_size=64, + lambda_=0.1, + gamma=0.95, + lr=0.0003, + vf_clip_param=10.0, + ) + .rl_module( + model_config=DefaultModelConfig(fcnet_activation="relu"), + ) + ) + + # Add a simple multi-agent setup. + if args.num_agents > 0: + base_config.multi_agent( + policies={f"p{i}" for i in range(args.num_agents)}, + policy_mapping_fn=lambda aid, *a, **kw: f"p{aid}", + ) + + # Augment the base config with further settings and train the agents. + results = run_rllib_example_script_experiment(base_config, args) + + # Create an env instance to get the observation and action spaces. + env = MultiAgentPendulum(config={"num_agents": args.num_agents}) + # Get the default module spec from the algorithm config. + module_spec = base_config.get_default_rl_module_spec() + module_spec.model_config = DefaultModelConfig(fcnet_activation="relu") + module_spec.observation_space = env.envs[0].observation_space + module_spec.action_space = env.envs[0].action_space + # Create the module for each policy, but policy 0. + module_specs = {} + for i in range(1, args.num_agents or 1): + module_specs[f"p{i}"] = module_spec + + # Now swap in the RLModule weights for policy 0. + chkpt_path = results.get_best_result().checkpoint.path + p_0_module_state_path = os.path.join(chkpt_path, "learner", "module_state", "p0") + module_spec.load_state_path = p_0_module_state_path + module_specs["p0"] = module_spec + + # Create the MultiRLModule. + multi_rl_module_spec = MultiRLModuleSpec(rl_module_specs=module_specs) + # Define the MultiRLModule in the base config. + base_config.rl_module(rl_module_spec=multi_rl_module_spec) + # We need to re-register the environment when starting a new run. + register_env( + "env", + lambda _: MultiAgentPendulum(config={"num_agents": args.num_agents}), + ) + # Define stopping criteria. + stop = { + f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": -800, + f"{NUM_ENV_STEPS_SAMPLED_LIFETIME}": 20000, + TRAINING_ITERATION: 30, + } + + # Run the experiment again with the restored MultiRLModule. + run_rllib_example_script_experiment(base_config, args, stop=stop) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/curiosity/__init__.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/curiosity/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/curiosity/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/curiosity/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a495e12d5bf7b1a63addfc6e80f1b8a9cb86334 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/curiosity/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/curiosity/__pycache__/count_based_curiosity.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/curiosity/__pycache__/count_based_curiosity.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53fc22480481bc758a0c15eecdcb1fe1c922b449 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/curiosity/__pycache__/count_based_curiosity.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/curiosity/__pycache__/euclidian_distance_based_curiosity.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/curiosity/__pycache__/euclidian_distance_based_curiosity.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4205d82c7f5dcb7b102e218e4b1b2f4f86663a9 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/curiosity/__pycache__/euclidian_distance_based_curiosity.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/curiosity/__pycache__/intrinsic_curiosity_model_based_curiosity.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/curiosity/__pycache__/intrinsic_curiosity_model_based_curiosity.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d32406083edfbba9ed42158e2284ed06a504b1c8 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/curiosity/__pycache__/intrinsic_curiosity_model_based_curiosity.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/curiosity/count_based_curiosity.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/curiosity/count_based_curiosity.py new file mode 100644 index 0000000000000000000000000000000000000000..f7d1aa6e15530b221dfe8b53448ed611178faf90 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/examples/curiosity/count_based_curiosity.py @@ -0,0 +1,137 @@ +"""Example of using a count-based curiosity mechanism to learn in sparse-rewards envs. + +This example: + - demonstrates how to define your own count-based curiosity ConnectorV2 piece + that computes intrinsic rewards based on simple observation counts and adds these + intrinsic rewards to the "main" (extrinsic) rewards. + - shows how this connector piece overrides the main (extrinsic) rewards in the + episode and thus demonstrates how to do reward shaping in general with RLlib. + - shows how to plug this connector piece into your algorithm's config. + - uses Tune and RLlib to learn the env described above and compares 2 + algorithms, one that does use curiosity vs one that does not. + +We use a FrozenLake (sparse reward) environment with a map size of 8x8 and a time step +limit of 14 to make it almost impossible for a non-curiosity based policy to learn. + + +How to run this script +---------------------- +`python [script file name].py --enable-new-api-stack` + +Use the `--no-curiosity` flag to disable curiosity learning and force your policy +to be trained on the task w/o the use of intrinsic rewards. With this option, the +algorithm should NOT succeed. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +In the console output, you can see that only a PPO policy that uses curiosity can +actually learn. + +Policy using count-based curiosity: ++-------------------------------+------------+--------+------------------+ +| Trial name | status | iter | total time (s) | +| | | | | +|-------------------------------+------------+--------+------------------+ +| PPO_FrozenLake-v1_109de_00000 | TERMINATED | 48 | 44.46 | ++-------------------------------+------------+--------+------------------+ ++------------------------+-------------------------+------------------------+ +| episode_return_mean | num_episodes_lifetime | num_env_steps_traine | +| | | d_lifetime | +|------------------------+-------------------------+------------------------| +| 0.99 | 12960 | 194000 | ++------------------------+-------------------------+------------------------+ + +Policy NOT using curiosity: +[DOES NOT LEARN AT ALL] +""" +from ray.rllib.connectors.env_to_module import FlattenObservations +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.examples.connectors.classes.count_based_curiosity import ( + CountBasedCuriosity, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls + +parser = add_rllib_example_script_args( + default_reward=0.99, default_iters=200, default_timesteps=1000000 +) +parser.set_defaults(enable_new_api_stack=True) +parser.add_argument( + "--intrinsic-reward-coeff", + type=float, + default=1.0, + help="The weight with which to multiply intrinsic rewards before adding them to " + "the extrinsic ones (default is 1.0).", +) +parser.add_argument( + "--no-curiosity", + action="store_true", + help="Whether to NOT use count-based curiosity.", +) + +ENV_OPTIONS = { + "is_slippery": False, + # Use this hard-to-solve 8x8 map with lots of holes (H) to fall into and only very + # few valid paths from the starting state (S) to the goal state (G). + "desc": [ + "SFFHFFFH", + "FFFHFFFF", + "FFFHHFFF", + "FFFFFFFH", + "HFFHFFFF", + "HHFHFFHF", + "FFFHFHHF", + "FHFFFFFG", + ], + # Limit the number of steps the agent is allowed to make in the env to + # make it almost impossible to learn without (count-based) curiosity. + "max_episode_steps": 14, +} + + +if __name__ == "__main__": + args = parser.parse_args() + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment( + "FrozenLake-v1", + env_config=ENV_OPTIONS, + ) + .env_runners( + num_envs_per_env_runner=5, + # Flatten discrete observations (into one-hot vectors). + env_to_module_connector=lambda env: FlattenObservations(), + ) + .training( + # The main code in this example: We add the `CountBasedCuriosity` connector + # piece to our Learner connector pipeline. + # This pipeline is fed with collected episodes (either directly from the + # EnvRunners in on-policy fashion or from a replay buffer) and converts + # these episodes into the final train batch. The added piece computes + # intrinsic rewards based on simple observation counts and add them to + # the "main" (extrinsic) rewards. + learner_connector=( + None if args.no_curiosity else lambda *ags, **kw: CountBasedCuriosity() + ), + num_epochs=10, + vf_loss_coeff=0.01, + ) + .rl_module(model_config=DefaultModelConfig(vf_share_layers=True)) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/curiosity/euclidian_distance_based_curiosity.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/curiosity/euclidian_distance_based_curiosity.py new file mode 100644 index 0000000000000000000000000000000000000000..d471c17f18587c5a49f6c20518b0c1bfe9a05797 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/examples/curiosity/euclidian_distance_based_curiosity.py @@ -0,0 +1,127 @@ +"""Example of a euclidian-distance curiosity mechanism to learn in sparse-rewards envs. + +This example: + - demonstrates how to define your own euclidian-distance-based curiosity ConnectorV2 + piece that computes intrinsic rewards based on the delta between incoming + observations and some set of already stored (prior) observations. Thereby, the + further away the incoming observation is from the already stored ones, the higher + its corresponding intrinsic reward. + - shows how this connector piece adds the intrinsic reward to the corresponding + "main" (extrinsic) reward and overrides the value in the "rewards" key in the + episode. It thus demonstrates how to do reward shaping in general with RLlib. + - shows how to plug this connector piece into your algorithm's config. + - uses Tune and RLlib to learn the env described above and compares 2 + algorithms, one that does use curiosity vs one that does not. + +We use the MountainCar-v0 environment, a sparse-reward env that is very hard to learn +for a regular PPO algorithm. + + +How to run this script +---------------------- +`python [script file name].py --enable-new-api-stack` + +Use the `--no-curiosity` flag to disable curiosity learning and force your policy +to be trained on the task w/o the use of intrinsic rewards. With this option, the +algorithm should NOT succeed. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +In the console output, you can see that only a PPO policy that uses curiosity can +actually learn. + +Policy using count-based curiosity: ++-------------------------------+------------+--------+------------------+ +| Trial name | status | iter | total time (s) | +| | | | | +|-------------------------------+------------+--------+------------------+ +| PPO_FrozenLake-v1_109de_00000 | TERMINATED | 48 | 44.46 | ++-------------------------------+------------+--------+------------------+ ++------------------------+-------------------------+------------------------+ +| episode_return_mean | num_episodes_lifetime | num_env_steps_traine | +| | | d_lifetime | +|------------------------+-------------------------+------------------------| +| 0.99 | 12960 | 194000 | ++------------------------+-------------------------+------------------------+ + +Policy NOT using curiosity: +[DOES NOT LEARN AT ALL] +""" +from ray.rllib.connectors.env_to_module import MeanStdFilter +from ray.rllib.examples.connectors.classes.euclidian_distance_based_curiosity import ( + EuclidianDistanceBasedCuriosity, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls + +# TODO (sven): SB3's PPO learns MountainCar-v0 until a reward of ~-110. +# We might have to play around some more with different initializations, etc.. +# to get to these results as well. +parser = add_rllib_example_script_args( + default_reward=-140.0, default_iters=2000, default_timesteps=1000000 +) +parser.set_defaults( + enable_new_api_stack=True, + num_env_runners=4, +) +parser.add_argument( + "--intrinsic-reward-coeff", + type=float, + default=0.0001, + help="The weight with which to multiply intrinsic rewards before adding them to " + "the extrinsic ones (default is 0.0001).", +) +parser.add_argument( + "--no-curiosity", + action="store_true", + help="Whether to NOT use count-based curiosity.", +) + + +if __name__ == "__main__": + args = parser.parse_args() + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment("MountainCar-v0") + .env_runners( + env_to_module_connector=lambda env: MeanStdFilter(), + num_envs_per_env_runner=5, + ) + .training( + # The main code in this example: We add the + # `EuclidianDistanceBasedCuriosity` connector piece to our Learner connector + # pipeline. This pipeline is fed with collected episodes (either directly + # from the EnvRunners in on-policy fashion or from a replay buffer) and + # converts these episodes into the final train batch. The added piece + # computes intrinsic rewards based on simple observation counts and add them + # to the "main" (extrinsic) rewards. + learner_connector=( + None + if args.no_curiosity + else lambda *ags, **kw: EuclidianDistanceBasedCuriosity() + ), + # train_batch_size_per_learner=512, + grad_clip=20.0, + entropy_coeff=0.003, + gamma=0.99, + lr=0.0002, + lambda_=0.98, + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/curiosity/intrinsic_curiosity_model_based_curiosity.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/curiosity/intrinsic_curiosity_model_based_curiosity.py new file mode 100644 index 0000000000000000000000000000000000000000..b70cc89bdbe7dcb179e8233f6ee35469b5a9ec56 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/examples/curiosity/intrinsic_curiosity_model_based_curiosity.py @@ -0,0 +1,313 @@ +"""Example of implementing and training with an intrinsic curiosity model (ICM). + +This type of curiosity-based learning trains a simplified model of the environment +dynamics based on three networks: +1) Embedding observations into latent space ("feature" network). +2) Predicting the action, given two consecutive embedded observations +("inverse" network). +3) Predicting the next embedded obs, given an obs and action +("forward" network). + +The less the ICM is able to predict the actually observed next feature vector, +given obs and action (through the forwards network), the larger the +"intrinsic reward", which will be added to the extrinsic reward of the agent. + +Therefore, if a state transition was unexpected, the agent becomes +"curious" and will further explore this transition leading to better +exploration in sparse rewards environments. + +For more details, see here: +[1] Curiosity-driven Exploration by Self-supervised Prediction +Pathak, Agrawal, Efros, and Darrell - UC Berkeley - ICML 2017. +https://arxiv.org/pdf/1705.05363.pdf + +This example: + - demonstrates how to write a custom RLModule, representing the ICM from the paper + above. Note that this custom RLModule does not belong to any individual agent. + - demonstrates how to write a custom (PPO) TorchLearner that a) adds the ICM to its + MultiRLModule, b) trains the regular PPO Policy plus the ICM module, using the + PPO parent loss and the ICM's RLModule's own loss function. + +We use a FrozenLake (sparse reward) environment with a custom map size of 12x12 and a +hard time step limit of 22 to make it almost impossible for a non-curiosity based +learners to learn a good policy. + + +How to run this script +---------------------- +`python [script file name].py --enable-new-api-stack` + +Use the `--no-curiosity` flag to disable curiosity learning and force your policy +to be trained on the task w/o the use of intrinsic rewards. With this option, the +algorithm should NOT succeed. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +In the console output, you can see that only a PPO policy that uses curiosity can +actually learn. + +Policy using ICM-based curiosity: ++-------------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +|-------------------------------+------------+-----------------+--------+ +| PPO_FrozenLake-v1_52ab2_00000 | TERMINATED | 127.0.0.1:73318 | 392 | ++-------------------------------+------------+-----------------+--------+ ++------------------+--------+----------+--------------------+ +| total time (s) | ts | reward | episode_len_mean | +|------------------+--------+----------+--------------------| +| 236.652 | 786000 | 1.0 | 22.0 | ++------------------+--------+----------+--------------------+ + +Policy NOT using curiosity: +[DOES NOT LEARN AT ALL] +""" +from collections import defaultdict + +import numpy as np + +from ray import tune +from ray.rllib.algorithms.algorithm_config import AlgorithmConfig +from ray.rllib.algorithms.callbacks import DefaultCallbacks +from ray.rllib.connectors.env_to_module import FlattenObservations +from ray.rllib.examples.learners.classes.intrinsic_curiosity_learners import ( + DQNTorchLearnerWithCuriosity, + PPOTorchLearnerWithCuriosity, +) +from ray.rllib.core import DEFAULT_MODULE_ID +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.examples.learners.classes.intrinsic_curiosity_learners import ( + ICM_MODULE_ID, +) +from ray.rllib.examples.rl_modules.classes.intrinsic_curiosity_model_rlm import ( + IntrinsicCuriosityModel, +) +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + NUM_ENV_STEPS_SAMPLED_LIFETIME, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) + +parser = add_rllib_example_script_args( + default_iters=2000, + default_timesteps=10000000, + default_reward=0.9, +) +parser.set_defaults(enable_new_api_stack=True) + + +class MeasureMaxDistanceToStart(DefaultCallbacks): + """Callback measuring the dist of the agent to its start position in FrozenLake-v1. + + Makes the naive assumption that the start position ("S") is in the upper left + corner of the used map. + Uses the MetricsLogger to record the (euclidian) distance value. + """ + + def __init__(self): + super().__init__() + self.max_dists = defaultdict(float) + self.max_dists_lifetime = 0.0 + + def on_episode_step( + self, + *, + episode, + env_runner, + metrics_logger, + env, + env_index, + rl_module, + **kwargs, + ): + num_rows = env.envs[0].unwrapped.nrow + num_cols = env.envs[0].unwrapped.ncol + obs = np.argmax(episode.get_observations(-1)) + row = obs // num_cols + col = obs % num_rows + curr_dist = (row**2 + col**2) ** 0.5 + if curr_dist > self.max_dists[episode.id_]: + self.max_dists[episode.id_] = curr_dist + + def on_episode_end( + self, + *, + episode, + env_runner, + metrics_logger, + env, + env_index, + rl_module, + **kwargs, + ): + # Compute current maximum distance across all running episodes + # (including the just ended one). + max_dist = max(self.max_dists.values()) + metrics_logger.log_value( + key="max_dist_travelled_across_running_episodes", + value=max_dist, + window=10, + ) + if max_dist > self.max_dists_lifetime: + self.max_dists_lifetime = max_dist + del self.max_dists[episode.id_] + + def on_sample_end( + self, + *, + env_runner, + metrics_logger, + samples, + **kwargs, + ): + metrics_logger.log_value( + key="max_dist_travelled_lifetime", + value=self.max_dists_lifetime, + window=1, + ) + + +if __name__ == "__main__": + args = parser.parse_args() + + if args.algo not in ["DQN", "PPO"]: + raise ValueError( + "Curiosity example only implemented for either DQN or PPO! See the " + ) + + base_config = ( + tune.registry.get_trainable_cls(args.algo) + .get_default_config() + .environment( + "FrozenLake-v1", + env_config={ + # Use a 12x12 map. + "desc": [ + "SFFFFFFFFFFF", + "FFFFFFFFFFFF", + "FFFFFFFFFFFF", + "FFFFFFFFFFFF", + "FFFFFFFFFFFF", + "FFFFFFFFFFFF", + "FFFFFFFFFFFF", + "FFFFFFFFFFFF", + "FFFFFFFFFFFF", + "FFFFFFFFFFFF", + "FFFFFFFFFFFF", + "FFFFFFFFFFFG", + ], + "is_slippery": False, + # Limit the number of steps the agent is allowed to make in the env to + # make it almost impossible to learn without the curriculum. + "max_episode_steps": 22, + }, + ) + .callbacks(MeasureMaxDistanceToStart) + .env_runners( + num_envs_per_env_runner=5 if args.algo == "PPO" else 1, + env_to_module_connector=lambda env: FlattenObservations(), + ) + .training( + learner_config_dict={ + # Intrinsic reward coefficient. + "intrinsic_reward_coeff": 0.05, + # Forward loss weight (vs inverse dynamics loss). Total ICM loss is: + # L(total ICM) = ( + # `forward_loss_weight` * L(forward) + # + (1.0 - `forward_loss_weight`) * L(inverse_dyn) + # ) + "forward_loss_weight": 0.2, + } + ) + .rl_module( + rl_module_spec=MultiRLModuleSpec( + rl_module_specs={ + # The "main" RLModule (policy) to be trained by our algo. + DEFAULT_MODULE_ID: RLModuleSpec( + **( + {"model_config": {"vf_share_layers": True}} + if args.algo == "PPO" + else {} + ), + ), + # The intrinsic curiosity model. + ICM_MODULE_ID: RLModuleSpec( + module_class=IntrinsicCuriosityModel, + # Only create the ICM on the Learner workers, NOT on the + # EnvRunners. + learner_only=True, + # Configure the architecture of the ICM here. + model_config={ + "feature_dim": 288, + "feature_net_hiddens": (256, 256), + "feature_net_activation": "relu", + "inverse_net_hiddens": (256, 256), + "inverse_net_activation": "relu", + "forward_net_hiddens": (256, 256), + "forward_net_activation": "relu", + }, + ), + } + ), + # Use a different learning rate for training the ICM. + algorithm_config_overrides_per_module={ + ICM_MODULE_ID: AlgorithmConfig.overrides(lr=0.0005) + }, + ) + ) + + # Set PPO-specific hyper-parameters. + if args.algo == "PPO": + base_config.training( + num_epochs=6, + # Plug in the correct Learner class. + learner_class=PPOTorchLearnerWithCuriosity, + train_batch_size_per_learner=2000, + lr=0.0003, + ) + elif args.algo == "DQN": + base_config.training( + # Plug in the correct Learner class. + learner_class=DQNTorchLearnerWithCuriosity, + train_batch_size_per_learner=128, + lr=0.00075, + replay_buffer_config={ + "type": "PrioritizedEpisodeReplayBuffer", + "capacity": 500000, + "alpha": 0.6, + "beta": 0.4, + }, + # Epsilon exploration schedule for DQN. + epsilon=[[0, 1.0], [500000, 0.05]], + n_step=(3, 5), + double_q=True, + dueling=True, + ) + + success_key = f"{ENV_RUNNER_RESULTS}/max_dist_travelled_across_running_episodes" + stop = { + success_key: 12.0, + f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": args.stop_reward, + NUM_ENV_STEPS_SAMPLED_LIFETIME: args.stop_timesteps, + } + + run_rllib_example_script_experiment( + base_config, + args, + stop=stop, + success_metric={success_key: stop[success_key]}, + ) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/curriculum/__init__.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/curriculum/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/curriculum/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/curriculum/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be7ea4aea811e21ff22008c0f9ff9c83eb2538a1 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/curriculum/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/curriculum/__pycache__/curriculum_learning.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/curriculum/__pycache__/curriculum_learning.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..257be898223c143554b42bfa8a2318b9430a7877 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/curriculum/__pycache__/curriculum_learning.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/curriculum/curriculum_learning.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/curriculum/curriculum_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..9a029bb2f1512f2bc53dd64b8dec06177ebb4464 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/examples/curriculum/curriculum_learning.py @@ -0,0 +1,241 @@ +"""Example of using an env-task curriculum by implementing a custom callback. + +This example: + - demonstrates how to define your own curriculum-capable environments using + gymnasium's FrozenLake env. + - defines a custom callback that gets called once per iteration and - if necessary - + changes the maps used by FrozenLake on all EnvRunners to a new task (by moving the + goal position further and further away from the starting position). + - also demonstrates an alternative approach via reloading/recreating an entirely new + env inside all EnvRunners. + - uses Tune and RLlib to curriculum-learn the env described above and compares 2 + algorithms, one that does use curriculum learning vs one that does not. + +We use a FrozenLake (sparse reward) environment with a map size of 8x8 and a time step +limit of 16 to make it almost impossible for a non-curriculum policy to learn. + + +How to run this script +---------------------- +`python [script file name].py --enable-new-api-stack` + +Use the `--no-curriculum` flag to disable curriculum learning and force your policy +to be trained on the hardest task right away. With this option, the algorithm should NOT +succeed. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +In the console output, you can see that only PPO policy that uses a curriculum can +actually learn, whereas the one that is thrown into the toughest task right from the +start never learns anything. + +Policy using the curriculum: ++-------------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +|-------------------------------+------------+-----------------+--------+ +| PPO_FrozenLake-v1_93ca4_00000 | TERMINATED | 127.0.0.1:73318 | 41 | ++-------------------------------+------------+-----------------+--------+ ++------------------+--------+----------+--------------------+ +| total time (s) | ts | reward | episode_len_mean | +|------------------+--------+----------+--------------------| +| 97.652 | 164000 | 1 | 14.0348 | ++------------------+--------+----------+--------------------+ + +Policy NOT using the curriculum (trying to solve the hardest task right away): +[DOES NOT LEARN AT ALL] +""" +from functools import partial + +from ray.air.constants import TRAINING_ITERATION +from ray.rllib.algorithms.algorithm import Algorithm +from ray.rllib.algorithms.callbacks import DefaultCallbacks +from ray.rllib.connectors.env_to_module import FlattenObservations +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + NUM_ENV_STEPS_SAMPLED_LIFETIME, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls + +parser = add_rllib_example_script_args(default_iters=100, default_timesteps=600000) +parser.set_defaults(enable_new_api_stack=True) +parser.add_argument( + "--upgrade-task-threshold", + type=float, + default=0.99, + help="The mean episode return, upon reaching of which we increase the task by one.", +) +parser.add_argument( + "--no-curriculum", + action="store_true", + help="Whether to NOT use curriculum learning (and instead trying to solve the " + "hardest task right away).", +) + +# __curriculum_learning_example_env_options__ +ENV_OPTIONS = { + "is_slippery": False, + # Limit the number of steps the agent is allowed to make in the env to + # make it almost impossible to learn without the curriculum. + "max_episode_steps": 16, +} + +# Our 3 tasks: 0=easiest, 1=medium, 2=hard +ENV_MAPS = [ + # 0 + [ + "SFFHFFFH", + "FFFHFFFF", + "FFGFFFFF", + "FFFFFFFF", + "HFFFFFFF", + "HHFFFFHF", + "FFFFFHHF", + "FHFFFFFF", + ], + # 1 + [ + "SFFHFFFH", + "FFFHFFFF", + "FFFFFFFF", + "FFFFFFFF", + "HFFFFFFF", + "HHFFGFHF", + "FFFFFHHF", + "FHFFFFFF", + ], + # 2 + [ + "SFFHFFFH", + "FFFHFFFF", + "FFFFFFFF", + "FFFFFFFF", + "HFFFFFFF", + "HHFFFFHF", + "FFFFFHHF", + "FHFFFFFG", + ], +] +# __END_curriculum_learning_example_env_options__ + + +# Simple function sent to an EnvRunner to change the map of all its gym. Envs from +# the current one to a new (tougher) one, in which the goal position is further away +# from the starting position. Note that a map is a list of strings, each one +# representing one row in the map. Each character in the strings represent a single +# field (S=starting position, H=hole (bad), F=frozen/free field (ok), G=goal (great!)). +def _remote_fn(env_runner, new_task: int): + # We recreate the entire env object by changing the env_config on the worker, + # then calling its `make_env()` method. + env_runner.config.environment(env_config={"desc": ENV_MAPS[new_task]}) + env_runner.make_env() + + +class EnvTaskCallback(DefaultCallbacks): + """Custom callback implementing `on_train_result()` for changing the envs' maps.""" + + def on_train_result( + self, + *, + algorithm: Algorithm, + metrics_logger=None, + result: dict, + **kwargs, + ) -> None: + # Hack: Store the current task inside a counter in our Algorithm. + # W/o a curriculum, the task is always 2 (hardest). + if args.no_curriculum: + algorithm._counters["current_env_task"] = 2 + current_task = algorithm._counters["current_env_task"] + + # If episode return is consistently `args.upgrade_task_threshold`, we switch + # to a more difficult task (if possible). If we already mastered the most + # difficult task, we publish our victory in the result dict. + result["task_solved"] = 0.0 + current_return = result[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] + if current_return > args.upgrade_task_threshold: + if current_task < 2: + new_task = current_task + 1 + print( + f"Switching task/map on all EnvRunners to #{new_task} (0=easiest, " + f"2=hardest), b/c R={current_return} on current task." + ) + algorithm.env_runner_group.foreach_worker( + func=partial(_remote_fn, new_task=new_task) + ) + algorithm._counters["current_env_task"] = new_task + + # Hardest task was solved (1.0) -> report this in the results dict. + elif current_return == 1.0: + result["task_solved"] = 1.0 + # Emergency brake: If return is 0.0 AND we are already at a harder task (1 or + # 2), we go back to task=0. + elif current_return == 0.0 and current_task > 0: + print( + "Emergency brake: Our policy seemed to have collapsed -> Setting task " + "back to 0." + ) + algorithm.env_runner_group.foreach_worker( + func=partial(_remote_fn, new_task=0) + ) + algorithm._counters["current_env_task"] = 0 + + +if __name__ == "__main__": + args = parser.parse_args() + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + # Plug in our curriculum callbacks that controls when we should upgrade the env + # task based on the received return for the current task. + .callbacks(EnvTaskCallback) + .environment( + "FrozenLake-v1", + env_config={ + # w/ curriculum: start with task=0 (easiest) + # w/o curriculum: start directly with hardest task 2. + "desc": ENV_MAPS[2 if args.no_curriculum else 0], + **ENV_OPTIONS, + }, + ) + .env_runners( + num_envs_per_env_runner=5, + env_to_module_connector=lambda env: FlattenObservations(), + ) + .training( + num_epochs=6, + vf_loss_coeff=0.01, + lr=0.0002, + ) + .rl_module(model_config=DefaultModelConfig(vf_share_layers=True)) + ) + + stop = { + TRAINING_ITERATION: args.stop_iters, + # Reward directly does not matter to us as we would like to continue + # after the policy reaches a return of ~1.0 on the 0-task (easiest). + # But we DO want to stop, once the entire task is learned (policy achieves + # return of 1.0 on the most difficult task=2). + "task_solved": 1.0, + NUM_ENV_STEPS_SAMPLED_LIFETIME: args.stop_timesteps, + } + + run_rllib_example_script_experiment( + base_config, args, stop=stop, success_metric={"task_solved": 1.0} + ) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/gpus/__init__.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/gpus/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/gpus/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/gpus/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d0d6fc08daa6457cfbde786684a501fc6f551f8 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/gpus/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/gpus/__pycache__/float16_training_and_inference.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/gpus/__pycache__/float16_training_and_inference.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8cad2218bd79c46113f7272b7168a12c92ffef17 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/gpus/__pycache__/float16_training_and_inference.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/gpus/__pycache__/fractional_gpus_per_learner.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/gpus/__pycache__/fractional_gpus_per_learner.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8962875fbf0a3bfd6b824b289aa1ef230937be8 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/gpus/__pycache__/fractional_gpus_per_learner.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/gpus/__pycache__/mixed_precision_training_float16_inference.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/gpus/__pycache__/mixed_precision_training_float16_inference.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4aa80247b4a76bdf606473336e7a6f3614a8ea1b Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/gpus/__pycache__/mixed_precision_training_float16_inference.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/gpus/float16_training_and_inference.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/gpus/float16_training_and_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..aa498663b2d620d438e0d34bdc5734ae6b10875a --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/examples/gpus/float16_training_and_inference.py @@ -0,0 +1,258 @@ +"""Example of using float16 precision for training and inference. + +This example: + - shows how to write a custom callback for RLlib to convert all RLModules + (on the EnvRunners and Learners) to float16 precision. + - shows how to write a custom env-to-module ConnectorV2 piece to convert all + observations and rewards in the collected trajectories to float16 (numpy) arrays. + - shows how to write a custom grad scaler for torch that is necessary to stabilize + learning with float16 weight matrices and gradients. This custom scaler behaves + exactly like the torch built-in `torch.amp.GradScaler` but also works for float16 + gradients (which the torch built-in one doesn't). + - shows how to write a custom TorchLearner to change the epsilon setting (to the + much larger 1e-4 to stabilize learning) on the default optimizer (Adam) registered + for each RLModule. + - demonstrates how to plug in all the above custom components into an + `AlgorithmConfig` instance and start training (and inference) with float16 + precision. + + +How to run this script +---------------------- +`python [script file name].py --enable-new-api-stack + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + +You can visualize experiment results in ~/ray_results using TensorBoard. + + +Results to expect +----------------- +You should see something similar to the following on your terminal, when running this +script with the above recommended options: + ++-----------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +| | | | | +|-----------------------------+------------+-----------------+--------+ +| PPO_CartPole-v1_437ee_00000 | TERMINATED | 127.0.0.1:81045 | 6 | ++-----------------------------+------------+-----------------+--------+ ++------------------+------------------------+------------------------+ +| total time (s) | episode_return_mean | num_episodes_lifetime | +| | | | +|------------------+------------------------+------------------------+ +| 71.3123 | 153.79 | 358 | ++------------------+------------------------+------------------------+ +""" +from typing import Optional + +import gymnasium as gym +import numpy as np +import torch + +from ray.rllib.algorithms.algorithm import Algorithm +from ray.rllib.algorithms.callbacks import DefaultCallbacks +from ray.rllib.algorithms.ppo.torch.ppo_torch_learner import PPOTorchLearner +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.learner.torch.torch_learner import TorchLearner +from ray.rllib.utils.annotations import override +from ray.rllib.utils.metrics.metrics_logger import MetricsLogger +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls + +parser = add_rllib_example_script_args( + default_iters=50, default_reward=150.0, default_timesteps=100000 +) +parser.set_defaults( + enable_new_api_stack=True, +) + + +class MakeAllRLModulesFloat16(DefaultCallbacks): + """Callback making sure that all RLModules in the algo are `half()`'ed.""" + + def on_algorithm_init( + self, + *, + algorithm: Algorithm, + metrics_logger: Optional[MetricsLogger] = None, + **kwargs, + ) -> None: + # Switch all Learner RLModules to float16. + algorithm.learner_group.foreach_learner( + lambda learner: learner.module.foreach_module(lambda mid, mod: mod.half()) + ) + # Switch all EnvRunner RLModules (assuming single RLModules) to float16. + algorithm.env_runner_group.foreach_worker( + lambda env_runner: env_runner.module.half() + ) + if algorithm.eval_env_runner_group: + algorithm.eval_env_runner_group.foreach_worker( + lambda env_runner: env_runner.module.half() + ) + + +class WriteObsAndRewardsAsFloat16(ConnectorV2): + """ConnectorV2 piece preprocessing observations and rewards to be float16. + + Note that users can also write a gymnasium.Wrapper for observations and rewards + to achieve the same thing. + """ + + def recompute_output_observation_space( + self, + input_observation_space, + input_action_space, + ): + return gym.spaces.Box( + input_observation_space.low.astype(np.float16), + input_observation_space.high.astype(np.float16), + input_observation_space.shape, + np.float16, + ) + + def __call__(self, *, rl_module, batch, episodes, **kwargs): + for sa_episode in self.single_agent_episode_iterator(episodes): + obs = sa_episode.get_observations(-1) + float16_obs = obs.astype(np.float16) + sa_episode.set_observations(new_data=float16_obs, at_indices=-1) + if len(sa_episode) > 0: + rew = sa_episode.get_rewards(-1).astype(np.float16) + sa_episode.set_rewards(new_data=rew, at_indices=-1) + return batch + + +class Float16GradScaler: + """Custom grad scaler for `TorchLearner`. + + This class is utilizing the experimental support for the `TorchLearner`'s support + for loss/gradient scaling (analogous to how a `torch.amp.GradScaler` would work). + + TorchLearner performs the following steps using this class (`scaler`): + - loss_per_module = TorchLearner.compute_losses() + - for L in loss_per_module: L = scaler.scale(L) + - grads = TorchLearner.compute_gradients() # L.backward() on scaled loss + - TorchLearner.apply_gradients(grads): + for optim in optimizers: + scaler.step(optim) # <- grads should get unscaled + scaler.update() # <- update scaling factor + """ + + def __init__( + self, + init_scale=1000.0, + growth_factor=2.0, + backoff_factor=0.5, + growth_interval=2000, + ): + self._scale = init_scale + self.growth_factor = growth_factor + self.backoff_factor = backoff_factor + self.growth_interval = growth_interval + self._found_inf_or_nan = False + self.steps_since_growth = 0 + + def scale(self, loss): + # Scale the loss by `self._scale`. + return loss * self._scale + + def get_scale(self): + return self._scale + + def step(self, optimizer): + # Unscale the gradients for all model parameters and apply. + for group in optimizer.param_groups: + for param in group["params"]: + if param.grad is not None: + param.grad.data.div_(self._scale) + if torch.isinf(param.grad).any() or torch.isnan(param.grad).any(): + self._found_inf_or_nan = True + break + if self._found_inf_or_nan: + break + # Only step if no inf/NaN grad found. + if not self._found_inf_or_nan: + optimizer.step() + + def update(self): + # If gradients are found to be inf/NaN, reduce the scale. + if self._found_inf_or_nan: + self._scale *= self.backoff_factor + self.steps_since_growth = 0 + # Increase the scale after a set number of steps without inf/NaN. + else: + self.steps_since_growth += 1 + if self.steps_since_growth >= self.growth_interval: + self._scale *= self.growth_factor + self.steps_since_growth = 0 + # Reset inf/NaN flag. + self._found_inf_or_nan = False + + +class LargeEpsAdamTorchLearner(PPOTorchLearner): + """A TorchLearner overriding the default optimizer (Adam) to use non-default eps.""" + + @override(TorchLearner) + def configure_optimizers_for_module(self, module_id, config): + """Registers an Adam optimizer with a larg epsilon under the given module_id.""" + params = list(self._module[module_id].parameters()) + + # Register one Adam optimizer (under the default optimizer name: + # DEFAULT_OPTIMIZER) for the `module_id`. + self.register_optimizer( + module_id=module_id, + # Create an Adam optimizer with a different eps for better float16 + # stability. + optimizer=torch.optim.Adam(params, eps=1e-4), + params=params, + # Let RLlib handle the learning rate/learning rate schedule. + # You can leave `lr_or_lr_schedule` at None, but then you should + # pass a fixed learning rate into the Adam constructor above. + lr_or_lr_schedule=config.lr, + ) + + +if __name__ == "__main__": + args = parser.parse_args() + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment("CartPole-v1") + # Plug in our custom callback (on_algorithm_init) to make all RLModules + # float16 models. + .callbacks(MakeAllRLModulesFloat16) + # Plug in our custom loss scaler class to stabilize gradient computations + # (by scaling the loss, then unscaling the gradients before applying them). + # This is using the built-in, experimental feature of TorchLearner. + .experimental(_torch_grad_scaler_class=Float16GradScaler) + # Plug in our custom env-to-module ConnectorV2 piece to convert all observations + # and reward in the episodes (permanently) to float16. + .env_runners(env_to_module_connector=lambda env: WriteObsAndRewardsAsFloat16()) + .training( + # Plug in our custom TorchLearner (using a much larger, stabilizing epsilon + # on the Adam optimizer). + learner_class=LargeEpsAdamTorchLearner, + # Switch off grad clipping entirely b/c we use our custom grad scaler with + # built-in inf/nan detection (see `step` method of `Float16GradScaler`). + grad_clip=None, + # Typical CartPole-v1 hyperparams known to work well: + gamma=0.99, + lr=0.0003, + num_epochs=6, + vf_loss_coeff=0.01, + use_kl_loss=True, + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/gpus/fractional_gpus_per_learner.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/gpus/fractional_gpus_per_learner.py new file mode 100644 index 0000000000000000000000000000000000000000..fe29d209224435cb2caf60b45b7ea11f098a5491 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/examples/gpus/fractional_gpus_per_learner.py @@ -0,0 +1,114 @@ +"""Example of using fractional GPUs (< 1.0) per Learner worker. + +This example: + - shows how to set up an Algorithm that uses one or more Learner workers ... + - ... and how to assign a fractional (< 1.0) number of GPUs to each of these Learners. + + +How to run this script +---------------------- +`python [script file name].py --enable-new-api-stack --num-learner-workers= +[number of Learner workers, e.g. 1] --num-gpus-per-learner [some fraction <1.0]` + +The following command line combinations been tested on a 4 NVIDIA T4 GPUs (16 vCPU) +machine. +Note that for each run, 4 tune trials will be setup; see tune.grid_search over 4 +learning rates in the `base_config` below: +1) --num-learners=1 --num-gpus-per-learner=0.5 (2.0 GPUs used). +2) --num-learners=1 --num-gpus-per-learner=0.3 (1.2 GPUs used). +3) --num-learners=1 --num-gpus-per-learner=0.25 (1.0 GPU used). +4) non-sensical setting: --num-learners=2 --num-gpus-per-learner=0.5 (expect an +NCCL-related error due to the fact that torch will try to perform DDP sharding, +but notices that the shards sit on the same GPU). + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +Note that the shown GPU settings in this script also work in case you are not +running via tune, but instead are using the `--no-tune` command line option. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + +You can visualize experiment results in ~/ray_results using TensorBoard. + + +Results to expect +----------------- +In the console output, you can see that only fractional GPUs are being used by RLlib: + +== Status == +... +Logical resource usage: 12.0/16 CPUs, 1.0/4 GPUs (...) +... +Number of trials: 4/4 (4 RUNNING) + +The final output should look something like this: ++-----------------------------+------------+-----------------+--------+--------+ +| Trial name | status | loc | lr | iter | +| | | | | | +|-----------------------------+------------+-----------------+--------+--------+ +| PPO_CartPole-v1_7104b_00000 | TERMINATED | 10.0.0.39:31197 | 0.005 | 10 | +| PPO_CartPole-v1_7104b_00001 | TERMINATED | 10.0.0.39:31202 | 0.003 | 11 | +| PPO_CartPole-v1_7104b_00002 | TERMINATED | 10.0.0.39:31203 | 0.001 | 10 | +| PPO_CartPole-v1_7104b_00003 | TERMINATED | 10.0.0.39:31204 | 0.0001 | 11 | ++-----------------------------+------------+-----------------+--------+--------+ + ++----------------+----------------------+----------------------+----------------------+ +| total time (s) | num_env_steps_sample | num_env_steps_traine | num_episodes_lifetim | +| | d_lifetime | d_lifetime | e | +|----------------+----------------------+----------------------+----------------------| +| 101.002 | 40000 | 40000 | 346 | +| 110.03 | 44000 | 44000 | 395 | +| 101.171 | 40000 | 40000 | 328 | +| 110.091 | 44000 | 44000 | 478 | ++----------------+----------------------+----------------------+----------------------+ +""" +from ray import tune +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import get_trainable_cls + +parser = add_rllib_example_script_args( + default_iters=50, default_reward=180, default_timesteps=100000 +) +parser.set_defaults( + enable_new_api_stack=True, + num_env_runners=2, +) + + +if __name__ == "__main__": + args = parser.parse_args() + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + # This script only works on the new API stack. + .api_stack( + enable_rl_module_and_learner=True, + enable_env_runner_and_connector_v2=True, + ) + .environment("CartPole-v1") + # Define EnvRunner scaling. + .env_runners(num_env_runners=args.num_env_runners) + # Define Learner scaling. + .learners( + # How many Learner workers do we need? If you have more than 1 GPU, + # set this parameter to the number of GPUs available. + num_learners=args.num_learners, + # How many GPUs does each Learner need? If you have more than 1 GPU or only + # one Learner, you should set this to 1, otherwise, set this to some + # fraction. + num_gpus_per_learner=args.num_gpus_per_learner, + ) + # 4 tune trials altogether. + .training(lr=tune.grid_search([0.005, 0.003, 0.001, 0.0001])) + ) + + run_rllib_example_script_experiment(base_config, args, keep_config=True) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/gpus/mixed_precision_training_float16_inference.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/gpus/mixed_precision_training_float16_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..e27dd8b7b579327c22e102817c55d6d4548ebdc8 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/examples/gpus/mixed_precision_training_float16_inference.py @@ -0,0 +1,178 @@ +"""Example of using automatic mixed precision training on a torch RLModule. + +This example: + - shows how to write a custom callback for RLlib to convert those RLModules + only(!) on the EnvRunners to float16 precision. + - shows how to write a custom env-to-module ConnectorV2 piece to add float16 + observations to the action computing forward batch on the EnvRunners, but NOT + permanently write these changes into the episodes, such that on the + Learner side, the original float32 observations will be used (for the mixed + precision `forward_train` and `loss` computations). + - shows how to plugin torch's built-in `GradScaler` class to be used by the + TorchLearner to scale losses and unscale gradients in order to gain more stability + when training with mixed precision. + - shows how to write a custom TorchLearner to run the update step (overrides + `_update()`) within a `torch.amp.autocast()` context. This makes sure that . + - demonstrates how to plug in all the above custom components into an + `AlgorithmConfig` instance and start training with mixed-precision while + performing the inference on the EnvRunners with float16 precision. + + +How to run this script +---------------------- +`python [script file name].py --enable-new-api-stack + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +Note that the shown GPU settings in this script also work in case you are not +running via tune, but instead are using the `--no-tune` command line option. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + +You can visualize experiment results in ~/ray_results using TensorBoard. + + +Results to expect +----------------- +In the console output, you should see something like this: + ++-----------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +| | | | | +|-----------------------------+------------+-----------------+--------+ +| PPO_CartPole-v1_485af_00000 | TERMINATED | 127.0.0.1:81045 | 22 | ++-----------------------------+------------+-----------------+--------+ ++------------------+------------------------+------------------------+ +| total time (s) | episode_return_mean | num_episodes_lifetime | +| | | | +|------------------+------------------------+------------------------+ +| 281.3231 | 455.81 | 1426 | ++------------------+------------------------+------------------------+ +""" +from typing import Optional + +import gymnasium as gym +import numpy as np +import torch + +from ray.rllib.algorithms.algorithm import Algorithm +from ray.rllib.algorithms.callbacks import DefaultCallbacks +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.algorithms.ppo.torch.ppo_torch_learner import PPOTorchLearner +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.utils.metrics.metrics_logger import MetricsLogger +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) + + +parser = add_rllib_example_script_args( + default_iters=200, default_reward=450.0, default_timesteps=200000 +) +parser.set_defaults( + algo="PPO", + enable_new_api_stack=True, +) + + +class MakeEnvRunnerRLModulesFloat16(DefaultCallbacks): + """Callback making sure that all RLModules in the algo are `half()`'ed.""" + + def on_algorithm_init( + self, + *, + algorithm: Algorithm, + metrics_logger: Optional[MetricsLogger] = None, + **kwargs, + ) -> None: + # Switch all EnvRunner RLModules (assuming single RLModules) to float16. + algorithm.env_runner_group.foreach_worker( + lambda env_runner: env_runner.module.half() + ) + if algorithm.eval_env_runner_group: + algorithm.eval_env_runner_group.foreach_worker( + lambda env_runner: env_runner.module.half() + ) + + +class Float16Connector(ConnectorV2): + """ConnectorV2 piece preprocessing observations and rewards to be float16. + + Note that users can also write a gymnasium.Wrapper for observations and rewards + to achieve the same thing. + """ + + def recompute_output_observation_space( + self, + input_observation_space, + input_action_space, + ): + return gym.spaces.Box( + input_observation_space.low.astype(np.float16), + input_observation_space.high.astype(np.float16), + input_observation_space.shape, + np.float16, + ) + + def __call__(self, *, rl_module, batch, episodes, **kwargs): + for sa_episode in self.single_agent_episode_iterator(episodes): + obs = sa_episode.get_observations(-1) + float16_obs = obs.astype(np.float16) + self.add_batch_item( + batch, + column="obs", + item_to_add=float16_obs, + single_agent_episode=sa_episode, + ) + return batch + + +class PPOTorchMixedPrecisionLearner(PPOTorchLearner): + def _update(self, *args, **kwargs): + with torch.cuda.amp.autocast(): + results = super()._update(*args, **kwargs) + return results + + +if __name__ == "__main__": + args = parser.parse_args() + + assert ( + args.enable_new_api_stack + ), "Must set --enable-new-api-stack when running this script!" + assert args.algo == "PPO", "Must set --algo=PPO when running this script!" + + base_config = ( + (PPOConfig().environment("CartPole-v1")) + .env_runners(env_to_module_connector=lambda env: Float16Connector()) + # Plug in our custom callback (on_algorithm_init) to make EnvRunner RLModules + # float16 models. + .callbacks(MakeEnvRunnerRLModulesFloat16) + # Plug in the torch built-int loss scaler class to stabilize gradient + # computations (by scaling the loss, then unscaling the gradients before + # applying them). This is using the built-in, experimental feature of + # TorchLearner. + .experimental(_torch_grad_scaler_class=torch.cuda.amp.GradScaler) + .training( + # Plug in the custom Learner class to activate mixed-precision training for + # our torch RLModule (uses `torch.amp.autocast()`). + learner_class=PPOTorchMixedPrecisionLearner, + # Switch off grad clipping entirely b/c we use our custom grad scaler with + # built-in inf/nan detection (see `step` method of `Float16GradScaler`). + grad_clip=None, + # Typical CartPole-v1 hyperparams known to work well: + gamma=0.99, + lr=0.0003, + num_epochs=6, + vf_loss_coeff=0.01, + use_kl_loss=True, + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/learners/__init__.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/learners/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/learners/__pycache__/ppo_load_rl_modules.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/rllib/examples/learners/__pycache__/ppo_load_rl_modules.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca67f733958ab399cdbdf7100a2c9037d52e7354 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/rllib/examples/learners/__pycache__/ppo_load_rl_modules.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/learners/custom_loss_fn_simple.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/learners/custom_loss_fn_simple.py new file mode 100644 index 0000000000000000000000000000000000000000..aa50db615977e189247b6d821b32093373263150 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/examples/learners/custom_loss_fn_simple.py @@ -0,0 +1,138 @@ +"""Example of how to write a custom loss function (based on the existing PPO loss). + +This example shows: + - how to subclass an existing (torch) Learner and override its + `compute_loss_for_module()` method. + - how you can add your own loss terms to the subclassed "base loss", in this + case here a weights regularizer term with the intention to keep the learnable + parameters of the RLModule reasonably small. + - how to add custom settings (here: the regularizer coefficient) to the + `AlgorithmConfig` in order to not have to subclass and write your own + (you could still do that, but are not required to). + - how to plug in the custom Learner into your config and then run the + experiment. + +See the :py:class:`~ray.rllib.examples.learners.classes.custom_loss_fn_learner.PPOTorchLearnerWithWeightRegularizerLoss` # noqa +class for details on how to override the main (PPO) loss function. + +We compute a naive regularizer term averaging over all parameters of the RLModule and +add this mean value (multiplied by the regularizer coefficient) to the base PPO loss. +The experiment shows that even with a large learning rate, our custom Learner is still +able to learn properly as it's forced to keep the weights small. + + +How to run this script +---------------------- +`python [script file name].py --enable-new-api-stack --regularizer-coeff=0.02 +--lr=0.01` + +Use the `--regularizer-coeff` option to set the value of the coefficient with which +the mean NN weight is being multiplied (inside the total loss) and the `--lr` option +to set the learning rate. Experiments using a large learning rate and no regularization +(`--regularizer-coeff=0.0`) should NOT learn a decently working policy. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +In the console output, you can see that - given a large learning rate - only with +weight regularization (`--regularizer-coeff` > 0.0), the algo has a chance to learn +a decent policy: + +With --regularizer-coeff=0.02 and --lr=0.01 +(trying to reach 250.0 return on CartPole in 100k env steps): ++-----------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +| | | | | +|-----------------------------+------------+-----------------+--------+ +| PPO_CartPole-v1_4a3a0_00000 | TERMINATED | 127.0.0.1:16845 | 18 | ++-----------------------------+------------+-----------------+--------+ ++------------------+------------------------+---------------------+ +| total time (s) | num_env_steps_sampled_ | episode_return_mean | +| | _lifetime | | +|------------------+------------------------+---------------------+ +| 16.8842 | 72000 | 256.35 | ++------------------+------------------------+---------------------+ + +With --regularizer-coeff=0.0 and --lr=0.01 +(trying to reach 250.0 return on CartPole in 100k env steps): + +[HAS SIGNIFICANT PROBLEMS REACHING THE DESIRED RETURN] +""" + +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.examples.learners.classes.custom_loss_fn_learner import ( + PPOTorchLearnerWithWeightRegularizerLoss, +) +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) + +torch, _ = try_import_torch() + + +parser = add_rllib_example_script_args( + default_reward=250.0, + default_timesteps=200000, +) +parser.set_defaults(enable_new_api_stack=True) +parser.add_argument( + "--regularizer-coeff", + type=float, + default=0.02, + help="The coefficient with which to multiply the mean NN-weight by (and then add " + "the result of this operation to the main loss term).", +) +parser.add_argument( + "--lr", + type=float, + default=0.01, + help="The learning rate to use.", +) + + +if __name__ == "__main__": + args = parser.parse_args() + + assert ( + args.enable_new_api_stack + ), "Must set --enable-new-api-stack when running this script!" + assert args.algo == "PPO", "Must set --algo=PPO when running this script!" + + base_config = ( + PPOConfig() + .environment("CartPole-v1") + .training( + # This is the most important setting in this script: We point our PPO + # algorithm to use the custom Learner (instead of the default + # PPOTorchLearner). + learner_class=PPOTorchLearnerWithWeightRegularizerLoss, + # We use this simple method here to inject a new setting that our + # custom Learner class uses in its loss function. This is convenient + # and avoids having to subclass `PPOConfig` only to add a few new settings + # to it. Within our Learner, we can access this new setting through: + # `self.config.learner_config_dict['regularizer_coeff']` + learner_config_dict={"regularizer_coeff": args.regularizer_coeff}, + # Some settings to make this example learn better. + num_epochs=6, + vf_loss_coeff=0.01, + # The learning rate, settable through the command line `--lr` arg. + lr=args.lr, + ) + .rl_module( + model_config=DefaultModelConfig(vf_share_layers=True), + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/learners/ppo_with_torch_lr_schedulers.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/learners/ppo_with_torch_lr_schedulers.py new file mode 100644 index 0000000000000000000000000000000000000000..3e109162e018751d5987783e7687278c4fdd8637 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/examples/learners/ppo_with_torch_lr_schedulers.py @@ -0,0 +1,209 @@ +"""Example of how to use PyTorch's learning rate schedulers to design a complex +learning rate schedule for training. + +Two learning rate schedules are applied in sequence to the learning rate of the +optimizer. In this way even more complex learning rate schedules can be assembled. + +This example shows: + - how to configure multiple learning rate schedulers, as a chained pipeline, in + PyTorch using partial initialization with `functools.partial`. + + +How to run this script +---------------------- +`python [script file name].py --enable-new-api-stack --lr-const-factor=0.9 +--lr-const-iters=10 --lr-exp-decay=0.9` + +Use the `--lr-const-factor` to define the facotr by which to multiply the +learning rate in the first `--lr-const-iters` iterations. Use the +`--lr-const-iters` to set the number of iterations in which the learning rate +should be adapted by the `--lr-const-factor`. Use `--lr-exp-decay` to define +the learning rate decay to be applied after the constant factor multiplication. + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +You should expect to observe decent learning behavior from your console output: + +With `--lr-const-factor=0.1`, `--lr-const-iters=10, and `--lr-exp_decay=0.3`. ++-----------------------------+------------+--------+------------------+ +| Trial name | status | iter | total time (s) | +| | | | | +|-----------------------------+------------+--------+------------------+ +| PPO_CartPole-v1_7fc44_00000 | TERMINATED | 50 | 59.6542 | ++-----------------------------+------------+--------+------------------+ ++------------------------+------------------------+------------------------+ +| episode_return_mean | num_episodes_lifetime | num_env_steps_traine | +| | | d_lifetime | ++------------------------+------------------------+------------------------| +| 451.2 | 9952 | 210047 | ++------------------------+------------------------+------------------------+ +""" +import functools +import numpy as np +from typing import Optional + +from ray.rllib.algorithms.algorithm import Algorithm +from ray.rllib.algorithms.callbacks import DefaultCallbacks +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.core import DEFAULT_MODULE_ID +from ray.rllib.core.learner.learner import DEFAULT_OPTIMIZER +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + EVALUATION_RESULTS, + NUM_ENV_STEPS_SAMPLED_LIFETIME, +) +from ray.rllib.utils.metrics.metrics_logger import MetricsLogger +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.test_utils import add_rllib_example_script_args + +torch, _ = try_import_torch() + + +class LRChecker(DefaultCallbacks): + def on_algorithm_init( + self, + *, + algorithm: "Algorithm", + metrics_logger: Optional[MetricsLogger] = None, + **kwargs, + ) -> None: + # Store the expected learning rates for each iteration. + self.lr = [] + # Retrieve the chosen configuration parameters from the config. + lr_factor = algorithm.config._torch_lr_scheduler_classes[0].keywords["factor"] + lr_total_iters = algorithm.config._torch_lr_scheduler_classes[0].keywords[ + "total_iters" + ] + lr_gamma = algorithm.config._torch_lr_scheduler_classes[1].keywords["gamma"] + # Compute the learning rates for all iterations up to `lr_const_iters`. + for i in range(1, lr_total_iters + 1): + # The initial learning rate. + lr = algorithm.config.lr + # In the first 10 iterations we multiply by `lr_const_factor`. + if i < lr_total_iters: + lr *= lr_factor + # Finally, we have an exponential decay of `lr_exp_decay`. + lr *= lr_gamma**i + self.lr.append(lr) + + def on_train_result( + self, + *, + algorithm: "Algorithm", + metrics_logger: Optional[MetricsLogger] = None, + result: dict, + **kwargs, + ) -> None: + + # Check for the first `lr_total_iters + 1` iterations, if expected + # and actual learning rates correspond. + if ( + algorithm.training_iteration + <= algorithm.config._torch_lr_scheduler_classes[0].keywords["total_iters"] + ): + actual_lr = algorithm.learner_group._learner.get_optimizer( + DEFAULT_MODULE_ID, DEFAULT_OPTIMIZER + ).param_groups[0]["lr"] + # Assert the learning rates are close enough. + assert np.isclose( + actual_lr, + self.lr[algorithm.training_iteration - 1], + atol=1e-9, + rtol=1e-9, + ) + + +parser = add_rllib_example_script_args(default_reward=450.0, default_timesteps=250000) +parser.set_defaults(enable_new_api_stack=True) +parser.add_argument( + "--lr-const-factor", + type=float, + default=0.9, + help="The factor by which the learning rate should be multiplied.", +) +parser.add_argument( + "--lr-const-iters", + type=int, + default=10, + help=( + "The number of iterations by which the learning rate should be " + "multiplied by the factor." + ), +) +parser.add_argument( + "--lr-exp-decay", + type=float, + default=0.99, + help="The rate by which the learning rate should exponentially decay.", +) + +if __name__ == "__main__": + # Use `parser` to add your own custom command line options to this script + # and (if needed) use their values to set up `config` below. + args = parser.parse_args() + + config = ( + PPOConfig() + .environment("CartPole-v1") + .training( + lr=0.03, + num_sgd_iter=6, + vf_loss_coeff=0.01, + ) + .rl_module( + model_config=DefaultModelConfig( + fcnet_hiddens=[32], + fcnet_activation="linear", + vf_share_layers=True, + ), + ) + .evaluation( + evaluation_num_env_runners=1, + evaluation_interval=1, + evaluation_parallel_to_training=True, + evaluation_config=PPOConfig.overrides(exploration=False), + ) + .experimental( + # Add two learning rate schedulers to be applied in sequence. + _torch_lr_scheduler_classes=[ + # Multiplies the learning rate by a factor of 0.1 for 10 iterations. + functools.partial( + torch.optim.lr_scheduler.ConstantLR, + factor=args.lr_const_factor, + total_iters=args.lr_const_iters, + ), + # Decays the learning rate after each gradients step by + # `args.lr_exp_decay`. + functools.partial( + torch.optim.lr_scheduler.ExponentialLR, gamma=args.lr_exp_decay + ), + ] + ) + .callbacks( + LRChecker, + ) + ) + + stop = { + f"{NUM_ENV_STEPS_SAMPLED_LIFETIME}": args.stop_timesteps, + f"{EVALUATION_RESULTS}/{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": ( + args.stop_reward + ), + } + + if __name__ == "__main__": + from ray.rllib.utils.test_utils import run_rllib_example_script_experiment + + run_rllib_example_script_experiment(config, args, stop=stop) diff --git a/vllm/lib/python3.10/site-packages/ray/rllib/examples/learners/separate_vf_lr_and_optimizer.py b/vllm/lib/python3.10/site-packages/ray/rllib/examples/learners/separate_vf_lr_and_optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..1e5359f1162b9b280e08273c81cb10284d1d8d19 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/rllib/examples/learners/separate_vf_lr_and_optimizer.py @@ -0,0 +1,135 @@ +"""Example of how to run any value function based algo (e.g. PPO) with 2 optimizers. + +One optimizer (with its own learning rate and other configurations) is responsible for +updating the policy network, the other (with its own learning rate and other +configurations) for updating the value function network. + +This example shows: + - how to subclass an existing (torch) Learner and override its + `configure_optimizers_for_module()` method. + - how to call `Learner.register_optimizer()` from within your custom + `configure_optimizers_for_module()` method in order to specify, which optimizer + (type, learning rate, other settings) is responsible for which neural network + parameters. + - how to add custom settings (here: the additional learning rate for the + vf-optimizer) to the `AlgorithmConfig` in order to not have to subclass and write + your own (you could still do that, but are not required to). + - how to plug in the custom Learner into your config and then run the + experiment. + +See the :py:class:`~ray.rllib.examples.learners.classes.separate_vf_lr_and_optimizer_learner.PPOTorchLearnerWithSeparateVfOptimizer` # noqa +class for details on how to override the main (torch) `configure_optimizers_for_module` +function. + +We assume here that the users properly sets up their RLModule to have separate policy- +and value function networks. If any model pieces are shared between the two optimizers, +you should experience learning instability up to the point where your algorithm can't +learn any useful policy anymore. + + +How to run this script +---------------------- +`python [script file name].py --enable-new-api-stack --lr-vf=0.001 --lr-policy=0.0005` + +Use the `--lr-policy` option to set the policy learning rate (used by the policy +optimizer) and the `--lr-vf` option to set the value function learning rate (used by the +value function optimizer). + +For debugging, use the following additional command line options +`--no-tune --num-env-runners=0` +which should allow you to set breakpoints anywhere in the RLlib code and +have the execution stop there for inspection and debugging. + +For logging to your WandB account, use: +`--wandb-key=[your WandB API key] --wandb-project=[some project name] +--wandb-run-name=[optional: WandB run name (within the defined project)]` + + +Results to expect +----------------- +You should expect to observe decent learning behavior from your console output: + +With --lr-vf=0.0005 and --lr-policy=0.001 ++-----------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +| | | | | +|-----------------------------+------------+-----------------+--------+ +| PPO_CartPole-v1_7b404_00000 | TERMINATED | 127.0.0.1:16845 | 19 | ++-----------------------------+------------+-----------------+--------+ ++------------------+------------------------+---------------------+ +| total time (s) | num_env_steps_sampled_ | episode_return_mean | +| | _lifetime | | +|------------------+------------------------+---------------------+ +| 19.4179 | 76000 | 459.94 | ++------------------+------------------------+---------------------+ +""" + +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.examples.learners.classes.separate_vf_lr_and_optimizer_learner import ( + PPOTorchLearnerWithSeparateVfOptimizer, +) +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) + +torch, _ = try_import_torch() + + +parser = add_rllib_example_script_args(default_reward=450.0) +parser.set_defaults(enable_new_api_stack=True) +parser.add_argument( + "--lr-vf", + type=float, + default=0.0005, + help="The learning rate used in the value function optimizer.", +) +parser.add_argument( + "--lr-policy", + type=float, + default=0.001, + help="The learning rate used in the policy optimizer.", +) + + +if __name__ == "__main__": + args = parser.parse_args() + + assert ( + args.enable_new_api_stack + ), "Must set --enable-new-api-stack when running this script!" + assert args.algo == "PPO", "Must set --algo=PPO when running this script!" + + base_config = ( + PPOConfig() + .environment("CartPole-v1") + .training( + # This is the most important setting in this script: We point our PPO + # algorithm to use the custom Learner (instead of the default + # PPOTorchLearner). + learner_class=PPOTorchLearnerWithSeparateVfOptimizer, + # We use this simple method here to inject a new setting that our + # custom Learner class uses in its `configure_optimizers_for_module` + # method. This is convenient and avoids having to subclass `PPOConfig` only + # to add a few new settings to it. Within our Learner, we can access this + # new setting through: + # `self.config.learner_config_dict['lr_vf']` + learner_config_dict={"lr_vf": args.lr_vf}, + # Some settings to make this example learn better. + num_epochs=6, + # Since we are using separate optimizers for the two NN components, the + # value of `vf_loss_coeff` does not matter anymore. We set this to 1.0 here. + vf_loss_coeff=1.0, + # The policy learning rate, settable through the command line `--lr` arg. + lr=args.lr_policy, + ) + .rl_module( + # Another very important setting is this here. Make sure you use + # completely separate NNs for policy and value-functions. + model_config=DefaultModelConfig(vf_share_layers=False), + ) + ) + + run_rllib_example_script_experiment(base_config, args)