text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def job(request): """View for a single job."""
job_id = request.GET.get("job_id") recent_jobs = JobRecord.objects.order_by("-start_time")[0:100] recent_trials = TrialRecord.objects \ .filter(job_id=job_id) \ .order_by("-start_time") trial_records = [] for recent_trial in recent_trials: trial_records.append(get_trial_info...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def trial(request): """View for a single trial."""
job_id = request.GET.get("job_id") trial_id = request.GET.get("trial_id") recent_trials = TrialRecord.objects \ .filter(job_id=job_id) \ .order_by("-start_time") recent_results = ResultRecord.objects \ .filter(trial_id=trial_id) \ .order_by("-date")[0:2000] current_t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_job_info(current_job): """Get job information for current job."""
trials = TrialRecord.objects.filter(job_id=current_job.job_id) total_num = len(trials) running_num = sum(t.trial_status == Trial.RUNNING for t in trials) success_num = sum(t.trial_status == Trial.TERMINATED for t in trials) failed_num = sum(t.trial_status == Trial.ERROR for t in trials) if tot...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_trial_info(current_trial): """Get job information for current trial."""
if current_trial.end_time and ("_" in current_trial.end_time): # end time is parsed from result.json and the format # is like: yyyy-mm-dd_hh-MM-ss, which will be converted # to yyyy-mm-dd hh:MM:ss here time_obj = datetime.datetime.strptime(current_trial.end_time, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_winner(trials): """Get winner trial of a job."""
winner = {} # TODO: sort_key should be customized here sort_key = "accuracy" if trials and len(trials) > 0: first_metrics = get_trial_info(trials[0])["metrics"] if first_metrics and not first_metrics.get("accuracy", None): sort_key = "episode_reward" max_metric = flo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_argv(config): """Converts configuration to a command line argument format."""
argv = [] for k, v in config.items(): if "-" in k: raise ValueError("Use '_' instead of '-' in `{}`".format(k)) if v is None: continue if not isinstance(v, bool) or v: # for argparse flags argv.append("--{}".format(k.replace("_", "-"))) if is...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_trial_from_spec(spec, output_path, parser, **trial_kwargs): """Creates a Trial object from parsing the spec. Arguments: spec (dict): A resolved exper...
try: args = parser.parse_args(to_argv(spec)) except SystemExit: raise TuneError("Error parsing args, see above message", spec) if "resources_per_trial" in spec: trial_kwargs["resources"] = json_to_resources( spec["resources_per_trial"]) return Trial( # Submit...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_for_compute_zone_operation(compute, project_name, operation, zone): """Poll for compute zone operation until finished."""
logger.info("wait_for_compute_zone_operation: " "Waiting for operation {} to finish...".format( operation["name"])) for _ in range(MAX_POLLS): result = compute.zoneOperations().get( project=project_name, operation=operation["name"], zone=zone...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_task_id(source): """Return the task id associated to the generic source of the signal. Args: source: source of the signal, it can be either an object id...
if type(source) is ray.actor.ActorHandle: return source._ray_actor_id else: if type(source) is ray.TaskID: return source else: return ray._raylet.compute_task_id(source)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receive(sources, timeout=None): """Get all outstanding signals from sources. A source can be either (1) an object ID returned by the task (we want to receive...
# If None, initialize the timeout to a huge value (i.e., over 30,000 years # in this case) to "approximate" infinity. if timeout is None: timeout = 10**12 if timeout < 0: raise ValueError("The 'timeout' argument cannot be less than 0.") if not hasattr(ray.worker.global_worker, "s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(): """ Reset the worker state associated with any signals that this worker has received so far. If the worker calls receive() on a source next, it will...
if hasattr(ray.worker.global_worker, "signal_counters"): ray.worker.global_worker.signal_counters = defaultdict(lambda: b"0")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_once(key): """Returns True if this is the "first" call for a given key. Various logging settings can adjust the definition of "first". Example: """
global _last_logged if _disabled: return False elif key not in _logged: _logged.add(key) _last_logged = time.time() return True elif _periodic_log and time.time() - _last_logged > 60.0: _logged.clear() _last_logged = time.time() return False ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(object_ids): """Get a single or a collection of remote objects from the object store. This method is identical to `ray.get` except it adds support for tu...
if isinstance(object_ids, (tuple, np.ndarray)): return ray.get(list(object_ids)) elif isinstance(object_ids, dict): keys_to_get = [ k for k, v in object_ids.items() if isinstance(v, ray.ObjectID) ] ids_to_get = [ v for k, v in object_ids.items() if isinst...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _raise_deprecation_note(deprecated, replacement, soft=False): """User notification for deprecated parameter. Arguments: deprecated (str): Deprecated paramet...
error_msg = ("`{deprecated}` is deprecated. Please use `{replacement}`. " "`{deprecated}` will be removed in future versions of " "Ray.".format(deprecated=deprecated, replacement=replacement)) if soft: logger.warning(error_msg) else: raise DeprecationWarnin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_to_experiment_list(experiments): """Produces a list of Experiment objects. Converts input from dict, single experiment, or list of experiments to lis...
exp_list = experiments # Transform list if necessary if experiments is None: exp_list = [] elif isinstance(experiments, Experiment): exp_list = [experiments] elif type(experiments) is dict: exp_list = [ Experiment.from_json(name, spec) for name, spec...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_json(cls, name, spec): """Generates an Experiment object from JSON. Args: name (str): Name of Experiment. spec (dict): JSON configuration of experimen...
if "run" not in spec: raise TuneError("No trainable specified!") # Special case the `env` param for RLlib by automatically # moving it into the `config` section. if "env" in spec: spec["config"] = spec.get("config", {}) spec["config"]["env"] = spec["...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _register_if_needed(cls, run_object): """Registers Trainable or Function at runtime. Assumes already registered if run_object is a string. Does not register ...
if isinstance(run_object, six.string_types): return run_object elif isinstance(run_object, types.FunctionType): if run_object.__name__ == "<lambda>": logger.warning( "Not auto-registering lambdas - resolving as variant.") retu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tsqr(a): """Perform a QR decomposition of a tall-skinny matrix. Args: a: A distributed matrix with shape MxN (suppose K = min(M, N)). Returns: A tuple of q (...
if len(a.shape) != 2: raise Exception("tsqr requires len(a.shape) == 2, but a.shape is " "{}".format(a.shape)) if a.num_blocks[1] != 1: raise Exception("tsqr requires a.num_blocks[1] == 1, but a.num_blocks " "is {}".format(a.num_blocks)) num_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def modified_lu(q): """Perform a modified LU decomposition of a matrix. This takes a matrix q with orthonormal columns, returns l, u, s such that q - s = l * u. ...
q = q.assemble() m, b = q.shape[0], q.shape[1] S = np.zeros(b) q_work = np.copy(q) for i in range(b): S[i] = -1 * np.sign(q_work[i, i]) q_work[i, i] -= S[i] # Scale ith column of L by diagonal element. q_work[(i + 1):m, i] /= q_work[i, i] # Perform Schur co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _naturalize(string): """Provides a natural representation for string for nice sorting."""
splits = re.split("([0-9]+)", string) return [int(text) if text.isdigit() else text.lower() for text in splits]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_newest_ckpt(ckpt_dir): """Returns path to most recently modified checkpoint."""
full_paths = [ os.path.join(ckpt_dir, fname) for fname in os.listdir(ckpt_dir) if fname.startswith("experiment_state") and fname.endswith(".json") ] return max(full_paths)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkpoint(self): """Saves execution state to `self._metadata_checkpoint_dir`. Overwrites the current session checkpoint, which starts when self is instantia...
if not self._metadata_checkpoint_dir: return metadata_checkpoint_dir = self._metadata_checkpoint_dir if not os.path.exists(metadata_checkpoint_dir): os.makedirs(metadata_checkpoint_dir) runner_state = { "checkpoints": list( self.trial_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restore(cls, metadata_checkpoint_dir, search_alg=None, scheduler=None, trial_executor=None): """Restores all checkpointed trials from previous run. Requires ...
newest_ckpt_path = _find_newest_ckpt(metadata_checkpoint_dir) with open(newest_ckpt_path, "r") as f: runner_state = json.load(f, cls=_TuneFunctionDecoder) logger.warning("".join([ "Attempting to resume experiment from {}. ".format( metadata_checkpoint_d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_finished(self): """Returns whether all trials have finished running."""
if self._total_time > self._global_time_limit: logger.warning("Exceeded global time limit {} / {}".format( self._total_time, self._global_time_limit)) return True trials_done = all(trial.is_finished() for trial in self._trials) return trials_done and se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def step(self): """Runs one step of the trial event loop. Callers should typically run this method repeatedly in a loop. They may inspect or modify the runner's ...
if self.is_finished(): raise TuneError("Called step when all trials finished?") with warn_if_slow("on_step_begin"): self.trial_executor.on_step_begin() next_trial = self._get_next_trial() # blocking if next_trial is not None: with warn_if_slow("start...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_trial(self, trial): """Adds a new trial to this TrialRunner. Trials may be added at any time. Args: trial (Trial): Trial to queue. """
trial.set_verbose(self._verbose) self._trials.append(trial) with warn_if_slow("scheduler.on_trial_add"): self._scheduler_alg.on_trial_add(self, trial) self.trial_executor.try_checkpoint_metadata(trial)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_next_trial(self): """Replenishes queue. Blocks if all trials queued have finished, but search algorithm is still not finished. """
trials_done = all(trial.is_finished() for trial in self._trials) wait_for_trial = trials_done and not self._search_alg.is_finished() self._update_trial_queue(blocking=wait_for_trial) with warn_if_slow("choose_trial_to_run"): trial = self._scheduler_alg.choose_trial_to_run(se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _checkpoint_trial_if_needed(self, trial): """Checkpoints trial based off trial.last_result."""
if trial.should_checkpoint(): # Save trial runtime if possible if hasattr(trial, "runner") and trial.runner: self.trial_executor.save(trial, storage=Checkpoint.DISK) self.trial_executor.try_checkpoint_metadata(trial)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _try_recover(self, trial, error_msg): """Tries to recover trial. Notifies SearchAlgorithm and Scheduler if failure to recover. Args: trial (Trial): Trial to...
try: self.trial_executor.stop_trial( trial, error=error_msg is not None, error_msg=error_msg, stop_logger=False) trial.result_logger.flush() if self.trial_executor.has_resources(trial.resources): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _requeue_trial(self, trial): """Notification to TrialScheduler and requeue trial. This does not notify the SearchAlgorithm because the function evaluation is...
self._scheduler_alg.on_trial_error(self, trial) self.trial_executor.set_status(trial, Trial.PENDING) with warn_if_slow("scheduler.on_trial_add"): self._scheduler_alg.on_trial_add(self, trial)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_trial_queue(self, blocking=False, timeout=600): """Adds next trials to queue if possible. Note that the timeout is currently unexposed to the user. A...
trials = self._search_alg.next_trials() if blocking and not trials: start = time.time() # Checking `is_finished` instead of _search_alg.is_finished # is fine because blocking only occurs if all trials are # finished and search_algorithm is not yet finishe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop_trial(self, trial): """Stops trial. Trials may be stopped at any time. If trial is in state PENDING or PAUSED, calls `on_trial_remove` for scheduler and...
error = False error_msg = None if trial.status in [Trial.ERROR, Trial.TERMINATED]: return elif trial.status in [Trial.PENDING, Trial.PAUSED]: self._scheduler_alg.on_trial_remove(self, trial) self._search_alg.on_trial_complete( trial.t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_func(func, *args, **kwargs): """Helper function for running examples"""
ray.init() func = ray.remote(func) # NOTE: kwargs not allowed for now result = ray.get(func.remote(*args)) # Inspect the stack to get calling example caller = inspect.stack()[1][3] print("%s: %s" % (caller, str(result))) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def example6(): """Cython simple class"""
ray.init() cls = ray.remote(cyth.simple_class) a1 = cls.remote() a2 = cls.remote() result1 = ray.get(a1.increment.remote()) result2 = ray.get(a2.increment.remote()) print(result1, result2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _adjust_nstep(n_step, gamma, obs, actions, rewards, new_obs, dones): """Rewrites the given trajectory fragments to encode n-step rewards. reward[i] = ( rewar...
assert not any(dones[:-1]), "Unexpected done in middle of trajectory" traj_length = len(rewards) for i in range(traj_length): for j in range(1, n_step): if i + j < traj_length: new_obs[i] = new_obs[i + j] dones[i] = dones[i + j] rewards[...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _minimize_and_clip(optimizer, objective, var_list, clip_val=10): """Minimized `objective` using `optimizer` w.r.t. variables in `var_list` while ensure the n...
gradients = optimizer.compute_gradients(objective, var_list=var_list) for i, (grad, var) in enumerate(gradients): if grad is not None: gradients[i] = (tf.clip_by_norm(grad, clip_val), var) return gradients
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _scope_vars(scope, trainable_only=False): """ Get variables inside a scope The scope can be specified as a string Parameters scope: str or VariableScope scop...
return tf.get_collection( tf.GraphKeys.TRAINABLE_VARIABLES if trainable_only else tf.GraphKeys.VARIABLES, scope=scope if isinstance(scope, str) else scope.name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_custom_getter(self): """Returns a custom getter that this class's methods must be called All methods of this class must be called under a variable scope ...
def inner_custom_getter(getter, *args, **kwargs): if not self.use_tf_layers: return getter(*args, **kwargs) requested_dtype = kwargs["dtype"] if not (requested_dtype == tf.float32 and self.variable_dtype == tf.float16): kw...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def switch_to_aux_top_layer(self): """Context that construct cnn in the auxiliary arm."""
if self.aux_top_layer is None: raise RuntimeError("Empty auxiliary top layer in the network.") saved_top_layer = self.top_layer saved_top_size = self.top_size self.top_layer = self.aux_top_layer self.top_size = self.aux_top_size yield self.aux_top_lay...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pool(self, pool_name, pool_function, k_height, k_width, d_height, d_width, mode, input_layer, num_channels_in): """Construct a pooling layer."""
if input_layer is None: input_layer = self.top_layer else: self.top_size = num_channels_in name = pool_name + str(self.counts[pool_name]) self.counts[pool_name] += 1 if self.use_tf_layers: pool = pool_function( input_layer, [k_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mpool(self, k_height, k_width, d_height=2, d_width=2, mode="VALID", input_layer=None, num_channels_in=None): """Construct a max pooling layer."""
return self._pool("mpool", pooling_layers.max_pooling2d, k_height, k_width, d_height, d_width, mode, input_layer, num_channels_in)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def apool(self, k_height, k_width, d_height=2, d_width=2, mode="VALID", input_layer=None, num_channels_in=None): """Construct an average pooling layer."""
return self._pool("apool", pooling_layers.average_pooling2d, k_height, k_width, d_height, d_width, mode, input_layer, num_channels_in)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _batch_norm_without_layers(self, input_layer, decay, use_scale, epsilon): """Batch normalization on `input_layer` without tf.layers."""
shape = input_layer.shape num_channels = shape[3] if self.data_format == "NHWC" else shape[1] beta = self.get_variable( "beta", [num_channels], tf.float32, tf.float32, initializer=tf.zeros_initializer()) if use_scale: gamma = s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lrn(self, depth_radius, bias, alpha, beta): """Adds a local response normalization layer."""
name = "lrn" + str(self.counts["lrn"]) self.counts["lrn"] += 1 self.top_layer = tf.nn.lrn( self.top_layer, depth_radius, bias, alpha, beta, name=name) return self.top_layer
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _internal_kv_get(key): """Fetch the value of a binary key."""
worker = ray.worker.get_global_worker() if worker.mode == ray.worker.LOCAL_MODE: return _local.get(key) return worker.redis_client.hget(key, "value")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _internal_kv_put(key, value, overwrite=False): """Globally associates a value with a given binary key. This only has an effect if the key does not already ha...
worker = ray.worker.get_global_worker() if worker.mode == ray.worker.LOCAL_MODE: exists = key in _local if not exists or overwrite: _local[key] = value return exists if overwrite: updated = worker.redis_client.hset(key, "value", value) else: updated...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init(self, aggregators): """Deferred init so that we can pass in previously created workers."""
assert len(aggregators) == self.num_aggregation_workers, aggregators if len(self.remote_evaluators) < self.num_aggregation_workers: raise ValueError( "The number of aggregation workers should not exceed the " "number of total evaluation workers ({} vs {})".f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def free(object_ids, local_only=False, delete_creating_tasks=False): """Free a list of IDs from object stores. This function is a low-level API which should be u...
worker = ray.worker.get_global_worker() if ray.worker._mode() == ray.worker.LOCAL_MODE: return if isinstance(object_ids, ray.ObjectID): object_ids = [object_ids] if not isinstance(object_ids, list): raise TypeError("free() expects a list of ObjectID, got {}".format( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """Start the collector worker thread. If running in standalone mode, the current thread will wait until the collector thread ends. """
self.collector.start() if self.standalone: self.collector.join()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_logger(cls, log_level): """Initialize logger settings."""
logger = logging.getLogger("AutoMLBoard") handler = logging.StreamHandler() formatter = logging.Formatter("[%(levelname)s %(asctime)s] " "%(filename)s: %(lineno)d " "%(message)s") handler.setFormatter(formatter...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """Run the main event loop for collector thread. In each round the collector traverse the results log directory and reload trial information from ...
self._initialize() self._do_collect() while not self._is_finished: time.sleep(self._reload_interval) self._do_collect() self.logger.info("Collector stopped.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _initialize(self): """Initialize collector worker thread, Log path will be checked first. Records in DB backend will be cleared. """
if not os.path.exists(self._logdir): raise CollectorError("Log directory %s not exists" % self._logdir) self.logger.info("Collector started, taking %s as parent directory" "for all job logs." % self._logdir) # clear old records JobRecord.objects.fi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sync_job_info(self, job_name): """Load information of the job with the given job name. 1. Traverse each experiment sub-directory and sync information for eac...
job_path = os.path.join(self._logdir, job_name) if job_name not in self._monitored_jobs: self._create_job_info(job_path) self._monitored_jobs.add(job_name) else: self._update_job_info(job_path) expr_dirs = filter(lambda d: os.path.isdir(os.path.join...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sync_trial_info(self, job_path, expr_dir_name): """Load information of the trial from the given experiment directory. Create or update the trial information,...
expr_name = expr_dir_name[-8:] expr_path = os.path.join(job_path, expr_dir_name) if expr_name not in self._monitored_trials: self._create_trial_info(expr_path) self._monitored_trials.add(expr_name) else: self._update_trial_info(expr_path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_job_info(self, job_dir): """Create information for given job. Meta file will be loaded if exists, and the job information will be saved in db backend...
meta = self._build_job_meta(job_dir) self.logger.debug("Create job: %s" % meta) job_record = JobRecord.from_json(meta) job_record.save()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_job_info(cls, job_dir): """Update information for given job. Meta file will be loaded if exists, and the job information in in db backend will be upd...
meta_file = os.path.join(job_dir, JOB_META_FILE) meta = parse_json(meta_file) if meta: logging.debug("Update job info for %s" % meta["job_id"]) JobRecord.objects \ .filter(job_id=meta["job_id"]) \ .update(end_time=timestamp2date(meta["end...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_trial_info(self, expr_dir): """Create information for given trial. Meta file will be loaded if exists, and the trial information will be saved in db ...
meta = self._build_trial_meta(expr_dir) self.logger.debug("Create trial for %s" % meta) trial_record = TrialRecord.from_json(meta) trial_record.save()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_trial_info(self, expr_dir): """Update information for given trial. Meta file will be loaded if exists, and the trial information in db backend will b...
trial_id = expr_dir[-8:] meta_file = os.path.join(expr_dir, EXPR_META_FILE) meta = parse_json(meta_file) result_file = os.path.join(expr_dir, EXPR_RESULT_FILE) offset = self._result_offsets.get(trial_id, 0) results, new_offset = parse_multiple_json(result_file, offset)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_job_meta(cls, job_dir): """Build meta file for job. Args: job_dir (str): Directory path of the job. Return: A dict of job meta info. """
meta_file = os.path.join(job_dir, JOB_META_FILE) meta = parse_json(meta_file) if not meta: job_name = job_dir.split("/")[-1] user = os.environ.get("USER", None) meta = { "job_id": job_name, "job_name": job_name, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_trial_meta(cls, expr_dir): """Build meta file for trial. Args: expr_dir (str): Directory path of the experiment. Return: A dict of trial meta info. "...
meta_file = os.path.join(expr_dir, EXPR_META_FILE) meta = parse_json(meta_file) if not meta: job_id = expr_dir.split("/")[-2] trial_id = expr_dir[-8:] params = parse_json(os.path.join(expr_dir, EXPR_PARARM_FILE)) meta = { "trial_i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_results(self, results, trial_id): """Add a list of results into db. Args: results (list): A list of json results. trial_id (str): Id of the trial. """
for result in results: self.logger.debug("Appending result: %s" % result) result["trial_id"] = trial_id result_record = ResultRecord.from_json(result) result_record.save()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_time_dimension(padded_inputs, seq_lens): """Adds a time dimension to padded inputs. Arguments: padded_inputs (Tensor): a padded batch of sequences. That...
# Sequence lengths have to be specified for LSTM batch inputs. The # input batch must be padded to the max seq length given here. That is, # batch_size == len(seq_lens) * max(seq_lens) padded_batch_size = tf.shape(padded_inputs)[0] max_seq_len = padded_batch_size // tf.shape(seq_lens)[0] # Dy...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chop_into_sequences(episode_ids, unroll_ids, agent_indices, feature_columns, state_columns, max_seq_len, dynamic_max=True, _extra_padding=0): """Truncate and...
prev_id = None seq_lens = [] seq_len = 0 unique_ids = np.add( np.add(episode_ids, agent_indices), np.array(unroll_ids) << 32) for uid in unique_ids: if (prev_id is not None and uid != prev_id) or \ seq_len >= max_seq_len: seq_lens.append(seq_len)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def explore(config, mutations, resample_probability, custom_explore_fn): """Return a config perturbed as specified. Args: config (dict): Original hyperparameter...
new_config = copy.deepcopy(config) for key, distribution in mutations.items(): if isinstance(distribution, dict): new_config.update({ key: explore(config[key], mutations[key], resample_probability, None) }) elif isinstance(dis...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_experiment_tag(orig_tag, config, mutations): """Appends perturbed params to the trial name to show in the console."""
resolved_vars = {} for k in mutations.keys(): resolved_vars[("config", k)] = config[k] return "{}@perturbed[{}]".format(orig_tag, format_vars(resolved_vars))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _exploit(self, trial_executor, trial, trial_to_clone): """Transfers perturbed state from trial_to_clone -> trial. If specified, also logs the updated hyperpa...
trial_state = self._trial_state[trial] new_state = self._trial_state[trial_to_clone] if not new_state.last_checkpoint: logger.info("[pbt]: no checkpoint for trial." " Skip exploit for Trial {}".format(trial)) return new_config = explore(t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _quantiles(self): """Returns trials in the lower and upper `quantile` of the population. If there is not enough data to compute this, returns empty lists."""
trials = [] for trial, state in self._trial_state.items(): if state.last_score is not None and not trial.is_finished(): trials.append(trial) trials.sort(key=lambda t: self._trial_state[t].last_score) if len(trials) <= 1: return [], [] el...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_layers(self, inputs, num_outputs, options): """Process the flattened inputs. Note that dict inputs will be flattened into a vector. To define a model ...
hiddens = options.get("fcnet_hiddens") activation = get_activation_fn(options.get("fcnet_activation")) with tf.name_scope("fc_net"): i = 1 last_layer = inputs for size in hiddens: label = "fc{}".format(i) last_layer = slim.fu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def with_base_config(base_config, extra_config): """Returns the given config dict merged with a base agent conf."""
config = copy.deepcopy(base_config) config.update(extra_config) return config
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_agent_class(alg): """Returns the class of a known agent given its name."""
try: return _get_agent_class(alg) except ImportError: from ray.rllib.agents.mock import _agent_import_failed return _agent_import_failed(traceback.format_exc())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def determine_ip_address(): """Return the first IP address for an ethernet interface on the system."""
addrs = [ x.address for k, v in psutil.net_if_addrs().items() if k[0] == "e" for x in v if x.family == AddressFamily.AF_INET ] return addrs[0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """Run the reporter."""
while True: try: self.perform_iteration() except Exception: traceback.print_exc() pass time.sleep(ray_constants.REPORTER_UPDATE_INTERVAL_MS / 1000)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_serializable(cls): """Throws an exception if Ray cannot serialize this class efficiently. Args: cls (type): The class to be serialized. Raises: Except...
if is_named_tuple(cls): # This case works. return if not hasattr(cls, "__new__"): print("The class {} does not have a '__new__' attribute and is " "probably an old-stye class. Please make it a new-style class " "by inheriting from 'object'.") raise Ra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_named_tuple(cls): """Return True if cls is a namedtuple and False otherwise."""
b = cls.__bases__ if len(b) != 1 or b[0] != tuple: return False f = getattr(cls, "_fields", None) if not isinstance(f, tuple): return False return all(type(n) == str for n in f)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_trainable(name, trainable): """Register a trainable function or class. Args: name (str): Name to register. trainable (obj): Function or tune.Train...
from ray.tune.trainable import Trainable from ray.tune.function_runner import wrap_function if isinstance(trainable, type): logger.debug("Detected class for trainable.") elif isinstance(trainable, FunctionType): logger.debug("Detected function for trainable.") trainable = wrap...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_env(name, env_creator): """Register a custom environment for use with RLlib. Args: name (str): Name to register. env_creator (obj): Function that ...
if not isinstance(env_creator, FunctionType): raise TypeError("Second argument must be a function.", env_creator) _global_registry.register(ENV_CREATOR, name, env_creator)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_learner_stats(grad_info): """Return optimization stats reported from the policy graph. Example: """
if LEARNER_STATS_KEY in grad_info: return grad_info[LEARNER_STATS_KEY] multiagent_stats = {} for k, v in grad_info.items(): if type(v) is dict: if LEARNER_STATS_KEY in v: multiagent_stats[k] = v[LEARNER_STATS_KEY] return multiagent_stats
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collect_metrics(local_evaluator=None, remote_evaluators=[], timeout_seconds=180): """Gathers episode metrics from PolicyEvaluator instances."""
episodes, num_dropped = collect_episodes( local_evaluator, remote_evaluators, timeout_seconds=timeout_seconds) metrics = summarize_episodes(episodes, episodes, num_dropped) return metrics
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collect_episodes(local_evaluator=None, remote_evaluators=[], timeout_seconds=180): """Gathers new episodes metrics tuples from the given evaluators."""
pending = [ a.apply.remote(lambda ev: ev.get_metrics()) for a in remote_evaluators ] collected, _ = ray.wait( pending, num_returns=len(pending), timeout=timeout_seconds * 1.0) num_metric_batches_dropped = len(pending) - len(collected) if pending and len(collected) == 0: rai...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _partition(episodes): """Divides metrics data into true rollouts vs off-policy estimates."""
from ray.rllib.evaluation.sampler import RolloutMetrics rollouts, estimates = [], [] for e in episodes: if isinstance(e, RolloutMetrics): rollouts.append(e) elif isinstance(e, OffPolicyEstimate): estimates.append(e) else: raise ValueError("Unkno...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_status(self, trial, status): """Sets status and checkpoints metadata if needed. Only checkpoints metadata if trial status is a terminal condition. PENDIN...
trial.status = status if status in [Trial.TERMINATED, Trial.ERROR]: self.try_checkpoint_metadata(trial)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def try_checkpoint_metadata(self, trial): """Checkpoints metadata. Args: trial (Trial): Trial to checkpoint. """
if trial._checkpoint.storage == Checkpoint.MEMORY: logger.debug("Not saving data for trial w/ memory checkpoint.") return try: logger.debug("Saving trial metadata.") self._cached_trial_state[trial.trial_id] = trial.__getstate__() except Exception:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unpause_trial(self, trial): """Sets PAUSED trial to pending to allow scheduler to start."""
assert trial.status == Trial.PAUSED, trial.status self.set_status(trial, Trial.PENDING)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resume_trial(self, trial): """Resumes PAUSED trials. This is a blocking call."""
assert trial.status == Trial.PAUSED, trial.status self.start_trial(trial)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_trial_complete(self, trial_id, result=None, error=False, early_terminated=False): """Passes the result to Nevergrad unless early terminated or errored. Th...
ng_trial_info = self._live_trial_mapping.pop(trial_id) if result: self._nevergrad_opt.tell(ng_trial_info, -result[self._reward_attr])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self): """Start the import thread."""
self.t = threading.Thread(target=self._run, name="ray_import_thread") # Making the thread a daemon causes it to exit # when the main thread exits. self.t.daemon = True self.t.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _process_key(self, key): """Process the given export key from redis."""
# Handle the driver case first. if self.mode != ray.WORKER_MODE: if key.startswith(b"FunctionsToRun"): with profiling.profile("fetch_and_run_function"): self.fetch_and_execute_function_to_run(key) # Return because FunctionsToRun are the only t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_and_execute_function_to_run(self, key): """Run on arbitrary function on the worker."""
(driver_id, serialized_function, run_on_other_drivers) = self.redis_client.hmget( key, ["driver_id", "function", "run_on_other_drivers"]) if (utils.decode(run_on_other_drivers) == "False" and self.worker.mode == ray.SCRIPT_MODE and driver_id != sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clip_action(action, space): """Called to clip actions to the specified range of this policy. Arguments: action: Single action. space: Action space the action...
if isinstance(space, gym.spaces.Box): return np.clip(action, space.low, space.high) elif isinstance(space, gym.spaces.Tuple): if type(action) not in (tuple, list): raise ValueError("Expected tuple space for actions {}: {}".format( action, space)) out = [] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_trial_complete(self, trial_id, result=None, error=False, early_terminated=False): """Passes the result to skopt unless early terminated or errored. The re...
skopt_trial_info = self._live_trial_mapping.pop(trial_id) if result: self._skopt_opt.tell(skopt_trial_info, -result[self._reward_attr])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def address_to_ip(address): """Convert a hostname to a numerical IP addresses in an address. This should be a no-op if address already contains an actual numeric...
address_parts = address.split(":") ip_address = socket.gethostbyname(address_parts[0]) # Make sure localhost isn't resolved to the loopback ip if ip_address == "127.0.0.1": ip_address = get_node_ip_address() return ":".join([ip_address] + address_parts[1:])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_node_ip_address(address="8.8.8.8:53"): """Determine the IP address of the local node. Args: address (str): The IP address and port of any known live ser...
ip_address, port = address.split(":") s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: # This command will raise an exception if there is no internet # connection. s.connect((ip_address, int(port))) node_ip_address = s.getsockname()[0] except Exception as e: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_redis_client(redis_address, password=None): """Create a Redis client. Args: The IP address, port, and password of the Redis server. Returns: A Redis c...
redis_ip_address, redis_port = redis_address.split(":") # For this command to work, some other client (on the same machine # as Redis) must have run "CONFIG SET protected-mode no". return redis.StrictRedis( host=redis_ip_address, port=int(redis_port), password=password)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait_for_redis_to_start(redis_ip_address, redis_port, password=None, num_retries=5): """Wait for a Redis server to be available. This is accomplished by crea...
redis_client = redis.StrictRedis( host=redis_ip_address, port=redis_port, password=password) # Wait for the Redis server to start. counter = 0 while counter < num_retries: try: # Run some random command and see if it worked. logger.info( "Waiting ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _autodetect_num_gpus(): """Attempt to detect the number of GPUs on this machine. TODO(rkn): This currently assumes Nvidia GPUs and Linux. Returns: The numbe...
proc_gpus_path = "/proc/driver/nvidia/gpus" if os.path.isdir(proc_gpus_path): return len(os.listdir(proc_gpus_path)) return 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compute_version_info(): """Compute the versions of Python, pyarrow, and Ray. Returns: A tuple containing the version information. """
ray_version = ray.__version__ python_version = ".".join(map(str, sys.version_info[:3])) pyarrow_version = pyarrow.__version__ return ray_version, python_version, pyarrow_version
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_version_info(redis_client): """Check if various version info of this process is correct. This will be used to detect if workers or drivers are started ...
redis_reply = redis_client.get("VERSION_INFO") # Don't do the check if there is no version information in Redis. This # is to make it easier to do things like start the processes by hand. if redis_reply is None: return true_version_info = tuple(json.loads(ray.utils.decode(redis_reply))) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _start_redis_instance(executable, modules, port=None, redis_max_clients=None, num_retries=20, stdout_file=None, stderr_file=None, password=None, redis_max_mem...
assert os.path.isfile(executable) for module in modules: assert os.path.isfile(module) counter = 0 if port is not None: # If a port is specified, then try only once to connect. # This ensures that we will use the given port. num_retries = 1 else: port = new_p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_log_monitor(redis_address, logs_dir, stdout_file=None, stderr_file=None, redis_password=None): """Start a log monitor process. Args: redis_address (str...
log_monitor_filepath = os.path.join( os.path.dirname(os.path.abspath(__file__)), "log_monitor.py") command = [ sys.executable, "-u", log_monitor_filepath, "--redis-address={}".format(redis_address), "--logs-dir={}".format(logs_dir) ] if redis_password: command +=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_reporter(redis_address, stdout_file=None, stderr_file=None, redis_password=None): """Start a reporter process. Args: redis_address (str): The address ...
reporter_filepath = os.path.join( os.path.dirname(os.path.abspath(__file__)), "reporter.py") command = [ sys.executable, "-u", reporter_filepath, "--redis-address={}".format(redis_address) ] if redis_password: command += ["--redis-password", redis_password] try: ...