rl4co 0.0.3.dev0__tar.gz → 0.0.3.dev3__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.
- {rl4co-0.0.3.dev0 → rl4co-0.0.3.dev3}/PKG-INFO +12 -10
- {rl4co-0.0.3.dev0 → rl4co-0.0.3.dev3}/README.md +11 -9
- {rl4co-0.0.3.dev0 → rl4co-0.0.3.dev3}/pyproject.toml +1 -1
- rl4co-0.0.3.dev3/rl4co/__init__.py +1 -0
- rl4co-0.0.3.dev3/rl4co/data/__init__.py +0 -0
- rl4co-0.0.3.dev3/rl4co/data/dataset.py +73 -0
- rl4co-0.0.3.dev3/rl4co/data/generate_data.py +336 -0
- rl4co-0.0.3.dev3/rl4co/data/utils.py +23 -0
- rl4co-0.0.3.dev3/rl4co/envs/__init__.py +11 -0
- rl4co-0.0.3.dev3/rl4co/envs/atsp.py +229 -0
- rl4co-0.0.3.dev3/rl4co/envs/base.py +128 -0
- rl4co-0.0.3.dev3/rl4co/envs/cvrp.py +445 -0
- rl4co-0.0.3.dev3/rl4co/envs/dpp.py +403 -0
- rl4co-0.0.3.dev3/rl4co/envs/ffsp.py +379 -0
- rl4co-0.0.3.dev3/rl4co/envs/mdpp.py +336 -0
- rl4co-0.0.3.dev3/rl4co/envs/mtsp.py +354 -0
- rl4co-0.0.3.dev3/rl4co/envs/op.py +304 -0
- rl4co-0.0.3.dev3/rl4co/envs/pctsp.py +318 -0
- rl4co-0.0.3.dev3/rl4co/envs/pdp.py +305 -0
- rl4co-0.0.3.dev3/rl4co/envs/sdvrp.py +251 -0
- rl4co-0.0.3.dev3/rl4co/envs/tsp.py +215 -0
- rl4co-0.0.3.dev3/rl4co/envs/utils.py +46 -0
- rl4co-0.0.3.dev3/rl4co/models/__init__.py +9 -0
- rl4co-0.0.3.dev3/rl4co/models/nn/attention.py +278 -0
- rl4co-0.0.3.dev3/rl4co/models/nn/env_context.py +171 -0
- rl4co-0.0.3.dev3/rl4co/models/nn/env_embedding.py +295 -0
- rl4co-0.0.3.dev3/rl4co/models/nn/flash_attention.py +709 -0
- rl4co-0.0.3.dev3/rl4co/models/nn/graph/gat.py +89 -0
- rl4co-0.0.3.dev3/rl4co/models/nn/graph/gcn.py +93 -0
- rl4co-0.0.3.dev3/rl4co/models/nn/graph/mpnn.py +172 -0
- rl4co-0.0.3.dev3/rl4co/models/nn/mlp.py +63 -0
- rl4co-0.0.3.dev3/rl4co/models/nn/ops.py +37 -0
- rl4co-0.0.3.dev3/rl4co/models/nn/utils.py +55 -0
- rl4co-0.0.3.dev3/rl4co/models/rl/ppo/model.py +141 -0
- rl4co-0.0.3.dev3/rl4co/models/rl/ppo/task.py +39 -0
- rl4co-0.0.3.dev3/rl4co/models/rl/reinforce/base.py +71 -0
- rl4co-0.0.3.dev3/rl4co/models/rl/reinforce/baselines.py +205 -0
- rl4co-0.0.3.dev3/rl4co/models/rl/reinforce/critic.py +60 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/am/__init__.py +2 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/am/decoder.py +175 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/am/model.py +25 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/am/policy.py +101 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/amppo/decoder.py +60 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/amppo/model.py +19 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/amppo/policy.py +119 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/ham/__init__.py +2 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/ham/attention.py +487 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/ham/encoder.py +66 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/ham/model.py +28 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/ham/policy.py +91 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/mdam/__init__.py +1 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/mdam/decoder.py +318 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/mdam/encoder.py +264 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/mdam/model.py +24 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/mdam/policy.py +121 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/pomo/__init__.py +2 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/pomo/augmentations.py +49 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/pomo/decoder.py +163 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/pomo/model.py +125 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/pomo/policy.py +95 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/ptrnet/__init__.py +2 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/ptrnet/critic.py +58 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/ptrnet/decoder.py +181 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/ptrnet/encoder.py +29 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/ptrnet/model.py +25 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/ptrnet/policy.py +108 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/symnco/__init__.py +2 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/symnco/augmentations.py +66 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/symnco/decoder.py +184 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/symnco/losses.py +39 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/symnco/model.py +139 -0
- rl4co-0.0.3.dev3/rl4co/models/zoo/symnco/policy.py +107 -0
- rl4co-0.0.3.dev3/rl4co/tasks/eval.py +417 -0
- rl4co-0.0.3.dev3/rl4co/tasks/rl4co.py +212 -0
- rl4co-0.0.3.dev3/rl4co/utils/__init__.py +5 -0
- rl4co-0.0.3.dev3/rl4co/utils/callbacks/speed_monitor.py +123 -0
- rl4co-0.0.3.dev3/rl4co/utils/download/constants.py +1 -0
- rl4co-0.0.3.dev3/rl4co/utils/download/downloader.py +283 -0
- rl4co-0.0.3.dev3/rl4co/utils/download/gdrive.py +143 -0
- rl4co-0.0.3.dev3/rl4co/utils/download/s3.py +120 -0
- rl4co-0.0.3.dev3/rl4co/utils/helpers.py +90 -0
- rl4co-0.0.3.dev3/rl4co/utils/instantiators.py +51 -0
- rl4co-0.0.3.dev3/rl4co/utils/lightning.py +137 -0
- rl4co-0.0.3.dev3/rl4co/utils/logging_utils.py +49 -0
- rl4co-0.0.3.dev3/rl4co/utils/ops.py +107 -0
- rl4co-0.0.3.dev3/rl4co/utils/param_grouping.py +138 -0
- rl4co-0.0.3.dev3/rl4co/utils/pylogger.py +25 -0
- rl4co-0.0.3.dev3/rl4co/utils/rich_utils.py +97 -0
- rl4co-0.0.3.dev3/rl4co/utils/test_utils.py +42 -0
- rl4co-0.0.3.dev3/rl4co/utils/transfer.py +39 -0
- rl4co-0.0.3.dev3/rl4co/utils/utils.py +210 -0
- {rl4co-0.0.3.dev0 → rl4co-0.0.3.dev3}/rl4co.egg-info/PKG-INFO +12 -10
- rl4co-0.0.3.dev3/rl4co.egg-info/SOURCES.txt +99 -0
- rl4co-0.0.3.dev0/rl4co/__init__.py +0 -1
- rl4co-0.0.3.dev0/rl4co.egg-info/SOURCES.txt +0 -12
- {rl4co-0.0.3.dev0 → rl4co-0.0.3.dev3}/LICENSE +0 -0
- {rl4co-0.0.3.dev0 → rl4co-0.0.3.dev3}/rl4co.egg-info/dependency_links.txt +0 -0
- {rl4co-0.0.3.dev0 → rl4co-0.0.3.dev3}/rl4co.egg-info/requires.txt +0 -0
- {rl4co-0.0.3.dev0 → rl4co-0.0.3.dev3}/rl4co.egg-info/top_level.txt +0 -0
- {rl4co-0.0.3.dev0 → rl4co-0.0.3.dev3}/setup.cfg +0 -0
- {rl4co-0.0.3.dev0 → rl4co-0.0.3.dev3}/tests/test_envs.py +0 -0
- {rl4co-0.0.3.dev0 → rl4co-0.0.3.dev3}/tests/test_models.py +0 -0
- {rl4co-0.0.3.dev0 → rl4co-0.0.3.dev3}/tests/test_ops.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: rl4co
|
|
3
|
-
Version: 0.0.3.
|
|
3
|
+
Version: 0.0.3.dev3
|
|
4
4
|
Summary: RL4CO: an Extensive Reinforcement Learning for Combinatorial Optimization Benchmark
|
|
5
5
|
Author-email: Federico Berto <berto.federico2@gmail.com>, Chuanbo Hua <cbhua@kaist.ac.kr>, Junyoung Park <junyoungpark.ml@gmail.com>
|
|
6
6
|
License: Apache License
|
|
@@ -224,14 +224,15 @@ License-File: LICENSE
|
|
|
224
224
|
<div align="center">
|
|
225
225
|
|
|
226
226
|
# RL4CO
|
|
227
|
-
|
|
228
|
-
An extensive Reinforcement Learning (RL) for Combinatorial Optimization (CO) benchmark. Our goal is to provide a unified framework for RL-based CO algorithms, and to facilitate reproducible research in this field, decoupling the science from the engineering.
|
|
229
|
-
|
|
227
|
+
|
|
228
|
+
An extensive Reinforcement Learning (RL) for Combinatorial Optimization (CO) benchmark. Our goal is to provide a unified framework for RL-based CO algorithms, and to facilitate reproducible research in this field, decoupling the science from the engineering.
|
|
229
|
+
|
|
230
230
|
<a href="https://pytorch.org/get-started/locally/"><img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-ee4c2c?logo=pytorch&logoColor=white"></a>
|
|
231
231
|
<a href="https://pytorchlightning.ai/"><img alt="Lightning" src="https://img.shields.io/badge/-Lightning-792ee5?logo=pytorchlightning&logoColor=white"></a>
|
|
232
232
|
<a href="https://github.com/pytorch/rl"><img alt="base: TorchRL" src="https://img.shields.io/badge/base-TorchRL-red">
|
|
233
233
|
<a href="https://hydra.cc/"><img alt="config: Hydra" src="https://img.shields.io/badge/config-Hydra-89b8cd"></a> [](https://github.com/psf/black)
|
|
234
|
-

|
|
234
|
+
[](https://pypi.org/project/rl4co)
|
|
235
|
+
[](https://github.com/kaist-silab/rl4co/actions/workflows/tests.yml)
|
|
235
236
|
<!--  -->
|
|
236
237
|
|
|
237
238
|
</div>
|
|
@@ -247,6 +248,7 @@ RL4CO is built upon:
|
|
|
247
248
|
|
|
248
249
|
|
|
249
250
|
## Getting started
|
|
251
|
+
<a href="https://colab.research.google.com/github/kaist-silab/rl4co/blob/main/notebooks/1-quickstart.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a>
|
|
250
252
|
|
|
251
253
|
RL4CO is now available for installation on `pip`!
|
|
252
254
|
```bash
|
|
@@ -283,7 +285,7 @@ To get started, we recommend checking out our [quickstart notebook](notebooks/1-
|
|
|
283
285
|
|
|
284
286
|
Train model with default configuration (AM on TSP environment):
|
|
285
287
|
```bash
|
|
286
|
-
python run.py
|
|
288
|
+
python run.py
|
|
287
289
|
```
|
|
288
290
|
|
|
289
291
|
|
|
@@ -293,14 +295,14 @@ python run.py
|
|
|
293
295
|
|
|
294
296
|
Train model with chosen experiment configuration from [configs/experiment/](configs/experiment/) (e.g. tsp/am, and environment with 42 cities)
|
|
295
297
|
```bash
|
|
296
|
-
python run.py experiment=tsp/am env.num_loc=42
|
|
298
|
+
python run.py experiment=tsp/am env.num_loc=42
|
|
297
299
|
```
|
|
298
300
|
</details>
|
|
299
301
|
|
|
300
302
|
|
|
301
303
|
<details>
|
|
302
304
|
<summary>Disable logging</summary>
|
|
303
|
-
|
|
305
|
+
|
|
304
306
|
```bash
|
|
305
307
|
python run.py experiment=test/am logger=none '~callbacks.learning_rate_monitor'
|
|
306
308
|
```
|
|
@@ -333,7 +335,7 @@ from rl4co.tasks.rl4co import RL4COLitModule
|
|
|
333
335
|
config = DictConfig(
|
|
334
336
|
{"data": {
|
|
335
337
|
"train_size": 100000,
|
|
336
|
-
"val_size": 10000,
|
|
338
|
+
"val_size": 10000,
|
|
337
339
|
"batch_size": 512,
|
|
338
340
|
},
|
|
339
341
|
"optimizer": {"lr": 1e-4}}
|
|
@@ -368,7 +370,7 @@ pytest tests
|
|
|
368
370
|
```
|
|
369
371
|
|
|
370
372
|
## Contributing
|
|
371
|
-
Have a suggestion, request, or found a bug? Feel free to [open an issue](https://github.com/kaist-silab/rl4co/issues) or [submit a pull request](https://github.com/kaist-silab/rl4co/pulls). We welcome contributions to RL4CO!
|
|
373
|
+
Have a suggestion, request, or found a bug? Feel free to [open an issue](https://github.com/kaist-silab/rl4co/issues) or [submit a pull request](https://github.com/kaist-silab/rl4co/pulls). We welcome contributions to RL4CO!
|
|
372
374
|
|
|
373
375
|
### Contributors
|
|
374
376
|
<a href="https://github.com/kaist-silab/rl4co/graphs/contributors">
|
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
<div align="center">
|
|
2
2
|
|
|
3
3
|
# RL4CO
|
|
4
|
-
|
|
5
|
-
An extensive Reinforcement Learning (RL) for Combinatorial Optimization (CO) benchmark. Our goal is to provide a unified framework for RL-based CO algorithms, and to facilitate reproducible research in this field, decoupling the science from the engineering.
|
|
6
|
-
|
|
4
|
+
|
|
5
|
+
An extensive Reinforcement Learning (RL) for Combinatorial Optimization (CO) benchmark. Our goal is to provide a unified framework for RL-based CO algorithms, and to facilitate reproducible research in this field, decoupling the science from the engineering.
|
|
6
|
+
|
|
7
7
|
<a href="https://pytorch.org/get-started/locally/"><img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-ee4c2c?logo=pytorch&logoColor=white"></a>
|
|
8
8
|
<a href="https://pytorchlightning.ai/"><img alt="Lightning" src="https://img.shields.io/badge/-Lightning-792ee5?logo=pytorchlightning&logoColor=white"></a>
|
|
9
9
|
<a href="https://github.com/pytorch/rl"><img alt="base: TorchRL" src="https://img.shields.io/badge/base-TorchRL-red">
|
|
10
10
|
<a href="https://hydra.cc/"><img alt="config: Hydra" src="https://img.shields.io/badge/config-Hydra-89b8cd"></a> [](https://github.com/psf/black)
|
|
11
|
-

|
|
11
|
+
[](https://pypi.org/project/rl4co)
|
|
12
|
+
[](https://github.com/kaist-silab/rl4co/actions/workflows/tests.yml)
|
|
12
13
|
<!--  -->
|
|
13
14
|
|
|
14
15
|
</div>
|
|
@@ -24,6 +25,7 @@ RL4CO is built upon:
|
|
|
24
25
|
|
|
25
26
|
|
|
26
27
|
## Getting started
|
|
28
|
+
<a href="https://colab.research.google.com/github/kaist-silab/rl4co/blob/main/notebooks/1-quickstart.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a>
|
|
27
29
|
|
|
28
30
|
RL4CO is now available for installation on `pip`!
|
|
29
31
|
```bash
|
|
@@ -60,7 +62,7 @@ To get started, we recommend checking out our [quickstart notebook](notebooks/1-
|
|
|
60
62
|
|
|
61
63
|
Train model with default configuration (AM on TSP environment):
|
|
62
64
|
```bash
|
|
63
|
-
python run.py
|
|
65
|
+
python run.py
|
|
64
66
|
```
|
|
65
67
|
|
|
66
68
|
|
|
@@ -70,14 +72,14 @@ python run.py
|
|
|
70
72
|
|
|
71
73
|
Train model with chosen experiment configuration from [configs/experiment/](configs/experiment/) (e.g. tsp/am, and environment with 42 cities)
|
|
72
74
|
```bash
|
|
73
|
-
python run.py experiment=tsp/am env.num_loc=42
|
|
75
|
+
python run.py experiment=tsp/am env.num_loc=42
|
|
74
76
|
```
|
|
75
77
|
</details>
|
|
76
78
|
|
|
77
79
|
|
|
78
80
|
<details>
|
|
79
81
|
<summary>Disable logging</summary>
|
|
80
|
-
|
|
82
|
+
|
|
81
83
|
```bash
|
|
82
84
|
python run.py experiment=test/am logger=none '~callbacks.learning_rate_monitor'
|
|
83
85
|
```
|
|
@@ -110,7 +112,7 @@ from rl4co.tasks.rl4co import RL4COLitModule
|
|
|
110
112
|
config = DictConfig(
|
|
111
113
|
{"data": {
|
|
112
114
|
"train_size": 100000,
|
|
113
|
-
"val_size": 10000,
|
|
115
|
+
"val_size": 10000,
|
|
114
116
|
"batch_size": 512,
|
|
115
117
|
},
|
|
116
118
|
"optimizer": {"lr": 1e-4}}
|
|
@@ -145,7 +147,7 @@ pytest tests
|
|
|
145
147
|
```
|
|
146
148
|
|
|
147
149
|
## Contributing
|
|
148
|
-
Have a suggestion, request, or found a bug? Feel free to [open an issue](https://github.com/kaist-silab/rl4co/issues) or [submit a pull request](https://github.com/kaist-silab/rl4co/pulls). We welcome contributions to RL4CO!
|
|
150
|
+
Have a suggestion, request, or found a bug? Feel free to [open an issue](https://github.com/kaist-silab/rl4co/issues) or [submit a pull request](https://github.com/kaist-silab/rl4co/pulls). We welcome contributions to RL4CO!
|
|
149
151
|
|
|
150
152
|
### Contributors
|
|
151
153
|
<a href="https://github.com/kaist-silab/rl4co/graphs/contributors">
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.0.3.dev3"
|
|
File without changes
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
import torch
|
|
4
|
+
|
|
5
|
+
from tensordict.tensordict import TensorDict
|
|
6
|
+
from torch.utils.data import Dataset
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class TensorDictDataset(Dataset):
|
|
10
|
+
"""Dataset compatible with TensorDicts
|
|
11
|
+
For some reason, it is better to "disassemble" the TensorDict into a list of dicts
|
|
12
|
+
We use a custom collate function to reassemble the TensorDicts
|
|
13
|
+
NOTE: may want to make an issue on TorchRL to ask best TensorDict practices
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
def __init__(self, data):
|
|
17
|
+
if isinstance(data, TensorDict):
|
|
18
|
+
self.data = [
|
|
19
|
+
{key: value[i] for key, value in data.items()}
|
|
20
|
+
for i in range(data.shape[0])
|
|
21
|
+
]
|
|
22
|
+
else:
|
|
23
|
+
self.data = [d for d in data]
|
|
24
|
+
|
|
25
|
+
def __len__(self):
|
|
26
|
+
return len(self.data)
|
|
27
|
+
|
|
28
|
+
def __getitem__(self, idx):
|
|
29
|
+
return self.data[idx]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class ExtraKeyDataset(Dataset):
|
|
33
|
+
"""Dataset that includes an extra key to add to the data dict
|
|
34
|
+
This is useful for adding a REINFORCE baseline reward to the data dict
|
|
35
|
+
We had extra_ to identify the key as an extra key
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
def __init__(self, dataset, extra):
|
|
39
|
+
self.data = dataset.data
|
|
40
|
+
self.extra = extra
|
|
41
|
+
assert len(self.data) == len(self.extra), "Data and extra must be same length"
|
|
42
|
+
|
|
43
|
+
def __len__(self):
|
|
44
|
+
return len(self.data)
|
|
45
|
+
|
|
46
|
+
def __getitem__(self, idx):
|
|
47
|
+
data = self.data[idx]
|
|
48
|
+
data["extra"] = self.extra[idx]
|
|
49
|
+
return data
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def tensordict_collate_fn(batch):
|
|
53
|
+
"""Collate function compatible with TensorDicts
|
|
54
|
+
Reassemble the list of dicts into a TensorDict; seems to be way more efficient than using a TensorDictDataset
|
|
55
|
+
https://github.com/pytorch-labs/tensordict/issues/374
|
|
56
|
+
"""
|
|
57
|
+
if isinstance(batch[0], TensorDict):
|
|
58
|
+
return torch.stack(batch)
|
|
59
|
+
return TensorDict(
|
|
60
|
+
{key: torch.stack([b[key] for b in batch]) for key in batch[0].keys()},
|
|
61
|
+
batch_size=len(batch),
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class TensorDictCollate:
|
|
66
|
+
def __init__(self) -> None:
|
|
67
|
+
print(
|
|
68
|
+
"Warning: TensorDictCollateFn is deprecated. Use tensordict_collate_fn instead."
|
|
69
|
+
)
|
|
70
|
+
pass
|
|
71
|
+
|
|
72
|
+
def __call__(self, *args: Any, **kwds: Any) -> Any:
|
|
73
|
+
return tensordict_collate_fn(*args, **kwds)
|
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import logging
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
from rl4co.data.utils import check_extension
|
|
9
|
+
from rl4co.utils.pylogger import get_pylogger
|
|
10
|
+
|
|
11
|
+
log = get_pylogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def generate_env_data(env_type, *args, **kwargs):
|
|
15
|
+
"""Generate data for a given environment type in the form of a dictionary"""
|
|
16
|
+
try:
|
|
17
|
+
# breakpoint()
|
|
18
|
+
# remove all None values from args
|
|
19
|
+
args = [arg for arg in args if arg is not None]
|
|
20
|
+
|
|
21
|
+
return getattr(sys.modules[__name__], f"generate_{env_type}_data")(
|
|
22
|
+
*args, **kwargs
|
|
23
|
+
)
|
|
24
|
+
except AttributeError:
|
|
25
|
+
raise NotImplementedError(f"Environment type {env_type} not implemented")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def generate_tsp_data(dataset_size, tsp_size):
|
|
29
|
+
return {
|
|
30
|
+
"locs": np.random.uniform(size=(dataset_size, tsp_size, 2)).astype(np.float32)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def generate_vrp_data(dataset_size, vrp_size, capacities=None):
|
|
35
|
+
# From Kool et al. 2019, Hottung et al. 2022, Kim et al. 2023
|
|
36
|
+
CAPACITIES = {
|
|
37
|
+
10: 20.0,
|
|
38
|
+
15: 25.0,
|
|
39
|
+
20: 30.0,
|
|
40
|
+
30: 33.0,
|
|
41
|
+
40: 37.0,
|
|
42
|
+
50: 40.0,
|
|
43
|
+
60: 43.0,
|
|
44
|
+
75: 45.0,
|
|
45
|
+
100: 50.0,
|
|
46
|
+
125: 55.0,
|
|
47
|
+
150: 60.0,
|
|
48
|
+
200: 70.0,
|
|
49
|
+
500: 100.0,
|
|
50
|
+
1000: 150.0,
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
# If capacities are provided, replace keys in CAPACITIES with provided values if they exist
|
|
54
|
+
if capacities is not None:
|
|
55
|
+
for k, v in capacities.items():
|
|
56
|
+
if k in CAPACITIES:
|
|
57
|
+
print(f"Replacing capacity for {k} with {v}")
|
|
58
|
+
CAPACITIES[k] = v
|
|
59
|
+
|
|
60
|
+
return {
|
|
61
|
+
"depot": np.random.uniform(size=(dataset_size, 2)).astype(
|
|
62
|
+
np.float32
|
|
63
|
+
), # Depot location
|
|
64
|
+
"locs": np.random.uniform(size=(dataset_size, vrp_size, 2)).astype(
|
|
65
|
+
np.float32
|
|
66
|
+
), # Node locations
|
|
67
|
+
"demand": np.random.randint(1, 10, size=(dataset_size, vrp_size)).astype(
|
|
68
|
+
np.float32
|
|
69
|
+
), # Demand, uniform integer 1 ... 9
|
|
70
|
+
"capacity": np.full(dataset_size, CAPACITIES[vrp_size]).astype(np.float32),
|
|
71
|
+
} # Capacity, same for whole dataset
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def generate_op_data(dataset_size, op_size, prize_type="const"):
|
|
75
|
+
depot = np.random.uniform(size=(dataset_size, 2))
|
|
76
|
+
loc = np.random.uniform(size=(dataset_size, op_size, 2))
|
|
77
|
+
|
|
78
|
+
# Methods taken from Fischetti et al. 1998
|
|
79
|
+
if prize_type == "const":
|
|
80
|
+
prize = np.ones((dataset_size, op_size))
|
|
81
|
+
elif prize_type == "unif":
|
|
82
|
+
prize = (1 + np.random.randint(0, 100, size=(dataset_size, op_size))) / 100.0
|
|
83
|
+
else: # Based on distance to depot
|
|
84
|
+
assert prize_type == "dist"
|
|
85
|
+
prize_ = np.linalg.norm(depot[:, None, :] - loc, axis=-1)
|
|
86
|
+
prize = (
|
|
87
|
+
1 + (prize_ / prize_.max(axis=-1, keepdims=True) * 99).astype(int)
|
|
88
|
+
) / 100.0
|
|
89
|
+
|
|
90
|
+
# Max length is approximately half of optimal TSP tour, such that half (a bit more) of the nodes can be visited
|
|
91
|
+
# which is maximally difficult as this has the largest number of possibilities
|
|
92
|
+
MAX_LENGTHS = {20: 2.0, 50: 3.0, 100: 4.0}
|
|
93
|
+
|
|
94
|
+
return {
|
|
95
|
+
"depot": depot.astype(np.float32),
|
|
96
|
+
"locs": loc.astype(np.float32),
|
|
97
|
+
"prize": prize.astype(np.float32),
|
|
98
|
+
"max_length": np.full(dataset_size, MAX_LENGTHS[op_size]).astype(np.float32),
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def generate_pctsp_data(dataset_size, pctsp_size, penalty_factor=3):
|
|
103
|
+
depot = np.random.uniform(size=(dataset_size, 2))
|
|
104
|
+
loc = np.random.uniform(size=(dataset_size, pctsp_size, 2))
|
|
105
|
+
|
|
106
|
+
# For the penalty to make sense it should be not too large (in which case all nodes will be visited) nor too small
|
|
107
|
+
# so we want the objective term to be approximately equal to the length of the tour, which we estimate with half
|
|
108
|
+
# of the nodes by half of the tour length (which is very rough but similar to op)
|
|
109
|
+
# This means that the sum of penalties for all nodes will be approximately equal to the tour length (on average)
|
|
110
|
+
# The expected total (uniform) penalty of half of the nodes (since approx half will be visited by the constraint)
|
|
111
|
+
# is (n / 2) / 2 = n / 4 so divide by this means multiply by 4 / n,
|
|
112
|
+
# However instead of 4 we use penalty_factor (3 works well) so we can make them larger or smaller
|
|
113
|
+
MAX_LENGTHS = {20: 2.0, 50: 3.0, 100: 4.0}
|
|
114
|
+
penalty_max = MAX_LENGTHS[pctsp_size] * (penalty_factor) / float(pctsp_size)
|
|
115
|
+
penalty = np.random.uniform(size=(dataset_size, pctsp_size)) * penalty_max
|
|
116
|
+
|
|
117
|
+
# Take uniform prizes
|
|
118
|
+
# Now expectation is 0.5 so expected total prize is n / 2, we want to force to visit approximately half of the nodes
|
|
119
|
+
# so the constraint will be that total prize >= (n / 2) / 2 = n / 4
|
|
120
|
+
# equivalently, we divide all prizes by n / 4 and the total prize should be >= 1
|
|
121
|
+
deterministic_prize = (
|
|
122
|
+
np.random.uniform(size=(dataset_size, pctsp_size)) * 4 / float(pctsp_size)
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
# In the deterministic setting, the stochastic_prize is not used and the deterministic prize is known
|
|
126
|
+
# In the stochastic setting, the deterministic prize is the expected prize and is known up front but the
|
|
127
|
+
# stochastic prize is only revealed once the node is visited
|
|
128
|
+
# Stochastic prize is between (0, 2 * expected_prize) such that E(stochastic prize) = E(deterministic_prize)
|
|
129
|
+
stochastic_prize = (
|
|
130
|
+
np.random.uniform(size=(dataset_size, pctsp_size)) * deterministic_prize * 2
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
return {
|
|
134
|
+
"locs": loc.astype(np.float32),
|
|
135
|
+
"depot": depot.astype(np.float32),
|
|
136
|
+
"penalty": penalty.astype(np.float32),
|
|
137
|
+
"deterministic_prize": deterministic_prize.astype(np.float32),
|
|
138
|
+
"stochastic_prize": stochastic_prize.astype(np.float32),
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def generate_mdpp_data(
|
|
143
|
+
dataset_size,
|
|
144
|
+
size=10,
|
|
145
|
+
num_probes_min=2,
|
|
146
|
+
num_probes_max=5,
|
|
147
|
+
num_keepout_min=1,
|
|
148
|
+
num_keepout_max=50,
|
|
149
|
+
lock_size=True,
|
|
150
|
+
):
|
|
151
|
+
"""Generate data for the nDPP problem.
|
|
152
|
+
If `lock_size` is True, then the size if fixed and we skip the `size` argument if it is not 10.
|
|
153
|
+
This is because the RL environment is based on a real-world PCB (parametrized with data)
|
|
154
|
+
"""
|
|
155
|
+
if lock_size and size != 10:
|
|
156
|
+
# log.info("Locking size to 10, skipping generate_mdpp_data with size {}".format(size))
|
|
157
|
+
return None
|
|
158
|
+
|
|
159
|
+
bs = dataset_size # bs = batch_size to generate data in batch
|
|
160
|
+
m = n = size
|
|
161
|
+
if isinstance(bs, int):
|
|
162
|
+
bs = [bs]
|
|
163
|
+
|
|
164
|
+
locs = np.stack(np.meshgrid(np.arange(m), np.arange(n)), axis=-1).reshape(-1, 2)
|
|
165
|
+
locs = locs / np.array([m, n], dtype=np.float32)
|
|
166
|
+
locs = np.expand_dims(locs, axis=0)
|
|
167
|
+
locs = np.repeat(locs, bs[0], axis=0)
|
|
168
|
+
|
|
169
|
+
available = np.ones((bs[0], m * n), dtype=bool)
|
|
170
|
+
|
|
171
|
+
probe = np.random.randint(0, high=m * n, size=(bs[0], 1))
|
|
172
|
+
np.put_along_axis(available, probe, False, axis=1)
|
|
173
|
+
|
|
174
|
+
num_probe = np.random.randint(num_probes_min, num_probes_max + 1, size=(bs[0], 1))
|
|
175
|
+
probes = np.zeros((bs[0], m * n), dtype=bool)
|
|
176
|
+
for i in range(bs[0]):
|
|
177
|
+
p = np.random.choice(m * n, num_probe[i], replace=False)
|
|
178
|
+
np.put_along_axis(available[i], p, False, axis=0)
|
|
179
|
+
np.put_along_axis(probes[i], p, True, axis=0)
|
|
180
|
+
|
|
181
|
+
num_keepout = np.random.randint(num_keepout_min, num_keepout_max + 1, size=(bs[0], 1))
|
|
182
|
+
for i in range(bs[0]):
|
|
183
|
+
k = np.random.choice(m * n, num_keepout[i], replace=False)
|
|
184
|
+
np.put_along_axis(available[i], k, False, axis=0)
|
|
185
|
+
|
|
186
|
+
return {
|
|
187
|
+
"locs": locs.astype(np.float32),
|
|
188
|
+
"probe": probes.astype(bool),
|
|
189
|
+
"action_mask": available.astype(bool),
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def generate_dataset(
|
|
194
|
+
filename=None,
|
|
195
|
+
data_dir="data",
|
|
196
|
+
name=None,
|
|
197
|
+
problem="all",
|
|
198
|
+
data_distribution="all",
|
|
199
|
+
dataset_size=10000,
|
|
200
|
+
graph_sizes=[20, 50, 100],
|
|
201
|
+
overwrite=False,
|
|
202
|
+
seed=1234,
|
|
203
|
+
disable_warning=True,
|
|
204
|
+
):
|
|
205
|
+
"""We keep a similar structure as in Kool et al. 2019 but save and load the data as npz
|
|
206
|
+
This is way faster and more memory efficient than pickle and also allows for easy transfer to TensorDict
|
|
207
|
+
"""
|
|
208
|
+
assert filename is None or (
|
|
209
|
+
len(problem) == 1 and len(graph_sizes) == 1
|
|
210
|
+
), "Can only specify filename when generating a single dataset"
|
|
211
|
+
|
|
212
|
+
distributions_per_problem = {
|
|
213
|
+
"tsp": [None],
|
|
214
|
+
"vrp": [None],
|
|
215
|
+
"pctsp": [None],
|
|
216
|
+
"op": ["const", "unif", "dist"],
|
|
217
|
+
"mdpp": [None],
|
|
218
|
+
}
|
|
219
|
+
if problem == "all":
|
|
220
|
+
problems = distributions_per_problem
|
|
221
|
+
else:
|
|
222
|
+
problems = {
|
|
223
|
+
problem: distributions_per_problem[problem]
|
|
224
|
+
if data_distribution == "all"
|
|
225
|
+
else [data_distribution]
|
|
226
|
+
}
|
|
227
|
+
# breakpoint()
|
|
228
|
+
fname = filename
|
|
229
|
+
for problem, distributions in problems.items():
|
|
230
|
+
for distribution in distributions or [None]:
|
|
231
|
+
for graph_size in graph_sizes:
|
|
232
|
+
datadir = os.path.join(data_dir, problem)
|
|
233
|
+
os.makedirs(datadir, exist_ok=True)
|
|
234
|
+
|
|
235
|
+
if filename is None:
|
|
236
|
+
fname = os.path.join(
|
|
237
|
+
datadir,
|
|
238
|
+
"{}{}{}_{}_seed{}.npz".format(
|
|
239
|
+
problem,
|
|
240
|
+
"_{}".format(distribution)
|
|
241
|
+
if distribution is not None
|
|
242
|
+
else "",
|
|
243
|
+
graph_size,
|
|
244
|
+
name,
|
|
245
|
+
seed,
|
|
246
|
+
),
|
|
247
|
+
)
|
|
248
|
+
else:
|
|
249
|
+
fname = check_extension(filename, extension=".npz")
|
|
250
|
+
|
|
251
|
+
if not overwrite and os.path.isfile(
|
|
252
|
+
check_extension(fname, extension=".npz")
|
|
253
|
+
):
|
|
254
|
+
if not disable_warning:
|
|
255
|
+
log.info(
|
|
256
|
+
"File {} already exists! Run with -f option to overwrite. Skipping...".format(
|
|
257
|
+
fname
|
|
258
|
+
)
|
|
259
|
+
)
|
|
260
|
+
continue
|
|
261
|
+
|
|
262
|
+
# Set seed
|
|
263
|
+
np.random.seed(seed)
|
|
264
|
+
|
|
265
|
+
# Automatically generate dataset
|
|
266
|
+
dataset = generate_env_data(
|
|
267
|
+
problem, dataset_size, graph_size, distribution
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
# A function can return None in case of an error or a skip
|
|
271
|
+
if dataset is not None:
|
|
272
|
+
# Save to disk as dict
|
|
273
|
+
log.info("Saving {} dataset to {}".format(problem, fname))
|
|
274
|
+
np.savez(fname, **dataset)
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def generate_default_datasets(data_dir):
|
|
278
|
+
"""Generate the default datasets used in the paper and save them to data_dir/problem"""
|
|
279
|
+
generate_dataset(data_dir=data_dir, name="val", problem="all", seed=4321)
|
|
280
|
+
generate_dataset(data_dir=data_dir, name="test", problem="all", seed=1234)
|
|
281
|
+
generate_dataset(
|
|
282
|
+
data_dir=data_dir,
|
|
283
|
+
name="test",
|
|
284
|
+
problem="mdpp",
|
|
285
|
+
seed=1234,
|
|
286
|
+
graph_sizes=[10],
|
|
287
|
+
dataset_size=100,
|
|
288
|
+
) # EDA (mDPP)
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
if __name__ == "__main__":
|
|
292
|
+
parser = argparse.ArgumentParser()
|
|
293
|
+
parser.add_argument(
|
|
294
|
+
"--filename", help="Filename of the dataset to create (ignores datadir)"
|
|
295
|
+
)
|
|
296
|
+
parser.add_argument(
|
|
297
|
+
"--data_dir",
|
|
298
|
+
default="data",
|
|
299
|
+
help="Create datasets in data_dir/problem (default 'data')",
|
|
300
|
+
)
|
|
301
|
+
parser.add_argument(
|
|
302
|
+
"--name", type=str, required=True, help="Name to identify dataset"
|
|
303
|
+
)
|
|
304
|
+
parser.add_argument(
|
|
305
|
+
"--problem",
|
|
306
|
+
type=str,
|
|
307
|
+
default="all",
|
|
308
|
+
help="Problem, 'tsp', 'vrp', 'pctsp' or 'op_const', 'op_unif' or 'op_dist'"
|
|
309
|
+
" or 'all' to generate all",
|
|
310
|
+
)
|
|
311
|
+
parser.add_argument(
|
|
312
|
+
"--data_distribution",
|
|
313
|
+
type=str,
|
|
314
|
+
default="all",
|
|
315
|
+
help="Distributions to generate for problem, default 'all'.",
|
|
316
|
+
)
|
|
317
|
+
parser.add_argument(
|
|
318
|
+
"--dataset_size", type=int, default=10000, help="Size of the dataset"
|
|
319
|
+
)
|
|
320
|
+
parser.add_argument(
|
|
321
|
+
"--graph_sizes",
|
|
322
|
+
type=int,
|
|
323
|
+
nargs="+",
|
|
324
|
+
default=[20, 50, 100],
|
|
325
|
+
help="Sizes of problem instances (default 20, 50, 100)",
|
|
326
|
+
)
|
|
327
|
+
parser.add_argument("-f", action="store_true", help="Set true to overwrite")
|
|
328
|
+
parser.add_argument("--seed", type=int, default=1234, help="Random seed")
|
|
329
|
+
parser.add_argument("--disable_warning", action="store_true", help="Disable warning")
|
|
330
|
+
args = parser.parse_args()
|
|
331
|
+
|
|
332
|
+
logging.basicConfig(level=logging.INFO)
|
|
333
|
+
|
|
334
|
+
args.overwrite = args.f
|
|
335
|
+
delattr(args, "f")
|
|
336
|
+
generate_dataset(**vars(args))
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
from tensordict.tensordict import TensorDict
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def load_npz_to_tensordict(filename):
|
|
9
|
+
"""Load a npz file directly into a TensorDict
|
|
10
|
+
We assume that the npz file contains a dictionary of numpy arrays
|
|
11
|
+
This is at least an order of magnitude faster than pickle
|
|
12
|
+
"""
|
|
13
|
+
x = np.load(filename)
|
|
14
|
+
x_dict = dict(x)
|
|
15
|
+
batch_size = x_dict[list(x_dict.keys())[0]].shape[0]
|
|
16
|
+
return TensorDict(x_dict, batch_size=batch_size)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def check_extension(filename, extension=".npz"):
|
|
20
|
+
"""Check that filename has extension, otherwise add it"""
|
|
21
|
+
if os.path.splitext(filename)[1] != extension:
|
|
22
|
+
return filename + extension
|
|
23
|
+
return filename
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
from rl4co.envs.atsp import ATSPEnv
|
|
2
|
+
from rl4co.envs.base import RL4COEnvBase
|
|
3
|
+
from rl4co.envs.cvrp import CVRPEnv
|
|
4
|
+
from rl4co.envs.dpp import DPPEnv
|
|
5
|
+
from rl4co.envs.mdpp import MDPPEnv
|
|
6
|
+
from rl4co.envs.mtsp import MTSPEnv
|
|
7
|
+
from rl4co.envs.op import OPEnv
|
|
8
|
+
from rl4co.envs.pctsp import PCTSPEnv
|
|
9
|
+
from rl4co.envs.pdp import PDPEnv
|
|
10
|
+
from rl4co.envs.sdvrp import SDVRPEnv
|
|
11
|
+
from rl4co.envs.tsp import TSPEnv
|