rlmodule 0.0.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
rlmodule-0.0.5/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 FabricaAI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,34 @@
1
+ Metadata-Version: 2.1
2
+ Name: rlmodule
3
+ Version: 0.0.5
4
+ Summary: Flexible reinforcement learning models instantiators library
5
+ Author: Lopatovsky
6
+ Maintainer: Lopatovsky
7
+ License: MIT License
8
+ Project-URL: Homepage, https://github.com/FabricaAI/rlmodule
9
+ Project-URL: Documentation, https://github.com/FabricaAI/rlmodule
10
+ Project-URL: Discussions, https://github.com/FabricaAI/rlmodule/discussions
11
+ Project-URL: Bug Reports, https://github.com/FabricaAI/rlmodule/issues
12
+ Project-URL: Say Thanks!, https://github.com/lopatovsky
13
+ Project-URL: Source, https://github.com/FabricaAI/rlmodule
14
+ Keywords: reinforcement-learning,machine-learning,reinforcement,machine,learning,rl,rl-models,rl-modules,models,modules
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Intended Audience :: Science/Research
17
+ Classifier: Topic :: Scientific/Engineering
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Operating System :: OS Independent
21
+ Requires-Python: >=3.6
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: gym
25
+ Requires-Dist: gymnasium
26
+ Requires-Dist: torch>=1.9
27
+ Requires-Dist: skrl>=1.2.0
28
+ Provides-Extra: skrl
29
+ Requires-Dist: skrl>=1.2.0; extra == "skrl"
30
+ Provides-Extra: all
31
+ Requires-Dist: skrl>=1.2.0; extra == "all"
32
+
33
+ # rlmodule
34
+ Flexible reinforcement learning models instantiators library
@@ -0,0 +1,2 @@
1
+ # rlmodule
2
+ Flexible reinforcement learning models instantiators library
@@ -0,0 +1,94 @@
1
+ [project]
2
+ name = "rlmodule"
3
+ version = "0.0.5"
4
+ description = "Flexible reinforcement learning models instantiators library"
5
+ readme = "README.md"
6
+ requires-python = ">=3.6"
7
+ license = {text = "MIT License"}
8
+ authors = [
9
+ {name = "Lopatovsky"},
10
+ ]
11
+ maintainers = [
12
+ {name = "Lopatovsky"},
13
+ ]
14
+ keywords = ["reinforcement-learning", "machine-learning", "reinforcement", "machine", "learning", "rl", "rl-models", "rl-modules", "models", "modules"]
15
+ classifiers = [
16
+ "License :: OSI Approved :: MIT License",
17
+ "Intended Audience :: Science/Research",
18
+ "Topic :: Scientific/Engineering",
19
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
20
+ "Programming Language :: Python :: 3",
21
+ "Operating System :: OS Independent",
22
+ ]
23
+ dependencies = [
24
+ "gym",
25
+ "gymnasium",
26
+ "torch>=1.9",
27
+ "skrl>=1.2.0",
28
+ ]
29
+
30
+ [project.optional-dependencies]
31
+
32
+ # TODO(ll) only examples should depend on skrl, not the main code.
33
+ skrl = [
34
+ "skrl>=1.2.0",
35
+ ]
36
+
37
+ all = [
38
+ "skrl>=1.2.0",
39
+ ]
40
+
41
+ # urls
42
+ [project.urls]
43
+ "Homepage" = "https://github.com/FabricaAI/rlmodule"
44
+ "Documentation" = "https://github.com/FabricaAI/rlmodule"
45
+ "Discussions" = "https://github.com/FabricaAI/rlmodule/discussions"
46
+ "Bug Reports" = "https://github.com/FabricaAI/rlmodule/issues"
47
+ "Say Thanks!" = "https://github.com/lopatovsky"
48
+ "Source" = "https://github.com/FabricaAI/rlmodule"
49
+
50
+ [tool.yapf]
51
+ # run: yapf -p -m -i -r <folder>
52
+ based_on_style = "pep8"
53
+ blank_line_before_nested_class_or_def = false
54
+ blank_lines_between_top_level_imports_and_variables = 2
55
+ column_limit = 120
56
+ join_multiple_lines = false
57
+ space_between_ending_comma_and_closing_bracket = false
58
+ spaces_around_power_operator = true
59
+ split_all_top_level_comma_separated_values = true
60
+ split_before_arithmetic_operator = true
61
+ split_before_dict_set_generator = false
62
+ split_before_dot = true
63
+ split_complex_comprehension = true
64
+ coalesce_brackets = true
65
+
66
+
67
+ [tool.codespell]
68
+ # run: codespell <folder>
69
+ skip = "./docs/_build,./docs/source/_static"
70
+ quiet-level = 3
71
+ count = ""
72
+
73
+
74
+ [tool.isort]
75
+ use_parentheses = false
76
+ line_length = 120
77
+ multi_line_output = 3
78
+ lines_after_imports = 2
79
+ known_annotation = ["typing"]
80
+ known_framework = [
81
+ "torch",
82
+ "numpy",
83
+ ]
84
+ sections = [
85
+ "FUTURE",
86
+ "ANNOTATION",
87
+ "STDLIB",
88
+ "THIRDPARTY",
89
+ "FRAMEWORK",
90
+ "FIRSTPARTY",
91
+ "LOCALFOLDER",
92
+ ]
93
+ no_lines_before = "THIRDPARTY"
94
+ skip = ["docs"]
@@ -0,0 +1,3 @@
1
+ # TODO this is not very good way
2
+ from .source.rlmodel import RLModel, SharedRLModel, GaussianLayer, DeterministicLayer # noqa: F401, F403
3
+ from .source.modules import MLP # noqa: F401, F403
File without changes
@@ -0,0 +1,120 @@
1
+ import gymnasium as gym
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+
6
+ from rlmodule import SharedRLModel, GaussianLayer, DeterministicLayer, MLP
7
+
8
+ # import the skrl components to build the RL system
9
+ from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG
10
+
11
+ from skrl.envs.wrappers.torch.gymnasium_envs import GymnasiumWrapper
12
+ #from skrl.envs.wrappers.torch import wrap_env
13
+ from skrl.memories.torch import RandomMemory
14
+ from skrl.resources.preprocessors.torch import RunningStandardScaler
15
+ from skrl.resources.schedulers.torch import KLAdaptiveRL
16
+ from skrl.trainers.torch import SequentialTrainer
17
+ from skrl.utils import set_seed
18
+ from skrl.envs.wrappers.torch.gymnasium_envs import GymnasiumWrapper
19
+
20
+ # todo set seed
21
+ # seed for reproducibility
22
+ set_seed() # e.g. `set_seed(42)` for fixed seed
23
+
24
+ def get_shared_model(env):
25
+ # instantiate the agent's models (function approximators).
26
+ params = {'input_size': env.observation_space.shape[0], 'hidden_units': [64, 64, 64], 'activations': ['relu', 'relu', 'relu']}
27
+ net = MLP(params)
28
+
29
+ model = SharedRLModel(
30
+ observation_space=env.observation_space.shape[0], # TODO not do shape[0] but process box normally
31
+ action_space=env.observation_space.shape[0],
32
+ device=device,
33
+ network=net,
34
+ output_layer={
35
+ 'policy': GaussianLayer(
36
+ input_size=64, # TODO
37
+ output_size=env.action_space.shape[0],
38
+ device=device,
39
+ output_activation=nn.Tanh(),
40
+ clip_actions=False,
41
+ clip_log_std=True,
42
+ min_log_std=-1.2,
43
+ max_log_std=2,
44
+ initial_log_std=0.2,
45
+ ),
46
+ 'value': DeterministicLayer(
47
+ input_size=64,
48
+ output_size=1,
49
+ device=device,
50
+ output_activation=nn.Identity(),
51
+ ),
52
+ },
53
+ ).to(device) # TODO careful about device
54
+
55
+ return {'policy': model, 'value': model}
56
+
57
+
58
+ # load and wrap the gymnasium environment.
59
+ # note: the environment version may change depending on the gymnasium version
60
+ try:
61
+ env = gym.vector.make("Pendulum-v1", num_envs=4, asynchronous=False)
62
+ except (gym.error.DeprecatedEnv, gym.error.VersionNotFound) as e:
63
+ env_id = [spec for spec in gym.envs.registry if spec.startswith("Pendulum-v")][0]
64
+ print("Pendulum-v1 not found. Trying {}".format(env_id))
65
+ env = gym.vector.make(env_id, num_envs=4, asynchronous=False)
66
+
67
+ env = GymnasiumWrapper(env)
68
+
69
+ device = env.device
70
+
71
+
72
+ # instantiate a memory as rollout buffer (any memory can be used for this)
73
+ memory = RandomMemory(memory_size=1024, num_envs=env.num_envs, device=device)
74
+
75
+ models = get_shared_model(env)
76
+
77
+ print(models)
78
+
79
+
80
+ # configure and instantiate the agent (visit its documentation to see all the options)
81
+ # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters
82
+ cfg = PPO_DEFAULT_CONFIG.copy()
83
+ cfg["rollouts"] = 1024 # memory_size
84
+ cfg["learning_epochs"] = 10
85
+ cfg["mini_batches"] = 32
86
+ cfg["discount_factor"] = 0.9
87
+ cfg["lambda"] = 0.95
88
+ cfg["learning_rate"] = 1e-3
89
+ cfg["learning_rate_scheduler"] = KLAdaptiveRL
90
+ cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008}
91
+ cfg["grad_norm_clip"] = 0.5
92
+ cfg["ratio_clip"] = 0.2
93
+ cfg["value_clip"] = 0.2
94
+ cfg["clip_predicted_values"] = False
95
+ cfg["entropy_loss_scale"] = 0.0
96
+ cfg["value_loss_scale"] = 0.5
97
+ cfg["kl_threshold"] = 0
98
+ cfg["state_preprocessor"] = RunningStandardScaler
99
+ cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device}
100
+ cfg["value_preprocessor"] = RunningStandardScaler
101
+ cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device}
102
+ # logging to TensorBoard and write checkpoints (in timesteps)
103
+ cfg["experiment"]["write_interval"] = 500
104
+ cfg["experiment"]["checkpoint_interval"] = 5000
105
+ cfg["experiment"]["directory"] = "runs/torch/Pendulum"
106
+
107
+ agent = PPO(models=models,
108
+ memory=memory,
109
+ cfg=cfg,
110
+ observation_space=env.observation_space,
111
+ action_space=env.action_space,
112
+ device=device)
113
+
114
+
115
+ # configure and instantiate the RL trainer
116
+ cfg_trainer = {"timesteps": 100000, "headless": True}
117
+ trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent])
118
+
119
+ # start training
120
+ trainer.train()
@@ -0,0 +1,123 @@
1
+ import gymnasium as gym
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+
6
+ # import the skrl components to build the RL system
7
+ from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG
8
+
9
+ from skrl.envs.wrappers.torch.gymnasium_envs import GymnasiumWrapper
10
+ # from skrl.envs.wrappers.torch import wrap_env
11
+ from skrl.memories.torch import RandomMemory
12
+ from skrl.models.torch import DeterministicMixin, GaussianMixin, Model
13
+ from skrl.resources.preprocessors.torch import RunningStandardScaler
14
+ from skrl.resources.schedulers.torch import KLAdaptiveRL
15
+ from skrl.trainers.torch import SequentialTrainer
16
+ from skrl.utils import set_seed
17
+
18
+
19
+ # seed for reproducibility
20
+ set_seed() # e.g. `set_seed(42)` for fixed seed
21
+
22
+
23
+ # define models (stochastic and deterministic models) using mixins
24
+ class Policy(GaussianMixin, Model):
25
+ def __init__(self, observation_space, action_space, device, clip_actions=False,
26
+ clip_log_std=True, min_log_std=-20, max_log_std=2, reduction="sum"):
27
+ Model.__init__(self, observation_space, action_space, device)
28
+ GaussianMixin.__init__(self, clip_actions, clip_log_std, min_log_std, max_log_std, reduction)
29
+
30
+ self.net = nn.Sequential(nn.Linear(self.num_observations, 64),
31
+ nn.ReLU(),
32
+ nn.Linear(64, 64),
33
+ nn.ReLU(),
34
+ nn.Linear(64, self.num_actions))
35
+ self.log_std_parameter = nn.Parameter(torch.zeros(self.num_actions))
36
+
37
+ def compute(self, inputs, role):
38
+ # Pendulum-v1 action_space is -2 to 2
39
+ return 2 * torch.tanh(self.net(inputs["states"])), self.log_std_parameter, {}
40
+
41
+ class Value(DeterministicMixin, Model):
42
+ def __init__(self, observation_space, action_space, device, clip_actions=False):
43
+ Model.__init__(self, observation_space, action_space, device)
44
+ DeterministicMixin.__init__(self, clip_actions)
45
+
46
+ self.net = nn.Sequential(nn.Linear(self.num_observations, 64),
47
+ nn.ReLU(),
48
+ nn.Linear(64, 64),
49
+ nn.ReLU(),
50
+ nn.Linear(64, 1))
51
+
52
+ def compute(self, inputs, role):
53
+ return self.net(inputs["states"]), {}
54
+
55
+
56
+ # load and wrap the gymnasium environment.
57
+ # note: the environment version may change depending on the gymnasium version
58
+ try:
59
+ env = gym.vector.make("Pendulum-v1", num_envs=4, asynchronous=False)
60
+ except (gym.error.DeprecatedEnv, gym.error.VersionNotFound) as e:
61
+ env_id = [spec for spec in gym.envs.registry if spec.startswith("Pendulum-v")][0]
62
+ print("Pendulum-v1 not found. Trying {}".format(env_id))
63
+ env = gym.vector.make(env_id, num_envs=4, asynchronous=False)
64
+
65
+ env = GymnasiumWrapper(env)
66
+
67
+ device = env.device
68
+
69
+
70
+ # instantiate a memory as rollout buffer (any memory can be used for this)
71
+ memory = RandomMemory(memory_size=1024, num_envs=env.num_envs, device=device)
72
+
73
+
74
+ # instantiate the agent's models (function approximators).
75
+ # PPO requires 2 models, visit its documentation for more details
76
+ # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#models
77
+ models = {}
78
+ models["policy"] = Policy(env.observation_space, env.action_space, device, clip_actions=True)
79
+ models["value"] = Value(env.observation_space, env.action_space, device)
80
+
81
+ print(models)
82
+
83
+ # configure and instantiate the agent (visit its documentation to see all the options)
84
+ # https://skrl.readthedocs.io/en/latest/api/agents/ppo.html#configuration-and-hyperparameters
85
+ cfg = PPO_DEFAULT_CONFIG.copy()
86
+ cfg["rollouts"] = 1024 # memory_size
87
+ cfg["learning_epochs"] = 10
88
+ cfg["mini_batches"] = 32
89
+ cfg["discount_factor"] = 0.9
90
+ cfg["lambda"] = 0.95
91
+ cfg["learning_rate"] = 1e-3
92
+ cfg["learning_rate_scheduler"] = KLAdaptiveRL
93
+ cfg["learning_rate_scheduler_kwargs"] = {"kl_threshold": 0.008}
94
+ cfg["grad_norm_clip"] = 0.5
95
+ cfg["ratio_clip"] = 0.2
96
+ cfg["value_clip"] = 0.2
97
+ cfg["clip_predicted_values"] = False
98
+ cfg["entropy_loss_scale"] = 0.0
99
+ cfg["value_loss_scale"] = 0.5
100
+ cfg["kl_threshold"] = 0
101
+ cfg["state_preprocessor"] = RunningStandardScaler
102
+ cfg["state_preprocessor_kwargs"] = {"size": env.observation_space, "device": device}
103
+ cfg["value_preprocessor"] = RunningStandardScaler
104
+ cfg["value_preprocessor_kwargs"] = {"size": 1, "device": device}
105
+ # logging to TensorBoard and write checkpoints (in timesteps)
106
+ cfg["experiment"]["write_interval"] = 500
107
+ cfg["experiment"]["checkpoint_interval"] = 5000
108
+ cfg["experiment"]["directory"] = "runs/torch/Pendulum"
109
+
110
+ agent = PPO(models=models,
111
+ memory=memory,
112
+ cfg=cfg,
113
+ observation_space=env.observation_space,
114
+ action_space=env.action_space,
115
+ device=device)
116
+
117
+
118
+ # configure and instantiate the RL trainer
119
+ cfg_trainer = {"timesteps": 100000, "headless": True}
120
+ trainer = SequentialTrainer(cfg=cfg_trainer, env=env, agents=[agent])
121
+
122
+ # start training
123
+ trainer.train()
File without changes