id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
24,400
ray-project/ray
python/ray/tune/automlboard/models/models.py
TrialRecord.from_json
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_ti...
python
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_ti...
[ "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\"", "]...
Build a Trial instance from a json string.
[ "Build", "a", "Trial", "instance", "from", "a", "json", "string", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/models/models.py#L48-L57
24,401
ray-project/ray
python/ray/tune/automlboard/models/models.py
ResultRecord.from_json
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), ...
python
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), ...
[ "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...
Build a Result instance from a json string.
[ "Build", "a", "Result", "instance", "from", "a", "json", "string", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/models/models.py#L80-L98
24,402
ray-project/ray
python/ray/rllib/evaluation/postprocessing.py
compute_advantages
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 f...
python
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 f...
[ "def", "compute_advantages", "(", "rollout", ",", "last_r", ",", "gamma", "=", "0.9", ",", "lambda_", "=", "1.0", ",", "use_gae", "=", "True", ")", ":", "traj", "=", "{", "}", "trajsize", "=", "len", "(", "rollout", "[", "SampleBatch", ".", "ACTIONS", ...
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 Genera...
[ "Given", "a", "rollout", "compute", "its", "value", "targets", "and", "the", "advantage", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/evaluation/postprocessing.py#L23-L70
24,403
ray-project/ray
python/ray/monitor.py
Monitor.xray_heartbeat_batch_handler
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.HeartbeatBatchT...
python
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.HeartbeatBatchT...
[ "def", "xray_heartbeat_batch_handler", "(", "self", ",", "unused_channel", ",", "data", ")", ":", "gcs_entries", "=", "ray", ".", "gcs_utils", ".", "GcsTableEntry", ".", "GetRootAsGcsTableEntry", "(", "data", ",", "0", ")", "heartbeat_data", "=", "gcs_entries", ...
Handle an xray heartbeat batch message from Redis.
[ "Handle", "an", "xray", "heartbeat", "batch", "message", "from", "Redis", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/monitor.py#L102-L135
24,404
ray-project/ray
python/ray/monitor.py
Monitor.xray_driver_removed_handler
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( ...
python
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( ...
[ "def", "xray_driver_removed_handler", "(", "self", ",", "unused_channel", ",", "data", ")", ":", "gcs_entries", "=", "ray", ".", "gcs_utils", ".", "GcsTableEntry", ".", "GetRootAsGcsTableEntry", "(", "data", ",", "0", ")", "driver_data", "=", "gcs_entries", ".",...
Handle a notification that a driver has been removed. Args: unused_channel: The message channel. data: The message data.
[ "Handle", "a", "notification", "that", "a", "driver", "has", "been", "removed", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/monitor.py#L201-L217
24,405
ray-project/ray
python/ray/monitor.py
Monitor.process_messages
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 mess...
python
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 mess...
[ "def", "process_messages", "(", "self", ",", "max_messages", "=", "10000", ")", ":", "subscribe_clients", "=", "[", "self", ".", "primary_subscribe_client", "]", "for", "subscribe_client", "in", "subscribe_clients", ":", "for", "_", "in", "range", "(", "max_mess...
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.
[ "Process", "all", "messages", "ready", "in", "the", "subscription", "channels", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/monitor.py#L219-L252
24,406
ray-project/ray
python/ray/monitor.py
Monitor.run
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.subscri...
python
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.subscri...
[ "def", "run", "(", "self", ")", ":", "# Initialize the subscription channel.", "self", ".", "subscribe", "(", "ray", ".", "gcs_utils", ".", "XRAY_HEARTBEAT_BATCH_CHANNEL", ")", "self", ".", "subscribe", "(", "ray", ".", "gcs_utils", ".", "XRAY_DRIVER_CHANNEL", ")"...
Run the monitor. This function loops forever, checking for messages about dead database clients and cleaning up state accordingly.
[ "Run", "the", "monitor", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/monitor.py#L295-L325
24,407
ray-project/ray
python/ray/tune/automlboard/frontend/view.py
index
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_nu...
python
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_nu...
[ "def", "index", "(", "request", ")", ":", "recent_jobs", "=", "JobRecord", ".", "objects", ".", "order_by", "(", "\"-start_time\"", ")", "[", "0", ":", "100", "]", "recent_trials", "=", "TrialRecord", ".", "objects", ".", "order_by", "(", "\"-start_time\"", ...
View for the home page.
[ "View", "for", "the", "home", "page", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/frontend/view.py#L17-L41
24,408
ray-project/ray
python/ray/tune/automlboard/frontend/view.py
job
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_t...
python
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_t...
[ "def", "job", "(", "request", ")", ":", "job_id", "=", "request", ".", "GET", ".", "get", "(", "\"job_id\"", ")", "recent_jobs", "=", "JobRecord", ".", "objects", ".", "order_by", "(", "\"-start_time\"", ")", "[", "0", ":", "100", "]", "recent_trials", ...
View for a single job.
[ "View", "for", "a", "single", "job", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/frontend/view.py#L44-L74
24,409
ray-project/ray
python/ray/tune/automlboard/frontend/view.py
trial
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_...
python
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_...
[ "def", "trial", "(", "request", ")", ":", "job_id", "=", "request", ".", "GET", ".", "get", "(", "\"job_id\"", ")", "trial_id", "=", "request", ".", "GET", ".", "get", "(", "\"trial_id\"", ")", "recent_trials", "=", "TrialRecord", ".", "objects", ".", ...
View for a single trial.
[ "View", "for", "a", "single", "trial", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/frontend/view.py#L77-L97
24,410
ray-project/ray
python/ray/tune/automlboard/frontend/view.py
get_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) ...
python
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) ...
[ "def", "get_job_info", "(", "current_job", ")", ":", "trials", "=", "TrialRecord", ".", "objects", ".", "filter", "(", "job_id", "=", "current_job", ".", "job_id", ")", "total_num", "=", "len", "(", "trials", ")", "running_num", "=", "sum", "(", "t", "."...
Get job information for current job.
[ "Get", "job", "information", "for", "current", "job", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/frontend/view.py#L100-L131
24,411
ray-project/ray
python/ray/tune/automlboard/frontend/view.py
get_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 ...
python
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 ...
[ "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...
Get job information for current trial.
[ "Get", "job", "information", "for", "current", "trial", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/frontend/view.py#L134-L161
24,412
ray-project/ray
python/ray/tune/automlboard/frontend/view.py
get_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): ...
python
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): ...
[ "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", "(", ...
Get winner trial of a job.
[ "Get", "winner", "trial", "of", "a", "job", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/frontend/view.py#L164-L182
24,413
ray-project/ray
python/ray/tune/config_parser.py
to_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 ...
python
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 ...
[ "def", "to_argv", "(", "config", ")", ":", "argv", "=", "[", "]", "for", "k", ",", "v", "in", "config", ".", "items", "(", ")", ":", "if", "\"-\"", "in", "k", ":", "raise", "ValueError", "(", "\"Use '_' instead of '-' in `{}`\"", ".", "format", "(", ...
Converts configuration to a command line argument format.
[ "Converts", "configuration", "to", "a", "command", "line", "argument", "format", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/config_parser.py#L154-L170
24,414
ray-project/ray
python/ray/tune/config_parser.py
create_trial_from_spec
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_pars...
python
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_pars...
[ "def", "create_trial_from_spec", "(", "spec", ",", "output_path", ",", "parser", ",", "*", "*", "trial_kwargs", ")", ":", "try", ":", "args", "=", "parser", ".", "parse_args", "(", "to_argv", "(", "spec", ")", ")", "except", "SystemExit", ":", "raise", "...
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. ...
[ "Creates", "a", "Trial", "object", "from", "parsing", "the", "spec", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/config_parser.py#L173-L218
24,415
ray-project/ray
python/ray/autoscaler/gcp/node_provider.py
wait_for_compute_zone_operation
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...
python
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...
[ "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", "[", ...
Poll for compute zone operation until finished.
[ "Poll", "for", "compute", "zone", "operation", "until", "finished", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/autoscaler/gcp/node_provider.py#L22-L42
24,416
ray-project/ray
python/ray/experimental/signal.py
_get_task_id
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 cre...
python
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 cre...
[ "def", "_get_task_id", "(", "source", ")", ":", "if", "type", "(", "source", ")", "is", "ray", ".", "actor", ".", "ActorHandle", ":", "return", "source", ".", "_ray_actor_id", "else", ":", "if", "type", "(", "source", ")", "is", "ray", ".", "TaskID", ...
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 i...
[ "Return", "the", "task", "id", "associated", "to", "the", "generic", "source", "of", "the", "signal", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/signal.py#L36-L54
24,417
ray-project/ray
python/ray/experimental/signal.py
receive
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...
python
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...
[ "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...
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...
[ "Get", "all", "outstanding", "signals", "from", "sources", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/signal.py#L79-L166
24,418
ray-project/ray
python/ray/experimental/signal.py
reset
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")...
python
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")...
[ "def", "reset", "(", ")", ":", "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. If the worker calls receive() on a source next, it will get all the signals generated by that source starting with index = 1.
[ "Reset", "the", "worker", "state", "associated", "with", "any", "signals", "that", "this", "worker", "has", "received", "so", "far", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/signal.py#L184-L193
24,419
ray-project/ray
python/ray/rllib/utils/debug.py
log_once
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: ...
python
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: ...
[ "def", "log_once", "(", "key", ")", ":", "global", "_last_logged", "if", "_disabled", ":", "return", "False", "elif", "key", "not", "in", "_logged", ":", "_logged", ".", "add", "(", "key", ")", "_last_logged", "=", "time", ".", "time", "(", ")", "retur...
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")
[ "Returns", "True", "if", "this", "is", "the", "first", "call", "for", "a", "given", "key", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/utils/debug.py#L18-L41
24,420
ray-project/ray
python/ray/experimental/api.py
get
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 t...
python
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 t...
[ "def", "get", "(", "object_ids", ")", ":", "if", "isinstance", "(", "object_ids", ",", "(", "tuple", ",", "np", ".", "ndarray", ")", ")", ":", "return", "ray", ".", "get", "(", "list", "(", "object_ids", ")", ")", "elif", "isinstance", "(", "object_i...
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: obj...
[ "Get", "a", "single", "or", "a", "collection", "of", "remote", "objects", "from", "the", "object", "store", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/api.py#L9-L38
24,421
ray-project/ray
python/ray/tune/experiment.py
_raise_deprecation_note
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...
python
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...
[ "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.\"", ".", "...
User notification for deprecated parameter. Arguments: deprecated (str): Deprecated parameter. replacement (str): Replacement parameter to use instead. soft (bool): Fatal if True.
[ "User", "notification", "for", "deprecated", "parameter", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/experiment.py#L18-L32
24,422
ray-project/ray
python/ray/tune/experiment.py
convert_to_experiment_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 ...
python
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 ...
[ "def", "convert_to_experiment_list", "(", "experiments", ")", ":", "exp_list", "=", "experiments", "# Transform list if necessary", "if", "experiments", "is", "None", ":", "exp_list", "=", "[", "]", "elif", "isinstance", "(", "experiments", ",", "Experiment", ")", ...
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.
[ "Produces", "a", "list", "of", "Experiment", "objects", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/experiment.py#L180-L215
24,423
ray-project/ray
python/ray/tune/experiment.py
Experiment.from_json
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 c...
python
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 c...
[ "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...
Generates an Experiment object from JSON. Args: name (str): Name of Experiment. spec (dict): JSON configuration of experiment.
[ "Generates", "an", "Experiment", "object", "from", "JSON", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/experiment.py#L118-L142
24,424
ray-project/ray
python/ray/tune/experiment.py
Experiment._register_if_needed
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. Argum...
python
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. Argum...
[ "def", "_register_if_needed", "(", "cls", ",", "run_object", ")", ":", "if", "isinstance", "(", "run_object", ",", "six", ".", "string_types", ")", ":", "return", "run_object", "elif", "isinstance", "(", "run_object", ",", "types", ".", "FunctionType", ")", ...
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): Tr...
[ "Registers", "Trainable", "or", "Function", "at", "runtime", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/experiment.py#L145-L177
24,425
ray-project/ray
python/ray/experimental/array/distributed/linalg.py
tsqr
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...
python
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...
[ "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", ".", "...
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 ...
[ "Perform", "a", "QR", "decomposition", "of", "a", "tall", "-", "skinny", "matrix", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/array/distributed/linalg.py#L15-L84
24,426
ray-project/ray
python/ray/experimental/array/distributed/linalg.py
modified_lu
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 ma...
python
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 ma...
[ "def", "modified_lu", "(", "q", ")", ":", "q", "=", "q", ".", "assemble", "(", ")", "m", ",", "b", "=", "q", ".", "shape", "[", "0", "]", ",", "q", ".", "shape", "[", "1", "]", "S", "=", "np", ".", "zeros", "(", "b", ")", "q_work", "=", ...
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...
[ "Perform", "a", "modified", "LU", "decomposition", "of", "a", "matrix", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/array/distributed/linalg.py#L91-L125
24,427
ray-project/ray
python/ray/tune/trial_runner.py
_naturalize
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]
python
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", ")", ":", "splits", "=", "re", ".", "split", "(", "\"([0-9]+)\"", ",", "string", ")", "return", "[", "int", "(", "text", ")", "if", "text", ".", "isdigit", "(", ")", "else", "text", ".", "lower", "(", ")", "for"...
Provides a natural representation for string for nice sorting.
[ "Provides", "a", "natural", "representation", "for", "string", "for", "nice", "sorting", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L30-L33
24,428
ray-project/ray
python/ray/tune/trial_runner.py
_find_newest_ckpt
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)
python
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", ")", ":", "full_paths", "=", "[", "os", ".", "path", ".", "join", "(", "ckpt_dir", ",", "fname", ")", "for", "fname", "in", "os", ".", "listdir", "(", "ckpt_dir", ")", "if", "fname", ".", "startswith", "(", ...
Returns path to most recently modified checkpoint.
[ "Returns", "path", "to", "most", "recently", "modified", "checkpoint", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L36-L42
24,429
ray-project/ray
python/ray/tune/trial_runner.py
TrialRunner.checkpoint
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_che...
python
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_che...
[ "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",...
Saves execution state to `self._metadata_checkpoint_dir`. Overwrites the current session checkpoint, which starts when self is instantiated.
[ "Saves", "execution", "state", "to", "self", ".", "_metadata_checkpoint_dir", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L167-L193
24,430
ray-project/ray
python/ray/tune/trial_runner.py
TrialRunner.restore
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 tri...
python
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 tri...
[ "def", "restore", "(", "cls", ",", "metadata_checkpoint_dir", ",", "search_alg", "=", "None", ",", "scheduler", "=", "None", ",", "trial_executor", "=", "None", ")", ":", "newest_ckpt_path", "=", "_find_newest_ckpt", "(", "metadata_checkpoint_dir", ")", "with", ...
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 ...
[ "Restores", "all", "checkpointed", "trials", "from", "previous", "run", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L196-L245
24,431
ray-project/ray
python/ray/tune/trial_runner.py
TrialRunner.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 ...
python
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 ...
[ "def", "is_finished", "(", "self", ")", ":", "if", "self", ".", "_total_time", ">", "self", ".", "_global_time_limit", ":", "logger", ".", "warning", "(", "\"Exceeded global time limit {} / {}\"", ".", "format", "(", "self", ".", "_total_time", ",", "self", "....
Returns whether all trials have finished running.
[ "Returns", "whether", "all", "trials", "have", "finished", "running", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L247-L256
24,432
ray-project/ray
python/ray/tune/trial_runner.py
TrialRunner.step
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 ...
python
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 ...
[ "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", ".", ...
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().
[ "Runs", "one", "step", "of", "the", "trial", "event", "loop", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L258-L308
24,433
ray-project/ray
python/ray/tune/trial_runner.py
TrialRunner.add_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"): ...
python
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"): ...
[ "def", "add_trial", "(", "self", ",", "trial", ")", ":", "trial", ".", "set_verbose", "(", "self", ".", "_verbose", ")", "self", ".", "_trials", ".", "append", "(", "trial", ")", "with", "warn_if_slow", "(", "\"scheduler.on_trial_add\"", ")", ":", "self", ...
Adds a new trial to this TrialRunner. Trials may be added at any time. Args: trial (Trial): Trial to queue.
[ "Adds", "a", "new", "trial", "to", "this", "TrialRunner", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L322-L334
24,434
ray-project/ray
python/ray/tune/trial_runner.py
TrialRunner._get_next_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(...
python
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(...
[ "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", ".", ...
Replenishes queue. Blocks if all trials queued have finished, but search algorithm is still not finished.
[ "Replenishes", "queue", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L423-L434
24,435
ray-project/ray
python/ray/tune/trial_runner.py
TrialRunner._checkpoint_trial_if_needed
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)...
python
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)...
[ "def", "_checkpoint_trial_if_needed", "(", "self", ",", "trial", ")", ":", "if", "trial", ".", "should_checkpoint", "(", ")", ":", "# Save trial runtime if possible", "if", "hasattr", "(", "trial", ",", "\"runner\"", ")", "and", "trial", ".", "runner", ":", "s...
Checkpoints trial based off trial.last_result.
[ "Checkpoints", "trial", "based", "off", "trial", ".", "last_result", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L506-L512
24,436
ray-project/ray
python/ray/tune/trial_runner.py
TrialRunner._try_recover
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: ...
python
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: ...
[ "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_...
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.
[ "Tries", "to", "recover", "trial", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L514-L542
24,437
ray-project/ray
python/ray/tune/trial_runner.py
TrialRunner._requeue_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, ...
python
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, ...
[ "def", "_requeue_trial", "(", "self", ",", "trial", ")", ":", "self", ".", "_scheduler_alg", ".", "on_trial_error", "(", "self", ",", "trial", ")", "self", ".", "trial_executor", ".", "set_status", "(", "trial", ",", "Trial", ".", "PENDING", ")", "with", ...
Notification to TrialScheduler and requeue trial. This does not notify the SearchAlgorithm because the function evaluation is still in progress.
[ "Notification", "to", "TrialScheduler", "and", "requeue", "trial", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L544-L553
24,438
ray-project/ray
python/ray/tune/trial_runner.py
TrialRunner._update_trial_queue
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 algorith...
python
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 algorith...
[ "def", "_update_trial_queue", "(", "self", ",", "blocking", "=", "False", ",", "timeout", "=", "600", ")", ":", "trials", "=", "self", ".", "_search_alg", ".", "next_trials", "(", ")", "if", "blocking", "and", "not", "trials", ":", "start", "=", "time", ...
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 o...
[ "Adds", "next", "trials", "to", "queue", "if", "possible", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L555-L578
24,439
ray-project/ray
python/ray/tune/trial_runner.py
TrialRunner.stop_trial
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 ...
python
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 ...
[ "def", "stop_trial", "(", "self", ",", "trial", ")", ":", "error", "=", "False", "error_msg", "=", "None", "if", "trial", ".", "status", "in", "[", "Trial", ".", "ERROR", ",", "Trial", ".", "TERMINATED", "]", ":", "return", "elif", "trial", ".", "sta...
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 ...
[ "Stops", "trial", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L588-L620
24,440
ray-project/ray
examples/cython/cython_main.py
run_func
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...
python
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...
[ "def", "run_func", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ray", ".", "init", "(", ")", "func", "=", "ray", ".", "remote", "(", "func", ")", "# NOTE: kwargs not allowed for now", "result", "=", "ray", ".", "get", "(", "func...
Helper function for running examples
[ "Helper", "function", "for", "running", "examples" ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/examples/cython/cython_main.py#L13-L26
24,441
ray-project/ray
examples/cython/cython_main.py
example6
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)
python
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", "(", ")", ":", "ray", ".", "init", "(", ")", "cls", "=", "ray", ".", "remote", "(", "cyth", ".", "simple_class", ")", "a1", "=", "cls", ".", "remote", "(", ")", "a2", "=", "cls", ".", "remote", "(", ")", "result1", "=", "ray"...
Cython simple class
[ "Cython", "simple", "class" ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/examples/cython/cython_main.py#L73-L85
24,442
ray-project/ray
python/ray/rllib/agents/dqn/dqn_policy_graph.py
_adjust_nstep
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 ...
python
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 ...
[ "def", "_adjust_nstep", "(", "n_step", ",", "gamma", ",", "obs", ",", "actions", ",", "rewards", ",", "new_obs", ",", "dones", ")", ":", "assert", "not", "any", "(", "dones", "[", ":", "-", "1", "]", ")", ",", "\"Unexpected done in middle of trajectory\"",...
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 traject...
[ "Rewrites", "the", "given", "trajectory", "fragments", "to", "encode", "n", "-", "step", "rewards", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/dqn/dqn_policy_graph.py#L603-L625
24,443
ray-project/ray
python/ray/rllib/agents/dqn/dqn_policy_graph.py
_minimize_and_clip
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) ...
python
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) ...
[ "def", "_minimize_and_clip", "(", "optimizer", ",", "objective", ",", "var_list", ",", "clip_val", "=", "10", ")", ":", "gradients", "=", "optimizer", ".", "compute_gradients", "(", "objective", ",", "var_list", "=", "var_list", ")", "for", "i", ",", "(", ...
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`
[ "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" ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/dqn/dqn_policy_graph.py#L667-L676
24,444
ray-project/ray
python/ray/rllib/agents/dqn/dqn_policy_graph.py
_scope_vars
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...
python
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...
[ "def", "_scope_vars", "(", "scope", ",", "trainable_only", "=", "False", ")", ":", "return", "tf", ".", "get_collection", "(", "tf", ".", "GraphKeys", ".", "TRAINABLE_VARIABLES", "if", "trainable_only", "else", "tf", ".", "GraphKeys", ".", "VARIABLES", ",", ...
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 ------- v...
[ "Get", "variables", "inside", "a", "scope", "The", "scope", "can", "be", "specified", "as", "a", "string" ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/dqn/dqn_policy_graph.py#L679-L700
24,445
ray-project/ray
python/ray/experimental/sgd/tfbench/convnet_builder.py
ConvNetBuilder.get_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=n...
python
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=n...
[ "def", "get_custom_getter", "(", "self", ")", ":", "def", "inner_custom_getter", "(", "getter", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "use_tf_layers", ":", "return", "getter", "(", "*", "args", ",", "*", "*", ...
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()): netwo...
[ "Returns", "a", "custom", "getter", "that", "this", "class", "s", "methods", "must", "be", "called" ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/sgd/tfbench/convnet_builder.py#L58-L89
24,446
ray-project/ray
python/ray/experimental/sgd/tfbench/convnet_builder.py
ConvNetBuilder.switch_to_aux_top_layer
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 = se...
python
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 = se...
[ "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", "=",...
Context that construct cnn in the auxiliary arm.
[ "Context", "that", "construct", "cnn", "in", "the", "auxiliary", "arm", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/sgd/tfbench/convnet_builder.py#L92-L104
24,447
ray-project/ray
python/ray/experimental/sgd/tfbench/convnet_builder.py
ConvNetBuilder._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 = po...
python
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 = po...
[ "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", ...
Construct a pooling layer.
[ "Construct", "a", "pooling", "layer", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/sgd/tfbench/convnet_builder.py#L245-L275
24,448
ray-project/ray
python/ray/experimental/sgd/tfbench/convnet_builder.py
ConvNetBuilder.mpool
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,...
python
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,...
[ "def", "mpool", "(", "self", ",", "k_height", ",", "k_width", ",", "d_height", "=", "2", ",", "d_width", "=", "2", ",", "mode", "=", "\"VALID\"", ",", "input_layer", "=", "None", ",", "num_channels_in", "=", "None", ")", ":", "return", "self", ".", "...
Construct a max pooling layer.
[ "Construct", "a", "max", "pooling", "layer", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/sgd/tfbench/convnet_builder.py#L277-L288
24,449
ray-project/ray
python/ray/experimental/sgd/tfbench/convnet_builder.py
ConvNetBuilder.apool
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_p...
python
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_p...
[ "def", "apool", "(", "self", ",", "k_height", ",", "k_width", ",", "d_height", "=", "2", ",", "d_width", "=", "2", ",", "mode", "=", "\"VALID\"", ",", "input_layer", "=", "None", ",", "num_channels_in", "=", "None", ")", ":", "return", "self", ".", "...
Construct an average pooling layer.
[ "Construct", "an", "average", "pooling", "layer", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/sgd/tfbench/convnet_builder.py#L290-L301
24,450
ray-project/ray
python/ray/experimental/sgd/tfbench/convnet_builder.py
ConvNetBuilder._batch_norm_without_layers
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_var...
python
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_var...
[ "def", "_batch_norm_without_layers", "(", "self", ",", "input_layer", ",", "decay", ",", "use_scale", ",", "epsilon", ")", ":", "shape", "=", "input_layer", ".", "shape", "num_channels", "=", "shape", "[", "3", "]", "if", "self", ".", "data_format", "==", ...
Batch normalization on `input_layer` without tf.layers.
[ "Batch", "normalization", "on", "input_layer", "without", "tf", ".", "layers", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/sgd/tfbench/convnet_builder.py#L411-L466
24,451
ray-project/ray
python/ray/experimental/sgd/tfbench/convnet_builder.py
ConvNetBuilder.lrn
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_laye...
python
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_laye...
[ "def", "lrn", "(", "self", ",", "depth_radius", ",", "bias", ",", "alpha", ",", "beta", ")", ":", "name", "=", "\"lrn\"", "+", "str", "(", "self", ".", "counts", "[", "\"lrn\"", "]", ")", "self", ".", "counts", "[", "\"lrn\"", "]", "+=", "1", "se...
Adds a local response normalization layer.
[ "Adds", "a", "local", "response", "normalization", "layer", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/sgd/tfbench/convnet_builder.py#L501-L507
24,452
ray-project/ray
python/ray/experimental/internal_kv.py
_internal_kv_get
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")
python
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", ")", ":", "worker", "=", "ray", ".", "worker", ".", "get_global_worker", "(", ")", "if", "worker", ".", "mode", "==", "ray", ".", "worker", ".", "LOCAL_MODE", ":", "return", "_local", ".", "get", "(", "key", ")", ...
Fetch the value of a binary key.
[ "Fetch", "the", "value", "of", "a", "binary", "key", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/internal_kv.py#L15-L22
24,453
ray-project/ray
python/ray/experimental/internal_kv.py
_internal_kv_put
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...
python
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...
[ "def", "_internal_kv_put", "(", "key", ",", "value", ",", "overwrite", "=", "False", ")", ":", "worker", "=", "ray", ".", "worker", ".", "get_global_worker", "(", ")", "if", "worker", ".", "mode", "==", "ray", ".", "worker", ".", "LOCAL_MODE", ":", "ex...
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.
[ "Globally", "associates", "a", "value", "with", "a", "given", "binary", "key", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/internal_kv.py#L25-L45
24,454
ray-project/ray
python/ray/rllib/optimizers/aso_tree_aggregator.py
TreeAggregator.init
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 ag...
python
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 ag...
[ "def", "init", "(", "self", ",", "aggregators", ")", ":", "assert", "len", "(", "aggregators", ")", "==", "self", ".", "num_aggregation_workers", ",", "aggregators", "if", "len", "(", "self", ".", "remote_evaluators", ")", "<", "self", ".", "num_aggregation_...
Deferred init so that we can pass in previously created workers.
[ "Deferred", "init", "so", "that", "we", "can", "pass", "in", "previously", "created", "workers", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/optimizers/aso_tree_aggregator.py#L57-L84
24,455
ray-project/ray
python/ray/internal/internal_api.py
free
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 valu...
python
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 valu...
[ "def", "free", "(", "object_ids", ",", "local_only", "=", "False", ",", "delete_creating_tasks", "=", "False", ")", ":", "worker", "=", "ray", ".", "worker", ".", "get_global_worker", "(", ")", "if", "ray", ".", "worker", ".", "_mode", "(", ")", "==", ...
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 i...
[ "Free", "a", "list", "of", "IDs", "from", "object", "stores", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/internal/internal_api.py#L11-L55
24,456
ray-project/ray
python/ray/tune/automlboard/backend/collector.py
CollectorService.run
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()
python
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", ")", ":", "self", ".", "collector", ".", "start", "(", ")", "if", "self", ".", "standalone", ":", "self", ".", "collector", ".", "join", "(", ")" ]
Start the collector worker thread. If running in standalone mode, the current thread will wait until the collector thread ends.
[ "Start", "the", "collector", "worker", "thread", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L47-L55
24,457
ray-project/ray
python/ray/tune/automlboard/backend/collector.py
CollectorService.init_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 " ...
python
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 " ...
[ "def", "init_logger", "(", "cls", ",", "log_level", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "\"AutoMLBoard\"", ")", "handler", "=", "logging", ".", "StreamHandler", "(", ")", "formatter", "=", "logging", ".", "Formatter", "(", "\"[%(leveln...
Initialize logger settings.
[ "Initialize", "logger", "settings", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L62-L72
24,458
ray-project/ray
python/ray/tune/automlboard/backend/collector.py
Collector.run
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: ...
python
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: ...
[ "def", "run", "(", "self", ")", ":", "self", ".", "_initialize", "(", ")", "self", ".", "_do_collect", "(", ")", "while", "not", "self", ".", "_is_finished", ":", "time", ".", "sleep", "(", "self", ".", "_reload_interval", ")", "self", ".", "_do_collec...
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.
[ "Run", "the", "main", "event", "loop", "for", "collector", "thread", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L98-L111
24,459
ray-project/ray
python/ray/tune/automlboard/backend/collector.py
Collector._initialize
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("Collect...
python
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("Collect...
[ "def", "_initialize", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "_logdir", ")", ":", "raise", "CollectorError", "(", "\"Log directory %s not exists\"", "%", "self", ".", "_logdir", ")", "self", ".", "logger", ...
Initialize collector worker thread, Log path will be checked first. Records in DB backend will be cleared.
[ "Initialize", "collector", "worker", "thread", "Log", "path", "will", "be", "checked", "first", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L117-L131
24,460
ray-project/ray
python/ray/tune/automlboard/backend/collector.py
Collector.sync_job_info
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: jo...
python
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: jo...
[ "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...
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
[ "Load", "information", "of", "the", "job", "with", "the", "given", "job", "name", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L140-L165
24,461
ray-project/ray
python/ray/tune/automlboard/backend/collector.py
Collector.sync_trial_info
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_...
python
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_...
[ "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_...
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)
[ "Load", "information", "of", "the", "trial", "from", "the", "given", "experiment", "directory", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L167-L185
24,462
ray-project/ray
python/ray/tune/automlboard/backend/collector.py
Collector._create_job_info
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) ...
python
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) ...
[ "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...
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.
[ "Create", "information", "for", "given", "job", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L187-L201
24,463
ray-project/ray
python/ray/tune/automlboard/backend/collector.py
Collector._update_job_info
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 ...
python
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 ...
[ "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", ...
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
[ "Update", "information", "for", "given", "job", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L204-L223
24,464
ray-project/ray
python/ray/tune/automlboard/backend/collector.py
Collector._create_trial_info
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_met...
python
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_met...
[ "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",...
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.
[ "Create", "information", "for", "given", "trial", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L225-L239
24,465
ray-project/ray
python/ray/tune/automlboard/backend/collector.py
Collector._update_trial_info
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(exp...
python
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(exp...
[ "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...
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)
[ "Update", "information", "for", "given", "trial", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L241-L281
24,466
ray-project/ray
python/ray/tune/automlboard/backend/collector.py
Collector._build_job_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...
python
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...
[ "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...
Build meta file for job. Args: job_dir (str): Directory path of the job. Return: A dict of job meta info.
[ "Build", "meta", "file", "for", "job", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L284-L312
24,467
ray-project/ray
python/ray/tune/automlboard/backend/collector.py
Collector._build_trial_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) ...
python
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) ...
[ "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", "=", ...
Build meta file for trial. Args: expr_dir (str): Directory path of the experiment. Return: A dict of trial meta info.
[ "Build", "meta", "file", "for", "trial", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L315-L354
24,468
ray-project/ray
python/ray/tune/automlboard/backend/collector.py
Collector._add_results
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) resul...
python
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) resul...
[ "def", "_add_results", "(", "self", ",", "results", ",", "trial_id", ")", ":", "for", "result", "in", "results", ":", "self", ".", "logger", ".", "debug", "(", "\"Appending result: %s\"", "%", "result", ")", "result", "[", "\"trial_id\"", "]", "=", "trial_...
Add a list of results into db. Args: results (list): A list of json results. trial_id (str): Id of the trial.
[ "Add", "a", "list", "of", "results", "into", "db", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L356-L367
24,469
ray-project/ray
python/ray/rllib/models/lstm.py
add_time_dimension
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....
python
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....
[ "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", ...
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 ...
[ "Adds", "a", "time", "dimension", "to", "padded", "inputs", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/models/lstm.py#L95-L119
24,470
ray-project/ray
python/ray/rllib/models/lstm.py
chop_into_sequences
def chop_into_sequences(episode_ids, unroll_ids, agent_indices, feature_columns, state_columns, max_seq_len, dynamic_max=True, _extra_padding=0): ""...
python
def chop_into_sequences(episode_ids, unroll_ids, agent_indices, feature_columns, state_columns, max_seq_len, dynamic_max=True, _extra_padding=0): ""...
[ "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_...
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...
[ "Truncate", "and", "pad", "experiences", "into", "fixed", "-", "length", "sequences", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/models/lstm.py#L123-L217
24,471
ray-project/ray
python/ray/tune/schedulers/pbt.py
explore
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 schedu...
python
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 schedu...
[ "def", "explore", "(", "config", ",", "mutations", ",", "resample_probability", ",", "custom_explore_fn", ")", ":", "new_config", "=", "copy", ".", "deepcopy", "(", "config", ")", "for", "key", ",", "distribution", "in", "mutations", ".", "items", "(", ")", ...
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...
[ "Return", "a", "config", "perturbed", "as", "specified", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/schedulers/pbt.py#L41-L87
24,472
ray-project/ray
python/ray/tune/schedulers/pbt.py
make_experiment_tag
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))
python
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", ")", ":", "resolved_vars", "=", "{", "}", "for", "k", "in", "mutations", ".", "keys", "(", ")", ":", "resolved_vars", "[", "(", "\"config\"", ",", "k", ")", "]", "=", "conf...
Appends perturbed params to the trial name to show in the console.
[ "Appends", "perturbed", "params", "to", "the", "trial", "name", "to", "show", "in", "the", "console", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/schedulers/pbt.py#L90-L96
24,473
ray-project/ray
python/ray/tune/schedulers/pbt.py
PopulationBasedTraining._exploit
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.l...
python
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.l...
[ "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", ...
Transfers perturbed state from trial_to_clone -> trial. If specified, also logs the updated hyperparam state.
[ "Transfers", "perturbed", "state", "from", "trial_to_clone", "-", ">", "trial", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/schedulers/pbt.py#L258-L297
24,474
ray-project/ray
python/ray/tune/schedulers/pbt.py
PopulationBasedTraining._quantiles
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_fini...
python
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_fini...
[ "def", "_quantiles", "(", "self", ")", ":", "trials", "=", "[", "]", "for", "trial", ",", "state", "in", "self", ".", "_trial_state", ".", "items", "(", ")", ":", "if", "state", ".", "last_score", "is", "not", "None", "and", "not", "trial", ".", "i...
Returns trials in the lower and upper `quantile` of the population. If there is not enough data to compute this, returns empty lists.
[ "Returns", "trials", "in", "the", "lower", "and", "upper", "quantile", "of", "the", "population", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/schedulers/pbt.py#L299-L314
24,475
ray-project/ray
python/ray/rllib/models/fcnet.py
FullyConnectedNetwork._build_layers
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") ...
python
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") ...
[ "def", "_build_layers", "(", "self", ",", "inputs", ",", "num_outputs", ",", "options", ")", ":", "hiddens", "=", "options", ".", "get", "(", "\"fcnet_hiddens\"", ")", "activation", "=", "get_activation_fn", "(", "options", ".", "get", "(", "\"fcnet_activation...
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().
[ "Process", "the", "flattened", "inputs", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/models/fcnet.py#L17-L46
24,476
ray-project/ray
python/ray/rllib/agents/trainer.py
with_base_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
python
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", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "base_config", ")", "config", ".", "update", "(", "extra_config", ")", "return", "config" ]
Returns the given config dict merged with a base agent conf.
[ "Returns", "the", "given", "config", "dict", "merged", "with", "a", "base", "agent", "conf", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/trainer.py#L241-L246
24,477
ray-project/ray
python/ray/rllib/agents/registry.py
get_agent_class
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())
python
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", ")", ":", "try", ":", "return", "_get_agent_class", "(", "alg", ")", "except", "ImportError", ":", "from", "ray", ".", "rllib", ".", "agents", ".", "mock", "import", "_agent_import_failed", "return", "_agent_import_failed", ...
Returns the class of a known agent given its name.
[ "Returns", "the", "class", "of", "a", "known", "agent", "given", "its", "name", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/registry.py#L112-L119
24,478
ray-project/ray
python/ray/reporter.py
determine_ip_address
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]
python
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", "(", ")", ":", "addrs", "=", "[", "x", ".", "address", "for", "k", ",", "v", "in", "psutil", ".", "net_if_addrs", "(", ")", ".", "items", "(", ")", "if", "k", "[", "0", "]", "==", "\"e\"", "for", "x", "in", "v", "...
Return the first IP address for an ethernet interface on the system.
[ "Return", "the", "first", "IP", "address", "for", "an", "ethernet", "interface", "on", "the", "system", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/reporter.py#L61-L67
24,479
ray-project/ray
python/ray/reporter.py
Reporter.run
def run(self): """Run the reporter.""" while True: try: self.perform_iteration() except Exception: traceback.print_exc() pass time.sleep(ray_constants.REPORTER_UPDATE_INTERVAL_MS / 1000)
python
def run(self): """Run the reporter.""" while True: try: self.perform_iteration() except Exception: traceback.print_exc() pass time.sleep(ray_constants.REPORTER_UPDATE_INTERVAL_MS / 1000)
[ "def", "run", "(", "self", ")", ":", "while", "True", ":", "try", ":", "self", ".", "perform_iteration", "(", ")", "except", "Exception", ":", "traceback", ".", "print_exc", "(", ")", "pass", "time", ".", "sleep", "(", "ray_constants", ".", "REPORTER_UPD...
Run the reporter.
[ "Run", "the", "reporter", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/reporter.py#L172-L181
24,480
ray-project/ray
python/ray/serialization.py
check_serializable
def check_serializable(cls): """Throws an exception if Ray cannot serialize this class efficiently. Args: cls (type): The class to be serialized. Raises: Exception: An exception is raised if Ray cannot serialize this class efficiently. """ if is_named_tuple(cls): ...
python
def check_serializable(cls): """Throws an exception if Ray cannot serialize this class efficiently. Args: cls (type): The class to be serialized. Raises: Exception: An exception is raised if Ray cannot serialize this class efficiently. """ if is_named_tuple(cls): ...
[ "def", "check_serializable", "(", "cls", ")", ":", "if", "is_named_tuple", "(", "cls", ")", ":", "# This case works.", "return", "if", "not", "hasattr", "(", "cls", ",", "\"__new__\"", ")", ":", "print", "(", "\"The class {} does not have a '__new__' attribute and i...
Throws an exception if Ray cannot serialize this class efficiently. Args: cls (type): The class to be serialized. Raises: Exception: An exception is raised if Ray cannot serialize this class efficiently.
[ "Throws", "an", "exception", "if", "Ray", "cannot", "serialize", "this", "class", "efficiently", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/serialization.py#L16-L55
24,481
ray-project/ray
python/ray/serialization.py
is_named_tuple
def is_named_tuple(cls): """Return True if cls is a namedtuple and False otherwise.""" b = cls.__bases__ if len(b) != 1 or b[0] != tuple: return False f = getattr(cls, "_fields", None) if not isinstance(f, tuple): return False return all(type(n) == str for n in f)
python
def is_named_tuple(cls): """Return True if cls is a namedtuple and False otherwise.""" b = cls.__bases__ if len(b) != 1 or b[0] != tuple: return False f = getattr(cls, "_fields", None) if not isinstance(f, tuple): return False return all(type(n) == str for n in f)
[ "def", "is_named_tuple", "(", "cls", ")", ":", "b", "=", "cls", ".", "__bases__", "if", "len", "(", "b", ")", "!=", "1", "or", "b", "[", "0", "]", "!=", "tuple", ":", "return", "False", "f", "=", "getattr", "(", "cls", ",", "\"_fields\"", ",", ...
Return True if cls is a namedtuple and False otherwise.
[ "Return", "True", "if", "cls", "is", "a", "namedtuple", "and", "False", "otherwise", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/serialization.py#L58-L66
24,482
ray-project/ray
python/ray/tune/registry.py
register_trainable
def register_trainable(name, trainable): """Register a trainable function or class. Args: name (str): Name to register. trainable (obj): Function or tune.Trainable class. Functions must take (config, status_reporter) as arguments and will be automatically converted into ...
python
def register_trainable(name, trainable): """Register a trainable function or class. Args: name (str): Name to register. trainable (obj): Function or tune.Trainable class. Functions must take (config, status_reporter) as arguments and will be automatically converted into ...
[ "def", "register_trainable", "(", "name", ",", "trainable", ")", ":", "from", "ray", ".", "tune", ".", "trainable", "import", "Trainable", "from", "ray", ".", "tune", ".", "function_runner", "import", "wrap_function", "if", "isinstance", "(", "trainable", ",",...
Register a trainable function or class. Args: name (str): Name to register. trainable (obj): Function or tune.Trainable class. Functions must take (config, status_reporter) as arguments and will be automatically converted into a class during registration.
[ "Register", "a", "trainable", "function", "or", "class", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/registry.py#L24-L50
24,483
ray-project/ray
python/ray/tune/registry.py
register_env
def register_env(name, env_creator): """Register a custom environment for use with RLlib. Args: name (str): Name to register. env_creator (obj): Function that creates an env. """ if not isinstance(env_creator, FunctionType): raise TypeError("Second argument must be a function."...
python
def register_env(name, env_creator): """Register a custom environment for use with RLlib. Args: name (str): Name to register. env_creator (obj): Function that creates an env. """ if not isinstance(env_creator, FunctionType): raise TypeError("Second argument must be a function."...
[ "def", "register_env", "(", "name", ",", "env_creator", ")", ":", "if", "not", "isinstance", "(", "env_creator", ",", "FunctionType", ")", ":", "raise", "TypeError", "(", "\"Second argument must be a function.\"", ",", "env_creator", ")", "_global_registry", ".", ...
Register a custom environment for use with RLlib. Args: name (str): Name to register. env_creator (obj): Function that creates an env.
[ "Register", "a", "custom", "environment", "for", "use", "with", "RLlib", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/registry.py#L53-L63
24,484
ray-project/ray
python/ray/rllib/evaluation/metrics.py
get_learner_stats
def get_learner_stats(grad_info): """Return optimization stats reported from the policy graph. Example: >>> grad_info = evaluator.learn_on_batch(samples) >>> print(get_stats(grad_info)) {"vf_loss": ..., "policy_loss": ...} """ if LEARNER_STATS_KEY in grad_info: return g...
python
def get_learner_stats(grad_info): """Return optimization stats reported from the policy graph. Example: >>> grad_info = evaluator.learn_on_batch(samples) >>> print(get_stats(grad_info)) {"vf_loss": ..., "policy_loss": ...} """ if LEARNER_STATS_KEY in grad_info: return g...
[ "def", "get_learner_stats", "(", "grad_info", ")", ":", "if", "LEARNER_STATS_KEY", "in", "grad_info", ":", "return", "grad_info", "[", "LEARNER_STATS_KEY", "]", "multiagent_stats", "=", "{", "}", "for", "k", ",", "v", "in", "grad_info", ".", "items", "(", ")...
Return optimization stats reported from the policy graph. Example: >>> grad_info = evaluator.learn_on_batch(samples) >>> print(get_stats(grad_info)) {"vf_loss": ..., "policy_loss": ...}
[ "Return", "optimization", "stats", "reported", "from", "the", "policy", "graph", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/evaluation/metrics.py#L23-L41
24,485
ray-project/ray
python/ray/rllib/evaluation/metrics.py
collect_metrics
def collect_metrics(local_evaluator=None, remote_evaluators=[], timeout_seconds=180): """Gathers episode metrics from PolicyEvaluator instances.""" episodes, num_dropped = collect_episodes( local_evaluator, remote_evaluators, timeout_seconds=timeout_seconds) ...
python
def collect_metrics(local_evaluator=None, remote_evaluators=[], timeout_seconds=180): """Gathers episode metrics from PolicyEvaluator instances.""" episodes, num_dropped = collect_episodes( local_evaluator, remote_evaluators, timeout_seconds=timeout_seconds) ...
[ "def", "collect_metrics", "(", "local_evaluator", "=", "None", ",", "remote_evaluators", "=", "[", "]", ",", "timeout_seconds", "=", "180", ")", ":", "episodes", ",", "num_dropped", "=", "collect_episodes", "(", "local_evaluator", ",", "remote_evaluators", ",", ...
Gathers episode metrics from PolicyEvaluator instances.
[ "Gathers", "episode", "metrics", "from", "PolicyEvaluator", "instances", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/evaluation/metrics.py#L45-L53
24,486
ray-project/ray
python/ray/rllib/evaluation/metrics.py
collect_episodes
def collect_episodes(local_evaluator=None, remote_evaluators=[], timeout_seconds=180): """Gathers new episodes metrics tuples from the given evaluators.""" pending = [ a.apply.remote(lambda ev: ev.get_metrics()) for a in remote_evaluators ] collected, _...
python
def collect_episodes(local_evaluator=None, remote_evaluators=[], timeout_seconds=180): """Gathers new episodes metrics tuples from the given evaluators.""" pending = [ a.apply.remote(lambda ev: ev.get_metrics()) for a in remote_evaluators ] collected, _...
[ "def", "collect_episodes", "(", "local_evaluator", "=", "None", ",", "remote_evaluators", "=", "[", "]", ",", "timeout_seconds", "=", "180", ")", ":", "pending", "=", "[", "a", ".", "apply", ".", "remote", "(", "lambda", "ev", ":", "ev", ".", "get_metric...
Gathers new episodes metrics tuples from the given evaluators.
[ "Gathers", "new", "episodes", "metrics", "tuples", "from", "the", "given", "evaluators", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/evaluation/metrics.py#L57-L79
24,487
ray-project/ray
python/ray/rllib/evaluation/metrics.py
_partition
def _partition(episodes): """Divides metrics data into true rollouts vs off-policy estimates.""" from ray.rllib.evaluation.sampler import RolloutMetrics rollouts, estimates = [], [] for e in episodes: if isinstance(e, RolloutMetrics): rollouts.append(e) elif isinstance(e, O...
python
def _partition(episodes): """Divides metrics data into true rollouts vs off-policy estimates.""" from ray.rllib.evaluation.sampler import RolloutMetrics rollouts, estimates = [], [] for e in episodes: if isinstance(e, RolloutMetrics): rollouts.append(e) elif isinstance(e, O...
[ "def", "_partition", "(", "episodes", ")", ":", "from", "ray", ".", "rllib", ".", "evaluation", ".", "sampler", "import", "RolloutMetrics", "rollouts", ",", "estimates", "=", "[", "]", ",", "[", "]", "for", "e", "in", "episodes", ":", "if", "isinstance",...
Divides metrics data into true rollouts vs off-policy estimates.
[ "Divides", "metrics", "data", "into", "true", "rollouts", "vs", "off", "-", "policy", "estimates", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/evaluation/metrics.py#L163-L176
24,488
ray-project/ray
python/ray/tune/trial_executor.py
TrialExecutor.set_status
def set_status(self, trial, status): """Sets status and checkpoints metadata if needed. Only checkpoints metadata if trial status is a terminal condition. PENDING, PAUSED, and RUNNING switches have checkpoints taken care of in the TrialRunner. Args: trial (Trial): T...
python
def set_status(self, trial, status): """Sets status and checkpoints metadata if needed. Only checkpoints metadata if trial status is a terminal condition. PENDING, PAUSED, and RUNNING switches have checkpoints taken care of in the TrialRunner. Args: trial (Trial): T...
[ "def", "set_status", "(", "self", ",", "trial", ",", "status", ")", ":", "trial", ".", "status", "=", "status", "if", "status", "in", "[", "Trial", ".", "TERMINATED", ",", "Trial", ".", "ERROR", "]", ":", "self", ".", "try_checkpoint_metadata", "(", "t...
Sets status and checkpoints metadata if needed. Only checkpoints metadata if trial status is a terminal condition. PENDING, PAUSED, and RUNNING switches have checkpoints taken care of in the TrialRunner. Args: trial (Trial): Trial to checkpoint. status (Trial.st...
[ "Sets", "status", "and", "checkpoints", "metadata", "if", "needed", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_executor.py#L30-L43
24,489
ray-project/ray
python/ray/tune/trial_executor.py
TrialExecutor.try_checkpoint_metadata
def try_checkpoint_metadata(self, trial): """Checkpoints metadata. Args: trial (Trial): Trial to checkpoint. """ if trial._checkpoint.storage == Checkpoint.MEMORY: logger.debug("Not saving data for trial w/ memory checkpoint.") return try: ...
python
def try_checkpoint_metadata(self, trial): """Checkpoints metadata. Args: trial (Trial): Trial to checkpoint. """ if trial._checkpoint.storage == Checkpoint.MEMORY: logger.debug("Not saving data for trial w/ memory checkpoint.") return try: ...
[ "def", "try_checkpoint_metadata", "(", "self", ",", "trial", ")", ":", "if", "trial", ".", "_checkpoint", ".", "storage", "==", "Checkpoint", ".", "MEMORY", ":", "logger", ".", "debug", "(", "\"Not saving data for trial w/ memory checkpoint.\"", ")", "return", "tr...
Checkpoints metadata. Args: trial (Trial): Trial to checkpoint.
[ "Checkpoints", "metadata", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_executor.py#L45-L58
24,490
ray-project/ray
python/ray/tune/trial_executor.py
TrialExecutor.unpause_trial
def unpause_trial(self, trial): """Sets PAUSED trial to pending to allow scheduler to start.""" assert trial.status == Trial.PAUSED, trial.status self.set_status(trial, Trial.PENDING)
python
def unpause_trial(self, trial): """Sets PAUSED trial to pending to allow scheduler to start.""" assert trial.status == Trial.PAUSED, trial.status self.set_status(trial, Trial.PENDING)
[ "def", "unpause_trial", "(", "self", ",", "trial", ")", ":", "assert", "trial", ".", "status", "==", "Trial", ".", "PAUSED", ",", "trial", ".", "status", "self", ".", "set_status", "(", "trial", ",", "Trial", ".", "PENDING", ")" ]
Sets PAUSED trial to pending to allow scheduler to start.
[ "Sets", "PAUSED", "trial", "to", "pending", "to", "allow", "scheduler", "to", "start", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_executor.py#L114-L117
24,491
ray-project/ray
python/ray/tune/trial_executor.py
TrialExecutor.resume_trial
def resume_trial(self, trial): """Resumes PAUSED trials. This is a blocking call.""" assert trial.status == Trial.PAUSED, trial.status self.start_trial(trial)
python
def resume_trial(self, trial): """Resumes PAUSED trials. This is a blocking call.""" assert trial.status == Trial.PAUSED, trial.status self.start_trial(trial)
[ "def", "resume_trial", "(", "self", ",", "trial", ")", ":", "assert", "trial", ".", "status", "==", "Trial", ".", "PAUSED", ",", "trial", ".", "status", "self", ".", "start_trial", "(", "trial", ")" ]
Resumes PAUSED trials. This is a blocking call.
[ "Resumes", "PAUSED", "trials", ".", "This", "is", "a", "blocking", "call", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_executor.py#L119-L123
24,492
ray-project/ray
python/ray/tune/suggest/nevergrad.py
NevergradSearch.on_trial_complete
def on_trial_complete(self, trial_id, result=None, error=False, early_terminated=False): """Passes the result to Nevergrad unless early terminated or errored. The result is internally negated when in...
python
def on_trial_complete(self, trial_id, result=None, error=False, early_terminated=False): """Passes the result to Nevergrad unless early terminated or errored. The result is internally negated when in...
[ "def", "on_trial_complete", "(", "self", ",", "trial_id", ",", "result", "=", "None", ",", "error", "=", "False", ",", "early_terminated", "=", "False", ")", ":", "ng_trial_info", "=", "self", ".", "_live_trial_mapping", ".", "pop", "(", "trial_id", ")", "...
Passes the result to Nevergrad unless early terminated or errored. The result is internally negated when interacting with Nevergrad so that Nevergrad Optimizers can "maximize" this value, as it minimizes on default.
[ "Passes", "the", "result", "to", "Nevergrad", "unless", "early", "terminated", "or", "errored", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/suggest/nevergrad.py#L109-L122
24,493
ray-project/ray
python/ray/import_thread.py
ImportThread.start
def start(self): """Start the import thread.""" self.t = threading.Thread(target=self._run, name="ray_import_thread") # Making the thread a daemon causes it to exit # when the main thread exits. self.t.daemon = True self.t.start()
python
def start(self): """Start the import thread.""" self.t = threading.Thread(target=self._run, name="ray_import_thread") # Making the thread a daemon causes it to exit # when the main thread exits. self.t.daemon = True self.t.start()
[ "def", "start", "(", "self", ")", ":", "self", ".", "t", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_run", ",", "name", "=", "\"ray_import_thread\"", ")", "# Making the thread a daemon causes it to exit", "# when the main thread exits.", "s...
Start the import thread.
[ "Start", "the", "import", "thread", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/import_thread.py#L36-L42
24,494
ray-project/ray
python/ray/import_thread.py
ImportThread._process_key
def _process_key(self, key): """Process the given export key from redis.""" # Handle the driver case first. if self.mode != ray.WORKER_MODE: if key.startswith(b"FunctionsToRun"): with profiling.profile("fetch_and_run_function"): self.fetch_and_exec...
python
def _process_key(self, key): """Process the given export key from redis.""" # Handle the driver case first. if self.mode != ray.WORKER_MODE: if key.startswith(b"FunctionsToRun"): with profiling.profile("fetch_and_run_function"): self.fetch_and_exec...
[ "def", "_process_key", "(", "self", ",", "key", ")", ":", "# Handle the driver case first.", "if", "self", ".", "mode", "!=", "ray", ".", "WORKER_MODE", ":", "if", "key", ".", "startswith", "(", "b\"FunctionsToRun\"", ")", ":", "with", "profiling", ".", "pro...
Process the given export key from redis.
[ "Process", "the", "given", "export", "key", "from", "redis", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/import_thread.py#L87-L113
24,495
ray-project/ray
python/ray/import_thread.py
ImportThread.fetch_and_execute_function_to_run
def fetch_and_execute_function_to_run(self, key): """Run on arbitrary function on the worker.""" (driver_id, serialized_function, run_on_other_drivers) = self.redis_client.hmget( key, ["driver_id", "function", "run_on_other_drivers"]) if (utils.decode(run_on_other_drivers)...
python
def fetch_and_execute_function_to_run(self, key): """Run on arbitrary function on the worker.""" (driver_id, serialized_function, run_on_other_drivers) = self.redis_client.hmget( key, ["driver_id", "function", "run_on_other_drivers"]) if (utils.decode(run_on_other_drivers)...
[ "def", "fetch_and_execute_function_to_run", "(", "self", ",", "key", ")", ":", "(", "driver_id", ",", "serialized_function", ",", "run_on_other_drivers", ")", "=", "self", ".", "redis_client", ".", "hmget", "(", "key", ",", "[", "\"driver_id\"", ",", "\"function...
Run on arbitrary function on the worker.
[ "Run", "on", "arbitrary", "function", "on", "the", "worker", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/import_thread.py#L115-L140
24,496
ray-project/ray
python/ray/rllib/evaluation/policy_graph.py
clip_action
def clip_action(action, space): """Called to clip actions to the specified range of this policy. Arguments: action: Single action. space: Action space the actions should be present in. Returns: Clipped batch of actions. """ if isinstance(space, gym.spaces.Box): ret...
python
def clip_action(action, space): """Called to clip actions to the specified range of this policy. Arguments: action: Single action. space: Action space the actions should be present in. Returns: Clipped batch of actions. """ if isinstance(space, gym.spaces.Box): ret...
[ "def", "clip_action", "(", "action", ",", "space", ")", ":", "if", "isinstance", "(", "space", ",", "gym", ".", "spaces", ".", "Box", ")", ":", "return", "np", ".", "clip", "(", "action", ",", "space", ".", "low", ",", "space", ".", "high", ")", ...
Called to clip actions to the specified range of this policy. Arguments: action: Single action. space: Action space the actions should be present in. Returns: Clipped batch of actions.
[ "Called", "to", "clip", "actions", "to", "the", "specified", "range", "of", "this", "policy", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/evaluation/policy_graph.py#L265-L287
24,497
ray-project/ray
python/ray/tune/suggest/skopt.py
SkOptSearch.on_trial_complete
def on_trial_complete(self, trial_id, result=None, error=False, early_terminated=False): """Passes the result to skopt unless early terminated or errored. The result is internally negated when intera...
python
def on_trial_complete(self, trial_id, result=None, error=False, early_terminated=False): """Passes the result to skopt unless early terminated or errored. The result is internally negated when intera...
[ "def", "on_trial_complete", "(", "self", ",", "trial_id", ",", "result", "=", "None", ",", "error", "=", "False", ",", "early_terminated", "=", "False", ")", ":", "skopt_trial_info", "=", "self", ".", "_live_trial_mapping", ".", "pop", "(", "trial_id", ")", ...
Passes the result to skopt unless early terminated or errored. The result is internally negated when interacting with Skopt so that Skopt Optimizers can "maximize" this value, as it minimizes on default.
[ "Passes", "the", "result", "to", "skopt", "unless", "early", "terminated", "or", "errored", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/suggest/skopt.py#L121-L134
24,498
ray-project/ray
python/ray/services.py
address_to_ip
def address_to_ip(address): """Convert a hostname to a numerical IP addresses in an address. This should be a no-op if address already contains an actual numerical IP address. Args: address: This can be either a string containing a hostname (or an IP address) and a port or it can b...
python
def address_to_ip(address): """Convert a hostname to a numerical IP addresses in an address. This should be a no-op if address already contains an actual numerical IP address. Args: address: This can be either a string containing a hostname (or an IP address) and a port or it can b...
[ "def", "address_to_ip", "(", "address", ")", ":", "address_parts", "=", "address", ".", "split", "(", "\":\"", ")", "ip_address", "=", "socket", ".", "gethostbyname", "(", "address_parts", "[", "0", "]", ")", "# Make sure localhost isn't resolved to the loopback ip"...
Convert a hostname to a numerical IP addresses in an address. This should be a no-op if address already contains an actual numerical IP address. Args: address: This can be either a string containing a hostname (or an IP address) and a port or it can be just an IP address. Returns:...
[ "Convert", "a", "hostname", "to", "a", "numerical", "IP", "addresses", "in", "an", "address", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L174-L193
24,499
ray-project/ray
python/ray/services.py
get_node_ip_address
def get_node_ip_address(address="8.8.8.8:53"): """Determine the IP address of the local node. Args: address (str): The IP address and port of any known live service on the network you care about. Returns: The IP address of the current node. """ ip_address, port = addres...
python
def get_node_ip_address(address="8.8.8.8:53"): """Determine the IP address of the local node. Args: address (str): The IP address and port of any known live service on the network you care about. Returns: The IP address of the current node. """ ip_address, port = addres...
[ "def", "get_node_ip_address", "(", "address", "=", "\"8.8.8.8:53\"", ")", ":", "ip_address", ",", "port", "=", "address", ".", "split", "(", "\":\"", ")", "s", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_DGRAM", ...
Determine the IP address of the local node. Args: address (str): The IP address and port of any known live service on the network you care about. Returns: The IP address of the current node.
[ "Determine", "the", "IP", "address", "of", "the", "local", "node", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L196-L226