-
Notifications
You must be signed in to change notification settings - Fork 52
/
consumer.py
265 lines (200 loc) · 8.89 KB
/
consumer.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
"""
Evaluate objective on a set of parameters
=========================================
Call user's script as a black box process to evaluate a trial.
"""
import copy
import json
import logging
import os
import subprocess
import tempfile
import orion.core
from orion.core.io.convert import JSONConverter
from orion.core.io.orion_cmdline_parser import OrionCmdlineParser
from orion.core.io.resolve_config import infer_versioning_metadata
from orion.core.utils.exceptions import (
BranchingEvent,
InexecutableUserScript,
MissingResultFile,
)
log = logging.getLogger(__name__)
class ExecutionError(Exception):
"""Error raised when Orion is unable to execute the user's script without errors."""
def __init__(self, return_code=0):
super().__init__()
self.return_code = return_code
class Consumer:
"""Consume a trial by using it to initialize a black-box box to evaluate it.
It uses an `Experiment` object to push an evaluated trial, if results are
delivered to the worker process successfully.
It forks another process which executes user's script with the suggested
options. It expects results to be written in a **JSON** file, whose path
has been defined in a special orion environmental variable which is set
into the child process' environment.
Parameters
----------
experiment: `orion.core.worker.experiment.Experiment`
Manager of this experiment, provides convenient interface for interacting with
the database.
heartbeat: int, optional
Frequency (seconds) at which the heartbeat of the trial is updated.
If the heartbeat of a `reserved` trial is larger than twice the configured
heartbeat, Oríon will reset the status of the trial to `interrupted`.
This allows restoring lost trials (ex: due to killed worker).
Defaults to ``orion.core.config.worker.heartbeat``.
user_script_config: str, optional
Config argument name of user's script (--config).
Defaults to ``orion.core.config.worker.user_script_config``.
interrupt_signal_code: int, optional
Signal returned by user script to signal to Oríon that it was interrupted.
Defaults to ``orion.core.config.worker.interrupt_signal_code``.
"""
def __init__(
self,
experiment,
user_script_config=None,
interrupt_signal_code=None,
ignore_code_changes=None,
):
log.debug("Creating Consumer object.")
self.experiment = experiment
self.space = experiment.space
if self.space is None:
raise RuntimeError(
"Experiment object provided to Consumer has not yet completed"
" initialization."
)
if user_script_config is None:
user_script_config = orion.core.config.worker.user_script_config
if interrupt_signal_code is None:
interrupt_signal_code = orion.core.config.worker.interrupt_signal_code
# NOTE: If ignore_code_changes is None, we can assume EVC is enabled.
if ignore_code_changes is None:
ignore_code_changes = orion.core.config.evc.ignore_code_changes
self.interrupt_signal_code = interrupt_signal_code
self.ignore_code_changes = ignore_code_changes
# Fetch space builder
self.template_builder = OrionCmdlineParser(user_script_config)
self.template_builder.set_state_dict(experiment.metadata["parser"])
self.pacemaker = None
def __call__(self, trial, **kwargs):
"""Execute user's script as a block box using the options contained
within ``trial``.
Parameters
----------
trial: `orion.core.worker.trial.Trial`
Orion trial to execute.
Returns
-------
bool
True if the trial was successfully executed. False if the trial is broken.
"""
log.debug("Consumer context: %s", trial.working_dir)
results_file = self._consume(trial, trial.working_dir)
log.debug("Parsing results from file and fill corresponding Trial object.")
results = self.retrieve_results(results_file)
return results
def retrieve_results(self, results_file):
"""Retrieve the results from the file"""
try:
results = JSONConverter().parse(results_file.name)
except json.decoder.JSONDecodeError as exc:
raise MissingResultFile() from exc
return results
def get_execution_environment(self, trial, results_file="results.log"):
"""Set a few environment variables to allow users and
underlying processes to know if they are running under orion.
Parameters
----------
results_file: str
file used to store results, this is only used by the legacy protocol
trial: Trial
reference to the trial object that is going to be run
Notes
-----
This function defines the environment variables described below
.. envvar:: ORION_EXPERIMENT_ID
:noindex:
Current experiment that is being ran.
.. envvar:: ORION_EXPERIMENT_NAME
:noindex:
Name of the experiment the worker is currently working on.
.. envvar:: ORION_EXPERIMENT_VERSION
:noindex:
Version of the experiment the worker is currently working on.
.. envvar:: ORION_TRIAL_ID
:noindex:
Current trial id that is currently being executed in this process.
.. envvar:: ORION_WORKING_DIRECTORY
:noindex:
Trial's current working directory.
.. envvar:: ORION_RESULTS_PATH
:noindex:
Trial's results file that is read by the legacy protocol to get the results of the trial
after a successful run.
"""
env = dict(os.environ)
env["ORION_EXPERIMENT_ID"] = str(self.experiment.id)
env["ORION_EXPERIMENT_NAME"] = str(self.experiment.name)
env["ORION_EXPERIMENT_VERSION"] = str(self.experiment.version)
env["ORION_TRIAL_ID"] = str(trial.id)
env["ORION_WORKING_DIR"] = str(trial.working_dir)
env["ORION_RESULTS_PATH"] = str(results_file)
env["ORION_INTERRUPT_CODE"] = str(self.interrupt_signal_code)
return env
def _consume(self, trial, workdirname):
# pylint: disable = consider-using-with
config_file = tempfile.NamedTemporaryFile(
mode="w", prefix="trial_", suffix=".conf", dir=workdirname, delete=False
)
config_file.close()
log.debug("New temp config file: %s", config_file.name)
# pylint: disable = consider-using-with
results_file = tempfile.NamedTemporaryFile(
mode="w", prefix="results_", suffix=".log", dir=workdirname, delete=False
)
results_file.close()
log.debug("New temp results file: %s", results_file.name)
log.debug("Building command line argument and configuration for trial.")
env = self.get_execution_environment(trial, results_file.name)
cmd_args = self.template_builder.format(
config_file.name, trial, self.experiment
)
log.debug("Launch user's script as a subprocess and wait for finish.")
self._validate_code_version()
self.execute_process(cmd_args, env)
return results_file
def _validate_code_version(self):
old_config = self.experiment.configuration
new_config = copy.deepcopy(old_config)
new_config["metadata"]["VCS"] = infer_versioning_metadata(
old_config["metadata"]["user_script"]
)
# Circular import
from orion.core.evc.conflicts import CodeConflict
conflicts = list(CodeConflict.detect(old_config, new_config))
if conflicts and not self.ignore_code_changes:
raise BranchingEvent(
f"Code changed between execution of 2 trials:\n{conflicts[0]}"
)
elif conflicts:
log.warning(
"Code changed between execution of 2 trials. Enable EVC with option "
"`ignore_code_changes` set to False to raise an error when trials are executed "
"with different versions. For more information, see documentation at "
"https://orion.readthedocs.io/en/stable/user/config.html#experiment-version-control"
)
def execute_process(self, cmd_args, environ):
"""Facilitate launching a black-box trial."""
command = cmd_args
try:
# pylint: disable = consider-using-with
process = subprocess.Popen(command, env=environ)
except PermissionError as exc:
log.debug("Script is not executable")
raise InexecutableUserScript(" ".join(cmd_args)) from exc
return_code = process.wait()
log.debug(f"Script finished with return code {return_code}")
if return_code != 0:
raise ExecutionError(return_code)