partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
query_job
Rest API to query the job info, with the given job_id. The url pattern should be like this: curl http://<server>:<port>/query_job?job_id=<job_id> The response may be: { "running_trials": 0, "start_time": "2018-07-19 20:49:40", "current_round": 1, "failed_trials": 0, "best_trial_id": "2067R2ZD", "name": "asynchyperband_test", "job_id": "asynchyperband_test", "user": "Grady", "type": "RAY TUNE", "total_trials": 4, "end_time": "2018-07-19 20:50:10", "progress": 100, "success_trials": 4 }
python/ray/tune/automlboard/frontend/query.py
def query_job(request): """Rest API to query the job info, with the given job_id. The url pattern should be like this: curl http://<server>:<port>/query_job?job_id=<job_id> The response may be: { "running_trials": 0, "start_time": "2018-07-19 20:49:40", "current_round": 1, "failed_trials": 0, "best_trial_id": "2067R2ZD", "name": "asynchyperband_test", "job_id": "asynchyperband_test", "user": "Grady", "type": "RAY TUNE", "total_trials": 4, "end_time": "2018-07-19 20:50:10", "progress": 100, "success_trials": 4 } """ job_id = request.GET.get("job_id") jobs = JobRecord.objects.filter(job_id=job_id) trials = TrialRecord.objects.filter(job_id=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 total_num == 0: progress = 0 else: progress = int(float(success_num) / total_num * 100) if len(jobs) == 0: resp = "Unkonwn job id %s.\n" % job_id else: job = jobs[0] result = { "job_id": job.job_id, "name": job.name, "user": job.user, "type": job.type, "start_time": job.start_time, "end_time": job.end_time, "success_trials": success_num, "failed_trials": failed_num, "running_trials": running_num, "total_trials": total_num, "best_trial_id": job.best_trial_id, "progress": progress } resp = json.dumps(result) return HttpResponse(resp, content_type="application/json;charset=utf-8")
def query_job(request): """Rest API to query the job info, with the given job_id. The url pattern should be like this: curl http://<server>:<port>/query_job?job_id=<job_id> The response may be: { "running_trials": 0, "start_time": "2018-07-19 20:49:40", "current_round": 1, "failed_trials": 0, "best_trial_id": "2067R2ZD", "name": "asynchyperband_test", "job_id": "asynchyperband_test", "user": "Grady", "type": "RAY TUNE", "total_trials": 4, "end_time": "2018-07-19 20:50:10", "progress": 100, "success_trials": 4 } """ job_id = request.GET.get("job_id") jobs = JobRecord.objects.filter(job_id=job_id) trials = TrialRecord.objects.filter(job_id=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 total_num == 0: progress = 0 else: progress = int(float(success_num) / total_num * 100) if len(jobs) == 0: resp = "Unkonwn job id %s.\n" % job_id else: job = jobs[0] result = { "job_id": job.job_id, "name": job.name, "user": job.user, "type": job.type, "start_time": job.start_time, "end_time": job.end_time, "success_trials": success_num, "failed_trials": failed_num, "running_trials": running_num, "total_trials": total_num, "best_trial_id": job.best_trial_id, "progress": progress } resp = json.dumps(result) return HttpResponse(resp, content_type="application/json;charset=utf-8")
[ "Rest", "API", "to", "query", "the", "job", "info", "with", "the", "given", "job_id", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/frontend/query.py#L14-L71
[ "def", "query_job", "(", "request", ")", ":", "job_id", "=", "request", ".", "GET", ".", "get", "(", "\"job_id\"", ")", "jobs", "=", "JobRecord", ".", "objects", ".", "filter", "(", "job_id", "=", "job_id", ")", "trials", "=", "TrialRecord", ".", "obje...
4eade036a0505e244c976f36aaa2d64386b5129b
train
query_trial
Rest API to query the trial info, with the given trial_id. The url pattern should be like this: curl http://<server>:<port>/query_trial?trial_id=<trial_id> The response may be: { "app_url": "None", "trial_status": "TERMINATED", "params": {'a': 1, 'b': 2}, "job_id": "asynchyperband_test", "end_time": "2018-07-19 20:49:44", "start_time": "2018-07-19 20:49:40", "trial_id": "2067R2ZD", }
python/ray/tune/automlboard/frontend/query.py
def query_trial(request): """Rest API to query the trial info, with the given trial_id. The url pattern should be like this: curl http://<server>:<port>/query_trial?trial_id=<trial_id> The response may be: { "app_url": "None", "trial_status": "TERMINATED", "params": {'a': 1, 'b': 2}, "job_id": "asynchyperband_test", "end_time": "2018-07-19 20:49:44", "start_time": "2018-07-19 20:49:40", "trial_id": "2067R2ZD", } """ trial_id = request.GET.get("trial_id") trials = TrialRecord.objects \ .filter(trial_id=trial_id) \ .order_by("-start_time") if len(trials) == 0: resp = "Unkonwn trial id %s.\n" % trials else: trial = trials[0] result = { "trial_id": trial.trial_id, "job_id": trial.job_id, "trial_status": trial.trial_status, "start_time": trial.start_time, "end_time": trial.end_time, "params": trial.params } resp = json.dumps(result) return HttpResponse(resp, content_type="application/json;charset=utf-8")
def query_trial(request): """Rest API to query the trial info, with the given trial_id. The url pattern should be like this: curl http://<server>:<port>/query_trial?trial_id=<trial_id> The response may be: { "app_url": "None", "trial_status": "TERMINATED", "params": {'a': 1, 'b': 2}, "job_id": "asynchyperband_test", "end_time": "2018-07-19 20:49:44", "start_time": "2018-07-19 20:49:40", "trial_id": "2067R2ZD", } """ trial_id = request.GET.get("trial_id") trials = TrialRecord.objects \ .filter(trial_id=trial_id) \ .order_by("-start_time") if len(trials) == 0: resp = "Unkonwn trial id %s.\n" % trials else: trial = trials[0] result = { "trial_id": trial.trial_id, "job_id": trial.job_id, "trial_status": trial.trial_status, "start_time": trial.start_time, "end_time": trial.end_time, "params": trial.params } resp = json.dumps(result) return HttpResponse(resp, content_type="application/json;charset=utf-8")
[ "Rest", "API", "to", "query", "the", "trial", "info", "with", "the", "given", "trial_id", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/frontend/query.py#L74-L110
[ "def", "query_trial", "(", "request", ")", ":", "trial_id", "=", "request", ".", "GET", ".", "get", "(", "\"trial_id\"", ")", "trials", "=", "TrialRecord", ".", "objects", ".", "filter", "(", "trial_id", "=", "trial_id", ")", ".", "order_by", "(", "\"-st...
4eade036a0505e244c976f36aaa2d64386b5129b
train
MedianStoppingRule.on_trial_result
Callback for early stopping. This stopping rule stops a running trial if the trial's best objective value by step `t` is strictly worse than the median of the running averages of all completed trials' objectives reported up to step `t`.
python/ray/tune/schedulers/median_stopping_rule.py
def on_trial_result(self, trial_runner, trial, result): """Callback for early stopping. This stopping rule stops a running trial if the trial's best objective value by step `t` is strictly worse than the median of the running averages of all completed trials' objectives reported up to step `t`. """ if trial in self._stopped_trials: assert not self._hard_stop return TrialScheduler.CONTINUE # fall back to FIFO time = result[self._time_attr] self._results[trial].append(result) median_result = self._get_median_result(time) best_result = self._best_result(trial) if self._verbose: logger.info("Trial {} best res={} vs median res={} at t={}".format( trial, best_result, median_result, time)) if best_result < median_result and time > self._grace_period: if self._verbose: logger.info("MedianStoppingRule: " "early stopping {}".format(trial)) self._stopped_trials.add(trial) if self._hard_stop: return TrialScheduler.STOP else: return TrialScheduler.PAUSE else: return TrialScheduler.CONTINUE
def on_trial_result(self, trial_runner, trial, result): """Callback for early stopping. This stopping rule stops a running trial if the trial's best objective value by step `t` is strictly worse than the median of the running averages of all completed trials' objectives reported up to step `t`. """ if trial in self._stopped_trials: assert not self._hard_stop return TrialScheduler.CONTINUE # fall back to FIFO time = result[self._time_attr] self._results[trial].append(result) median_result = self._get_median_result(time) best_result = self._best_result(trial) if self._verbose: logger.info("Trial {} best res={} vs median res={} at t={}".format( trial, best_result, median_result, time)) if best_result < median_result and time > self._grace_period: if self._verbose: logger.info("MedianStoppingRule: " "early stopping {}".format(trial)) self._stopped_trials.add(trial) if self._hard_stop: return TrialScheduler.STOP else: return TrialScheduler.PAUSE else: return TrialScheduler.CONTINUE
[ "Callback", "for", "early", "stopping", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/schedulers/median_stopping_rule.py#L56-L85
[ "def", "on_trial_result", "(", "self", ",", "trial_runner", ",", "trial", ",", "result", ")", ":", "if", "trial", "in", "self", ".", "_stopped_trials", ":", "assert", "not", "self", ".", "_hard_stop", "return", "TrialScheduler", ".", "CONTINUE", "# fall back t...
4eade036a0505e244c976f36aaa2d64386b5129b
train
MedianStoppingRule.on_trial_remove
Marks trial as completed if it is paused and has previously ran.
python/ray/tune/schedulers/median_stopping_rule.py
def on_trial_remove(self, trial_runner, trial): """Marks trial as completed if it is paused and has previously ran.""" if trial.status is Trial.PAUSED and trial in self._results: self._completed_trials.add(trial)
def on_trial_remove(self, trial_runner, trial): """Marks trial as completed if it is paused and has previously ran.""" if trial.status is Trial.PAUSED and trial in self._results: self._completed_trials.add(trial)
[ "Marks", "trial", "as", "completed", "if", "it", "is", "paused", "and", "has", "previously", "ran", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/schedulers/median_stopping_rule.py#L91-L94
[ "def", "on_trial_remove", "(", "self", ",", "trial_runner", ",", "trial", ")", ":", "if", "trial", ".", "status", "is", "Trial", ".", "PAUSED", "and", "trial", "in", "self", ".", "_results", ":", "self", ".", "_completed_trials", ".", "add", "(", "trial"...
4eade036a0505e244c976f36aaa2d64386b5129b
train
JobRecord.from_json
Build a Job instance from a json string.
python/ray/tune/automlboard/models/models.py
def from_json(cls, json_info): """Build a Job instance from a json string.""" if json_info is None: return None return JobRecord( job_id=json_info["job_id"], name=json_info["job_name"], user=json_info["user"], type=json_info["type"], start_time=json_info["start_time"])
def from_json(cls, json_info): """Build a Job instance from a json string.""" if json_info is None: return None return JobRecord( job_id=json_info["job_id"], name=json_info["job_name"], user=json_info["user"], type=json_info["type"], start_time=json_info["start_time"])
[ "Build", "a", "Job", "instance", "from", "a", "json", "string", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/models/models.py#L20-L29
[ "def", "from_json", "(", "cls", ",", "json_info", ")", ":", "if", "json_info", "is", "None", ":", "return", "None", "return", "JobRecord", "(", "job_id", "=", "json_info", "[", "\"job_id\"", "]", ",", "name", "=", "json_info", "[", "\"job_name\"", "]", "...
4eade036a0505e244c976f36aaa2d64386b5129b
train
TrialRecord.from_json
Build a Trial instance from a json string.
python/ray/tune/automlboard/models/models.py
def from_json(cls, json_info): """Build a Trial instance from a json string.""" if json_info is None: return None return TrialRecord( trial_id=json_info["trial_id"], job_id=json_info["job_id"], trial_status=json_info["status"], start_time=json_info["start_time"], params=json_info["params"])
def from_json(cls, json_info): """Build a Trial instance from a json string.""" if json_info is None: return None return TrialRecord( trial_id=json_info["trial_id"], job_id=json_info["job_id"], trial_status=json_info["status"], start_time=json_info["start_time"], params=json_info["params"])
[ "Build", "a", "Trial", "instance", "from", "a", "json", "string", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/models/models.py#L48-L57
[ "def", "from_json", "(", "cls", ",", "json_info", ")", ":", "if", "json_info", "is", "None", ":", "return", "None", "return", "TrialRecord", "(", "trial_id", "=", "json_info", "[", "\"trial_id\"", "]", ",", "job_id", "=", "json_info", "[", "\"job_id\"", "]...
4eade036a0505e244c976f36aaa2d64386b5129b
train
ResultRecord.from_json
Build a Result instance from a json string.
python/ray/tune/automlboard/models/models.py
def from_json(cls, json_info): """Build a Result instance from a json string.""" if json_info is None: return None return ResultRecord( trial_id=json_info["trial_id"], timesteps_total=json_info["timesteps_total"], done=json_info.get("done", None), episode_reward_mean=json_info.get("episode_reward_mean", None), mean_accuracy=json_info.get("mean_accuracy", None), mean_loss=json_info.get("mean_loss", None), trainning_iteration=json_info.get("training_iteration", None), timesteps_this_iter=json_info.get("timesteps_this_iter", None), time_this_iter_s=json_info.get("time_this_iter_s", None), time_total_s=json_info.get("time_total_s", None), date=json_info.get("date", None), hostname=json_info.get("hostname", None), node_ip=json_info.get("node_ip", None), config=json_info.get("config", None))
def from_json(cls, json_info): """Build a Result instance from a json string.""" if json_info is None: return None return ResultRecord( trial_id=json_info["trial_id"], timesteps_total=json_info["timesteps_total"], done=json_info.get("done", None), episode_reward_mean=json_info.get("episode_reward_mean", None), mean_accuracy=json_info.get("mean_accuracy", None), mean_loss=json_info.get("mean_loss", None), trainning_iteration=json_info.get("training_iteration", None), timesteps_this_iter=json_info.get("timesteps_this_iter", None), time_this_iter_s=json_info.get("time_this_iter_s", None), time_total_s=json_info.get("time_total_s", None), date=json_info.get("date", None), hostname=json_info.get("hostname", None), node_ip=json_info.get("node_ip", None), config=json_info.get("config", None))
[ "Build", "a", "Result", "instance", "from", "a", "json", "string", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/models/models.py#L80-L98
[ "def", "from_json", "(", "cls", ",", "json_info", ")", ":", "if", "json_info", "is", "None", ":", "return", "None", "return", "ResultRecord", "(", "trial_id", "=", "json_info", "[", "\"trial_id\"", "]", ",", "timesteps_total", "=", "json_info", "[", "\"times...
4eade036a0505e244c976f36aaa2d64386b5129b
train
compute_advantages
Given a rollout, compute its value targets and the advantage. Args: rollout (SampleBatch): SampleBatch of a single trajectory last_r (float): Value estimation for last observation gamma (float): Discount factor. lambda_ (float): Parameter for GAE use_gae (bool): Using Generalized Advantage Estamation Returns: SampleBatch (SampleBatch): Object with experience from rollout and processed rewards.
python/ray/rllib/evaluation/postprocessing.py
def compute_advantages(rollout, last_r, gamma=0.9, lambda_=1.0, use_gae=True): """Given a rollout, compute its value targets and the advantage. Args: rollout (SampleBatch): SampleBatch of a single trajectory last_r (float): Value estimation for last observation gamma (float): Discount factor. lambda_ (float): Parameter for GAE use_gae (bool): Using Generalized Advantage Estamation Returns: SampleBatch (SampleBatch): Object with experience from rollout and processed rewards. """ traj = {} trajsize = len(rollout[SampleBatch.ACTIONS]) for key in rollout: traj[key] = np.stack(rollout[key]) if use_gae: assert SampleBatch.VF_PREDS in rollout, "Values not found!" vpred_t = np.concatenate( [rollout[SampleBatch.VF_PREDS], np.array([last_r])]) delta_t = ( traj[SampleBatch.REWARDS] + gamma * vpred_t[1:] - vpred_t[:-1]) # This formula for the advantage comes # "Generalized Advantage Estimation": https://arxiv.org/abs/1506.02438 traj[Postprocessing.ADVANTAGES] = discount(delta_t, gamma * lambda_) traj[Postprocessing.VALUE_TARGETS] = ( traj[Postprocessing.ADVANTAGES] + traj[SampleBatch.VF_PREDS]).copy().astype(np.float32) else: rewards_plus_v = np.concatenate( [rollout[SampleBatch.REWARDS], np.array([last_r])]) traj[Postprocessing.ADVANTAGES] = discount(rewards_plus_v, gamma)[:-1] # TODO(ekl): support using a critic without GAE traj[Postprocessing.VALUE_TARGETS] = np.zeros_like( traj[Postprocessing.ADVANTAGES]) traj[Postprocessing.ADVANTAGES] = traj[ Postprocessing.ADVANTAGES].copy().astype(np.float32) assert all(val.shape[0] == trajsize for val in traj.values()), \ "Rollout stacked incorrectly!" return SampleBatch(traj)
def compute_advantages(rollout, last_r, gamma=0.9, lambda_=1.0, use_gae=True): """Given a rollout, compute its value targets and the advantage. Args: rollout (SampleBatch): SampleBatch of a single trajectory last_r (float): Value estimation for last observation gamma (float): Discount factor. lambda_ (float): Parameter for GAE use_gae (bool): Using Generalized Advantage Estamation Returns: SampleBatch (SampleBatch): Object with experience from rollout and processed rewards. """ traj = {} trajsize = len(rollout[SampleBatch.ACTIONS]) for key in rollout: traj[key] = np.stack(rollout[key]) if use_gae: assert SampleBatch.VF_PREDS in rollout, "Values not found!" vpred_t = np.concatenate( [rollout[SampleBatch.VF_PREDS], np.array([last_r])]) delta_t = ( traj[SampleBatch.REWARDS] + gamma * vpred_t[1:] - vpred_t[:-1]) # This formula for the advantage comes # "Generalized Advantage Estimation": https://arxiv.org/abs/1506.02438 traj[Postprocessing.ADVANTAGES] = discount(delta_t, gamma * lambda_) traj[Postprocessing.VALUE_TARGETS] = ( traj[Postprocessing.ADVANTAGES] + traj[SampleBatch.VF_PREDS]).copy().astype(np.float32) else: rewards_plus_v = np.concatenate( [rollout[SampleBatch.REWARDS], np.array([last_r])]) traj[Postprocessing.ADVANTAGES] = discount(rewards_plus_v, gamma)[:-1] # TODO(ekl): support using a critic without GAE traj[Postprocessing.VALUE_TARGETS] = np.zeros_like( traj[Postprocessing.ADVANTAGES]) traj[Postprocessing.ADVANTAGES] = traj[ Postprocessing.ADVANTAGES].copy().astype(np.float32) assert all(val.shape[0] == trajsize for val in traj.values()), \ "Rollout stacked incorrectly!" return SampleBatch(traj)
[ "Given", "a", "rollout", "compute", "its", "value", "targets", "and", "the", "advantage", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/evaluation/postprocessing.py#L23-L70
[ "def", "compute_advantages", "(", "rollout", ",", "last_r", ",", "gamma", "=", "0.9", ",", "lambda_", "=", "1.0", ",", "use_gae", "=", "True", ")", ":", "traj", "=", "{", "}", "trajsize", "=", "len", "(", "rollout", "[", "SampleBatch", ".", "ACTIONS", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
Monitor.xray_heartbeat_batch_handler
Handle an xray heartbeat batch message from Redis.
python/ray/monitor.py
def xray_heartbeat_batch_handler(self, unused_channel, data): """Handle an xray heartbeat batch message from Redis.""" gcs_entries = ray.gcs_utils.GcsTableEntry.GetRootAsGcsTableEntry( data, 0) heartbeat_data = gcs_entries.Entries(0) message = (ray.gcs_utils.HeartbeatBatchTableData. GetRootAsHeartbeatBatchTableData(heartbeat_data, 0)) for j in range(message.BatchLength()): heartbeat_message = message.Batch(j) num_resources = heartbeat_message.ResourcesAvailableLabelLength() static_resources = {} dynamic_resources = {} for i in range(num_resources): dyn = heartbeat_message.ResourcesAvailableLabel(i) static = heartbeat_message.ResourcesTotalLabel(i) dynamic_resources[dyn] = ( heartbeat_message.ResourcesAvailableCapacity(i)) static_resources[static] = ( heartbeat_message.ResourcesTotalCapacity(i)) # Update the load metrics for this raylet. client_id = ray.utils.binary_to_hex(heartbeat_message.ClientId()) ip = self.raylet_id_to_ip_map.get(client_id) if ip: self.load_metrics.update(ip, static_resources, dynamic_resources) else: logger.warning( "Monitor: " "could not find ip for client {}".format(client_id))
def xray_heartbeat_batch_handler(self, unused_channel, data): """Handle an xray heartbeat batch message from Redis.""" gcs_entries = ray.gcs_utils.GcsTableEntry.GetRootAsGcsTableEntry( data, 0) heartbeat_data = gcs_entries.Entries(0) message = (ray.gcs_utils.HeartbeatBatchTableData. GetRootAsHeartbeatBatchTableData(heartbeat_data, 0)) for j in range(message.BatchLength()): heartbeat_message = message.Batch(j) num_resources = heartbeat_message.ResourcesAvailableLabelLength() static_resources = {} dynamic_resources = {} for i in range(num_resources): dyn = heartbeat_message.ResourcesAvailableLabel(i) static = heartbeat_message.ResourcesTotalLabel(i) dynamic_resources[dyn] = ( heartbeat_message.ResourcesAvailableCapacity(i)) static_resources[static] = ( heartbeat_message.ResourcesTotalCapacity(i)) # Update the load metrics for this raylet. client_id = ray.utils.binary_to_hex(heartbeat_message.ClientId()) ip = self.raylet_id_to_ip_map.get(client_id) if ip: self.load_metrics.update(ip, static_resources, dynamic_resources) else: logger.warning( "Monitor: " "could not find ip for client {}".format(client_id))
[ "Handle", "an", "xray", "heartbeat", "batch", "message", "from", "Redis", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/monitor.py#L102-L135
[ "def", "xray_heartbeat_batch_handler", "(", "self", ",", "unused_channel", ",", "data", ")", ":", "gcs_entries", "=", "ray", ".", "gcs_utils", ".", "GcsTableEntry", ".", "GetRootAsGcsTableEntry", "(", "data", ",", "0", ")", "heartbeat_data", "=", "gcs_entries", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
Monitor._xray_clean_up_entries_for_driver
Remove this driver's object/task entries from redis. Removes control-state entries of all tasks and task return objects belonging to the driver. Args: driver_id: The driver id.
python/ray/monitor.py
def _xray_clean_up_entries_for_driver(self, driver_id): """Remove this driver's object/task entries from redis. Removes control-state entries of all tasks and task return objects belonging to the driver. Args: driver_id: The driver id. """ xray_task_table_prefix = ( ray.gcs_utils.TablePrefix_RAYLET_TASK_string.encode("ascii")) xray_object_table_prefix = ( ray.gcs_utils.TablePrefix_OBJECT_string.encode("ascii")) task_table_objects = self.state.task_table() driver_id_hex = binary_to_hex(driver_id) driver_task_id_bins = set() for task_id_hex, task_info in task_table_objects.items(): task_table_object = task_info["TaskSpec"] task_driver_id_hex = task_table_object["DriverID"] if driver_id_hex != task_driver_id_hex: # Ignore tasks that aren't from this driver. continue driver_task_id_bins.add(hex_to_binary(task_id_hex)) # Get objects associated with the driver. object_table_objects = self.state.object_table() driver_object_id_bins = set() for object_id, _ in object_table_objects.items(): task_id_bin = ray._raylet.compute_task_id(object_id).binary() if task_id_bin in driver_task_id_bins: driver_object_id_bins.add(object_id.binary()) def to_shard_index(id_bin): return binary_to_object_id(id_bin).redis_shard_hash() % len( self.state.redis_clients) # Form the redis keys to delete. sharded_keys = [[] for _ in range(len(self.state.redis_clients))] for task_id_bin in driver_task_id_bins: sharded_keys[to_shard_index(task_id_bin)].append( xray_task_table_prefix + task_id_bin) for object_id_bin in driver_object_id_bins: sharded_keys[to_shard_index(object_id_bin)].append( xray_object_table_prefix + object_id_bin) # Remove with best effort. for shard_index in range(len(sharded_keys)): keys = sharded_keys[shard_index] if len(keys) == 0: continue redis = self.state.redis_clients[shard_index] num_deleted = redis.delete(*keys) logger.info("Monitor: " "Removed {} dead redis entries of the " "driver from redis shard {}.".format( num_deleted, shard_index)) if num_deleted != len(keys): logger.warning("Monitor: " "Failed to remove {} relevant redis " "entries from redis shard {}.".format( len(keys) - num_deleted, shard_index))
def _xray_clean_up_entries_for_driver(self, driver_id): """Remove this driver's object/task entries from redis. Removes control-state entries of all tasks and task return objects belonging to the driver. Args: driver_id: The driver id. """ xray_task_table_prefix = ( ray.gcs_utils.TablePrefix_RAYLET_TASK_string.encode("ascii")) xray_object_table_prefix = ( ray.gcs_utils.TablePrefix_OBJECT_string.encode("ascii")) task_table_objects = self.state.task_table() driver_id_hex = binary_to_hex(driver_id) driver_task_id_bins = set() for task_id_hex, task_info in task_table_objects.items(): task_table_object = task_info["TaskSpec"] task_driver_id_hex = task_table_object["DriverID"] if driver_id_hex != task_driver_id_hex: # Ignore tasks that aren't from this driver. continue driver_task_id_bins.add(hex_to_binary(task_id_hex)) # Get objects associated with the driver. object_table_objects = self.state.object_table() driver_object_id_bins = set() for object_id, _ in object_table_objects.items(): task_id_bin = ray._raylet.compute_task_id(object_id).binary() if task_id_bin in driver_task_id_bins: driver_object_id_bins.add(object_id.binary()) def to_shard_index(id_bin): return binary_to_object_id(id_bin).redis_shard_hash() % len( self.state.redis_clients) # Form the redis keys to delete. sharded_keys = [[] for _ in range(len(self.state.redis_clients))] for task_id_bin in driver_task_id_bins: sharded_keys[to_shard_index(task_id_bin)].append( xray_task_table_prefix + task_id_bin) for object_id_bin in driver_object_id_bins: sharded_keys[to_shard_index(object_id_bin)].append( xray_object_table_prefix + object_id_bin) # Remove with best effort. for shard_index in range(len(sharded_keys)): keys = sharded_keys[shard_index] if len(keys) == 0: continue redis = self.state.redis_clients[shard_index] num_deleted = redis.delete(*keys) logger.info("Monitor: " "Removed {} dead redis entries of the " "driver from redis shard {}.".format( num_deleted, shard_index)) if num_deleted != len(keys): logger.warning("Monitor: " "Failed to remove {} relevant redis " "entries from redis shard {}.".format( len(keys) - num_deleted, shard_index))
[ "Remove", "this", "driver", "s", "object", "/", "task", "entries", "from", "redis", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/monitor.py#L137-L199
[ "def", "_xray_clean_up_entries_for_driver", "(", "self", ",", "driver_id", ")", ":", "xray_task_table_prefix", "=", "(", "ray", ".", "gcs_utils", ".", "TablePrefix_RAYLET_TASK_string", ".", "encode", "(", "\"ascii\"", ")", ")", "xray_object_table_prefix", "=", "(", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
Monitor.xray_driver_removed_handler
Handle a notification that a driver has been removed. Args: unused_channel: The message channel. data: The message data.
python/ray/monitor.py
def xray_driver_removed_handler(self, unused_channel, data): """Handle a notification that a driver has been removed. Args: unused_channel: The message channel. data: The message data. """ gcs_entries = ray.gcs_utils.GcsTableEntry.GetRootAsGcsTableEntry( data, 0) driver_data = gcs_entries.Entries(0) message = ray.gcs_utils.DriverTableData.GetRootAsDriverTableData( driver_data, 0) driver_id = message.DriverId() logger.info("Monitor: " "XRay Driver {} has been removed.".format( binary_to_hex(driver_id))) self._xray_clean_up_entries_for_driver(driver_id)
def xray_driver_removed_handler(self, unused_channel, data): """Handle a notification that a driver has been removed. Args: unused_channel: The message channel. data: The message data. """ gcs_entries = ray.gcs_utils.GcsTableEntry.GetRootAsGcsTableEntry( data, 0) driver_data = gcs_entries.Entries(0) message = ray.gcs_utils.DriverTableData.GetRootAsDriverTableData( driver_data, 0) driver_id = message.DriverId() logger.info("Monitor: " "XRay Driver {} has been removed.".format( binary_to_hex(driver_id))) self._xray_clean_up_entries_for_driver(driver_id)
[ "Handle", "a", "notification", "that", "a", "driver", "has", "been", "removed", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/monitor.py#L201-L217
[ "def", "xray_driver_removed_handler", "(", "self", ",", "unused_channel", ",", "data", ")", ":", "gcs_entries", "=", "ray", ".", "gcs_utils", ".", "GcsTableEntry", ".", "GetRootAsGcsTableEntry", "(", "data", ",", "0", ")", "driver_data", "=", "gcs_entries", ".",...
4eade036a0505e244c976f36aaa2d64386b5129b
train
Monitor.process_messages
Process all messages ready in the subscription channels. This reads messages from the subscription channels and calls the appropriate handlers until there are no messages left. Args: max_messages: The maximum number of messages to process before returning.
python/ray/monitor.py
def process_messages(self, max_messages=10000): """Process all messages ready in the subscription channels. This reads messages from the subscription channels and calls the appropriate handlers until there are no messages left. Args: max_messages: The maximum number of messages to process before returning. """ subscribe_clients = [self.primary_subscribe_client] for subscribe_client in subscribe_clients: for _ in range(max_messages): message = subscribe_client.get_message() if message is None: # Continue on to the next subscribe client. break # Parse the message. channel = message["channel"] data = message["data"] # Determine the appropriate message handler. if channel == ray.gcs_utils.XRAY_HEARTBEAT_BATCH_CHANNEL: # Similar functionality as raylet info channel message_handler = self.xray_heartbeat_batch_handler elif channel == ray.gcs_utils.XRAY_DRIVER_CHANNEL: # Handles driver death. message_handler = self.xray_driver_removed_handler else: raise Exception("This code should be unreachable.") # Call the handler. message_handler(channel, data)
def process_messages(self, max_messages=10000): """Process all messages ready in the subscription channels. This reads messages from the subscription channels and calls the appropriate handlers until there are no messages left. Args: max_messages: The maximum number of messages to process before returning. """ subscribe_clients = [self.primary_subscribe_client] for subscribe_client in subscribe_clients: for _ in range(max_messages): message = subscribe_client.get_message() if message is None: # Continue on to the next subscribe client. break # Parse the message. channel = message["channel"] data = message["data"] # Determine the appropriate message handler. if channel == ray.gcs_utils.XRAY_HEARTBEAT_BATCH_CHANNEL: # Similar functionality as raylet info channel message_handler = self.xray_heartbeat_batch_handler elif channel == ray.gcs_utils.XRAY_DRIVER_CHANNEL: # Handles driver death. message_handler = self.xray_driver_removed_handler else: raise Exception("This code should be unreachable.") # Call the handler. message_handler(channel, data)
[ "Process", "all", "messages", "ready", "in", "the", "subscription", "channels", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/monitor.py#L219-L252
[ "def", "process_messages", "(", "self", ",", "max_messages", "=", "10000", ")", ":", "subscribe_clients", "=", "[", "self", ".", "primary_subscribe_client", "]", "for", "subscribe_client", "in", "subscribe_clients", ":", "for", "_", "in", "range", "(", "max_mess...
4eade036a0505e244c976f36aaa2d64386b5129b
train
Monitor._maybe_flush_gcs
Experimental: issue a flush request to the GCS. The purpose of this feature is to control GCS memory usage. To activate this feature, Ray must be compiled with the flag RAY_USE_NEW_GCS set, and Ray must be started at run time with the flag as well.
python/ray/monitor.py
def _maybe_flush_gcs(self): """Experimental: issue a flush request to the GCS. The purpose of this feature is to control GCS memory usage. To activate this feature, Ray must be compiled with the flag RAY_USE_NEW_GCS set, and Ray must be started at run time with the flag as well. """ if not self.issue_gcs_flushes: return if self.gcs_flush_policy is None: serialized = self.redis.get("gcs_flushing_policy") if serialized is None: # Client has not set any policy; by default flushing is off. return self.gcs_flush_policy = pickle.loads(serialized) if not self.gcs_flush_policy.should_flush(self.redis_shard): return max_entries_to_flush = self.gcs_flush_policy.num_entries_to_flush() num_flushed = self.redis_shard.execute_command( "HEAD.FLUSH {}".format(max_entries_to_flush)) logger.info("Monitor: num_flushed {}".format(num_flushed)) # This flushes event log and log files. ray.experimental.flush_redis_unsafe(self.redis) self.gcs_flush_policy.record_flush()
def _maybe_flush_gcs(self): """Experimental: issue a flush request to the GCS. The purpose of this feature is to control GCS memory usage. To activate this feature, Ray must be compiled with the flag RAY_USE_NEW_GCS set, and Ray must be started at run time with the flag as well. """ if not self.issue_gcs_flushes: return if self.gcs_flush_policy is None: serialized = self.redis.get("gcs_flushing_policy") if serialized is None: # Client has not set any policy; by default flushing is off. return self.gcs_flush_policy = pickle.loads(serialized) if not self.gcs_flush_policy.should_flush(self.redis_shard): return max_entries_to_flush = self.gcs_flush_policy.num_entries_to_flush() num_flushed = self.redis_shard.execute_command( "HEAD.FLUSH {}".format(max_entries_to_flush)) logger.info("Monitor: num_flushed {}".format(num_flushed)) # This flushes event log and log files. ray.experimental.flush_redis_unsafe(self.redis) self.gcs_flush_policy.record_flush()
[ "Experimental", ":", "issue", "a", "flush", "request", "to", "the", "GCS", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/monitor.py#L264-L293
[ "def", "_maybe_flush_gcs", "(", "self", ")", ":", "if", "not", "self", ".", "issue_gcs_flushes", ":", "return", "if", "self", ".", "gcs_flush_policy", "is", "None", ":", "serialized", "=", "self", ".", "redis", ".", "get", "(", "\"gcs_flushing_policy\"", ")"...
4eade036a0505e244c976f36aaa2d64386b5129b
train
Monitor.run
Run the monitor. This function loops forever, checking for messages about dead database clients and cleaning up state accordingly.
python/ray/monitor.py
def run(self): """Run the monitor. This function loops forever, checking for messages about dead database clients and cleaning up state accordingly. """ # Initialize the subscription channel. self.subscribe(ray.gcs_utils.XRAY_HEARTBEAT_BATCH_CHANNEL) self.subscribe(ray.gcs_utils.XRAY_DRIVER_CHANNEL) # TODO(rkn): If there were any dead clients at startup, we should clean # up the associated state in the state tables. # Handle messages from the subscription channels. while True: # Update the mapping from raylet client ID to IP address. # This is only used to update the load metrics for the autoscaler. self.update_raylet_map() # Process autoscaling actions if self.autoscaler: self.autoscaler.update() self._maybe_flush_gcs() # Process a round of messages. self.process_messages() # Wait for a heartbeat interval before processing the next round of # messages. time.sleep(ray._config.heartbeat_timeout_milliseconds() * 1e-3)
def run(self): """Run the monitor. This function loops forever, checking for messages about dead database clients and cleaning up state accordingly. """ # Initialize the subscription channel. self.subscribe(ray.gcs_utils.XRAY_HEARTBEAT_BATCH_CHANNEL) self.subscribe(ray.gcs_utils.XRAY_DRIVER_CHANNEL) # TODO(rkn): If there were any dead clients at startup, we should clean # up the associated state in the state tables. # Handle messages from the subscription channels. while True: # Update the mapping from raylet client ID to IP address. # This is only used to update the load metrics for the autoscaler. self.update_raylet_map() # Process autoscaling actions if self.autoscaler: self.autoscaler.update() self._maybe_flush_gcs() # Process a round of messages. self.process_messages() # Wait for a heartbeat interval before processing the next round of # messages. time.sleep(ray._config.heartbeat_timeout_milliseconds() * 1e-3)
[ "Run", "the", "monitor", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/monitor.py#L295-L325
[ "def", "run", "(", "self", ")", ":", "# Initialize the subscription channel.", "self", ".", "subscribe", "(", "ray", ".", "gcs_utils", ".", "XRAY_HEARTBEAT_BATCH_CHANNEL", ")", "self", ".", "subscribe", "(", "ray", ".", "gcs_utils", ".", "XRAY_DRIVER_CHANNEL", ")"...
4eade036a0505e244c976f36aaa2d64386b5129b
train
index
View for the home page.
python/ray/tune/automlboard/frontend/view.py
def index(request): """View for the home page.""" recent_jobs = JobRecord.objects.order_by("-start_time")[0:100] recent_trials = TrialRecord.objects.order_by("-start_time")[0:500] total_num = len(recent_trials) running_num = sum(t.trial_status == Trial.RUNNING for t in recent_trials) success_num = sum( t.trial_status == Trial.TERMINATED for t in recent_trials) failed_num = sum(t.trial_status == Trial.ERROR for t in recent_trials) job_records = [] for recent_job in recent_jobs: job_records.append(get_job_info(recent_job)) context = { "log_dir": AUTOMLBOARD_LOG_DIR, "reload_interval": AUTOMLBOARD_RELOAD_INTERVAL, "recent_jobs": job_records, "job_num": len(job_records), "trial_num": total_num, "running_num": running_num, "success_num": success_num, "failed_num": failed_num } return render(request, "index.html", context)
def index(request): """View for the home page.""" recent_jobs = JobRecord.objects.order_by("-start_time")[0:100] recent_trials = TrialRecord.objects.order_by("-start_time")[0:500] total_num = len(recent_trials) running_num = sum(t.trial_status == Trial.RUNNING for t in recent_trials) success_num = sum( t.trial_status == Trial.TERMINATED for t in recent_trials) failed_num = sum(t.trial_status == Trial.ERROR for t in recent_trials) job_records = [] for recent_job in recent_jobs: job_records.append(get_job_info(recent_job)) context = { "log_dir": AUTOMLBOARD_LOG_DIR, "reload_interval": AUTOMLBOARD_RELOAD_INTERVAL, "recent_jobs": job_records, "job_num": len(job_records), "trial_num": total_num, "running_num": running_num, "success_num": success_num, "failed_num": failed_num } return render(request, "index.html", context)
[ "View", "for", "the", "home", "page", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/frontend/view.py#L17-L41
[ "def", "index", "(", "request", ")", ":", "recent_jobs", "=", "JobRecord", ".", "objects", ".", "order_by", "(", "\"-start_time\"", ")", "[", "0", ":", "100", "]", "recent_trials", "=", "TrialRecord", ".", "objects", ".", "order_by", "(", "\"-start_time\"", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
job
View for a single job.
python/ray/tune/automlboard/frontend/view.py
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(recent_trial)) current_job = JobRecord.objects \ .filter(job_id=job_id) \ .order_by("-start_time")[0] if len(trial_records) > 0: param_keys = trial_records[0]["params"].keys() else: param_keys = [] # TODO: support custom metrics here metric_keys = ["episode_reward", "accuracy", "loss"] context = { "current_job": get_job_info(current_job), "recent_jobs": recent_jobs, "recent_trials": trial_records, "param_keys": param_keys, "param_num": len(param_keys), "metric_keys": metric_keys, "metric_num": len(metric_keys) } return render(request, "job.html", context)
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(recent_trial)) current_job = JobRecord.objects \ .filter(job_id=job_id) \ .order_by("-start_time")[0] if len(trial_records) > 0: param_keys = trial_records[0]["params"].keys() else: param_keys = [] # TODO: support custom metrics here metric_keys = ["episode_reward", "accuracy", "loss"] context = { "current_job": get_job_info(current_job), "recent_jobs": recent_jobs, "recent_trials": trial_records, "param_keys": param_keys, "param_num": len(param_keys), "metric_keys": metric_keys, "metric_num": len(metric_keys) } return render(request, "job.html", context)
[ "View", "for", "a", "single", "job", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/frontend/view.py#L44-L74
[ "def", "job", "(", "request", ")", ":", "job_id", "=", "request", ".", "GET", ".", "get", "(", "\"job_id\"", ")", "recent_jobs", "=", "JobRecord", ".", "objects", ".", "order_by", "(", "\"-start_time\"", ")", "[", "0", ":", "100", "]", "recent_trials", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
trial
View for a single trial.
python/ray/tune/automlboard/frontend/view.py
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_trial = TrialRecord.objects \ .filter(trial_id=trial_id) \ .order_by("-start_time")[0] context = { "job_id": job_id, "trial_id": trial_id, "current_trial": current_trial, "recent_results": recent_results, "recent_trials": recent_trials } return render(request, "trial.html", context)
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_trial = TrialRecord.objects \ .filter(trial_id=trial_id) \ .order_by("-start_time")[0] context = { "job_id": job_id, "trial_id": trial_id, "current_trial": current_trial, "recent_results": recent_results, "recent_trials": recent_trials } return render(request, "trial.html", context)
[ "View", "for", "a", "single", "trial", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/frontend/view.py#L77-L97
[ "def", "trial", "(", "request", ")", ":", "job_id", "=", "request", ".", "GET", ".", "get", "(", "\"job_id\"", ")", "trial_id", "=", "request", ".", "GET", ".", "get", "(", "\"trial_id\"", ")", "recent_trials", "=", "TrialRecord", ".", "objects", ".", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
get_job_info
Get job information for current job.
python/ray/tune/automlboard/frontend/view.py
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 total_num == 0: progress = 0 else: progress = int(float(success_num) / total_num * 100) winner = get_winner(trials) job_info = { "job_id": current_job.job_id, "job_name": current_job.name, "user": current_job.user, "type": current_job.type, "start_time": current_job.start_time, "end_time": current_job.end_time, "total_num": total_num, "running_num": running_num, "success_num": success_num, "failed_num": failed_num, "best_trial_id": current_job.best_trial_id, "progress": progress, "winner": winner } return job_info
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 total_num == 0: progress = 0 else: progress = int(float(success_num) / total_num * 100) winner = get_winner(trials) job_info = { "job_id": current_job.job_id, "job_name": current_job.name, "user": current_job.user, "type": current_job.type, "start_time": current_job.start_time, "end_time": current_job.end_time, "total_num": total_num, "running_num": running_num, "success_num": success_num, "failed_num": failed_num, "best_trial_id": current_job.best_trial_id, "progress": progress, "winner": winner } return job_info
[ "Get", "job", "information", "for", "current", "job", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/frontend/view.py#L100-L131
[ "def", "get_job_info", "(", "current_job", ")", ":", "trials", "=", "TrialRecord", ".", "objects", ".", "filter", "(", "job_id", "=", "current_job", ".", "job_id", ")", "total_num", "=", "len", "(", "trials", ")", "running_num", "=", "sum", "(", "t", "."...
4eade036a0505e244c976f36aaa2d64386b5129b
train
get_trial_info
Get job information for current trial.
python/ray/tune/automlboard/frontend/view.py
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, "%Y-%m-%d_%H-%M-%S") end_time = time_obj.strftime("%Y-%m-%d %H:%M:%S") else: end_time = current_trial.end_time if current_trial.metrics: metrics = eval(current_trial.metrics) else: metrics = None trial_info = { "trial_id": current_trial.trial_id, "job_id": current_trial.job_id, "trial_status": current_trial.trial_status, "start_time": current_trial.start_time, "end_time": end_time, "params": eval(current_trial.params.encode("utf-8")), "metrics": metrics } return trial_info
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, "%Y-%m-%d_%H-%M-%S") end_time = time_obj.strftime("%Y-%m-%d %H:%M:%S") else: end_time = current_trial.end_time if current_trial.metrics: metrics = eval(current_trial.metrics) else: metrics = None trial_info = { "trial_id": current_trial.trial_id, "job_id": current_trial.job_id, "trial_status": current_trial.trial_status, "start_time": current_trial.start_time, "end_time": end_time, "params": eval(current_trial.params.encode("utf-8")), "metrics": metrics } return trial_info
[ "Get", "job", "information", "for", "current", "trial", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/frontend/view.py#L134-L161
[ "def", "get_trial_info", "(", "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 conve...
4eade036a0505e244c976f36aaa2d64386b5129b
train
get_winner
Get winner trial of a job.
python/ray/tune/automlboard/frontend/view.py
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 = float("-Inf") for t in trials: metrics = get_trial_info(t).get("metrics", None) if metrics and metrics.get(sort_key, None): current_metric = float(metrics[sort_key]) if current_metric > max_metric: winner["trial_id"] = t.trial_id winner["metric"] = sort_key + ": " + str(current_metric) max_metric = current_metric return winner
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 = float("-Inf") for t in trials: metrics = get_trial_info(t).get("metrics", None) if metrics and metrics.get(sort_key, None): current_metric = float(metrics[sort_key]) if current_metric > max_metric: winner["trial_id"] = t.trial_id winner["metric"] = sort_key + ": " + str(current_metric) max_metric = current_metric return winner
[ "Get", "winner", "trial", "of", "a", "job", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/frontend/view.py#L164-L182
[ "def", "get_winner", "(", "trials", ")", ":", "winner", "=", "{", "}", "# TODO: sort_key should be customized here", "sort_key", "=", "\"accuracy\"", "if", "trials", "and", "len", "(", "trials", ")", ">", "0", ":", "first_metrics", "=", "get_trial_info", "(", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
make_parser
Returns a base argument parser for the ray.tune tool. Args: parser_creator: A constructor for the parser class. kwargs: Non-positional args to be passed into the parser class constructor.
python/ray/tune/config_parser.py
def make_parser(parser_creator=None, **kwargs): """Returns a base argument parser for the ray.tune tool. Args: parser_creator: A constructor for the parser class. kwargs: Non-positional args to be passed into the parser class constructor. """ if parser_creator: parser = parser_creator(**kwargs) else: parser = argparse.ArgumentParser(**kwargs) # Note: keep this in sync with rllib/train.py parser.add_argument( "--run", default=None, type=str, help="The algorithm or model to train. This may refer to the name " "of a built-on algorithm (e.g. RLLib's DQN or PPO), or a " "user-defined trainable function or class registered in the " "tune registry.") parser.add_argument( "--stop", default="{}", type=json.loads, help="The stopping criteria, specified in JSON. The keys may be any " "field returned by 'train()' e.g. " "'{\"time_total_s\": 600, \"training_iteration\": 100000}' to stop " "after 600 seconds or 100k iterations, whichever is reached first.") parser.add_argument( "--config", default="{}", type=json.loads, help="Algorithm-specific configuration (e.g. env, hyperparams), " "specified in JSON.") parser.add_argument( "--resources-per-trial", default=None, type=json_to_resources, help="Override the machine resources to allocate per trial, e.g. " "'{\"cpu\": 64, \"gpu\": 8}'. Note that GPUs will not be assigned " "unless you specify them here. For RLlib, you probably want to " "leave this alone and use RLlib configs to control parallelism.") parser.add_argument( "--num-samples", default=1, type=int, help="Number of times to repeat each trial.") parser.add_argument( "--local-dir", default=DEFAULT_RESULTS_DIR, type=str, help="Local dir to save training results to. Defaults to '{}'.".format( DEFAULT_RESULTS_DIR)) parser.add_argument( "--upload-dir", default="", type=str, help="Optional URI to sync training results to (e.g. s3://bucket).") parser.add_argument( "--trial-name-creator", default=None, help="Optional creator function for the trial string, used in " "generating a trial directory.") parser.add_argument( "--sync-function", default=None, help="Function for syncing the local_dir to upload_dir. If string, " "then it must be a string template for syncer to run and needs to " "include replacement fields '{local_dir}' and '{remote_dir}'.") parser.add_argument( "--loggers", default=None, help="List of logger creators to be used with each Trial. " "Defaults to ray.tune.logger.DEFAULT_LOGGERS.") parser.add_argument( "--checkpoint-freq", default=0, type=int, help="How many training iterations between checkpoints. " "A value of 0 (default) disables checkpointing.") parser.add_argument( "--checkpoint-at-end", action="store_true", help="Whether to checkpoint at the end of the experiment. " "Default is False.") parser.add_argument( "--keep-checkpoints-num", default=None, type=int, help="Number of last checkpoints to keep. Others get " "deleted. Default (None) keeps all checkpoints.") parser.add_argument( "--checkpoint-score-attr", default="training_iteration", type=str, help="Specifies by which attribute to rank the best checkpoint. " "Default is increasing order. If attribute starts with min- it " "will rank attribute in decreasing order. Example: " "min-validation_loss") parser.add_argument( "--export-formats", default=None, help="List of formats that exported at the end of the experiment. " "Default is None. For RLlib, 'checkpoint' and 'model' are " "supported for TensorFlow policy graphs.") parser.add_argument( "--max-failures", default=3, type=int, help="Try to recover a trial from its last checkpoint at least this " "many times. Only applies if checkpointing is enabled.") parser.add_argument( "--scheduler", default="FIFO", type=str, help="FIFO (default), MedianStopping, AsyncHyperBand, " "HyperBand, or HyperOpt.") parser.add_argument( "--scheduler-config", default="{}", type=json.loads, help="Config options to pass to the scheduler.") # Note: this currently only makes sense when running a single trial parser.add_argument( "--restore", default=None, type=str, help="If specified, restore from this checkpoint.") return parser
def make_parser(parser_creator=None, **kwargs): """Returns a base argument parser for the ray.tune tool. Args: parser_creator: A constructor for the parser class. kwargs: Non-positional args to be passed into the parser class constructor. """ if parser_creator: parser = parser_creator(**kwargs) else: parser = argparse.ArgumentParser(**kwargs) # Note: keep this in sync with rllib/train.py parser.add_argument( "--run", default=None, type=str, help="The algorithm or model to train. This may refer to the name " "of a built-on algorithm (e.g. RLLib's DQN or PPO), or a " "user-defined trainable function or class registered in the " "tune registry.") parser.add_argument( "--stop", default="{}", type=json.loads, help="The stopping criteria, specified in JSON. The keys may be any " "field returned by 'train()' e.g. " "'{\"time_total_s\": 600, \"training_iteration\": 100000}' to stop " "after 600 seconds or 100k iterations, whichever is reached first.") parser.add_argument( "--config", default="{}", type=json.loads, help="Algorithm-specific configuration (e.g. env, hyperparams), " "specified in JSON.") parser.add_argument( "--resources-per-trial", default=None, type=json_to_resources, help="Override the machine resources to allocate per trial, e.g. " "'{\"cpu\": 64, \"gpu\": 8}'. Note that GPUs will not be assigned " "unless you specify them here. For RLlib, you probably want to " "leave this alone and use RLlib configs to control parallelism.") parser.add_argument( "--num-samples", default=1, type=int, help="Number of times to repeat each trial.") parser.add_argument( "--local-dir", default=DEFAULT_RESULTS_DIR, type=str, help="Local dir to save training results to. Defaults to '{}'.".format( DEFAULT_RESULTS_DIR)) parser.add_argument( "--upload-dir", default="", type=str, help="Optional URI to sync training results to (e.g. s3://bucket).") parser.add_argument( "--trial-name-creator", default=None, help="Optional creator function for the trial string, used in " "generating a trial directory.") parser.add_argument( "--sync-function", default=None, help="Function for syncing the local_dir to upload_dir. If string, " "then it must be a string template for syncer to run and needs to " "include replacement fields '{local_dir}' and '{remote_dir}'.") parser.add_argument( "--loggers", default=None, help="List of logger creators to be used with each Trial. " "Defaults to ray.tune.logger.DEFAULT_LOGGERS.") parser.add_argument( "--checkpoint-freq", default=0, type=int, help="How many training iterations between checkpoints. " "A value of 0 (default) disables checkpointing.") parser.add_argument( "--checkpoint-at-end", action="store_true", help="Whether to checkpoint at the end of the experiment. " "Default is False.") parser.add_argument( "--keep-checkpoints-num", default=None, type=int, help="Number of last checkpoints to keep. Others get " "deleted. Default (None) keeps all checkpoints.") parser.add_argument( "--checkpoint-score-attr", default="training_iteration", type=str, help="Specifies by which attribute to rank the best checkpoint. " "Default is increasing order. If attribute starts with min- it " "will rank attribute in decreasing order. Example: " "min-validation_loss") parser.add_argument( "--export-formats", default=None, help="List of formats that exported at the end of the experiment. " "Default is None. For RLlib, 'checkpoint' and 'model' are " "supported for TensorFlow policy graphs.") parser.add_argument( "--max-failures", default=3, type=int, help="Try to recover a trial from its last checkpoint at least this " "many times. Only applies if checkpointing is enabled.") parser.add_argument( "--scheduler", default="FIFO", type=str, help="FIFO (default), MedianStopping, AsyncHyperBand, " "HyperBand, or HyperOpt.") parser.add_argument( "--scheduler-config", default="{}", type=json.loads, help="Config options to pass to the scheduler.") # Note: this currently only makes sense when running a single trial parser.add_argument( "--restore", default=None, type=str, help="If specified, restore from this checkpoint.") return parser
[ "Returns", "a", "base", "argument", "parser", "for", "the", "ray", ".", "tune", "tool", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/config_parser.py#L18-L151
[ "def", "make_parser", "(", "parser_creator", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "parser_creator", ":", "parser", "=", "parser_creator", "(", "*", "*", "kwargs", ")", "else", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "...
4eade036a0505e244c976f36aaa2d64386b5129b
train
to_argv
Converts configuration to a command line argument format.
python/ray/tune/config_parser.py
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 isinstance(v, string_types): argv.append(v) elif isinstance(v, bool): pass else: argv.append(json.dumps(v, cls=_SafeFallbackEncoder)) return argv
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 isinstance(v, string_types): argv.append(v) elif isinstance(v, bool): pass else: argv.append(json.dumps(v, cls=_SafeFallbackEncoder)) return argv
[ "Converts", "configuration", "to", "a", "command", "line", "argument", "format", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/config_parser.py#L154-L170
[ "def", "to_argv", "(", "config", ")", ":", "argv", "=", "[", "]", "for", "k", ",", "v", "in", "config", ".", "items", "(", ")", ":", "if", "\"-\"", "in", "k", ":", "raise", "ValueError", "(", "\"Use '_' instead of '-' in `{}`\"", ".", "format", "(", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
create_trial_from_spec
Creates a Trial object from parsing the spec. Arguments: spec (dict): A resolved experiment specification. Arguments should The args here should correspond to the command line flags in ray.tune.config_parser. output_path (str); A specific output path within the local_dir. Typically the name of the experiment. parser (ArgumentParser): An argument parser object from make_parser. trial_kwargs: Extra keyword arguments used in instantiating the Trial. Returns: A trial object with corresponding parameters to the specification.
python/ray/tune/config_parser.py
def create_trial_from_spec(spec, output_path, parser, **trial_kwargs): """Creates a Trial object from parsing the spec. Arguments: spec (dict): A resolved experiment specification. Arguments should The args here should correspond to the command line flags in ray.tune.config_parser. output_path (str); A specific output path within the local_dir. Typically the name of the experiment. parser (ArgumentParser): An argument parser object from make_parser. trial_kwargs: Extra keyword arguments used in instantiating the Trial. Returns: A trial object with corresponding parameters to the specification. """ 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( # Submitting trial via server in py2.7 creates Unicode, which does not # convert to string in a straightforward manner. trainable_name=spec["run"], # json.load leads to str -> unicode in py2.7 config=spec.get("config", {}), local_dir=os.path.join(args.local_dir, output_path), # json.load leads to str -> unicode in py2.7 stopping_criterion=spec.get("stop", {}), checkpoint_freq=args.checkpoint_freq, checkpoint_at_end=args.checkpoint_at_end, keep_checkpoints_num=args.keep_checkpoints_num, checkpoint_score_attr=args.checkpoint_score_attr, export_formats=spec.get("export_formats", []), # str(None) doesn't create None restore_path=spec.get("restore"), upload_dir=args.upload_dir, trial_name_creator=spec.get("trial_name_creator"), loggers=spec.get("loggers"), # str(None) doesn't create None sync_function=spec.get("sync_function"), max_failures=args.max_failures, **trial_kwargs)
def create_trial_from_spec(spec, output_path, parser, **trial_kwargs): """Creates a Trial object from parsing the spec. Arguments: spec (dict): A resolved experiment specification. Arguments should The args here should correspond to the command line flags in ray.tune.config_parser. output_path (str); A specific output path within the local_dir. Typically the name of the experiment. parser (ArgumentParser): An argument parser object from make_parser. trial_kwargs: Extra keyword arguments used in instantiating the Trial. Returns: A trial object with corresponding parameters to the specification. """ 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( # Submitting trial via server in py2.7 creates Unicode, which does not # convert to string in a straightforward manner. trainable_name=spec["run"], # json.load leads to str -> unicode in py2.7 config=spec.get("config", {}), local_dir=os.path.join(args.local_dir, output_path), # json.load leads to str -> unicode in py2.7 stopping_criterion=spec.get("stop", {}), checkpoint_freq=args.checkpoint_freq, checkpoint_at_end=args.checkpoint_at_end, keep_checkpoints_num=args.keep_checkpoints_num, checkpoint_score_attr=args.checkpoint_score_attr, export_formats=spec.get("export_formats", []), # str(None) doesn't create None restore_path=spec.get("restore"), upload_dir=args.upload_dir, trial_name_creator=spec.get("trial_name_creator"), loggers=spec.get("loggers"), # str(None) doesn't create None sync_function=spec.get("sync_function"), max_failures=args.max_failures, **trial_kwargs)
[ "Creates", "a", "Trial", "object", "from", "parsing", "the", "spec", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/config_parser.py#L173-L218
[ "def", "create_trial_from_spec", "(", "spec", ",", "output_path", ",", "parser", ",", "*", "*", "trial_kwargs", ")", ":", "try", ":", "args", "=", "parser", ".", "parse_args", "(", "to_argv", "(", "spec", ")", ")", "except", "SystemExit", ":", "raise", "...
4eade036a0505e244c976f36aaa2d64386b5129b
train
wait_for_compute_zone_operation
Poll for compute zone operation until finished.
python/ray/autoscaler/gcp/node_provider.py
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).execute() if "error" in result: raise Exception(result["error"]) if result["status"] == "DONE": logger.info("wait_for_compute_zone_operation: " "Operation {} finished.".format(operation["name"])) break time.sleep(POLL_INTERVAL) return result
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).execute() if "error" in result: raise Exception(result["error"]) if result["status"] == "DONE": logger.info("wait_for_compute_zone_operation: " "Operation {} finished.".format(operation["name"])) break time.sleep(POLL_INTERVAL) return result
[ "Poll", "for", "compute", "zone", "operation", "until", "finished", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/autoscaler/gcp/node_provider.py#L22-L42
[ "def", "wait_for_compute_zone_operation", "(", "compute", ",", "project_name", ",", "operation", ",", "zone", ")", ":", "logger", ".", "info", "(", "\"wait_for_compute_zone_operation: \"", "\"Waiting for operation {} to finish...\"", ".", "format", "(", "operation", "[", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
_get_task_id
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 returned by a task, a task id, or an actor handle. Returns: - If source is an object id, return id of task which creted object. - If source is an actor handle, return id of actor's task creator. - If source is a task id, return same task id.
python/ray/experimental/signal.py
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 returned by a task, a task id, or an actor handle. Returns: - If source is an object id, return id of task which creted object. - If source is an actor handle, return id of actor's task creator. - If source is a task id, return same task 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)
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 returned by a task, a task id, or an actor handle. Returns: - If source is an object id, return id of task which creted object. - If source is an actor handle, return id of actor's task creator. - If source is a task id, return same task 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)
[ "Return", "the", "task", "id", "associated", "to", "the", "generic", "source", "of", "the", "signal", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/signal.py#L36-L54
[ "def", "_get_task_id", "(", "source", ")", ":", "if", "type", "(", "source", ")", "is", "ray", ".", "actor", ".", "ActorHandle", ":", "return", "source", ".", "_ray_actor_id", "else", ":", "if", "type", "(", "source", ")", "is", "ray", ".", "TaskID", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
send
Send signal. The signal has a unique identifier that is computed from (1) the id of the actor or task sending this signal (i.e., the actor or task calling this function), and (2) an index that is incremented every time this source sends a signal. This index starts from 1. Args: signal: Signal to be sent.
python/ray/experimental/signal.py
def send(signal): """Send signal. The signal has a unique identifier that is computed from (1) the id of the actor or task sending this signal (i.e., the actor or task calling this function), and (2) an index that is incremented every time this source sends a signal. This index starts from 1. Args: signal: Signal to be sent. """ if hasattr(ray.worker.global_worker, "actor_creation_task_id"): source_key = ray.worker.global_worker.actor_id.hex() else: # No actors; this function must have been called from a task source_key = ray.worker.global_worker.current_task_id.hex() encoded_signal = ray.utils.binary_to_hex(cloudpickle.dumps(signal)) ray.worker.global_worker.redis_client.execute_command( "XADD " + source_key + " * signal " + encoded_signal)
def send(signal): """Send signal. The signal has a unique identifier that is computed from (1) the id of the actor or task sending this signal (i.e., the actor or task calling this function), and (2) an index that is incremented every time this source sends a signal. This index starts from 1. Args: signal: Signal to be sent. """ if hasattr(ray.worker.global_worker, "actor_creation_task_id"): source_key = ray.worker.global_worker.actor_id.hex() else: # No actors; this function must have been called from a task source_key = ray.worker.global_worker.current_task_id.hex() encoded_signal = ray.utils.binary_to_hex(cloudpickle.dumps(signal)) ray.worker.global_worker.redis_client.execute_command( "XADD " + source_key + " * signal " + encoded_signal)
[ "Send", "signal", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/signal.py#L57-L76
[ "def", "send", "(", "signal", ")", ":", "if", "hasattr", "(", "ray", ".", "worker", ".", "global_worker", ",", "\"actor_creation_task_id\"", ")", ":", "source_key", "=", "ray", ".", "worker", ".", "global_worker", ".", "actor_id", ".", "hex", "(", ")", "...
4eade036a0505e244c976f36aaa2d64386b5129b
train
receive
Get all outstanding signals from sources. A source can be either (1) an object ID returned by the task (we want to receive signals from), or (2) an actor handle. When invoked by the same entity E (where E can be an actor, task or driver), for each source S in sources, this function returns all signals generated by S since the last receive() was invoked by E on S. If this is the first call on S, this function returns all past signals generated by S so far. Note that different actors, tasks or drivers that call receive() on the same source S will get independent copies of the signals generated by S. Args: sources: List of sources from which the caller waits for signals. A source is either an object ID returned by a task (in this case the object ID is used to identify that task), or an actor handle. If the user passes the IDs of multiple objects returned by the same task, this function returns a copy of the signals generated by that task for each object ID. timeout: Maximum time (in seconds) this function waits to get a signal from a source in sources. If None, the timeout is infinite. Returns: A list of pairs (S, sig), where S is a source in the sources argument, and sig is a signal generated by S since the last time receive() was called on S. Thus, for each S in sources, the return list can contain zero or multiple entries.
python/ray/experimental/signal.py
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 signals from), or (2) an actor handle. When invoked by the same entity E (where E can be an actor, task or driver), for each source S in sources, this function returns all signals generated by S since the last receive() was invoked by E on S. If this is the first call on S, this function returns all past signals generated by S so far. Note that different actors, tasks or drivers that call receive() on the same source S will get independent copies of the signals generated by S. Args: sources: List of sources from which the caller waits for signals. A source is either an object ID returned by a task (in this case the object ID is used to identify that task), or an actor handle. If the user passes the IDs of multiple objects returned by the same task, this function returns a copy of the signals generated by that task for each object ID. timeout: Maximum time (in seconds) this function waits to get a signal from a source in sources. If None, the timeout is infinite. Returns: A list of pairs (S, sig), where S is a source in the sources argument, and sig is a signal generated by S since the last time receive() was called on S. Thus, for each S in sources, the return list can contain zero or multiple entries. """ # 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, "signal_counters"): ray.worker.global_worker.signal_counters = defaultdict(lambda: b"0") signal_counters = ray.worker.global_worker.signal_counters # Map the ID of each source task to the source itself. task_id_to_sources = defaultdict(lambda: []) for s in sources: task_id_to_sources[_get_task_id(s).hex()].append(s) # Construct the redis query. query = "XREAD BLOCK " # Multiply by 1000x since timeout is in sec and redis expects ms. query += str(1000 * timeout) query += " STREAMS " query += " ".join([task_id for task_id in task_id_to_sources]) query += " " query += " ".join([ ray.utils.decode(signal_counters[ray.utils.hex_to_binary(task_id)]) for task_id in task_id_to_sources ]) answers = ray.worker.global_worker.redis_client.execute_command(query) if not answers: return [] results = [] # Decoding is a little bit involved. Iterate through all the answers: for i, answer in enumerate(answers): # Make sure the answer corresponds to a source, s, in sources. task_id = ray.utils.decode(answer[0]) task_source_list = task_id_to_sources[task_id] # The list of results for source s is stored in answer[1] for r in answer[1]: for s in task_source_list: if r[1][1].decode("ascii") == ACTOR_DIED_STR: results.append((s, ActorDiedSignal())) else: # Now it gets tricky: r[0] is the redis internal sequence # id signal_counters[ray.utils.hex_to_binary(task_id)] = r[0] # r[1] contains a list with elements (key, value), in our # case we only have one key "signal" and the value is the # signal. signal = cloudpickle.loads( ray.utils.hex_to_binary(r[1][1])) results.append((s, signal)) return results
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 signals from), or (2) an actor handle. When invoked by the same entity E (where E can be an actor, task or driver), for each source S in sources, this function returns all signals generated by S since the last receive() was invoked by E on S. If this is the first call on S, this function returns all past signals generated by S so far. Note that different actors, tasks or drivers that call receive() on the same source S will get independent copies of the signals generated by S. Args: sources: List of sources from which the caller waits for signals. A source is either an object ID returned by a task (in this case the object ID is used to identify that task), or an actor handle. If the user passes the IDs of multiple objects returned by the same task, this function returns a copy of the signals generated by that task for each object ID. timeout: Maximum time (in seconds) this function waits to get a signal from a source in sources. If None, the timeout is infinite. Returns: A list of pairs (S, sig), where S is a source in the sources argument, and sig is a signal generated by S since the last time receive() was called on S. Thus, for each S in sources, the return list can contain zero or multiple entries. """ # 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, "signal_counters"): ray.worker.global_worker.signal_counters = defaultdict(lambda: b"0") signal_counters = ray.worker.global_worker.signal_counters # Map the ID of each source task to the source itself. task_id_to_sources = defaultdict(lambda: []) for s in sources: task_id_to_sources[_get_task_id(s).hex()].append(s) # Construct the redis query. query = "XREAD BLOCK " # Multiply by 1000x since timeout is in sec and redis expects ms. query += str(1000 * timeout) query += " STREAMS " query += " ".join([task_id for task_id in task_id_to_sources]) query += " " query += " ".join([ ray.utils.decode(signal_counters[ray.utils.hex_to_binary(task_id)]) for task_id in task_id_to_sources ]) answers = ray.worker.global_worker.redis_client.execute_command(query) if not answers: return [] results = [] # Decoding is a little bit involved. Iterate through all the answers: for i, answer in enumerate(answers): # Make sure the answer corresponds to a source, s, in sources. task_id = ray.utils.decode(answer[0]) task_source_list = task_id_to_sources[task_id] # The list of results for source s is stored in answer[1] for r in answer[1]: for s in task_source_list: if r[1][1].decode("ascii") == ACTOR_DIED_STR: results.append((s, ActorDiedSignal())) else: # Now it gets tricky: r[0] is the redis internal sequence # id signal_counters[ray.utils.hex_to_binary(task_id)] = r[0] # r[1] contains a list with elements (key, value), in our # case we only have one key "signal" and the value is the # signal. signal = cloudpickle.loads( ray.utils.hex_to_binary(r[1][1])) results.append((s, signal)) return results
[ "Get", "all", "outstanding", "signals", "from", "sources", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/signal.py#L79-L166
[ "def", "receive", "(", "sources", ",", "timeout", "=", "None", ")", ":", "# 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...
4eade036a0505e244c976f36aaa2d64386b5129b
train
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 get all the signals generated by that source starting with index = 1.
python/ray/experimental/signal.py
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 get all the signals generated by that source starting with index = 1. """ if hasattr(ray.worker.global_worker, "signal_counters"): ray.worker.global_worker.signal_counters = defaultdict(lambda: b"0")
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 get all the signals generated by that source starting with index = 1. """ if hasattr(ray.worker.global_worker, "signal_counters"): ray.worker.global_worker.signal_counters = defaultdict(lambda: b"0")
[ "Reset", "the", "worker", "state", "associated", "with", "any", "signals", "that", "this", "worker", "has", "received", "so", "far", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/signal.py#L184-L193
[ "def", "reset", "(", ")", ":", "if", "hasattr", "(", "ray", ".", "worker", ".", "global_worker", ",", "\"signal_counters\"", ")", ":", "ray", ".", "worker", ".", "global_worker", ".", "signal_counters", "=", "defaultdict", "(", "lambda", ":", "b\"0\"", ")"...
4eade036a0505e244c976f36aaa2d64386b5129b
train
log_once
Returns True if this is the "first" call for a given key. Various logging settings can adjust the definition of "first". Example: >>> if log_once("some_key"): ... logger.info("Some verbose logging statement")
python/ray/rllib/utils/debug.py
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: >>> if log_once("some_key"): ... logger.info("Some verbose logging statement") """ 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 else: return False
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: >>> if log_once("some_key"): ... logger.info("Some verbose logging statement") """ 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 else: return False
[ "Returns", "True", "if", "this", "is", "the", "first", "call", "for", "a", "given", "key", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/utils/debug.py#L18-L41
[ "def", "log_once", "(", "key", ")", ":", "global", "_last_logged", "if", "_disabled", ":", "return", "False", "elif", "key", "not", "in", "_logged", ":", "_logged", ".", "add", "(", "key", ")", "_last_logged", "=", "time", ".", "time", "(", ")", "retur...
4eade036a0505e244c976f36aaa2d64386b5129b
train
get
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 tuples, ndarrays and dictionaries. Args: object_ids: Object ID of the object to get, a list, tuple, ndarray of object IDs to get or a dict of {key: object ID}. Returns: A Python object, a list of Python objects or a dict of {key: object}.
python/ray/experimental/api.py
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 tuples, ndarrays and dictionaries. Args: object_ids: Object ID of the object to get, a list, tuple, ndarray of object IDs to get or a dict of {key: object ID}. Returns: A Python object, a list of Python objects or a dict of {key: object}. """ 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 isinstance(v, ray.ObjectID) ] values = ray.get(ids_to_get) result = object_ids.copy() for key, value in zip(keys_to_get, values): result[key] = value return result else: return ray.get(object_ids)
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 tuples, ndarrays and dictionaries. Args: object_ids: Object ID of the object to get, a list, tuple, ndarray of object IDs to get or a dict of {key: object ID}. Returns: A Python object, a list of Python objects or a dict of {key: object}. """ 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 isinstance(v, ray.ObjectID) ] values = ray.get(ids_to_get) result = object_ids.copy() for key, value in zip(keys_to_get, values): result[key] = value return result else: return ray.get(object_ids)
[ "Get", "a", "single", "or", "a", "collection", "of", "remote", "objects", "from", "the", "object", "store", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/api.py#L9-L38
[ "def", "get", "(", "object_ids", ")", ":", "if", "isinstance", "(", "object_ids", ",", "(", "tuple", ",", "np", ".", "ndarray", ")", ")", ":", "return", "ray", ".", "get", "(", "list", "(", "object_ids", ")", ")", "elif", "isinstance", "(", "object_i...
4eade036a0505e244c976f36aaa2d64386b5129b
train
wait
Return a list of IDs that are ready and a list of IDs that are not. This method is identical to `ray.wait` except it adds support for tuples and ndarrays. Args: object_ids (List[ObjectID], Tuple(ObjectID), np.array(ObjectID)): List like of object IDs for objects that may or may not be ready. Note that these IDs must be unique. num_returns (int): The number of object IDs that should be returned. timeout (float): The maximum amount of time in seconds to wait before returning. Returns: A list of object IDs that are ready and a list of the remaining object IDs.
python/ray/experimental/api.py
def wait(object_ids, num_returns=1, timeout=None): """Return a list of IDs that are ready and a list of IDs that are not. This method is identical to `ray.wait` except it adds support for tuples and ndarrays. Args: object_ids (List[ObjectID], Tuple(ObjectID), np.array(ObjectID)): List like of object IDs for objects that may or may not be ready. Note that these IDs must be unique. num_returns (int): The number of object IDs that should be returned. timeout (float): The maximum amount of time in seconds to wait before returning. Returns: A list of object IDs that are ready and a list of the remaining object IDs. """ if isinstance(object_ids, (tuple, np.ndarray)): return ray.wait( list(object_ids), num_returns=num_returns, timeout=timeout) return ray.wait(object_ids, num_returns=num_returns, timeout=timeout)
def wait(object_ids, num_returns=1, timeout=None): """Return a list of IDs that are ready and a list of IDs that are not. This method is identical to `ray.wait` except it adds support for tuples and ndarrays. Args: object_ids (List[ObjectID], Tuple(ObjectID), np.array(ObjectID)): List like of object IDs for objects that may or may not be ready. Note that these IDs must be unique. num_returns (int): The number of object IDs that should be returned. timeout (float): The maximum amount of time in seconds to wait before returning. Returns: A list of object IDs that are ready and a list of the remaining object IDs. """ if isinstance(object_ids, (tuple, np.ndarray)): return ray.wait( list(object_ids), num_returns=num_returns, timeout=timeout) return ray.wait(object_ids, num_returns=num_returns, timeout=timeout)
[ "Return", "a", "list", "of", "IDs", "that", "are", "ready", "and", "a", "list", "of", "IDs", "that", "are", "not", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/api.py#L41-L63
[ "def", "wait", "(", "object_ids", ",", "num_returns", "=", "1", ",", "timeout", "=", "None", ")", ":", "if", "isinstance", "(", "object_ids", ",", "(", "tuple", ",", "np", ".", "ndarray", ")", ")", ":", "return", "ray", ".", "wait", "(", "list", "(...
4eade036a0505e244c976f36aaa2d64386b5129b
train
_raise_deprecation_note
User notification for deprecated parameter. Arguments: deprecated (str): Deprecated parameter. replacement (str): Replacement parameter to use instead. soft (bool): Fatal if True.
python/ray/tune/experiment.py
def _raise_deprecation_note(deprecated, replacement, soft=False): """User notification for deprecated parameter. Arguments: deprecated (str): Deprecated parameter. replacement (str): Replacement parameter to use instead. soft (bool): Fatal if True. """ 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 DeprecationWarning(error_msg)
def _raise_deprecation_note(deprecated, replacement, soft=False): """User notification for deprecated parameter. Arguments: deprecated (str): Deprecated parameter. replacement (str): Replacement parameter to use instead. soft (bool): Fatal if True. """ 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 DeprecationWarning(error_msg)
[ "User", "notification", "for", "deprecated", "parameter", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/experiment.py#L18-L32
[ "def", "_raise_deprecation_note", "(", "deprecated", ",", "replacement", ",", "soft", "=", "False", ")", ":", "error_msg", "=", "(", "\"`{deprecated}` is deprecated. Please use `{replacement}`. \"", "\"`{deprecated}` will be removed in future versions of \"", "\"Ray.\"", ".", "...
4eade036a0505e244c976f36aaa2d64386b5129b
train
convert_to_experiment_list
Produces a list of Experiment objects. Converts input from dict, single experiment, or list of experiments to list of experiments. If input is None, will return an empty list. Arguments: experiments (Experiment | list | dict): Experiments to run. Returns: List of experiments.
python/ray/tune/experiment.py
def convert_to_experiment_list(experiments): """Produces a list of Experiment objects. Converts input from dict, single experiment, or list of experiments to list of experiments. If input is None, will return an empty list. Arguments: experiments (Experiment | list | dict): Experiments to run. Returns: List of experiments. """ 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 in experiments.items() ] # Validate exp_list if (type(exp_list) is list and all(isinstance(exp, Experiment) for exp in exp_list)): if len(exp_list) > 1: logger.warning("All experiments will be " "using the same SearchAlgorithm.") else: raise TuneError("Invalid argument: {}".format(experiments)) return exp_list
def convert_to_experiment_list(experiments): """Produces a list of Experiment objects. Converts input from dict, single experiment, or list of experiments to list of experiments. If input is None, will return an empty list. Arguments: experiments (Experiment | list | dict): Experiments to run. Returns: List of experiments. """ 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 in experiments.items() ] # Validate exp_list if (type(exp_list) is list and all(isinstance(exp, Experiment) for exp in exp_list)): if len(exp_list) > 1: logger.warning("All experiments will be " "using the same SearchAlgorithm.") else: raise TuneError("Invalid argument: {}".format(experiments)) return exp_list
[ "Produces", "a", "list", "of", "Experiment", "objects", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/experiment.py#L180-L215
[ "def", "convert_to_experiment_list", "(", "experiments", ")", ":", "exp_list", "=", "experiments", "# Transform list if necessary", "if", "experiments", "is", "None", ":", "exp_list", "=", "[", "]", "elif", "isinstance", "(", "experiments", ",", "Experiment", ")", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
Experiment.from_json
Generates an Experiment object from JSON. Args: name (str): Name of Experiment. spec (dict): JSON configuration of experiment.
python/ray/tune/experiment.py
def from_json(cls, name, spec): """Generates an Experiment object from JSON. Args: name (str): Name of Experiment. spec (dict): JSON configuration of experiment. """ 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["env"] del spec["env"] spec = copy.deepcopy(spec) run_value = spec.pop("run") try: exp = cls(name, run_value, **spec) except TypeError: raise TuneError("Improper argument from JSON: {}.".format(spec)) return exp
def from_json(cls, name, spec): """Generates an Experiment object from JSON. Args: name (str): Name of Experiment. spec (dict): JSON configuration of experiment. """ 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["env"] del spec["env"] spec = copy.deepcopy(spec) run_value = spec.pop("run") try: exp = cls(name, run_value, **spec) except TypeError: raise TuneError("Improper argument from JSON: {}.".format(spec)) return exp
[ "Generates", "an", "Experiment", "object", "from", "JSON", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/experiment.py#L118-L142
[ "def", "from_json", "(", "cls", ",", "name", ",", "spec", ")", ":", "if", "\"run\"", "not", "in", "spec", ":", "raise", "TuneError", "(", "\"No trainable specified!\"", ")", "# Special case the `env` param for RLlib by automatically", "# moving it into the `config` sectio...
4eade036a0505e244c976f36aaa2d64386b5129b
train
Experiment._register_if_needed
Registers Trainable or Function at runtime. Assumes already registered if run_object is a string. Does not register lambdas because they could be part of variant generation. Also, does not inspect interface of given run_object. Arguments: run_object (str|function|class): Trainable to run. If string, assumes it is an ID and does not modify it. Otherwise, returns a string corresponding to the run_object name. Returns: A string representing the trainable identifier.
python/ray/tune/experiment.py
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 lambdas because they could be part of variant generation. Also, does not inspect interface of given run_object. Arguments: run_object (str|function|class): Trainable to run. If string, assumes it is an ID and does not modify it. Otherwise, returns a string corresponding to the run_object name. Returns: A string representing the trainable identifier. """ 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.") return run_object else: name = run_object.__name__ register_trainable(name, run_object) return name elif isinstance(run_object, type): name = run_object.__name__ register_trainable(name, run_object) return name else: raise TuneError("Improper 'run' - not string nor trainable.")
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 lambdas because they could be part of variant generation. Also, does not inspect interface of given run_object. Arguments: run_object (str|function|class): Trainable to run. If string, assumes it is an ID and does not modify it. Otherwise, returns a string corresponding to the run_object name. Returns: A string representing the trainable identifier. """ 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.") return run_object else: name = run_object.__name__ register_trainable(name, run_object) return name elif isinstance(run_object, type): name = run_object.__name__ register_trainable(name, run_object) return name else: raise TuneError("Improper 'run' - not string nor trainable.")
[ "Registers", "Trainable", "or", "Function", "at", "runtime", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/experiment.py#L145-L177
[ "def", "_register_if_needed", "(", "cls", ",", "run_object", ")", ":", "if", "isinstance", "(", "run_object", ",", "six", ".", "string_types", ")", ":", "return", "run_object", "elif", "isinstance", "(", "run_object", ",", "types", ".", "FunctionType", ")", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
tsqr
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 (a DistArray) and r (a numpy array) satisfying the following. - If q_full = ray.get(DistArray, q).assemble(), then q_full.shape == (M, K). - np.allclose(np.dot(q_full.T, q_full), np.eye(K)) == True. - If r_val = ray.get(np.ndarray, r), then r_val.shape == (K, N). - np.allclose(r, np.triu(r)) == True.
python/ray/experimental/array/distributed/linalg.py
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 (a DistArray) and r (a numpy array) satisfying the following. - If q_full = ray.get(DistArray, q).assemble(), then q_full.shape == (M, K). - np.allclose(np.dot(q_full.T, q_full), np.eye(K)) == True. - If r_val = ray.get(np.ndarray, r), then r_val.shape == (K, N). - np.allclose(r, np.triu(r)) == True. """ 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_blocks = a.num_blocks[0] K = int(np.ceil(np.log2(num_blocks))) + 1 q_tree = np.empty((num_blocks, K), dtype=object) current_rs = [] for i in range(num_blocks): block = a.objectids[i, 0] q, r = ra.linalg.qr.remote(block) q_tree[i, 0] = q current_rs.append(r) for j in range(1, K): new_rs = [] for i in range(int(np.ceil(1.0 * len(current_rs) / 2))): stacked_rs = ra.vstack.remote(*current_rs[(2 * i):(2 * i + 2)]) q, r = ra.linalg.qr.remote(stacked_rs) q_tree[i, j] = q new_rs.append(r) current_rs = new_rs assert len(current_rs) == 1, "len(current_rs) = " + str(len(current_rs)) # handle the special case in which the whole DistArray "a" fits in one # block and has fewer rows than columns, this is a bit ugly so think about # how to remove it if a.shape[0] >= a.shape[1]: q_shape = a.shape else: q_shape = [a.shape[0], a.shape[0]] q_num_blocks = core.DistArray.compute_num_blocks(q_shape) q_objectids = np.empty(q_num_blocks, dtype=object) q_result = core.DistArray(q_shape, q_objectids) # reconstruct output for i in range(num_blocks): q_block_current = q_tree[i, 0] ith_index = i for j in range(1, K): if np.mod(ith_index, 2) == 0: lower = [0, 0] upper = [a.shape[1], core.BLOCK_SIZE] else: lower = [a.shape[1], 0] upper = [2 * a.shape[1], core.BLOCK_SIZE] ith_index //= 2 q_block_current = ra.dot.remote( q_block_current, ra.subarray.remote(q_tree[ith_index, j], lower, upper)) q_result.objectids[i] = q_block_current r = current_rs[0] return q_result, ray.get(r)
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 (a DistArray) and r (a numpy array) satisfying the following. - If q_full = ray.get(DistArray, q).assemble(), then q_full.shape == (M, K). - np.allclose(np.dot(q_full.T, q_full), np.eye(K)) == True. - If r_val = ray.get(np.ndarray, r), then r_val.shape == (K, N). - np.allclose(r, np.triu(r)) == True. """ 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_blocks = a.num_blocks[0] K = int(np.ceil(np.log2(num_blocks))) + 1 q_tree = np.empty((num_blocks, K), dtype=object) current_rs = [] for i in range(num_blocks): block = a.objectids[i, 0] q, r = ra.linalg.qr.remote(block) q_tree[i, 0] = q current_rs.append(r) for j in range(1, K): new_rs = [] for i in range(int(np.ceil(1.0 * len(current_rs) / 2))): stacked_rs = ra.vstack.remote(*current_rs[(2 * i):(2 * i + 2)]) q, r = ra.linalg.qr.remote(stacked_rs) q_tree[i, j] = q new_rs.append(r) current_rs = new_rs assert len(current_rs) == 1, "len(current_rs) = " + str(len(current_rs)) # handle the special case in which the whole DistArray "a" fits in one # block and has fewer rows than columns, this is a bit ugly so think about # how to remove it if a.shape[0] >= a.shape[1]: q_shape = a.shape else: q_shape = [a.shape[0], a.shape[0]] q_num_blocks = core.DistArray.compute_num_blocks(q_shape) q_objectids = np.empty(q_num_blocks, dtype=object) q_result = core.DistArray(q_shape, q_objectids) # reconstruct output for i in range(num_blocks): q_block_current = q_tree[i, 0] ith_index = i for j in range(1, K): if np.mod(ith_index, 2) == 0: lower = [0, 0] upper = [a.shape[1], core.BLOCK_SIZE] else: lower = [a.shape[1], 0] upper = [2 * a.shape[1], core.BLOCK_SIZE] ith_index //= 2 q_block_current = ra.dot.remote( q_block_current, ra.subarray.remote(q_tree[ith_index, j], lower, upper)) q_result.objectids[i] = q_block_current r = current_rs[0] return q_result, ray.get(r)
[ "Perform", "a", "QR", "decomposition", "of", "a", "tall", "-", "skinny", "matrix", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/array/distributed/linalg.py#L15-L84
[ "def", "tsqr", "(", "a", ")", ":", "if", "len", "(", "a", ".", "shape", ")", "!=", "2", ":", "raise", "Exception", "(", "\"tsqr requires len(a.shape) == 2, but a.shape is \"", "\"{}\"", ".", "format", "(", "a", ".", "shape", ")", ")", "if", "a", ".", "...
4eade036a0505e244c976f36aaa2d64386b5129b
train
modified_lu
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. Args: q: A two dimensional orthonormal matrix q. Returns: A tuple of a lower triangular matrix l, an upper triangular matrix u, and a a vector representing a diagonal matrix s such that q - s = l * u.
python/ray/experimental/array/distributed/linalg.py
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. Args: q: A two dimensional orthonormal matrix q. Returns: A tuple of a lower triangular matrix l, an upper triangular matrix u, and a a vector representing a diagonal matrix 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 complement update. q_work[(i + 1):m, (i + 1):b] -= np.outer(q_work[(i + 1):m, i], q_work[i, (i + 1):b]) L = np.tril(q_work) for i in range(b): L[i, i] = 1 U = np.triu(q_work)[:b, :] # TODO(rkn): Get rid of the put below. return ray.get(core.numpy_to_dist.remote(ray.put(L))), U, S
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. Args: q: A two dimensional orthonormal matrix q. Returns: A tuple of a lower triangular matrix l, an upper triangular matrix u, and a a vector representing a diagonal matrix 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 complement update. q_work[(i + 1):m, (i + 1):b] -= np.outer(q_work[(i + 1):m, i], q_work[i, (i + 1):b]) L = np.tril(q_work) for i in range(b): L[i, i] = 1 U = np.triu(q_work)[:b, :] # TODO(rkn): Get rid of the put below. return ray.get(core.numpy_to_dist.remote(ray.put(L))), U, S
[ "Perform", "a", "modified", "LU", "decomposition", "of", "a", "matrix", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/array/distributed/linalg.py#L91-L125
[ "def", "modified_lu", "(", "q", ")", ":", "q", "=", "q", ".", "assemble", "(", ")", "m", ",", "b", "=", "q", ".", "shape", "[", "0", "]", ",", "q", ".", "shape", "[", "1", "]", "S", "=", "np", ".", "zeros", "(", "b", ")", "q_work", "=", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
_naturalize
Provides a natural representation for string for nice sorting.
python/ray/tune/trial_runner.py
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]
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]
[ "Provides", "a", "natural", "representation", "for", "string", "for", "nice", "sorting", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L30-L33
[ "def", "_naturalize", "(", "string", ")", ":", "splits", "=", "re", ".", "split", "(", "\"([0-9]+)\"", ",", "string", ")", "return", "[", "int", "(", "text", ")", "if", "text", ".", "isdigit", "(", ")", "else", "text", ".", "lower", "(", ")", "for"...
4eade036a0505e244c976f36aaa2d64386b5129b
train
_find_newest_ckpt
Returns path to most recently modified checkpoint.
python/ray/tune/trial_runner.py
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)
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)
[ "Returns", "path", "to", "most", "recently", "modified", "checkpoint", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L36-L42
[ "def", "_find_newest_ckpt", "(", "ckpt_dir", ")", ":", "full_paths", "=", "[", "os", ".", "path", ".", "join", "(", "ckpt_dir", ",", "fname", ")", "for", "fname", "in", "os", ".", "listdir", "(", "ckpt_dir", ")", "if", "fname", ".", "startswith", "(", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
TrialRunner.checkpoint
Saves execution state to `self._metadata_checkpoint_dir`. Overwrites the current session checkpoint, which starts when self is instantiated.
python/ray/tune/trial_runner.py
def checkpoint(self): """Saves execution state to `self._metadata_checkpoint_dir`. Overwrites the current session checkpoint, which starts when self is instantiated. """ 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_executor.get_checkpoints().values()), "runner_data": self.__getstate__(), "timestamp": time.time() } tmp_file_name = os.path.join(metadata_checkpoint_dir, ".tmp_checkpoint") with open(tmp_file_name, "w") as f: json.dump(runner_state, f, indent=2, cls=_TuneFunctionEncoder) os.rename( tmp_file_name, os.path.join(metadata_checkpoint_dir, TrialRunner.CKPT_FILE_TMPL.format(self._session_str))) return metadata_checkpoint_dir
def checkpoint(self): """Saves execution state to `self._metadata_checkpoint_dir`. Overwrites the current session checkpoint, which starts when self is instantiated. """ 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_executor.get_checkpoints().values()), "runner_data": self.__getstate__(), "timestamp": time.time() } tmp_file_name = os.path.join(metadata_checkpoint_dir, ".tmp_checkpoint") with open(tmp_file_name, "w") as f: json.dump(runner_state, f, indent=2, cls=_TuneFunctionEncoder) os.rename( tmp_file_name, os.path.join(metadata_checkpoint_dir, TrialRunner.CKPT_FILE_TMPL.format(self._session_str))) return metadata_checkpoint_dir
[ "Saves", "execution", "state", "to", "self", ".", "_metadata_checkpoint_dir", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L167-L193
[ "def", "checkpoint", "(", "self", ")", ":", "if", "not", "self", ".", "_metadata_checkpoint_dir", ":", "return", "metadata_checkpoint_dir", "=", "self", ".", "_metadata_checkpoint_dir", "if", "not", "os", ".", "path", ".", "exists", "(", "metadata_checkpoint_dir",...
4eade036a0505e244c976f36aaa2d64386b5129b
train
TrialRunner.restore
Restores all checkpointed trials from previous run. Requires user to manually re-register their objects. Also stops all ongoing trials. Args: metadata_checkpoint_dir (str): Path to metadata checkpoints. search_alg (SearchAlgorithm): Search Algorithm. Defaults to BasicVariantGenerator. scheduler (TrialScheduler): Scheduler for executing the experiment. trial_executor (TrialExecutor): Manage the execution of trials. Returns: runner (TrialRunner): A TrialRunner to resume experiments from.
python/ray/tune/trial_runner.py
def restore(cls, metadata_checkpoint_dir, search_alg=None, scheduler=None, trial_executor=None): """Restores all checkpointed trials from previous run. Requires user to manually re-register their objects. Also stops all ongoing trials. Args: metadata_checkpoint_dir (str): Path to metadata checkpoints. search_alg (SearchAlgorithm): Search Algorithm. Defaults to BasicVariantGenerator. scheduler (TrialScheduler): Scheduler for executing the experiment. trial_executor (TrialExecutor): Manage the execution of trials. Returns: runner (TrialRunner): A TrialRunner to resume experiments from. """ 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_dir), "This feature is experimental, " "and may not work with all search algorithms. ", "This will ignore any new changes to the specification." ])) from ray.tune.suggest import BasicVariantGenerator runner = TrialRunner( search_alg or BasicVariantGenerator(), scheduler=scheduler, trial_executor=trial_executor) runner.__setstate__(runner_state["runner_data"]) trials = [] for trial_cp in runner_state["checkpoints"]: new_trial = Trial(trial_cp["trainable_name"]) new_trial.__setstate__(trial_cp) trials += [new_trial] for trial in sorted( trials, key=lambda t: t.last_update_time, reverse=True): runner.add_trial(trial) return runner
def restore(cls, metadata_checkpoint_dir, search_alg=None, scheduler=None, trial_executor=None): """Restores all checkpointed trials from previous run. Requires user to manually re-register their objects. Also stops all ongoing trials. Args: metadata_checkpoint_dir (str): Path to metadata checkpoints. search_alg (SearchAlgorithm): Search Algorithm. Defaults to BasicVariantGenerator. scheduler (TrialScheduler): Scheduler for executing the experiment. trial_executor (TrialExecutor): Manage the execution of trials. Returns: runner (TrialRunner): A TrialRunner to resume experiments from. """ 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_dir), "This feature is experimental, " "and may not work with all search algorithms. ", "This will ignore any new changes to the specification." ])) from ray.tune.suggest import BasicVariantGenerator runner = TrialRunner( search_alg or BasicVariantGenerator(), scheduler=scheduler, trial_executor=trial_executor) runner.__setstate__(runner_state["runner_data"]) trials = [] for trial_cp in runner_state["checkpoints"]: new_trial = Trial(trial_cp["trainable_name"]) new_trial.__setstate__(trial_cp) trials += [new_trial] for trial in sorted( trials, key=lambda t: t.last_update_time, reverse=True): runner.add_trial(trial) return runner
[ "Restores", "all", "checkpointed", "trials", "from", "previous", "run", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L196-L245
[ "def", "restore", "(", "cls", ",", "metadata_checkpoint_dir", ",", "search_alg", "=", "None", ",", "scheduler", "=", "None", ",", "trial_executor", "=", "None", ")", ":", "newest_ckpt_path", "=", "_find_newest_ckpt", "(", "metadata_checkpoint_dir", ")", "with", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
TrialRunner.is_finished
Returns whether all trials have finished running.
python/ray/tune/trial_runner.py
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 self._search_alg.is_finished()
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 self._search_alg.is_finished()
[ "Returns", "whether", "all", "trials", "have", "finished", "running", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L247-L256
[ "def", "is_finished", "(", "self", ")", ":", "if", "self", ".", "_total_time", ">", "self", ".", "_global_time_limit", ":", "logger", ".", "warning", "(", "\"Exceeded global time limit {} / {}\"", ".", "format", "(", "self", ".", "_total_time", ",", "self", "....
4eade036a0505e244c976f36aaa2d64386b5129b
train
TrialRunner.step
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 state in between calls to step().
python/ray/tune/trial_runner.py
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 state in between calls to step(). """ 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_trial"): self.trial_executor.start_trial(next_trial) elif self.trial_executor.get_running_trials(): self._process_events() # blocking else: for trial in self._trials: if trial.status == Trial.PENDING: if not self.has_resources(trial.resources): raise TuneError( ("Insufficient cluster resources to launch trial: " "trial requested {} but the cluster has only {}. " "Pass `queue_trials=True` in " "ray.tune.run() or on the command " "line to queue trials until the cluster scales " "up. {}").format( trial.resources.summary_string(), self.trial_executor.resource_string(), trial._get_trainable_cls().resource_help( trial.config))) elif trial.status == Trial.PAUSED: raise TuneError( "There are paused trials, but no more pending " "trials with sufficient resources.") try: with warn_if_slow("experiment_checkpoint"): self.checkpoint() except Exception: logger.exception("Trial Runner checkpointing failed.") self._iteration += 1 if self._server: with warn_if_slow("server"): self._process_requests() if self.is_finished(): self._server.shutdown() with warn_if_slow("on_step_end"): self.trial_executor.on_step_end()
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 state in between calls to step(). """ 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_trial"): self.trial_executor.start_trial(next_trial) elif self.trial_executor.get_running_trials(): self._process_events() # blocking else: for trial in self._trials: if trial.status == Trial.PENDING: if not self.has_resources(trial.resources): raise TuneError( ("Insufficient cluster resources to launch trial: " "trial requested {} but the cluster has only {}. " "Pass `queue_trials=True` in " "ray.tune.run() or on the command " "line to queue trials until the cluster scales " "up. {}").format( trial.resources.summary_string(), self.trial_executor.resource_string(), trial._get_trainable_cls().resource_help( trial.config))) elif trial.status == Trial.PAUSED: raise TuneError( "There are paused trials, but no more pending " "trials with sufficient resources.") try: with warn_if_slow("experiment_checkpoint"): self.checkpoint() except Exception: logger.exception("Trial Runner checkpointing failed.") self._iteration += 1 if self._server: with warn_if_slow("server"): self._process_requests() if self.is_finished(): self._server.shutdown() with warn_if_slow("on_step_end"): self.trial_executor.on_step_end()
[ "Runs", "one", "step", "of", "the", "trial", "event", "loop", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L258-L308
[ "def", "step", "(", "self", ")", ":", "if", "self", ".", "is_finished", "(", ")", ":", "raise", "TuneError", "(", "\"Called step when all trials finished?\"", ")", "with", "warn_if_slow", "(", "\"on_step_begin\"", ")", ":", "self", ".", "trial_executor", ".", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
TrialRunner.add_trial
Adds a new trial to this TrialRunner. Trials may be added at any time. Args: trial (Trial): Trial to queue.
python/ray/tune/trial_runner.py
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)
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)
[ "Adds", "a", "new", "trial", "to", "this", "TrialRunner", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L322-L334
[ "def", "add_trial", "(", "self", ",", "trial", ")", ":", "trial", ".", "set_verbose", "(", "self", ".", "_verbose", ")", "self", ".", "_trials", ".", "append", "(", "trial", ")", "with", "warn_if_slow", "(", "\"scheduler.on_trial_add\"", ")", ":", "self", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
TrialRunner.debug_string
Returns a human readable message for printing to the console.
python/ray/tune/trial_runner.py
def debug_string(self, max_debug=MAX_DEBUG_TRIALS): """Returns a human readable message for printing to the console.""" messages = self._debug_messages() states = collections.defaultdict(set) limit_per_state = collections.Counter() for t in self._trials: states[t.status].add(t) # Show at most max_debug total, but divide the limit fairly while max_debug > 0: start_num = max_debug for s in states: if limit_per_state[s] >= len(states[s]): continue max_debug -= 1 limit_per_state[s] += 1 if max_debug == start_num: break for local_dir in sorted({t.local_dir for t in self._trials}): messages.append("Result logdir: {}".format(local_dir)) num_trials_per_state = { state: len(trials) for state, trials in states.items() } total_number_of_trials = sum(num_trials_per_state.values()) if total_number_of_trials > 0: messages.append("Number of trials: {} ({})" "".format(total_number_of_trials, num_trials_per_state)) for state, trials in sorted(states.items()): limit = limit_per_state[state] messages.append("{} trials:".format(state)) sorted_trials = sorted( trials, key=lambda t: _naturalize(t.experiment_tag)) if len(trials) > limit: tail_length = limit // 2 first = sorted_trials[:tail_length] for t in first: messages.append(" - {}:\t{}".format( t, t.progress_string())) messages.append( " ... {} not shown".format(len(trials) - tail_length * 2)) last = sorted_trials[-tail_length:] for t in last: messages.append(" - {}:\t{}".format( t, t.progress_string())) else: for t in sorted_trials: messages.append(" - {}:\t{}".format( t, t.progress_string())) return "\n".join(messages) + "\n"
def debug_string(self, max_debug=MAX_DEBUG_TRIALS): """Returns a human readable message for printing to the console.""" messages = self._debug_messages() states = collections.defaultdict(set) limit_per_state = collections.Counter() for t in self._trials: states[t.status].add(t) # Show at most max_debug total, but divide the limit fairly while max_debug > 0: start_num = max_debug for s in states: if limit_per_state[s] >= len(states[s]): continue max_debug -= 1 limit_per_state[s] += 1 if max_debug == start_num: break for local_dir in sorted({t.local_dir for t in self._trials}): messages.append("Result logdir: {}".format(local_dir)) num_trials_per_state = { state: len(trials) for state, trials in states.items() } total_number_of_trials = sum(num_trials_per_state.values()) if total_number_of_trials > 0: messages.append("Number of trials: {} ({})" "".format(total_number_of_trials, num_trials_per_state)) for state, trials in sorted(states.items()): limit = limit_per_state[state] messages.append("{} trials:".format(state)) sorted_trials = sorted( trials, key=lambda t: _naturalize(t.experiment_tag)) if len(trials) > limit: tail_length = limit // 2 first = sorted_trials[:tail_length] for t in first: messages.append(" - {}:\t{}".format( t, t.progress_string())) messages.append( " ... {} not shown".format(len(trials) - tail_length * 2)) last = sorted_trials[-tail_length:] for t in last: messages.append(" - {}:\t{}".format( t, t.progress_string())) else: for t in sorted_trials: messages.append(" - {}:\t{}".format( t, t.progress_string())) return "\n".join(messages) + "\n"
[ "Returns", "a", "human", "readable", "message", "for", "printing", "to", "the", "console", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L336-L390
[ "def", "debug_string", "(", "self", ",", "max_debug", "=", "MAX_DEBUG_TRIALS", ")", ":", "messages", "=", "self", ".", "_debug_messages", "(", ")", "states", "=", "collections", ".", "defaultdict", "(", "set", ")", "limit_per_state", "=", "collections", ".", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
TrialRunner._get_next_trial
Replenishes queue. Blocks if all trials queued have finished, but search algorithm is still not finished.
python/ray/tune/trial_runner.py
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(self) return trial
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(self) return trial
[ "Replenishes", "queue", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L423-L434
[ "def", "_get_next_trial", "(", "self", ")", ":", "trials_done", "=", "all", "(", "trial", ".", "is_finished", "(", ")", "for", "trial", "in", "self", ".", "_trials", ")", "wait_for_trial", "=", "trials_done", "and", "not", "self", ".", "_search_alg", ".", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
TrialRunner._checkpoint_trial_if_needed
Checkpoints trial based off trial.last_result.
python/ray/tune/trial_runner.py
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)
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)
[ "Checkpoints", "trial", "based", "off", "trial", ".", "last_result", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L506-L512
[ "def", "_checkpoint_trial_if_needed", "(", "self", ",", "trial", ")", ":", "if", "trial", ".", "should_checkpoint", "(", ")", ":", "# Save trial runtime if possible", "if", "hasattr", "(", "trial", ",", "\"runner\"", ")", "and", "trial", ".", "runner", ":", "s...
4eade036a0505e244c976f36aaa2d64386b5129b
train
TrialRunner._try_recover
Tries to recover trial. Notifies SearchAlgorithm and Scheduler if failure to recover. Args: trial (Trial): Trial to recover. error_msg (str): Error message from prior to invoking this method.
python/ray/tune/trial_runner.py
def _try_recover(self, trial, error_msg): """Tries to recover trial. Notifies SearchAlgorithm and Scheduler if failure to recover. Args: trial (Trial): Trial to recover. error_msg (str): Error message from prior to invoking this method. """ 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): logger.info("Attempting to recover" " trial state from last checkpoint.") self.trial_executor.start_trial(trial) if trial.status == Trial.ERROR: raise RuntimeError("Trial did not start correctly.") else: logger.debug("Notifying Scheduler and requeueing trial.") self._requeue_trial(trial) except Exception: logger.exception("Error recovering trial from checkpoint, abort.") self._scheduler_alg.on_trial_error(self, trial) self._search_alg.on_trial_complete(trial.trial_id, error=True)
def _try_recover(self, trial, error_msg): """Tries to recover trial. Notifies SearchAlgorithm and Scheduler if failure to recover. Args: trial (Trial): Trial to recover. error_msg (str): Error message from prior to invoking this method. """ 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): logger.info("Attempting to recover" " trial state from last checkpoint.") self.trial_executor.start_trial(trial) if trial.status == Trial.ERROR: raise RuntimeError("Trial did not start correctly.") else: logger.debug("Notifying Scheduler and requeueing trial.") self._requeue_trial(trial) except Exception: logger.exception("Error recovering trial from checkpoint, abort.") self._scheduler_alg.on_trial_error(self, trial) self._search_alg.on_trial_complete(trial.trial_id, error=True)
[ "Tries", "to", "recover", "trial", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L514-L542
[ "def", "_try_recover", "(", "self", ",", "trial", ",", "error_msg", ")", ":", "try", ":", "self", ".", "trial_executor", ".", "stop_trial", "(", "trial", ",", "error", "=", "error_msg", "is", "not", "None", ",", "error_msg", "=", "error_msg", ",", "stop_...
4eade036a0505e244c976f36aaa2d64386b5129b
train
TrialRunner._requeue_trial
Notification to TrialScheduler and requeue trial. This does not notify the SearchAlgorithm because the function evaluation is still in progress.
python/ray/tune/trial_runner.py
def _requeue_trial(self, trial): """Notification to TrialScheduler and requeue trial. This does not notify the SearchAlgorithm because the function evaluation is still in progress. """ 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)
def _requeue_trial(self, trial): """Notification to TrialScheduler and requeue trial. This does not notify the SearchAlgorithm because the function evaluation is still in progress. """ 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)
[ "Notification", "to", "TrialScheduler", "and", "requeue", "trial", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L544-L553
[ "def", "_requeue_trial", "(", "self", ",", "trial", ")", ":", "self", ".", "_scheduler_alg", ".", "on_trial_error", "(", "self", ",", "trial", ")", "self", ".", "trial_executor", ".", "set_status", "(", "trial", ",", "Trial", ".", "PENDING", ")", "with", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
TrialRunner._update_trial_queue
Adds next trials to queue if possible. Note that the timeout is currently unexposed to the user. Args: blocking (bool): Blocks until either a trial is available or is_finished (timeout or search algorithm finishes). timeout (int): Seconds before blocking times out.
python/ray/tune/trial_runner.py
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. Args: blocking (bool): Blocks until either a trial is available or is_finished (timeout or search algorithm finishes). timeout (int): Seconds before blocking times out. """ 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 finished while (not trials and not self.is_finished() and time.time() - start < timeout): logger.info("Blocking for next trial...") trials = self._search_alg.next_trials() time.sleep(1) for trial in trials: self.add_trial(trial)
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. Args: blocking (bool): Blocks until either a trial is available or is_finished (timeout or search algorithm finishes). timeout (int): Seconds before blocking times out. """ 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 finished while (not trials and not self.is_finished() and time.time() - start < timeout): logger.info("Blocking for next trial...") trials = self._search_alg.next_trials() time.sleep(1) for trial in trials: self.add_trial(trial)
[ "Adds", "next", "trials", "to", "queue", "if", "possible", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L555-L578
[ "def", "_update_trial_queue", "(", "self", ",", "blocking", "=", "False", ",", "timeout", "=", "600", ")", ":", "trials", "=", "self", ".", "_search_alg", ".", "next_trials", "(", ")", "if", "blocking", "and", "not", "trials", ":", "start", "=", "time", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
TrialRunner.stop_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 `on_trial_complete(..., early_terminated=True) for search_alg. Otherwise waits for result for the trial and calls `on_trial_complete` for scheduler and search_alg if RUNNING.
python/ray/tune/trial_runner.py
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 `on_trial_complete(..., early_terminated=True) for search_alg. Otherwise waits for result for the trial and calls `on_trial_complete` for scheduler and search_alg if RUNNING. """ 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.trial_id, early_terminated=True) elif trial.status is Trial.RUNNING: try: result = self.trial_executor.fetch_result(trial) trial.update_last_result(result, terminate=True) self._scheduler_alg.on_trial_complete(self, trial, result) self._search_alg.on_trial_complete( trial.trial_id, result=result) except Exception: error_msg = traceback.format_exc() logger.exception("Error processing event.") self._scheduler_alg.on_trial_error(self, trial) self._search_alg.on_trial_complete(trial.trial_id, error=True) error = True self.trial_executor.stop_trial(trial, error=error, error_msg=error_msg)
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 `on_trial_complete(..., early_terminated=True) for search_alg. Otherwise waits for result for the trial and calls `on_trial_complete` for scheduler and search_alg if RUNNING. """ 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.trial_id, early_terminated=True) elif trial.status is Trial.RUNNING: try: result = self.trial_executor.fetch_result(trial) trial.update_last_result(result, terminate=True) self._scheduler_alg.on_trial_complete(self, trial, result) self._search_alg.on_trial_complete( trial.trial_id, result=result) except Exception: error_msg = traceback.format_exc() logger.exception("Error processing event.") self._scheduler_alg.on_trial_error(self, trial) self._search_alg.on_trial_complete(trial.trial_id, error=True) error = True self.trial_executor.stop_trial(trial, error=error, error_msg=error_msg)
[ "Stops", "trial", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L588-L620
[ "def", "stop_trial", "(", "self", ",", "trial", ")", ":", "error", "=", "False", "error_msg", "=", "None", "if", "trial", ".", "status", "in", "[", "Trial", ".", "ERROR", ",", "Trial", ".", "TERMINATED", "]", ":", "return", "elif", "trial", ".", "sta...
4eade036a0505e244c976f36aaa2d64386b5129b
train
run_func
Helper function for running examples
examples/cython/cython_main.py
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
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
[ "Helper", "function", "for", "running", "examples" ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/examples/cython/cython_main.py#L13-L26
[ "def", "run_func", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ray", ".", "init", "(", ")", "func", "=", "ray", ".", "remote", "(", "func", ")", "# NOTE: kwargs not allowed for now", "result", "=", "ray", ".", "get", "(", "func...
4eade036a0505e244c976f36aaa2d64386b5129b
train
example6
Cython simple class
examples/cython/cython_main.py
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)
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)
[ "Cython", "simple", "class" ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/examples/cython/cython_main.py#L73-L85
[ "def", "example6", "(", ")", ":", "ray", ".", "init", "(", ")", "cls", "=", "ray", ".", "remote", "(", "cyth", ".", "simple_class", ")", "a1", "=", "cls", ".", "remote", "(", ")", "a2", "=", "cls", ".", "remote", "(", ")", "result1", "=", "ray"...
4eade036a0505e244c976f36aaa2d64386b5129b
train
example8
Cython with blas. NOTE: requires scipy
examples/cython/cython_main.py
def example8(): """Cython with blas. NOTE: requires scipy""" # See cython_blas.pyx for argument documentation mat = np.array([[[2.0, 2.0], [2.0, 2.0]], [[2.0, 2.0], [2.0, 2.0]]], dtype=np.float32) result = np.zeros((2, 2), np.float32, order="C") run_func(cyth.compute_kernel_matrix, "L", "T", 2, 2, 1.0, mat, 0, 2, 1.0, result, 2 )
def example8(): """Cython with blas. NOTE: requires scipy""" # See cython_blas.pyx for argument documentation mat = np.array([[[2.0, 2.0], [2.0, 2.0]], [[2.0, 2.0], [2.0, 2.0]]], dtype=np.float32) result = np.zeros((2, 2), np.float32, order="C") run_func(cyth.compute_kernel_matrix, "L", "T", 2, 2, 1.0, mat, 0, 2, 1.0, result, 2 )
[ "Cython", "with", "blas", ".", "NOTE", ":", "requires", "scipy" ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/examples/cython/cython_main.py#L96-L116
[ "def", "example8", "(", ")", ":", "# See cython_blas.pyx for argument documentation", "mat", "=", "np", ".", "array", "(", "[", "[", "[", "2.0", ",", "2.0", "]", ",", "[", "2.0", ",", "2.0", "]", "]", ",", "[", "[", "2.0", ",", "2.0", "]", ",", "["...
4eade036a0505e244c976f36aaa2d64386b5129b
train
_adjust_nstep
Rewrites the given trajectory fragments to encode n-step rewards. reward[i] = ( reward[i] * gamma**0 + reward[i+1] * gamma**1 + ... + reward[i+n_step-1] * gamma**(n_step-1)) The ith new_obs is also adjusted to point to the (i+n_step-1)'th new obs. At the end of the trajectory, n is truncated to fit in the traj length.
python/ray/rllib/agents/dqn/dqn_policy_graph.py
def _adjust_nstep(n_step, gamma, obs, actions, rewards, new_obs, dones): """Rewrites the given trajectory fragments to encode n-step rewards. reward[i] = ( reward[i] * gamma**0 + reward[i+1] * gamma**1 + ... + reward[i+n_step-1] * gamma**(n_step-1)) The ith new_obs is also adjusted to point to the (i+n_step-1)'th new obs. At the end of the trajectory, n is truncated to fit in the traj length. """ 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[i] += gamma**j * rewards[i + j]
def _adjust_nstep(n_step, gamma, obs, actions, rewards, new_obs, dones): """Rewrites the given trajectory fragments to encode n-step rewards. reward[i] = ( reward[i] * gamma**0 + reward[i+1] * gamma**1 + ... + reward[i+n_step-1] * gamma**(n_step-1)) The ith new_obs is also adjusted to point to the (i+n_step-1)'th new obs. At the end of the trajectory, n is truncated to fit in the traj length. """ 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[i] += gamma**j * rewards[i + j]
[ "Rewrites", "the", "given", "trajectory", "fragments", "to", "encode", "n", "-", "step", "rewards", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/dqn/dqn_policy_graph.py#L603-L625
[ "def", "_adjust_nstep", "(", "n_step", ",", "gamma", ",", "obs", ",", "actions", ",", "rewards", ",", "new_obs", ",", "dones", ")", ":", "assert", "not", "any", "(", "dones", "[", ":", "-", "1", "]", ")", ",", "\"Unexpected done in middle of trajectory\"",...
4eade036a0505e244c976f36aaa2d64386b5129b
train
_reduce_mean_ignore_inf
Same as tf.reduce_mean() but ignores -inf values.
python/ray/rllib/agents/dqn/dqn_policy_graph.py
def _reduce_mean_ignore_inf(x, axis): """Same as tf.reduce_mean() but ignores -inf values.""" mask = tf.not_equal(x, tf.float32.min) x_zeroed = tf.where(mask, x, tf.zeros_like(x)) return (tf.reduce_sum(x_zeroed, axis) / tf.reduce_sum( tf.cast(mask, tf.float32), axis))
def _reduce_mean_ignore_inf(x, axis): """Same as tf.reduce_mean() but ignores -inf values.""" mask = tf.not_equal(x, tf.float32.min) x_zeroed = tf.where(mask, x, tf.zeros_like(x)) return (tf.reduce_sum(x_zeroed, axis) / tf.reduce_sum( tf.cast(mask, tf.float32), axis))
[ "Same", "as", "tf", ".", "reduce_mean", "()", "but", "ignores", "-", "inf", "values", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/dqn/dqn_policy_graph.py#L652-L657
[ "def", "_reduce_mean_ignore_inf", "(", "x", ",", "axis", ")", ":", "mask", "=", "tf", ".", "not_equal", "(", "x", ",", "tf", ".", "float32", ".", "min", ")", "x_zeroed", "=", "tf", ".", "where", "(", "mask", ",", "x", ",", "tf", ".", "zeros_like", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
_huber_loss
Reference: https://en.wikipedia.org/wiki/Huber_loss
python/ray/rllib/agents/dqn/dqn_policy_graph.py
def _huber_loss(x, delta=1.0): """Reference: https://en.wikipedia.org/wiki/Huber_loss""" return tf.where( tf.abs(x) < delta, tf.square(x) * 0.5, delta * (tf.abs(x) - 0.5 * delta))
def _huber_loss(x, delta=1.0): """Reference: https://en.wikipedia.org/wiki/Huber_loss""" return tf.where( tf.abs(x) < delta, tf.square(x) * 0.5, delta * (tf.abs(x) - 0.5 * delta))
[ "Reference", ":", "https", ":", "//", "en", ".", "wikipedia", ".", "org", "/", "wiki", "/", "Huber_loss" ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/dqn/dqn_policy_graph.py#L660-L664
[ "def", "_huber_loss", "(", "x", ",", "delta", "=", "1.0", ")", ":", "return", "tf", ".", "where", "(", "tf", ".", "abs", "(", "x", ")", "<", "delta", ",", "tf", ".", "square", "(", "x", ")", "*", "0.5", ",", "delta", "*", "(", "tf", ".", "a...
4eade036a0505e244c976f36aaa2d64386b5129b
train
_minimize_and_clip
Minimized `objective` using `optimizer` w.r.t. variables in `var_list` while ensure the norm of the gradients for each variable is clipped to `clip_val`
python/ray/rllib/agents/dqn/dqn_policy_graph.py
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 norm of the gradients for each variable is clipped to `clip_val` """ 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
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 norm of the gradients for each variable is clipped to `clip_val` """ 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
[ "Minimized", "objective", "using", "optimizer", "w", ".", "r", ".", "t", ".", "variables", "in", "var_list", "while", "ensure", "the", "norm", "of", "the", "gradients", "for", "each", "variable", "is", "clipped", "to", "clip_val" ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/dqn/dqn_policy_graph.py#L667-L676
[ "def", "_minimize_and_clip", "(", "optimizer", ",", "objective", ",", "var_list", ",", "clip_val", "=", "10", ")", ":", "gradients", "=", "optimizer", ".", "compute_gradients", "(", "objective", ",", "var_list", "=", "var_list", ")", "for", "i", ",", "(", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
_scope_vars
Get variables inside a scope The scope can be specified as a string Parameters ---------- scope: str or VariableScope scope in which the variables reside. trainable_only: bool whether or not to return only the variables that were marked as trainable. Returns ------- vars: [tf.Variable] list of variables in `scope`.
python/ray/rllib/agents/dqn/dqn_policy_graph.py
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 scope in which the variables reside. trainable_only: bool whether or not to return only the variables that were marked as trainable. Returns ------- vars: [tf.Variable] list of variables in `scope`. """ return tf.get_collection( tf.GraphKeys.TRAINABLE_VARIABLES if trainable_only else tf.GraphKeys.VARIABLES, scope=scope if isinstance(scope, str) else scope.name)
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 scope in which the variables reside. trainable_only: bool whether or not to return only the variables that were marked as trainable. Returns ------- vars: [tf.Variable] list of variables in `scope`. """ return tf.get_collection( tf.GraphKeys.TRAINABLE_VARIABLES if trainable_only else tf.GraphKeys.VARIABLES, scope=scope if isinstance(scope, str) else scope.name)
[ "Get", "variables", "inside", "a", "scope", "The", "scope", "can", "be", "specified", "as", "a", "string" ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/dqn/dqn_policy_graph.py#L679-L700
[ "def", "_scope_vars", "(", "scope", ",", "trainable_only", "=", "False", ")", ":", "return", "tf", ".", "get_collection", "(", "tf", ".", "GraphKeys", ".", "TRAINABLE_VARIABLES", "if", "trainable_only", "else", "tf", ".", "GraphKeys", ".", "VARIABLES", ",", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
QNetwork.noisy_layer
a common dense layer: y = w^{T}x + b a noisy layer: y = (w + \epsilon_w*\sigma_w)^{T}x + (b+\epsilon_b*\sigma_b) where \epsilon are random variables sampled from factorized normal distributions and \sigma are trainable variables which are expected to vanish along the training procedure
python/ray/rllib/agents/dqn/dqn_policy_graph.py
def noisy_layer(self, prefix, action_in, out_size, sigma0, non_linear=True): """ a common dense layer: y = w^{T}x + b a noisy layer: y = (w + \epsilon_w*\sigma_w)^{T}x + (b+\epsilon_b*\sigma_b) where \epsilon are random variables sampled from factorized normal distributions and \sigma are trainable variables which are expected to vanish along the training procedure """ in_size = int(action_in.shape[1]) epsilon_in = tf.random_normal(shape=[in_size]) epsilon_out = tf.random_normal(shape=[out_size]) epsilon_in = self.f_epsilon(epsilon_in) epsilon_out = self.f_epsilon(epsilon_out) epsilon_w = tf.matmul( a=tf.expand_dims(epsilon_in, -1), b=tf.expand_dims(epsilon_out, 0)) epsilon_b = epsilon_out sigma_w = tf.get_variable( name=prefix + "_sigma_w", shape=[in_size, out_size], dtype=tf.float32, initializer=tf.random_uniform_initializer( minval=-1.0 / np.sqrt(float(in_size)), maxval=1.0 / np.sqrt(float(in_size)))) # TF noise generation can be unreliable on GPU # If generating the noise on the CPU, # lowering sigma0 to 0.1 may be helpful sigma_b = tf.get_variable( name=prefix + "_sigma_b", shape=[out_size], dtype=tf.float32, # 0.5~GPU, 0.1~CPU initializer=tf.constant_initializer( sigma0 / np.sqrt(float(in_size)))) w = tf.get_variable( name=prefix + "_fc_w", shape=[in_size, out_size], dtype=tf.float32, initializer=layers.xavier_initializer()) b = tf.get_variable( name=prefix + "_fc_b", shape=[out_size], dtype=tf.float32, initializer=tf.zeros_initializer()) action_activation = tf.nn.xw_plus_b(action_in, w + sigma_w * epsilon_w, b + sigma_b * epsilon_b) if not non_linear: return action_activation return tf.nn.relu(action_activation)
def noisy_layer(self, prefix, action_in, out_size, sigma0, non_linear=True): """ a common dense layer: y = w^{T}x + b a noisy layer: y = (w + \epsilon_w*\sigma_w)^{T}x + (b+\epsilon_b*\sigma_b) where \epsilon are random variables sampled from factorized normal distributions and \sigma are trainable variables which are expected to vanish along the training procedure """ in_size = int(action_in.shape[1]) epsilon_in = tf.random_normal(shape=[in_size]) epsilon_out = tf.random_normal(shape=[out_size]) epsilon_in = self.f_epsilon(epsilon_in) epsilon_out = self.f_epsilon(epsilon_out) epsilon_w = tf.matmul( a=tf.expand_dims(epsilon_in, -1), b=tf.expand_dims(epsilon_out, 0)) epsilon_b = epsilon_out sigma_w = tf.get_variable( name=prefix + "_sigma_w", shape=[in_size, out_size], dtype=tf.float32, initializer=tf.random_uniform_initializer( minval=-1.0 / np.sqrt(float(in_size)), maxval=1.0 / np.sqrt(float(in_size)))) # TF noise generation can be unreliable on GPU # If generating the noise on the CPU, # lowering sigma0 to 0.1 may be helpful sigma_b = tf.get_variable( name=prefix + "_sigma_b", shape=[out_size], dtype=tf.float32, # 0.5~GPU, 0.1~CPU initializer=tf.constant_initializer( sigma0 / np.sqrt(float(in_size)))) w = tf.get_variable( name=prefix + "_fc_w", shape=[in_size, out_size], dtype=tf.float32, initializer=layers.xavier_initializer()) b = tf.get_variable( name=prefix + "_fc_b", shape=[out_size], dtype=tf.float32, initializer=tf.zeros_initializer()) action_activation = tf.nn.xw_plus_b(action_in, w + sigma_w * epsilon_w, b + sigma_b * epsilon_b) if not non_linear: return action_activation return tf.nn.relu(action_activation)
[ "a", "common", "dense", "layer", ":", "y", "=", "w^", "{", "T", "}", "x", "+", "b", "a", "noisy", "layer", ":", "y", "=", "(", "w", "+", "\\", "epsilon_w", "*", "\\", "sigma_w", ")", "^", "{", "T", "}", "x", "+", "(", "b", "+", "\\", "eps...
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/dqn/dqn_policy_graph.py#L256-L308
[ "def", "noisy_layer", "(", "self", ",", "prefix", ",", "action_in", ",", "out_size", ",", "sigma0", ",", "non_linear", "=", "True", ")", ":", "in_size", "=", "int", "(", "action_in", ".", "shape", "[", "1", "]", ")", "epsilon_in", "=", "tf", ".", "ra...
4eade036a0505e244c976f36aaa2d64386b5129b
train
ConvNetBuilder.get_custom_getter
Returns a custom getter that this class's methods must be called All methods of this class must be called under a variable scope that was passed this custom getter. Example: ```python network = ConvNetBuilder(...) with tf.variable_scope("cg", custom_getter=network.get_custom_getter()): network.conv(...) # Call more methods of network here ``` Currently, this custom getter only does anything if self.use_tf_layers is True. In that case, it causes variables to be stored as dtype self.variable_type, then casted to the requested dtype, instead of directly storing the variable as the requested dtype.
python/ray/experimental/sgd/tfbench/convnet_builder.py
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 that was passed this custom getter. Example: ```python network = ConvNetBuilder(...) with tf.variable_scope("cg", custom_getter=network.get_custom_getter()): network.conv(...) # Call more methods of network here ``` Currently, this custom getter only does anything if self.use_tf_layers is True. In that case, it causes variables to be stored as dtype self.variable_type, then casted to the requested dtype, instead of directly storing the variable as the requested dtype. """ 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): kwargs["dtype"] = self.variable_dtype var = getter(*args, **kwargs) if var.dtype.base_dtype != requested_dtype: var = tf.cast(var, requested_dtype) return var return inner_custom_getter
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 that was passed this custom getter. Example: ```python network = ConvNetBuilder(...) with tf.variable_scope("cg", custom_getter=network.get_custom_getter()): network.conv(...) # Call more methods of network here ``` Currently, this custom getter only does anything if self.use_tf_layers is True. In that case, it causes variables to be stored as dtype self.variable_type, then casted to the requested dtype, instead of directly storing the variable as the requested dtype. """ 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): kwargs["dtype"] = self.variable_dtype var = getter(*args, **kwargs) if var.dtype.base_dtype != requested_dtype: var = tf.cast(var, requested_dtype) return var return inner_custom_getter
[ "Returns", "a", "custom", "getter", "that", "this", "class", "s", "methods", "must", "be", "called" ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/sgd/tfbench/convnet_builder.py#L58-L89
[ "def", "get_custom_getter", "(", "self", ")", ":", "def", "inner_custom_getter", "(", "getter", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "use_tf_layers", ":", "return", "getter", "(", "*", "args", ",", "*", "*", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
ConvNetBuilder.switch_to_aux_top_layer
Context that construct cnn in the auxiliary arm.
python/ray/experimental/sgd/tfbench/convnet_builder.py
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_layer = self.top_layer self.aux_top_size = self.top_size self.top_layer = saved_top_layer self.top_size = saved_top_size
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_layer = self.top_layer self.aux_top_size = self.top_size self.top_layer = saved_top_layer self.top_size = saved_top_size
[ "Context", "that", "construct", "cnn", "in", "the", "auxiliary", "arm", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/sgd/tfbench/convnet_builder.py#L92-L104
[ "def", "switch_to_aux_top_layer", "(", "self", ")", ":", "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", "=",...
4eade036a0505e244c976f36aaa2d64386b5129b
train
ConvNetBuilder.conv
Construct a conv2d layer on top of cnn.
python/ray/experimental/sgd/tfbench/convnet_builder.py
def conv(self, num_out_channels, k_height, k_width, d_height=1, d_width=1, mode="SAME", input_layer=None, num_channels_in=None, use_batch_norm=None, stddev=None, activation="relu", bias=0.0): """Construct a conv2d layer on top of cnn.""" if input_layer is None: input_layer = self.top_layer if num_channels_in is None: num_channels_in = self.top_size kernel_initializer = None if stddev is not None: kernel_initializer = tf.truncated_normal_initializer(stddev=stddev) name = "conv" + str(self.counts["conv"]) self.counts["conv"] += 1 with tf.variable_scope(name): strides = [1, d_height, d_width, 1] if self.data_format == "NCHW": strides = [strides[0], strides[3], strides[1], strides[2]] if mode != "SAME_RESNET": conv = self._conv2d_impl( input_layer, num_channels_in, num_out_channels, kernel_size=[k_height, k_width], strides=[d_height, d_width], padding=mode, kernel_initializer=kernel_initializer) else: # Special padding mode for ResNet models if d_height == 1 and d_width == 1: conv = self._conv2d_impl( input_layer, num_channels_in, num_out_channels, kernel_size=[k_height, k_width], strides=[d_height, d_width], padding="SAME", kernel_initializer=kernel_initializer) else: rate = 1 # Unused (for 'a trous' convolutions) kernel_height_effective = k_height + (k_height - 1) * ( rate - 1) pad_h_beg = (kernel_height_effective - 1) // 2 pad_h_end = kernel_height_effective - 1 - pad_h_beg kernel_width_effective = k_width + (k_width - 1) * ( rate - 1) pad_w_beg = (kernel_width_effective - 1) // 2 pad_w_end = kernel_width_effective - 1 - pad_w_beg padding = [[0, 0], [pad_h_beg, pad_h_end], [pad_w_beg, pad_w_end], [0, 0]] if self.data_format == "NCHW": padding = [ padding[0], padding[3], padding[1], padding[2] ] input_layer = tf.pad(input_layer, padding) conv = self._conv2d_impl( input_layer, num_channels_in, num_out_channels, kernel_size=[k_height, k_width], strides=[d_height, d_width], padding="VALID", kernel_initializer=kernel_initializer) if use_batch_norm is None: use_batch_norm = self.use_batch_norm if not use_batch_norm: if bias is not None: biases = self.get_variable( "biases", [num_out_channels], self.variable_dtype, self.dtype, initializer=tf.constant_initializer(bias)) biased = tf.reshape( tf.nn.bias_add( conv, biases, data_format=self.data_format), conv.get_shape()) else: biased = conv else: self.top_layer = conv self.top_size = num_out_channels biased = self.batch_norm(**self.batch_norm_config) if activation == "relu": conv1 = tf.nn.relu(biased) elif activation == "linear" or activation is None: conv1 = biased elif activation == "tanh": conv1 = tf.nn.tanh(biased) else: raise KeyError("Invalid activation type \"%s\"" % activation) self.top_layer = conv1 self.top_size = num_out_channels return conv1
def conv(self, num_out_channels, k_height, k_width, d_height=1, d_width=1, mode="SAME", input_layer=None, num_channels_in=None, use_batch_norm=None, stddev=None, activation="relu", bias=0.0): """Construct a conv2d layer on top of cnn.""" if input_layer is None: input_layer = self.top_layer if num_channels_in is None: num_channels_in = self.top_size kernel_initializer = None if stddev is not None: kernel_initializer = tf.truncated_normal_initializer(stddev=stddev) name = "conv" + str(self.counts["conv"]) self.counts["conv"] += 1 with tf.variable_scope(name): strides = [1, d_height, d_width, 1] if self.data_format == "NCHW": strides = [strides[0], strides[3], strides[1], strides[2]] if mode != "SAME_RESNET": conv = self._conv2d_impl( input_layer, num_channels_in, num_out_channels, kernel_size=[k_height, k_width], strides=[d_height, d_width], padding=mode, kernel_initializer=kernel_initializer) else: # Special padding mode for ResNet models if d_height == 1 and d_width == 1: conv = self._conv2d_impl( input_layer, num_channels_in, num_out_channels, kernel_size=[k_height, k_width], strides=[d_height, d_width], padding="SAME", kernel_initializer=kernel_initializer) else: rate = 1 # Unused (for 'a trous' convolutions) kernel_height_effective = k_height + (k_height - 1) * ( rate - 1) pad_h_beg = (kernel_height_effective - 1) // 2 pad_h_end = kernel_height_effective - 1 - pad_h_beg kernel_width_effective = k_width + (k_width - 1) * ( rate - 1) pad_w_beg = (kernel_width_effective - 1) // 2 pad_w_end = kernel_width_effective - 1 - pad_w_beg padding = [[0, 0], [pad_h_beg, pad_h_end], [pad_w_beg, pad_w_end], [0, 0]] if self.data_format == "NCHW": padding = [ padding[0], padding[3], padding[1], padding[2] ] input_layer = tf.pad(input_layer, padding) conv = self._conv2d_impl( input_layer, num_channels_in, num_out_channels, kernel_size=[k_height, k_width], strides=[d_height, d_width], padding="VALID", kernel_initializer=kernel_initializer) if use_batch_norm is None: use_batch_norm = self.use_batch_norm if not use_batch_norm: if bias is not None: biases = self.get_variable( "biases", [num_out_channels], self.variable_dtype, self.dtype, initializer=tf.constant_initializer(bias)) biased = tf.reshape( tf.nn.bias_add( conv, biases, data_format=self.data_format), conv.get_shape()) else: biased = conv else: self.top_layer = conv self.top_size = num_out_channels biased = self.batch_norm(**self.batch_norm_config) if activation == "relu": conv1 = tf.nn.relu(biased) elif activation == "linear" or activation is None: conv1 = biased elif activation == "tanh": conv1 = tf.nn.tanh(biased) else: raise KeyError("Invalid activation type \"%s\"" % activation) self.top_layer = conv1 self.top_size = num_out_channels return conv1
[ "Construct", "a", "conv2d", "layer", "on", "top", "of", "cnn", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/sgd/tfbench/convnet_builder.py#L143-L243
[ "def", "conv", "(", "self", ",", "num_out_channels", ",", "k_height", ",", "k_width", ",", "d_height", "=", "1", ",", "d_width", "=", "1", ",", "mode", "=", "\"SAME\"", ",", "input_layer", "=", "None", ",", "num_channels_in", "=", "None", ",", "use_batch...
4eade036a0505e244c976f36aaa2d64386b5129b
train
ConvNetBuilder._pool
Construct a pooling layer.
python/ray/experimental/sgd/tfbench/convnet_builder.py
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_height, k_width], [d_height, d_width], padding=mode, data_format=self.channel_pos, name=name) else: if self.data_format == "NHWC": ksize = [1, k_height, k_width, 1] strides = [1, d_height, d_width, 1] else: ksize = [1, 1, k_height, k_width] strides = [1, 1, d_height, d_width] pool = tf.nn.max_pool( input_layer, ksize, strides, padding=mode, data_format=self.data_format, name=name) self.top_layer = pool return pool
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_height, k_width], [d_height, d_width], padding=mode, data_format=self.channel_pos, name=name) else: if self.data_format == "NHWC": ksize = [1, k_height, k_width, 1] strides = [1, d_height, d_width, 1] else: ksize = [1, 1, k_height, k_width] strides = [1, 1, d_height, d_width] pool = tf.nn.max_pool( input_layer, ksize, strides, padding=mode, data_format=self.data_format, name=name) self.top_layer = pool return pool
[ "Construct", "a", "pooling", "layer", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/sgd/tfbench/convnet_builder.py#L245-L275
[ "def", "_pool", "(", "self", ",", "pool_name", ",", "pool_function", ",", "k_height", ",", "k_width", ",", "d_height", ",", "d_width", ",", "mode", ",", "input_layer", ",", "num_channels_in", ")", ":", "if", "input_layer", "is", "None", ":", "input_layer", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
ConvNetBuilder.mpool
Construct a max pooling layer.
python/ray/experimental/sgd/tfbench/convnet_builder.py
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)
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)
[ "Construct", "a", "max", "pooling", "layer", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/sgd/tfbench/convnet_builder.py#L277-L288
[ "def", "mpool", "(", "self", ",", "k_height", ",", "k_width", ",", "d_height", "=", "2", ",", "d_width", "=", "2", ",", "mode", "=", "\"VALID\"", ",", "input_layer", "=", "None", ",", "num_channels_in", "=", "None", ")", ":", "return", "self", ".", "...
4eade036a0505e244c976f36aaa2d64386b5129b
train
ConvNetBuilder.apool
Construct an average pooling layer.
python/ray/experimental/sgd/tfbench/convnet_builder.py
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)
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)
[ "Construct", "an", "average", "pooling", "layer", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/sgd/tfbench/convnet_builder.py#L290-L301
[ "def", "apool", "(", "self", ",", "k_height", ",", "k_width", ",", "d_height", "=", "2", ",", "d_width", "=", "2", ",", "mode", "=", "\"VALID\"", ",", "input_layer", "=", "None", ",", "num_channels_in", "=", "None", ")", ":", "return", "self", ".", "...
4eade036a0505e244c976f36aaa2d64386b5129b
train
ConvNetBuilder._batch_norm_without_layers
Batch normalization on `input_layer` without tf.layers.
python/ray/experimental/sgd/tfbench/convnet_builder.py
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 = self.get_variable( "gamma", [num_channels], tf.float32, tf.float32, initializer=tf.ones_initializer()) else: gamma = tf.constant(1.0, tf.float32, [num_channels]) moving_mean = tf.get_variable( "moving_mean", [num_channels], tf.float32, initializer=tf.zeros_initializer(), trainable=False) moving_variance = tf.get_variable( "moving_variance", [num_channels], tf.float32, initializer=tf.ones_initializer(), trainable=False) if self.phase_train: bn, batch_mean, batch_variance = tf.nn.fused_batch_norm( input_layer, gamma, beta, epsilon=epsilon, data_format=self.data_format, is_training=True) mean_update = moving_averages.assign_moving_average( moving_mean, batch_mean, decay=decay, zero_debias=False) variance_update = moving_averages.assign_moving_average( moving_variance, batch_variance, decay=decay, zero_debias=False) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, mean_update) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, variance_update) else: bn, _, _ = tf.nn.fused_batch_norm( input_layer, gamma, beta, mean=moving_mean, variance=moving_variance, epsilon=epsilon, data_format=self.data_format, is_training=False) return bn
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 = self.get_variable( "gamma", [num_channels], tf.float32, tf.float32, initializer=tf.ones_initializer()) else: gamma = tf.constant(1.0, tf.float32, [num_channels]) moving_mean = tf.get_variable( "moving_mean", [num_channels], tf.float32, initializer=tf.zeros_initializer(), trainable=False) moving_variance = tf.get_variable( "moving_variance", [num_channels], tf.float32, initializer=tf.ones_initializer(), trainable=False) if self.phase_train: bn, batch_mean, batch_variance = tf.nn.fused_batch_norm( input_layer, gamma, beta, epsilon=epsilon, data_format=self.data_format, is_training=True) mean_update = moving_averages.assign_moving_average( moving_mean, batch_mean, decay=decay, zero_debias=False) variance_update = moving_averages.assign_moving_average( moving_variance, batch_variance, decay=decay, zero_debias=False) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, mean_update) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, variance_update) else: bn, _, _ = tf.nn.fused_batch_norm( input_layer, gamma, beta, mean=moving_mean, variance=moving_variance, epsilon=epsilon, data_format=self.data_format, is_training=False) return bn
[ "Batch", "normalization", "on", "input_layer", "without", "tf", ".", "layers", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/sgd/tfbench/convnet_builder.py#L411-L466
[ "def", "_batch_norm_without_layers", "(", "self", ",", "input_layer", ",", "decay", ",", "use_scale", ",", "epsilon", ")", ":", "shape", "=", "input_layer", ".", "shape", "num_channels", "=", "shape", "[", "3", "]", "if", "self", ".", "data_format", "==", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
ConvNetBuilder.batch_norm
Adds a Batch Normalization layer.
python/ray/experimental/sgd/tfbench/convnet_builder.py
def batch_norm(self, input_layer=None, decay=0.999, scale=False, epsilon=0.001): """Adds a Batch Normalization layer.""" if input_layer is None: input_layer = self.top_layer else: self.top_size = None name = "batchnorm" + str(self.counts["batchnorm"]) self.counts["batchnorm"] += 1 with tf.variable_scope(name) as scope: if self.use_tf_layers: bn = tf.contrib.layers.batch_norm( input_layer, decay=decay, scale=scale, epsilon=epsilon, is_training=self.phase_train, fused=True, data_format=self.data_format, scope=scope) else: bn = self._batch_norm_without_layers(input_layer, decay, scale, epsilon) self.top_layer = bn self.top_size = bn.shape[ 3] if self.data_format == "NHWC" else bn.shape[1] self.top_size = int(self.top_size) return bn
def batch_norm(self, input_layer=None, decay=0.999, scale=False, epsilon=0.001): """Adds a Batch Normalization layer.""" if input_layer is None: input_layer = self.top_layer else: self.top_size = None name = "batchnorm" + str(self.counts["batchnorm"]) self.counts["batchnorm"] += 1 with tf.variable_scope(name) as scope: if self.use_tf_layers: bn = tf.contrib.layers.batch_norm( input_layer, decay=decay, scale=scale, epsilon=epsilon, is_training=self.phase_train, fused=True, data_format=self.data_format, scope=scope) else: bn = self._batch_norm_without_layers(input_layer, decay, scale, epsilon) self.top_layer = bn self.top_size = bn.shape[ 3] if self.data_format == "NHWC" else bn.shape[1] self.top_size = int(self.top_size) return bn
[ "Adds", "a", "Batch", "Normalization", "layer", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/sgd/tfbench/convnet_builder.py#L468-L499
[ "def", "batch_norm", "(", "self", ",", "input_layer", "=", "None", ",", "decay", "=", "0.999", ",", "scale", "=", "False", ",", "epsilon", "=", "0.001", ")", ":", "if", "input_layer", "is", "None", ":", "input_layer", "=", "self", ".", "top_layer", "el...
4eade036a0505e244c976f36aaa2d64386b5129b
train
ConvNetBuilder.lrn
Adds a local response normalization layer.
python/ray/experimental/sgd/tfbench/convnet_builder.py
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
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
[ "Adds", "a", "local", "response", "normalization", "layer", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/sgd/tfbench/convnet_builder.py#L501-L507
[ "def", "lrn", "(", "self", ",", "depth_radius", ",", "bias", ",", "alpha", ",", "beta", ")", ":", "name", "=", "\"lrn\"", "+", "str", "(", "self", ".", "counts", "[", "\"lrn\"", "]", ")", "self", ".", "counts", "[", "\"lrn\"", "]", "+=", "1", "se...
4eade036a0505e244c976f36aaa2d64386b5129b
train
_internal_kv_get
Fetch the value of a binary key.
python/ray/experimental/internal_kv.py
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")
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")
[ "Fetch", "the", "value", "of", "a", "binary", "key", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/internal_kv.py#L15-L22
[ "def", "_internal_kv_get", "(", "key", ")", ":", "worker", "=", "ray", ".", "worker", ".", "get_global_worker", "(", ")", "if", "worker", ".", "mode", "==", "ray", ".", "worker", ".", "LOCAL_MODE", ":", "return", "_local", ".", "get", "(", "key", ")", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
_internal_kv_put
Globally associates a value with a given binary key. This only has an effect if the key does not already have a value. Returns: already_exists (bool): whether the value already exists.
python/ray/experimental/internal_kv.py
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 have a value. Returns: already_exists (bool): whether the value already exists. """ 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 = worker.redis_client.hsetnx(key, "value", value) return updated == 0
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 have a value. Returns: already_exists (bool): whether the value already exists. """ 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 = worker.redis_client.hsetnx(key, "value", value) return updated == 0
[ "Globally", "associates", "a", "value", "with", "a", "given", "binary", "key", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/internal_kv.py#L25-L45
[ "def", "_internal_kv_put", "(", "key", ",", "value", ",", "overwrite", "=", "False", ")", ":", "worker", "=", "ray", ".", "worker", ".", "get_global_worker", "(", ")", "if", "worker", ".", "mode", "==", "ray", ".", "worker", ".", "LOCAL_MODE", ":", "ex...
4eade036a0505e244c976f36aaa2d64386b5129b
train
TreeAggregator.init
Deferred init so that we can pass in previously created workers.
python/ray/rllib/optimizers/aso_tree_aggregator.py
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 {})".format( self.num_aggregation_workers, len(self.remote_evaluators))) assigned_evaluators = collections.defaultdict(list) for i, ev in enumerate(self.remote_evaluators): assigned_evaluators[i % self.num_aggregation_workers].append(ev) self.workers = aggregators for i, worker in enumerate(self.workers): worker.init.remote( self.broadcasted_weights, assigned_evaluators[i], self.max_sample_requests_in_flight_per_worker, self.replay_proportion, self.replay_buffer_num_slots, self.train_batch_size, self.sample_batch_size) self.agg_tasks = TaskPool() for agg in self.workers: agg.set_weights.remote(self.broadcasted_weights) self.agg_tasks.add(agg, agg.get_train_batches.remote()) self.initialized = True
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 {})".format( self.num_aggregation_workers, len(self.remote_evaluators))) assigned_evaluators = collections.defaultdict(list) for i, ev in enumerate(self.remote_evaluators): assigned_evaluators[i % self.num_aggregation_workers].append(ev) self.workers = aggregators for i, worker in enumerate(self.workers): worker.init.remote( self.broadcasted_weights, assigned_evaluators[i], self.max_sample_requests_in_flight_per_worker, self.replay_proportion, self.replay_buffer_num_slots, self.train_batch_size, self.sample_batch_size) self.agg_tasks = TaskPool() for agg in self.workers: agg.set_weights.remote(self.broadcasted_weights) self.agg_tasks.add(agg, agg.get_train_batches.remote()) self.initialized = True
[ "Deferred", "init", "so", "that", "we", "can", "pass", "in", "previously", "created", "workers", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/optimizers/aso_tree_aggregator.py#L57-L84
[ "def", "init", "(", "self", ",", "aggregators", ")", ":", "assert", "len", "(", "aggregators", ")", "==", "self", ".", "num_aggregation_workers", ",", "aggregators", "if", "len", "(", "self", ".", "remote_evaluators", ")", "<", "self", ".", "num_aggregation_...
4eade036a0505e244c976f36aaa2d64386b5129b
train
free
Free a list of IDs from object stores. This function is a low-level API which should be used in restricted scenarios. If local_only is false, the request will be send to all object stores. This method will not return any value to indicate whether the deletion is successful or not. This function is an instruction to object store. If the some of the objects are in use, object stores will delete them later when the ref count is down to 0. Args: object_ids (List[ObjectID]): List of object IDs to delete. local_only (bool): Whether only deleting the list of objects in local object store or all object stores. delete_creating_tasks (bool): Whether also delete the object creating tasks.
python/ray/internal/internal_api.py
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 used in restricted scenarios. If local_only is false, the request will be send to all object stores. This method will not return any value to indicate whether the deletion is successful or not. This function is an instruction to object store. If the some of the objects are in use, object stores will delete them later when the ref count is down to 0. Args: object_ids (List[ObjectID]): List of object IDs to delete. local_only (bool): Whether only deleting the list of objects in local object store or all object stores. delete_creating_tasks (bool): Whether also delete the object creating tasks. """ 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( type(object_ids))) # Make sure that the values are object IDs. for object_id in object_ids: if not isinstance(object_id, ray.ObjectID): raise TypeError("Attempting to call `free` on the value {}, " "which is not an ray.ObjectID.".format(object_id)) worker.check_connected() with profiling.profile("ray.free"): if len(object_ids) == 0: return worker.raylet_client.free_objects(object_ids, local_only, delete_creating_tasks)
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 used in restricted scenarios. If local_only is false, the request will be send to all object stores. This method will not return any value to indicate whether the deletion is successful or not. This function is an instruction to object store. If the some of the objects are in use, object stores will delete them later when the ref count is down to 0. Args: object_ids (List[ObjectID]): List of object IDs to delete. local_only (bool): Whether only deleting the list of objects in local object store or all object stores. delete_creating_tasks (bool): Whether also delete the object creating tasks. """ 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( type(object_ids))) # Make sure that the values are object IDs. for object_id in object_ids: if not isinstance(object_id, ray.ObjectID): raise TypeError("Attempting to call `free` on the value {}, " "which is not an ray.ObjectID.".format(object_id)) worker.check_connected() with profiling.profile("ray.free"): if len(object_ids) == 0: return worker.raylet_client.free_objects(object_ids, local_only, delete_creating_tasks)
[ "Free", "a", "list", "of", "IDs", "from", "object", "stores", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/internal/internal_api.py#L11-L55
[ "def", "free", "(", "object_ids", ",", "local_only", "=", "False", ",", "delete_creating_tasks", "=", "False", ")", ":", "worker", "=", "ray", ".", "worker", ".", "get_global_worker", "(", ")", "if", "ray", ".", "worker", ".", "_mode", "(", ")", "==", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
CollectorService.run
Start the collector worker thread. If running in standalone mode, the current thread will wait until the collector thread ends.
python/ray/tune/automlboard/backend/collector.py
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()
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()
[ "Start", "the", "collector", "worker", "thread", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L47-L55
[ "def", "run", "(", "self", ")", ":", "self", ".", "collector", ".", "start", "(", ")", "if", "self", ".", "standalone", ":", "self", ".", "collector", ".", "join", "(", ")" ]
4eade036a0505e244c976f36aaa2d64386b5129b
train
CollectorService.init_logger
Initialize logger settings.
python/ray/tune/automlboard/backend/collector.py
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) logger.setLevel(log_level) logger.addHandler(handler) return logger
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) logger.setLevel(log_level) logger.addHandler(handler) return logger
[ "Initialize", "logger", "settings", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L62-L72
[ "def", "init_logger", "(", "cls", ",", "log_level", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "\"AutoMLBoard\"", ")", "handler", "=", "logging", ".", "StreamHandler", "(", ")", "formatter", "=", "logging", ".", "Formatter", "(", "\"[%(leveln...
4eade036a0505e244c976f36aaa2d64386b5129b
train
Collector.run
Run the main event loop for collector thread. In each round the collector traverse the results log directory and reload trial information from the status files.
python/ray/tune/automlboard/backend/collector.py
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 the status files. """ self._initialize() self._do_collect() while not self._is_finished: time.sleep(self._reload_interval) self._do_collect() self.logger.info("Collector stopped.")
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 the status files. """ self._initialize() self._do_collect() while not self._is_finished: time.sleep(self._reload_interval) self._do_collect() self.logger.info("Collector stopped.")
[ "Run", "the", "main", "event", "loop", "for", "collector", "thread", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L98-L111
[ "def", "run", "(", "self", ")", ":", "self", ".", "_initialize", "(", ")", "self", ".", "_do_collect", "(", ")", "while", "not", "self", ".", "_is_finished", ":", "time", ".", "sleep", "(", "self", ".", "_reload_interval", ")", "self", ".", "_do_collec...
4eade036a0505e244c976f36aaa2d64386b5129b
train
Collector._initialize
Initialize collector worker thread, Log path will be checked first. Records in DB backend will be cleared.
python/ray/tune/automlboard/backend/collector.py
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.filter().delete() TrialRecord.objects.filter().delete() ResultRecord.objects.filter().delete()
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.filter().delete() TrialRecord.objects.filter().delete() ResultRecord.objects.filter().delete()
[ "Initialize", "collector", "worker", "thread", "Log", "path", "will", "be", "checked", "first", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L117-L131
[ "def", "_initialize", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "_logdir", ")", ":", "raise", "CollectorError", "(", "\"Log directory %s not exists\"", "%", "self", ".", "_logdir", ")", "self", ".", "logger", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
Collector.sync_job_info
Load information of the job with the given job name. 1. Traverse each experiment sub-directory and sync information for each trial. 2. Create or update the job information, together with the job meta file. Args: job_name (str) name of the Tune experiment
python/ray/tune/automlboard/backend/collector.py
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 each trial. 2. Create or update the job information, together with the job meta file. Args: job_name (str) name of the Tune experiment """ 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(job_path, d)), os.listdir(job_path)) for expr_dir_name in expr_dirs: self.sync_trial_info(job_path, expr_dir_name) self._update_job_info(job_path)
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 each trial. 2. Create or update the job information, together with the job meta file. Args: job_name (str) name of the Tune experiment """ 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(job_path, d)), os.listdir(job_path)) for expr_dir_name in expr_dirs: self.sync_trial_info(job_path, expr_dir_name) self._update_job_info(job_path)
[ "Load", "information", "of", "the", "job", "with", "the", "given", "job", "name", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L140-L165
[ "def", "sync_job_info", "(", "self", ",", "job_name", ")", ":", "job_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_logdir", ",", "job_name", ")", "if", "job_name", "not", "in", "self", ".", "_monitored_jobs", ":", "self", ".", "_creat...
4eade036a0505e244c976f36aaa2d64386b5129b
train
Collector.sync_trial_info
Load information of the trial from the given experiment directory. Create or update the trial information, together with the trial meta file. Args: job_path(str) expr_dir_name(str)
python/ray/tune/automlboard/backend/collector.py
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, together with the trial meta file. Args: job_path(str) expr_dir_name(str) """ 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)
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, together with the trial meta file. Args: job_path(str) expr_dir_name(str) """ 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)
[ "Load", "information", "of", "the", "trial", "from", "the", "given", "experiment", "directory", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L167-L185
[ "def", "sync_trial_info", "(", "self", ",", "job_path", ",", "expr_dir_name", ")", ":", "expr_name", "=", "expr_dir_name", "[", "-", "8", ":", "]", "expr_path", "=", "os", ".", "path", ".", "join", "(", "job_path", ",", "expr_dir_name", ")", "if", "expr_...
4eade036a0505e244c976f36aaa2d64386b5129b
train
Collector._create_job_info
Create information for given job. Meta file will be loaded if exists, and the job information will be saved in db backend. Args: job_dir (str): Directory path of the job.
python/ray/tune/automlboard/backend/collector.py
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. Args: job_dir (str): Directory path of the job. """ meta = self._build_job_meta(job_dir) self.logger.debug("Create job: %s" % meta) job_record = JobRecord.from_json(meta) job_record.save()
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. Args: job_dir (str): Directory path of the job. """ meta = self._build_job_meta(job_dir) self.logger.debug("Create job: %s" % meta) job_record = JobRecord.from_json(meta) job_record.save()
[ "Create", "information", "for", "given", "job", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L187-L201
[ "def", "_create_job_info", "(", "self", ",", "job_dir", ")", ":", "meta", "=", "self", ".", "_build_job_meta", "(", "job_dir", ")", "self", ".", "logger", ".", "debug", "(", "\"Create job: %s\"", "%", "meta", ")", "job_record", "=", "JobRecord", ".", "from...
4eade036a0505e244c976f36aaa2d64386b5129b
train
Collector._update_job_info
Update information for given job. Meta file will be loaded if exists, and the job information in in db backend will be updated. Args: job_dir (str): Directory path of the job. Return: Updated dict of job meta info
python/ray/tune/automlboard/backend/collector.py
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 updated. Args: job_dir (str): Directory path of the job. Return: Updated dict of job meta info """ 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_time"]))
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 updated. Args: job_dir (str): Directory path of the job. Return: Updated dict of job meta info """ 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_time"]))
[ "Update", "information", "for", "given", "job", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L204-L223
[ "def", "_update_job_info", "(", "cls", ",", "job_dir", ")", ":", "meta_file", "=", "os", ".", "path", ".", "join", "(", "job_dir", ",", "JOB_META_FILE", ")", "meta", "=", "parse_json", "(", "meta_file", ")", "if", "meta", ":", "logging", ".", "debug", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
Collector._create_trial_info
Create information for given trial. Meta file will be loaded if exists, and the trial information will be saved in db backend. Args: expr_dir (str): Directory path of the experiment.
python/ray/tune/automlboard/backend/collector.py
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 backend. Args: expr_dir (str): Directory path of the experiment. """ meta = self._build_trial_meta(expr_dir) self.logger.debug("Create trial for %s" % meta) trial_record = TrialRecord.from_json(meta) trial_record.save()
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 backend. Args: expr_dir (str): Directory path of the experiment. """ meta = self._build_trial_meta(expr_dir) self.logger.debug("Create trial for %s" % meta) trial_record = TrialRecord.from_json(meta) trial_record.save()
[ "Create", "information", "for", "given", "trial", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L225-L239
[ "def", "_create_trial_info", "(", "self", ",", "expr_dir", ")", ":", "meta", "=", "self", ".", "_build_trial_meta", "(", "expr_dir", ")", "self", ".", "logger", ".", "debug", "(", "\"Create trial for %s\"", "%", "meta", ")", "trial_record", "=", "TrialRecord",...
4eade036a0505e244c976f36aaa2d64386b5129b
train
Collector._update_trial_info
Update information for given trial. Meta file will be loaded if exists, and the trial information in db backend will be updated. Args: expr_dir(str)
python/ray/tune/automlboard/backend/collector.py
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 be updated. Args: expr_dir(str) """ 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) self._add_results(results, trial_id) self._result_offsets[trial_id] = new_offset if meta: TrialRecord.objects \ .filter(trial_id=trial_id) \ .update(trial_status=meta["status"], end_time=timestamp2date(meta.get("end_time", None))) elif len(results) > 0: metrics = { "episode_reward": results[-1].get("episode_reward_mean", None), "accuracy": results[-1].get("mean_accuracy", None), "loss": results[-1].get("loss", None) } if results[-1].get("done"): TrialRecord.objects \ .filter(trial_id=trial_id) \ .update(trial_status="TERMINATED", end_time=results[-1].get("date", None), metrics=str(metrics)) else: TrialRecord.objects \ .filter(trial_id=trial_id) \ .update(metrics=str(metrics))
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 be updated. Args: expr_dir(str) """ 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) self._add_results(results, trial_id) self._result_offsets[trial_id] = new_offset if meta: TrialRecord.objects \ .filter(trial_id=trial_id) \ .update(trial_status=meta["status"], end_time=timestamp2date(meta.get("end_time", None))) elif len(results) > 0: metrics = { "episode_reward": results[-1].get("episode_reward_mean", None), "accuracy": results[-1].get("mean_accuracy", None), "loss": results[-1].get("loss", None) } if results[-1].get("done"): TrialRecord.objects \ .filter(trial_id=trial_id) \ .update(trial_status="TERMINATED", end_time=results[-1].get("date", None), metrics=str(metrics)) else: TrialRecord.objects \ .filter(trial_id=trial_id) \ .update(metrics=str(metrics))
[ "Update", "information", "for", "given", "trial", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L241-L281
[ "def", "_update_trial_info", "(", "self", ",", "expr_dir", ")", ":", "trial_id", "=", "expr_dir", "[", "-", "8", ":", "]", "meta_file", "=", "os", ".", "path", ".", "join", "(", "expr_dir", ",", "EXPR_META_FILE", ")", "meta", "=", "parse_json", "(", "m...
4eade036a0505e244c976f36aaa2d64386b5129b
train
Collector._build_job_meta
Build meta file for job. Args: job_dir (str): Directory path of the job. Return: A dict of job meta info.
python/ray/tune/automlboard/backend/collector.py
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, "user": user, "type": "ray", "start_time": os.path.getctime(job_dir), "end_time": None, "best_trial_id": None, } if meta.get("start_time", None): meta["start_time"] = timestamp2date(meta["start_time"]) return meta
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, "user": user, "type": "ray", "start_time": os.path.getctime(job_dir), "end_time": None, "best_trial_id": None, } if meta.get("start_time", None): meta["start_time"] = timestamp2date(meta["start_time"]) return meta
[ "Build", "meta", "file", "for", "job", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L284-L312
[ "def", "_build_job_meta", "(", "cls", ",", "job_dir", ")", ":", "meta_file", "=", "os", ".", "path", ".", "join", "(", "job_dir", ",", "JOB_META_FILE", ")", "meta", "=", "parse_json", "(", "meta_file", ")", "if", "not", "meta", ":", "job_name", "=", "j...
4eade036a0505e244c976f36aaa2d64386b5129b
train
Collector._build_trial_meta
Build meta file for trial. Args: expr_dir (str): Directory path of the experiment. Return: A dict of trial meta info.
python/ray/tune/automlboard/backend/collector.py
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_id": trial_id, "job_id": job_id, "status": "RUNNING", "type": "TUNE", "start_time": os.path.getctime(expr_dir), "end_time": None, "progress_offset": 0, "result_offset": 0, "params": params } if not meta.get("start_time", None): meta["start_time"] = os.path.getctime(expr_dir) if isinstance(meta["start_time"], float): meta["start_time"] = timestamp2date(meta["start_time"]) if meta.get("end_time", None): meta["end_time"] = timestamp2date(meta["end_time"]) meta["params"] = parse_json(os.path.join(expr_dir, EXPR_PARARM_FILE)) return meta
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_id": trial_id, "job_id": job_id, "status": "RUNNING", "type": "TUNE", "start_time": os.path.getctime(expr_dir), "end_time": None, "progress_offset": 0, "result_offset": 0, "params": params } if not meta.get("start_time", None): meta["start_time"] = os.path.getctime(expr_dir) if isinstance(meta["start_time"], float): meta["start_time"] = timestamp2date(meta["start_time"]) if meta.get("end_time", None): meta["end_time"] = timestamp2date(meta["end_time"]) meta["params"] = parse_json(os.path.join(expr_dir, EXPR_PARARM_FILE)) return meta
[ "Build", "meta", "file", "for", "trial", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L315-L354
[ "def", "_build_trial_meta", "(", "cls", ",", "expr_dir", ")", ":", "meta_file", "=", "os", ".", "path", ".", "join", "(", "expr_dir", ",", "EXPR_META_FILE", ")", "meta", "=", "parse_json", "(", "meta_file", ")", "if", "not", "meta", ":", "job_id", "=", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
Collector._add_results
Add a list of results into db. Args: results (list): A list of json results. trial_id (str): Id of the trial.
python/ray/tune/automlboard/backend/collector.py
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()
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()
[ "Add", "a", "list", "of", "results", "into", "db", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L356-L367
[ "def", "_add_results", "(", "self", ",", "results", ",", "trial_id", ")", ":", "for", "result", "in", "results", ":", "self", ".", "logger", ".", "debug", "(", "\"Appending result: %s\"", "%", "result", ")", "result", "[", "\"trial_id\"", "]", "=", "trial_...
4eade036a0505e244c976f36aaa2d64386b5129b
train
add_time_dimension
Adds a time dimension to padded inputs. Arguments: padded_inputs (Tensor): a padded batch of sequences. That is, for seq_lens=[1, 2, 2], then inputs=[A, *, B, B, C, C], where A, B, C are sequence elements and * denotes padding. seq_lens (Tensor): the sequence lengths within the input batch, suitable for passing to tf.nn.dynamic_rnn(). Returns: Reshaped tensor of shape [NUM_SEQUENCES, MAX_SEQ_LEN, ...].
python/ray/rllib/models/lstm.py
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 is, for seq_lens=[1, 2, 2], then inputs=[A, *, B, B, C, C], where A, B, C are sequence elements and * denotes padding. seq_lens (Tensor): the sequence lengths within the input batch, suitable for passing to tf.nn.dynamic_rnn(). Returns: Reshaped tensor of shape [NUM_SEQUENCES, MAX_SEQ_LEN, ...]. """ # 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] # Dynamically reshape the padded batch to introduce a time dimension. new_batch_size = padded_batch_size // max_seq_len new_shape = ([new_batch_size, max_seq_len] + padded_inputs.get_shape().as_list()[1:]) return tf.reshape(padded_inputs, new_shape)
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 is, for seq_lens=[1, 2, 2], then inputs=[A, *, B, B, C, C], where A, B, C are sequence elements and * denotes padding. seq_lens (Tensor): the sequence lengths within the input batch, suitable for passing to tf.nn.dynamic_rnn(). Returns: Reshaped tensor of shape [NUM_SEQUENCES, MAX_SEQ_LEN, ...]. """ # 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] # Dynamically reshape the padded batch to introduce a time dimension. new_batch_size = padded_batch_size // max_seq_len new_shape = ([new_batch_size, max_seq_len] + padded_inputs.get_shape().as_list()[1:]) return tf.reshape(padded_inputs, new_shape)
[ "Adds", "a", "time", "dimension", "to", "padded", "inputs", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/models/lstm.py#L95-L119
[ "def", "add_time_dimension", "(", "padded_inputs", ",", "seq_lens", ")", ":", "# 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", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
chop_into_sequences
Truncate and pad experiences into fixed-length sequences. Arguments: episode_ids (list): List of episode ids for each step. unroll_ids (list): List of identifiers for the sample batch. This is used to make sure sequences are cut between sample batches. agent_indices (list): List of agent ids for each step. Note that this has to be combined with episode_ids for uniqueness. feature_columns (list): List of arrays containing features. state_columns (list): List of arrays containing LSTM state values. max_seq_len (int): Max length of sequences before truncation. dynamic_max (bool): Whether to dynamically shrink the max seq len. For example, if max len is 20 and the actual max seq len in the data is 7, it will be shrunk to 7. _extra_padding (int): Add extra padding to the end of sequences. Returns: f_pad (list): Padded feature columns. These will be of shape [NUM_SEQUENCES * MAX_SEQ_LEN, ...]. s_init (list): Initial states for each sequence, of shape [NUM_SEQUENCES, ...]. seq_lens (list): List of sequence lengths, of shape [NUM_SEQUENCES]. Examples: >>> f_pad, s_init, seq_lens = chop_into_sequences( episode_ids=[1, 1, 5, 5, 5, 5], unroll_ids=[4, 4, 4, 4, 4, 4], agent_indices=[0, 0, 0, 0, 0, 0], feature_columns=[[4, 4, 8, 8, 8, 8], [1, 1, 0, 1, 1, 0]], state_columns=[[4, 5, 4, 5, 5, 5]], max_seq_len=3) >>> print(f_pad) [[4, 4, 0, 8, 8, 8, 8, 0, 0], [1, 1, 0, 0, 1, 1, 0, 0, 0]] >>> print(s_init) [[4, 4, 5]] >>> print(seq_lens) [2, 3, 1]
python/ray/rllib/models/lstm.py
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 pad experiences into fixed-length sequences. Arguments: episode_ids (list): List of episode ids for each step. unroll_ids (list): List of identifiers for the sample batch. This is used to make sure sequences are cut between sample batches. agent_indices (list): List of agent ids for each step. Note that this has to be combined with episode_ids for uniqueness. feature_columns (list): List of arrays containing features. state_columns (list): List of arrays containing LSTM state values. max_seq_len (int): Max length of sequences before truncation. dynamic_max (bool): Whether to dynamically shrink the max seq len. For example, if max len is 20 and the actual max seq len in the data is 7, it will be shrunk to 7. _extra_padding (int): Add extra padding to the end of sequences. Returns: f_pad (list): Padded feature columns. These will be of shape [NUM_SEQUENCES * MAX_SEQ_LEN, ...]. s_init (list): Initial states for each sequence, of shape [NUM_SEQUENCES, ...]. seq_lens (list): List of sequence lengths, of shape [NUM_SEQUENCES]. Examples: >>> f_pad, s_init, seq_lens = chop_into_sequences( episode_ids=[1, 1, 5, 5, 5, 5], unroll_ids=[4, 4, 4, 4, 4, 4], agent_indices=[0, 0, 0, 0, 0, 0], feature_columns=[[4, 4, 8, 8, 8, 8], [1, 1, 0, 1, 1, 0]], state_columns=[[4, 5, 4, 5, 5, 5]], max_seq_len=3) >>> print(f_pad) [[4, 4, 0, 8, 8, 8, 8, 0, 0], [1, 1, 0, 0, 1, 1, 0, 0, 0]] >>> print(s_init) [[4, 4, 5]] >>> print(seq_lens) [2, 3, 1] """ 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) seq_len = 0 seq_len += 1 prev_id = uid if seq_len: seq_lens.append(seq_len) assert sum(seq_lens) == len(unique_ids) # Dynamically shrink max len as needed to optimize memory usage if dynamic_max: max_seq_len = max(seq_lens) + _extra_padding feature_sequences = [] for f in feature_columns: f = np.array(f) f_pad = np.zeros((len(seq_lens) * max_seq_len, ) + np.shape(f)[1:]) seq_base = 0 i = 0 for l in seq_lens: for seq_offset in range(l): f_pad[seq_base + seq_offset] = f[i] i += 1 seq_base += max_seq_len assert i == len(unique_ids), f feature_sequences.append(f_pad) initial_states = [] for s in state_columns: s = np.array(s) s_init = [] i = 0 for l in seq_lens: s_init.append(s[i]) i += l initial_states.append(np.array(s_init)) return feature_sequences, initial_states, np.array(seq_lens)
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 pad experiences into fixed-length sequences. Arguments: episode_ids (list): List of episode ids for each step. unroll_ids (list): List of identifiers for the sample batch. This is used to make sure sequences are cut between sample batches. agent_indices (list): List of agent ids for each step. Note that this has to be combined with episode_ids for uniqueness. feature_columns (list): List of arrays containing features. state_columns (list): List of arrays containing LSTM state values. max_seq_len (int): Max length of sequences before truncation. dynamic_max (bool): Whether to dynamically shrink the max seq len. For example, if max len is 20 and the actual max seq len in the data is 7, it will be shrunk to 7. _extra_padding (int): Add extra padding to the end of sequences. Returns: f_pad (list): Padded feature columns. These will be of shape [NUM_SEQUENCES * MAX_SEQ_LEN, ...]. s_init (list): Initial states for each sequence, of shape [NUM_SEQUENCES, ...]. seq_lens (list): List of sequence lengths, of shape [NUM_SEQUENCES]. Examples: >>> f_pad, s_init, seq_lens = chop_into_sequences( episode_ids=[1, 1, 5, 5, 5, 5], unroll_ids=[4, 4, 4, 4, 4, 4], agent_indices=[0, 0, 0, 0, 0, 0], feature_columns=[[4, 4, 8, 8, 8, 8], [1, 1, 0, 1, 1, 0]], state_columns=[[4, 5, 4, 5, 5, 5]], max_seq_len=3) >>> print(f_pad) [[4, 4, 0, 8, 8, 8, 8, 0, 0], [1, 1, 0, 0, 1, 1, 0, 0, 0]] >>> print(s_init) [[4, 4, 5]] >>> print(seq_lens) [2, 3, 1] """ 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) seq_len = 0 seq_len += 1 prev_id = uid if seq_len: seq_lens.append(seq_len) assert sum(seq_lens) == len(unique_ids) # Dynamically shrink max len as needed to optimize memory usage if dynamic_max: max_seq_len = max(seq_lens) + _extra_padding feature_sequences = [] for f in feature_columns: f = np.array(f) f_pad = np.zeros((len(seq_lens) * max_seq_len, ) + np.shape(f)[1:]) seq_base = 0 i = 0 for l in seq_lens: for seq_offset in range(l): f_pad[seq_base + seq_offset] = f[i] i += 1 seq_base += max_seq_len assert i == len(unique_ids), f feature_sequences.append(f_pad) initial_states = [] for s in state_columns: s = np.array(s) s_init = [] i = 0 for l in seq_lens: s_init.append(s[i]) i += l initial_states.append(np.array(s_init)) return feature_sequences, initial_states, np.array(seq_lens)
[ "Truncate", "and", "pad", "experiences", "into", "fixed", "-", "length", "sequences", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/models/lstm.py#L123-L217
[ "def", "chop_into_sequences", "(", "episode_ids", ",", "unroll_ids", ",", "agent_indices", ",", "feature_columns", ",", "state_columns", ",", "max_seq_len", ",", "dynamic_max", "=", "True", ",", "_extra_padding", "=", "0", ")", ":", "prev_id", "=", "None", "seq_...
4eade036a0505e244c976f36aaa2d64386b5129b
train
explore
Return a config perturbed as specified. Args: config (dict): Original hyperparameter configuration. mutations (dict): Specification of mutations to perform as documented in the PopulationBasedTraining scheduler. resample_probability (float): Probability of allowing resampling of a particular variable. custom_explore_fn (func): Custom explore fn applied after built-in config perturbations are.
python/ray/tune/schedulers/pbt.py
def explore(config, mutations, resample_probability, custom_explore_fn): """Return a config perturbed as specified. Args: config (dict): Original hyperparameter configuration. mutations (dict): Specification of mutations to perform as documented in the PopulationBasedTraining scheduler. resample_probability (float): Probability of allowing resampling of a particular variable. custom_explore_fn (func): Custom explore fn applied after built-in config perturbations are. """ 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(distribution, list): if random.random() < resample_probability or \ config[key] not in distribution: new_config[key] = random.choice(distribution) elif random.random() > 0.5: new_config[key] = distribution[max( 0, distribution.index(config[key]) - 1)] else: new_config[key] = distribution[min( len(distribution) - 1, distribution.index(config[key]) + 1)] else: if random.random() < resample_probability: new_config[key] = distribution() elif random.random() > 0.5: new_config[key] = config[key] * 1.2 else: new_config[key] = config[key] * 0.8 if type(config[key]) is int: new_config[key] = int(new_config[key]) if custom_explore_fn: new_config = custom_explore_fn(new_config) assert new_config is not None, \ "Custom explore fn failed to return new config" logger.info("[explore] perturbed config from {} -> {}".format( config, new_config)) return new_config
def explore(config, mutations, resample_probability, custom_explore_fn): """Return a config perturbed as specified. Args: config (dict): Original hyperparameter configuration. mutations (dict): Specification of mutations to perform as documented in the PopulationBasedTraining scheduler. resample_probability (float): Probability of allowing resampling of a particular variable. custom_explore_fn (func): Custom explore fn applied after built-in config perturbations are. """ 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(distribution, list): if random.random() < resample_probability or \ config[key] not in distribution: new_config[key] = random.choice(distribution) elif random.random() > 0.5: new_config[key] = distribution[max( 0, distribution.index(config[key]) - 1)] else: new_config[key] = distribution[min( len(distribution) - 1, distribution.index(config[key]) + 1)] else: if random.random() < resample_probability: new_config[key] = distribution() elif random.random() > 0.5: new_config[key] = config[key] * 1.2 else: new_config[key] = config[key] * 0.8 if type(config[key]) is int: new_config[key] = int(new_config[key]) if custom_explore_fn: new_config = custom_explore_fn(new_config) assert new_config is not None, \ "Custom explore fn failed to return new config" logger.info("[explore] perturbed config from {} -> {}".format( config, new_config)) return new_config
[ "Return", "a", "config", "perturbed", "as", "specified", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/schedulers/pbt.py#L41-L87
[ "def", "explore", "(", "config", ",", "mutations", ",", "resample_probability", ",", "custom_explore_fn", ")", ":", "new_config", "=", "copy", ".", "deepcopy", "(", "config", ")", "for", "key", ",", "distribution", "in", "mutations", ".", "items", "(", ")", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
make_experiment_tag
Appends perturbed params to the trial name to show in the console.
python/ray/tune/schedulers/pbt.py
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))
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))
[ "Appends", "perturbed", "params", "to", "the", "trial", "name", "to", "show", "in", "the", "console", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/schedulers/pbt.py#L90-L96
[ "def", "make_experiment_tag", "(", "orig_tag", ",", "config", ",", "mutations", ")", ":", "resolved_vars", "=", "{", "}", "for", "k", "in", "mutations", ".", "keys", "(", ")", ":", "resolved_vars", "[", "(", "\"config\"", ",", "k", ")", "]", "=", "conf...
4eade036a0505e244c976f36aaa2d64386b5129b
train
PopulationBasedTraining._log_config_on_step
Logs transition during exploit/exploit step. For each step, logs: [target trial tag, clone trial tag, target trial iteration, clone trial iteration, old config, new config].
python/ray/tune/schedulers/pbt.py
def _log_config_on_step(self, trial_state, new_state, trial, trial_to_clone, new_config): """Logs transition during exploit/exploit step. For each step, logs: [target trial tag, clone trial tag, target trial iteration, clone trial iteration, old config, new config]. """ trial_name, trial_to_clone_name = (trial_state.orig_tag, new_state.orig_tag) trial_id = "".join(itertools.takewhile(str.isdigit, trial_name)) trial_to_clone_id = "".join( itertools.takewhile(str.isdigit, trial_to_clone_name)) trial_path = os.path.join(trial.local_dir, "pbt_policy_" + trial_id + ".txt") trial_to_clone_path = os.path.join( trial_to_clone.local_dir, "pbt_policy_" + trial_to_clone_id + ".txt") policy = [ trial_name, trial_to_clone_name, trial.last_result[TRAINING_ITERATION], trial_to_clone.last_result[TRAINING_ITERATION], trial_to_clone.config, new_config ] # Log to global file. with open(os.path.join(trial.local_dir, "pbt_global.txt"), "a+") as f: f.write(json.dumps(policy) + "\n") # Overwrite state in target trial from trial_to_clone. if os.path.exists(trial_to_clone_path): shutil.copyfile(trial_to_clone_path, trial_path) # Log new exploit in target trial log. with open(trial_path, "a+") as f: f.write(json.dumps(policy) + "\n")
def _log_config_on_step(self, trial_state, new_state, trial, trial_to_clone, new_config): """Logs transition during exploit/exploit step. For each step, logs: [target trial tag, clone trial tag, target trial iteration, clone trial iteration, old config, new config]. """ trial_name, trial_to_clone_name = (trial_state.orig_tag, new_state.orig_tag) trial_id = "".join(itertools.takewhile(str.isdigit, trial_name)) trial_to_clone_id = "".join( itertools.takewhile(str.isdigit, trial_to_clone_name)) trial_path = os.path.join(trial.local_dir, "pbt_policy_" + trial_id + ".txt") trial_to_clone_path = os.path.join( trial_to_clone.local_dir, "pbt_policy_" + trial_to_clone_id + ".txt") policy = [ trial_name, trial_to_clone_name, trial.last_result[TRAINING_ITERATION], trial_to_clone.last_result[TRAINING_ITERATION], trial_to_clone.config, new_config ] # Log to global file. with open(os.path.join(trial.local_dir, "pbt_global.txt"), "a+") as f: f.write(json.dumps(policy) + "\n") # Overwrite state in target trial from trial_to_clone. if os.path.exists(trial_to_clone_path): shutil.copyfile(trial_to_clone_path, trial_path) # Log new exploit in target trial log. with open(trial_path, "a+") as f: f.write(json.dumps(policy) + "\n")
[ "Logs", "transition", "during", "exploit", "/", "exploit", "step", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/schedulers/pbt.py#L225-L256
[ "def", "_log_config_on_step", "(", "self", ",", "trial_state", ",", "new_state", ",", "trial", ",", "trial_to_clone", ",", "new_config", ")", ":", "trial_name", ",", "trial_to_clone_name", "=", "(", "trial_state", ".", "orig_tag", ",", "new_state", ".", "orig_ta...
4eade036a0505e244c976f36aaa2d64386b5129b
train
PopulationBasedTraining._exploit
Transfers perturbed state from trial_to_clone -> trial. If specified, also logs the updated hyperparam state.
python/ray/tune/schedulers/pbt.py
def _exploit(self, trial_executor, trial, trial_to_clone): """Transfers perturbed state from trial_to_clone -> trial. If specified, also logs the updated hyperparam state.""" 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(trial_to_clone.config, self._hyperparam_mutations, self._resample_probability, self._custom_explore_fn) logger.info("[exploit] transferring weights from trial " "{} (score {}) -> {} (score {})".format( trial_to_clone, new_state.last_score, trial, trial_state.last_score)) if self._log_config: self._log_config_on_step(trial_state, new_state, trial, trial_to_clone, new_config) new_tag = make_experiment_tag(trial_state.orig_tag, new_config, self._hyperparam_mutations) reset_successful = trial_executor.reset_trial(trial, new_config, new_tag) if reset_successful: trial_executor.restore( trial, Checkpoint.from_object(new_state.last_checkpoint)) else: trial_executor.stop_trial(trial, stop_logger=False) trial.config = new_config trial.experiment_tag = new_tag trial_executor.start_trial( trial, Checkpoint.from_object(new_state.last_checkpoint)) self._num_perturbations += 1 # Transfer over the last perturbation time as well trial_state.last_perturbation_time = new_state.last_perturbation_time
def _exploit(self, trial_executor, trial, trial_to_clone): """Transfers perturbed state from trial_to_clone -> trial. If specified, also logs the updated hyperparam state.""" 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(trial_to_clone.config, self._hyperparam_mutations, self._resample_probability, self._custom_explore_fn) logger.info("[exploit] transferring weights from trial " "{} (score {}) -> {} (score {})".format( trial_to_clone, new_state.last_score, trial, trial_state.last_score)) if self._log_config: self._log_config_on_step(trial_state, new_state, trial, trial_to_clone, new_config) new_tag = make_experiment_tag(trial_state.orig_tag, new_config, self._hyperparam_mutations) reset_successful = trial_executor.reset_trial(trial, new_config, new_tag) if reset_successful: trial_executor.restore( trial, Checkpoint.from_object(new_state.last_checkpoint)) else: trial_executor.stop_trial(trial, stop_logger=False) trial.config = new_config trial.experiment_tag = new_tag trial_executor.start_trial( trial, Checkpoint.from_object(new_state.last_checkpoint)) self._num_perturbations += 1 # Transfer over the last perturbation time as well trial_state.last_perturbation_time = new_state.last_perturbation_time
[ "Transfers", "perturbed", "state", "from", "trial_to_clone", "-", ">", "trial", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/schedulers/pbt.py#L258-L297
[ "def", "_exploit", "(", "self", ",", "trial_executor", ",", "trial", ",", "trial_to_clone", ")", ":", "trial_state", "=", "self", ".", "_trial_state", "[", "trial", "]", "new_state", "=", "self", ".", "_trial_state", "[", "trial_to_clone", "]", "if", "not", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
PopulationBasedTraining._quantiles
Returns trials in the lower and upper `quantile` of the population. If there is not enough data to compute this, returns empty lists.
python/ray/tune/schedulers/pbt.py
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 [], [] else: return (trials[:int(math.ceil(len(trials) * PBT_QUANTILE))], trials[int(math.floor(-len(trials) * PBT_QUANTILE)):])
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 [], [] else: return (trials[:int(math.ceil(len(trials) * PBT_QUANTILE))], trials[int(math.floor(-len(trials) * PBT_QUANTILE)):])
[ "Returns", "trials", "in", "the", "lower", "and", "upper", "quantile", "of", "the", "population", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/schedulers/pbt.py#L299-L314
[ "def", "_quantiles", "(", "self", ")", ":", "trials", "=", "[", "]", "for", "trial", ",", "state", "in", "self", ".", "_trial_state", ".", "items", "(", ")", ":", "if", "state", ".", "last_score", "is", "not", "None", "and", "not", "trial", ".", "i...
4eade036a0505e244c976f36aaa2d64386b5129b
train
PopulationBasedTraining.choose_trial_to_run
Ensures all trials get fair share of time (as defined by time_attr). This enables the PBT scheduler to support a greater number of concurrent trials than can fit in the cluster at any given time.
python/ray/tune/schedulers/pbt.py
def choose_trial_to_run(self, trial_runner): """Ensures all trials get fair share of time (as defined by time_attr). This enables the PBT scheduler to support a greater number of concurrent trials than can fit in the cluster at any given time. """ candidates = [] for trial in trial_runner.get_trials(): if trial.status in [Trial.PENDING, Trial.PAUSED] and \ trial_runner.has_resources(trial.resources): candidates.append(trial) candidates.sort( key=lambda trial: self._trial_state[trial].last_perturbation_time) return candidates[0] if candidates else None
def choose_trial_to_run(self, trial_runner): """Ensures all trials get fair share of time (as defined by time_attr). This enables the PBT scheduler to support a greater number of concurrent trials than can fit in the cluster at any given time. """ candidates = [] for trial in trial_runner.get_trials(): if trial.status in [Trial.PENDING, Trial.PAUSED] and \ trial_runner.has_resources(trial.resources): candidates.append(trial) candidates.sort( key=lambda trial: self._trial_state[trial].last_perturbation_time) return candidates[0] if candidates else None
[ "Ensures", "all", "trials", "get", "fair", "share", "of", "time", "(", "as", "defined", "by", "time_attr", ")", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/schedulers/pbt.py#L316-L330
[ "def", "choose_trial_to_run", "(", "self", ",", "trial_runner", ")", ":", "candidates", "=", "[", "]", "for", "trial", "in", "trial_runner", ".", "get_trials", "(", ")", ":", "if", "trial", ".", "status", "in", "[", "Trial", ".", "PENDING", ",", "Trial",...
4eade036a0505e244c976f36aaa2d64386b5129b
train
key_pair
Returns the ith default (aws_key_pair_name, key_pair_path).
python/ray/autoscaler/aws/config.py
def key_pair(i, region): """Returns the ith default (aws_key_pair_name, key_pair_path).""" if i == 0: return ("{}_{}".format(RAY, region), os.path.expanduser("~/.ssh/{}_{}.pem".format(RAY, region))) return ("{}_{}_{}".format(RAY, i, region), os.path.expanduser("~/.ssh/{}_{}_{}.pem".format(RAY, i, region)))
def key_pair(i, region): """Returns the ith default (aws_key_pair_name, key_pair_path).""" if i == 0: return ("{}_{}".format(RAY, region), os.path.expanduser("~/.ssh/{}_{}.pem".format(RAY, region))) return ("{}_{}_{}".format(RAY, i, region), os.path.expanduser("~/.ssh/{}_{}_{}.pem".format(RAY, i, region)))
[ "Returns", "the", "ith", "default", "(", "aws_key_pair_name", "key_pair_path", ")", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/autoscaler/aws/config.py#L28-L34
[ "def", "key_pair", "(", "i", ",", "region", ")", ":", "if", "i", "==", "0", ":", "return", "(", "\"{}_{}\"", ".", "format", "(", "RAY", ",", "region", ")", ",", "os", ".", "path", ".", "expanduser", "(", "\"~/.ssh/{}_{}.pem\"", ".", "format", "(", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
FullyConnectedNetwork._build_layers
Process the flattened inputs. Note that dict inputs will be flattened into a vector. To define a model that processes the components separately, use _build_layers_v2().
python/ray/rllib/models/fcnet.py
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 that processes the components separately, use _build_layers_v2(). """ 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.fully_connected( last_layer, size, weights_initializer=normc_initializer(1.0), activation_fn=activation, scope=label) i += 1 label = "fc_out" output = slim.fully_connected( last_layer, num_outputs, weights_initializer=normc_initializer(0.01), activation_fn=None, scope=label) return output, last_layer
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 that processes the components separately, use _build_layers_v2(). """ 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.fully_connected( last_layer, size, weights_initializer=normc_initializer(1.0), activation_fn=activation, scope=label) i += 1 label = "fc_out" output = slim.fully_connected( last_layer, num_outputs, weights_initializer=normc_initializer(0.01), activation_fn=None, scope=label) return output, last_layer
[ "Process", "the", "flattened", "inputs", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/models/fcnet.py#L17-L46
[ "def", "_build_layers", "(", "self", ",", "inputs", ",", "num_outputs", ",", "options", ")", ":", "hiddens", "=", "options", ".", "get", "(", "\"fcnet_hiddens\"", ")", "activation", "=", "get_activation_fn", "(", "options", ".", "get", "(", "\"fcnet_activation...
4eade036a0505e244c976f36aaa2d64386b5129b
train
with_base_config
Returns the given config dict merged with a base agent conf.
python/ray/rllib/agents/trainer.py
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
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
[ "Returns", "the", "given", "config", "dict", "merged", "with", "a", "base", "agent", "conf", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/trainer.py#L241-L246
[ "def", "with_base_config", "(", "base_config", ",", "extra_config", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "base_config", ")", "config", ".", "update", "(", "extra_config", ")", "return", "config" ]
4eade036a0505e244c976f36aaa2d64386b5129b
train
get_agent_class
Returns the class of a known agent given its name.
python/ray/rllib/agents/registry.py
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())
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())
[ "Returns", "the", "class", "of", "a", "known", "agent", "given", "its", "name", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/registry.py#L112-L119
[ "def", "get_agent_class", "(", "alg", ")", ":", "try", ":", "return", "_get_agent_class", "(", "alg", ")", "except", "ImportError", ":", "from", "ray", ".", "rllib", ".", "agents", ".", "mock", "import", "_agent_import_failed", "return", "_agent_import_failed", ...
4eade036a0505e244c976f36aaa2d64386b5129b
train
determine_ip_address
Return the first IP address for an ethernet interface on the system.
python/ray/reporter.py
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]
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]
[ "Return", "the", "first", "IP", "address", "for", "an", "ethernet", "interface", "on", "the", "system", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/reporter.py#L61-L67
[ "def", "determine_ip_address", "(", ")", ":", "addrs", "=", "[", "x", ".", "address", "for", "k", ",", "v", "in", "psutil", ".", "net_if_addrs", "(", ")", ".", "items", "(", ")", "if", "k", "[", "0", "]", "==", "\"e\"", "for", "x", "in", "v", "...
4eade036a0505e244c976f36aaa2d64386b5129b
train
Reporter.perform_iteration
Get any changes to the log files and push updates to Redis.
python/ray/reporter.py
def perform_iteration(self): """Get any changes to the log files and push updates to Redis.""" stats = self.get_all_stats() self.redis_client.publish( self.redis_key, jsonify_asdict(stats), )
def perform_iteration(self): """Get any changes to the log files and push updates to Redis.""" stats = self.get_all_stats() self.redis_client.publish( self.redis_key, jsonify_asdict(stats), )
[ "Get", "any", "changes", "to", "the", "log", "files", "and", "push", "updates", "to", "Redis", "." ]
ray-project/ray
python
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/reporter.py#L163-L170
[ "def", "perform_iteration", "(", "self", ")", ":", "stats", "=", "self", ".", "get_all_stats", "(", ")", "self", ".", "redis_client", ".", "publish", "(", "self", ".", "redis_key", ",", "jsonify_asdict", "(", "stats", ")", ",", ")" ]
4eade036a0505e244c976f36aaa2d64386b5129b