diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/algorithms/classes/__pycache__/__init__.cpython-310.pyc b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/algorithms/classes/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e3b0c453b1aa5d54d71b71376340f35a5489f27 Binary files /dev/null and b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/algorithms/classes/__pycache__/__init__.cpython-310.pyc differ diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/algorithms/classes/__pycache__/vpg.cpython-310.pyc b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/algorithms/classes/__pycache__/vpg.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c486b3c5c5f86b634ff08a0a2a2499fa117fbe04 Binary files /dev/null and b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/algorithms/classes/__pycache__/vpg.cpython-310.pyc differ diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/__init__.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/__pycache__/euclidian_distance_based_curiosity.cpython-310.pyc b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/__pycache__/euclidian_distance_based_curiosity.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e93f01ebebcf67bdb427e55df019459fc563c78f Binary files /dev/null and b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/__pycache__/euclidian_distance_based_curiosity.cpython-310.pyc differ diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/__pycache__/flatten_observations_dict_space.cpython-310.pyc b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/__pycache__/flatten_observations_dict_space.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1796e609cbff88d2a6cb2376adbf733ce593b61e Binary files /dev/null and b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/__pycache__/flatten_observations_dict_space.cpython-310.pyc differ diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/classes/__init__.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/classes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/classes/__pycache__/protobuf_cartpole_observation_decoder.cpython-310.pyc b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/classes/__pycache__/protobuf_cartpole_observation_decoder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7a5e5c6bb039410490c144dd51427427ac89349 Binary files /dev/null and b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/classes/__pycache__/protobuf_cartpole_observation_decoder.cpython-310.pyc differ diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/classes/euclidian_distance_based_curiosity.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/classes/euclidian_distance_based_curiosity.py new file mode 100644 index 0000000000000000000000000000000000000000..c50a2caae5d744e40a95f1c78608ca0f99050398 --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/classes/euclidian_distance_based_curiosity.py @@ -0,0 +1,122 @@ +from collections import deque +from typing import Any, List, Optional + +import gymnasium as gym +import numpy as np + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.typing import EpisodeType + + +class EuclidianDistanceBasedCuriosity(ConnectorV2): + """Learner ConnectorV2 piece computing intrinsic rewards with euclidian distance. + + Add this connector piece to your Learner pipeline, through your algo config: + ``` + config.training( + learner_connector=lambda obs_sp, act_sp: EuclidianDistanceBasedCuriosity() + ) + ``` + + Intrinsic rewards are computed on the Learner side based on comparing the euclidian + distance of observations vs already seen ones. A configurable number of observations + will be stored in a FIFO buffer and all incoming observations have their distance + measured against those. + + The minimum distance measured is the intrinsic reward for the incoming obs + (multiplied by a fixed coeffieicnt and added to the "main" extrinsic reward): + r(i) = intrinsic_reward_coeff * min(ED(o, o(i)) for o in stored_obs)) + where `ED` is the euclidian distance and `stored_obs` is the buffer. + + The intrinsic reward is then added to the extrinsic reward and saved back into the + episode (under the main "rewards" key). + + Note that the computation and saving back to the episode all happens before the + actual train batch is generated from the episode data. Thus, the Learner and the + RLModule used do not take notice of the extra reward added. + + Only one observation per incoming episode will be stored as a new one in the buffer. + Thereby, we pick the observation with the largest `min(ED)` value over all already + stored observations to be stored per episode. + + If you would like to use a simpler, count-based mechanism for intrinsic reward + computations, take a look at the `CountBasedCuriosity` connector piece + at `ray.rllib.examples.connectors.classes.count_based_curiosity` + """ + + def __init__( + self, + input_observation_space: Optional[gym.Space] = None, + input_action_space: Optional[gym.Space] = None, + *, + intrinsic_reward_coeff: float = 1.0, + max_buffer_size: int = 100, + **kwargs, + ): + """Initializes a CountBasedCuriosity instance. + + Args: + intrinsic_reward_coeff: The weight with which to multiply the intrinsic + reward before adding (and saving) it back to the main (extrinsic) + reward of the episode at each timestep. + """ + super().__init__(input_observation_space, input_action_space) + + # Create an observation buffer + self.obs_buffer = deque(maxlen=max_buffer_size) + self.intrinsic_reward_coeff = intrinsic_reward_coeff + + self._test = 0 + + def __call__( + self, + *, + rl_module: RLModule, + batch: Any, + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + if self._test > 10: + return batch + self._test += 1 + # Loop through all episodes and change the reward to + # [reward + intrinsic reward] + for sa_episode in self.single_agent_episode_iterator( + episodes=episodes, agents_that_stepped_only=False + ): + # Loop through all obs, except the last one. + observations = sa_episode.get_observations(slice(None, -1)) + # Get all respective (extrinsic) rewards. + rewards = sa_episode.get_rewards() + + max_dist_obs = None + max_dist = float("-inf") + for i, (obs, rew) in enumerate(zip(observations, rewards)): + # Compare obs to all stored observations and compute euclidian distance. + min_dist = 0.0 + if self.obs_buffer: + min_dist = min( + np.sqrt(np.sum((obs - stored_obs) ** 2)) + for stored_obs in self.obs_buffer + ) + if min_dist > max_dist: + max_dist = min_dist + max_dist_obs = obs + + # Compute our euclidian distance-based intrinsic reward and add it to + # the main (extrinsic) reward. + rew += self.intrinsic_reward_coeff * min_dist + # Store the new reward back to the episode (under the correct + # timestep/index). + sa_episode.set_rewards(new_data=rew, at_indices=i) + + # Add the one observation of this episode with the largest (min) euclidian + # dist to all already stored obs to the buffer (maybe throwing out the + # oldest obs in there). + if max_dist_obs is not None: + self.obs_buffer.append(max_dist_obs) + + return batch diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/classes/protobuf_cartpole_observation_decoder.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/classes/protobuf_cartpole_observation_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..2ed4a891afcd4e64cb50148446ecca5cc1e1e06c --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/classes/protobuf_cartpole_observation_decoder.py @@ -0,0 +1,80 @@ +from typing import Any, List, Optional + +import gymnasium as gym +import numpy as np + +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.examples.envs.classes.utils.cartpole_observations_proto import ( + CartPoleObservation, +) +from ray.rllib.utils.annotations import override +from ray.rllib.utils.typing import EpisodeType + + +class ProtobufCartPoleObservationDecoder(ConnectorV2): + """Env-to-module ConnectorV2 piece decoding protobuf obs into CartPole-v1 obs. + + Add this connector piece to your env-to-module pipeline, through your algo config: + ``` + config.env_runners( + env_to_module_connector=lambda env: ProtobufCartPoleObservationDecoder() + ) + ``` + + The incoming observation space must be a 1D Box of dtype uint8 + (which is the same as a binary string). The outgoing observation space is the + normal CartPole-v1 1D space: Box(-inf, inf, (4,), float32). + """ + + @override(ConnectorV2) + def recompute_output_observation_space( + self, + input_observation_space: gym.Space, + input_action_space: gym.Space, + ) -> gym.Space: + # Make sure the incoming observation space is a protobuf (binary string). + assert ( + isinstance(input_observation_space, gym.spaces.Box) + and len(input_observation_space.shape) == 1 + and input_observation_space.dtype.name == "uint8" + ) + # Return CartPole-v1's natural observation space. + return gym.spaces.Box(float("-inf"), float("inf"), (4,), np.float32) + + def __call__( + self, + *, + rl_module: RLModule, + batch: Any, + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + # Loop through all episodes and change the observation from a binary string + # to an actual 1D np.ndarray (normal CartPole-v1 obs). + for sa_episode in self.single_agent_episode_iterator(episodes=episodes): + # Get last obs (binary string). + obs = sa_episode.get_observations(-1) + obs_bytes = obs.tobytes() + obs_protobuf = CartPoleObservation() + obs_protobuf.ParseFromString(obs_bytes) + + # Set up the natural CartPole-v1 observation tensor from the protobuf + # values. + new_obs = np.array( + [ + obs_protobuf.x_pos, + obs_protobuf.x_veloc, + obs_protobuf.angle_pos, + obs_protobuf.angle_veloc, + ], + np.float32, + ) + + # Write the new observation (1D tensor) back into the Episode. + sa_episode.set_observations(new_data=new_obs, at_indices=-1) + + # Return `data` as-is. + return batch diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/count_based_curiosity.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/count_based_curiosity.py new file mode 100644 index 0000000000000000000000000000000000000000..ad09e4ceb6bf2665d0766ebe218d071ca2ada19f --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/count_based_curiosity.py @@ -0,0 +1,14 @@ +"""Placeholder for training with count-based curiosity. + +The actual script can be found at a different location (see code below). +""" + +if __name__ == "__main__": + import subprocess + import sys + + # Forward to "python ../curiosity/[same script name].py [same options]" + command = [sys.executable, "../curiosity/", sys.argv[0]] + sys.argv[1:] + + # Run the script. + subprocess.run(command, capture_output=True) diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/euclidian_distance_based_curiosity.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/euclidian_distance_based_curiosity.py new file mode 100644 index 0000000000000000000000000000000000000000..6e52de76791304545eebcf1aea76fe93cb2c6f39 --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/euclidian_distance_based_curiosity.py @@ -0,0 +1,14 @@ +"""Placeholder for training with euclidian distance-based curiosity. + +The actual script can be found at a different location (see code below). +""" + +if __name__ == "__main__": + import subprocess + import sys + + # Forward to "python ../curiosity/[same script name].py [same options]" + command = [sys.executable, "../curiosity/", sys.argv[0]] + sys.argv[1:] + + # Run the script. + subprocess.run(command, capture_output=True) diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/flatten_observations_dict_space.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/flatten_observations_dict_space.py new file mode 100644 index 0000000000000000000000000000000000000000..564df75c6b9d76cd86e260556609140a6adf47d0 --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/flatten_observations_dict_space.py @@ -0,0 +1,154 @@ +"""Example using a ConnectorV2 to flatten arbitrarily nested dict or tuple observations. + +An RLlib Algorithm has 3 distinct connector pipelines: +- An env-to-module pipeline in an EnvRunner accepting a list of episodes and producing +a batch for an RLModule to compute actions (`forward_inference()` or +`forward_exploration()`). +- A module-to-env pipeline in an EnvRunner taking the RLModule's output and converting +it into an action readable by the environment. +- A learner connector pipeline on a Learner taking a list of episodes and producing +a batch for an RLModule to perform the training forward pass (`forward_train()`). + +Each of these pipelines has a fixed set of default ConnectorV2 pieces that RLlib +adds/prepends to these pipelines in order to perform the most basic functionalities. +For example, RLlib adds the `AddObservationsFromEpisodesToBatch` ConnectorV2 into any +env-to-module pipeline to make sure the batch for computing actions contains - at the +minimum - the most recent observation. + +On top of these default ConnectorV2 pieces, users can define their own ConnectorV2 +pieces (or use the ones available already in RLlib) and add them to one of the 3 +different pipelines described above, as required. + +This example: + - shows how the `FlattenObservation` ConnectorV2 piece can be added to the + env-to-module pipeline. + - demonstrates that by using this connector, any arbitrarily nested dict or tuple + observations is properly flattened into a simple 1D tensor, for easier RLModule + processing. + - shows how - in a multi-agent setup - individual agents can be specified, whose + observations should be flattened (while other agents' observations will always + be left as-is). + - uses a variant of the CartPole-v1 environment, in which the 4 observation items + (x-pos, x-veloc, angle, and angle-veloc) are taken apart and put into a nested dict + with the structure: + { + "x-pos": [x-pos], + "angular-pos": { + "value": [angle], + "some_random_stuff": [random Discrete(3)], # <- should be ignored by algo + }, + "velocs": Tuple([x-veloc], [angle-veloc]), + } + + +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 +----------------- + ++---------------------+------------+----------------+--------+------------------+ +| Trial name | status | loc | iter | total time (s) | +| | | | | | +|---------------------+------------+----------------+--------+------------------+ +| PPO_env_a2fd6_00000 | TERMINATED | 127.0.0.1:7409 | 25 | 24.1426 | ++---------------------+------------+----------------+--------+------------------+ ++------------------------+------------------------+------------------------+ +| num_env_steps_sample | num_env_steps_traine | episode_return_mean | +| d_lifetime | d_lifetime | | ++------------------------+------------------------+------------------------| +| 100000 | 100000 | 421.42 | ++------------------------+------------------------+------------------------+ +""" +from ray.tune.registry import register_env +from ray.rllib.connectors.env_to_module import FlattenObservations +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.examples.envs.classes.cartpole_with_dict_observation_space import ( + CartPoleWithDictObservationSpace, +) +from ray.rllib.examples.envs.classes.multi_agent import ( + MultiAgentCartPoleWithDictObservationSpace, +) +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 + + +# Read in common example script command line arguments. +parser = add_rllib_example_script_args(default_timesteps=200000, default_reward=400.0) +parser.set_defaults(enable_new_api_stack=True) + + +if __name__ == "__main__": + args = parser.parse_args() + + # Define env-to-module-connector pipeline for the new stack. + def _env_to_module_pipeline(env): + return FlattenObservations(multi_agent=args.num_agents > 0) + + # Register our environment with tune. + if args.num_agents > 0: + register_env( + "env", + lambda _: MultiAgentCartPoleWithDictObservationSpace( + config={"num_agents": args.num_agents} + ), + ) + else: + register_env("env", lambda _: CartPoleWithDictObservationSpace()) + + # Define the AlgorithmConfig used. + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment("env") + .env_runners(env_to_module_connector=_env_to_module_pipeline) + .training( + gamma=0.99, + lr=0.0003, + ) + .rl_module( + model_config=DefaultModelConfig( + fcnet_hiddens=[32], + fcnet_activation="linear", + vf_share_layers=True, + ), + ) + ) + + # 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}", + ) + + # PPO-specific settings (for better learning behavior only). + if args.algo == "PPO": + base_config.training( + num_epochs=6, + vf_loss_coeff=0.01, + ) + # IMPALA-specific settings (for better learning behavior only). + elif args.algo == "IMPALA": + base_config.training( + lr=0.0005, + vf_loss_coeff=0.05, + entropy_coeff=0.0, + ) + + # Run everything as configured. + run_rllib_example_script_experiment(base_config, args) diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/mean_std_filtering.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/mean_std_filtering.py new file mode 100644 index 0000000000000000000000000000000000000000..aaccbf02cddbbd88eb3b341edcfc3d0777744b09 --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/mean_std_filtering.py @@ -0,0 +1,198 @@ +"""Example using a ConnectorV2 for processing observations with a mean/std filter. + +An RLlib Algorithm has 3 distinct connector pipelines: +- An env-to-module pipeline in an EnvRunner accepting a list of episodes and producing +a batch for an RLModule to compute actions (`forward_inference()` or +`forward_exploration()`). +- A module-to-env pipeline in an EnvRunner taking the RLModule's output and converting +it into an action readable by the environment. +- A learner connector pipeline on a Learner taking a list of episodes and producing +a batch for an RLModule to perform the training forward pass (`forward_train()`). + +Each of these pipelines has a fixed set of default ConnectorV2 pieces that RLlib +adds/prepends to these pipelines in order to perform the most basic functionalities. +For example, RLlib adds the `AddObservationsFromEpisodesToBatch` ConnectorV2 into any +env-to-module pipeline to make sure the batch for computing actions contains - at the +minimum - the most recent observation. + +On top of these default ConnectorV2 pieces, users can define their own ConnectorV2 +pieces (or use the ones available already in RLlib) and add them to one of the 3 +different pipelines described above, as required. + +This example: + - shows how the `MeanStdFilter` ConnectorV2 piece can be added to the env-to-module + pipeline. + - demonstrates that using such a filter enhances learning behavior (or even makes + if possible to learn overall) in some environments, especially those with lopsided + observation spaces, for example `Box(-3000, -1000, ...)`. + + +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 +----------------- +Running this example with the mean-std filter results in the normally expected Pendulum +learning behavior: ++-------------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +| | | | | +|-------------------------------+------------+-----------------+--------+ +| PPO_lopsided-pend_f9c96_00000 | TERMINATED | 127.0.0.1:43612 | 77 | ++-------------------------------+------------+-----------------+--------+ ++------------------+------------------------+-----------------------+ +| total time (s) | num_env_steps_sample | episode_return_mean | +| | d_lifetime | | +|------------------+------------------------+-----------------------| +| 30.7466 | 40040 | -276.3 | ++------------------+------------------------+-----------------------+ + +If you try using the `--disable-mean-std-filter` (all other things being equal), you +will either see no learning progress at all (or a very slow one), but more likely some +numerical instability related error will be thrown: + +ValueError: Expected parameter loc (Tensor of shape (64, 1)) of distribution + Normal(loc: torch.Size([64, 1]), scale: torch.Size([64, 1])) to satisfy the + constraint Real(), but found invalid values: +tensor([[nan], + [nan], + [nan], + ... +""" +import gymnasium as gym +import numpy as np + +from ray.rllib.connectors.env_to_module.mean_std_filter import MeanStdFilter +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.examples.envs.classes.multi_agent import MultiAgentPendulum +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, +) +from ray.tune.registry import get_trainable_cls, register_env + +torch, _ = try_import_torch() + +parser = add_rllib_example_script_args( + default_iters=500, + default_timesteps=500000, + default_reward=-300.0, +) +parser.add_argument( + "--disable-mean-std-filter", + action="store_true", + help="Run w/o a mean/std env-to-module connector piece (filter).", +) + + +class LopsidedObs(gym.ObservationWrapper): + def __init__(self, env): + super().__init__(env) + self.observation_space = gym.spaces.Box(-4000.0, -1456.0, (3,), np.float32) + + def observation(self, observation): + # Lopside [-1.0, 1.0] Pendulum observations + return ((observation + 1.0) / 2.0) * (4000.0 - 1456.0) - 4000.0 + + +if __name__ == "__main__": + args = parser.parse_args() + + assert ( + args.enable_new_api_stack + ), "Must set --enable-new-api-stack when running this script!" + + # Register our environment with tune. + if args.num_agents > 0: + register_env( + "lopsided-pend", + lambda _: MultiAgentPendulum(config={"num_agents": args.num_agents}), + ) + else: + register_env("lopsided-pend", lambda _: LopsidedObs(gym.make("Pendulum-v1"))) + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment("lopsided-pend") + .env_runners( + # TODO (sven): MAEnvRunner does not support vectorized envs yet + # due to gym's env checkers and non-compatability with RLlib's + # MultiAgentEnv API. + num_envs_per_env_runner=1 if args.num_agents > 0 else 20, + # Define a single connector piece to be prepended to the env-to-module + # connector pipeline. + # Alternatively, return a list of n ConnectorV2 pieces (which will then be + # included in an automatically generated EnvToModulePipeline or return a + # EnvToModulePipeline directly. + env_to_module_connector=( + None + if args.disable_mean_std_filter + else lambda env: MeanStdFilter(multi_agent=args.num_agents > 0) + ), + ) + .training( + train_batch_size_per_learner=512, + gamma=0.95, + # Linearly adjust learning rate based on number of GPUs. + lr=0.0003 * (args.num_learners or 1), + vf_loss_coeff=0.01, + ) + .rl_module( + model_config=DefaultModelConfig( + fcnet_activation="relu", + fcnet_kernel_initializer=torch.nn.init.xavier_uniform_, + fcnet_bias_initializer=torch.nn.init.constant_, + fcnet_bias_initializer_kwargs={"val": 0.0}, + ), + ) + # In case you would like to run with a evaluation EnvRunners, make sure your + # `evaluation_config` key contains the `use_worker_filter_stats=False` setting + # (see below). This setting makes sure that the mean/std stats collected by the + # evaluation EnvRunners are NOT used for the training EnvRunners (unless you + # really want to mix these stats). It's normally a good idea to keep the stats + # collected during evaluation completely out of the training data (already for + # better reproducibility alone). + # .evaluation( + # evaluation_num_env_runners=1, + # evaluation_interval=1, + # evaluation_config={ + # "explore": False, + # # Do NOT use the eval EnvRunners' ConnectorV2 states. Instead, before + # # each round of evaluation, broadcast the latest training + # # EnvRunnerGroup's ConnectorV2 states (merged from all training remote + # # EnvRunners) to the eval EnvRunnerGroup (and discard the eval + # # EnvRunners' stats). + # "use_worker_filter_stats": False, + # }, + # ) + ) + + # PPO specific settings. + if args.algo == "PPO": + base_config.training( + minibatch_size=64, + lambda_=0.1, + vf_clip_param=10.0, + ) + + # 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}", + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/prev_actions_prev_rewards.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/prev_actions_prev_rewards.py new file mode 100644 index 0000000000000000000000000000000000000000..1fa1e6681b90dfcad83b3f765599d8dd4f724ace --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/connectors/prev_actions_prev_rewards.py @@ -0,0 +1,164 @@ +"""Example using a ConnectorV2 to add previous rewards/actions to an RLModule's input. + +An RLlib Algorithm has 3 distinct connector pipelines: +- An env-to-module pipeline in an EnvRunner accepting a list of episodes and producing +a batch for an RLModule to compute actions (`forward_inference()` or +`forward_exploration()`). +- A module-to-env pipeline in an EnvRunner taking the RLModule's output and converting +it into an action readable by the environment. +- A learner connector pipeline on a Learner taking a list of episodes and producing +a batch for an RLModule to perform the training forward pass (`forward_train()`). + +Each of these pipelines has a fixed set of default ConnectorV2 pieces that RLlib +adds/prepends to these pipelines in order to perform the most basic functionalities. +For example, RLlib adds the `AddObservationsFromEpisodesToBatch` ConnectorV2 into any +env-to-module pipeline to make sure the batch for computing actions contains - at the +minimum - the most recent observation. + +On top of these default ConnectorV2 pieces, users can define their own ConnectorV2 +pieces (or use the ones available already in RLlib) and add them to one of the 3 +different pipelines described above, as required. + +This example: + - shows how the `PrevActionsPrevRewards` ConnectorV2 piece can be added to the + env-to-module pipeline to extract previous rewards and/or actions from the ongoing + episodes. + - shows how this connector creates and wraps this new information (rewards and + actions) together with the original observations into the RLModule's input dict + under a new `gym.spaces.Dict` structure (for example, if your observation space + is `O=Box(shape=(3,))` and you add the most recent 1 reward, the new observation + space will be `Dict({"_original_obs": O, "prev_n_rewards": Box(shape=())})`. + - demonstrates how to use RLlib's `FlattenObservations` right after the + `PrevActionsPrevRewards` to flatten that new dict observation structure again into + a single 1D tensor. + - uses the StatelessCartPole environment, a CartPole-v1 derivative that's missing + both x-veloc and angle-veloc observation components and is therefore non-Markovian + (only partially observable). An LSTM default model is used for training. Adding + the additional context to the observations (for example, prev. actions) helps the + LSTM to more quickly learn in this environment. + + +How to run this script +---------------------- +`python [script file name].py --enable-new-api-stack --num-frames=4 --env=ALE/Pong-v5` + +Use the `--num-frames` option to define the number of observations to framestack. +If you don't want to use Connectors to perform the framestacking, set the +`--use-gym-wrapper-framestacking` flag to perform framestacking already inside a +gymnasium observation wrapper. In this case though, be aware that the tensors being +sent through the network are `--num-frames` x larger than if you use the Connector +setup. + +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 see something similar to this in your terminal output when running +ths script as described above: + ++---------------------+------------+-----------------+--------+------------------+ +| Trial name | status | loc | iter | total time (s) | +| | | | | | +|---------------------+------------+-----------------+--------+------------------+ +| PPO_env_0edd2_00000 | TERMINATED | 127.0.0.1:12632 | 17 | 42.6898 | ++---------------------+------------+-----------------+--------+------------------+ ++------------------------+------------------------+------------------------+ +| num_env_steps_sample | num_env_steps_traine | episode_return_mean | +| d_lifetime | d_lifetime | | +|------------------------+------------------------+------------------------| +| 68000 | 68000 | 205.22 | ++------------------------+------------------------+------------------------+ +""" +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.connectors.env_to_module import ( + FlattenObservations, + PrevActionsPrevRewards, +) +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.examples.envs.classes.stateless_cartpole import StatelessCartPole +from ray.rllib.examples.envs.classes.multi_agent import MultiAgentStatelessCartPole +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, +) +from ray.tune import register_env + +torch, nn = try_import_torch() + + +parser = add_rllib_example_script_args( + default_reward=200.0, default_timesteps=1000000, default_iters=2000 +) +parser.set_defaults(enable_new_api_stack=True) +parser.add_argument("--n-prev-rewards", type=int, default=1) +parser.add_argument("--n-prev-actions", type=int, default=1) + + +if __name__ == "__main__": + args = parser.parse_args() + + # Define our custom connector pipelines. + def _env_to_module(env): + # Create the env-to-module connector pipeline. + return [ + PrevActionsPrevRewards( + multi_agent=args.num_agents > 0, + n_prev_rewards=args.n_prev_rewards, + n_prev_actions=args.n_prev_actions, + ), + FlattenObservations(multi_agent=args.num_agents > 0), + ] + + # Register our environment with tune. + if args.num_agents > 0: + register_env( + "env", + lambda _: MultiAgentStatelessCartPole( + config={"num_agents": args.num_agents} + ), + ) + else: + register_env("env", lambda _: StatelessCartPole()) + + config = ( + PPOConfig() + .environment("env") + .env_runners(env_to_module_connector=_env_to_module) + .training( + num_epochs=6, + lr=0.0003, + train_batch_size=4000, + vf_loss_coeff=0.01, + ) + .rl_module( + model_config=DefaultModelConfig( + use_lstm=True, + max_seq_len=20, + fcnet_hiddens=[32], + fcnet_activation="linear", + fcnet_kernel_initializer=nn.init.xavier_uniform_, + fcnet_bias_initializer=nn.init.constant_, + fcnet_bias_initializer_kwargs={"val": 0.0}, + vf_share_layers=True, + ), + ) + ) + + # Add a simple multi-agent setup. + if args.num_agents > 0: + config = config.multi_agent( + policies={f"p{i}" for i in range(args.num_agents)}, + policy_mapping_fn=lambda aid, *a, **kw: f"p{aid}", + ) + + run_rllib_example_script_experiment(config, args) diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/envs/__init__.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/envs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/envs/__pycache__/__init__.cpython-310.pyc b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/envs/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2b3292864ba6b5b39eb3b94e6ea8f48f91340c9 Binary files /dev/null and b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/envs/__pycache__/__init__.cpython-310.pyc differ diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/envs/__pycache__/env_rendering_and_recording.cpython-310.pyc b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/envs/__pycache__/env_rendering_and_recording.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bdf7f81368ff7bce1eb80a174b5e1c8e0c6e944c Binary files /dev/null and b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/envs/__pycache__/env_rendering_and_recording.cpython-310.pyc differ diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/envs/__pycache__/env_with_protobuf_observations.cpython-310.pyc b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/envs/__pycache__/env_with_protobuf_observations.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bcec8931cab61f3bdb55108e5522e1901635c1e0 Binary files /dev/null and b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/envs/__pycache__/env_with_protobuf_observations.cpython-310.pyc differ diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/envs/__pycache__/unity3d_env_local.cpython-310.pyc b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/envs/__pycache__/unity3d_env_local.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65d0ee808ef72a86b4539890d51eb79f75a152c9 Binary files /dev/null and b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/envs/__pycache__/unity3d_env_local.cpython-310.pyc differ diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/envs/classes/gpu_requiring_env.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/envs/classes/gpu_requiring_env.py new file mode 100644 index 0000000000000000000000000000000000000000..42f835c3a8c32f297466d1ceef38ee1433e2cf6e --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/envs/classes/gpu_requiring_env.py @@ -0,0 +1,27 @@ +import ray +from ray.rllib.examples.envs.classes.simple_corridor import SimpleCorridor + + +class GPURequiringEnv(SimpleCorridor): + """A dummy env that requires a GPU in order to work. + + The env here is a simple corridor env that additionally simulates a GPU + check in its constructor via `ray.get_gpu_ids()`. If this returns an + empty list, we raise an error. + + To make this env work, use `num_gpus_per_env_runner > 0` (RolloutWorkers + requesting this many GPUs each) and - maybe - `num_gpus > 0` in case + your local worker/driver must have an env as well. However, this is + only the case if `create_env_on_driver`=True (default is False). + """ + + def __init__(self, config=None): + super().__init__(config) + + # Fake-require some GPUs (at least one). + # If your local worker's env (`create_env_on_driver`=True) does not + # necessarily require a GPU, you can perform the below assertion only + # if `config.worker_index != 0`. + gpus_available = ray.get_gpu_ids() + assert len(gpus_available) > 0, "Not enough GPUs for this env!" + print("Env can see these GPUs: {}".format(gpus_available)) diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/envs/classes/simple_corridor.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/envs/classes/simple_corridor.py new file mode 100644 index 0000000000000000000000000000000000000000..9088f73dbd374da7f7d1312e6ed68c1d5c25444e --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/envs/classes/simple_corridor.py @@ -0,0 +1,42 @@ +import gymnasium as gym +from gymnasium.spaces import Box, Discrete +import numpy as np + + +class SimpleCorridor(gym.Env): + """Example of a custom env in which you have to walk down a corridor. + + You can configure the length of the corridor via the env config.""" + + def __init__(self, config=None): + config = config or {} + + self.action_space = Discrete(2) + self.observation_space = Box(0.0, 999.0, shape=(1,), dtype=np.float32) + + self.set_corridor_length(config.get("corridor_length", 10)) + + self._cur_pos = 0 + + def set_corridor_length(self, length): + self.end_pos = length + print(f"Set corridor length to {self.end_pos}") + assert self.end_pos <= 999, "The maximum `corridor_length` allowed is 999!" + + def reset(self, *, seed=None, options=None): + self._cur_pos = 0.0 + return self._get_obs(), {} + + def step(self, action): + assert action in [0, 1], action + if action == 0 and self._cur_pos > 0: + self._cur_pos -= 1.0 + elif action == 1: + self._cur_pos += 1.0 + terminated = self._cur_pos >= self.end_pos + truncated = False + reward = 1.0 if terminated else -0.01 + return self._get_obs(), reward, terminated, truncated, {} + + def _get_obs(self): + return np.array([self._cur_pos], np.float32) diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/envs/classes/transformed_action_space_env.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/envs/classes/transformed_action_space_env.py new file mode 100644 index 0000000000000000000000000000000000000000..1dce1051cbf30861fb196e6c8fbc0cf1522c871a --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/envs/classes/transformed_action_space_env.py @@ -0,0 +1,61 @@ +import gymnasium as gym +from typing import Type + + +class ActionTransform(gym.ActionWrapper): + def __init__(self, env, low, high): + super().__init__(env) + self._low = low + self._high = high + self.action_space = type(env.action_space)( + self._low, self._high, env.action_space.shape, env.action_space.dtype + ) + + def action(self, action): + return (action - self._low) / (self._high - self._low) * ( + self.env.action_space.high - self.env.action_space.low + ) + self.env.action_space.low + + +def transform_action_space(env_name_or_creator) -> Type[gym.Env]: + """Wrapper for gym.Envs to have their action space transformed. + + Args: + env_name_or_creator (Union[str, Callable[]]: String specifier or + env_maker function. + + Returns: + New transformed_action_space_env function that returns an environment + wrapped by the ActionTransform wrapper. The constructor takes a + config dict with `_low` and `_high` keys specifying the new action + range (default -1.0 to 1.0). The reset of the config dict will be + passed on to the underlying/wrapped env's constructor. + + .. testcode:: + :skipif: True + + # By gym string: + pendulum_300_to_500_cls = transform_action_space("Pendulum-v1") + # Create a transformed pendulum env. + pendulum_300_to_500 = pendulum_300_to_500_cls({"_low": -15.0}) + pendulum_300_to_500.action_space + + .. testoutput:: + + gym.spaces.Box(-15.0, 1.0, (1, ), "float32") + """ + + def transformed_action_space_env(config): + if isinstance(env_name_or_creator, str): + inner_env = gym.make(env_name_or_creator) + else: + inner_env = env_name_or_creator(config) + _low = config.pop("low", -1.0) + _high = config.pop("high", 1.0) + env = ActionTransform(inner_env, _low, _high) + return env + + return transformed_action_space_env + + +TransformedActionPendulum = transform_action_space("Pendulum-v1") diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/hierarchical/__pycache__/hierarchical_training.cpython-310.pyc b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/hierarchical/__pycache__/hierarchical_training.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7290cbb9b486ace9410b890c4992715e431eb0e3 Binary files /dev/null and b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/hierarchical/__pycache__/hierarchical_training.cpython-310.pyc differ diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/learners/classes/intrinsic_curiosity_learners.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/learners/classes/intrinsic_curiosity_learners.py new file mode 100644 index 0000000000000000000000000000000000000000..d28aded45989d4adf5a461562c2db2233f13f9a2 --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/learners/classes/intrinsic_curiosity_learners.py @@ -0,0 +1,164 @@ +from typing import Any, List, Optional + +import gymnasium as gym +import torch + +from ray.rllib.algorithms.dqn.torch.dqn_rainbow_torch_learner import ( + DQNRainbowTorchLearner, +) +from ray.rllib.algorithms.ppo.torch.ppo_torch_learner import PPOTorchLearner +from ray.rllib.connectors.common.add_observations_from_episodes_to_batch import ( + AddObservationsFromEpisodesToBatch, +) +from ray.rllib.connectors.common.numpy_to_tensor import NumpyToTensor +from ray.rllib.connectors.learner.add_next_observations_from_episodes_to_train_batch import ( # noqa + AddNextObservationsFromEpisodesToTrainBatch, +) +from ray.rllib.connectors.connector_v2 import ConnectorV2 +from ray.rllib.core import Columns, DEFAULT_MODULE_ID +from ray.rllib.core.learner.torch.torch_learner import TorchLearner +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.typing import EpisodeType + +ICM_MODULE_ID = "_intrinsic_curiosity_model" + + +class DQNTorchLearnerWithCuriosity(DQNRainbowTorchLearner): + def build(self) -> None: + super().build() + add_intrinsic_curiosity_connectors(self) + + +class PPOTorchLearnerWithCuriosity(PPOTorchLearner): + def build(self) -> None: + super().build() + add_intrinsic_curiosity_connectors(self) + + +def add_intrinsic_curiosity_connectors(torch_learner: TorchLearner) -> None: + """Adds two connector pieces to the Learner pipeline, needed for ICM training. + + - The `AddNextObservationsFromEpisodesToTrainBatch` connector makes sure the train + batch contains the NEXT_OBS for ICM's forward- and inverse dynamics net training. + - The `IntrinsicCuriosityModelConnector` piece computes intrinsic rewards from the + ICM and adds the results to the extrinsic reward of the main module's train batch. + + Args: + torch_learner: The TorchLearner, to whose Learner pipeline the two ICM connector + pieces should be added. + """ + learner_config_dict = torch_learner.config.learner_config_dict + + # Assert, we are only training one policy (RLModule) and we have the ICM + # in our MultiRLModule. + assert ( + len(torch_learner.module) == 2 + and DEFAULT_MODULE_ID in torch_learner.module + and ICM_MODULE_ID in torch_learner.module + ) + + # Make sure both curiosity loss settings are explicitly set in the + # `learner_config_dict`. + if ( + "forward_loss_weight" not in learner_config_dict + or "intrinsic_reward_coeff" not in learner_config_dict + ): + raise KeyError( + "When using the IntrinsicCuriosityTorchLearner, both `forward_loss_weight` " + " and `intrinsic_reward_coeff` must be part of your config's " + "`learner_config_dict`! Add these values through: `config.training(" + "learner_config_dict={'forward_loss_weight': .., 'intrinsic_reward_coeff': " + "..})`." + ) + + if torch_learner.config.add_default_connectors_to_learner_pipeline: + # Prepend a "add-NEXT_OBS-from-episodes-to-train-batch" connector piece + # (right after the corresponding "add-OBS-..." default piece). + torch_learner._learner_connector.insert_after( + AddObservationsFromEpisodesToBatch, + AddNextObservationsFromEpisodesToTrainBatch(), + ) + # Append the ICM connector, computing intrinsic rewards and adding these to + # the main model's extrinsic rewards. + torch_learner._learner_connector.insert_after( + NumpyToTensor, + IntrinsicCuriosityModelConnector( + intrinsic_reward_coeff=( + torch_learner.config.learner_config_dict["intrinsic_reward_coeff"] + ) + ), + ) + + +class IntrinsicCuriosityModelConnector(ConnectorV2): + """Learner ConnectorV2 piece to compute intrinsic rewards based on an ICM. + + 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 connector piece: + - requires two RLModules to be present in the MultiRLModule: + DEFAULT_MODULE_ID (the policy model to be trained) and ICM_MODULE_ID (the instrinsic + curiosity architecture). + - must be located toward the end of to your Learner pipeline (after the + `NumpyToTensor` piece) in order to perform a forward pass on the ICM model with the + readily compiled batch and a following forward-loss computation to get the intrinsi + rewards. + - these intrinsic rewards will then be added to the (extrinsic) rewards in the main + model's train batch. + """ + + def __init__( + self, + input_observation_space: Optional[gym.Space] = None, + input_action_space: Optional[gym.Space] = None, + *, + intrinsic_reward_coeff: float, + **kwargs, + ): + """Initializes a CountBasedCuriosity instance. + + Args: + intrinsic_reward_coeff: The weight with which to multiply the intrinsic + reward before adding it to the extrinsic rewards of the main model. + """ + super().__init__(input_observation_space, input_action_space) + + self.intrinsic_reward_coeff = intrinsic_reward_coeff + + def __call__( + self, + *, + rl_module: RLModule, + batch: Any, + episodes: List[EpisodeType], + explore: Optional[bool] = None, + shared_data: Optional[dict] = None, + **kwargs, + ) -> Any: + # Assert that the batch is ready. + assert DEFAULT_MODULE_ID in batch and ICM_MODULE_ID not in batch + assert ( + Columns.OBS in batch[DEFAULT_MODULE_ID] + and Columns.NEXT_OBS in batch[DEFAULT_MODULE_ID] + ) + # TODO (sven): We are performing two forward passes per update right now. + # Once here in the connector (w/o grad) to just get the intrinsic rewards + # and once in the learner to actually compute the ICM loss and update the ICM. + # Maybe we can save one of these, but this would currently harm the DDP-setup + # for multi-GPU training. + with torch.no_grad(): + # Perform ICM forward pass. + fwd_out = rl_module[ICM_MODULE_ID].forward_train(batch[DEFAULT_MODULE_ID]) + + # Add the intrinsic rewards to the main module's extrinsic rewards. + batch[DEFAULT_MODULE_ID][Columns.REWARDS] += ( + self.intrinsic_reward_coeff * fwd_out[Columns.INTRINSIC_REWARDS] + ) + + # Duplicate the batch such that the ICM also has data to learn on. + batch[ICM_MODULE_ID] = batch[DEFAULT_MODULE_ID] + + return batch diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/metrics/__init__.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/metrics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/metrics/__pycache__/__init__.cpython-310.pyc b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/metrics/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..295bdd1f3ebe40c48570b1b37c8bca36c7924517 Binary files /dev/null and b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/metrics/__pycache__/__init__.cpython-310.pyc differ diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/metrics/custom_metrics_in_env_runners.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/metrics/custom_metrics_in_env_runners.py new file mode 100644 index 0000000000000000000000000000000000000000..6c69bdc5746e1fbb5551da8cb2b66586a34730c4 --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/metrics/custom_metrics_in_env_runners.py @@ -0,0 +1,340 @@ +"""Example of adding custom metrics to the results returned by `EnvRunner.sample()`. + +We use the `MetricsLogger` class, which RLlib provides inside all its components (only +when using the new API stack through +`config.api_stack(enable_rl_module_and_learner=True, +enable_env_runner_and_connector_v2=True)`), +and which offers a unified API to log individual values per iteration, per episode +timestep, per episode (as a whole), per loss call, etc.. +`MetricsLogger` objects are available in all custom API code, for example inside your +custom `Algorithm.training_step()` methods, custom loss functions, custom callbacks, +and custom EnvRunners. + +This example: + - demonstrates how to write a custom Callbacks subclass, which overrides some + EnvRunner-bound methods, such as `on_episode_start`, `on_episode_step`, and + `on_episode_end`. + - shows how to temporarily store per-timestep data inside the currently running + episode within the EnvRunner (and the callback methods). + - shows how to extract this temporary data again when the episode is done in order + to further process the data into a single, reportable metric. + - explains how to use the `MetricsLogger` API to create and log different metrics + to the final Algorithm's iteration output. These include - but are not limited to - + a 2D heatmap (image) per episode, an average per-episode metric (over a sliding + window of 200 episodes), a maximum per-episode metric (over a sliding window of 100 + episodes), and an EMA-smoothed metric. + +In this script, we define a custom `DefaultCallbacks` class and then override some of +its methods in order to define custom behavior during episode sampling. In particular, +we add custom metrics to the Algorithm's published result dict (once per +iteration) before it is sent back to Ray Tune (and possibly a WandB logger). + +For demonstration purposes only, we log the following custom metrics: +- A 2D heatmap showing the frequency of all accumulated y/x-locations of Ms Pacman +during an episode. We create and log a separate heatmap per episode and limit the number +of heatmaps reported back to the algorithm by each EnvRunner to 10 (`window=10`). +- The maximum per-episode distance travelled by Ms Pacman over a sliding window of 100 +episodes. +- The average per-episode distance travelled by Ms Pacman over a sliding window of 200 +episodes. +- The EMA-smoothed number of lives of Ms Pacman at each timestep (across all episodes). + + +How to run this script +---------------------- +`python [script file name].py --enable-new-api-stack --wandb-key [your WandB key] +--wandb-project [some project name]` + +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 +----------------- +This script has not been finetuned to actually learn the environment. Its purpose +is to show how you can create and log custom metrics during episode sampling and +have these stats be sent to WandB for further analysis. + +However, you should see training proceeding over time like this: ++---------------------+----------+----------------+--------+------------------+ +| Trial name | status | loc | iter | total time (s) | +| | | | | | +|---------------------+----------+----------------+--------+------------------+ +| PPO_env_efd16_00000 | RUNNING | 127.0.0.1:6181 | 4 | 72.4725 | ++---------------------+----------+----------------+--------+------------------+ ++------------------------+------------------------+------------------------+ +| episode_return_mean | num_episodes_lifetim | num_env_steps_traine | +| | e | d_lifetime | +|------------------------+------------------------+------------------------| +| 76.4 | 45 | 8053 | ++------------------------+------------------------+------------------------+ +""" +from typing import Optional, Sequence + +import gymnasium as gym +import matplotlib.pyplot as plt +from matplotlib.colors import Normalize +import numpy as np + +from ray.rllib.algorithms.callbacks import DefaultCallbacks +from ray.rllib.env.wrappers.atari_wrappers import wrap_atari_for_new_api_stack +from ray.rllib.utils.images import resize +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 + + +class MsPacmanHeatmapCallback(DefaultCallbacks): + """A custom callback to extract information from MsPacman and log these. + + This callback logs: + - the positions of MsPacman over an episode to produce heatmaps from this data. + At each episode timestep, the current pacman (y/x)-position is determined and added + to the episode's temporary storage. At the end of an episode, a simple 2D heatmap + is created from this data and the heatmap is logged to the MetricsLogger (to be + viewed in WandB). + - the max distance travelled by MsPacman per episode, then averaging these max + values over a window of size=100. + - the mean distance travelled by MsPacman per episode (over an infinite window). + - the number of lifes of MsPacman EMA-smoothed over time. + + This callback can be setup to only log stats on certain EnvRunner indices through + the `env_runner_indices` c'tor arg. + """ + + def __init__(self, env_runner_indices: Optional[Sequence[int]] = None): + """Initializes an MsPacmanHeatmapCallback instance. + + Args: + env_runner_indices: The (optional) EnvRunner indices, for this callback + should be active. If None, activates the heatmap for all EnvRunners. + If a Sequence type, only logs/heatmaps, if the EnvRunner index is found + in `env_runner_indices`. + """ + super().__init__() + # Only create heatmap on certain EnvRunner indices? + self._env_runner_indices = env_runner_indices + + # Mapping from episode ID to max distance travelled thus far. + self._episode_start_position = {} + + def on_episode_start( + self, + *, + episode, + env_runner, + metrics_logger, + env, + env_index, + rl_module, + **kwargs, + ) -> None: + # Skip, if this EnvRunner's index is not in `self._env_runner_indices`. + if ( + self._env_runner_indices is not None + and env_runner.worker_index not in self._env_runner_indices + ): + return + + yx_pos = self._get_pacman_yx_pos(env) + self._episode_start_position[episode.id_] = yx_pos + + def on_episode_step( + self, + *, + episode, + env_runner, + metrics_logger, + env, + env_index, + rl_module, + **kwargs, + ) -> None: + """Adds current pacman y/x-position to episode's temporary data.""" + + # Skip, if this EnvRunner's index is not in `self._env_runner_indices`. + if ( + self._env_runner_indices is not None + and env_runner.worker_index not in self._env_runner_indices + ): + return + + yx_pos = self._get_pacman_yx_pos(env) + episode.add_temporary_timestep_data("pacman_yx_pos", yx_pos) + + # Compute distance to start position. + dist_travelled = np.sqrt( + np.sum( + np.square( + np.array(self._episode_start_position[episode.id_]) + - np.array(yx_pos) + ) + ) + ) + episode.add_temporary_timestep_data("pacman_dist_travelled", dist_travelled) + + def on_episode_end( + self, + *, + episode, + env_runner, + metrics_logger, + env, + env_index, + rl_module, + **kwargs, + ) -> None: + # Skip, if this EnvRunner's index is not in `self._env_runner_indices`. + if ( + self._env_runner_indices is not None + and env_runner.worker_index not in self._env_runner_indices + ): + return + + # Erase the start position record. + del self._episode_start_position[episode.id_] + + # Get all pacman y/x-positions from the episode. + yx_positions = episode.get_temporary_timestep_data("pacman_yx_pos") + # h x w + heatmap = np.zeros((80, 100), dtype=np.int32) + for yx_pos in yx_positions: + if yx_pos != (-1, -1): + heatmap[yx_pos[0], yx_pos[1]] += 1 + + # Create the actual heatmap image. + # Normalize the heatmap to values between 0 and 1 + norm = Normalize(vmin=heatmap.min(), vmax=heatmap.max()) + # Use a colormap (e.g., 'hot') to map normalized values to RGB + colormap = plt.get_cmap("coolwarm") # try "hot" and "viridis" as well? + # Returns a (64, 64, 4) array (RGBA). + heatmap_rgb = colormap(norm(heatmap)) + # Convert RGBA to RGB by dropping the alpha channel and converting to uint8. + heatmap_rgb = (heatmap_rgb[:, :, :3] * 255).astype(np.uint8) + # Log the image. + metrics_logger.log_value( + "pacman_heatmap", + heatmap_rgb, + reduce=None, + window=10, # Log 10 images at most per EnvRunner/training iteration. + ) + + # Get the max distance travelled for this episode. + dist_travelled = np.max( + episode.get_temporary_timestep_data("pacman_dist_travelled") + ) + + # Log the max. dist travelled in this episode (window=100). + metrics_logger.log_value( + "pacman_max_dist_travelled", + dist_travelled, + # For future reductions (e.g. over n different episodes and all the + # data coming from other env runners), reduce by max. + reduce="max", + # Always keep the last 100 values and max over this window. + # Note that this means that over time, if the values drop to lower + # numbers again, the reported `pacman_max_dist_travelled` might also + # decrease again (meaning `window=100` makes this not a "lifetime max"). + window=100, + ) + + # Log the average dist travelled per episode (window=200). + metrics_logger.log_value( + "pacman_mean_dist_travelled", + dist_travelled, + reduce="mean", # <- default + # Always keep the last 200 values and average over this window. + window=200, + ) + + # Log the number of lifes (as EMA-smoothed; no window). + metrics_logger.log_value( + "pacman_lifes", + episode.get_infos(-1)["lives"], + reduce="mean", # <- default (must be "mean" for EMA smothing) + ema_coeff=0.01, # <- default EMA coefficient (`window` must be None) + ) + + def _get_pacman_yx_pos(self, env): + # If we have a vector env, only render the sub-env at index 0. + if isinstance(env.unwrapped, gym.vector.VectorEnv): + image = env.envs[0].render() + else: + image = env.render() + # Downsize to 100x100 for our utility function to work with. + image = resize(image, 100, 100) + # Crop image at bottom 20% (where lives are shown, which may confuse the pacman + # detector). + image = image[:80] + # Define the yellow color range in RGB (Ms. Pac-Man is yellowish). + # We allow some range around yellow to account for variation. + yellow_lower = np.array([200, 130, 65], dtype=np.uint8) + yellow_upper = np.array([220, 175, 105], dtype=np.uint8) + # Create a mask that highlights the yellow pixels + mask = np.all((image >= yellow_lower) & (image <= yellow_upper), axis=-1) + # Find the coordinates of the yellow pixels + yellow_pixels = np.argwhere(mask) + if yellow_pixels.size == 0: + return (-1, -1) + + # Calculate the centroid of the yellow pixels to get Ms. Pac-Man's position + y, x = yellow_pixels.mean(axis=0).astype(int) + return y, x + + +parser = add_rllib_example_script_args(default_reward=450.0) +parser.set_defaults(enable_new_api_stack=True) + + +if __name__ == "__main__": + args = parser.parse_args() + + # Register our environment with tune. + register_env( + "env", + lambda cfg: wrap_atari_for_new_api_stack( + gym.make("ale_py:ALE/MsPacman-v5", **cfg, **{"render_mode": "rgb_array"}), + framestack=4, + ), + ) + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment( + "env", + env_config={ + # Make analogous to old v4 + NoFrameskip. + "frameskip": 1, + "full_action_space": False, + "repeat_action_probability": 0.0, + }, + ) + .callbacks(MsPacmanHeatmapCallback) + .training( + # Make learning time fast, but note that this example may not + # necessarily learn well (its purpose is to demo the + # functionality of callbacks and the MetricsLogger). + train_batch_size_per_learner=2000, + minibatch_size=512, + num_epochs=6, + ) + .rl_module( + model_config_dict={ + "vf_share_layers": True, + "conv_filters": [[16, 4, 2], [32, 4, 2], [64, 4, 2], [128, 4, 2]], + "conv_activation": "relu", + "post_fcnet_hiddens": [256], + } + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/multi_agent/__init__.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/multi_agent/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/multi_agent/multi_agent_pendulum.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/multi_agent/multi_agent_pendulum.py new file mode 100644 index 0000000000000000000000000000000000000000..985e55aada326bc68b1fa74f9595411611b8c12e --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/multi_agent/multi_agent_pendulum.py @@ -0,0 +1,73 @@ +"""Simple example of setting up an agent-to-module mapping function. + +How to run this script +---------------------- +`python [script file name].py --enable-new-api-stack --num-agents=2` + +Control the number of agents and policies (RLModules) via --num-agents and +--num-policies. + +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)]` +""" + +from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig +from ray.rllib.examples.envs.classes.multi_agent import MultiAgentPendulum +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, +) +# 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 > 0: + register_env( + "env", + lambda _: MultiAgentPendulum(config={"num_agents": args.num_agents}), + ) + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment("env" if args.num_agents > 0 else "Pendulum-v1") + .training( + train_batch_size_per_learner=512, + minibatch_size=64, + lambda_=0.1, + gamma=0.95, + lr=0.0003, + model={"fcnet_activation": "relu"}, + 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 + run_rllib_example_script_experiment(base_config, args) diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/multi_agent/pettingzoo_shared_value_function.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/multi_agent/pettingzoo_shared_value_function.py new file mode 100644 index 0000000000000000000000000000000000000000..e2c8bb9a4ffb933f99f32c65eaa167e0d75e196d --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/multi_agent/pettingzoo_shared_value_function.py @@ -0,0 +1,7 @@ +msg = """ +This script is NOT yet ready, but will be available soon at this location. It will +feature a MultiRLModule with one shared value function and n policy heads for +cooperative multi-agent learning. +""" + +raise NotImplementedError(msg) diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/multi_agent/two_step_game_with_grouped_agents.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/multi_agent/two_step_game_with_grouped_agents.py new file mode 100644 index 0000000000000000000000000000000000000000..11daa3f218d5d46cb0c0cbcbb6307ea6fad9607c --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/multi_agent/two_step_game_with_grouped_agents.py @@ -0,0 +1,90 @@ +"""The two-step game from the QMIX paper: +https://arxiv.org/pdf/1803.11485.pdf + +See also: rllib/examples/centralized_critic.py for centralized critic PPO on this game. + +How to run this script +---------------------- +`python [script file name].py --enable-new-api-stack --num-agents=2` + +Note that in this script, we use an multi-agent environment in which both +agents that normally play this game have been merged into one agent with ID +"agents" and observation- and action-spaces being 2-tupled (1 item for each +agent). The "agents" agent is mapped to the policy with ID "p0". + +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 8.0 (the max to reach in thie game) eventually +being achieved by a simple PPO policy (no tuning, just using RLlib's default settings): + ++---------------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +|---------------------------------+------------+-----------------+--------+ +| PPO_grouped_twostep_4354b_00000 | TERMINATED | 127.0.0.1:42602 | 20 | ++---------------------------------+------------+-----------------+--------+ + ++------------------+-------+-------------------+-------------+ +| total time (s) | ts | combined reward | reward p0 | ++------------------+-------+-------------------+-------------| +| 87.5756 | 80000 | 8 | 8 | ++------------------+-------+-------------------+-------------+ +""" + +from ray.rllib.connectors.env_to_module import FlattenObservations +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.envs.classes.two_step_game import TwoStepGameWithGroupedAgents +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune.registry import register_env, get_trainable_cls + + +parser = add_rllib_example_script_args(default_reward=7.0) + + +if __name__ == "__main__": + args = parser.parse_args() + + assert args.num_agents == 2, "Must set --num-agents=2 when running this script!" + assert ( + args.enable_new_api_stack + ), "Must set --enable-new-api-stack when running this script!" + + register_env( + "grouped_twostep", + lambda config: TwoStepGameWithGroupedAgents(config), + ) + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment("grouped_twostep") + .env_runners( + env_to_module_connector=lambda env: FlattenObservations(multi_agent=True), + ) + .multi_agent( + policies={"p0"}, + policy_mapping_fn=lambda aid, *a, **kw: "p0", + ) + .rl_module( + rl_module_spec=MultiRLModuleSpec( + rl_module_specs={ + "p0": RLModuleSpec(), + }, + ) + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/multi_agent/utils/self_play_callback_old_api_stack.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/multi_agent/utils/self_play_callback_old_api_stack.py new file mode 100644 index 0000000000000000000000000000000000000000..a939c0fcbc594e0d93c64a2acebd7e8d7d9a061a --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/multi_agent/utils/self_play_callback_old_api_stack.py @@ -0,0 +1,75 @@ +import numpy as np + +from ray.rllib.algorithms.callbacks import DefaultCallbacks +from ray.rllib.utils.deprecation import Deprecated +from ray.rllib.utils.metrics import ENV_RUNNER_RESULTS + + +@Deprecated(help="Use the example for the new RLlib API stack.", error=False) +class SelfPlayCallbackOldAPIStack(DefaultCallbacks): + def __init__(self, win_rate_threshold): + super().__init__() + # 0=RandomPolicy, 1=1st main policy snapshot, + # 2=2nd main policy snapshot, etc.. + self.current_opponent = 0 + + self.win_rate_threshold = win_rate_threshold + + def on_train_result(self, *, algorithm, result, **kwargs): + # Get the win rate for the train batch. + # Note that normally, you should set up a proper evaluation config, + # such that evaluation always happens on the already updated policy, + # instead of on the already used train_batch. + main_rew = result[ENV_RUNNER_RESULTS]["hist_stats"].pop("policy_main_reward") + opponent_rew = list(result[ENV_RUNNER_RESULTS]["hist_stats"].values())[0] + assert len(main_rew) == len(opponent_rew) + won = 0 + for r_main, r_opponent in zip(main_rew, opponent_rew): + if r_main > r_opponent: + won += 1 + win_rate = won / len(main_rew) + result["win_rate"] = win_rate + print(f"Iter={algorithm.iteration} win-rate={win_rate} -> ", end="") + # If win rate is good -> Snapshot current policy and play against + # it next, keeping the snapshot fixed and only improving the "main" + # policy. + if win_rate > self.win_rate_threshold: + self.current_opponent += 1 + new_pol_id = f"main_v{self.current_opponent}" + print(f"adding new opponent to the mix ({new_pol_id}).") + + # Re-define the mapping function, such that "main" is forced + # to play against any of the previously played policies + # (excluding "random"). + def policy_mapping_fn(agent_id, episode, worker, **kwargs): + # agent_id = [0|1] -> policy depends on episode ID + # This way, we make sure that both policies sometimes play + # (start player) and sometimes agent1 (player to move 2nd). + return ( + "main" + if episode.episode_id % 2 == agent_id + else "main_v{}".format( + np.random.choice(list(range(1, self.current_opponent + 1))) + ) + ) + + main_policy = algorithm.get_policy("main") + new_policy = algorithm.add_policy( + policy_id=new_pol_id, + policy_cls=type(main_policy), + policy_mapping_fn=policy_mapping_fn, + ) + + # Set the weights of the new policy to the main policy. + # We'll keep training the main policy, whereas `new_pol_id` will + # remain fixed. + main_state = main_policy.get_state() + new_policy.set_state(main_state) + # We need to sync the just copied local weights (from main policy) + # to all the remote workers as well. + algorithm.env_runner_group.sync_weights() + else: + print("not good enough; will keep learning ...") + + # +2 = main + random + result["league_size"] = self.current_opponent + 2 diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/offline_rl/__pycache__/custom_input_api.cpython-310.pyc b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/offline_rl/__pycache__/custom_input_api.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a542be743a652d9b22859e1f67c7cbfc3da528df Binary files /dev/null and b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/offline_rl/__pycache__/custom_input_api.cpython-310.pyc differ diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/offline_rl/offline_rl.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/offline_rl/offline_rl.py new file mode 100644 index 0000000000000000000000000000000000000000..5679fc1ac63b3eb403864ef94d1245736623388b --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/offline_rl/offline_rl.py @@ -0,0 +1,167 @@ +# @OldAPIStack + +"""Example on how to use CQL to learn from an offline JSON file. + +Important node: Make sure that your offline data file contains only +a single timestep per line to mimic the way SAC pulls samples from +the buffer. + +Generate the offline json file by running an SAC algo until it reaches expert +level on your command line. For example: +$ cd ray +$ rllib train -f rllib/tuned_examples/sac/pendulum-sac.yaml --no-ray-ui + +Also make sure that in the above SAC yaml file (pendulum-sac.yaml), +you specify an additional "output" key with any path on your local +file system. In that path, the offline json files will be written to. + +Use the generated file(s) as "input" in the CQL config below +(`config["input"] = [list of your json files]`), then run this script. +""" + +import argparse +import numpy as np + +from ray.rllib.policy.sample_batch import convert_ma_batch_to_sample_batch +from ray.rllib.algorithms import cql as cql +from ray.rllib.execution.rollout_ops import ( + synchronous_parallel_sample, +) +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + EVALUATION_RESULTS, +) + +torch, _ = try_import_torch() + +parser = argparse.ArgumentParser() +parser.add_argument( + "--as-test", + action="store_true", + help="Whether this script should be run as a test: --stop-reward must " + "be achieved within --stop-timesteps AND --stop-iters.", +) +parser.add_argument( + "--stop-iters", type=int, default=5, help="Number of iterations to train." +) +parser.add_argument( + "--stop-reward", type=float, default=50.0, help="Reward at which we stop training." +) + + +if __name__ == "__main__": + args = parser.parse_args() + + # See rllib/tuned_examples/cql/pendulum-cql.yaml for comparison. + config = ( + cql.CQLConfig() + .api_stack( + enable_env_runner_and_connector_v2=False, + enable_rl_module_and_learner=False, + ) + .framework(framework="torch") + .env_runners(num_env_runners=0) + .training( + n_step=3, + bc_iters=0, + clip_actions=False, + tau=0.005, + target_entropy="auto", + q_model_config={ + "fcnet_hiddens": [256, 256], + "fcnet_activation": "relu", + }, + policy_model_config={ + "fcnet_hiddens": [256, 256], + "fcnet_activation": "relu", + }, + optimization_config={ + "actor_learning_rate": 3e-4, + "critic_learning_rate": 3e-4, + "entropy_learning_rate": 3e-4, + }, + train_batch_size=256, + target_network_update_freq=1, + num_steps_sampled_before_learning_starts=256, + ) + .reporting(min_train_timesteps_per_iteration=1000) + .debugging(log_level="INFO") + .environment("Pendulum-v1", normalize_actions=True) + .offline_data( + input_config={ + "paths": ["tests/data/pendulum/enormous.zip"], + "format": "json", + } + ) + .evaluation( + evaluation_num_env_runners=1, + evaluation_interval=1, + evaluation_duration=10, + evaluation_parallel_to_training=False, + evaluation_config=cql.CQLConfig.overrides(input_="sampler"), + ) + ) + # evaluation_parallel_to_training should be False b/c iterations are very long + # and this would cause evaluation to lag one iter behind training. + + # Check, whether we can learn from the given file in `num_iterations` + # iterations, up to a reward of `min_reward`. + num_iterations = 5 + min_reward = -300 + + cql_algorithm = cql.CQL(config=config) + learnt = False + for i in range(num_iterations): + print(f"Iter {i}") + eval_results = cql_algorithm.train().get(EVALUATION_RESULTS) + if eval_results: + print( + "... R={}".format(eval_results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN]) + ) + # Learn until some reward is reached on an actual live env. + if eval_results[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN] >= min_reward: + # Test passed gracefully. + if args.as_test: + print("Test passed after {} iterations.".format(i)) + quit(0) + learnt = True + break + + # Get policy and model. + cql_policy = cql_algorithm.get_policy() + cql_model = cql_policy.model + + # If you would like to query CQL's learnt Q-function for arbitrary + # (cont.) actions, do the following: + obs_batch = torch.from_numpy(np.random.random(size=(5, 3))) + action_batch = torch.from_numpy(np.random.random(size=(5, 1))) + q_values = cql_model.get_q_values(obs_batch, action_batch)[0] + # If you are using the "twin_q", there'll be 2 Q-networks and + # we usually consider the min of the 2 outputs, like so: + twin_q_values = cql_model.get_twin_q_values(obs_batch, action_batch)[0] + final_q_values = torch.min(q_values, twin_q_values)[0] + print(f"final_q_values={final_q_values.detach().numpy()}") + + # Example on how to do evaluation on the trained Algorithm. + # using the data from our buffer. + # Get a sample (MultiAgentBatch). + + batch = synchronous_parallel_sample(worker_set=cql_algorithm.env_runner_group) + batch = convert_ma_batch_to_sample_batch(batch) + obs = torch.from_numpy(batch["obs"]) + # Pass the observations through our model to get the + # features, which then to pass through the Q-head. + model_out, _ = cql_model({"obs": obs}) + # The estimated Q-values from the (historic) actions in the batch. + q_values_old = cql_model.get_q_values( + model_out, torch.from_numpy(batch["actions"]) + )[0] + # The estimated Q-values for the new actions computed by our policy. + actions_new = cql_policy.compute_actions_from_input_dict({"obs": obs})[0] + q_values_new = cql_model.get_q_values(model_out, torch.from_numpy(actions_new))[0] + print(f"Q-val batch={q_values_old.detach().numpy()}") + print(f"Q-val policy={q_values_new.detach().numpy()}") + + cql_algorithm.stop() diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/offline_rl/pretrain_bc_single_agent_evaluate_as_multi_agent.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/offline_rl/pretrain_bc_single_agent_evaluate_as_multi_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..a6e468771834a4c7751735467e359d89373b93c4 --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/offline_rl/pretrain_bc_single_agent_evaluate_as_multi_agent.py @@ -0,0 +1,171 @@ +# @HybridAPIStack + +"""Example showing how to train a (SA) BC RLModule while evaluating in a MA setup. + +Here, SA=single-agent and MA=multi-agent. + +Note that the BC Algorithm - by default - runs on the hybrid API stack, using RLModules, +but not `ConnectorV2` and `SingleAgentEpisode` yet. + +This example: + - demonstrates how you can train a single-agent BC Policy (RLModule) from a JSON + file, which contains SampleBatch (expert or non-expert) data. + - shows how you can run evaluation in a multi-agent setup (for example vs one + or more heuristic policies), while training the BC Policy. + + +How to run this script +---------------------- +`python [script file name].py --checkpoint-at-end` + +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 the episode returns of the "main" policy on +the evaluation track keep increasing as BC manages to more and more clone the behavior +found in our (expert) JSON file. + +After 50-100 iterations, you should see the episode reward reach 450.0. +Note that the opponent (random) policy does not learn as it's a) not a trainable +RLModule and b) not being trained via the BCConfig. It's only used for evaluation +purposes here. + ++---------------------+------------+-----------------+--------+--------+ +| Trial name | status | loc | iter | ts | +|---------------------+------------+-----------------+--------+--------+ +| BC_None_ee65e_00000 | TERMINATED | 127.0.0.1:35031 | 93 | 203754 | ++---------------------+------------+-----------------+--------+--------+ ++----------------------+------------------------+ +| eps. return (main) | eps. return (random) | +|----------------------+------------------------| +| 452.4 | 28.3 | ++----------------------+------------------------+ +""" +import os +from pathlib import Path + +import gymnasium as gym + +from ray import tune +from ray.air.constants import TRAINING_ITERATION +from ray.rllib.algorithms.bc import BCConfig +from ray.rllib.examples.envs.classes.multi_agent import MultiAgentCartPole +from ray.rllib.examples._old_api_stack.policy.random_policy import RandomPolicy +from ray.rllib.policy.policy import PolicySpec +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EVALUATION_RESULTS, + NUM_ENV_STEPS_TRAINED, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.train.constants import TIME_TOTAL_S +from ray.tune.registry import register_env + +parser = add_rllib_example_script_args( + default_reward=450.0, + default_timesteps=300000, +) +parser.set_defaults(num_agents=2) + + +if __name__ == "__main__": + args = parser.parse_args() + + register_env("multi_cart", lambda cfg: MultiAgentCartPole(cfg)) + dummy_env = gym.make("CartPole-v1") + + rllib_dir = Path(__file__).parent.parent.parent + print(f"rllib dir={rllib_dir}") + offline_file = os.path.join(rllib_dir, "tests/data/cartpole/large.json") + + base_config = ( + BCConfig() + # For offline RL, we do not specify an env here (b/c we don't want any env + # instances created on the EnvRunners). Instead, we'll provide observation- + # and action-spaces here for the RLModule to know its input- and output types. + .environment( + observation_space=dummy_env.observation_space, + action_space=dummy_env.action_space, + ) + .offline_data( + input_=offline_file, + ) + .multi_agent( + policies={"main"}, + policy_mapping_fn=lambda *a, **kw: "main", + ) + .evaluation( + evaluation_interval=1, + evaluation_num_env_runners=0, + evaluation_config=BCConfig.overrides( + # Evaluate on an actual env -> switch input back to "sampler". + input_="sampler", + # Do not explore during evaluation, but act greedily. + explore=False, + # Use a multi-agent setup for evaluation. + env="multi_cart", + env_config={"num_agents": args.num_agents}, + policies={ + "main": PolicySpec(), + "random": PolicySpec(policy_class=RandomPolicy), + }, + # Only control agent 0 with the main (trained) policy. + policy_mapping_fn=( + lambda aid, *a, **kw: "main" if aid == 0 else "random" + ), + # Note that we do NOT have to specify the `policies_to_train` here, + # b/c we are inside the evaluation config (no policy is trained during + # evaluation). The fact that the BCConfig above is "only" setup + # as single-agent makes it automatically only train the policy found in + # the BCConfig's `policies` field (which is "main"). + # policies_to_train=["main"], + ), + ) + ) + + policy_eval_returns = ( + f"{EVALUATION_RESULTS}/{ENV_RUNNER_RESULTS}/policy_reward_mean/" + ) + + stop = { + # Check for the "main" policy's episode return, not the combined one. + # The combined one is the sum of the "main" policy + the "random" one. + policy_eval_returns + "main": args.stop_reward, + NUM_ENV_STEPS_TRAINED: args.stop_timesteps, + TRAINING_ITERATION: args.stop_iters, + } + + run_rllib_example_script_experiment( + base_config, + args, + stop=stop, + success_metric={policy_eval_returns + "main": args.stop_reward}, + # We use a special progress reporter here to show the evaluation results (of the + # "main" policy). + # In the following dict, the keys are the (possibly nested) keys that can be + # found in RLlib's (BC's) result dict, produced at every training iteration, and + # the values are the column names you would like to see in your console reports. + # Note that for nested result dict keys, you need to use slashes "/" to define + # the exact path. + progress_reporter=tune.CLIReporter( + metric_columns={ + TRAINING_ITERATION: "iter", + TIME_TOTAL_S: "total time (s)", + NUM_ENV_STEPS_TRAINED: "ts", + policy_eval_returns + "main": "eps. return (main)", + policy_eval_returns + "random": "eps. return (random)", + } + ), + ) diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/ray_serve/__pycache__/ray_serve_with_rllib.cpython-310.pyc b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/ray_serve/__pycache__/ray_serve_with_rllib.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d5455993ac911b1b79197d45043ed6af1972bd1 Binary files /dev/null and b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/ray_serve/__pycache__/ray_serve_with_rllib.cpython-310.pyc differ diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/ray_serve/ray_serve_with_rllib.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/ray_serve/ray_serve_with_rllib.py new file mode 100644 index 0000000000000000000000000000000000000000..0853151f40fa0b11905531305393ec58c5cc9c25 --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/ray_serve/ray_serve_with_rllib.py @@ -0,0 +1,190 @@ +"""Example on how to run RLlib in combination with Ray Serve. + +This example trains an agent with PPO on the CartPole environment, then creates +an RLModule checkpoint and returns its location. After that, it sends the checkpoint +to the Serve deployment for serving the trained RLModule (policy). + +This example: + - shows how to set up a Ray Serve deployment for serving an already trained + RLModule (policy network). + - shows how to request new actions from the Ray Serve deployment while actually + running through episodes in an environment (on which the RLModule that's served + was trained). + + +How to run this script +---------------------- +`python [script file name].py --enable-new-api-stack --stop-reward=200.0` + +Use the `--stop-iters`, `--stop-reward`, and/or `--stop-timesteps` options to +determine how long to train the policy for. Use the `--serve-episodes` option to +set the number of episodes to serve (after training) and the `--no-render` option +to NOT render the environment during the serving phase. + +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 the command line when using the +options: `--stop-reward=250.0`, `--num-episodes-served=2`, and `--port=12345`: + +[First, the RLModule is trained through PPO] + ++-----------------------------+------------+-----------------+--------+ +| Trial name | status | loc | iter | +| | | | | +|-----------------------------+------------+-----------------+--------+ +| PPO_CartPole-v1_84778_00000 | TERMINATED | 127.0.0.1:40411 | 1 | ++-----------------------------+------------+-----------------+--------+ ++------------------+---------------------+------------------------+ +| total time (s) | episode_return_mean | num_env_steps_sample | +| | | d_lifetime | +|------------------+---------------------|------------------------| +| 2.87052 | 253.2 | 12000 | ++------------------+---------------------+------------------------+ + +[The RLModule is deployed through Ray Serve on port 12345] + +Started Ray Serve with PID: 40458 + +[A few episodes are played through using the policy service (w/ greedy, non-exploratory +actions)] + +Episode R=500.0 +Episode R=500.0 +""" + +import atexit +import os + +import requests +import subprocess +import time + +import gymnasium as gym +from pathlib import Path + +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.core import ( + COMPONENT_LEARNER_GROUP, + COMPONENT_LEARNER, + COMPONENT_RL_MODULE, + DEFAULT_MODULE_ID, +) +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, +) +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) + +parser = add_rllib_example_script_args() +parser.set_defaults( + enable_new_api_stack=True, + checkpoint_freq=1, + checkpoint_at_and=True, +) +parser.add_argument("--num-episodes-served", type=int, default=2) +parser.add_argument("--no-render", action="store_true") +parser.add_argument("--port", type=int, default=12345) + + +def kill_proc(proc): + try: + proc.terminate() # Send SIGTERM + proc.wait(timeout=5) # Wait for process to terminate + except subprocess.TimeoutExpired: + proc.kill() # Send SIGKILL + proc.wait() # Ensure process is dead + + +if __name__ == "__main__": + args = parser.parse_args() + + # Config for the served RLlib RLModule/Algorithm. + base_config = PPOConfig().environment("CartPole-v1") + + results = run_rllib_example_script_experiment(base_config, args) + algo_checkpoint = results.get_best_result( + f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}" + ).checkpoint.path + # We only need the RLModule component from the algorithm checkpoint. It's located + # under "[algo checkpoint dir]/learner_group/learner/rl_module/[default policy ID] + rl_module_checkpoint = ( + Path(algo_checkpoint) + / COMPONENT_LEARNER_GROUP + / COMPONENT_LEARNER + / COMPONENT_RL_MODULE + / DEFAULT_MODULE_ID + ) + + path_of_this_file = Path(__file__).parent + os.chdir(path_of_this_file) + # Start the serve app with the trained checkpoint. + serve_proc = subprocess.Popen( + [ + "serve", + "run", + "classes.cartpole_deployment:rl_module", + f"rl_module_checkpoint={rl_module_checkpoint}", + f"port={args.port}", + "route_prefix=/rllib-rlmodule", + ] + ) + # Register our `kill_proc` function to be called on exit to stop Ray Serve again. + atexit.register(kill_proc, serve_proc) + # Wait a while to make sure the app is ready to serve. + time.sleep(20) + print(f"Started Ray Serve with PID: {serve_proc.pid}") + + try: + # Create the environment that we would like to receive + # served actions for. + env = gym.make("CartPole-v1", render_mode="human") + obs, _ = env.reset() + + num_episodes = 0 + episode_return = 0.0 + + while num_episodes < args.num_episodes_served: + # Render env if necessary. + if not args.no_render: + env.render() + + # print(f"-> Requesting action for obs={obs} ...", end="") + # Send a request to serve. + resp = requests.get( + f"http://localhost:{args.port}/rllib-rlmodule", + json={"observation": obs.tolist()}, + ) + response = resp.json() + # print(f" received: action={response['action']}") + + # Apply the action in the env. + action = response["action"] + obs, reward, terminated, truncated, _ = env.step(action) + episode_return += reward + + # If episode done -> reset to get initial observation of new episode. + if terminated or truncated: + print(f"Episode R={episode_return}") + obs, _ = env.reset() + num_episodes += 1 + episode_return = 0.0 + + finally: + # Make sure to kill the process on script termination + kill_proc(serve_proc) diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/__pycache__/__init__.cpython-310.pyc b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36db7ff4dcfab2ca7c59a7d9458ecd2c08fc081a Binary files /dev/null and b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/__pycache__/__init__.cpython-310.pyc differ diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/__pycache__/migrate_modelv2_to_new_api_stack_by_config.cpython-310.pyc b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/__pycache__/migrate_modelv2_to_new_api_stack_by_config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f51756f8bf075cd362bbb847cf5c735896fbce4f Binary files /dev/null and b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/__pycache__/migrate_modelv2_to_new_api_stack_by_config.cpython-310.pyc differ diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/__pycache__/migrate_modelv2_to_new_api_stack_by_policy_checkpoint.cpython-310.pyc b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/__pycache__/migrate_modelv2_to_new_api_stack_by_policy_checkpoint.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b39d9feaefbf7d11c9493a9d5ddfef45809099d Binary files /dev/null and b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/__pycache__/migrate_modelv2_to_new_api_stack_by_policy_checkpoint.cpython-310.pyc differ diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/autoregressive_actions_rl_module.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/autoregressive_actions_rl_module.py new file mode 100644 index 0000000000000000000000000000000000000000..af1e27146582c8e5413cff10dbb88c8bcdefb987 --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/autoregressive_actions_rl_module.py @@ -0,0 +1,112 @@ +"""An example script showing how to define and load an `RLModule` with +a dependent action space. + +This examples: + - Defines an `RLModule` with autoregressive actions. + - It does so by implementing a prior distribution for the first couple + of actions and then using these actions in a posterior distribution. + - Furthermore, it uses in the `RLModule` our simple base `Catalog` class + to build the distributions. + - Uses this `RLModule` in a PPO training run on a simple environment + that rewards synchronized actions. + - Stops the training after 100k steps or when the mean episode return + exceeds -0.012 in evaluation, i.e. if the agent has learned to + synchronize its actions. + +How to run this script +---------------------- +`python [script file name].py --enable-new-api-stack --num-env-runners 2` + +Control the number of `EnvRunner`s with the `--num-env-runners` flag. This +will increase the sampling speed. + +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 around 155-160 after ~36,000 timesteps sampled +(trained) being achieved by a simple PPO policy (no tuning, just using RLlib's +default settings). For details take also a closer look into the +`CorrelatedActionsEnv` environment. Rewards are such that to receive a return +over 100, the agent must learn to synchronize its actions. +""" + + +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.core.models.catalog import Catalog +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.examples.envs.classes.correlated_actions_env import ( + AutoRegressiveActionEnv, +) +from ray.rllib.examples.rl_modules.classes.autoregressive_actions_rlm import ( + AutoregressiveActionsTorchRLM, +) +from ray.rllib.utils.metrics import ( + ENV_RUNNER_RESULTS, + EPISODE_RETURN_MEAN, + EVALUATION_RESULTS, + 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 import register_env + + +register_env("correlated_actions_env", lambda _: AutoRegressiveActionEnv(_)) + +parser = add_rllib_example_script_args( + default_iters=200, + default_timesteps=100000, + default_reward=150.0, +) + +if __name__ == "__main__": + args = parser.parse_args() + + if args.algo != "PPO": + raise ValueError("This example only supports PPO. Please use --algo=PPO.") + + base_config = ( + PPOConfig() + .environment("correlated_actions_env") + .rl_module( + # We need to explicitly specify here RLModule to use and + # the catalog needed to build it. + rl_module_spec=RLModuleSpec( + module_class=AutoregressiveActionsTorchRLM, + model_config={ + "head_fcnet_hiddens": [64, 64], + "head_fcnet_activation": "relu", + }, + catalog_class=Catalog, + ), + ) + .env_runners( + num_env_runners=0, + ) + .evaluation( + evaluation_num_env_runners=1, + evaluation_interval=1, + # Run evaluation parallel to training to speed up the example. + evaluation_parallel_to_training=True, + ) + ) + + # Let's stop the training after 100k steps or when the mean episode return + # exceeds -0.012 in evaluation. + stop = { + f"{NUM_ENV_STEPS_SAMPLED_LIFETIME}": 100000, + f"{EVALUATION_RESULTS}/{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}": -0.012, + } + + # Run the example (with Tune). + run_rllib_example_script_experiment(base_config, args, stop=stop) diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/classes/__init__.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/classes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b6525851c1ac8cecc0a4491a2bf04f21969ac921 --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/classes/__init__.py @@ -0,0 +1,10 @@ +from ray.rllib.examples.rl_modules.classes.rock_paper_scissors_heuristic_rlm import ( + AlwaysSameHeuristicRLM, + BeatLastHeuristicRLM, +) + + +__all__ = [ + "AlwaysSameHeuristicRLM", + "BeatLastHeuristicRLM", +] diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/action_masking_rlm.cpython-310.pyc b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/action_masking_rlm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e473f28ceafa54bfc5120e07bf8a891c5de76d9d Binary files /dev/null and b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/action_masking_rlm.cpython-310.pyc differ diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/random_rlm.cpython-310.pyc b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/random_rlm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8602098d6b92248f2444fa0df3513f563b4ae044 Binary files /dev/null and b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/classes/__pycache__/random_rlm.cpython-310.pyc differ diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/classes/mobilenet_rlm.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/classes/mobilenet_rlm.py new file mode 100644 index 0000000000000000000000000000000000000000..8f3a86e692355eaebbb8e797876c32e38090cc83 --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/classes/mobilenet_rlm.py @@ -0,0 +1,78 @@ +""" +This example shows how to take full control over what models and action distribution +are being built inside an RL Module. With this pattern, we can bypass a Catalog and +explicitly define our own models within a given RL Module. +""" +# __sphinx_doc_begin__ +import gymnasium as gym +import numpy as np + +from ray.rllib.algorithms.ppo.ppo import PPOConfig +from ray.rllib.algorithms.ppo.torch.ppo_torch_rl_module import PPOTorchRLModule +from ray.rllib.core.models.configs import MLPHeadConfig +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.examples.envs.classes.random_env import RandomEnv +from ray.rllib.examples._old_api_stack.models.mobilenet_v2_encoder import ( + MobileNetV2EncoderConfig, + MOBILENET_INPUT_SHAPE, +) +from ray.rllib.core.models.configs import ActorCriticEncoderConfig + + +class MobileNetTorchPPORLModule(PPOTorchRLModule): + """A PPORLModules with mobilenet v2 as an encoder. + + The idea behind this model is to demonstrate how we can bypass catalog to + take full control over what models and action distribution are being built. + In this example, we do this to modify an existing RLModule with a custom encoder. + """ + + def setup(self): + mobilenet_v2_config = MobileNetV2EncoderConfig() + # Since we want to use PPO, which is an actor-critic algorithm, we need to + # use an ActorCriticEncoderConfig to wrap the base encoder config. + actor_critic_encoder_config = ActorCriticEncoderConfig( + base_encoder_config=mobilenet_v2_config + ) + + self.encoder = actor_critic_encoder_config.build(framework="torch") + mobilenet_v2_output_dims = mobilenet_v2_config.output_dims + + pi_config = MLPHeadConfig( + input_dims=mobilenet_v2_output_dims, + output_layer_dim=2, + ) + + vf_config = MLPHeadConfig( + input_dims=mobilenet_v2_output_dims, output_layer_dim=1 + ) + + self.pi = pi_config.build(framework="torch") + self.vf = vf_config.build(framework="torch") + + +config = ( + PPOConfig() + .rl_module(rl_module_spec=RLModuleSpec(module_class=MobileNetTorchPPORLModule)) + .environment( + RandomEnv, + env_config={ + "action_space": gym.spaces.Discrete(2), + # Test a simple Image observation space. + "observation_space": gym.spaces.Box( + 0.0, + 1.0, + shape=MOBILENET_INPUT_SHAPE, + dtype=np.float32, + ), + }, + ) + .env_runners(num_env_runners=0) + # The following training settings make it so that a training iteration is very + # quick. This is just for the sake of this example. PPO will not learn properly + # with these settings! + .training(train_batch_size_per_learner=32, minibatch_size=16, num_epochs=1) +) + +config.build().train() +# __sphinx_doc_end__ diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/classes/random_rlm.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/classes/random_rlm.py new file mode 100644 index 0000000000000000000000000000000000000000..e35292e212cfb90731eb188770222bf388f7d45a --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/classes/random_rlm.py @@ -0,0 +1,71 @@ +import gymnasium as gym +import numpy as np +import tree # pip install dm_tree + +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module import RLModule +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.utils.annotations import override +from ray.rllib.utils.spaces.space_utils import batch as batch_func + + +class RandomRLModule(RLModule): + @override(RLModule) + def _forward(self, batch, **kwargs): + obs_batch_size = len(tree.flatten(batch[SampleBatch.OBS])[0]) + actions = batch_func( + [self.action_space.sample() for _ in range(obs_batch_size)] + ) + return {SampleBatch.ACTIONS: actions} + + @override(RLModule) + def _forward_train(self, *args, **kwargs): + # RandomRLModule should always be configured as non-trainable. + # To do so, set in your config: + # `config.multi_agent(policies_to_train=[list of ModuleIDs to be trained, + # NOT including the ModuleID of this RLModule])` + raise NotImplementedError("Random RLModule: Should not be trained!") + + @override(RLModule) + def output_specs_inference(self): + return [SampleBatch.ACTIONS] + + @override(RLModule) + def output_specs_exploration(self): + return [SampleBatch.ACTIONS] + + def compile(self, *args, **kwargs): + """Dummy method for compatibility with TorchRLModule. + + This is hit when RolloutWorker tries to compile TorchRLModule.""" + pass + + +class StatefulRandomRLModule(RandomRLModule): + """A stateful RLModule that returns STATE_OUT from its forward methods. + + - Implements the `get_initial_state` method (returning a all-zeros dummy state). + - Returns a dummy state under the `Columns.STATE_OUT` from its forward methods. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._internal_state_space = gym.spaces.Box(-1.0, 1.0, (1,)) + + @override(RLModule) + def get_initial_state(self): + return { + "state": np.zeros_like([self._internal_state_space.sample()]), + } + + def _random_forward(self, batch, **kwargs): + batch = super()._random_forward(batch, **kwargs) + batch[Columns.STATE_OUT] = { + "state": batch_func( + [ + self._internal_state_space.sample() + for _ in range(len(batch[Columns.ACTIONS])) + ] + ), + } + return batch diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/classes/rock_paper_scissors_heuristic_rlm.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/classes/rock_paper_scissors_heuristic_rlm.py new file mode 100644 index 0000000000000000000000000000000000000000..f4b3d661f4de3e970979d4c2c42b7b7464932ecd --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/classes/rock_paper_scissors_heuristic_rlm.py @@ -0,0 +1,108 @@ +from collections import defaultdict + +import numpy as np + +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.rl_module import RLModule +from ray.rllib.utils.annotations import override + + +class AlwaysSameHeuristicRLM(RLModule): + """In rock-paper-scissors, always chooses the same action within an episode. + + The first move is random, all the following moves are the same as the first one. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._actions_per_vector_idx = defaultdict(int) + + @override(RLModule) + def _forward_inference(self, batch, **kwargs): + ret = [] + # Note that the obs is the previous move of the opponens (0-2). If it's 3, it + # means that there was no previous move and thus, the episode just started. + for i, obs in enumerate(batch[Columns.OBS]): + if obs == 3: + self._actions_per_vector_idx[i] = np.random.choice([0, 1, 2]) + ret.append(self._actions_per_vector_idx[i]) + return {Columns.ACTIONS: np.array(ret)} + + @override(RLModule) + def _forward_exploration(self, batch, **kwargs): + return self._forward_inference(batch, **kwargs) + + @override(RLModule) + def _forward_train(self, batch, **kwargs): + raise NotImplementedError( + "AlwaysSameHeuristicRLM is not trainable! Make sure you do NOT include it " + "in your `config.multi_agent(policies_to_train={...})` set." + ) + + @override(RLModule) + def output_specs_inference(self): + return [Columns.ACTIONS] + + @override(RLModule) + def output_specs_exploration(self): + return [Columns.ACTIONS] + + +class BeatLastHeuristicRLM(RLModule): + """In rock-paper-scissors, always acts such that it beats prev. move of opponent. + + The first move is random. + + For example, after opponent played `rock` (and this policy made a random + move), the next move would be `paper`(to beat `rock`). + """ + + @override(RLModule) + def _forward_inference(self, batch, **kwargs): + """Returns the exact action that would beat the previous action of the opponent. + + The opponent's previous action is the current observation for this agent. + + Both action- and observation spaces are discrete. There are 3 actions available. + (0-2) and 4 observations (0-2 plus 3, where 3 is the observation after the env + reset, when no action has been taken yet). Thereby: + 0=Rock + 1=Paper + 2=Scissors + 3=[after reset] (observation space only) + """ + return { + Columns.ACTIONS: np.array( + [self._pick_single_action(obs) for obs in batch[Columns.OBS]] + ), + } + + @override(RLModule) + def _forward_exploration(self, batch, **kwargs): + return self._forward_inference(batch, **kwargs) + + @override(RLModule) + def _forward_train(self, batch, **kwargs): + raise NotImplementedError( + "BeatLastHeuristicRLM is not trainable! Make sure you do NOT include it in " + "your `config.multi_agent(policies_to_train={...})` set." + ) + + @override(RLModule) + def output_specs_inference(self): + return [Columns.ACTIONS] + + @override(RLModule) + def output_specs_exploration(self): + return [Columns.ACTIONS] + + @staticmethod + def _pick_single_action(prev_opponent_obs): + if prev_opponent_obs == 0: + return 1 + elif prev_opponent_obs == 1: + return 2 + elif prev_opponent_obs == 2: + return 0 + else: + return np.random.choice([0, 1, 2]) diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/classes/tiny_atari_cnn_rlm.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/classes/tiny_atari_cnn_rlm.py new file mode 100644 index 0000000000000000000000000000000000000000..0f58f18a3543264125e21626fc203e22c89f6272 --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/classes/tiny_atari_cnn_rlm.py @@ -0,0 +1,168 @@ +from typing import Any, Dict, Optional + +from ray.rllib.core.columns import Columns +from ray.rllib.core.rl_module.apis.value_function_api import ValueFunctionAPI +from ray.rllib.core.rl_module.torch import TorchRLModule +from ray.rllib.models.torch.misc import ( + normc_initializer, + same_padding, + valid_padding, +) +from ray.rllib.utils.annotations import override +from ray.rllib.utils.framework import try_import_torch +from ray.rllib.utils.typing import TensorType + +torch, nn = try_import_torch() + + +class TinyAtariCNN(TorchRLModule, ValueFunctionAPI): + """A tiny CNN stack for fast-learning of Atari envs. + + The architecture here is the exact same as the one used by the old API stack as + CNN default ModelV2. + + We stack 3 CNN layers based on the config, then a 4th one with linear activation + and n 1x1 filters, where n is the number of actions in the (discrete) action space. + Simple reshaping (no flattening or extra linear layers necessary) lead to the + action logits, which can directly be used inside a distribution or loss. + + import numpy as np + import gymnasium as gym + from ray.rllib.core.rl_module.rl_module import RLModuleConfig + + rl_module_config = RLModuleConfig( + observation_space=gym.spaces.Box(-1.0, 1.0, (42, 42, 4), np.float32), + action_space=gym.spaces.Discrete(4), + ) + my_net = TinyAtariCNN(rl_module_config) + + B = 10 + w = 42 + h = 42 + c = 4 + data = torch.from_numpy( + np.random.random_sample(size=(B, w, h, c)).astype(np.float32) + ) + print(my_net.forward_inference({"obs": data})) + print(my_net.forward_exploration({"obs": data})) + print(my_net.forward_train({"obs": data})) + + num_all_params = sum(int(np.prod(p.size())) for p in my_net.parameters()) + print(f"num params = {num_all_params}") + """ + + @override(TorchRLModule) + def setup(self): + """Use this method to create all the model components that you require. + + Feel free to access the following useful properties in this class: + - `self.model_config`: The config dict for this RLModule class, + which should contain flxeible settings, for example: {"hiddens": [256, 256]}. + - `self.observation|action_space`: The observation and action space that + this RLModule is subject to. Note that the observation space might not be the + exact space from your env, but that it might have already gone through + preprocessing through a connector pipeline (for example, flattening, + frame-stacking, mean/std-filtering, etc..). + """ + # Get the CNN stack config from our RLModuleConfig's (self.config) + # `model_config` property: + conv_filters = self.model_config.get("conv_filters") + # Default CNN stack with 3 layers: + if conv_filters is None: + conv_filters = [ + [16, 4, 2, "same"], # num filters, kernel wxh, stride wxh, padding type + [32, 4, 2, "same"], + [256, 11, 1, "valid"], + ] + + # Build the CNN layers. + layers = [] + + # Add user-specified hidden convolutional layers first + width, height, in_depth = self.observation_space.shape + in_size = [width, height] + for filter_specs in conv_filters: + if len(filter_specs) == 4: + out_depth, kernel_size, strides, padding = filter_specs + else: + out_depth, kernel_size, strides = filter_specs + padding = "same" + + # Pad like in tensorflow's SAME mode. + if padding == "same": + padding_size, out_size = same_padding(in_size, kernel_size, strides) + layers.append(nn.ZeroPad2d(padding_size)) + # No actual padding is performed for "valid" mode, but we will still + # compute the output size (input for the next layer). + else: + out_size = valid_padding(in_size, kernel_size, strides) + + layer = nn.Conv2d(in_depth, out_depth, kernel_size, strides, bias=True) + # Initialize CNN layer kernel and bias. + nn.init.xavier_uniform_(layer.weight) + nn.init.zeros_(layer.bias) + layers.append(layer) + # Activation. + layers.append(nn.ReLU()) + + in_size = out_size + in_depth = out_depth + + self._base_cnn_stack = nn.Sequential(*layers) + + # Add the final CNN 1x1 layer with num_filters == num_actions to be reshaped to + # yield the logits (no flattening, no additional linear layers required). + _final_conv = nn.Conv2d(in_depth, self.action_space.n, 1, 1, bias=True) + nn.init.xavier_uniform_(_final_conv.weight) + nn.init.zeros_(_final_conv.bias) + self._logits = nn.Sequential( + nn.ZeroPad2d(same_padding(in_size, 1, 1)[0]), _final_conv + ) + + self._values = nn.Linear(in_depth, 1) + # Mimick old API stack behavior of initializing the value function with `normc` + # std=0.01. + normc_initializer(0.01)(self._values.weight) + + @override(TorchRLModule) + def _forward(self, batch, **kwargs): + # Compute the basic 1D feature tensor (inputs to policy- and value-heads). + _, logits = self._compute_embeddings_and_logits(batch) + # Return features and logits as ACTION_DIST_INPUTS (categorical distribution). + return { + Columns.ACTION_DIST_INPUTS: logits, + } + + @override(TorchRLModule) + def _forward_train(self, batch, **kwargs): + # Compute the basic 1D feature tensor (inputs to policy- and value-heads). + embeddings, logits = self._compute_embeddings_and_logits(batch) + # Return features and logits as ACTION_DIST_INPUTS (categorical distribution). + return { + Columns.ACTION_DIST_INPUTS: logits, + Columns.EMBEDDINGS: embeddings, + } + + # We implement this RLModule as a ValueFunctionAPI RLModule, so it can be used + # by value-based methods like PPO or IMPALA. + @override(ValueFunctionAPI) + def compute_values( + self, + batch: Dict[str, Any], + embeddings: Optional[Any] = None, + ) -> TensorType: + # Features not provided -> We need to compute them first. + if embeddings is None: + obs = batch[Columns.OBS] + embeddings = self._base_cnn_stack(obs.permute(0, 3, 1, 2)) + embeddings = torch.squeeze(embeddings, dim=[-1, -2]) + return self._values(embeddings).squeeze(-1) + + def _compute_embeddings_and_logits(self, batch): + obs = batch[Columns.OBS].permute(0, 3, 1, 2) + embeddings = self._base_cnn_stack(obs) + logits = self._logits(embeddings) + return ( + torch.squeeze(embeddings, dim=[-1, -2]), + torch.squeeze(logits, dim=[-1, -2]), + ) diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/custom_cnn_rl_module.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/custom_cnn_rl_module.py new file mode 100644 index 0000000000000000000000000000000000000000..4001f3e21d6b8b09793f19355f0e7ae177634112 --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/custom_cnn_rl_module.py @@ -0,0 +1,120 @@ +"""Example of implementing and configuring a custom (torch) CNN containing RLModule. + +This example: + - demonstrates how you can subclass the TorchRLModule base class and set up your + own CNN-stack architecture by overriding the `setup()` method. + - shows how to override the 3 forward methods: `_forward_inference()`, + `_forward_exploration()`, and `forward_train()` to implement your own custom forward + logic(s). You will also learn, when each of these 3 methods is called by RLlib or + the users of your RLModule. + - shows how you then configure an RLlib Algorithm such that it uses your custom + RLModule (instead of a default RLModule). + +We implement a tiny CNN stack here, the exact same one that is used by the old API +stack as default CNN net. It comprises 4 convolutional layers, the last of which +ends in a 1x1 filter size and the number of filters exactly matches the number of +discrete actions (logits). This way, the (non-activated) output of the last layer only +needs to be reshaped in order to receive the policy's logit outputs. No flattening +or additional dense layer required. + +The network is then used in a fast ALE/Pong-v5 experiment. + + +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 +----------------- +You should see the following output (during the experiment) in your console: + +Number of trials: 1/1 (1 RUNNING) ++---------------------+----------+----------------+--------+------------------+ +| Trial name | status | loc | iter | total time (s) | +| | | | | | +|---------------------+----------+----------------+--------+------------------+ +| PPO_env_82b44_00000 | RUNNING | 127.0.0.1:9718 | 1 | 98.3585 | ++---------------------+----------+----------------+--------+------------------+ ++------------------------+------------------------+------------------------+ +| num_env_steps_sample | num_env_steps_traine | num_episodes_lifetim | +| d_lifetime | d_lifetime | e | +|------------------------+------------------------+------------------------| +| 4000 | 4000 | 4 | ++------------------------+------------------------+------------------------+ +""" +import gymnasium as gym + +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.env.wrappers.atari_wrappers import wrap_atari_for_new_api_stack +from ray.rllib.examples.rl_modules.classes.tiny_atari_cnn_rlm import TinyAtariCNN +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=100, default_timesteps=600000) +parser.set_defaults( + enable_new_api_stack=True, + env="ale_py:ALE/Pong-v5", +) + + +if __name__ == "__main__": + args = parser.parse_args() + + assert ( + args.enable_new_api_stack + ), "Must set --enable-new-api-stack when running this script!" + + register_env( + "env", + lambda cfg: wrap_atari_for_new_api_stack( + gym.make(args.env, **cfg), + dim=42, # <- need images to be "tiny" for our custom model + framestack=4, + ), + ) + + base_config = ( + get_trainable_cls(args.algo) + .get_default_config() + .environment( + env="env", + env_config=dict( + frameskip=1, + full_action_space=False, + repeat_action_probability=0.0, + ), + ) + .rl_module( + # Plug-in our custom RLModule class. + rl_module_spec=RLModuleSpec( + module_class=TinyAtariCNN, + # Feel free to specify your own `model_config` settings below. + # The `model_config` defined here will be available inside your + # custom RLModule class through the `self.model_config` + # property. + model_config={ + "conv_filters": [ + # num filters, kernel wxh, stride wxh, padding type + [16, 4, 2, "same"], + [32, 4, 2, "same"], + [256, 11, 1, "valid"], + ], + }, + ), + ) + ) + + run_rllib_example_script_experiment(base_config, args) diff --git a/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/pretraining_single_agent_training_multi_agent.py b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/pretraining_single_agent_training_multi_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..4792bd6e1d15bb051df3ccd706cc0524186861c2 --- /dev/null +++ b/deepseek/lib/python3.10/site-packages/ray/rllib/examples/rl_modules/pretraining_single_agent_training_multi_agent.py @@ -0,0 +1,149 @@ +"""Example of running a single-agent pre-training followed with a multi-agent training. + +This examples `num_agents` agents each of them with its own `RLModule` that defines its +policy. The first agent is pre-trained using a single-agent PPO algorithm. All agents +are trained together in the main training run using a multi-agent PPO algorithm where +the pre-trained module is used for the first agent. + +The environment is MultiAgentCartPole, in which there are n agents both policies. + +How to run this script +---------------------- +`python [script file name].py --enable-new-api-stack --num-agents=2` + +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)]` + + + +""" + +import gymnasium as gym +from ray.rllib.algorithms.ppo import PPOConfig +from ray.rllib.algorithms.ppo.ppo_catalog import PPOCatalog +from ray.rllib.algorithms.ppo.torch.ppo_torch_rl_module import PPOTorchRLModule +from ray.rllib.core.rl_module.rl_module import RLModuleSpec +from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec +from ray.rllib.examples.envs.classes.multi_agent import MultiAgentCartPole +from ray.rllib.utils.test_utils import ( + add_rllib_example_script_args, + run_rllib_example_script_experiment, +) +from ray.tune import register_env + +# Read in common example script command line arguments. +parser = add_rllib_example_script_args( + # Use less training steps for the main training run. + default_timesteps=50000, + default_reward=200.0, + default_iters=20, +) +# Instead use mroe for the pre-training run. +parser.add_argument( + "--stop-iters-pretraining", + type=int, + default=200, + help="The number of iterations to pre-train.", +) +parser.add_argument( + "--stop-timesteps-pretraining", + type=int, + default=5000000, + help="The number of (environment sampling) timesteps to pre-train.", +) + + +if __name__ == "__main__": + + # Parse the command line arguments. + args = parser.parse_args() + + # Ensure that the user has set the number of agents. + if args.num_agents == 0: + raise ValueError( + "This pre-training example script requires at least 1 agent. " + "Try setting the command line argument `--num-agents` to the " + "number of agents you want to use." + ) + + # Store the user's stopping criteria for the later training run. + stop_iters = args.stop_iters + stop_timesteps = args.stop_timesteps + checkpoint_at_end = args.checkpoint_at_end + num_agents = args.num_agents + # Override these criteria for the pre-training run. + setattr(args, "stop_iters", args.stop_iters_pretraining) + setattr(args, "stop_timesteps", args.stop_timesteps_pretraining) + setattr(args, "checkpoint_at_end", True) + setattr(args, "num_agents", 0) + + # Define out pre-training single-agent algorithm. We will use the same module + # configuration for the pre-training and the training. + config = ( + PPOConfig() + .environment("CartPole-v1") + .rl_module( + # Use a different number of hidden units for the pre-trained module. + model_config={"fcnet_hiddens": [64]}, + ) + ) + + # Run the pre-training. + results = run_rllib_example_script_experiment(config, args) + # Get the checkpoint path. + module_chkpt_path = results.get_best_result().checkpoint.path + + # Create a new MultiRLModule using the pre-trained module for policy 0. + env = gym.make("CartPole-v1") + module_specs = {} + module_class = PPOTorchRLModule + for i in range(args.num_agents): + module_specs[f"policy_{i}"] = RLModuleSpec( + module_class=PPOTorchRLModule, + observation_space=env.observation_space, + action_space=env.action_space, + model_config={"fcnet_hiddens": [32]}, + catalog_class=PPOCatalog, + ) + + # Swap in the pre-trained module for policy 0. + module_specs["policy_0"] = RLModuleSpec( + module_class=PPOTorchRLModule, + observation_space=env.observation_space, + action_space=env.action_space, + model_config={"fcnet_hiddens": [64]}, + catalog_class=PPOCatalog, + # Note, we load here the module directly from the checkpoint. + load_state_path=module_chkpt_path, + ) + multi_rl_module_spec = MultiRLModuleSpec(rl_module_specs=module_specs) + + # Register our environment with tune if we use multiple agents. + register_env( + "multi-agent-carpole-env", + lambda _: MultiAgentCartPole(config={"num_agents": args.num_agents}), + ) + + # Configure the main (multi-agent) training run. + config = ( + PPOConfig() + .environment( + "multi-agent-carpole-env" if args.num_agents > 0 else "CartPole-v1" + ) + .rl_module(rl_module_spec=multi_rl_module_spec) + ) + + # Restore the user's stopping criteria for the training run. + setattr(args, "stop_iters", stop_iters) + setattr(args, "stop_timesteps", stop_timesteps) + setattr(args, "checkpoint_at_end", checkpoint_at_end) + setattr(args, "num_agents", num_agents) + + # Run the main training run. + run_rllib_example_script_experiment(config, args) diff --git a/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/_builder.cpython-310.pyc b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/_builder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ec7f1060a20ec82956a6846e820397f6d34b07a Binary files /dev/null and b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/_builder.cpython-310.pyc differ diff --git a/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/_efficientnet_blocks.cpython-310.pyc b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/_efficientnet_blocks.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97d1cf6011d3d855983c4bda8b50db5733f72771 Binary files /dev/null and b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/_efficientnet_blocks.cpython-310.pyc differ diff --git a/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/_features.cpython-310.pyc b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/_features.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1c3e6bb1c7ffffc190e39522a35f2db6f6a32f8 Binary files /dev/null and b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/_features.cpython-310.pyc differ diff --git a/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/_features_fx.cpython-310.pyc b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/_features_fx.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64a69cf58f1141fc94ea6d70ea5b22cb67a9ee99 Binary files /dev/null and b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/_features_fx.cpython-310.pyc differ diff --git a/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/_manipulate.cpython-310.pyc b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/_manipulate.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f13f672df0468fc105c3c405be6ca01f6c6265f Binary files /dev/null and b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/_manipulate.cpython-310.pyc differ diff --git a/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/byoanet.cpython-310.pyc b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/byoanet.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0af37f51f98ac88cf793fa84dbfcb48fc0ae914f Binary files /dev/null and b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/byoanet.cpython-310.pyc differ diff --git a/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/convmixer.cpython-310.pyc b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/convmixer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b38f28e23a605d513d5677ce35aef50b0787fcf Binary files /dev/null and b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/convmixer.cpython-310.pyc differ diff --git a/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/convnext.cpython-310.pyc b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/convnext.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e109fb40bee4c4cc99c2802d609438114ce00d2 Binary files /dev/null and b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/convnext.cpython-310.pyc differ diff --git a/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/densenet.cpython-310.pyc b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/densenet.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3a1aea54b7aec62c9eef3a3fb4926b484195333 Binary files /dev/null and b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/densenet.cpython-310.pyc differ diff --git a/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/ghostnet.cpython-310.pyc b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/ghostnet.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..892500876b1af2a16b26adeb22ce617bb005f84d Binary files /dev/null and b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/ghostnet.cpython-310.pyc differ diff --git a/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/levit.cpython-310.pyc b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/levit.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b49ffd2b5599b0f75b3e39f61ffe3c1f8dd277d Binary files /dev/null and b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/levit.cpython-310.pyc differ diff --git a/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/repvit.cpython-310.pyc b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/repvit.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd92426ad59b687a5c58cf424b1abe3fd12ac2d2 Binary files /dev/null and b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/repvit.cpython-310.pyc differ diff --git a/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/selecsls.cpython-310.pyc b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/selecsls.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b0d456e2d7544a5726aebffeb57309fc4fd1506 Binary files /dev/null and b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/selecsls.cpython-310.pyc differ diff --git a/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/senet.cpython-310.pyc b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/senet.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba424799a1ba731119f2cd8647253cb60dfa5aae Binary files /dev/null and b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/senet.cpython-310.pyc differ diff --git a/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/sknet.cpython-310.pyc b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/sknet.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bee3f503ffb5ff0ed1c34d98224bb9a2c88d5718 Binary files /dev/null and b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/sknet.cpython-310.pyc differ diff --git a/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/tresnet.cpython-310.pyc b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/tresnet.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89f504af02da84c38b3d58641ed289e7ccf01769 Binary files /dev/null and b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/tresnet.cpython-310.pyc differ diff --git a/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/vision_transformer_relpos.cpython-310.pyc b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/vision_transformer_relpos.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..afd5c91d7f90930e94f04547431c8dd5a40d6087 Binary files /dev/null and b/evalkit_tf433/lib/python3.10/site-packages/timm/models/__pycache__/vision_transformer_relpos.cpython-310.pyc differ diff --git a/evalkit_tf433/lib/python3.10/site-packages/timm/utils/__init__.py b/evalkit_tf433/lib/python3.10/site-packages/timm/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4c6a00cad54b958d64b2c592c5116a2fc497a392 --- /dev/null +++ b/evalkit_tf433/lib/python3.10/site-packages/timm/utils/__init__.py @@ -0,0 +1,15 @@ +from .agc import adaptive_clip_grad +from .checkpoint_saver import CheckpointSaver +from .clip_grad import dispatch_clip_grad +from .cuda import ApexScaler, NativeScaler +from .decay_batch import decay_batch_step, check_batch_size_retry +from .distributed import distribute_bn, reduce_tensor, init_distributed_device,\ + world_info_from_env, is_distributed_env, is_primary +from .jit import set_jit_legacy, set_jit_fuser +from .log import setup_default_logging, FormatterNoInfo +from .metrics import AverageMeter, accuracy +from .misc import natural_key, add_bool_arg, ParseKwargs +from .model import unwrap_model, get_state_dict, freeze, unfreeze, reparameterize_model +from .model_ema import ModelEma, ModelEmaV2, ModelEmaV3 +from .random import random_seed +from .summary import update_summary, get_outdir diff --git a/evalkit_tf433/lib/python3.10/site-packages/timm/utils/checkpoint_saver.py b/evalkit_tf433/lib/python3.10/site-packages/timm/utils/checkpoint_saver.py new file mode 100644 index 0000000000000000000000000000000000000000..6aad74ee52655f68220f799efaffcbccdd0748ad --- /dev/null +++ b/evalkit_tf433/lib/python3.10/site-packages/timm/utils/checkpoint_saver.py @@ -0,0 +1,150 @@ +""" Checkpoint Saver + +Track top-n training checkpoints and maintain recovery checkpoints on specified intervals. + +Hacked together by / Copyright 2020 Ross Wightman +""" + +import glob +import operator +import os +import logging + +import torch + +from .model import unwrap_model, get_state_dict + + +_logger = logging.getLogger(__name__) + + +class CheckpointSaver: + def __init__( + self, + model, + optimizer, + args=None, + model_ema=None, + amp_scaler=None, + checkpoint_prefix='checkpoint', + recovery_prefix='recovery', + checkpoint_dir='', + recovery_dir='', + decreasing=False, + max_history=10, + unwrap_fn=unwrap_model): + + # objects to save state_dicts of + self.model = model + self.optimizer = optimizer + self.args = args + self.model_ema = model_ema + self.amp_scaler = amp_scaler + + # state + self.checkpoint_files = [] # (filename, metric) tuples in order of decreasing betterness + self.best_epoch = None + self.best_metric = None + self.curr_recovery_file = '' + self.last_recovery_file = '' + + # config + self.checkpoint_dir = checkpoint_dir + self.recovery_dir = recovery_dir + self.save_prefix = checkpoint_prefix + self.recovery_prefix = recovery_prefix + self.extension = '.pth.tar' + self.decreasing = decreasing # a lower metric is better if True + self.cmp = operator.lt if decreasing else operator.gt # True if lhs better than rhs + self.max_history = max_history + self.unwrap_fn = unwrap_fn + assert self.max_history >= 1 + + def save_checkpoint(self, epoch, metric=None): + assert epoch >= 0 + tmp_save_path = os.path.join(self.checkpoint_dir, 'tmp' + self.extension) + last_save_path = os.path.join(self.checkpoint_dir, 'last' + self.extension) + self._save(tmp_save_path, epoch, metric) + if os.path.exists(last_save_path): + os.unlink(last_save_path) # required for Windows support. + os.rename(tmp_save_path, last_save_path) + worst_file = self.checkpoint_files[-1] if self.checkpoint_files else None + if (len(self.checkpoint_files) < self.max_history + or metric is None or self.cmp(metric, worst_file[1])): + if len(self.checkpoint_files) >= self.max_history: + self._cleanup_checkpoints(1) + filename = '-'.join([self.save_prefix, str(epoch)]) + self.extension + save_path = os.path.join(self.checkpoint_dir, filename) + os.link(last_save_path, save_path) + self.checkpoint_files.append((save_path, metric)) + self.checkpoint_files = sorted( + self.checkpoint_files, key=lambda x: x[1], + reverse=not self.decreasing) # sort in descending order if a lower metric is not better + + checkpoints_str = "Current checkpoints:\n" + for c in self.checkpoint_files: + checkpoints_str += ' {}\n'.format(c) + _logger.info(checkpoints_str) + + if metric is not None and (self.best_metric is None or self.cmp(metric, self.best_metric)): + self.best_epoch = epoch + self.best_metric = metric + best_save_path = os.path.join(self.checkpoint_dir, 'model_best' + self.extension) + if os.path.exists(best_save_path): + os.unlink(best_save_path) + os.link(last_save_path, best_save_path) + + return (None, None) if self.best_metric is None else (self.best_metric, self.best_epoch) + + def _save(self, save_path, epoch, metric=None): + save_state = { + 'epoch': epoch, + 'arch': type(self.model).__name__.lower(), + 'state_dict': get_state_dict(self.model, self.unwrap_fn), + 'optimizer': self.optimizer.state_dict(), + 'version': 2, # version < 2 increments epoch before save + } + if self.args is not None: + save_state['arch'] = self.args.model + save_state['args'] = self.args + if self.amp_scaler is not None: + save_state[self.amp_scaler.state_dict_key] = self.amp_scaler.state_dict() + if self.model_ema is not None: + save_state['state_dict_ema'] = get_state_dict(self.model_ema, self.unwrap_fn) + if metric is not None: + save_state['metric'] = metric + torch.save(save_state, save_path) + + def _cleanup_checkpoints(self, trim=0): + trim = min(len(self.checkpoint_files), trim) + delete_index = self.max_history - trim + if delete_index < 0 or len(self.checkpoint_files) <= delete_index: + return + to_delete = self.checkpoint_files[delete_index:] + for d in to_delete: + try: + _logger.debug("Cleaning checkpoint: {}".format(d)) + os.remove(d[0]) + except Exception as e: + _logger.error("Exception '{}' while deleting checkpoint".format(e)) + self.checkpoint_files = self.checkpoint_files[:delete_index] + + def save_recovery(self, epoch, batch_idx=0): + assert epoch >= 0 + filename = '-'.join([self.recovery_prefix, str(epoch), str(batch_idx)]) + self.extension + save_path = os.path.join(self.recovery_dir, filename) + self._save(save_path, epoch) + if os.path.exists(self.last_recovery_file): + try: + _logger.debug("Cleaning recovery: {}".format(self.last_recovery_file)) + os.remove(self.last_recovery_file) + except Exception as e: + _logger.error("Exception '{}' while removing {}".format(e, self.last_recovery_file)) + self.last_recovery_file = self.curr_recovery_file + self.curr_recovery_file = save_path + + def find_recovery(self): + recovery_path = os.path.join(self.recovery_dir, self.recovery_prefix) + files = glob.glob(recovery_path + '*' + self.extension) + files = sorted(files) + return files[0] if len(files) else '' diff --git a/evalkit_tf433/lib/python3.10/site-packages/timm/utils/cuda.py b/evalkit_tf433/lib/python3.10/site-packages/timm/utils/cuda.py new file mode 100644 index 0000000000000000000000000000000000000000..de0b881cf9031333df9db5674ee6c55354e81fd7 --- /dev/null +++ b/evalkit_tf433/lib/python3.10/site-packages/timm/utils/cuda.py @@ -0,0 +1,75 @@ +""" CUDA / AMP utils + +Hacked together by / Copyright 2020 Ross Wightman +""" +import torch + +try: + from apex import amp + has_apex = True +except ImportError: + amp = None + has_apex = False + +from .clip_grad import dispatch_clip_grad + + +class ApexScaler: + state_dict_key = "amp" + + def __call__( + self, + loss, + optimizer, + clip_grad=None, + clip_mode='norm', + parameters=None, + create_graph=False, + need_update=True, + ): + with amp.scale_loss(loss, optimizer) as scaled_loss: + scaled_loss.backward(create_graph=create_graph) + if need_update: + if clip_grad is not None: + dispatch_clip_grad(amp.master_params(optimizer), clip_grad, mode=clip_mode) + optimizer.step() + + def state_dict(self): + if 'state_dict' in amp.__dict__: + return amp.state_dict() + + def load_state_dict(self, state_dict): + if 'load_state_dict' in amp.__dict__: + amp.load_state_dict(state_dict) + + +class NativeScaler: + state_dict_key = "amp_scaler" + + def __init__(self): + self._scaler = torch.cuda.amp.GradScaler() + + def __call__( + self, + loss, + optimizer, + clip_grad=None, + clip_mode='norm', + parameters=None, + create_graph=False, + need_update=True, + ): + self._scaler.scale(loss).backward(create_graph=create_graph) + if need_update: + if clip_grad is not None: + assert parameters is not None + self._scaler.unscale_(optimizer) # unscale the gradients of optimizer's assigned params in-place + dispatch_clip_grad(parameters, clip_grad, mode=clip_mode) + self._scaler.step(optimizer) + self._scaler.update() + + def state_dict(self): + return self._scaler.state_dict() + + def load_state_dict(self, state_dict): + self._scaler.load_state_dict(state_dict) diff --git a/evalkit_tf433/lib/python3.10/site-packages/timm/utils/distributed.py b/evalkit_tf433/lib/python3.10/site-packages/timm/utils/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..286e8ba49957c972a6edc08fa7f0d6892de275da --- /dev/null +++ b/evalkit_tf433/lib/python3.10/site-packages/timm/utils/distributed.py @@ -0,0 +1,175 @@ +""" Distributed training/validation utils + +Hacked together by / Copyright 2020 Ross Wightman +""" +import logging +import os +from typing import Optional + +import torch +from torch import distributed as dist + +from .model import unwrap_model + +_logger = logging.getLogger(__name__) + + +def reduce_tensor(tensor, n): + rt = tensor.clone() + dist.all_reduce(rt, op=dist.ReduceOp.SUM) + rt /= n + return rt + + +def distribute_bn(model, world_size, reduce=False): + # ensure every node has the same running bn stats + for bn_name, bn_buf in unwrap_model(model).named_buffers(recurse=True): + if ('running_mean' in bn_name) or ('running_var' in bn_name): + if reduce: + # average bn stats across whole group + torch.distributed.all_reduce(bn_buf, op=dist.ReduceOp.SUM) + bn_buf /= float(world_size) + else: + # broadcast bn stats from rank 0 to whole group + torch.distributed.broadcast(bn_buf, 0) + + +def is_global_primary(args): + return args.rank == 0 + + +def is_local_primary(args): + return args.local_rank == 0 + + +def is_primary(args, local=False): + return is_local_primary(args) if local else is_global_primary(args) + + +def is_distributed_env(): + if 'WORLD_SIZE' in os.environ: + return int(os.environ['WORLD_SIZE']) > 1 + if 'SLURM_NTASKS' in os.environ: + return int(os.environ['SLURM_NTASKS']) > 1 + return False + + +def world_info_from_env(): + local_rank = 0 + for v in ('LOCAL_RANK', 'MPI_LOCALRANKID', 'SLURM_LOCALID', 'OMPI_COMM_WORLD_LOCAL_RANK'): + if v in os.environ: + local_rank = int(os.environ[v]) + break + + global_rank = 0 + for v in ('RANK', 'PMI_RANK', 'SLURM_PROCID', 'OMPI_COMM_WORLD_RANK'): + if v in os.environ: + global_rank = int(os.environ[v]) + break + + world_size = 1 + for v in ('WORLD_SIZE', 'PMI_SIZE', 'SLURM_NTASKS', 'OMPI_COMM_WORLD_SIZE'): + if v in os.environ: + world_size = int(os.environ[v]) + break + + return local_rank, global_rank, world_size + + +def init_distributed_device(args): + # Distributed training = training on more than one GPU. + # Works in both single and multi-node scenarios. + args.distributed = False + args.world_size = 1 + args.rank = 0 # global rank + args.local_rank = 0 + result = init_distributed_device_so( + device=getattr(args, 'device', 'cuda'), + dist_backend=getattr(args, 'dist_backend', None), + dist_url=getattr(args, 'dist_url', None), + ) + args.device = result['device'] + args.world_size = result['world_size'] + args.rank = result['global_rank'] + args.local_rank = result['local_rank'] + args.distributed = result['distributed'] + device = torch.device(args.device) + return device + + +def init_distributed_device_so( + device: str = 'cuda', + dist_backend: Optional[str] = None, + dist_url: Optional[str] = None, +): + # Distributed training = training on more than one GPU. + # Works in both single and multi-node scenarios. + distributed = False + world_size = 1 + global_rank = 0 + local_rank = 0 + if dist_backend is None: + # FIXME sane defaults for other device backends? + dist_backend = 'nccl' if 'cuda' in device else 'gloo' + dist_url = dist_url or 'env://' + + # TBD, support horovod? + # if args.horovod: + # import horovod.torch as hvd + # assert hvd is not None, "Horovod is not installed" + # hvd.init() + # args.local_rank = int(hvd.local_rank()) + # args.rank = hvd.rank() + # args.world_size = hvd.size() + # args.distributed = True + # os.environ['LOCAL_RANK'] = str(args.local_rank) + # os.environ['RANK'] = str(args.rank) + # os.environ['WORLD_SIZE'] = str(args.world_size) + if is_distributed_env(): + if 'SLURM_PROCID' in os.environ: + # DDP via SLURM + local_rank, global_rank, world_size = world_info_from_env() + # SLURM var -> torch.distributed vars in case needed + os.environ['LOCAL_RANK'] = str(local_rank) + os.environ['RANK'] = str(global_rank) + os.environ['WORLD_SIZE'] = str(world_size) + torch.distributed.init_process_group( + backend=dist_backend, + init_method=dist_url, + world_size=world_size, + rank=global_rank, + ) + else: + # DDP via torchrun, torch.distributed.launch + local_rank, _, _ = world_info_from_env() + torch.distributed.init_process_group( + backend=dist_backend, + init_method=dist_url, + ) + world_size = torch.distributed.get_world_size() + global_rank = torch.distributed.get_rank() + distributed = True + + if 'cuda' in device: + assert torch.cuda.is_available(), f'CUDA is not available but {device} was specified.' + + if distributed and device != 'cpu': + device, *device_idx = device.split(':', maxsplit=1) + + # Ignore manually specified device index in distributed mode and + # override with resolved local rank, fewer headaches in most setups. + if device_idx: + _logger.warning(f'device index {device_idx[0]} removed from specified ({device}).') + + device = f'{device}:{local_rank}' + + if device.startswith('cuda:'): + torch.cuda.set_device(device) + + return dict( + device=device, + global_rank=global_rank, + local_rank=local_rank, + world_size=world_size, + distributed=distributed, + ) diff --git a/evalkit_tf433/lib/python3.10/site-packages/timm/utils/model_ema.py b/evalkit_tf433/lib/python3.10/site-packages/timm/utils/model_ema.py new file mode 100644 index 0000000000000000000000000000000000000000..3e4916756dd9115f567bf889fa228bac7afd728d --- /dev/null +++ b/evalkit_tf433/lib/python3.10/site-packages/timm/utils/model_ema.py @@ -0,0 +1,260 @@ +""" Exponential Moving Average (EMA) of model updates + +Hacked together by / Copyright 2020 Ross Wightman +""" +import logging +from collections import OrderedDict +from copy import deepcopy +from typing import Optional + +import torch +import torch.nn as nn + +_logger = logging.getLogger(__name__) + + +class ModelEma: + """ Model Exponential Moving Average (DEPRECATED) + + Keep a moving average of everything in the model state_dict (parameters and buffers). + This version is deprecated, it does not work with scripted models. Will be removed eventually. + + This is intended to allow functionality like + https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage + + A smoothed version of the weights is necessary for some training schemes to perform well. + E.g. Google's hyper-params for training MNASNet, MobileNet-V3, EfficientNet, etc that use + RMSprop with a short 2.4-3 epoch decay period and slow LR decay rate of .96-.99 requires EMA + smoothing of weights to match results. Pay attention to the decay constant you are using + relative to your update count per epoch. + + To keep EMA from using GPU resources, set device='cpu'. This will save a bit of memory but + disable validation of the EMA weights. Validation will have to be done manually in a separate + process, or after the training stops converging. + + This class is sensitive where it is initialized in the sequence of model init, + GPU assignment and distributed training wrappers. + """ + def __init__(self, model, decay=0.9999, device='', resume=''): + # make a copy of the model for accumulating moving average of weights + self.ema = deepcopy(model) + self.ema.eval() + self.decay = decay + self.device = device # perform ema on different device from model if set + if device: + self.ema.to(device=device) + self.ema_has_module = hasattr(self.ema, 'module') + if resume: + self._load_checkpoint(resume) + for p in self.ema.parameters(): + p.requires_grad_(False) + + def _load_checkpoint(self, checkpoint_path): + checkpoint = torch.load(checkpoint_path, map_location='cpu') + assert isinstance(checkpoint, dict) + if 'state_dict_ema' in checkpoint: + new_state_dict = OrderedDict() + for k, v in checkpoint['state_dict_ema'].items(): + # ema model may have been wrapped by DataParallel, and need module prefix + if self.ema_has_module: + name = 'module.' + k if not k.startswith('module') else k + else: + name = k + new_state_dict[name] = v + self.ema.load_state_dict(new_state_dict) + _logger.info("Loaded state_dict_ema") + else: + _logger.warning("Failed to find state_dict_ema, starting from loaded model weights") + + def update(self, model): + # correct a mismatch in state dict keys + needs_module = hasattr(model, 'module') and not self.ema_has_module + with torch.no_grad(): + msd = model.state_dict() + for k, ema_v in self.ema.state_dict().items(): + if needs_module: + k = 'module.' + k + model_v = msd[k].detach() + if self.device: + model_v = model_v.to(device=self.device) + ema_v.copy_(ema_v * self.decay + (1. - self.decay) * model_v) + + +class ModelEmaV2(nn.Module): + """ Model Exponential Moving Average V2 + + Keep a moving average of everything in the model state_dict (parameters and buffers). + V2 of this module is simpler, it does not match params/buffers based on name but simply + iterates in order. It works with torchscript (JIT of full model). + + This is intended to allow functionality like + https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage + + A smoothed version of the weights is necessary for some training schemes to perform well. + E.g. Google's hyper-params for training MNASNet, MobileNet-V3, EfficientNet, etc that use + RMSprop with a short 2.4-3 epoch decay period and slow LR decay rate of .96-.99 requires EMA + smoothing of weights to match results. Pay attention to the decay constant you are using + relative to your update count per epoch. + + To keep EMA from using GPU resources, set device='cpu'. This will save a bit of memory but + disable validation of the EMA weights. Validation will have to be done manually in a separate + process, or after the training stops converging. + + This class is sensitive where it is initialized in the sequence of model init, + GPU assignment and distributed training wrappers. + """ + def __init__(self, model, decay=0.9999, device=None): + super().__init__() + # make a copy of the model for accumulating moving average of weights + self.module = deepcopy(model) + self.module.eval() + self.decay = decay + self.device = device # perform ema on different device from model if set + if self.device is not None: + self.module.to(device=device) + + def _update(self, model, update_fn): + with torch.no_grad(): + for ema_v, model_v in zip(self.module.state_dict().values(), model.state_dict().values()): + if self.device is not None: + model_v = model_v.to(device=self.device) + ema_v.copy_(update_fn(ema_v, model_v)) + + def update(self, model): + self._update(model, update_fn=lambda e, m: self.decay * e + (1. - self.decay) * m) + + def set(self, model): + self._update(model, update_fn=lambda e, m: m) + + def forward(self, *args, **kwargs): + return self.module(*args, **kwargs) + + +class ModelEmaV3(nn.Module): + """ Model Exponential Moving Average V3 + + Keep a moving average of everything in the model state_dict (parameters and buffers). + V3 of this module leverages for_each and in-place operations for faster performance. + + Decay warmup based on code by @crowsonkb, her comments: + If inv_gamma=1 and power=1, implements a simple average. inv_gamma=1, power=2/3 are + good values for models you plan to train for a million or more steps (reaches decay + factor 0.999 at 31.6K steps, 0.9999 at 1M steps), inv_gamma=1, power=3/4 for models + you plan to train for less (reaches decay factor 0.999 at 10K steps, 0.9999 at + 215.4k steps). + + This is intended to allow functionality like + https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage + + To keep EMA from using GPU resources, set device='cpu'. This will save a bit of memory but + disable validation of the EMA weights. Validation will have to be done manually in a separate + process, or after the training stops converging. + + This class is sensitive where it is initialized in the sequence of model init, + GPU assignment and distributed training wrappers. + """ + def __init__( + self, + model, + decay: float = 0.9999, + min_decay: float = 0.0, + update_after_step: int = 0, + use_warmup: bool = False, + warmup_gamma: float = 1.0, + warmup_power: float = 2/3, + device: Optional[torch.device] = None, + foreach: bool = True, + exclude_buffers: bool = False, + ): + super().__init__() + # make a copy of the model for accumulating moving average of weights + self.module = deepcopy(model) + self.module.eval() + self.decay = decay + self.min_decay = min_decay + self.update_after_step = update_after_step + self.use_warmup = use_warmup + self.warmup_gamma = warmup_gamma + self.warmup_power = warmup_power + self.foreach = foreach + self.device = device # perform ema on different device from model if set + self.exclude_buffers = exclude_buffers + if self.device is not None and device != next(model.parameters()).device: + self.foreach = False # cannot use foreach methods with different devices + self.module.to(device=device) + + def get_decay(self, step: Optional[int] = None) -> float: + """ + Compute the decay factor for the exponential moving average. + """ + if step is None: + return self.decay + + step = max(0, step - self.update_after_step - 1) + if step <= 0: + return 0.0 + + if self.use_warmup: + decay = 1 - (1 + step / self.warmup_gamma) ** -self.warmup_power + decay = max(min(decay, self.decay), self.min_decay) + else: + decay = self.decay + + return decay + + @torch.no_grad() + def update(self, model, step: Optional[int] = None): + decay = self.get_decay(step) + if self.exclude_buffers: + self.apply_update_no_buffers_(model, decay) + else: + self.apply_update_(model, decay) + + def apply_update_(self, model, decay: float): + # interpolate parameters and buffers + if self.foreach: + ema_lerp_values = [] + model_lerp_values = [] + for ema_v, model_v in zip(self.module.state_dict().values(), model.state_dict().values()): + if ema_v.is_floating_point(): + ema_lerp_values.append(ema_v) + model_lerp_values.append(model_v) + else: + ema_v.copy_(model_v) + + if hasattr(torch, '_foreach_lerp_'): + torch._foreach_lerp_(ema_lerp_values, model_lerp_values, weight=1. - decay) + else: + torch._foreach_mul_(ema_lerp_values, scalar=decay) + torch._foreach_add_(ema_lerp_values, model_lerp_values, alpha=1. - decay) + else: + for ema_v, model_v in zip(self.module.state_dict().values(), model.state_dict().values()): + if ema_v.is_floating_point(): + ema_v.lerp_(model_v, weight=1. - decay) + else: + ema_v.copy_(model_v) + + def apply_update_no_buffers_(self, model, decay: float): + # interpolate parameters, copy buffers + ema_params = tuple(self.module.parameters()) + model_params = tuple(model.parameters()) + if self.foreach: + if hasattr(torch, '_foreach_lerp_'): + torch._foreach_lerp_(ema_params, model_params, weight=1. - decay) + else: + torch._foreach_mul_(ema_params, scalar=decay) + torch._foreach_add_(ema_params, model_params, alpha=1 - decay) + else: + for ema_p, model_p in zip(ema_params, model_params): + ema_p.lerp_(model_p, weight=1. - decay) + + for ema_b, model_b in zip(self.module.buffers(), model.buffers()): + ema_b.copy_(model_b.to(device=self.device)) + + @torch.no_grad() + def set(self, model): + for ema_v, model_v in zip(self.module.state_dict().values(), model.state_dict().values()): + ema_v.copy_(model_v.to(device=self.device)) + + def forward(self, *args, **kwargs): + return self.module(*args, **kwargs) \ No newline at end of file diff --git a/evalkit_tf433/lib/python3.10/site-packages/timm/utils/onnx.py b/evalkit_tf433/lib/python3.10/site-packages/timm/utils/onnx.py new file mode 100644 index 0000000000000000000000000000000000000000..58cb2d2a13494bba445134f5e51f48ca67ecda3e --- /dev/null +++ b/evalkit_tf433/lib/python3.10/site-packages/timm/utils/onnx.py @@ -0,0 +1,95 @@ +from typing import Optional, Tuple, List + +import torch + + +def onnx_forward(onnx_file, example_input): + import onnxruntime + + sess_options = onnxruntime.SessionOptions() + session = onnxruntime.InferenceSession(onnx_file, sess_options) + input_name = session.get_inputs()[0].name + output = session.run([], {input_name: example_input.numpy()}) + output = output[0] + return output + + +def onnx_export( + model: torch.nn.Module, + output_file: str, + example_input: Optional[torch.Tensor] = None, + training: bool = False, + verbose: bool = False, + check: bool = True, + check_forward: bool = False, + batch_size: int = 64, + input_size: Tuple[int, int, int] = None, + opset: Optional[int] = None, + dynamic_size: bool = False, + aten_fallback: bool = False, + keep_initializers: Optional[bool] = None, + input_names: List[str] = None, + output_names: List[str] = None, +): + import onnx + + if training: + training_mode = torch.onnx.TrainingMode.TRAINING + model.train() + else: + training_mode = torch.onnx.TrainingMode.EVAL + model.eval() + + if example_input is None: + if not input_size: + assert hasattr(model, 'default_cfg') + input_size = model.default_cfg.get('input_size') + example_input = torch.randn((batch_size,) + input_size, requires_grad=training) + + # Run model once before export trace, sets padding for models with Conv2dSameExport. This means + # that the padding for models with Conv2dSameExport (most models with tf_ prefix) is fixed for + # the input img_size specified in this script. + + # Opset >= 11 should allow for dynamic padding, however I cannot get it to work due to + # issues in the tracing of the dynamic padding or errors attempting to export the model after jit + # scripting it (an approach that should work). Perhaps in a future PyTorch or ONNX versions... + original_out = model(example_input) + + input_names = input_names or ["input0"] + output_names = output_names or ["output0"] + + dynamic_axes = {'input0': {0: 'batch'}, 'output0': {0: 'batch'}} + if dynamic_size: + dynamic_axes['input0'][2] = 'height' + dynamic_axes['input0'][3] = 'width' + + if aten_fallback: + export_type = torch.onnx.OperatorExportTypes.ONNX_ATEN_FALLBACK + else: + export_type = torch.onnx.OperatorExportTypes.ONNX + + torch_out = torch.onnx._export( + model, + example_input, + output_file, + training=training_mode, + export_params=True, + verbose=verbose, + input_names=input_names, + output_names=output_names, + keep_initializers_as_inputs=keep_initializers, + dynamic_axes=dynamic_axes, + opset_version=opset, + operator_export_type=export_type + ) + + if check: + onnx_model = onnx.load(output_file) + onnx.checker.check_model(onnx_model, full_check=True) # assuming throw on error + if check_forward and not training: + import numpy as np + onnx_out = onnx_forward(output_file, example_input) + np.testing.assert_almost_equal(torch_out.data.numpy(), onnx_out, decimal=3) + np.testing.assert_almost_equal(original_out.data.numpy(), torch_out.data.numpy(), decimal=5) + + diff --git a/evalkit_tf433/lib/python3.10/site-packages/timm/utils/random.py b/evalkit_tf433/lib/python3.10/site-packages/timm/utils/random.py new file mode 100644 index 0000000000000000000000000000000000000000..a9679983e96a9a6634c0b77aaf7b996e70eff50b --- /dev/null +++ b/evalkit_tf433/lib/python3.10/site-packages/timm/utils/random.py @@ -0,0 +1,9 @@ +import random +import numpy as np +import torch + + +def random_seed(seed=42, rank=0): + torch.manual_seed(seed + rank) + np.random.seed(seed + rank) + random.seed(seed + rank) diff --git a/evalkit_tf433/lib/python3.10/site-packages/timm/utils/summary.py b/evalkit_tf433/lib/python3.10/site-packages/timm/utils/summary.py new file mode 100644 index 0000000000000000000000000000000000000000..eccbb941fef37283f1819180c0d9834459a6ec14 --- /dev/null +++ b/evalkit_tf433/lib/python3.10/site-packages/timm/utils/summary.py @@ -0,0 +1,51 @@ +""" Summary utilities + +Hacked together by / Copyright 2020 Ross Wightman +""" +import csv +import os +from collections import OrderedDict +try: + import wandb +except ImportError: + pass + + +def get_outdir(path, *paths, inc=False): + outdir = os.path.join(path, *paths) + if not os.path.exists(outdir): + os.makedirs(outdir) + elif inc: + count = 1 + outdir_inc = outdir + '-' + str(count) + while os.path.exists(outdir_inc): + count = count + 1 + outdir_inc = outdir + '-' + str(count) + assert count < 100 + outdir = outdir_inc + os.makedirs(outdir) + return outdir + + +def update_summary( + epoch, + train_metrics, + eval_metrics, + filename, + lr=None, + write_header=False, + log_wandb=False, +): + rowd = OrderedDict(epoch=epoch) + rowd.update([('train_' + k, v) for k, v in train_metrics.items()]) + if eval_metrics: + rowd.update([('eval_' + k, v) for k, v in eval_metrics.items()]) + if lr is not None: + rowd['lr'] = lr + if log_wandb: + wandb.log(rowd) + with open(filename, mode='a') as cf: + dw = csv.DictWriter(cf, fieldnames=rowd.keys()) + if write_header: # first iteration (epoch == 1 can't be used) + dw.writeheader() + dw.writerow(rowd)