def test_format_with_properties( parser: OrionCmdlineParser, cmd_with_properties: List[str], hacked_exp: Experiment, weird_argument: WeirdArgument, ): """Test if format correctly puts the value of `trial` and `exp` when used as properties""" parser.parse(cmd_with_properties) # NOTE: Also using a weird argument here, to make sure the parser is able to distinguish # property look-up vs weird argument names. trial = Trial( experiment="trial_test", params=[ {"name": "/lr", "type": "real", "value": -2.4}, {"name": "/prior", "type": "categorical", "value": "sgd"}, { "name": f"/{weird_argument.name}", "type": weird_argument.prior_type, "value": weird_argument.value, }, ], ) cmd_line = parser.format(None, trial=trial, experiment=hacked_exp) assert trial.hash_name in cmd_line assert "supernaedo2-dendi" in cmd_line
def test_format_commandline_only( parser: OrionCmdlineParser, commandline: List[str], weird_argument: WeirdArgument ): """Format the commandline using only args.""" parser.parse(commandline) trial = Trial( params=[ {"name": "/lr", "type": "real", "value": -2.4}, {"name": "/prior", "type": "categorical", "value": "sgd"}, {"name": "/a.b", "type": "real", "value": 0.5}, { "name": f"/{weird_argument.name}", "type": weird_argument.prior_type, "value": weird_argument.value, }, ] ) cmd_inst = parser.format(trial=trial) assert cmd_inst == [ "--seed", "555", "--lr", "-2.4", "--non-prior", "choices({'sgd': 0.2, 'adam': 0.8})", "--prior", "sgd", "--a.b", "0.5", f"--{weird_argument.name}", f"{weird_argument.value}", ]
def test_format_without_config_path( parser: OrionCmdlineParser, commandline: List[str], json_config: List[str], tmp_path: Path, json_converter: JSONConverter, weird_argument: WeirdArgument, ): """Verify that parser.format() raises ValueError when config path not passed.""" cmd_args = json_config cmd_args.extend(commandline) parser.parse(cmd_args) trial = Trial( params=[ {"name": "/lr", "type": "real", "value": -2.4}, {"name": "/prior", "type": "categorical", "value": "sgd"}, {"name": "/layers/1/width", "type": "integer", "value": 100}, {"name": "/layers/1/type", "type": "categorical", "value": "relu"}, {"name": "/layers/2/type", "type": "categorical", "value": "sigmoid"}, {"name": "/training/lr0", "type": "real", "value": 0.032}, {"name": "/training/mbs", "type": "integer", "value": 64}, {"name": "/something-same", "type": "categorical", "value": "3"}, { "name": f"/{weird_argument.name}", "type": "categorical", "value": weird_argument.value, }, ] ) with pytest.raises( ValueError, match="Cannot format without a `config_path` argument." ): parser.format(trial=trial)
class SpaceBuilder(object): """Build a `Space` object form user's configuration.""" def __init__(self): """Initialize a `SpaceBuilder`.""" self.dimbuilder = DimensionBuilder() self.space = None self.commands_tmpl = None self.converter = None self.parser = None def build_from(self, config): """Build a `Space` object from a configuration. Initialize a new parser for this commandline and parse the given config then build a `Space` object from that configuration. Returns ------- `orion.algo.space.Space` The problem's search space definition. """ self.parser = OrionCmdlineParser(orion_config.user_script_config) self.parser.parse(config) return self.build(self.parser.priors) def build(self, configuration): """Create a definition of the problem's search space. Using information from the user's script configuration (if provided) and the command line arguments, will create a `Space` object defining the problem's search space. Parameters ---------- configuration: OrderedDict An OrderedDict containing the name and the expression of the parameters. Returns ------- `orion.algo.space.Space` The problem's search space definition. """ self.space = Space() for namespace, expression in configuration.items(): if _should_not_be_built(expression): continue expression = _remove_marker(expression) dimension = self.dimbuilder.build(namespace, expression) try: self.space.register(dimension) except ValueError as exc: error_msg = 'Conflict for name \'{}\' in parameters'.format( namespace) raise ValueError(error_msg) from exc return self.space def build_to(self, config_path, trial, experiment=None): """Create the configuration for the user's script. Using the configuration parser, create the commandline associated with the user's script while replacing the correct instances of parameter distributions by their actual values. If needed, the parser will also create a configuration file. Parameters ---------- config_path: str Path in which the configuration file instance will be created. trial: `orion.core.worker.trial.Trial` Object with concrete parameter values for the defined `Space`. experiment: `orion.core.worker.experiment.Experiment`, optional Object with information related to the current experiment. Returns ------- list The commandline arguments that must be given to script for execution. """ return self.parser.format(config_path, trial, experiment)
class Consumer(object): """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. """ def __init__(self, experiment): """Initialize a consumer. :param experiment: Manager of this experiment, provides convenient interface for interacting with the database. """ 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.") # Fetch space builder self.template_builder = OrionCmdlineParser( orion.core.config.user_script_config) self.template_builder.set_state_dict(experiment.metadata['parser']) # Get path to user's script and infer trial configuration directory if experiment.working_dir: self.working_dir = os.path.abspath(experiment.working_dir) else: self.working_dir = os.path.join(tempfile.gettempdir(), 'orion') self.script_path = experiment.metadata['user_script'] self.pacemaker = None def consume(self, trial): """Execute user's script as a block box using the options contained within `trial`. :type trial: `orion.core.worker.trial.Trial` """ log.debug("### Create new directory at '%s':", self.working_dir) temp_dir = self.experiment.working_dir is None prefix = self.experiment.name + "_" suffix = trial.id try: with WorkingDir(self.working_dir, temp_dir, prefix=prefix, suffix=suffix) as workdirname: log.debug("## New consumer context: %s", workdirname) trial.working_dir = workdirname results_file = self._consume(trial, workdirname) log.debug( "## Parse results from file and fill corresponding Trial object." ) self.experiment.update_completed_trial(trial, results_file) except KeyboardInterrupt: log.debug("### Save %s as interrupted.", trial) self.experiment.set_trial_status(trial, status='interrupted') raise except ExecutionError: log.debug("### Save %s as broken.", trial) self.experiment.set_trial_status(trial, status='broken') 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 Current experiment that is being ran. .. envvar:: ORION_EXPERIMENT_NAME Name of the experiment the worker is currently working on. .. envvar:: ORION_EXPERIMENT_VERSION Version of the experiment the worker is currently working on. .. envvar:: ORION_TRIAL_ID Current trial id that is currently being executed in this process. .. envvar:: ORION_WORKING_DIRECTORY Trial's current working directory. .. envvar:: ORION_RESULTS_PATH 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) return env def _consume(self, trial, workdirname): 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) 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.pacemaker = TrialPacemaker(trial) self.pacemaker.start() try: self.execute_process(cmd_args, env) finally: # merciless self.pacemaker.stop() return results_file def execute_process(self, cmd_args, environ): """Facilitate launching a black-box trial.""" command = [self.script_path] + cmd_args signal.signal(signal.SIGTERM, _handler) process = subprocess.Popen(command, env=environ) return_code = process.wait() if return_code != 0: raise ExecutionError("Something went wrong. Check logs. Process " "returned with code {} !".format(return_code))
def test_set_state_dict( parser: OrionCmdlineParser, commandline: List[str], json_config: List[str], tmp_path: Path, json_converter, weird_argument: WeirdArgument, ): """Test that set_state_dict sets state properly to generate new config.""" cmd_args = json_config cmd_args.extend(commandline) temp_parser: Optional[OrionCmdlineParser] = parser assert temp_parser is not None temp_parser.parse(cmd_args) state = temp_parser.get_state_dict() temp_parser = None blank_parser = OrionCmdlineParser(allow_non_existing_files=True) blank_parser.set_state_dict(state) trial = Trial( params=[ {"name": "/lr", "type": "real", "value": -2.4}, {"name": "/prior", "type": "categorical", "value": "sgd"}, {"name": "/layers/1/width", "type": "integer", "value": 100}, {"name": "/layers/1/type", "type": "categorical", "value": "relu"}, {"name": "/layers/2/type", "type": "categorical", "value": "sigmoid"}, {"name": "/training/lr0", "type": "real", "value": 0.032}, {"name": "/training/mbs", "type": "integer", "value": 64}, {"name": "/something-same", "type": "categorical", "value": "3"}, {"name": "/a.b", "type": "real", "value": 0.2}, { "name": f"/{weird_argument.name}", "type": weird_argument.prior_type, "value": weird_argument.value, }, ] ) output_file = str(tmp_path / "output.json") cmd_inst = blank_parser.format(output_file, trial) assert cmd_inst == [ "--config", output_file, "--seed", "555", "--lr", "-2.4", "--non-prior", "choices({'sgd': 0.2, 'adam': 0.8})", "--prior", "sgd", "--a.b", "0.2", f"--{weird_argument.name}", f"{weird_argument.value}", ] output_data = json_converter.parse(output_file) assert output_data == { "yo": 5, "training": {"lr0": 0.032, "mbs": 64}, "layers": [ {"width": 64, "type": "relu"}, {"width": 100, "type": "relu"}, {"width": 16, "type": "sigmoid"}, ], "something-same": "3", }
def test_format_commandline_and_config( parser: OrionCmdlineParser, commandline: List[str], json_config: List[str], tmp_path: Path, json_converter, weird_argument: WeirdArgument, ): """Format the commandline and a configuration file.""" cmd_args = json_config cmd_args.extend(commandline) parser.parse(cmd_args) trial = Trial( params=[ {"name": "/lr", "type": "real", "value": -2.4}, {"name": "/prior", "type": "categorical", "value": "sgd"}, {"name": "/layers/1/width", "type": "integer", "value": 100}, {"name": "/layers/1/type", "type": "categorical", "value": "relu"}, {"name": "/layers/2/type", "type": "categorical", "value": "sigmoid"}, {"name": "/training/lr0", "type": "real", "value": 0.032}, {"name": "/training/mbs", "type": "integer", "value": 64}, {"name": "/something-same", "type": "categorical", "value": "3"}, {"name": "/a.b", "type": "real", "value": 0.3}, { "name": f"/{weird_argument.name}", "type": f"{weird_argument.prior_type}", "value": weird_argument.value, }, ] ) output_file = str(tmp_path / "output.json") cmd_inst = parser.format(output_file, trial) assert cmd_inst == [ "--config", output_file, "--seed", "555", "--lr", "-2.4", "--non-prior", "choices({'sgd': 0.2, 'adam': 0.8})", "--prior", "sgd", "--a.b", "0.3", f"--{weird_argument.name}", f"{weird_argument.value}", ] output_data = json_converter.parse(output_file) assert output_data == { "yo": 5, "training": {"lr0": 0.032, "mbs": 64}, "layers": [ {"width": 64, "type": "relu"}, {"width": 100, "type": "relu"}, {"width": 16, "type": "sigmoid"}, ], "something-same": "3", }
def test_set_state_dict(parser, commandline, json_config, tmpdir, json_converter): """Test that set_state_dict sets state properly to generate new config.""" cmd_args = json_config cmd_args.extend(commandline) parser.parse(cmd_args) state = parser.get_state_dict() parser = None blank_parser = OrionCmdlineParser(allow_non_existing_files=True) blank_parser.set_state_dict(state) trial = Trial(params=[ { "name": "/lr", "type": "real", "value": -2.4 }, { "name": "/prior", "type": "categorical", "value": "sgd" }, { "name": "/layers/1/width", "type": "integer", "value": 100 }, { "name": "/layers/1/type", "type": "categorical", "value": "relu" }, { "name": "/layers/2/type", "type": "categorical", "value": "sigmoid" }, { "name": "/training/lr0", "type": "real", "value": 0.032 }, { "name": "/training/mbs", "type": "integer", "value": 64 }, { "name": "/something-same", "type": "categorical", "value": "3" }, ]) output_file = str(tmpdir.join("output.json")) cmd_inst = blank_parser.format(output_file, trial) assert cmd_inst == [ "--config", output_file, "--seed", "555", "--lr", "-2.4", "--non-prior", "choices({'sgd': 0.2, 'adam': 0.8})", "--prior", "sgd", ] output_data = json_converter.parse(output_file) assert output_data == { "yo": 5, "training": { "lr0": 0.032, "mbs": 64 }, "layers": [ { "width": 64, "type": "relu" }, { "width": 100, "type": "relu" }, { "width": 16, "type": "sigmoid" }, ], "something-same": "3", }
def test_set_state_dict(parser, commandline, json_config, tmpdir, json_converter): """Test that set_state_dict sets state properly to generate new config.""" cmd_args = json_config cmd_args.extend(commandline) parser.parse(cmd_args) state = parser.get_state_dict() parser = None blank_parser = OrionCmdlineParser() blank_parser.set_state_dict(state) trial = Trial(params=[{ 'name': '/lr', 'type': 'real', 'value': -2.4 }, { 'name': '/prior', 'type': 'categorical', 'value': 'sgd' }, { 'name': '/layers/1/width', 'type': 'integer', 'value': 100 }, { 'name': '/layers/1/type', 'type': 'categorical', 'value': 'relu' }, { 'name': '/layers/2/type', 'type': 'categorical', 'value': 'sigmoid' }, { 'name': '/training/lr0', 'type': 'real', 'value': 0.032 }, { 'name': '/training/mbs', 'type': 'integer', 'value': 64 }, { 'name': '/something-same', 'type': 'categorical', 'value': '3' }]) output_file = str(tmpdir.join("output.json")) cmd_inst = blank_parser.format(output_file, trial) assert cmd_inst == [ '--config', output_file, "--seed", "555", "--lr", "-2.4", "--non-prior", "choices({'sgd': 0.2, 'adam': 0.8})", "--prior", "sgd" ] output_data = json_converter.parse(output_file) assert output_data == { 'yo': 5, 'training': { 'lr0': 0.032, 'mbs': 64 }, 'layers': [{ 'width': 64, 'type': 'relu' }, { 'width': 100, 'type': 'relu' }, { 'width': 16, 'type': 'sigmoid' }], 'something-same': '3' }
class Consumer(object): """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, heartbeat=None, 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 heartbeat is None: heartbeat = orion.core.config.worker.heartbeat 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 if ignore_code_changes is None: ignore_code_changes = orion.core.config.evc.ignore_code_changes self.heartbeat = heartbeat 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"]) # Get path to user's script and infer trial configuration directory if experiment.working_dir: self.working_dir = os.path.abspath(experiment.working_dir) else: self.working_dir = os.path.join(tempfile.gettempdir(), "orion") self.pacemaker = None def consume(self, trial): """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("### Create new directory at '%s':", self.working_dir) temp_dir = not bool(self.experiment.working_dir) prefix = self.experiment.name + "_" suffix = trial.id try: with WorkingDir(self.working_dir, temp_dir, prefix=prefix, suffix=suffix) as workdirname: log.debug("## New consumer context: %s", workdirname) trial.working_dir = workdirname results_file = self._consume(trial, workdirname) log.debug( "## Parse results from file and fill corresponding Trial object." ) self.experiment.update_completed_trial(trial, results_file) success = True except KeyboardInterrupt: log.debug("### Save %s as interrupted.", trial) self.experiment.set_trial_status(trial, status="interrupted") raise except ExecutionError: log.debug("### Save %s as broken.", trial) self.experiment.set_trial_status(trial, status="broken") success = False return success 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): 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) 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.pacemaker = TrialPacemaker(trial, self.heartbeat) self.pacemaker.start() try: self.execute_process(cmd_args, env) finally: # merciless self.pacemaker.stop() return results_file def _validate_code_version(self): if self.ignore_code_changes: return 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: raise BranchingEvent( f"Code changed between execution of 2 trials:\n{conflicts[0]}") # pylint: disable = no-self-use def execute_process(self, cmd_args, environ): """Facilitate launching a black-box trial.""" command = cmd_args signal.signal(signal.SIGTERM, _handler) try: process = subprocess.Popen(command, env=environ) except PermissionError: log.debug("### Script is not executable") raise InexecutableUserScript(" ".join(cmd_args)) return_code = process.wait() if return_code == self.interrupt_signal_code: raise KeyboardInterrupt() elif return_code != 0: raise ExecutionError("Something went wrong. Check logs. Process " "returned with code {} !".format(return_code))
class Consumer(object): """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) os.makedirs(trial.working_dir, exist_ok=True) 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): """Retrive the results from the file""" try: results = JSONConverter().parse(results_file.name) except json.decoder.JSONDecodeError: raise MissingResultFile() 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): 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) 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" ) # pylint: disable = no-self-use def execute_process(self, cmd_args, environ): """Facilitate launching a black-box trial.""" command = cmd_args try: process = subprocess.Popen(command, env=environ) except PermissionError: log.debug("Script is not executable") raise InexecutableUserScript(" ".join(cmd_args)) return_code = process.wait() log.debug(f"Script finished with return code {return_code}") if return_code != 0: raise ExecutionError(return_code)