-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_submission.py
319 lines (251 loc) · 9.87 KB
/
test_submission.py
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
#!/usr/bin/env python3
import argparse
import docker
import glob
import gym
import json
import multiprocessing
import os
import requests
import subprocess
import sys
import tempfile
import textworld
import textworld.gym
import time
import tqdm
NB_EPISODES = 10
MAX_EPISODE_STEPS = 100
TIMEOUT = 6 * 3600 # 6 hours
# List of additional information available during evaluation.
AVAILABLE_INFORMATION = textworld.EnvInfos(
max_score=True, has_won=True, has_lost=True, # Handicap 0
description=True, inventory=True, objective=True, # Handicap 1
verbs=True, command_templates=True, # Handicap 2
entities=True, # Handicap 3
extras=["recipe"], # Handicap 4
admissible_commands=True, # Handicap 5
)
def _validate_requested_infos(infos):
msg = "The following information cannot be requested: {}"
for key in infos.basics:
if not getattr(AVAILABLE_INFORMATION, key):
raise ValueError(msg.format(key))
for key in infos.extras:
if key not in AVAILABLE_INFORMATION.extras:
raise ValueError(msg.format(key))
class _ReplayAgent:
"""
An agent that replays the actions of another agent.
"""
def __init__(self, stats):
self._stats = stats
self._game = None
self._episode = 0
self._step = 0
def train(self):
pass
def eval(self):
pass
def select_additional_infos(self):
infos = textworld.EnvInfos()
for info in self._stats["requested_infos"]:
if info in AVAILABLE_INFORMATION.extras:
infos.extras.append(info)
else:
setattr(infos, info, True)
return infos
def act(self, obs, scores, dones, infos):
if all(dones):
self._episode += 1
self._step = 0
return
if infos["_name"] != self._game:
self._game = infos["_name"]
self._episode = 0
step = self._step
self._step += 1
command = self._stats["games"][self._game]["runs"][self._episode]["commands"][step]
return [command]
def _play_game(agent_class, agent_class_args, gamefile):
game_name = os.path.basename(gamefile)
if agent_class_args:
agent = agent_class(agent_class_args)
else:
agent = agent_class()
agent.eval()
requested_infos = agent.select_additional_infos()
_validate_requested_infos(requested_infos)
# Turn on flags needed for the evaluation.
requested_infos.has_won = True
requested_infos.has_lost = True
requested_infos.max_score = True
stats = {}
start_time = time.time()
stats["runs"] = []
name = "test_{}".format(hash(gamefile))
env_id = textworld.gym.register_games([gamefile], requested_infos,
max_episode_steps=MAX_EPISODE_STEPS,
name=name)
env_id = textworld.gym.make_batch(env_id, batch_size=1)
env = gym.make(env_id)
for no_episode in range(NB_EPISODES):
obs, infos = env.reset()
all_commands = []
scores = [0] * len(obs)
dones = [False] * len(obs)
steps = [0] * len(obs)
while not all(dones):
# Increase step counts.
steps = [step + int(not done) for step, done in zip(steps, dones)]
# HACK to get the replay agent the current game
if isinstance(agent, _ReplayAgent):
infos["_name"] = game_name
commands = agent.act(obs, scores, dones, infos)
all_commands.append(commands)
obs, scores, dones, infos = env.step(commands)
# Let the agent knows the game is done.
agent.act(obs, scores, dones, infos)
# Collect stats
stats["runs"].append({})
stats["runs"][no_episode]["score"] = scores[0]
stats["runs"][no_episode]["steps"] = steps[0]
stats["runs"][no_episode]["commands"] = [cmds[0] for cmds in all_commands]
stats["runs"][no_episode]["has_won"] = infos["has_won"][0]
stats["runs"][no_episode]["has_lost"] = infos["has_lost"][0]
env.close()
stats["max_scores"] = infos["max_score"][0]
elapsed = time.time() - start_time
stats["duration"] = elapsed
return {game_name: stats}, requested_infos.basics + requested_infos.extras
def evaluate(agent_class, agent_class_args, game_files, nb_processes):
stats = {"games": {}, "requested_infos": [], "game_files": game_files}
print("Using {} processes.".format(nb_processes))
desc = "Evaluating {} games".format(len(game_files))
pbar = tqdm.tqdm(total=len(game_files), desc=desc)
def _assemble_results(args):
data, requested_infos = args
stats["games"].update(data)
stats["requested_infos"] = requested_infos
game_name, infos = list(data.items())[0]
total_scores = sum(d["score"] for d in infos["runs"])
total_steps = sum(d["steps"] for d in infos["runs"])
desc = "{:2d} / {}:\t{}".format(total_scores, total_steps, game_name)
pbar.write(desc)
pbar.update()
if nb_processes > 1:
pool = multiprocessing.Pool(nb_processes)
results = []
for game_file in game_files:
result = pool.apply_async(_play_game, (agent_class, agent_class_args, game_file), callback=_assemble_results)
results.append(result)
for result in results:
result.get()
pool.close()
pool.join()
pbar.close()
else:
for game_file in game_files:
data = _play_game(agent_class, agent_class_args, game_file)
_assemble_results(data)
pbar.close()
return stats
def _run_evaluation(agent_class, args, agent_class_args=None):
games = glob.glob(os.path.join(args.games_dir, "**/*.ulx"), recursive=True)
stats = evaluate(agent_class, agent_class_args, games, args.nb_processes)
out_dir = os.path.dirname(os.path.abspath(args.output))
if not os.path.isdir(out_dir):
os.makedirs(out_dir)
with open(args.output, "w") as f:
json.dump(stats, f)
def _dockerize(args):
submission_dir = os.path.abspath(args.submission_dir)
games_dir = os.path.abspath(args.games_dir)
output_dir = os.path.dirname(os.path.abspath(args.output))
self_file = os.path.abspath(__file__)
with tempfile.NamedTemporaryFile(dir=output_dir) as output_file:
client = docker.from_env()
image_path = os.path.join(submission_dir, "Dockerimage")
if os.path.exists(image_path):
with open(image_path, "r") as f:
image = f.read().strip()
else:
image = "tavianator/textworld-codalab"
volumes = {
submission_dir: {
"bind": "/usr/src/submission",
"mode": "ro",
},
games_dir: {
"bind": "/usr/share/textworld-games",
"mode": "ro",
},
output_file.name: {
"bind": "/usr/share/textworld-stats.json",
"mode": "rw",
},
self_file: {
"bind": "/usr/bin/evaluate.py",
"mode": "ro",
},
}
command = [
"python3",
"/usr/bin/evaluate.py",
"--in-docker",
"/usr/src/submission",
"/usr/share/textworld-games",
"/usr/share/textworld-stats.json",
]
if args.debug:
command += ["--debug"]
print("Loading {}...".format(image))
container = client.containers.run(
image,
command,
detach=True,
network_mode="none",
volumes=volumes,
environment=["PYTHONUNBUFFERED=1", "MKL_NUM_THREADS=1", "OMP_NUM_THREADS=1"],
)
try:
print("Running {}...".format(image))
result = container.wait(timeout=TIMEOUT)
finally:
if args.debug:
sys.stdout.buffer.write(container.logs(stdout=True, stderr=False))
sys.stderr.buffer.write(container.logs(stdout=False, stderr=True))
container.remove(force=True)
if result["StatusCode"] != 0:
msg = ("Some errors occur when evaluating the agent. You can test your agent"
" using the `test_submission.py` script provided with the starting kit"
" and using the `--debug` flag."
" If you can't find your error, reach out to us: textworld@microsoft.com.")
raise NameError(msg)
print("Done")
stats = json.load(output_file)
_run_evaluation(_ReplayAgent, args, agent_class_args=stats)
def main():
parser = argparse.ArgumentParser(description="Evaluate an agent.")
parser.add_argument("--in-docker", action="store_true", default=False, help=argparse.SUPPRESS)
parser.add_argument("submission_dir")
parser.add_argument("games_dir")
parser.add_argument("output", nargs='?', default="stats.json")
parser.add_argument("--nb-processes", type=int)
parser.add_argument("--debug", action="store_true")
args = parser.parse_args()
args.nb_processes = args.nb_processes or multiprocessing.cpu_count()
if args.debug:
args.nb_processes = 1
if args.in_docker:
args.submission_dir = os.path.abspath(args.submission_dir)
args.games_dir = os.path.abspath(args.games_dir)
args.output = os.path.abspath(args.output)
os.chdir(args.submission_dir) # Needed to load local files (e.g. vocab.txt)
sys.path = [args.submission_dir] + sys.path # Prepend to PYTHONPATH
from custom_agent import CustomAgent
_run_evaluation(CustomAgent, args)
else:
_dockerize(args)
if __name__ == "__main__":
main()