-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathalfworld_rl.py
More file actions
255 lines (201 loc) · 8.08 KB
/
Copy pathalfworld_rl.py
File metadata and controls
255 lines (201 loc) · 8.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
import os
import subprocess
import shlex
from omegaconf import DictConfig, ListConfig, OmegaConf
def run_local(cmd: str, check: bool = True) -> None:
subprocess.run(f"bash -lc {shlex.quote(cmd)}", shell=True, check=check)
def run_local_async(cmd: str) -> subprocess.Popen:
return subprocess.Popen(f"bash -lc {shlex.quote(cmd)}", shell=True)
def run_remote(host: str, cmd: str, check: bool = True) -> None:
ssh_cmd = f'ssh root@{host} "bash -lc {shlex.quote(cmd)}"'
subprocess.run(ssh_cmd, shell=True, check=check)
def run_remote_async(host: str, cmd: str) -> subprocess.Popen:
ssh_cmd = f'ssh root@{host} "bash -lc {shlex.quote(cmd)}"'
return subprocess.Popen(ssh_cmd, shell=True)
def get_config():
cli_conf = OmegaConf.from_cli()
yaml_conf = OmegaConf.load(cli_conf.config)
return OmegaConf.merge(yaml_conf, cli_conf)
def begin_with(file_name: str):
with open(file_name, "w"):
pass
def make_init_bash(cfg) -> str:
sc = cfg.system
http_proxy = sc.HTTP_PROXY
https_proxy = sc.HTTP_PROXY
hf_home = sc.HF_HOME
envs_dir = sc.envs_dir
environment_data_dir = cfg.dataset.environment_data_dir
lines = []
lines.append("set -e")
if http_proxy is not None:
lines.append(f"echo 'export HTTP_PROXY={http_proxy}' >> ~/.bashrc")
if https_proxy is not None:
lines.append(f"echo 'export HTTPS_PROXY={https_proxy}' >> ~/.bashrc")
if hf_home is not None:
lines.append(f"echo 'export HF_HOME={hf_home}' >> ~/.bashrc")
lines.append(f"echo 'export ALFWORLD_DATA={environment_data_dir}' >> ~/.bashrc")
lines.append("")
if envs_dir is not None:
lines.append(f"conda config --append envs_dirs {envs_dir} || true")
lines.append("")
lines.append("echo 'source ~/.bashrc' >> ~/.bash_profile")
lines.append("")
return "\n".join(lines)
if __name__ == "__main__":
def init_node(host: str):
run_remote(host, INIT_BASH, check=False)
def init_hosts(worker_hosts):
for h in worker_hosts:
if h is None:
continue
init_node(h)
def env_prefix() -> str:
return (
"source ~/.bashrc && "
f"source activate {env_name} && "
)
def sample(worker_hosts, epoch, cfg, type):
project = cfg.experiment.project
procs = []
script_name = "alfworld_rl_rollout.py"
for idx, host in enumerate(worker_hosts):
body = (
f"cd {BASE_DIR}/sample && "
f"python {script_name} "
f"config=../configs/{project}.yaml "
f"experiment.current_epoch={epoch} "
f"experiment.function={type} "
f"experiment.node_index={idx}"
)
full_cmd = env_prefix() + body
if idx == 0:
procs.append(run_local_async(full_cmd))
else:
procs.append(run_remote_async(host, full_cmd))
for p in procs:
p.wait()
def aggregate(epoch, cfg, type):
project = cfg.experiment.project
full_cmd = env_prefix() + (
f"cd {BASE_DIR}/reward && "
f"python rl_aggregate_data.py "
f"config=../configs/{project}.yaml "
f"experiment.function={type} "
f"experiment.current_epoch={epoch}"
)
run_local(full_cmd)
def reward(epoch, cfg, type):
project = cfg.experiment.project
script_name = "alfworld_rl_reward.py"
full_cmd = env_prefix() + (
f"cd {BASE_DIR}/reward && "
f"python {script_name} "
f"config=../configs/{project}.yaml "
f"experiment.function={type} "
f"experiment.current_epoch={epoch}"
)
run_local(full_cmd)
import os, json
def json_not_empty(path: str) -> bool:
if not path or (not os.path.isfile(path)):
return False
try:
with open(path, "r", encoding="utf-8") as f:
obj = json.load(f)
except Exception:
return False
if isinstance(obj, list):
return len(obj) > 0
if isinstance(obj, dict):
return len(obj) > 0
return False
def train(worker_hosts, epoch, cfg, target = None):
project = cfg.experiment.project
ds_file = cfg.experiment.deepspeed_file
num_nodes = len(worker_hosts)
master_ip = os.environ["MLP_WORKER_0_HOST"]
master_port = os.environ["MLP_WORKER_0_PORT"]
script_name = "alfworld_train.py"
procs = []
for idx, host in enumerate(worker_hosts):
body = (
f"cd {BASE_DIR} && "
"export DS_SKIP_CUDA_CHECK=1 && "
"accelerate launch "
f"--num_machines {num_nodes} "
f"--machine_rank {idx} "
f"--main_process_ip {master_ip} "
f"--main_process_port {master_port} "
f"--config_file accelerate_configs/{ds_file}.yaml "
f"train/{script_name} "
f"config=configs/{project}.yaml "
f'training.target={target} '
f"experiment.current_epoch={epoch}"
)
full_cmd = env_prefix() + body
if idx == 0:
procs.append(run_local_async(full_cmd))
else:
procs.append(run_remote_async(host, full_cmd))
print(f"[DISPATCH] train node {idx} → {host}")
for p in procs:
p.wait()
print("All train nodes finished.")
cfg = get_config()
INIT_BASH = make_init_bash(cfg)
BASE_DIR = cfg.system.rl_base_dir
env_name = cfg.system.env_name
total_step = cfg.experiment.total_step
project = cfg.experiment.project
num_node = cfg.experiment.num_node
#worker_hosts = [os.environ[f"MLP_WORKER_{i}_HOST"] for i in range(num_node)]
if num_node <= 1:
worker_hosts = [None] # rank0 local placeholder
else:
worker_hosts = [os.environ[f"MLP_WORKER_{i}_HOST"] for i in range(num_node)]
import time
time.sleep(30)
init_hosts(worker_hosts)
import time
time.sleep(10)
if cfg.experiment.start_from_scratch:
os.makedirs(f"{project}/results", exist_ok=True)
optimized = f"../{project}/ckpt/{cfg.model.optimized_name}"
path = (
f"{project}/results/results-rl-"
f"{optimized.replace('/', '.')}-"
f"{cfg.dataset.environment_type}.txt"
)
begin_with(path)
path = (
f"{project}/results/results-eval-"
f"{optimized.replace('/', '.')}-"
f"{cfg.dataset.environment_type}-{cfg.dataset.alfworld_eval_type}.txt"
)
begin_with(path)
import shutil
def clear_dir(out_dir):
if os.path.exists(out_dir):
shutil.rmtree(out_dir)
os.makedirs(out_dir, exist_ok=True)
clear_dir(f"{cfg.dataset.environment_data_dir}/json_2.1.1/{cfg.experiment.project}")
clear_dir(f"{cfg.dataset.environment_data_dir}/json_2.1.1/{cfg.experiment.project}/{cfg.dataset.alfworld_syn_train_type}")
clear_dir(f"{cfg.dataset.environment_data_dir}/json_2.1.1/{cfg.experiment.project}/{cfg.dataset.alfworld_temp_train_type}")
epoch = cfg.experiment.current_epoch
while epoch <= total_step:
print(f"\n========== epoch {epoch} ==========")
sample(worker_hosts, epoch, cfg, "train")
aggregate(epoch, cfg, "train")
reward(epoch, cfg, "train")
reward_ds_path = f"./{project}/temp_data/{cfg.dataset.reward_optimization_data}.json"
train(worker_hosts, epoch, cfg, target = "policy")
if json_not_empty(reward_ds_path):
train(worker_hosts, epoch, cfg, target="reward")
else:
print(f"[SKIP] reward train skipped: empty or missing {reward_ds_path}")
if epoch % cfg.experiment.eval_every == 0:
sample(worker_hosts, epoch, cfg, "evaluation")
aggregate(epoch, cfg, "evaluation")
reward(epoch, cfg, "evaluation")
epoch += 1