ZTWHHH commited on
Commit
84d93a0
·
verified ·
1 Parent(s): d114ec7

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/__init__.cpython-310.pyc +0 -0
  2. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/attention_net_supervised.cpython-310.pyc +0 -0
  3. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/complex_struct_space.cpython-310.pyc +0 -0
  4. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/custom_keras_model.cpython-310.pyc +0 -0
  5. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/parametric_actions_cartpole.cpython-310.pyc +0 -0
  6. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/parametric_actions_cartpole_embeddings_learnt_by_model.cpython-310.pyc +0 -0
  7. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/remote_base_env_with_custom_api.cpython-310.pyc +0 -0
  8. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/remote_envs_with_inference_done_on_main_node.cpython-310.pyc +0 -0
  9. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/sb2rllib_rllib_example.cpython-310.pyc +0 -0
  10. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/sb2rllib_sb_example.cpython-310.pyc +0 -0
  11. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/action_mask_model.cpython-310.pyc +0 -0
  12. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/batch_norm_model.cpython-310.pyc +0 -0
  13. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/centralized_critic_models.cpython-310.pyc +0 -0
  14. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/custom_loss_model.cpython-310.pyc +0 -0
  15. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/custom_model_api.cpython-310.pyc +0 -0
  16. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/eager_model.cpython-310.pyc +0 -0
  17. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/mobilenet_v2_encoder.cpython-310.pyc +0 -0
  18. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/mobilenet_v2_with_lstm_models.cpython-310.pyc +0 -0
  19. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/parametric_actions_model.cpython-310.pyc +0 -0
  20. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/shared_weights_model.cpython-310.pyc +0 -0
  21. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/simple_rpg_model.cpython-310.pyc +0 -0
  22. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/trajectory_view_utilizing_models.cpython-310.pyc +0 -0
  23. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__init__.py +0 -0
  24. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/__init__.cpython-310.pyc +0 -0
  25. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/cliff_walking_wall_policy.cpython-310.pyc +0 -0
  26. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/episode_env_aware_policy.cpython-310.pyc +0 -0
  27. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/memory_leaking_policy.cpython-310.pyc +0 -0
  28. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/random_policy.cpython-310.pyc +0 -0
  29. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/rock_paper_scissors_dummies.cpython-310.pyc +0 -0
  30. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/cliff_walking_wall_policy.py +100 -0
  31. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/episode_env_aware_policy.py +134 -0
  32. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/memory_leaking_policy.py +60 -0
  33. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/random_policy.py +101 -0
  34. vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/rock_paper_scissors_dummies.py +96 -0
  35. vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__init__.py +0 -0
  36. vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/__init__.cpython-310.pyc +0 -0
  37. vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/cartpole_dqn_export.cpython-310.pyc +0 -0
  38. vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/checkpoint_by_custom_criteria.cpython-310.pyc +0 -0
  39. vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/continue_training_from_checkpoint.cpython-310.pyc +0 -0
  40. vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/onnx_tf.cpython-310.pyc +0 -0
  41. vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/onnx_torch.cpython-310.pyc +0 -0
  42. vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/onnx_torch_lstm.cpython-310.pyc +0 -0
  43. vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/restore_1_of_n_agents_from_checkpoint.cpython-310.pyc +0 -0
  44. vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/cartpole_dqn_export.py +77 -0
  45. vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/checkpoint_by_custom_criteria.py +146 -0
  46. vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/continue_training_from_checkpoint.py +268 -0
  47. vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/onnx_tf.py +91 -0
  48. vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/onnx_torch.py +79 -0
  49. vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/onnx_torch_lstm.py +136 -0
  50. vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/restore_1_of_n_agents_from_checkpoint.py +160 -0
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (183 Bytes). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/attention_net_supervised.cpython-310.pyc ADDED
Binary file (2.72 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/complex_struct_space.cpython-310.pyc ADDED
Binary file (1.78 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/custom_keras_model.cpython-310.pyc ADDED
Binary file (5.1 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/parametric_actions_cartpole.cpython-310.pyc ADDED
Binary file (3.18 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/parametric_actions_cartpole_embeddings_learnt_by_model.cpython-310.pyc ADDED
Binary file (2.97 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/remote_base_env_with_custom_api.cpython-310.pyc ADDED
Binary file (5.04 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/remote_envs_with_inference_done_on_main_node.cpython-310.pyc ADDED
Binary file (4.14 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/sb2rllib_rllib_example.cpython-310.pyc ADDED
Binary file (1.61 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/__pycache__/sb2rllib_sb_example.cpython-310.pyc ADDED
Binary file (1.26 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/action_mask_model.cpython-310.pyc ADDED
Binary file (3.25 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/batch_norm_model.cpython-310.pyc ADDED
Binary file (6.57 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/centralized_critic_models.cpython-310.pyc ADDED
Binary file (6.24 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/custom_loss_model.cpython-310.pyc ADDED
Binary file (4.94 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/custom_model_api.cpython-310.pyc ADDED
Binary file (3.41 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/eager_model.cpython-310.pyc ADDED
Binary file (2.63 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/mobilenet_v2_encoder.cpython-310.pyc ADDED
Binary file (2.19 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/mobilenet_v2_with_lstm_models.cpython-310.pyc ADDED
Binary file (4.83 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/parametric_actions_model.cpython-310.pyc ADDED
Binary file (5.01 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/shared_weights_model.cpython-310.pyc ADDED
Binary file (5.62 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/simple_rpg_model.cpython-310.pyc ADDED
Binary file (2.35 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/models/__pycache__/trajectory_view_utilizing_models.cpython-310.pyc ADDED
Binary file (4.15 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (190 Bytes). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/cliff_walking_wall_policy.cpython-310.pyc ADDED
Binary file (3.65 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/episode_env_aware_policy.cpython-310.pyc ADDED
Binary file (5.3 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/memory_leaking_policy.cpython-310.pyc ADDED
Binary file (2.09 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/random_policy.cpython-310.pyc ADDED
Binary file (3.48 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/__pycache__/rock_paper_scissors_dummies.cpython-310.pyc ADDED
Binary file (3.51 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/cliff_walking_wall_policy.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @OldAPIStack
2
+ import gymnasium as gym
3
+ from typing import Dict, Union, List, Tuple, Optional
4
+ import numpy as np
5
+
6
+ from ray.rllib.policy.policy import Policy, ViewRequirement
7
+ from ray.rllib.policy.sample_batch import SampleBatch
8
+ from ray.rllib.models.torch.torch_action_dist import TorchCategorical
9
+ from ray.rllib.utils.typing import AlgorithmConfigDict, TensorStructType, TensorType
10
+ from ray.rllib.utils.annotations import override
11
+ from ray.rllib.utils.debug import update_global_seed_if_necessary
12
+
13
+
14
+ class CliffWalkingWallPolicy(Policy):
15
+ """Optimal RLlib policy for the CliffWalkingWallEnv environment, defined in
16
+ ray/rllib/examples/env/cliff_walking_wall_env.py, with epsilon-greedy exploration.
17
+
18
+ The policy takes a random action with probability epsilon, specified
19
+ by `config["epsilon"]`, and the optimal action with probability 1 - epsilon.
20
+ """
21
+
22
+ @override(Policy)
23
+ def __init__(
24
+ self,
25
+ observation_space: gym.Space,
26
+ action_space: gym.Space,
27
+ config: AlgorithmConfigDict,
28
+ ):
29
+ update_global_seed_if_necessary(seed=config.get("seed"))
30
+ super().__init__(observation_space, action_space, config)
31
+
32
+ # Known optimal action dist for each of the 48 states and 4 actions
33
+ self.action_dist = np.zeros((48, 4), dtype=float)
34
+ # Starting state: go up
35
+ self.action_dist[36] = (1, 0, 0, 0)
36
+ # Cliff + Goal: never actually used, set to random
37
+ self.action_dist[37:] = (0.25, 0.25, 0.25, 0.25)
38
+ # Row 2; always go right
39
+ self.action_dist[24:36] = (0, 1, 0, 0)
40
+ # Row 0 and Row 1; go down or go right
41
+ self.action_dist[0:24] = (0, 0.5, 0.5, 0)
42
+ # Col 11; always go down, supercedes previous values
43
+ self.action_dist[[11, 23, 35]] = (0, 0, 1, 0)
44
+ assert np.allclose(self.action_dist.sum(-1), 1)
45
+
46
+ # Epsilon-Greedy action selection
47
+ epsilon = config.get("epsilon", 0.0)
48
+ self.action_dist = self.action_dist * (1 - epsilon) + epsilon / 4
49
+ assert np.allclose(self.action_dist.sum(-1), 1)
50
+
51
+ # Attributes required for RLlib; note that while CliffWalkingWallPolicy
52
+ # inherits from Policy, it actually implements TorchPolicyV2.
53
+ self.view_requirements[SampleBatch.ACTION_PROB] = ViewRequirement()
54
+ self.device = "cpu"
55
+ self.model = None
56
+ self.dist_class = TorchCategorical
57
+
58
+ @override(Policy)
59
+ def compute_actions(
60
+ self,
61
+ obs_batch: Union[List[TensorStructType], TensorStructType],
62
+ state_batches: Optional[List[TensorType]] = None,
63
+ **kwargs,
64
+ ) -> Tuple[TensorType, List[TensorType], Dict[str, TensorType]]:
65
+ obs = np.array(obs_batch, dtype=int)
66
+ action_probs = self.action_dist[obs]
67
+ actions = np.zeros(len(obs), dtype=int)
68
+ for i in range(len(obs)):
69
+ actions[i] = np.random.choice(4, p=action_probs[i])
70
+ return (
71
+ actions,
72
+ [],
73
+ {SampleBatch.ACTION_PROB: action_probs[np.arange(len(obs)), actions]},
74
+ )
75
+
76
+ @override(Policy)
77
+ def compute_log_likelihoods(
78
+ self,
79
+ actions: Union[List[TensorType], TensorType],
80
+ obs_batch: Union[List[TensorType], TensorType],
81
+ **kwargs,
82
+ ) -> TensorType:
83
+ obs = np.array(obs_batch, dtype=int)
84
+ actions = np.array(actions, dtype=int)
85
+ # Compute action probs for all possible actions
86
+ action_probs = self.action_dist[obs]
87
+ # Take the action_probs corresponding to the specified actions
88
+ action_probs = action_probs[np.arange(len(obs)), actions]
89
+ # Ignore RuntimeWarning thrown by np.log(0) if action_probs is 0
90
+ with np.errstate(divide="ignore"):
91
+ return np.log(action_probs)
92
+
93
+ def action_distribution_fn(
94
+ self, model, obs_batch: TensorStructType, **kwargs
95
+ ) -> Tuple[TensorType, type, List[TensorType]]:
96
+ obs = np.array(obs_batch[SampleBatch.OBS], dtype=int)
97
+ action_probs = self.action_dist[obs]
98
+ # Ignore RuntimeWarning thrown by np.log(0) if action_probs is 0
99
+ with np.errstate(divide="ignore"):
100
+ return np.log(action_probs), TorchCategorical, None
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/episode_env_aware_policy.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @OldAPIStack
2
+ import numpy as np
3
+ from gymnasium.spaces import Box
4
+
5
+ from ray.rllib.core.columns import Columns
6
+ from ray.rllib.examples._old_api_stack.policy.random_policy import RandomPolicy
7
+ from ray.rllib.examples.rl_modules.classes.random_rlm import StatefulRandomRLModule
8
+ from ray.rllib.policy.policy import Policy
9
+ from ray.rllib.policy.sample_batch import SampleBatch
10
+ from ray.rllib.policy.view_requirement import ViewRequirement
11
+ from ray.rllib.utils.annotations import override
12
+
13
+
14
+ class StatefulRandomPolicy(RandomPolicy):
15
+ """A Policy that has acts randomly and has stateful view requirements."""
16
+
17
+ def __init__(self, *args, **kwargs):
18
+ super().__init__(*args, **kwargs)
19
+ self.model = StatefulRandomRLModule(
20
+ action_space=self.action_space,
21
+ model_config={
22
+ "max_seq_len": 50,
23
+ "lstm_use_prev_action": False,
24
+ "lstm_use_prev_reward": False,
25
+ },
26
+ )
27
+
28
+ self.view_requirements = self.model.update_default_view_requirements(
29
+ self.view_requirements
30
+ )
31
+
32
+ @override(Policy)
33
+ def is_recurrent(self):
34
+ return True
35
+
36
+ @override(Policy)
37
+ def postprocess_trajectory(
38
+ self, sample_batch, other_agent_batches=None, episode=None
39
+ ):
40
+ sample_batch["2xobs"] = sample_batch["obs"] * 2.0
41
+ return sample_batch
42
+
43
+ @override(Policy)
44
+ def compute_actions_from_input_dict(self, input_dict, *args, **kwargs):
45
+ fwd_out = self.model.forward_exploration(input_dict)
46
+ actions = fwd_out[SampleBatch.ACTIONS]
47
+ state_out = fwd_out[Columns.STATE_OUT]
48
+ return actions, state_out, {}
49
+
50
+
51
+ class EpisodeEnvAwareAttentionPolicy(RandomPolicy):
52
+ """A Policy that always knows the current EpisodeID and EnvID and
53
+ returns these in its actions."""
54
+
55
+ def __init__(self, *args, **kwargs):
56
+ super().__init__(*args, **kwargs)
57
+ self.state_space = Box(-1.0, 1.0, (1,))
58
+ self.config["model"] = {"max_seq_len": 50}
59
+
60
+ class _fake_model:
61
+ def __init__(self, state_space, config):
62
+ self.state_space = state_space
63
+ self.view_requirements = {
64
+ SampleBatch.AGENT_INDEX: ViewRequirement(),
65
+ SampleBatch.EPS_ID: ViewRequirement(),
66
+ "env_id": ViewRequirement(),
67
+ "t": ViewRequirement(),
68
+ SampleBatch.OBS: ViewRequirement(),
69
+ "state_in_0": ViewRequirement(
70
+ "state_out_0",
71
+ # Provide state outs -50 to -1 as "state-in".
72
+ shift="-50:-1",
73
+ # Repeat the incoming state every n time steps (usually max seq
74
+ # len).
75
+ batch_repeat_value=config["model"]["max_seq_len"],
76
+ space=state_space,
77
+ ),
78
+ "state_out_0": ViewRequirement(
79
+ space=state_space, used_for_compute_actions=False
80
+ ),
81
+ }
82
+
83
+ def compile(self, *args, **kwargs):
84
+ """Dummy method for compatibility with TorchRLModule.
85
+
86
+ This is hit when RolloutWorker tries to compile TorchRLModule."""
87
+ pass
88
+
89
+ # We need to provide at least an initial state if we want agent collector
90
+ # to build episodes with state_in_ and state_out_
91
+ def get_initial_state(self):
92
+ return [self.state_space.sample()]
93
+
94
+ self.model = _fake_model(self.state_space, self.config)
95
+
96
+ self.view_requirements = dict(
97
+ super()._get_default_view_requirements(), **self.model.view_requirements
98
+ )
99
+
100
+ @override(Policy)
101
+ def get_initial_state(self):
102
+ return self.model.get_initial_state()
103
+
104
+ @override(Policy)
105
+ def is_recurrent(self):
106
+ return True
107
+
108
+ @override(Policy)
109
+ def compute_actions_from_input_dict(
110
+ self, input_dict, explore=None, timestep=None, **kwargs
111
+ ):
112
+ ts = input_dict["t"]
113
+ print(ts)
114
+ # Always return [episodeID, envID] as actions.
115
+ actions = np.array(
116
+ [
117
+ [
118
+ input_dict[SampleBatch.AGENT_INDEX][i],
119
+ input_dict[SampleBatch.EPS_ID][i],
120
+ input_dict["env_id"][i],
121
+ ]
122
+ for i, _ in enumerate(input_dict["obs"])
123
+ ]
124
+ )
125
+ states = [np.array([[ts[i]] for i in range(len(input_dict["obs"]))])]
126
+ self.global_timestep += 1
127
+ return actions, states, {}
128
+
129
+ @override(Policy)
130
+ def postprocess_trajectory(
131
+ self, sample_batch, other_agent_batches=None, episode=None
132
+ ):
133
+ sample_batch["3xobs"] = sample_batch["obs"] * 3.0
134
+ return sample_batch
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/memory_leaking_policy.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @OldAPIStack
2
+ import gymnasium as gym
3
+
4
+ from ray.rllib.examples._old_api_stack.policy.random_policy import RandomPolicy
5
+ from ray.rllib.utils.annotations import override
6
+ from ray.rllib.utils.typing import AlgorithmConfigDict
7
+
8
+
9
+ class MemoryLeakingPolicy(RandomPolicy):
10
+ """A Policy that leaks very little memory.
11
+
12
+ Useful for proving that our memory-leak tests can catch the
13
+ slightest leaks.
14
+ """
15
+
16
+ def __init__(
17
+ self,
18
+ observation_space: gym.Space,
19
+ action_space: gym.Space,
20
+ config: AlgorithmConfigDict,
21
+ ):
22
+ super().__init__(observation_space, action_space, config)
23
+ self._leakage_size = config.get("leakage_size", "small")
24
+ self._leak = []
25
+
26
+ @override(RandomPolicy)
27
+ def compute_actions(self, *args, **kwargs):
28
+ # Leak.
29
+ if self._leakage_size == "small":
30
+ self._leak.append(1.5)
31
+ else:
32
+ self._leak.append([1.5] * 100)
33
+ return super().compute_actions(*args, **kwargs)
34
+
35
+ @override(RandomPolicy)
36
+ def compute_actions_from_input_dict(self, *args, **kwargs):
37
+ # Leak.
38
+ if self._leakage_size == "small":
39
+ self._leak.append(1)
40
+ else:
41
+ self._leak.append([1] * 100)
42
+ return super().compute_actions_from_input_dict(*args, **kwargs)
43
+
44
+ @override(RandomPolicy)
45
+ def learn_on_batch(self, samples):
46
+ # Leak.
47
+ if self._leakage_size == "small":
48
+ self._leak.append(False)
49
+ else:
50
+ self._leak.append([False] * 100)
51
+ return super().learn_on_batch(samples)
52
+
53
+ @override(RandomPolicy)
54
+ def compute_log_likelihoods(self, *args, **kwargs):
55
+ # Leak.
56
+ if self._leakage_size == "small":
57
+ self._leak.append("test")
58
+ else:
59
+ self._leak.append(["test"] * 100)
60
+ return super().compute_log_likelihoods(*args, **kwargs)
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/random_policy.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @OldAPIStack
2
+ from gymnasium.spaces import Box
3
+ import numpy as np
4
+ import random
5
+ import tree # pip install dm_tree
6
+ from typing import (
7
+ List,
8
+ Optional,
9
+ Union,
10
+ )
11
+
12
+ from ray.rllib.policy.policy import Policy
13
+ from ray.rllib.policy.sample_batch import SampleBatch
14
+ from ray.rllib.utils.annotations import override
15
+ from ray.rllib.utils.typing import ModelWeights, TensorStructType, TensorType
16
+
17
+
18
+ class RandomPolicy(Policy):
19
+ """Hand-coded policy that returns random actions."""
20
+
21
+ def __init__(self, *args, **kwargs):
22
+ super().__init__(*args, **kwargs)
23
+
24
+ # Whether for compute_actions, the bounds given in action_space
25
+ # should be ignored (default: False). This is to test action-clipping
26
+ # and any Env's reaction to bounds breaches.
27
+ if self.config.get("ignore_action_bounds", False) and isinstance(
28
+ self.action_space, Box
29
+ ):
30
+ self.action_space_for_sampling = Box(
31
+ -float("inf"),
32
+ float("inf"),
33
+ shape=self.action_space.shape,
34
+ dtype=self.action_space.dtype,
35
+ )
36
+ else:
37
+ self.action_space_for_sampling = self.action_space
38
+
39
+ @override(Policy)
40
+ def init_view_requirements(self):
41
+ super().init_view_requirements()
42
+ # Disable for_training and action attributes for SampleBatch.INFOS column
43
+ # since it can not be properly batched.
44
+ vr = self.view_requirements[SampleBatch.INFOS]
45
+ vr.used_for_training = False
46
+ vr.used_for_compute_actions = False
47
+
48
+ @override(Policy)
49
+ def compute_actions(
50
+ self,
51
+ obs_batch: Union[List[TensorStructType], TensorStructType],
52
+ state_batches: Optional[List[TensorType]] = None,
53
+ prev_action_batch: Union[List[TensorStructType], TensorStructType] = None,
54
+ prev_reward_batch: Union[List[TensorStructType], TensorStructType] = None,
55
+ **kwargs,
56
+ ):
57
+ # Alternatively, a numpy array would work here as well.
58
+ # e.g.: np.array([random.choice([0, 1])] * len(obs_batch))
59
+ obs_batch_size = len(tree.flatten(obs_batch)[0])
60
+ return (
61
+ [self.action_space_for_sampling.sample() for _ in range(obs_batch_size)],
62
+ [],
63
+ {},
64
+ )
65
+
66
+ @override(Policy)
67
+ def learn_on_batch(self, samples):
68
+ """No learning."""
69
+ return {}
70
+
71
+ @override(Policy)
72
+ def compute_log_likelihoods(
73
+ self,
74
+ actions,
75
+ obs_batch,
76
+ state_batches=None,
77
+ prev_action_batch=None,
78
+ prev_reward_batch=None,
79
+ **kwargs,
80
+ ):
81
+ return np.array([random.random()] * len(obs_batch))
82
+
83
+ @override(Policy)
84
+ def get_weights(self) -> ModelWeights:
85
+ """No weights to save."""
86
+ return {}
87
+
88
+ @override(Policy)
89
+ def set_weights(self, weights: ModelWeights) -> None:
90
+ """No weights to set."""
91
+ pass
92
+
93
+ @override(Policy)
94
+ def _get_dummy_batch_from_view_requirements(self, batch_size: int = 1):
95
+ return SampleBatch(
96
+ {
97
+ SampleBatch.OBS: tree.map_structure(
98
+ lambda s: s[None], self.observation_space.sample()
99
+ ),
100
+ }
101
+ )
vllm/lib/python3.10/site-packages/ray/rllib/examples/_old_api_stack/policy/rock_paper_scissors_dummies.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @OldAPIStack
2
+ import gymnasium as gym
3
+ import numpy as np
4
+ import random
5
+ from ray.rllib.policy.policy import Policy
6
+ from ray.rllib.policy.view_requirement import ViewRequirement
7
+
8
+ ROCK = 0
9
+ PAPER = 1
10
+ SCISSORS = 2
11
+
12
+
13
+ class AlwaysSameHeuristic(Policy):
14
+ """Pick a random move and stick with it for the entire episode."""
15
+
16
+ def __init__(self, *args, **kwargs):
17
+ super().__init__(*args, **kwargs)
18
+ self.exploration = self._create_exploration()
19
+ self.view_requirements.update(
20
+ {
21
+ "state_in_0": ViewRequirement(
22
+ "state_out_0",
23
+ shift=-1,
24
+ space=gym.spaces.Box(ROCK, SCISSORS, shape=(1,), dtype=np.int32),
25
+ )
26
+ }
27
+ )
28
+
29
+ def get_initial_state(self):
30
+ return [random.choice([ROCK, PAPER, SCISSORS])]
31
+
32
+ def is_recurrent(self) -> bool:
33
+ return True
34
+
35
+ def compute_actions(
36
+ self,
37
+ obs_batch,
38
+ state_batches=None,
39
+ prev_action_batch=None,
40
+ prev_reward_batch=None,
41
+ info_batch=None,
42
+ episodes=None,
43
+ **kwargs
44
+ ):
45
+ return [state_batches[0][0] for x in obs_batch], state_batches, {}
46
+
47
+
48
+ class BeatLastHeuristic(Policy):
49
+ """Play the move that would beat the last move of the opponent."""
50
+
51
+ def __init__(self, *args, **kwargs):
52
+ super().__init__(*args, **kwargs)
53
+ self.exploration = self._create_exploration()
54
+
55
+ def compute_actions(
56
+ self,
57
+ obs_batch,
58
+ state_batches=None,
59
+ prev_action_batch=None,
60
+ prev_reward_batch=None,
61
+ info_batch=None,
62
+ episodes=None,
63
+ **kwargs
64
+ ):
65
+ def successor(x):
66
+ # Make this also work w/o one-hot preprocessing.
67
+ if isinstance(self.observation_space, gym.spaces.Discrete):
68
+ if x == ROCK:
69
+ return PAPER
70
+ elif x == PAPER:
71
+ return SCISSORS
72
+ elif x == SCISSORS:
73
+ return ROCK
74
+ else:
75
+ return random.choice([ROCK, PAPER, SCISSORS])
76
+ # One-hot (auto-preprocessed) inputs.
77
+ else:
78
+ if x[ROCK] == 1:
79
+ return PAPER
80
+ elif x[PAPER] == 1:
81
+ return SCISSORS
82
+ elif x[SCISSORS] == 1:
83
+ return ROCK
84
+ elif x[-1] == 1:
85
+ return random.choice([ROCK, PAPER, SCISSORS])
86
+
87
+ return [successor(x) for x in obs_batch], [], {}
88
+
89
+ def learn_on_batch(self, samples):
90
+ pass
91
+
92
+ def get_weights(self):
93
+ pass
94
+
95
+ def set_weights(self, weights):
96
+ pass
vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (180 Bytes). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/cartpole_dqn_export.cpython-310.pyc ADDED
Binary file (2.38 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/checkpoint_by_custom_criteria.cpython-310.pyc ADDED
Binary file (4.87 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/continue_training_from_checkpoint.cpython-310.pyc ADDED
Binary file (9.88 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/onnx_tf.cpython-310.pyc ADDED
Binary file (1.88 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/onnx_torch.cpython-310.pyc ADDED
Binary file (1.54 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/onnx_torch_lstm.cpython-310.pyc ADDED
Binary file (3.12 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/__pycache__/restore_1_of_n_agents_from_checkpoint.cpython-310.pyc ADDED
Binary file (5.05 kB). View file
 
vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/cartpole_dqn_export.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # @OldAPIStack
4
+
5
+ import numpy as np
6
+ import os
7
+ import ray
8
+
9
+ from ray.rllib.policy.policy import Policy
10
+ from ray.rllib.utils.framework import try_import_tf
11
+ from ray.tune.registry import get_trainable_cls
12
+
13
+ tf1, tf, tfv = try_import_tf()
14
+
15
+ ray.init()
16
+
17
+
18
+ def train_and_export_policy_and_model(algo_name, num_steps, model_dir, ckpt_dir):
19
+ cls = get_trainable_cls(algo_name)
20
+ config = cls.get_default_config()
21
+ config.api_stack(
22
+ enable_rl_module_and_learner=False,
23
+ enable_env_runner_and_connector_v2=False,
24
+ )
25
+ # This Example is only for tf.
26
+ config.framework("tf")
27
+ # Set exporting native (DL-framework) model files to True.
28
+ config.export_native_model_files = True
29
+ config.env = "CartPole-v1"
30
+ alg = config.build()
31
+ for _ in range(num_steps):
32
+ alg.train()
33
+
34
+ # Export Policy checkpoint.
35
+ alg.export_policy_checkpoint(ckpt_dir)
36
+ # Export tensorflow keras Model for online serving
37
+ alg.export_policy_model(model_dir)
38
+
39
+
40
+ def restore_saved_model(export_dir):
41
+ signature_key = (
42
+ tf1.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
43
+ )
44
+ g = tf1.Graph()
45
+ with g.as_default():
46
+ with tf1.Session(graph=g) as sess:
47
+ meta_graph_def = tf1.saved_model.load(
48
+ sess, [tf1.saved_model.tag_constants.SERVING], export_dir
49
+ )
50
+ print("Model restored!")
51
+ print("Signature Def Information:")
52
+ print(meta_graph_def.signature_def[signature_key])
53
+ print("You can inspect the model using TensorFlow SavedModel CLI.")
54
+ print("https://www.tensorflow.org/guide/saved_model")
55
+
56
+
57
+ def restore_policy_from_checkpoint(export_dir):
58
+ # Load the model from the checkpoint.
59
+ policy = Policy.from_checkpoint(export_dir)
60
+ # Perform a dummy (CartPole) forward pass.
61
+ test_obs = np.array([0.1, 0.2, 0.3, 0.4])
62
+ results = policy.compute_single_action(test_obs)
63
+ # Check results for correctness.
64
+ assert len(results) == 3
65
+ assert results[0].shape == () # pure single action (int)
66
+ assert results[1] == [] # RNN states
67
+ assert results[2]["action_dist_inputs"].shape == (2,) # categorical inputs
68
+
69
+
70
+ if __name__ == "__main__":
71
+ algo = "PPO"
72
+ model_dir = os.path.join(ray._private.utils.get_user_temp_dir(), "model_export_dir")
73
+ ckpt_dir = os.path.join(ray._private.utils.get_user_temp_dir(), "ckpt_export_dir")
74
+ num_steps = 1
75
+ train_and_export_policy_and_model(algo, num_steps, model_dir, ckpt_dir)
76
+ restore_saved_model(model_dir)
77
+ restore_policy_from_checkpoint(ckpt_dir)
vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/checkpoint_by_custom_criteria.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Example extracting a checkpoint from n trials using one or more custom criteria.
2
+
3
+ This example:
4
+ - runs a CartPole experiment with three different learning rates (three tune
5
+ "trials"). During the experiment, for each trial, we create a checkpoint at each
6
+ iteration.
7
+ - at the end of the experiment, we compare the trials and pick the one that
8
+ performed best, based on the criterion: Lowest episode count per single iteration
9
+ (for CartPole, a low episode count means the episodes are very long and thus the
10
+ reward is also very high).
11
+ - from that best trial (with the lowest episode count), we then pick those
12
+ checkpoints that a) have the lowest policy loss (good) and b) have the highest value
13
+ function loss (bad).
14
+
15
+
16
+ How to run this script
17
+ ----------------------
18
+ `python [script file name].py --enable-new-api-stack`
19
+
20
+ For debugging, use the following additional command line options
21
+ `--no-tune --num-env-runners=0`
22
+ which should allow you to set breakpoints anywhere in the RLlib code and
23
+ have the execution stop there for inspection and debugging.
24
+
25
+ For logging to your WandB account, use:
26
+ `--wandb-key=[your WandB API key] --wandb-project=[some project name]
27
+ --wandb-run-name=[optional: WandB run name (within the defined project)]`
28
+
29
+
30
+ Results to expect
31
+ -----------------
32
+ In the console output, you can see the performance of the three different learning
33
+ rates used here:
34
+
35
+ +-----------------------------+------------+-----------------+--------+--------+
36
+ | Trial name | status | loc | lr | iter |
37
+ |-----------------------------+------------+-----------------+--------+--------+
38
+ | PPO_CartPole-v1_d7dbe_00000 | TERMINATED | 127.0.0.1:98487 | 0.01 | 17 |
39
+ | PPO_CartPole-v1_d7dbe_00001 | TERMINATED | 127.0.0.1:98488 | 0.001 | 8 |
40
+ | PPO_CartPole-v1_d7dbe_00002 | TERMINATED | 127.0.0.1:98489 | 0.0001 | 9 |
41
+ +-----------------------------+------------+-----------------+--------+--------+
42
+
43
+ +------------------+-------+----------+----------------------+----------------------+
44
+ | total time (s) | ts | reward | episode_reward_max | episode_reward_min |
45
+ |------------------+-------+----------+----------------------+----------------------+
46
+ | 28.1068 | 39797 | 151.11 | 500 | 12 |
47
+ | 13.304 | 18728 | 158.91 | 500 | 15 |
48
+ | 14.8848 | 21069 | 167.36 | 500 | 13 |
49
+ +------------------+-------+----------+----------------------+----------------------+
50
+
51
+ +--------------------+
52
+ | episode_len_mean |
53
+ |--------------------|
54
+ | 151.11 |
55
+ | 158.91 |
56
+ | 167.36 |
57
+ +--------------------+
58
+ """
59
+
60
+ from ray import tune
61
+ from ray.rllib.core import DEFAULT_MODULE_ID
62
+ from ray.rllib.utils.metrics import (
63
+ ENV_RUNNER_RESULTS,
64
+ EPISODE_RETURN_MEAN,
65
+ LEARNER_RESULTS,
66
+ )
67
+ from ray.rllib.utils.test_utils import (
68
+ add_rllib_example_script_args,
69
+ run_rllib_example_script_experiment,
70
+ )
71
+ from ray.tune.registry import get_trainable_cls
72
+
73
+ parser = add_rllib_example_script_args(
74
+ default_reward=450.0, default_timesteps=100000, default_iters=200
75
+ )
76
+
77
+
78
+ if __name__ == "__main__":
79
+ args = parser.parse_args()
80
+
81
+ # Force-set `args.checkpoint_freq` to 1.
82
+ args.checkpoint_freq = 1
83
+
84
+ # Simple generic config.
85
+ base_config = (
86
+ get_trainable_cls(args.algo)
87
+ .get_default_config()
88
+ .environment("CartPole-v1")
89
+ # Run 3 trials, each w/ a different learning rate.
90
+ .training(lr=tune.grid_search([0.01, 0.001, 0.0001]), train_batch_size=2341)
91
+ )
92
+ # Run tune for some iterations and generate checkpoints.
93
+ results = run_rllib_example_script_experiment(base_config, args)
94
+
95
+ # Get the best of the 3 trials by using some metric.
96
+ # NOTE: Choosing the min `episodes_this_iter` automatically picks the trial
97
+ # with the best performance (over the entire run (scope="all")):
98
+ # The fewer episodes, the longer each episode lasted, the more reward we
99
+ # got each episode.
100
+ # Setting scope to "last", "last-5-avg", or "last-10-avg" will only compare
101
+ # (using `mode=min|max`) the average values of the last 1, 5, or 10
102
+ # iterations with each other, respectively.
103
+ # Setting scope to "avg" will compare (using `mode`=min|max) the average
104
+ # values over the entire run.
105
+ metric = "env_runners/num_episodes"
106
+ # notice here `scope` is `all`, meaning for each trial,
107
+ # all results (not just the last one) will be examined.
108
+ best_result = results.get_best_result(metric=metric, mode="min", scope="all")
109
+ value_best_metric = best_result.metrics_dataframe[metric].min()
110
+ best_return_best = best_result.metrics_dataframe[
111
+ f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}"
112
+ ].max()
113
+ print(
114
+ f"Best trial was the one with lr={best_result.metrics['config']['lr']}. "
115
+ f"Reached lowest episode count ({value_best_metric}) in a single iteration and "
116
+ f"an average return of {best_return_best}."
117
+ )
118
+
119
+ # Confirm, we picked the right trial.
120
+
121
+ assert (
122
+ value_best_metric
123
+ == results.get_dataframe(filter_metric=metric, filter_mode="min")[metric].min()
124
+ )
125
+
126
+ # Get the best checkpoints from the trial, based on different metrics.
127
+ # Checkpoint with the lowest policy loss value:
128
+ if args.enable_new_api_stack:
129
+ policy_loss_key = f"{LEARNER_RESULTS}/{DEFAULT_MODULE_ID}/policy_loss"
130
+ else:
131
+ policy_loss_key = "info/learner/default_policy/learner_stats/policy_loss"
132
+ best_result = results.get_best_result(metric=policy_loss_key, mode="min")
133
+ ckpt = best_result.checkpoint
134
+ lowest_policy_loss = best_result.metrics_dataframe[policy_loss_key].min()
135
+ print(f"Checkpoint w/ lowest policy loss ({lowest_policy_loss}): {ckpt}")
136
+
137
+ # Checkpoint with the highest value-function loss:
138
+ if args.enable_new_api_stack:
139
+ vf_loss_key = f"{LEARNER_RESULTS}/{DEFAULT_MODULE_ID}/vf_loss"
140
+ else:
141
+ vf_loss_key = "info/learner/default_policy/learner_stats/vf_loss"
142
+ best_result = results.get_best_result(metric=vf_loss_key, mode="max")
143
+ ckpt = best_result.checkpoint
144
+ highest_value_fn_loss = best_result.metrics_dataframe[vf_loss_key].max()
145
+ print(f"Checkpoint w/ highest value function loss: {ckpt}")
146
+ print(f"Highest value function loss: {highest_value_fn_loss}")
vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/continue_training_from_checkpoint.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Example showing how to restore an Algorithm from a checkpoint and resume training.
2
+
3
+ Use the setup shown in this script if your experiments tend to crash after some time,
4
+ and you would therefore like to make your setup more robust and fault-tolerant.
5
+
6
+ This example:
7
+ - runs a single- or multi-agent CartPole experiment (for multi-agent, we use
8
+ different learning rates) thereby checkpointing the state of the Algorithm every n
9
+ iterations.
10
+ - stops the experiment due to an expected crash in the algorithm's main process
11
+ after a certain number of iterations.
12
+ - just for testing purposes, restores the entire algorithm from the latest
13
+ checkpoint and checks, whether the state of the restored algo exactly match the
14
+ state of the crashed one.
15
+ - then continues training with the restored algorithm until the desired final
16
+ episode return is reached.
17
+
18
+
19
+ How to run this script
20
+ ----------------------
21
+ `python [script file name].py --enable-new-api-stack --num-agents=[0 or 2]
22
+ --stop-reward-crash=[the episode return after which the algo should crash]
23
+ --stop-reward=[the final episode return to achieve after(!) restoration from the
24
+ checkpoint]
25
+ `
26
+
27
+ For debugging, use the following additional command line options
28
+ `--no-tune --num-env-runners=0`
29
+ which should allow you to set breakpoints anywhere in the RLlib code and
30
+ have the execution stop there for inspection and debugging.
31
+
32
+ For logging to your WandB account, use:
33
+ `--wandb-key=[your WandB API key] --wandb-project=[some project name]
34
+ --wandb-run-name=[optional: WandB run name (within the defined project)]`
35
+
36
+
37
+ Results to expect
38
+ -----------------
39
+ First, you should see the initial tune.Tuner do it's thing:
40
+
41
+ Trial status: 1 RUNNING
42
+ Current time: 2024-06-03 12:03:39. Total running time: 30s
43
+ Logical resource usage: 3.0/12 CPUs, 0/0 GPUs
44
+ ╭────────────────────────────────────────────────────────────────────────
45
+ │ Trial name status iter total time (s)
46
+ ├────────────────────────────────────────────────────────────────────────
47
+ │ PPO_CartPole-v1_7b1eb_00000 RUNNING 6 15.362
48
+ ╰────────────────────────────────────────────────────────────────────────
49
+ ───────────────────────────────────────────────────────────────────────╮
50
+ ..._sampled_lifetime ..._trained_lifetime ...episodes_lifetime │
51
+ ───────────────────────────────────────────────────────────────────────┤
52
+ 24000 24000 340 │
53
+ ───────────────────────────────────────────────────────────────────────╯
54
+ ...
55
+
56
+ then, you should see the experiment crashing as soon as the `--stop-reward-crash`
57
+ has been reached:
58
+
59
+ ```RuntimeError: Intended crash after reaching trigger return.```
60
+
61
+ At some point, the experiment should resume exactly where it left off (using
62
+ the checkpoint and restored Tuner):
63
+
64
+ Trial status: 1 RUNNING
65
+ Current time: 2024-06-03 12:05:00. Total running time: 1min 0s
66
+ Logical resource usage: 3.0/12 CPUs, 0/0 GPUs
67
+ ╭────────────────────────────────────────────────────────────────────────
68
+ │ Trial name status iter total time (s)
69
+ ├────────────────────────────────────────────────────────────────────────
70
+ │ PPO_CartPole-v1_7b1eb_00000 RUNNING 27 66.1451
71
+ ╰────────────────────────────────────────────────────────────────────────
72
+ ───────────────────────────────────────────────────────────────────────╮
73
+ ..._sampled_lifetime ..._trained_lifetime ...episodes_lifetime │
74
+ ───────────────────────────────────────────────────────────────────────┤
75
+ 108000 108000 531 │
76
+ ───────────────────────────────────────────────────────────────────────╯
77
+
78
+ And if you are using the `--as-test` option, you should see a finel message:
79
+
80
+ ```
81
+ `env_runners/episode_return_mean` of 500.0 reached! ok
82
+ ```
83
+ """
84
+ import re
85
+ import time
86
+
87
+ from ray import train, tune
88
+ from ray.rllib.algorithms.algorithm_config import AlgorithmConfig
89
+ from ray.rllib.algorithms.callbacks import DefaultCallbacks
90
+ from ray.rllib.examples.envs.classes.multi_agent import MultiAgentCartPole
91
+ from ray.rllib.policy.policy import PolicySpec
92
+ from ray.rllib.utils.metrics import (
93
+ ENV_RUNNER_RESULTS,
94
+ EPISODE_RETURN_MEAN,
95
+ )
96
+ from ray.rllib.utils.test_utils import (
97
+ add_rllib_example_script_args,
98
+ check_learning_achieved,
99
+ )
100
+ from ray.tune.registry import get_trainable_cls, register_env
101
+ from ray.air.integrations.wandb import WandbLoggerCallback
102
+
103
+
104
+ parser = add_rllib_example_script_args(
105
+ default_reward=500.0, default_timesteps=10000000, default_iters=2000
106
+ )
107
+ parser.add_argument(
108
+ "--stop-reward-crash",
109
+ type=float,
110
+ default=200.0,
111
+ help="Mean episode return after which the Algorithm should crash.",
112
+ )
113
+ # By default, set `args.checkpoint_freq` to 1 and `args.checkpoint_at_end` to True.
114
+ parser.set_defaults(checkpoint_freq=1, checkpoint_at_end=True)
115
+
116
+
117
+ class CrashAfterNIters(DefaultCallbacks):
118
+ """Callback that makes the algo crash after a certain avg. return is reached."""
119
+
120
+ def __init__(self):
121
+ super().__init__()
122
+ # We have to delay crashing by one iteration just so the checkpoint still
123
+ # gets created by Tune after(!) we have reached the trigger avg. return.
124
+ self._should_crash = False
125
+
126
+ def on_train_result(self, *, algorithm, metrics_logger, result, **kwargs):
127
+ # We had already reached the mean-return to crash, the last checkpoint written
128
+ # (the one from the previous iteration) should yield that exact avg. return.
129
+ if self._should_crash:
130
+ raise RuntimeError("Intended crash after reaching trigger return.")
131
+ # Reached crashing criterion, crash on next iteration.
132
+ elif result[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] >= args.stop_reward_crash:
133
+ print(
134
+ "Reached trigger return of "
135
+ f"{result[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN]}"
136
+ )
137
+ self._should_crash = True
138
+
139
+
140
+ if __name__ == "__main__":
141
+ args = parser.parse_args()
142
+
143
+ register_env(
144
+ "ma_cart", lambda cfg: MultiAgentCartPole({"num_agents": args.num_agents})
145
+ )
146
+
147
+ # Simple generic config.
148
+ config = (
149
+ get_trainable_cls(args.algo)
150
+ .get_default_config()
151
+ .api_stack(
152
+ enable_rl_module_and_learner=args.enable_new_api_stack,
153
+ enable_env_runner_and_connector_v2=args.enable_new_api_stack,
154
+ )
155
+ .environment("CartPole-v1" if args.num_agents == 0 else "ma_cart")
156
+ .env_runners(create_env_on_local_worker=True)
157
+ .training(lr=0.0001)
158
+ .callbacks(CrashAfterNIters)
159
+ )
160
+
161
+ # Tune config.
162
+ # Need a WandB callback?
163
+ tune_callbacks = []
164
+ if args.wandb_key:
165
+ project = args.wandb_project or (
166
+ args.algo.lower() + "-" + re.sub("\\W+", "-", str(config.env).lower())
167
+ )
168
+ tune_callbacks.append(
169
+ WandbLoggerCallback(
170
+ api_key=args.wandb_key,
171
+ project=args.wandb_project,
172
+ upload_checkpoints=False,
173
+ **({"name": args.wandb_run_name} if args.wandb_run_name else {}),
174
+ )
175
+ )
176
+
177
+ # Setup multi-agent, if required.
178
+ if args.num_agents > 0:
179
+ config.multi_agent(
180
+ policies={
181
+ f"p{aid}": PolicySpec(
182
+ config=AlgorithmConfig.overrides(
183
+ lr=5e-5
184
+ * (aid + 1), # agent 1 has double the learning rate as 0.
185
+ )
186
+ )
187
+ for aid in range(args.num_agents)
188
+ },
189
+ policy_mapping_fn=lambda aid, *a, **kw: f"p{aid}",
190
+ )
191
+
192
+ # Define some stopping criterion. Note that this criterion is an avg episode return
193
+ # to be reached. The stop criterion does not consider the built-in crash we are
194
+ # triggering through our callback.
195
+ stop = {
196
+ f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": args.stop_reward,
197
+ }
198
+
199
+ # Run tune for some iterations and generate checkpoints.
200
+ tuner = tune.Tuner(
201
+ trainable=config.algo_class,
202
+ param_space=config,
203
+ run_config=train.RunConfig(
204
+ callbacks=tune_callbacks,
205
+ checkpoint_config=train.CheckpointConfig(
206
+ checkpoint_frequency=args.checkpoint_freq,
207
+ checkpoint_at_end=args.checkpoint_at_end,
208
+ ),
209
+ stop=stop,
210
+ ),
211
+ )
212
+ tuner_results = tuner.fit()
213
+
214
+ # Perform a very quick test to make sure our algo (upon restoration) did not lose
215
+ # its ability to perform well in the env.
216
+ # - Extract the best checkpoint.
217
+ metric = f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}"
218
+ best_result = tuner_results.get_best_result(metric=metric, mode="max")
219
+ assert (
220
+ best_result.metrics[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN]
221
+ >= args.stop_reward_crash
222
+ )
223
+ # - Change our config, such that the restored algo will have an env on the local
224
+ # EnvRunner (to perform evaluation) and won't crash anymore (remove the crashing
225
+ # callback).
226
+ config.callbacks(None)
227
+ # Rebuild the algorithm (just for testing purposes).
228
+ test_algo = config.build()
229
+ # Load algo's state from best checkpoint.
230
+ test_algo.restore(best_result.checkpoint)
231
+ # Perform some checks on the restored state.
232
+ assert test_algo.training_iteration > 0
233
+ # Evaluate on the restored algorithm.
234
+ test_eval_results = test_algo.evaluate()
235
+ assert (
236
+ test_eval_results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN]
237
+ >= args.stop_reward_crash
238
+ ), test_eval_results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN]
239
+ # Train one iteration to make sure, the performance does not collapse (e.g. due
240
+ # to the optimizer weights not having been restored properly).
241
+ test_results = test_algo.train()
242
+ assert (
243
+ test_results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] >= args.stop_reward_crash
244
+ ), test_results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN]
245
+ # Stop the test algorithm again.
246
+ test_algo.stop()
247
+
248
+ # Create a new Tuner from the existing experiment path (which contains the tuner's
249
+ # own checkpoint file). Note that even the WandB logging will be continued without
250
+ # creating a new WandB run name.
251
+ restored_tuner = tune.Tuner.restore(
252
+ path=tuner_results.experiment_path,
253
+ trainable=config.algo_class,
254
+ param_space=config,
255
+ # Important to set this to True b/c the previous trial had failed (due to our
256
+ # `CrashAfterNIters` callback).
257
+ resume_errored=True,
258
+ )
259
+ # Continue the experiment exactly where we left off.
260
+ tuner_results = restored_tuner.fit()
261
+
262
+ # Not sure, whether this is really necessary, but we have observed the WandB
263
+ # logger sometimes not logging some of the last iterations. This sleep here might
264
+ # give it enough time to do so.
265
+ time.sleep(20)
266
+
267
+ if args.as_test:
268
+ check_learning_achieved(tuner_results, args.stop_reward, metric=metric)
vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/onnx_tf.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @OldAPIStack
2
+ import argparse
3
+ import numpy as np
4
+ import onnxruntime
5
+ import os
6
+ import shutil
7
+
8
+ import ray
9
+ import ray.rllib.algorithms.ppo as ppo
10
+
11
+ parser = argparse.ArgumentParser()
12
+
13
+ parser.add_argument(
14
+ "--framework",
15
+ choices=["tf", "tf2"],
16
+ default="tf2",
17
+ help="The TF framework specifier (either 'tf' or 'tf2').",
18
+ )
19
+
20
+
21
+ if __name__ == "__main__":
22
+
23
+ args = parser.parse_args()
24
+
25
+ # Configure our PPO Algorithm.
26
+ config = (
27
+ ppo.PPOConfig()
28
+ .api_stack(
29
+ enable_env_runner_and_connector_v2=False,
30
+ enable_rl_module_and_learner=False,
31
+ )
32
+ .env_runners(num_env_runners=1)
33
+ .framework(args.framework)
34
+ )
35
+
36
+ outdir = "export_tf"
37
+ if os.path.exists(outdir):
38
+ shutil.rmtree(outdir)
39
+
40
+ np.random.seed(1234)
41
+
42
+ # We will run inference with this test batch
43
+ test_data = {
44
+ "obs": np.random.uniform(0, 1.0, size=(10, 4)).astype(np.float32),
45
+ }
46
+
47
+ # Start Ray and initialize a PPO Algorithm
48
+ ray.init()
49
+ algo = config.build(env="CartPole-v1")
50
+
51
+ # You could train the model here via:
52
+ # algo.train()
53
+
54
+ # Let's run inference on the tensorflow model
55
+ policy = algo.get_policy()
56
+ result_tf, _ = policy.model(test_data)
57
+
58
+ # Evaluate tensor to fetch numpy array.
59
+ if args.framework == "tf":
60
+ with policy.get_session().as_default():
61
+ result_tf = result_tf.eval()
62
+
63
+ # This line will export the model to ONNX.
64
+ policy.export_model(outdir, onnx=11)
65
+ # Equivalent to:
66
+ # algo.export_policy_model(outdir, onnx=11)
67
+
68
+ # Import ONNX model.
69
+ exported_model_file = os.path.join(outdir, "model.onnx")
70
+
71
+ # Start an inference session for the ONNX model
72
+ session = onnxruntime.InferenceSession(exported_model_file, None)
73
+
74
+ # Pass the same test batch to the ONNX model (rename to match tensor names)
75
+ onnx_test_data = {f"default_policy/{k}:0": v for k, v in test_data.items()}
76
+
77
+ # Tf2 model stored differently from tf (static graph) model.
78
+ if args.framework == "tf2":
79
+ result_onnx = session.run(["fc_out"], {"observations": test_data["obs"]})
80
+ else:
81
+ result_onnx = session.run(
82
+ ["default_policy/model/fc_out/BiasAdd:0"],
83
+ onnx_test_data,
84
+ )
85
+
86
+ # These results should be equal!
87
+ print("TENSORFLOW", result_tf)
88
+ print("ONNX", result_onnx)
89
+
90
+ assert np.allclose(result_tf, result_onnx), "Model outputs are NOT equal. FAILED"
91
+ print("Model outputs are equal. PASSED")
vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/onnx_torch.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @OldAPIStack
2
+
3
+ from packaging.version import Version
4
+ import numpy as np
5
+ import ray
6
+ import ray.rllib.algorithms.ppo as ppo
7
+ import onnxruntime
8
+ import os
9
+ import shutil
10
+ import torch
11
+
12
+ if __name__ == "__main__":
13
+ # Configure our PPO Algorithm.
14
+ config = (
15
+ ppo.PPOConfig()
16
+ .api_stack(
17
+ enable_env_runner_and_connector_v2=False,
18
+ enable_rl_module_and_learner=False,
19
+ )
20
+ .env_runners(num_env_runners=1)
21
+ .framework("torch")
22
+ )
23
+
24
+ outdir = "export_torch"
25
+ if os.path.exists(outdir):
26
+ shutil.rmtree(outdir)
27
+
28
+ np.random.seed(1234)
29
+
30
+ # We will run inference with this test batch
31
+ test_data = {
32
+ "obs": np.random.uniform(0, 1.0, size=(10, 4)).astype(np.float32),
33
+ "state_ins": np.array([0.0], dtype=np.float32),
34
+ }
35
+
36
+ # Start Ray and initialize a PPO Algorithm.
37
+ ray.init()
38
+ algo = config.build(env="CartPole-v1")
39
+
40
+ # You could train the model here
41
+ # algo.train()
42
+
43
+ # Let's run inference on the torch model
44
+ policy = algo.get_policy()
45
+ result_pytorch, _ = policy.model(
46
+ {
47
+ "obs": torch.tensor(test_data["obs"]),
48
+ }
49
+ )
50
+
51
+ # Evaluate tensor to fetch numpy array
52
+ result_pytorch = result_pytorch.detach().numpy()
53
+
54
+ # This line will export the model to ONNX.
55
+ policy.export_model(outdir, onnx=11)
56
+ # Equivalent to:
57
+ # algo.export_policy_model(outdir, onnx=11)
58
+
59
+ # Import ONNX model.
60
+ exported_model_file = os.path.join(outdir, "model.onnx")
61
+
62
+ # Start an inference session for the ONNX model
63
+ session = onnxruntime.InferenceSession(exported_model_file, None)
64
+
65
+ # Pass the same test batch to the ONNX model
66
+ if Version(torch.__version__) < Version("1.9.0"):
67
+ # In torch < 1.9.0 the second input/output name gets mixed up
68
+ test_data["state_outs"] = test_data.pop("state_ins")
69
+
70
+ result_onnx = session.run(["output"], test_data)
71
+
72
+ # These results should be equal!
73
+ print("PYTORCH", result_pytorch)
74
+ print("ONNX", result_onnx)
75
+
76
+ assert np.allclose(
77
+ result_pytorch, result_onnx
78
+ ), "Model outputs are NOT equal. FAILED"
79
+ print("Model outputs are equal. PASSED")
vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/onnx_torch_lstm.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @OldAPIStack
2
+
3
+ import numpy as np
4
+ import onnxruntime
5
+
6
+ import ray
7
+ import ray.rllib.algorithms.ppo as ppo
8
+ from ray.rllib.utils.framework import try_import_torch
9
+ from ray.rllib.utils.test_utils import add_rllib_example_script_args, check
10
+ from ray.rllib.utils.torch_utils import convert_to_torch_tensor
11
+
12
+ torch, _ = try_import_torch()
13
+
14
+ parser = add_rllib_example_script_args()
15
+ parser.set_defaults(num_env_runners=1)
16
+
17
+
18
+ class ONNXCompatibleWrapper(torch.nn.Module):
19
+ def __init__(self, original_model):
20
+ super(ONNXCompatibleWrapper, self).__init__()
21
+ self.original_model = original_model
22
+
23
+ def forward(self, a, b0, b1, c):
24
+ # Convert the separate tensor inputs back into the list format
25
+ # expected by the original model's forward method.
26
+ b = [b0, b1]
27
+ ret = self.original_model({"obs": a}, b, c)
28
+ # results, state_out_0, state_out_1
29
+ return ret[0], ret[1][0], ret[1][1]
30
+
31
+
32
+ if __name__ == "__main__":
33
+ args = parser.parse_args()
34
+
35
+ assert (
36
+ not args.enable_new_api_stack
37
+ ), "Must NOT set --enable-new-api-stack when running this script!"
38
+
39
+ ray.init(local_mode=args.local_mode)
40
+
41
+ # Configure our PPO Algorithm.
42
+ config = (
43
+ ppo.PPOConfig()
44
+ # ONNX is not supported by RLModule API yet.
45
+ .api_stack(
46
+ enable_rl_module_and_learner=args.enable_new_api_stack,
47
+ enable_env_runner_and_connector_v2=args.enable_new_api_stack,
48
+ )
49
+ .environment("CartPole-v1")
50
+ .env_runners(num_env_runners=args.num_env_runners)
51
+ .training(model={"use_lstm": True})
52
+ )
53
+
54
+ B = 3
55
+ T = 5
56
+ LSTM_CELL = 256
57
+
58
+ # Input data for a python inference forward call.
59
+ test_data_python = {
60
+ "obs": np.random.uniform(0, 1.0, size=(B * T, 4)).astype(np.float32),
61
+ "state_ins": [
62
+ np.random.uniform(0, 1.0, size=(B, LSTM_CELL)).astype(np.float32),
63
+ np.random.uniform(0, 1.0, size=(B, LSTM_CELL)).astype(np.float32),
64
+ ],
65
+ "seq_lens": np.array([T] * B, np.float32),
66
+ }
67
+ # Input data for the ONNX session.
68
+ test_data_onnx = {
69
+ "obs": test_data_python["obs"],
70
+ "state_in_0": test_data_python["state_ins"][0],
71
+ "state_in_1": test_data_python["state_ins"][1],
72
+ "seq_lens": test_data_python["seq_lens"],
73
+ }
74
+
75
+ # Input data for compiling the ONNX model.
76
+ test_data_onnx_input = convert_to_torch_tensor(test_data_onnx)
77
+
78
+ # Initialize a PPO Algorithm.
79
+ algo = config.build()
80
+
81
+ # You could train the model here
82
+ # algo.train()
83
+
84
+ # Let's run inference on the torch model
85
+ policy = algo.get_policy()
86
+ result_pytorch, _ = policy.model(
87
+ {
88
+ "obs": torch.tensor(test_data_python["obs"]),
89
+ },
90
+ [
91
+ torch.tensor(test_data_python["state_ins"][0]),
92
+ torch.tensor(test_data_python["state_ins"][1]),
93
+ ],
94
+ torch.tensor(test_data_python["seq_lens"]),
95
+ )
96
+
97
+ # Evaluate tensor to fetch numpy array
98
+ result_pytorch = result_pytorch.detach().numpy()
99
+
100
+ # Wrap the actual ModelV2 with the torch wrapper above to make this all work with
101
+ # LSTMs (extra `state` in- and outputs and `seq_lens` inputs).
102
+ onnx_compatible = ONNXCompatibleWrapper(policy.model)
103
+ exported_model_file = "model.onnx"
104
+ input_names = [
105
+ "obs",
106
+ "state_in_0",
107
+ "state_in_1",
108
+ "seq_lens",
109
+ ]
110
+
111
+ # This line will export the model to ONNX.
112
+ torch.onnx.export(
113
+ onnx_compatible,
114
+ tuple(test_data_onnx_input[n] for n in input_names),
115
+ exported_model_file,
116
+ export_params=True,
117
+ opset_version=11,
118
+ do_constant_folding=True,
119
+ input_names=input_names,
120
+ output_names=[
121
+ "output",
122
+ "state_out_0",
123
+ "state_out_1",
124
+ ],
125
+ dynamic_axes={k: {0: "batch_size"} for k in input_names},
126
+ )
127
+ # Start an inference session for the ONNX model.
128
+ session = onnxruntime.InferenceSession(exported_model_file, None)
129
+ result_onnx = session.run(["output"], test_data_onnx)
130
+
131
+ # These results should be equal!
132
+ print("PYTORCH", result_pytorch)
133
+ print("ONNX", result_onnx[0])
134
+
135
+ check(result_pytorch, result_onnx[0])
136
+ print("Model outputs are equal. PASSED")
vllm/lib/python3.10/site-packages/ray/rllib/examples/checkpoints/restore_1_of_n_agents_from_checkpoint.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """An example script showing how to load module weights for 1 of n agents
2
+ from checkpoint.
3
+
4
+ This example:
5
+ - Runs a multi-agent `Pendulum-v1` experiment with >= 2 policies.
6
+ - Saves a checkpoint of the `MultiRLModule` used every `--checkpoint-freq`
7
+ iterations.
8
+ - Stops the experiments after the agents reach a combined return of -800.
9
+ - Picks the best checkpoint by combined return and restores policy 0 from it.
10
+ - Runs a second experiment with the restored `RLModule` for policy 0 and
11
+ a fresh `RLModule` for the other policies.
12
+ - Stops the second experiment after the agents reach a combined return of -800.
13
+
14
+
15
+ How to run this script
16
+ ----------------------
17
+ `python [script file name].py --enable-new-api-stack --num-agents=2
18
+ --checkpoint-freq=20 --checkpoint-at-end`
19
+
20
+ Control the number of agents and policies (RLModules) via --num-agents and
21
+ --num-policies.
22
+
23
+ Control the number of checkpoints by setting `--checkpoint-freq` to a value > 0.
24
+ Note that the checkpoint frequency is per iteration and this example needs at
25
+ least a single checkpoint to load the RLModule weights for policy 0.
26
+ If `--checkpoint-at-end` is set, a checkpoint will be saved at the end of the
27
+ experiment.
28
+
29
+ For debugging, use the following additional command line options
30
+ `--no-tune --num-env-runners=0`
31
+ which should allow you to set breakpoints anywhere in the RLlib code and
32
+ have the execution stop there for inspection and debugging.
33
+
34
+ For logging to your WandB account, use:
35
+ `--wandb-key=[your WandB API key] --wandb-project=[some project name]
36
+ --wandb-run-name=[optional: WandB run name (within the defined project)]`
37
+
38
+
39
+ Results to expect
40
+ -----------------
41
+ You should expect a reward of -400.0 eventually being achieved by a simple
42
+ single PPO policy (no tuning, just using RLlib's default settings). In the
43
+ second run of the experiment, the MultiRLModule weights for policy 0 are
44
+ restored from the checkpoint of the first run. The reward for a single agent
45
+ should be -400.0 again, but the training time should be shorter (around 30
46
+ iterations instead of 190).
47
+ """
48
+
49
+ import os
50
+ from ray.air.constants import TRAINING_ITERATION
51
+ from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig
52
+ from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec
53
+ from ray.rllib.examples.envs.classes.multi_agent import MultiAgentPendulum
54
+ from ray.rllib.utils.metrics import (
55
+ ENV_RUNNER_RESULTS,
56
+ EPISODE_RETURN_MEAN,
57
+ NUM_ENV_STEPS_SAMPLED_LIFETIME,
58
+ )
59
+ from ray.rllib.utils.test_utils import (
60
+ add_rllib_example_script_args,
61
+ run_rllib_example_script_experiment,
62
+ )
63
+ from ray.tune.registry import get_trainable_cls, register_env
64
+
65
+ parser = add_rllib_example_script_args(
66
+ default_iters=200,
67
+ default_timesteps=100000,
68
+ default_reward=-400.0,
69
+ )
70
+ parser.set_defaults(
71
+ checkpoint_freq=1,
72
+ num_agents=2,
73
+ )
74
+ # TODO (sven): This arg is currently ignored (hard-set to 2).
75
+ parser.add_argument("--num-policies", type=int, default=2)
76
+
77
+
78
+ if __name__ == "__main__":
79
+ args = parser.parse_args()
80
+
81
+ # Register our environment with tune.
82
+ if args.num_agents > 1:
83
+ register_env(
84
+ "env",
85
+ lambda _: MultiAgentPendulum(config={"num_agents": args.num_agents}),
86
+ )
87
+ else:
88
+ raise ValueError(
89
+ f"`num_agents` must be > 1, but is {args.num_agents}."
90
+ "Read the script docstring for more information."
91
+ )
92
+
93
+ assert args.checkpoint_freq > 0, (
94
+ "This example requires at least one checkpoint to load the RLModule "
95
+ "weights for policy 0."
96
+ )
97
+
98
+ base_config = (
99
+ get_trainable_cls(args.algo)
100
+ .get_default_config()
101
+ .environment("env")
102
+ .training(
103
+ train_batch_size_per_learner=512,
104
+ minibatch_size=64,
105
+ lambda_=0.1,
106
+ gamma=0.95,
107
+ lr=0.0003,
108
+ vf_clip_param=10.0,
109
+ )
110
+ .rl_module(
111
+ model_config=DefaultModelConfig(fcnet_activation="relu"),
112
+ )
113
+ )
114
+
115
+ # Add a simple multi-agent setup.
116
+ if args.num_agents > 0:
117
+ base_config.multi_agent(
118
+ policies={f"p{i}" for i in range(args.num_agents)},
119
+ policy_mapping_fn=lambda aid, *a, **kw: f"p{aid}",
120
+ )
121
+
122
+ # Augment the base config with further settings and train the agents.
123
+ results = run_rllib_example_script_experiment(base_config, args)
124
+
125
+ # Create an env instance to get the observation and action spaces.
126
+ env = MultiAgentPendulum(config={"num_agents": args.num_agents})
127
+ # Get the default module spec from the algorithm config.
128
+ module_spec = base_config.get_default_rl_module_spec()
129
+ module_spec.model_config = DefaultModelConfig(fcnet_activation="relu")
130
+ module_spec.observation_space = env.envs[0].observation_space
131
+ module_spec.action_space = env.envs[0].action_space
132
+ # Create the module for each policy, but policy 0.
133
+ module_specs = {}
134
+ for i in range(1, args.num_agents or 1):
135
+ module_specs[f"p{i}"] = module_spec
136
+
137
+ # Now swap in the RLModule weights for policy 0.
138
+ chkpt_path = results.get_best_result().checkpoint.path
139
+ p_0_module_state_path = os.path.join(chkpt_path, "learner", "module_state", "p0")
140
+ module_spec.load_state_path = p_0_module_state_path
141
+ module_specs["p0"] = module_spec
142
+
143
+ # Create the MultiRLModule.
144
+ multi_rl_module_spec = MultiRLModuleSpec(rl_module_specs=module_specs)
145
+ # Define the MultiRLModule in the base config.
146
+ base_config.rl_module(rl_module_spec=multi_rl_module_spec)
147
+ # We need to re-register the environment when starting a new run.
148
+ register_env(
149
+ "env",
150
+ lambda _: MultiAgentPendulum(config={"num_agents": args.num_agents}),
151
+ )
152
+ # Define stopping criteria.
153
+ stop = {
154
+ f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": -800,
155
+ f"{NUM_ENV_STEPS_SAMPLED_LIFETIME}": 20000,
156
+ TRAINING_ITERATION: 30,
157
+ }
158
+
159
+ # Run the experiment again with the restored MultiRLModule.
160
+ run_rllib_example_script_experiment(base_config, args, stop=stop)