repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
ray-project/ray | python/ray/tune/schedulers/pbt.py | PopulationBasedTraining._log_config_on_step | def _log_config_on_step(self, trial_state, new_state, trial,
trial_to_clone, new_config):
"""Logs transition during exploit/exploit step.
For each step, logs: [target trial tag, clone trial tag, target trial
iteration, clone trial iteration, old config, new config].
... | python | def _log_config_on_step(self, trial_state, new_state, trial,
trial_to_clone, new_config):
"""Logs transition during exploit/exploit step.
For each step, logs: [target trial tag, clone trial tag, target trial
iteration, clone trial iteration, old config, new config].
... | [
"def",
"_log_config_on_step",
"(",
"self",
",",
"trial_state",
",",
"new_state",
",",
"trial",
",",
"trial_to_clone",
",",
"new_config",
")",
":",
"trial_name",
",",
"trial_to_clone_name",
"=",
"(",
"trial_state",
".",
"orig_tag",
",",
"new_state",
".",
"orig_ta... | Logs transition during exploit/exploit step.
For each step, logs: [target trial tag, clone trial tag, target trial
iteration, clone trial iteration, old config, new config]. | [
"Logs",
"transition",
"during",
"exploit",
"/",
"exploit",
"step",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/schedulers/pbt.py#L225-L256 | train |
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 | train |
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 | train |
ray-project/ray | python/ray/tune/schedulers/pbt.py | PopulationBasedTraining.choose_trial_to_run | def choose_trial_to_run(self, trial_runner):
"""Ensures all trials get fair share of time (as defined by time_attr).
This enables the PBT scheduler to support a greater number of
concurrent trials than can fit in the cluster at any given time.
"""
candidates = []
for tr... | python | def choose_trial_to_run(self, trial_runner):
"""Ensures all trials get fair share of time (as defined by time_attr).
This enables the PBT scheduler to support a greater number of
concurrent trials than can fit in the cluster at any given time.
"""
candidates = []
for tr... | [
"def",
"choose_trial_to_run",
"(",
"self",
",",
"trial_runner",
")",
":",
"candidates",
"=",
"[",
"]",
"for",
"trial",
"in",
"trial_runner",
".",
"get_trials",
"(",
")",
":",
"if",
"trial",
".",
"status",
"in",
"[",
"Trial",
".",
"PENDING",
",",
"Trial",... | Ensures all trials get fair share of time (as defined by time_attr).
This enables the PBT scheduler to support a greater number of
concurrent trials than can fit in the cluster at any given time. | [
"Ensures",
"all",
"trials",
"get",
"fair",
"share",
"of",
"time",
"(",
"as",
"defined",
"by",
"time_attr",
")",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/schedulers/pbt.py#L316-L330 | train |
ray-project/ray | python/ray/autoscaler/aws/config.py | key_pair | def key_pair(i, region):
"""Returns the ith default (aws_key_pair_name, key_pair_path)."""
if i == 0:
return ("{}_{}".format(RAY, region),
os.path.expanduser("~/.ssh/{}_{}.pem".format(RAY, region)))
return ("{}_{}_{}".format(RAY, i, region),
os.path.expanduser("~/.ssh/{}_... | python | def key_pair(i, region):
"""Returns the ith default (aws_key_pair_name, key_pair_path)."""
if i == 0:
return ("{}_{}".format(RAY, region),
os.path.expanduser("~/.ssh/{}_{}.pem".format(RAY, region)))
return ("{}_{}_{}".format(RAY, i, region),
os.path.expanduser("~/.ssh/{}_... | [
"def",
"key_pair",
"(",
"i",
",",
"region",
")",
":",
"if",
"i",
"==",
"0",
":",
"return",
"(",
"\"{}_{}\"",
".",
"format",
"(",
"RAY",
",",
"region",
")",
",",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~/.ssh/{}_{}.pem\"",
".",
"format",
"(",
... | Returns the ith default (aws_key_pair_name, key_pair_path). | [
"Returns",
"the",
"ith",
"default",
"(",
"aws_key_pair_name",
"key_pair_path",
")",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/autoscaler/aws/config.py#L28-L34 | train |
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 | train |
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 | train |
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 | train |
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 | train |
ray-project/ray | python/ray/reporter.py | Reporter.perform_iteration | def perform_iteration(self):
"""Get any changes to the log files and push updates to Redis."""
stats = self.get_all_stats()
self.redis_client.publish(
self.redis_key,
jsonify_asdict(stats),
) | python | def perform_iteration(self):
"""Get any changes to the log files and push updates to Redis."""
stats = self.get_all_stats()
self.redis_client.publish(
self.redis_key,
jsonify_asdict(stats),
) | [
"def",
"perform_iteration",
"(",
"self",
")",
":",
"stats",
"=",
"self",
".",
"get_all_stats",
"(",
")",
"self",
".",
"redis_client",
".",
"publish",
"(",
"self",
".",
"redis_key",
",",
"jsonify_asdict",
"(",
"stats",
")",
",",
")"
] | Get any changes to the log files and push updates to Redis. | [
"Get",
"any",
"changes",
"to",
"the",
"log",
"files",
"and",
"push",
"updates",
"to",
"Redis",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/reporter.py#L163-L170 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
ray-project/ray | python/ray/rllib/evaluation/metrics.py | summarize_episodes | def summarize_episodes(episodes, new_episodes, num_dropped):
"""Summarizes a set of episode metrics tuples.
Arguments:
episodes: smoothed set of episodes including historical ones
new_episodes: just the new episodes in this iteration
num_dropped: number of workers haven't returned their... | python | def summarize_episodes(episodes, new_episodes, num_dropped):
"""Summarizes a set of episode metrics tuples.
Arguments:
episodes: smoothed set of episodes including historical ones
new_episodes: just the new episodes in this iteration
num_dropped: number of workers haven't returned their... | [
"def",
"summarize_episodes",
"(",
"episodes",
",",
"new_episodes",
",",
"num_dropped",
")",
":",
"if",
"num_dropped",
">",
"0",
":",
"logger",
".",
"warning",
"(",
"\"WARNING: {} workers have NOT returned metrics\"",
".",
"format",
"(",
"num_dropped",
")",
")",
"e... | Summarizes a set of episode metrics tuples.
Arguments:
episodes: smoothed set of episodes including historical ones
new_episodes: just the new episodes in this iteration
num_dropped: number of workers haven't returned their metrics | [
"Summarizes",
"a",
"set",
"of",
"episode",
"metrics",
"tuples",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/evaluation/metrics.py#L83-L160 | train |
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 | train |
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 | train |
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 | train |
ray-project/ray | python/ray/tune/trial_executor.py | TrialExecutor.pause_trial | def pause_trial(self, trial):
"""Pauses the trial.
We want to release resources (specifically GPUs) when pausing an
experiment. This results in PAUSED state that similar to TERMINATED.
"""
assert trial.status == Trial.RUNNING, trial.status
try:
self.save(tria... | python | def pause_trial(self, trial):
"""Pauses the trial.
We want to release resources (specifically GPUs) when pausing an
experiment. This results in PAUSED state that similar to TERMINATED.
"""
assert trial.status == Trial.RUNNING, trial.status
try:
self.save(tria... | [
"def",
"pause_trial",
"(",
"self",
",",
"trial",
")",
":",
"assert",
"trial",
".",
"status",
"==",
"Trial",
".",
"RUNNING",
",",
"trial",
".",
"status",
"try",
":",
"self",
".",
"save",
"(",
"trial",
",",
"Checkpoint",
".",
"MEMORY",
")",
"self",
"."... | Pauses the trial.
We want to release resources (specifically GPUs) when pausing an
experiment. This results in PAUSED state that similar to TERMINATED. | [
"Pauses",
"the",
"trial",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_executor.py#L99-L112 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
ray-project/ray | python/ray/services.py | create_redis_client | def create_redis_client(redis_address, password=None):
"""Create a Redis client.
Args:
The IP address, port, and password of the Redis server.
Returns:
A Redis client.
"""
redis_ip_address, redis_port = redis_address.split(":")
# For this command to work, some other client (on ... | python | def create_redis_client(redis_address, password=None):
"""Create a Redis client.
Args:
The IP address, port, and password of the Redis server.
Returns:
A Redis client.
"""
redis_ip_address, redis_port = redis_address.split(":")
# For this command to work, some other client (on ... | [
"def",
"create_redis_client",
"(",
"redis_address",
",",
"password",
"=",
"None",
")",
":",
"redis_ip_address",
",",
"redis_port",
"=",
"redis_address",
".",
"split",
"(",
"\":\"",
")",
"# For this command to work, some other client (on the same machine",
"# as Redis) must ... | Create a Redis client.
Args:
The IP address, port, and password of the Redis server.
Returns:
A Redis client. | [
"Create",
"a",
"Redis",
"client",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L229-L242 | train |
ray-project/ray | python/ray/services.py | start_ray_process | def start_ray_process(command,
process_type,
env_updates=None,
cwd=None,
use_valgrind=False,
use_gdb=False,
use_valgrind_profiler=False,
use_perftools_profiler=False,... | python | def start_ray_process(command,
process_type,
env_updates=None,
cwd=None,
use_valgrind=False,
use_gdb=False,
use_valgrind_profiler=False,
use_perftools_profiler=False,... | [
"def",
"start_ray_process",
"(",
"command",
",",
"process_type",
",",
"env_updates",
"=",
"None",
",",
"cwd",
"=",
"None",
",",
"use_valgrind",
"=",
"False",
",",
"use_gdb",
"=",
"False",
",",
"use_valgrind_profiler",
"=",
"False",
",",
"use_perftools_profiler",... | Start one of the Ray processes.
TODO(rkn): We need to figure out how these commands interact. For example,
it may only make sense to start a process in gdb if we also start it in
tmux. Similarly, certain combinations probably don't make sense, like
simultaneously running the process in valgrind and the... | [
"Start",
"one",
"of",
"the",
"Ray",
"processes",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L245-L378 | train |
ray-project/ray | python/ray/services.py | wait_for_redis_to_start | def wait_for_redis_to_start(redis_ip_address,
redis_port,
password=None,
num_retries=5):
"""Wait for a Redis server to be available.
This is accomplished by creating a Redis client and sending a random
command to the server... | python | def wait_for_redis_to_start(redis_ip_address,
redis_port,
password=None,
num_retries=5):
"""Wait for a Redis server to be available.
This is accomplished by creating a Redis client and sending a random
command to the server... | [
"def",
"wait_for_redis_to_start",
"(",
"redis_ip_address",
",",
"redis_port",
",",
"password",
"=",
"None",
",",
"num_retries",
"=",
"5",
")",
":",
"redis_client",
"=",
"redis",
".",
"StrictRedis",
"(",
"host",
"=",
"redis_ip_address",
",",
"port",
"=",
"redis... | Wait for a Redis server to be available.
This is accomplished by creating a Redis client and sending a random
command to the server until the command gets through.
Args:
redis_ip_address (str): The IP address of the redis server.
redis_port (int): The port of the redis server.
pass... | [
"Wait",
"for",
"a",
"Redis",
"server",
"to",
"be",
"available",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L381-L421 | train |
ray-project/ray | python/ray/services.py | _autodetect_num_gpus | def _autodetect_num_gpus():
"""Attempt to detect the number of GPUs on this machine.
TODO(rkn): This currently assumes Nvidia GPUs and Linux.
Returns:
The number of GPUs if any were detected, otherwise 0.
"""
proc_gpus_path = "/proc/driver/nvidia/gpus"
if os.path.isdir(proc_gpus_path):... | python | def _autodetect_num_gpus():
"""Attempt to detect the number of GPUs on this machine.
TODO(rkn): This currently assumes Nvidia GPUs and Linux.
Returns:
The number of GPUs if any were detected, otherwise 0.
"""
proc_gpus_path = "/proc/driver/nvidia/gpus"
if os.path.isdir(proc_gpus_path):... | [
"def",
"_autodetect_num_gpus",
"(",
")",
":",
"proc_gpus_path",
"=",
"\"/proc/driver/nvidia/gpus\"",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"proc_gpus_path",
")",
":",
"return",
"len",
"(",
"os",
".",
"listdir",
"(",
"proc_gpus_path",
")",
")",
"return",
... | Attempt to detect the number of GPUs on this machine.
TODO(rkn): This currently assumes Nvidia GPUs and Linux.
Returns:
The number of GPUs if any were detected, otherwise 0. | [
"Attempt",
"to",
"detect",
"the",
"number",
"of",
"GPUs",
"on",
"this",
"machine",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L424-L435 | train |
ray-project/ray | python/ray/services.py | _compute_version_info | def _compute_version_info():
"""Compute the versions of Python, pyarrow, and Ray.
Returns:
A tuple containing the version information.
"""
ray_version = ray.__version__
python_version = ".".join(map(str, sys.version_info[:3]))
pyarrow_version = pyarrow.__version__
return ray_version... | python | def _compute_version_info():
"""Compute the versions of Python, pyarrow, and Ray.
Returns:
A tuple containing the version information.
"""
ray_version = ray.__version__
python_version = ".".join(map(str, sys.version_info[:3]))
pyarrow_version = pyarrow.__version__
return ray_version... | [
"def",
"_compute_version_info",
"(",
")",
":",
"ray_version",
"=",
"ray",
".",
"__version__",
"python_version",
"=",
"\".\"",
".",
"join",
"(",
"map",
"(",
"str",
",",
"sys",
".",
"version_info",
"[",
":",
"3",
"]",
")",
")",
"pyarrow_version",
"=",
"pya... | Compute the versions of Python, pyarrow, and Ray.
Returns:
A tuple containing the version information. | [
"Compute",
"the",
"versions",
"of",
"Python",
"pyarrow",
"and",
"Ray",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L438-L447 | train |
ray-project/ray | python/ray/services.py | check_version_info | def check_version_info(redis_client):
"""Check if various version info of this process is correct.
This will be used to detect if workers or drivers are started using
different versions of Python, pyarrow, or Ray. If the version
information is not present in Redis, then no check is done.
Args:
... | python | def check_version_info(redis_client):
"""Check if various version info of this process is correct.
This will be used to detect if workers or drivers are started using
different versions of Python, pyarrow, or Ray. If the version
information is not present in Redis, then no check is done.
Args:
... | [
"def",
"check_version_info",
"(",
"redis_client",
")",
":",
"redis_reply",
"=",
"redis_client",
".",
"get",
"(",
"\"VERSION_INFO\"",
")",
"# Don't do the check if there is no version information in Redis. This",
"# is to make it easier to do things like start the processes by hand.",
... | Check if various version info of this process is correct.
This will be used to detect if workers or drivers are started using
different versions of Python, pyarrow, or Ray. If the version
information is not present in Redis, then no check is done.
Args:
redis_client: A client for the primary R... | [
"Check",
"if",
"various",
"version",
"info",
"of",
"this",
"process",
"is",
"correct",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L462-L498 | train |
ray-project/ray | python/ray/services.py | start_redis | def start_redis(node_ip_address,
redirect_files,
port=None,
redis_shard_ports=None,
num_redis_shards=1,
redis_max_clients=None,
redirect_worker_output=False,
password=None,
use_credis=None,
... | python | def start_redis(node_ip_address,
redirect_files,
port=None,
redis_shard_ports=None,
num_redis_shards=1,
redis_max_clients=None,
redirect_worker_output=False,
password=None,
use_credis=None,
... | [
"def",
"start_redis",
"(",
"node_ip_address",
",",
"redirect_files",
",",
"port",
"=",
"None",
",",
"redis_shard_ports",
"=",
"None",
",",
"num_redis_shards",
"=",
"1",
",",
"redis_max_clients",
"=",
"None",
",",
"redirect_worker_output",
"=",
"False",
",",
"pas... | Start the Redis global state store.
Args:
node_ip_address: The IP address of the current node. This is only used
for recording the log filenames in Redis.
redirect_files: The list of (stdout, stderr) file pairs.
port (int): If provided, the primary Redis shard will be started on... | [
"Start",
"the",
"Redis",
"global",
"state",
"store",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L501-L700 | train |
ray-project/ray | python/ray/services.py | _start_redis_instance | def _start_redis_instance(executable,
modules,
port=None,
redis_max_clients=None,
num_retries=20,
stdout_file=None,
stderr_file=None,
pass... | python | def _start_redis_instance(executable,
modules,
port=None,
redis_max_clients=None,
num_retries=20,
stdout_file=None,
stderr_file=None,
pass... | [
"def",
"_start_redis_instance",
"(",
"executable",
",",
"modules",
",",
"port",
"=",
"None",
",",
"redis_max_clients",
"=",
"None",
",",
"num_retries",
"=",
"20",
",",
"stdout_file",
"=",
"None",
",",
"stderr_file",
"=",
"None",
",",
"password",
"=",
"None",... | Start a single Redis server.
Notes:
If "port" is not None, then we will only use this port and try
only once. Otherwise, random ports will be used and the maximum
retries count is "num_retries".
Args:
executable (str): Full path of the redis-server executable.
modules (... | [
"Start",
"a",
"single",
"Redis",
"server",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L703-L841 | train |
ray-project/ray | python/ray/services.py | start_log_monitor | def start_log_monitor(redis_address,
logs_dir,
stdout_file=None,
stderr_file=None,
redis_password=None):
"""Start a log monitor process.
Args:
redis_address (str): The address of the Redis instance.
logs_dir... | python | def start_log_monitor(redis_address,
logs_dir,
stdout_file=None,
stderr_file=None,
redis_password=None):
"""Start a log monitor process.
Args:
redis_address (str): The address of the Redis instance.
logs_dir... | [
"def",
"start_log_monitor",
"(",
"redis_address",
",",
"logs_dir",
",",
"stdout_file",
"=",
"None",
",",
"stderr_file",
"=",
"None",
",",
"redis_password",
"=",
"None",
")",
":",
"log_monitor_filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
... | Start a log monitor process.
Args:
redis_address (str): The address of the Redis instance.
logs_dir (str): The directory of logging files.
stdout_file: A file handle opened for writing to redirect stdout to. If
no redirection should happen, then this should be None.
stde... | [
"Start",
"a",
"log",
"monitor",
"process",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L844-L877 | train |
ray-project/ray | python/ray/services.py | start_reporter | def start_reporter(redis_address,
stdout_file=None,
stderr_file=None,
redis_password=None):
"""Start a reporter process.
Args:
redis_address (str): The address of the Redis instance.
stdout_file: A file handle opened for writing to redire... | python | def start_reporter(redis_address,
stdout_file=None,
stderr_file=None,
redis_password=None):
"""Start a reporter process.
Args:
redis_address (str): The address of the Redis instance.
stdout_file: A file handle opened for writing to redire... | [
"def",
"start_reporter",
"(",
"redis_address",
",",
"stdout_file",
"=",
"None",
",",
"stderr_file",
"=",
"None",
",",
"redis_password",
"=",
"None",
")",
":",
"reporter_filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",... | Start a reporter process.
Args:
redis_address (str): The address of the Redis instance.
stdout_file: A file handle opened for writing to redirect stdout to. If
no redirection should happen, then this should be None.
stderr_file: A file handle opened for writing to redirect stder... | [
"Start",
"a",
"reporter",
"process",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L880-L918 | train |
ray-project/ray | python/ray/services.py | start_dashboard | def start_dashboard(redis_address,
temp_dir,
stdout_file=None,
stderr_file=None,
redis_password=None):
"""Start a dashboard process.
Args:
redis_address (str): The address of the Redis instance.
temp_dir (str): The ... | python | def start_dashboard(redis_address,
temp_dir,
stdout_file=None,
stderr_file=None,
redis_password=None):
"""Start a dashboard process.
Args:
redis_address (str): The address of the Redis instance.
temp_dir (str): The ... | [
"def",
"start_dashboard",
"(",
"redis_address",
",",
"temp_dir",
",",
"stdout_file",
"=",
"None",
",",
"stderr_file",
"=",
"None",
",",
"redis_password",
"=",
"None",
")",
":",
"port",
"=",
"8080",
"while",
"True",
":",
"try",
":",
"port_test_socket",
"=",
... | Start a dashboard process.
Args:
redis_address (str): The address of the Redis instance.
temp_dir (str): The temporary directory used for log files and
information for this Ray session.
stdout_file: A file handle opened for writing to redirect stdout to. If
no redire... | [
"Start",
"a",
"dashboard",
"process",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L921-L987 | train |
ray-project/ray | python/ray/services.py | check_and_update_resources | def check_and_update_resources(num_cpus, num_gpus, resources):
"""Sanity check a resource dictionary and add sensible defaults.
Args:
num_cpus: The number of CPUs.
num_gpus: The number of GPUs.
resources: A dictionary mapping resource names to resource quantities.
Returns:
... | python | def check_and_update_resources(num_cpus, num_gpus, resources):
"""Sanity check a resource dictionary and add sensible defaults.
Args:
num_cpus: The number of CPUs.
num_gpus: The number of GPUs.
resources: A dictionary mapping resource names to resource quantities.
Returns:
... | [
"def",
"check_and_update_resources",
"(",
"num_cpus",
",",
"num_gpus",
",",
"resources",
")",
":",
"if",
"resources",
"is",
"None",
":",
"resources",
"=",
"{",
"}",
"resources",
"=",
"resources",
".",
"copy",
"(",
")",
"assert",
"\"CPU\"",
"not",
"in",
"re... | Sanity check a resource dictionary and add sensible defaults.
Args:
num_cpus: The number of CPUs.
num_gpus: The number of GPUs.
resources: A dictionary mapping resource names to resource quantities.
Returns:
A new resource dictionary. | [
"Sanity",
"check",
"a",
"resource",
"dictionary",
"and",
"add",
"sensible",
"defaults",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L990-L1057 | train |
ray-project/ray | python/ray/services.py | start_raylet | def start_raylet(redis_address,
node_ip_address,
raylet_name,
plasma_store_name,
worker_path,
temp_dir,
num_cpus=None,
num_gpus=None,
resources=None,
object_manager_po... | python | def start_raylet(redis_address,
node_ip_address,
raylet_name,
plasma_store_name,
worker_path,
temp_dir,
num_cpus=None,
num_gpus=None,
resources=None,
object_manager_po... | [
"def",
"start_raylet",
"(",
"redis_address",
",",
"node_ip_address",
",",
"raylet_name",
",",
"plasma_store_name",
",",
"worker_path",
",",
"temp_dir",
",",
"num_cpus",
"=",
"None",
",",
"num_gpus",
"=",
"None",
",",
"resources",
"=",
"None",
",",
"object_manage... | Start a raylet, which is a combined local scheduler and object manager.
Args:
redis_address (str): The address of the primary Redis server.
node_ip_address (str): The IP address of this node.
raylet_name (str): The name of the raylet socket to create.
plasma_store_name (str): The na... | [
"Start",
"a",
"raylet",
"which",
"is",
"a",
"combined",
"local",
"scheduler",
"and",
"object",
"manager",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L1060-L1206 | train |
ray-project/ray | python/ray/services.py | build_java_worker_command | def build_java_worker_command(
java_worker_options,
redis_address,
plasma_store_name,
raylet_name,
redis_password,
temp_dir,
):
"""This method assembles the command used to start a Java worker.
Args:
java_worker_options (str): The command options for Java... | python | def build_java_worker_command(
java_worker_options,
redis_address,
plasma_store_name,
raylet_name,
redis_password,
temp_dir,
):
"""This method assembles the command used to start a Java worker.
Args:
java_worker_options (str): The command options for Java... | [
"def",
"build_java_worker_command",
"(",
"java_worker_options",
",",
"redis_address",
",",
"plasma_store_name",
",",
"raylet_name",
",",
"redis_password",
",",
"temp_dir",
",",
")",
":",
"assert",
"java_worker_options",
"is",
"not",
"None",
"command",
"=",
"\"java \""... | This method assembles the command used to start a Java worker.
Args:
java_worker_options (str): The command options for Java worker.
redis_address (str): Redis address of GCS.
plasma_store_name (str): The name of the plasma store socket to connect
to.
raylet_name (str): T... | [
"This",
"method",
"assembles",
"the",
"command",
"used",
"to",
"start",
"a",
"Java",
"worker",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L1209-L1256 | train |
ray-project/ray | python/ray/services.py | determine_plasma_store_config | def determine_plasma_store_config(object_store_memory=None,
plasma_directory=None,
huge_pages=False):
"""Figure out how to configure the plasma object store.
This will determine which directory to use for the plasma store (e.g.,
/tmp or /d... | python | def determine_plasma_store_config(object_store_memory=None,
plasma_directory=None,
huge_pages=False):
"""Figure out how to configure the plasma object store.
This will determine which directory to use for the plasma store (e.g.,
/tmp or /d... | [
"def",
"determine_plasma_store_config",
"(",
"object_store_memory",
"=",
"None",
",",
"plasma_directory",
"=",
"None",
",",
"huge_pages",
"=",
"False",
")",
":",
"system_memory",
"=",
"ray",
".",
"utils",
".",
"get_system_memory",
"(",
")",
"# Choose a default objec... | Figure out how to configure the plasma object store.
This will determine which directory to use for the plasma store (e.g.,
/tmp or /dev/shm) and how much memory to start the store with. On Linux,
we will try to use /dev/shm unless the shared memory file system is too
small, in which case we will fall ... | [
"Figure",
"out",
"how",
"to",
"configure",
"the",
"plasma",
"object",
"store",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L1259-L1337 | train |
ray-project/ray | python/ray/services.py | _start_plasma_store | def _start_plasma_store(plasma_store_memory,
use_valgrind=False,
use_profiler=False,
stdout_file=None,
stderr_file=None,
plasma_directory=None,
huge_pages=False,
... | python | def _start_plasma_store(plasma_store_memory,
use_valgrind=False,
use_profiler=False,
stdout_file=None,
stderr_file=None,
plasma_directory=None,
huge_pages=False,
... | [
"def",
"_start_plasma_store",
"(",
"plasma_store_memory",
",",
"use_valgrind",
"=",
"False",
",",
"use_profiler",
"=",
"False",
",",
"stdout_file",
"=",
"None",
",",
"stderr_file",
"=",
"None",
",",
"plasma_directory",
"=",
"None",
",",
"huge_pages",
"=",
"False... | Start a plasma store process.
Args:
plasma_store_memory (int): The amount of memory in bytes to start the
plasma store with.
use_valgrind (bool): True if the plasma store should be started inside
of valgrind. If this is True, use_profiler must be False.
use_profiler ... | [
"Start",
"a",
"plasma",
"store",
"process",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L1340-L1402 | train |
ray-project/ray | python/ray/services.py | start_plasma_store | def start_plasma_store(stdout_file=None,
stderr_file=None,
object_store_memory=None,
plasma_directory=None,
huge_pages=False,
plasma_store_socket_name=None):
"""This method starts an object store proce... | python | def start_plasma_store(stdout_file=None,
stderr_file=None,
object_store_memory=None,
plasma_directory=None,
huge_pages=False,
plasma_store_socket_name=None):
"""This method starts an object store proce... | [
"def",
"start_plasma_store",
"(",
"stdout_file",
"=",
"None",
",",
"stderr_file",
"=",
"None",
",",
"object_store_memory",
"=",
"None",
",",
"plasma_directory",
"=",
"None",
",",
"huge_pages",
"=",
"False",
",",
"plasma_store_socket_name",
"=",
"None",
")",
":",... | This method starts an object store process.
Args:
stdout_file: A file handle opened for writing to redirect stdout
to. If no redirection should happen, then this should be None.
stderr_file: A file handle opened for writing to redirect stderr
to. If no redirection should hap... | [
"This",
"method",
"starts",
"an",
"object",
"store",
"process",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L1405-L1452 | train |
ray-project/ray | python/ray/services.py | start_worker | def start_worker(node_ip_address,
object_store_name,
raylet_name,
redis_address,
worker_path,
temp_dir,
stdout_file=None,
stderr_file=None):
"""This method starts a worker process.
Args:
... | python | def start_worker(node_ip_address,
object_store_name,
raylet_name,
redis_address,
worker_path,
temp_dir,
stdout_file=None,
stderr_file=None):
"""This method starts a worker process.
Args:
... | [
"def",
"start_worker",
"(",
"node_ip_address",
",",
"object_store_name",
",",
"raylet_name",
",",
"redis_address",
",",
"worker_path",
",",
"temp_dir",
",",
"stdout_file",
"=",
"None",
",",
"stderr_file",
"=",
"None",
")",
":",
"command",
"=",
"[",
"sys",
".",... | This method starts a worker process.
Args:
node_ip_address (str): The IP address of the node that this worker is
running on.
object_store_name (str): The socket name of the object store.
raylet_name (str): The socket name of the raylet server.
redis_address (str): The ad... | [
"This",
"method",
"starts",
"a",
"worker",
"process",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L1455-L1494 | train |
ray-project/ray | python/ray/services.py | start_monitor | def start_monitor(redis_address,
stdout_file=None,
stderr_file=None,
autoscaling_config=None,
redis_password=None):
"""Run a process to monitor the other processes.
Args:
redis_address (str): The address that the Redis server is li... | python | def start_monitor(redis_address,
stdout_file=None,
stderr_file=None,
autoscaling_config=None,
redis_password=None):
"""Run a process to monitor the other processes.
Args:
redis_address (str): The address that the Redis server is li... | [
"def",
"start_monitor",
"(",
"redis_address",
",",
"stdout_file",
"=",
"None",
",",
"stderr_file",
"=",
"None",
",",
"autoscaling_config",
"=",
"None",
",",
"redis_password",
"=",
"None",
")",
":",
"monitor_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
... | Run a process to monitor the other processes.
Args:
redis_address (str): The address that the Redis server is listening on.
stdout_file: A file handle opened for writing to redirect stdout to. If
no redirection should happen, then this should be None.
stderr_file: A file handle ... | [
"Run",
"a",
"process",
"to",
"monitor",
"the",
"other",
"processes",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L1497-L1531 | train |
ray-project/ray | python/ray/services.py | start_raylet_monitor | def start_raylet_monitor(redis_address,
stdout_file=None,
stderr_file=None,
redis_password=None,
config=None):
"""Run a process to monitor the other processes.
Args:
redis_address (str): The address that... | python | def start_raylet_monitor(redis_address,
stdout_file=None,
stderr_file=None,
redis_password=None,
config=None):
"""Run a process to monitor the other processes.
Args:
redis_address (str): The address that... | [
"def",
"start_raylet_monitor",
"(",
"redis_address",
",",
"stdout_file",
"=",
"None",
",",
"stderr_file",
"=",
"None",
",",
"redis_password",
"=",
"None",
",",
"config",
"=",
"None",
")",
":",
"gcs_ip_address",
",",
"gcs_port",
"=",
"redis_address",
".",
"spli... | Run a process to monitor the other processes.
Args:
redis_address (str): The address that the Redis server is listening on.
stdout_file: A file handle opened for writing to redirect stdout to. If
no redirection should happen, then this should be None.
stderr_file: A file handle ... | [
"Run",
"a",
"process",
"to",
"monitor",
"the",
"other",
"processes",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L1534-L1571 | train |
ray-project/ray | python/ray/rllib/models/model.py | restore_original_dimensions | def restore_original_dimensions(obs, obs_space, tensorlib=tf):
"""Unpacks Dict and Tuple space observations into their original form.
This is needed since we flatten Dict and Tuple observations in transit.
Before sending them to the model though, we should unflatten them into
Dicts or Tuples of tensors... | python | def restore_original_dimensions(obs, obs_space, tensorlib=tf):
"""Unpacks Dict and Tuple space observations into their original form.
This is needed since we flatten Dict and Tuple observations in transit.
Before sending them to the model though, we should unflatten them into
Dicts or Tuples of tensors... | [
"def",
"restore_original_dimensions",
"(",
"obs",
",",
"obs_space",
",",
"tensorlib",
"=",
"tf",
")",
":",
"if",
"hasattr",
"(",
"obs_space",
",",
"\"original_space\"",
")",
":",
"return",
"_unpack_obs",
"(",
"obs",
",",
"obs_space",
".",
"original_space",
","... | Unpacks Dict and Tuple space observations into their original form.
This is needed since we flatten Dict and Tuple observations in transit.
Before sending them to the model though, we should unflatten them into
Dicts or Tuples of tensors.
Arguments:
obs: The flattened observation tensor.
... | [
"Unpacks",
"Dict",
"and",
"Tuple",
"space",
"observations",
"into",
"their",
"original",
"form",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/models/model.py#L208-L229 | train |
ray-project/ray | python/ray/rllib/models/model.py | _unpack_obs | def _unpack_obs(obs, space, tensorlib=tf):
"""Unpack a flattened Dict or Tuple observation array/tensor.
Arguments:
obs: The flattened observation tensor
space: The original space prior to flattening
tensorlib: The library used to unflatten (reshape) the array/tensor
"""
if (is... | python | def _unpack_obs(obs, space, tensorlib=tf):
"""Unpack a flattened Dict or Tuple observation array/tensor.
Arguments:
obs: The flattened observation tensor
space: The original space prior to flattening
tensorlib: The library used to unflatten (reshape) the array/tensor
"""
if (is... | [
"def",
"_unpack_obs",
"(",
"obs",
",",
"space",
",",
"tensorlib",
"=",
"tf",
")",
":",
"if",
"(",
"isinstance",
"(",
"space",
",",
"gym",
".",
"spaces",
".",
"Dict",
")",
"or",
"isinstance",
"(",
"space",
",",
"gym",
".",
"spaces",
".",
"Tuple",
")... | Unpack a flattened Dict or Tuple observation array/tensor.
Arguments:
obs: The flattened observation tensor
space: The original space prior to flattening
tensorlib: The library used to unflatten (reshape) the array/tensor | [
"Unpack",
"a",
"flattened",
"Dict",
"or",
"Tuple",
"observation",
"array",
"/",
"tensor",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/models/model.py#L232-L272 | train |
ray-project/ray | python/ray/autoscaler/aws/node_provider.py | to_aws_format | def to_aws_format(tags):
"""Convert the Ray node name tag to the AWS-specific 'Name' tag."""
if TAG_RAY_NODE_NAME in tags:
tags["Name"] = tags[TAG_RAY_NODE_NAME]
del tags[TAG_RAY_NODE_NAME]
return tags | python | def to_aws_format(tags):
"""Convert the Ray node name tag to the AWS-specific 'Name' tag."""
if TAG_RAY_NODE_NAME in tags:
tags["Name"] = tags[TAG_RAY_NODE_NAME]
del tags[TAG_RAY_NODE_NAME]
return tags | [
"def",
"to_aws_format",
"(",
"tags",
")",
":",
"if",
"TAG_RAY_NODE_NAME",
"in",
"tags",
":",
"tags",
"[",
"\"Name\"",
"]",
"=",
"tags",
"[",
"TAG_RAY_NODE_NAME",
"]",
"del",
"tags",
"[",
"TAG_RAY_NODE_NAME",
"]",
"return",
"tags"
] | Convert the Ray node name tag to the AWS-specific 'Name' tag. | [
"Convert",
"the",
"Ray",
"node",
"name",
"tag",
"to",
"the",
"AWS",
"-",
"specific",
"Name",
"tag",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/autoscaler/aws/node_provider.py#L18-L24 | train |
ray-project/ray | python/ray/autoscaler/aws/node_provider.py | AWSNodeProvider._node_tag_update_loop | def _node_tag_update_loop(self):
""" Update the AWS tags for a cluster periodically.
The purpose of this loop is to avoid excessive EC2 calls when a large
number of nodes are being launched simultaneously.
"""
while True:
self.tag_cache_update_event.wait()
... | python | def _node_tag_update_loop(self):
""" Update the AWS tags for a cluster periodically.
The purpose of this loop is to avoid excessive EC2 calls when a large
number of nodes are being launched simultaneously.
"""
while True:
self.tag_cache_update_event.wait()
... | [
"def",
"_node_tag_update_loop",
"(",
"self",
")",
":",
"while",
"True",
":",
"self",
".",
"tag_cache_update_event",
".",
"wait",
"(",
")",
"self",
".",
"tag_cache_update_event",
".",
"clear",
"(",
")",
"batch_updates",
"=",
"defaultdict",
"(",
"list",
")",
"... | Update the AWS tags for a cluster periodically.
The purpose of this loop is to avoid excessive EC2 calls when a large
number of nodes are being launched simultaneously. | [
"Update",
"the",
"AWS",
"tags",
"for",
"a",
"cluster",
"periodically",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/autoscaler/aws/node_provider.py#L59-L94 | train |
ray-project/ray | python/ray/autoscaler/aws/node_provider.py | AWSNodeProvider._get_node | def _get_node(self, node_id):
"""Refresh and get info for this node, updating the cache."""
self.non_terminated_nodes({}) # Side effect: updates cache
if node_id in self.cached_nodes:
return self.cached_nodes[node_id]
# Node not in {pending, running} -- retry with a point ... | python | def _get_node(self, node_id):
"""Refresh and get info for this node, updating the cache."""
self.non_terminated_nodes({}) # Side effect: updates cache
if node_id in self.cached_nodes:
return self.cached_nodes[node_id]
# Node not in {pending, running} -- retry with a point ... | [
"def",
"_get_node",
"(",
"self",
",",
"node_id",
")",
":",
"self",
".",
"non_terminated_nodes",
"(",
"{",
"}",
")",
"# Side effect: updates cache",
"if",
"node_id",
"in",
"self",
".",
"cached_nodes",
":",
"return",
"self",
".",
"cached_nodes",
"[",
"node_id",
... | Refresh and get info for this node, updating the cache. | [
"Refresh",
"and",
"get",
"info",
"for",
"this",
"node",
"updating",
"the",
"cache",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/autoscaler/aws/node_provider.py#L231-L242 | train |
ray-project/ray | python/ray/tune/trial.py | ExportFormat.validate | def validate(export_formats):
"""Validates export_formats.
Raises:
ValueError if the format is unknown.
"""
for i in range(len(export_formats)):
export_formats[i] = export_formats[i].strip().lower()
if export_formats[i] not in [
Ex... | python | def validate(export_formats):
"""Validates export_formats.
Raises:
ValueError if the format is unknown.
"""
for i in range(len(export_formats)):
export_formats[i] = export_formats[i].strip().lower()
if export_formats[i] not in [
Ex... | [
"def",
"validate",
"(",
"export_formats",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"export_formats",
")",
")",
":",
"export_formats",
"[",
"i",
"]",
"=",
"export_formats",
"[",
"i",
"]",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
... | Validates export_formats.
Raises:
ValueError if the format is unknown. | [
"Validates",
"export_formats",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial.py#L215-L227 | train |
ray-project/ray | python/ray/tune/trial.py | Trial.init_logger | def init_logger(self):
"""Init logger."""
if not self.result_logger:
if not os.path.exists(self.local_dir):
os.makedirs(self.local_dir)
if not self.logdir:
self.logdir = tempfile.mkdtemp(
prefix="{}_{}".format(
... | python | def init_logger(self):
"""Init logger."""
if not self.result_logger:
if not os.path.exists(self.local_dir):
os.makedirs(self.local_dir)
if not self.logdir:
self.logdir = tempfile.mkdtemp(
prefix="{}_{}".format(
... | [
"def",
"init_logger",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"result_logger",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"local_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"self",
".",
"local_dir",
")",
"if",
"n... | Init logger. | [
"Init",
"logger",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial.py#L346-L365 | train |
ray-project/ray | python/ray/tune/trial.py | Trial.update_resources | def update_resources(self, cpu, gpu, **kwargs):
"""EXPERIMENTAL: Updates the resource requirements.
Should only be called when the trial is not running.
Raises:
ValueError if trial status is running.
"""
if self.status is Trial.RUNNING:
raise ValueError(... | python | def update_resources(self, cpu, gpu, **kwargs):
"""EXPERIMENTAL: Updates the resource requirements.
Should only be called when the trial is not running.
Raises:
ValueError if trial status is running.
"""
if self.status is Trial.RUNNING:
raise ValueError(... | [
"def",
"update_resources",
"(",
"self",
",",
"cpu",
",",
"gpu",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"status",
"is",
"Trial",
".",
"RUNNING",
":",
"raise",
"ValueError",
"(",
"\"Cannot update resources while Trial is running.\"",
")",
"self",
... | EXPERIMENTAL: Updates the resource requirements.
Should only be called when the trial is not running.
Raises:
ValueError if trial status is running. | [
"EXPERIMENTAL",
":",
"Updates",
"the",
"resource",
"requirements",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial.py#L367-L377 | train |
ray-project/ray | python/ray/tune/trial.py | Trial.should_stop | def should_stop(self, result):
"""Whether the given result meets this trial's stopping criteria."""
if result.get(DONE):
return True
for criteria, stop_value in self.stopping_criterion.items():
if criteria not in result:
raise TuneError(
... | python | def should_stop(self, result):
"""Whether the given result meets this trial's stopping criteria."""
if result.get(DONE):
return True
for criteria, stop_value in self.stopping_criterion.items():
if criteria not in result:
raise TuneError(
... | [
"def",
"should_stop",
"(",
"self",
",",
"result",
")",
":",
"if",
"result",
".",
"get",
"(",
"DONE",
")",
":",
"return",
"True",
"for",
"criteria",
",",
"stop_value",
"in",
"self",
".",
"stopping_criterion",
".",
"items",
"(",
")",
":",
"if",
"criteria... | Whether the given result meets this trial's stopping criteria. | [
"Whether",
"the",
"given",
"result",
"meets",
"this",
"trial",
"s",
"stopping",
"criteria",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial.py#L403-L417 | train |
ray-project/ray | python/ray/tune/trial.py | Trial.should_checkpoint | def should_checkpoint(self):
"""Whether this trial is due for checkpointing."""
result = self.last_result or {}
if result.get(DONE) and self.checkpoint_at_end:
return True
if self.checkpoint_freq:
return result.get(TRAINING_ITERATION,
... | python | def should_checkpoint(self):
"""Whether this trial is due for checkpointing."""
result = self.last_result or {}
if result.get(DONE) and self.checkpoint_at_end:
return True
if self.checkpoint_freq:
return result.get(TRAINING_ITERATION,
... | [
"def",
"should_checkpoint",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"last_result",
"or",
"{",
"}",
"if",
"result",
".",
"get",
"(",
"DONE",
")",
"and",
"self",
".",
"checkpoint_at_end",
":",
"return",
"True",
"if",
"self",
".",
"checkpoint_fre... | Whether this trial is due for checkpointing. | [
"Whether",
"this",
"trial",
"is",
"due",
"for",
"checkpointing",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial.py#L419-L430 | train |
ray-project/ray | python/ray/tune/trial.py | Trial.progress_string | def progress_string(self):
"""Returns a progress message for printing out to the console."""
if not self.last_result:
return self._status_string()
def location_string(hostname, pid):
if hostname == os.uname()[1]:
return "pid={}".format(pid)
e... | python | def progress_string(self):
"""Returns a progress message for printing out to the console."""
if not self.last_result:
return self._status_string()
def location_string(hostname, pid):
if hostname == os.uname()[1]:
return "pid={}".format(pid)
e... | [
"def",
"progress_string",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"last_result",
":",
"return",
"self",
".",
"_status_string",
"(",
")",
"def",
"location_string",
"(",
"hostname",
",",
"pid",
")",
":",
"if",
"hostname",
"==",
"os",
".",
"uname",... | Returns a progress message for printing out to the console. | [
"Returns",
"a",
"progress",
"message",
"for",
"printing",
"out",
"to",
"the",
"console",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial.py#L432-L472 | train |
ray-project/ray | python/ray/tune/trial.py | Trial.should_recover | def should_recover(self):
"""Returns whether the trial qualifies for restoring.
This is if a checkpoint frequency is set and has not failed more than
max_failures. This may return true even when there may not yet
be a checkpoint.
"""
return (self.checkpoint_freq > 0
... | python | def should_recover(self):
"""Returns whether the trial qualifies for restoring.
This is if a checkpoint frequency is set and has not failed more than
max_failures. This may return true even when there may not yet
be a checkpoint.
"""
return (self.checkpoint_freq > 0
... | [
"def",
"should_recover",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"checkpoint_freq",
">",
"0",
"and",
"(",
"self",
".",
"num_failures",
"<",
"self",
".",
"max_failures",
"or",
"self",
".",
"max_failures",
"<",
"0",
")",
")"
] | Returns whether the trial qualifies for restoring.
This is if a checkpoint frequency is set and has not failed more than
max_failures. This may return true even when there may not yet
be a checkpoint. | [
"Returns",
"whether",
"the",
"trial",
"qualifies",
"for",
"restoring",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial.py#L486-L495 | train |
ray-project/ray | python/ray/tune/trial.py | Trial.compare_checkpoints | def compare_checkpoints(self, attr_mean):
"""Compares two checkpoints based on the attribute attr_mean param.
Greater than is used by default. If command-line parameter
checkpoint_score_attr starts with "min-" less than is used.
Arguments:
attr_mean: mean of attribute value... | python | def compare_checkpoints(self, attr_mean):
"""Compares two checkpoints based on the attribute attr_mean param.
Greater than is used by default. If command-line parameter
checkpoint_score_attr starts with "min-" less than is used.
Arguments:
attr_mean: mean of attribute value... | [
"def",
"compare_checkpoints",
"(",
"self",
",",
"attr_mean",
")",
":",
"if",
"self",
".",
"_cmp_greater",
"and",
"attr_mean",
">",
"self",
".",
"best_checkpoint_attr_value",
":",
"return",
"True",
"elif",
"(",
"not",
"self",
".",
"_cmp_greater",
"and",
"attr_m... | Compares two checkpoints based on the attribute attr_mean param.
Greater than is used by default. If command-line parameter
checkpoint_score_attr starts with "min-" less than is used.
Arguments:
attr_mean: mean of attribute value for the current checkpoint
Returns:
... | [
"Compares",
"two",
"checkpoints",
"based",
"on",
"the",
"attribute",
"attr_mean",
"param",
".",
"Greater",
"than",
"is",
"used",
"by",
"default",
".",
"If",
"command",
"-",
"line",
"parameter",
"checkpoint_score_attr",
"starts",
"with",
"min",
"-",
"less",
"th... | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial.py#L509-L529 | train |
ray-project/ray | examples/rl_pong/driver.py | preprocess | def preprocess(img):
"""Preprocess 210x160x3 uint8 frame into 6400 (80x80) 1D float vector."""
# Crop the image.
img = img[35:195]
# Downsample by factor of 2.
img = img[::2, ::2, 0]
# Erase background (background type 1).
img[img == 144] = 0
# Erase background (background type 2).
i... | python | def preprocess(img):
"""Preprocess 210x160x3 uint8 frame into 6400 (80x80) 1D float vector."""
# Crop the image.
img = img[35:195]
# Downsample by factor of 2.
img = img[::2, ::2, 0]
# Erase background (background type 1).
img[img == 144] = 0
# Erase background (background type 2).
i... | [
"def",
"preprocess",
"(",
"img",
")",
":",
"# Crop the image.",
"img",
"=",
"img",
"[",
"35",
":",
"195",
"]",
"# Downsample by factor of 2.",
"img",
"=",
"img",
"[",
":",
":",
"2",
",",
":",
":",
"2",
",",
"0",
"]",
"# Erase background (background type 1)... | Preprocess 210x160x3 uint8 frame into 6400 (80x80) 1D float vector. | [
"Preprocess",
"210x160x3",
"uint8",
"frame",
"into",
"6400",
"(",
"80x80",
")",
"1D",
"float",
"vector",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/examples/rl_pong/driver.py#L35-L47 | train |
ray-project/ray | examples/rl_pong/driver.py | discount_rewards | def discount_rewards(r):
"""take 1D float array of rewards and compute discounted reward"""
discounted_r = np.zeros_like(r)
running_add = 0
for t in reversed(range(0, r.size)):
# Reset the sum, since this was a game boundary (pong specific!).
if r[t] != 0:
running_add = 0
... | python | def discount_rewards(r):
"""take 1D float array of rewards and compute discounted reward"""
discounted_r = np.zeros_like(r)
running_add = 0
for t in reversed(range(0, r.size)):
# Reset the sum, since this was a game boundary (pong specific!).
if r[t] != 0:
running_add = 0
... | [
"def",
"discount_rewards",
"(",
"r",
")",
":",
"discounted_r",
"=",
"np",
".",
"zeros_like",
"(",
"r",
")",
"running_add",
"=",
"0",
"for",
"t",
"in",
"reversed",
"(",
"range",
"(",
"0",
",",
"r",
".",
"size",
")",
")",
":",
"# Reset the sum, since thi... | take 1D float array of rewards and compute discounted reward | [
"take",
"1D",
"float",
"array",
"of",
"rewards",
"and",
"compute",
"discounted",
"reward"
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/examples/rl_pong/driver.py#L50-L60 | train |
ray-project/ray | examples/rl_pong/driver.py | policy_backward | def policy_backward(eph, epx, epdlogp, model):
"""backward pass. (eph is array of intermediate hidden states)"""
dW2 = np.dot(eph.T, epdlogp).ravel()
dh = np.outer(epdlogp, model["W2"])
# Backprop relu.
dh[eph <= 0] = 0
dW1 = np.dot(dh.T, epx)
return {"W1": dW1, "W2": dW2} | python | def policy_backward(eph, epx, epdlogp, model):
"""backward pass. (eph is array of intermediate hidden states)"""
dW2 = np.dot(eph.T, epdlogp).ravel()
dh = np.outer(epdlogp, model["W2"])
# Backprop relu.
dh[eph <= 0] = 0
dW1 = np.dot(dh.T, epx)
return {"W1": dW1, "W2": dW2} | [
"def",
"policy_backward",
"(",
"eph",
",",
"epx",
",",
"epdlogp",
",",
"model",
")",
":",
"dW2",
"=",
"np",
".",
"dot",
"(",
"eph",
".",
"T",
",",
"epdlogp",
")",
".",
"ravel",
"(",
")",
"dh",
"=",
"np",
".",
"outer",
"(",
"epdlogp",
",",
"mode... | backward pass. (eph is array of intermediate hidden states) | [
"backward",
"pass",
".",
"(",
"eph",
"is",
"array",
"of",
"intermediate",
"hidden",
"states",
")"
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/examples/rl_pong/driver.py#L72-L79 | train |
ray-project/ray | python/ray/autoscaler/node_provider.py | load_class | def load_class(path):
"""
Load a class at runtime given a full path.
Example of the path: mypkg.mysubpkg.myclass
"""
class_data = path.split(".")
if len(class_data) < 2:
raise ValueError(
"You need to pass a valid path like mymodule.provider_class")
module_path = ".".joi... | python | def load_class(path):
"""
Load a class at runtime given a full path.
Example of the path: mypkg.mysubpkg.myclass
"""
class_data = path.split(".")
if len(class_data) < 2:
raise ValueError(
"You need to pass a valid path like mymodule.provider_class")
module_path = ".".joi... | [
"def",
"load_class",
"(",
"path",
")",
":",
"class_data",
"=",
"path",
".",
"split",
"(",
"\".\"",
")",
"if",
"len",
"(",
"class_data",
")",
"<",
"2",
":",
"raise",
"ValueError",
"(",
"\"You need to pass a valid path like mymodule.provider_class\"",
")",
"module... | Load a class at runtime given a full path.
Example of the path: mypkg.mysubpkg.myclass | [
"Load",
"a",
"class",
"at",
"runtime",
"given",
"a",
"full",
"path",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/autoscaler/node_provider.py#L76-L89 | train |
ray-project/ray | python/ray/autoscaler/node_provider.py | NodeProvider.terminate_nodes | def terminate_nodes(self, node_ids):
"""Terminates a set of nodes. May be overridden with a batch method."""
for node_id in node_ids:
logger.info("NodeProvider: "
"{}: Terminating node".format(node_id))
self.terminate_node(node_id) | python | def terminate_nodes(self, node_ids):
"""Terminates a set of nodes. May be overridden with a batch method."""
for node_id in node_ids:
logger.info("NodeProvider: "
"{}: Terminating node".format(node_id))
self.terminate_node(node_id) | [
"def",
"terminate_nodes",
"(",
"self",
",",
"node_ids",
")",
":",
"for",
"node_id",
"in",
"node_ids",
":",
"logger",
".",
"info",
"(",
"\"NodeProvider: \"",
"\"{}: Terminating node\"",
".",
"format",
"(",
"node_id",
")",
")",
"self",
".",
"terminate_node",
"("... | Terminates a set of nodes. May be overridden with a batch method. | [
"Terminates",
"a",
"set",
"of",
"nodes",
".",
"May",
"be",
"overridden",
"with",
"a",
"batch",
"method",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/autoscaler/node_provider.py#L181-L186 | train |
ray-project/ray | python/ray/tune/suggest/bayesopt.py | BayesOptSearch.on_trial_complete | def on_trial_complete(self,
trial_id,
result=None,
error=False,
early_terminated=False):
"""Passes the result to BayesOpt unless early terminated or errored"""
if result:
self.optimizer.re... | python | def on_trial_complete(self,
trial_id,
result=None,
error=False,
early_terminated=False):
"""Passes the result to BayesOpt unless early terminated or errored"""
if result:
self.optimizer.re... | [
"def",
"on_trial_complete",
"(",
"self",
",",
"trial_id",
",",
"result",
"=",
"None",
",",
"error",
"=",
"False",
",",
"early_terminated",
"=",
"False",
")",
":",
"if",
"result",
":",
"self",
".",
"optimizer",
".",
"register",
"(",
"params",
"=",
"self",... | Passes the result to BayesOpt unless early terminated or errored | [
"Passes",
"the",
"result",
"to",
"BayesOpt",
"unless",
"early",
"terminated",
"or",
"errored"
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/suggest/bayesopt.py#L79-L90 | train |
ray-project/ray | python/ray/experimental/serve/mixin.py | _execute_and_seal_error | def _execute_and_seal_error(method, arg, method_name):
"""Execute method with arg and return the result.
If the method fails, return a RayTaskError so it can be sealed in the
resultOID and retried by user.
"""
try:
return method(arg)
except Exception:
return ray.worker.RayTaskEr... | python | def _execute_and_seal_error(method, arg, method_name):
"""Execute method with arg and return the result.
If the method fails, return a RayTaskError so it can be sealed in the
resultOID and retried by user.
"""
try:
return method(arg)
except Exception:
return ray.worker.RayTaskEr... | [
"def",
"_execute_and_seal_error",
"(",
"method",
",",
"arg",
",",
"method_name",
")",
":",
"try",
":",
"return",
"method",
"(",
"arg",
")",
"except",
"Exception",
":",
"return",
"ray",
".",
"worker",
".",
"RayTaskError",
"(",
"method_name",
",",
"traceback",... | Execute method with arg and return the result.
If the method fails, return a RayTaskError so it can be sealed in the
resultOID and retried by user. | [
"Execute",
"method",
"with",
"arg",
"and",
"return",
"the",
"result",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/serve/mixin.py#L21-L30 | train |
ray-project/ray | python/ray/experimental/serve/mixin.py | RayServeMixin._dispatch | def _dispatch(self, input_batch: List[SingleQuery]):
"""Helper method to dispatch a batch of input to self.serve_method."""
method = getattr(self, self.serve_method)
if hasattr(method, "ray_serve_batched_input"):
batch = [inp.data for inp in input_batch]
result = _execute... | python | def _dispatch(self, input_batch: List[SingleQuery]):
"""Helper method to dispatch a batch of input to self.serve_method."""
method = getattr(self, self.serve_method)
if hasattr(method, "ray_serve_batched_input"):
batch = [inp.data for inp in input_batch]
result = _execute... | [
"def",
"_dispatch",
"(",
"self",
",",
"input_batch",
":",
"List",
"[",
"SingleQuery",
"]",
")",
":",
"method",
"=",
"getattr",
"(",
"self",
",",
"self",
".",
"serve_method",
")",
"if",
"hasattr",
"(",
"method",
",",
"\"ray_serve_batched_input\"",
")",
":",... | Helper method to dispatch a batch of input to self.serve_method. | [
"Helper",
"method",
"to",
"dispatch",
"a",
"batch",
"of",
"input",
"to",
"self",
".",
"serve_method",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/serve/mixin.py#L50-L63 | train |
ray-project/ray | python/ray/rllib/env/atari_wrappers.py | get_wrapper_by_cls | def get_wrapper_by_cls(env, cls):
"""Returns the gym env wrapper of the given class, or None."""
currentenv = env
while True:
if isinstance(currentenv, cls):
return currentenv
elif isinstance(currentenv, gym.Wrapper):
currentenv = currentenv.env
else:
... | python | def get_wrapper_by_cls(env, cls):
"""Returns the gym env wrapper of the given class, or None."""
currentenv = env
while True:
if isinstance(currentenv, cls):
return currentenv
elif isinstance(currentenv, gym.Wrapper):
currentenv = currentenv.env
else:
... | [
"def",
"get_wrapper_by_cls",
"(",
"env",
",",
"cls",
")",
":",
"currentenv",
"=",
"env",
"while",
"True",
":",
"if",
"isinstance",
"(",
"currentenv",
",",
"cls",
")",
":",
"return",
"currentenv",
"elif",
"isinstance",
"(",
"currentenv",
",",
"gym",
".",
... | Returns the gym env wrapper of the given class, or None. | [
"Returns",
"the",
"gym",
"env",
"wrapper",
"of",
"the",
"given",
"class",
"or",
"None",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/env/atari_wrappers.py#L17-L26 | train |
ray-project/ray | python/ray/rllib/env/atari_wrappers.py | wrap_deepmind | def wrap_deepmind(env, dim=84, framestack=True):
"""Configure environment for DeepMind-style Atari.
Note that we assume reward clipping is done outside the wrapper.
Args:
dim (int): Dimension to resize observations to (dim x dim).
framestack (bool): Whether to framestack observations.
... | python | def wrap_deepmind(env, dim=84, framestack=True):
"""Configure environment for DeepMind-style Atari.
Note that we assume reward clipping is done outside the wrapper.
Args:
dim (int): Dimension to resize observations to (dim x dim).
framestack (bool): Whether to framestack observations.
... | [
"def",
"wrap_deepmind",
"(",
"env",
",",
"dim",
"=",
"84",
",",
"framestack",
"=",
"True",
")",
":",
"env",
"=",
"MonitorEnv",
"(",
"env",
")",
"env",
"=",
"NoopResetEnv",
"(",
"env",
",",
"noop_max",
"=",
"30",
")",
"if",
"\"NoFrameskip\"",
"in",
"e... | Configure environment for DeepMind-style Atari.
Note that we assume reward clipping is done outside the wrapper.
Args:
dim (int): Dimension to resize observations to (dim x dim).
framestack (bool): Whether to framestack observations. | [
"Configure",
"environment",
"for",
"DeepMind",
"-",
"style",
"Atari",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/env/atari_wrappers.py#L270-L291 | train |
ray-project/ray | python/ray/rllib/models/pytorch/misc.py | valid_padding | def valid_padding(in_size, filter_size, stride_size):
"""Note: Padding is added to match TF conv2d `same` padding. See
www.tensorflow.org/versions/r0.12/api_docs/python/nn/convolution
Params:
in_size (tuple): Rows (Height), Column (Width) for input
stride_size (tuple): Rows (Height), Column... | python | def valid_padding(in_size, filter_size, stride_size):
"""Note: Padding is added to match TF conv2d `same` padding. See
www.tensorflow.org/versions/r0.12/api_docs/python/nn/convolution
Params:
in_size (tuple): Rows (Height), Column (Width) for input
stride_size (tuple): Rows (Height), Column... | [
"def",
"valid_padding",
"(",
"in_size",
",",
"filter_size",
",",
"stride_size",
")",
":",
"in_height",
",",
"in_width",
"=",
"in_size",
"filter_height",
",",
"filter_width",
"=",
"filter_size",
"stride_height",
",",
"stride_width",
"=",
"stride_size",
"out_height",
... | Note: Padding is added to match TF conv2d `same` padding. See
www.tensorflow.org/versions/r0.12/api_docs/python/nn/convolution
Params:
in_size (tuple): Rows (Height), Column (Width) for input
stride_size (tuple): Rows (Height), Column (Width) for stride
filter_size (tuple): Rows (Height... | [
"Note",
":",
"Padding",
"is",
"added",
"to",
"match",
"TF",
"conv2d",
"same",
"padding",
".",
"See",
"www",
".",
"tensorflow",
".",
"org",
"/",
"versions",
"/",
"r0",
".",
"12",
"/",
"api_docs",
"/",
"python",
"/",
"nn",
"/",
"convolution"
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/models/pytorch/misc.py#L20-L50 | train |
ray-project/ray | python/ray/rllib/utils/memory.py | ray_get_and_free | def ray_get_and_free(object_ids):
"""Call ray.get and then queue the object ids for deletion.
This function should be used whenever possible in RLlib, to optimize
memory usage. The only exception is when an object_id is shared among
multiple readers.
Args:
object_ids (ObjectID|List[ObjectI... | python | def ray_get_and_free(object_ids):
"""Call ray.get and then queue the object ids for deletion.
This function should be used whenever possible in RLlib, to optimize
memory usage. The only exception is when an object_id is shared among
multiple readers.
Args:
object_ids (ObjectID|List[ObjectI... | [
"def",
"ray_get_and_free",
"(",
"object_ids",
")",
":",
"global",
"_last_free_time",
"global",
"_to_free",
"result",
"=",
"ray",
".",
"get",
"(",
"object_ids",
")",
"if",
"type",
"(",
"object_ids",
")",
"is",
"not",
"list",
":",
"object_ids",
"=",
"[",
"ob... | Call ray.get and then queue the object ids for deletion.
This function should be used whenever possible in RLlib, to optimize
memory usage. The only exception is when an object_id is shared among
multiple readers.
Args:
object_ids (ObjectID|List[ObjectID]): Object ids to fetch and free.
R... | [
"Call",
"ray",
".",
"get",
"and",
"then",
"queue",
"the",
"object",
"ids",
"for",
"deletion",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/utils/memory.py#L16-L46 | train |
ray-project/ray | python/ray/rllib/utils/memory.py | aligned_array | def aligned_array(size, dtype, align=64):
"""Returns an array of a given size that is 64-byte aligned.
The returned array can be efficiently copied into GPU memory by TensorFlow.
"""
n = size * dtype.itemsize
empty = np.empty(n + (align - 1), dtype=np.uint8)
data_align = empty.ctypes.data % al... | python | def aligned_array(size, dtype, align=64):
"""Returns an array of a given size that is 64-byte aligned.
The returned array can be efficiently copied into GPU memory by TensorFlow.
"""
n = size * dtype.itemsize
empty = np.empty(n + (align - 1), dtype=np.uint8)
data_align = empty.ctypes.data % al... | [
"def",
"aligned_array",
"(",
"size",
",",
"dtype",
",",
"align",
"=",
"64",
")",
":",
"n",
"=",
"size",
"*",
"dtype",
".",
"itemsize",
"empty",
"=",
"np",
".",
"empty",
"(",
"n",
"+",
"(",
"align",
"-",
"1",
")",
",",
"dtype",
"=",
"np",
".",
... | Returns an array of a given size that is 64-byte aligned.
The returned array can be efficiently copied into GPU memory by TensorFlow. | [
"Returns",
"an",
"array",
"of",
"a",
"given",
"size",
"that",
"is",
"64",
"-",
"byte",
"aligned",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/utils/memory.py#L49-L63 | train |
ray-project/ray | python/ray/rllib/utils/memory.py | concat_aligned | def concat_aligned(items):
"""Concatenate arrays, ensuring the output is 64-byte aligned.
We only align float arrays; other arrays are concatenated as normal.
This should be used instead of np.concatenate() to improve performance
when the output array is likely to be fed into TensorFlow.
"""
... | python | def concat_aligned(items):
"""Concatenate arrays, ensuring the output is 64-byte aligned.
We only align float arrays; other arrays are concatenated as normal.
This should be used instead of np.concatenate() to improve performance
when the output array is likely to be fed into TensorFlow.
"""
... | [
"def",
"concat_aligned",
"(",
"items",
")",
":",
"if",
"len",
"(",
"items",
")",
"==",
"0",
":",
"return",
"[",
"]",
"elif",
"len",
"(",
"items",
")",
"==",
"1",
":",
"# we assume the input is aligned. In any case, it doesn't help",
"# performance to force align i... | Concatenate arrays, ensuring the output is 64-byte aligned.
We only align float arrays; other arrays are concatenated as normal.
This should be used instead of np.concatenate() to improve performance
when the output array is likely to be fed into TensorFlow. | [
"Concatenate",
"arrays",
"ensuring",
"the",
"output",
"is",
"64",
"-",
"byte",
"aligned",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/utils/memory.py#L66-L92 | train |
ray-project/ray | python/ray/experimental/queue.py | Queue.put | def put(self, item, block=True, timeout=None):
"""Adds an item to the queue.
Uses polling if block=True, so there is no guarantee of order if
multiple producers put to the same full queue.
Raises:
Full if the queue is full and blocking is False.
"""
if self.... | python | def put(self, item, block=True, timeout=None):
"""Adds an item to the queue.
Uses polling if block=True, so there is no guarantee of order if
multiple producers put to the same full queue.
Raises:
Full if the queue is full and blocking is False.
"""
if self.... | [
"def",
"put",
"(",
"self",
",",
"item",
",",
"block",
"=",
"True",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"self",
".",
"maxsize",
"<=",
"0",
":",
"self",
".",
"actor",
".",
"put",
".",
"remote",
"(",
"item",
")",
"elif",
"not",
"block",
"... | Adds an item to the queue.
Uses polling if block=True, so there is no guarantee of order if
multiple producers put to the same full queue.
Raises:
Full if the queue is full and blocking is False. | [
"Adds",
"an",
"item",
"to",
"the",
"queue",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/queue.py#L49-L79 | train |
ray-project/ray | python/ray/experimental/queue.py | Queue.get | def get(self, block=True, timeout=None):
"""Gets an item from the queue.
Uses polling if block=True, so there is no guarantee of order if
multiple consumers get from the same empty queue.
Returns:
The next item in the queue.
Raises:
Empty if the queue i... | python | def get(self, block=True, timeout=None):
"""Gets an item from the queue.
Uses polling if block=True, so there is no guarantee of order if
multiple consumers get from the same empty queue.
Returns:
The next item in the queue.
Raises:
Empty if the queue i... | [
"def",
"get",
"(",
"self",
",",
"block",
"=",
"True",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"block",
":",
"success",
",",
"item",
"=",
"ray",
".",
"get",
"(",
"self",
".",
"actor",
".",
"get",
".",
"remote",
"(",
")",
")",
"if",
... | Gets an item from the queue.
Uses polling if block=True, so there is no guarantee of order if
multiple consumers get from the same empty queue.
Returns:
The next item in the queue.
Raises:
Empty if the queue is empty and blocking is False. | [
"Gets",
"an",
"item",
"from",
"the",
"queue",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/queue.py#L81-L115 | train |
ray-project/ray | python/ray/rllib/utils/annotations.py | override | def override(cls):
"""Annotation for documenting method overrides.
Arguments:
cls (type): The superclass that provides the overriden method. If this
cls does not actually have the method, an error is raised.
"""
def check_override(method):
if method.__name__ not in dir(cls)... | python | def override(cls):
"""Annotation for documenting method overrides.
Arguments:
cls (type): The superclass that provides the overriden method. If this
cls does not actually have the method, an error is raised.
"""
def check_override(method):
if method.__name__ not in dir(cls)... | [
"def",
"override",
"(",
"cls",
")",
":",
"def",
"check_override",
"(",
"method",
")",
":",
"if",
"method",
".",
"__name__",
"not",
"in",
"dir",
"(",
"cls",
")",
":",
"raise",
"NameError",
"(",
"\"{} does not override any method of {}\"",
".",
"format",
"(",
... | Annotation for documenting method overrides.
Arguments:
cls (type): The superclass that provides the overriden method. If this
cls does not actually have the method, an error is raised. | [
"Annotation",
"for",
"documenting",
"method",
"overrides",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/utils/annotations.py#L6-L20 | train |
ray-project/ray | python/ray/tune/schedulers/hyperband.py | HyperBandScheduler.on_trial_add | def on_trial_add(self, trial_runner, trial):
"""Adds new trial.
On a new trial add, if current bracket is not filled,
add to current bracket. Else, if current band is not filled,
create new bracket, add to current bracket.
Else, create new iteration, create new bracket, add to b... | python | def on_trial_add(self, trial_runner, trial):
"""Adds new trial.
On a new trial add, if current bracket is not filled,
add to current bracket. Else, if current band is not filled,
create new bracket, add to current bracket.
Else, create new iteration, create new bracket, add to b... | [
"def",
"on_trial_add",
"(",
"self",
",",
"trial_runner",
",",
"trial",
")",
":",
"cur_bracket",
"=",
"self",
".",
"_state",
"[",
"\"bracket\"",
"]",
"cur_band",
"=",
"self",
".",
"_hyperbands",
"[",
"self",
".",
"_state",
"[",
"\"band_idx\"",
"]",
"]",
"... | Adds new trial.
On a new trial add, if current bracket is not filled,
add to current bracket. Else, if current band is not filled,
create new bracket, add to current bracket.
Else, create new iteration, create new bracket, add to bracket. | [
"Adds",
"new",
"trial",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/schedulers/hyperband.py#L98-L132 | train |
ray-project/ray | python/ray/tune/schedulers/hyperband.py | HyperBandScheduler._cur_band_filled | def _cur_band_filled(self):
"""Checks if the current band is filled.
The size of the current band should be equal to s_max_1"""
cur_band = self._hyperbands[self._state["band_idx"]]
return len(cur_band) == self._s_max_1 | python | def _cur_band_filled(self):
"""Checks if the current band is filled.
The size of the current band should be equal to s_max_1"""
cur_band = self._hyperbands[self._state["band_idx"]]
return len(cur_band) == self._s_max_1 | [
"def",
"_cur_band_filled",
"(",
"self",
")",
":",
"cur_band",
"=",
"self",
".",
"_hyperbands",
"[",
"self",
".",
"_state",
"[",
"\"band_idx\"",
"]",
"]",
"return",
"len",
"(",
"cur_band",
")",
"==",
"self",
".",
"_s_max_1"
] | Checks if the current band is filled.
The size of the current band should be equal to s_max_1 | [
"Checks",
"if",
"the",
"current",
"band",
"is",
"filled",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/schedulers/hyperband.py#L134-L140 | train |
ray-project/ray | python/ray/tune/schedulers/hyperband.py | HyperBandScheduler.on_trial_result | def on_trial_result(self, trial_runner, trial, result):
"""If bracket is finished, all trials will be stopped.
If a given trial finishes and bracket iteration is not done,
the trial will be paused and resources will be given up.
This scheduler will not start trials but will stop trials... | python | def on_trial_result(self, trial_runner, trial, result):
"""If bracket is finished, all trials will be stopped.
If a given trial finishes and bracket iteration is not done,
the trial will be paused and resources will be given up.
This scheduler will not start trials but will stop trials... | [
"def",
"on_trial_result",
"(",
"self",
",",
"trial_runner",
",",
"trial",
",",
"result",
")",
":",
"bracket",
",",
"_",
"=",
"self",
".",
"_trial_info",
"[",
"trial",
"]",
"bracket",
".",
"update_trial_stats",
"(",
"trial",
",",
"result",
")",
"if",
"bra... | If bracket is finished, all trials will be stopped.
If a given trial finishes and bracket iteration is not done,
the trial will be paused and resources will be given up.
This scheduler will not start trials but will stop trials.
The current running trial will not be handled,
as... | [
"If",
"bracket",
"is",
"finished",
"all",
"trials",
"will",
"be",
"stopped",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/schedulers/hyperband.py#L142-L159 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.