Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def query_trial(request):
trial_id = request.GET.get("trial_id")
trials = TrialRecord.objects \
.filter(trial_id=trial_id) \
.order_by("-start_time")
if len(trials) == 0:
resp = "Unkonwn trial id %s.\n" % trials
else:
tria... | [
"Rest API to query the trial info, with the given trial_id.\n\n The url pattern should be like this:\n\n curl http://<server>:<port>/query_trial?trial_id=<trial_id>\n\n The response may be:\n\n {\n \"app_url\": \"None\",\n \"trial_status\": \"TERMINATED\",\n \"params\": {'a': 1, 'b'... |
Please provide a description of the function:def on_trial_result(self, trial_runner, trial, result):
if trial in self._stopped_trials:
assert not self._hard_stop
return TrialScheduler.CONTINUE # fall back to FIFO
time = result[self._time_attr]
self._results[tr... | [
"Callback for early stopping.\n\n This stopping rule stops a running trial if the trial's best objective\n value by step `t` is strictly worse than the median of the running\n averages of all completed trials' objectives reported up to step `t`.\n "
] |
Please provide a description of the function:def on_trial_remove(self, trial_runner, trial):
if trial.status is Trial.PAUSED and trial in self._results:
self._completed_trials.add(trial) | [
"Marks trial as completed if it is paused and has previously ran."
] |
Please provide a description of the function:def from_json(cls, json_info):
if json_info is None:
return None
return JobRecord(
job_id=json_info["job_id"],
name=json_info["job_name"],
user=json_info["user"],
type=json_info["type"],
... | [
"Build a Job instance from a json string."
] |
Please provide a description of the function:def from_json(cls, json_info):
if json_info is None:
return None
return TrialRecord(
trial_id=json_info["trial_id"],
job_id=json_info["job_id"],
trial_status=json_info["status"],
start_time=... | [
"Build a Trial instance from a json string."
] |
Please provide a description of the function:def from_json(cls, json_info):
if json_info is None:
return None
return ResultRecord(
trial_id=json_info["trial_id"],
timesteps_total=json_info["timesteps_total"],
done=json_info.get("done", None),
... | [
"Build a Result instance from a json string."
] |
Please provide a description of the function:def compute_advantages(rollout, last_r, gamma=0.9, lambda_=1.0, use_gae=True):
traj = {}
trajsize = len(rollout[SampleBatch.ACTIONS])
for key in rollout:
traj[key] = np.stack(rollout[key])
if use_gae:
assert SampleBatch.VF_PREDS in roll... | [
"Given a rollout, compute its value targets and the advantage.\n\n Args:\n rollout (SampleBatch): SampleBatch of a single trajectory\n last_r (float): Value estimation for last observation\n gamma (float): Discount factor.\n lambda_ (float): Parameter for GAE\n use_gae (bool): ... |
Please provide a description of the function:def xray_heartbeat_batch_handler(self, unused_channel, data):
gcs_entries = ray.gcs_utils.GcsTableEntry.GetRootAsGcsTableEntry(
data, 0)
heartbeat_data = gcs_entries.Entries(0)
message = (ray.gcs_utils.HeartbeatBatchTableData.
... | [
"Handle an xray heartbeat batch message from Redis."
] |
Please provide a description of the function:def _xray_clean_up_entries_for_driver(self, driver_id):
xray_task_table_prefix = (
ray.gcs_utils.TablePrefix_RAYLET_TASK_string.encode("ascii"))
xray_object_table_prefix = (
ray.gcs_utils.TablePrefix_OBJECT_string.encode("asc... | [
"Remove this driver's object/task entries from redis.\n\n Removes control-state entries of all tasks and task return\n objects belonging to the driver.\n\n Args:\n driver_id: The driver id.\n "
] |
Please provide a description of the function:def xray_driver_removed_handler(self, unused_channel, data):
gcs_entries = ray.gcs_utils.GcsTableEntry.GetRootAsGcsTableEntry(
data, 0)
driver_data = gcs_entries.Entries(0)
message = ray.gcs_utils.DriverTableData.GetRootAsDriverTa... | [
"Handle a notification that a driver has been removed.\n\n Args:\n unused_channel: The message channel.\n data: The message data.\n "
] |
Please provide a description of the function:def process_messages(self, max_messages=10000):
subscribe_clients = [self.primary_subscribe_client]
for subscribe_client in subscribe_clients:
for _ in range(max_messages):
message = subscribe_client.get_message()
... | [
"Process all messages ready in the subscription channels.\n\n This reads messages from the subscription channels and calls the\n appropriate handlers until there are no messages left.\n\n Args:\n max_messages: The maximum number of messages to process before\n returnin... |
Please provide a description of the function:def _maybe_flush_gcs(self):
if not self.issue_gcs_flushes:
return
if self.gcs_flush_policy is None:
serialized = self.redis.get("gcs_flushing_policy")
if serialized is None:
# Client has not set any... | [
"Experimental: issue a flush request to the GCS.\n\n The purpose of this feature is to control GCS memory usage.\n\n To activate this feature, Ray must be compiled with the flag\n RAY_USE_NEW_GCS set, and Ray must be started at run time with the flag\n as well.\n "
] |
Please provide a description of the function:def run(self):
# Initialize the subscription channel.
self.subscribe(ray.gcs_utils.XRAY_HEARTBEAT_BATCH_CHANNEL)
self.subscribe(ray.gcs_utils.XRAY_DRIVER_CHANNEL)
# TODO(rkn): If there were any dead clients at startup, we should clea... | [
"Run the monitor.\n\n This function loops forever, checking for messages about dead database\n clients and cleaning up state accordingly.\n "
] |
Please provide a description of the function:def index(request):
recent_jobs = JobRecord.objects.order_by("-start_time")[0:100]
recent_trials = TrialRecord.objects.order_by("-start_time")[0:500]
total_num = len(recent_trials)
running_num = sum(t.trial_status == Trial.RUNNING for t in recent_trials... | [
"View for the home page."
] |
Please provide a description of the function:def job(request):
job_id = request.GET.get("job_id")
recent_jobs = JobRecord.objects.order_by("-start_time")[0:100]
recent_trials = TrialRecord.objects \
.filter(job_id=job_id) \
.order_by("-start_time")
trial_records = []
for recent_... | [
"View for a single job."
] |
Please provide a description of the function:def trial(request):
job_id = request.GET.get("job_id")
trial_id = request.GET.get("trial_id")
recent_trials = TrialRecord.objects \
.filter(job_id=job_id) \
.order_by("-start_time")
recent_results = ResultRecord.objects \
.filter(... | [
"View for a single trial."
] |
Please provide a description of the function:def get_job_info(current_job):
trials = TrialRecord.objects.filter(job_id=current_job.job_id)
total_num = len(trials)
running_num = sum(t.trial_status == Trial.RUNNING for t in trials)
success_num = sum(t.trial_status == Trial.TERMINATED for t in trials)... | [
"Get job information for current job."
] |
Please provide a description of the function:def get_trial_info(current_trial):
if current_trial.end_time and ("_" in current_trial.end_time):
# end time is parsed from result.json and the format
# is like: yyyy-mm-dd_hh-MM-ss, which will be converted
# to yyyy-mm-dd hh:MM:ss here
... | [
"Get job information for current trial."
] |
Please provide a description of the function:def get_winner(trials):
winner = {}
# TODO: sort_key should be customized here
sort_key = "accuracy"
if trials and len(trials) > 0:
first_metrics = get_trial_info(trials[0])["metrics"]
if first_metrics and not first_metrics.get("accuracy"... | [
"Get winner trial of a job."
] |
Please provide a description of the function:def make_parser(parser_creator=None, **kwargs):
if parser_creator:
parser = parser_creator(**kwargs)
else:
parser = argparse.ArgumentParser(**kwargs)
# Note: keep this in sync with rllib/train.py
parser.add_argument(
"--run",
... | [
"Returns a base argument parser for the ray.tune tool.\n\n Args:\n parser_creator: A constructor for the parser class.\n kwargs: Non-positional args to be passed into the\n parser class constructor.\n "
] |
Please provide a description of the function:def to_argv(config):
argv = []
for k, v in config.items():
if "-" in k:
raise ValueError("Use '_' instead of '-' in `{}`".format(k))
if v is None:
continue
if not isinstance(v, bool) or v: # for argparse flags
... | [
"Converts configuration to a command line argument format."
] |
Please provide a description of the function:def create_trial_from_spec(spec, output_path, parser, **trial_kwargs):
try:
args = parser.parse_args(to_argv(spec))
except SystemExit:
raise TuneError("Error parsing args, see above message", spec)
if "resources_per_trial" in spec:
tr... | [
"Creates a Trial object from parsing the spec.\n\n Arguments:\n spec (dict): A resolved experiment specification. Arguments should\n The args here should correspond to the command line flags\n in ray.tune.config_parser.\n output_path (str); A specific output path within the lo... |
Please provide a description of the function:def wait_for_compute_zone_operation(compute, project_name, operation, zone):
logger.info("wait_for_compute_zone_operation: "
"Waiting for operation {} to finish...".format(
operation["name"]))
for _ in range(MAX_POLLS):
... | [
"Poll for compute zone operation until finished."
] |
Please provide a description of the function:def _get_task_id(source):
if type(source) is ray.actor.ActorHandle:
return source._ray_actor_id
else:
if type(source) is ray.TaskID:
return source
else:
return ray._raylet.compute_task_id(source) | [
"Return the task id associated to the generic source of the signal.\n\n Args:\n source: source of the signal, it can be either an object id returned\n by a task, a task id, or an actor handle.\n\n Returns:\n - If source is an object id, return id of task which creted object.\n ... |
Please provide a description of the function:def send(signal):
if hasattr(ray.worker.global_worker, "actor_creation_task_id"):
source_key = ray.worker.global_worker.actor_id.hex()
else:
# No actors; this function must have been called from a task
source_key = ray.worker.global_worke... | [
"Send signal.\n\n The signal has a unique identifier that is computed from (1) the id\n of the actor or task sending this signal (i.e., the actor or task calling\n this function), and (2) an index that is incremented every time this\n source sends a signal. This index starts from 1.\n\n Args:\n ... |
Please provide a description of the function:def receive(sources, timeout=None):
# If None, initialize the timeout to a huge value (i.e., over 30,000 years
# in this case) to "approximate" infinity.
if timeout is None:
timeout = 10**12
if timeout < 0:
raise ValueError("The 'timeou... | [
"Get all outstanding signals from sources.\n\n A source can be either (1) an object ID returned by the task (we want\n to receive signals from), or (2) an actor handle.\n\n When invoked by the same entity E (where E can be an actor, task or\n driver), for each source S in sources, this function returns ... |
Please provide a description of the function:def reset():
if hasattr(ray.worker.global_worker, "signal_counters"):
ray.worker.global_worker.signal_counters = defaultdict(lambda: b"0") | [
"\n Reset the worker state associated with any signals that this worker\n has received so far.\n\n If the worker calls receive() on a source next, it will get all the\n signals generated by that source starting with index = 1.\n "
] |
Please provide a description of the function:def log_once(key):
global _last_logged
if _disabled:
return False
elif key not in _logged:
_logged.add(key)
_last_logged = time.time()
return True
elif _periodic_log and time.time() - _last_logged > 60.0:
_logged... | [
"Returns True if this is the \"first\" call for a given key.\n\n Various logging settings can adjust the definition of \"first\".\n\n Example:\n >>> if log_once(\"some_key\"):\n ... logger.info(\"Some verbose logging statement\")\n "
] |
Please provide a description of the function:def get(object_ids):
if isinstance(object_ids, (tuple, np.ndarray)):
return ray.get(list(object_ids))
elif isinstance(object_ids, dict):
keys_to_get = [
k for k, v in object_ids.items() if isinstance(v, ray.ObjectID)
]
... | [
"Get a single or a collection of remote objects from the object store.\n\n This method is identical to `ray.get` except it adds support for tuples,\n ndarrays and dictionaries.\n\n Args:\n object_ids: Object ID of the object to get, a list, tuple, ndarray of\n object IDs to get or a dict ... |
Please provide a description of the function:def wait(object_ids, num_returns=1, timeout=None):
if isinstance(object_ids, (tuple, np.ndarray)):
return ray.wait(
list(object_ids), num_returns=num_returns, timeout=timeout)
return ray.wait(object_ids, num_returns=num_returns, timeout=time... | [
"Return a list of IDs that are ready and a list of IDs that are not.\n\n This method is identical to `ray.wait` except it adds support for tuples\n and ndarrays.\n\n Args:\n object_ids (List[ObjectID], Tuple(ObjectID), np.array(ObjectID)):\n List like of object IDs for objects that may or... |
Please provide a description of the function:def _raise_deprecation_note(deprecated, replacement, soft=False):
error_msg = ("`{deprecated}` is deprecated. Please use `{replacement}`. "
"`{deprecated}` will be removed in future versions of "
"Ray.".format(deprecated=deprecated,... | [
"User notification for deprecated parameter.\n\n Arguments:\n deprecated (str): Deprecated parameter.\n replacement (str): Replacement parameter to use instead.\n soft (bool): Fatal if True.\n "
] |
Please provide a description of the function:def convert_to_experiment_list(experiments):
exp_list = experiments
# Transform list if necessary
if experiments is None:
exp_list = []
elif isinstance(experiments, Experiment):
exp_list = [experiments]
elif type(experiments) is dict... | [
"Produces a list of Experiment objects.\n\n Converts input from dict, single experiment, or list of\n experiments to list of experiments. If input is None,\n will return an empty list.\n\n Arguments:\n experiments (Experiment | list | dict): Experiments to run.\n\n Returns:\n List of ex... |
Please provide a description of the function:def from_json(cls, name, spec):
if "run" not in spec:
raise TuneError("No trainable specified!")
# Special case the `env` param for RLlib by automatically
# moving it into the `config` section.
if "env" in spec:
... | [
"Generates an Experiment object from JSON.\n\n Args:\n name (str): Name of Experiment.\n spec (dict): JSON configuration of experiment.\n "
] |
Please provide a description of the function:def _register_if_needed(cls, run_object):
if isinstance(run_object, six.string_types):
return run_object
elif isinstance(run_object, types.FunctionType):
if run_object.__name__ == "<lambda>":
logger.warning(
... | [
"Registers Trainable or Function at runtime.\n\n Assumes already registered if run_object is a string. Does not\n register lambdas because they could be part of variant generation.\n Also, does not inspect interface of given run_object.\n\n Arguments:\n run_object (str|functio... |
Please provide a description of the function:def tsqr(a):
if len(a.shape) != 2:
raise Exception("tsqr requires len(a.shape) == 2, but a.shape is "
"{}".format(a.shape))
if a.num_blocks[1] != 1:
raise Exception("tsqr requires a.num_blocks[1] == 1, but a.num_blocks "
... | [
"Perform a QR decomposition of a tall-skinny matrix.\n\n Args:\n a: A distributed matrix with shape MxN (suppose K = min(M, N)).\n\n Returns:\n A tuple of q (a DistArray) and r (a numpy array) satisfying the\n following.\n - If q_full = ray.get(DistArray, q).assemble(), the... |
Please provide a description of the function:def modified_lu(q):
q = q.assemble()
m, b = q.shape[0], q.shape[1]
S = np.zeros(b)
q_work = np.copy(q)
for i in range(b):
S[i] = -1 * np.sign(q_work[i, i])
q_work[i, i] -= S[i]
# Scale ith column of L by diagonal element.
... | [
"Perform a modified LU decomposition of a matrix.\n\n This takes a matrix q with orthonormal columns, returns l, u, s such that\n q - s = l * u.\n\n Args:\n q: A two dimensional orthonormal matrix q.\n\n Returns:\n A tuple of a lower triangular matrix l, an upper triangular matrix u,\n ... |
Please provide a description of the function:def _naturalize(string):
splits = re.split("([0-9]+)", string)
return [int(text) if text.isdigit() else text.lower() for text in splits] | [
"Provides a natural representation for string for nice sorting."
] |
Please provide a description of the function:def _find_newest_ckpt(ckpt_dir):
full_paths = [
os.path.join(ckpt_dir, fname) for fname in os.listdir(ckpt_dir)
if fname.startswith("experiment_state") and fname.endswith(".json")
]
return max(full_paths) | [
"Returns path to most recently modified checkpoint."
] |
Please provide a description of the function:def checkpoint(self):
if not self._metadata_checkpoint_dir:
return
metadata_checkpoint_dir = self._metadata_checkpoint_dir
if not os.path.exists(metadata_checkpoint_dir):
os.makedirs(metadata_checkpoint_dir)
ru... | [
"Saves execution state to `self._metadata_checkpoint_dir`.\n\n Overwrites the current session checkpoint, which starts when self\n is instantiated.\n "
] |
Please provide a description of the function:def restore(cls,
metadata_checkpoint_dir,
search_alg=None,
scheduler=None,
trial_executor=None):
newest_ckpt_path = _find_newest_ckpt(metadata_checkpoint_dir)
with open(newest_ckpt_path... | [
"Restores all checkpointed trials from previous run.\n\n Requires user to manually re-register their objects. Also stops\n all ongoing trials.\n\n Args:\n metadata_checkpoint_dir (str): Path to metadata checkpoints.\n search_alg (SearchAlgorithm): Search Algorithm. Default... |
Please provide a description of the function:def is_finished(self):
if self._total_time > self._global_time_limit:
logger.warning("Exceeded global time limit {} / {}".format(
self._total_time, self._global_time_limit))
return True
trials_done = all(tria... | [
"Returns whether all trials have finished running."
] |
Please provide a description of the function:def step(self):
if self.is_finished():
raise TuneError("Called step when all trials finished?")
with warn_if_slow("on_step_begin"):
self.trial_executor.on_step_begin()
next_trial = self._get_next_trial() # blocking
... | [
"Runs one step of the trial event loop.\n\n Callers should typically run this method repeatedly in a loop. They\n may inspect or modify the runner's state in between calls to step().\n "
] |
Please provide a description of the function:def add_trial(self, trial):
trial.set_verbose(self._verbose)
self._trials.append(trial)
with warn_if_slow("scheduler.on_trial_add"):
self._scheduler_alg.on_trial_add(self, trial)
self.trial_executor.try_checkpoint_metadata... | [
"Adds a new trial to this TrialRunner.\n\n Trials may be added at any time.\n\n Args:\n trial (Trial): Trial to queue.\n "
] |
Please provide a description of the function:def debug_string(self, max_debug=MAX_DEBUG_TRIALS):
messages = self._debug_messages()
states = collections.defaultdict(set)
limit_per_state = collections.Counter()
for t in self._trials:
states[t.status].add(t)
# ... | [
"Returns a human readable message for printing to the console."
] |
Please provide a description of the function:def _get_next_trial(self):
trials_done = all(trial.is_finished() for trial in self._trials)
wait_for_trial = trials_done and not self._search_alg.is_finished()
self._update_trial_queue(blocking=wait_for_trial)
with warn_if_slow("choos... | [
"Replenishes queue.\n\n Blocks if all trials queued have finished, but search algorithm is\n still not finished.\n "
] |
Please provide a description of the function:def _checkpoint_trial_if_needed(self, trial):
if trial.should_checkpoint():
# Save trial runtime if possible
if hasattr(trial, "runner") and trial.runner:
self.trial_executor.save(trial, storage=Checkpoint.DISK)
... | [
"Checkpoints trial based off trial.last_result."
] |
Please provide a description of the function:def _try_recover(self, trial, error_msg):
try:
self.trial_executor.stop_trial(
trial,
error=error_msg is not None,
error_msg=error_msg,
stop_logger=False)
trial.result_lo... | [
"Tries to recover trial.\n\n Notifies SearchAlgorithm and Scheduler if failure to recover.\n\n Args:\n trial (Trial): Trial to recover.\n error_msg (str): Error message from prior to invoking this method.\n "
] |
Please provide a description of the function:def _requeue_trial(self, trial):
self._scheduler_alg.on_trial_error(self, trial)
self.trial_executor.set_status(trial, Trial.PENDING)
with warn_if_slow("scheduler.on_trial_add"):
self._scheduler_alg.on_trial_add(self, trial) | [
"Notification to TrialScheduler and requeue trial.\n\n This does not notify the SearchAlgorithm because the function\n evaluation is still in progress.\n "
] |
Please provide a description of the function:def _update_trial_queue(self, blocking=False, timeout=600):
trials = self._search_alg.next_trials()
if blocking and not trials:
start = time.time()
# Checking `is_finished` instead of _search_alg.is_finished
# is f... | [
"Adds next trials to queue if possible.\n\n Note that the timeout is currently unexposed to the user.\n\n Args:\n blocking (bool): Blocks until either a trial is available\n or is_finished (timeout or search algorithm finishes).\n timeout (int): Seconds before bloc... |
Please provide a description of the function:def stop_trial(self, trial):
error = False
error_msg = None
if trial.status in [Trial.ERROR, Trial.TERMINATED]:
return
elif trial.status in [Trial.PENDING, Trial.PAUSED]:
self._scheduler_alg.on_trial_remove(se... | [
"Stops trial.\n\n Trials may be stopped at any time. If trial is in state PENDING\n or PAUSED, calls `on_trial_remove` for scheduler and\n `on_trial_complete(..., early_terminated=True) for search_alg.\n Otherwise waits for result for the trial and calls\n `on_trial_complete` for... |
Please provide a description of the function:def run_func(func, *args, **kwargs):
ray.init()
func = ray.remote(func)
# NOTE: kwargs not allowed for now
result = ray.get(func.remote(*args))
# Inspect the stack to get calling example
caller = inspect.stack()[1][3]
print("%s: %s" % (cal... | [
"Helper function for running examples"
] |
Please provide a description of the function:def example6():
ray.init()
cls = ray.remote(cyth.simple_class)
a1 = cls.remote()
a2 = cls.remote()
result1 = ray.get(a1.increment.remote())
result2 = ray.get(a2.increment.remote())
print(result1, result2) | [
"Cython simple class"
] |
Please provide a description of the function:def example8():
# See cython_blas.pyx for argument documentation
mat = np.array([[[2.0, 2.0], [2.0, 2.0]], [[2.0, 2.0], [2.0, 2.0]]],
dtype=np.float32)
result = np.zeros((2, 2), np.float32, order="C")
run_func(cyth.compute_kernel_mat... | [
"Cython with blas. NOTE: requires scipy"
] |
Please provide a description of the function:def _adjust_nstep(n_step, gamma, obs, actions, rewards, new_obs, dones):
assert not any(dones[:-1]), "Unexpected done in middle of trajectory"
traj_length = len(rewards)
for i in range(traj_length):
for j in range(1, n_step):
if i + j <... | [
"Rewrites the given trajectory fragments to encode n-step rewards.\n\n reward[i] = (\n reward[i] * gamma**0 +\n reward[i+1] * gamma**1 +\n ... +\n reward[i+n_step-1] * gamma**(n_step-1))\n\n The ith new_obs is also adjusted to point to the (i+n_step-1)'th new obs.\n\n At the end... |
Please provide a description of the function:def _reduce_mean_ignore_inf(x, axis):
mask = tf.not_equal(x, tf.float32.min)
x_zeroed = tf.where(mask, x, tf.zeros_like(x))
return (tf.reduce_sum(x_zeroed, axis) / tf.reduce_sum(
tf.cast(mask, tf.float32), axis)) | [
"Same as tf.reduce_mean() but ignores -inf values."
] |
Please provide a description of the function:def _huber_loss(x, delta=1.0):
return tf.where(
tf.abs(x) < delta,
tf.square(x) * 0.5, delta * (tf.abs(x) - 0.5 * delta)) | [
"Reference: https://en.wikipedia.org/wiki/Huber_loss"
] |
Please provide a description of the function:def _minimize_and_clip(optimizer, objective, var_list, clip_val=10):
gradients = optimizer.compute_gradients(objective, var_list=var_list)
for i, (grad, var) in enumerate(gradients):
if grad is not None:
gradients[i] = (tf.clip_by_norm(grad, ... | [
"Minimized `objective` using `optimizer` w.r.t. variables in\n `var_list` while ensure the norm of the gradients for each\n variable is clipped to `clip_val`\n "
] |
Please provide a description of the function:def _scope_vars(scope, trainable_only=False):
return tf.get_collection(
tf.GraphKeys.TRAINABLE_VARIABLES
if trainable_only else tf.GraphKeys.VARIABLES,
scope=scope if isinstance(scope, str) else scope.name) | [
"\n Get variables inside a scope\n The scope can be specified as a string\n\n Parameters\n ----------\n scope: str or VariableScope\n scope in which the variables reside.\n trainable_only: bool\n whether or not to return only the variables that were marked as\n trainable.\n\n Ret... |
Please provide a description of the function:def noisy_layer(self, prefix, action_in, out_size, sigma0,
non_linear=True):
in_size = int(action_in.shape[1])
epsilon_in = tf.random_normal(shape=[in_size])
epsilon_out = tf.random_normal(shape=[out_size])
epsilo... | [
"\n a common dense layer: y = w^{T}x + b\n a noisy layer: y = (w + \\epsilon_w*\\sigma_w)^{T}x +\n (b+\\epsilon_b*\\sigma_b)\n where \\epsilon are random variables sampled from factorized normal\n distributions and \\sigma are trainable variables which are expected to\n ... |
Please provide a description of the function:def get_custom_getter(self):
def inner_custom_getter(getter, *args, **kwargs):
if not self.use_tf_layers:
return getter(*args, **kwargs)
requested_dtype = kwargs["dtype"]
if not (requested_dtype == tf.floa... | [
"Returns a custom getter that this class's methods must be called\n\n All methods of this class must be called under a variable scope that was\n passed this custom getter. Example:\n\n ```python\n network = ConvNetBuilder(...)\n with tf.variable_scope(\"cg\", custom_getter=network.get_custom_getter()... |
Please provide a description of the function:def switch_to_aux_top_layer(self):
if self.aux_top_layer is None:
raise RuntimeError("Empty auxiliary top layer in the network.")
saved_top_layer = self.top_layer
saved_top_size = self.top_size
self.top_layer = self.aux_to... | [
"Context that construct cnn in the auxiliary arm."
] |
Please provide a description of the function:def conv(self,
num_out_channels,
k_height,
k_width,
d_height=1,
d_width=1,
mode="SAME",
input_layer=None,
num_channels_in=None,
use_batch_norm=None,
... | [
"Construct a conv2d layer on top of cnn."
] |
Please provide a description of the function:def _pool(self, pool_name, pool_function, k_height, k_width, d_height,
d_width, mode, input_layer, num_channels_in):
if input_layer is None:
input_layer = self.top_layer
else:
self.top_size = num_channels_in
... | [
"Construct a pooling layer."
] |
Please provide a description of the function:def mpool(self,
k_height,
k_width,
d_height=2,
d_width=2,
mode="VALID",
input_layer=None,
num_channels_in=None):
return self._pool("mpool", pooling_layers.max_p... | [
"Construct a max pooling layer."
] |
Please provide a description of the function:def apool(self,
k_height,
k_width,
d_height=2,
d_width=2,
mode="VALID",
input_layer=None,
num_channels_in=None):
return self._pool("apool", pooling_layers.avera... | [
"Construct an average pooling layer."
] |
Please provide a description of the function:def _batch_norm_without_layers(self, input_layer, decay, use_scale,
epsilon):
shape = input_layer.shape
num_channels = shape[3] if self.data_format == "NHWC" else shape[1]
beta = self.get_variable(
... | [
"Batch normalization on `input_layer` without tf.layers."
] |
Please provide a description of the function:def batch_norm(self,
input_layer=None,
decay=0.999,
scale=False,
epsilon=0.001):
if input_layer is None:
input_layer = self.top_layer
else:
self.top_s... | [
"Adds a Batch Normalization layer."
] |
Please provide a description of the function:def lrn(self, depth_radius, bias, alpha, beta):
name = "lrn" + str(self.counts["lrn"])
self.counts["lrn"] += 1
self.top_layer = tf.nn.lrn(
self.top_layer, depth_radius, bias, alpha, beta, name=name)
return self.top_layer | [
"Adds a local response normalization layer."
] |
Please provide a description of the function:def _internal_kv_get(key):
worker = ray.worker.get_global_worker()
if worker.mode == ray.worker.LOCAL_MODE:
return _local.get(key)
return worker.redis_client.hget(key, "value") | [
"Fetch the value of a binary key."
] |
Please provide a description of the function:def _internal_kv_put(key, value, overwrite=False):
worker = ray.worker.get_global_worker()
if worker.mode == ray.worker.LOCAL_MODE:
exists = key in _local
if not exists or overwrite:
_local[key] = value
return exists
if ... | [
"Globally associates a value with a given binary key.\n\n This only has an effect if the key does not already have a value.\n\n Returns:\n already_exists (bool): whether the value already exists.\n "
] |
Please provide a description of the function:def init(self, aggregators):
assert len(aggregators) == self.num_aggregation_workers, aggregators
if len(self.remote_evaluators) < self.num_aggregation_workers:
raise ValueError(
"The number of aggregation workers should ... | [
"Deferred init so that we can pass in previously created workers."
] |
Please provide a description of the function:def free(object_ids, local_only=False, delete_creating_tasks=False):
worker = ray.worker.get_global_worker()
if ray.worker._mode() == ray.worker.LOCAL_MODE:
return
if isinstance(object_ids, ray.ObjectID):
object_ids = [object_ids]
if n... | [
"Free a list of IDs from object stores.\n\n This function is a low-level API which should be used in restricted\n scenarios.\n\n If local_only is false, the request will be send to all object stores.\n\n This method will not return any value to indicate whether the deletion is\n successful or not. Th... |
Please provide a description of the function:def run(self):
self.collector.start()
if self.standalone:
self.collector.join() | [
"Start the collector worker thread.\n\n If running in standalone mode, the current thread will wait\n until the collector thread ends.\n "
] |
Please provide a description of the function:def init_logger(cls, log_level):
logger = logging.getLogger("AutoMLBoard")
handler = logging.StreamHandler()
formatter = logging.Formatter("[%(levelname)s %(asctime)s] "
"%(filename)s: %(lineno)d "
... | [
"Initialize logger settings."
] |
Please provide a description of the function:def run(self):
self._initialize()
self._do_collect()
while not self._is_finished:
time.sleep(self._reload_interval)
self._do_collect()
self.logger.info("Collector stopped.") | [
"Run the main event loop for collector thread.\n\n In each round the collector traverse the results log directory\n and reload trial information from the status files.\n "
] |
Please provide a description of the function:def _initialize(self):
if not os.path.exists(self._logdir):
raise CollectorError("Log directory %s not exists" % self._logdir)
self.logger.info("Collector started, taking %s as parent directory"
"for all job logs... | [
"Initialize collector worker thread, Log path will be checked first.\n\n Records in DB backend will be cleared.\n "
] |
Please provide a description of the function: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._create_job_info(job_path)
self._monitored_jobs.add(job_name)
else:
self._up... | [
"Load information of the job with the given job name.\n\n 1. Traverse each experiment sub-directory and sync information\n for each trial.\n 2. Create or update the job information, together with the job\n meta file.\n\n Args:\n job_name (str) name of the Tune exp... |
Please provide a description of the function: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_name not in self._monitored_trials:
self._create_trial_info(expr_path)
self.... | [
"Load information of the trial from the given experiment directory.\n\n Create or update the trial information, together with the trial\n meta file.\n\n Args:\n job_path(str)\n expr_dir_name(str)\n\n "
] |
Please provide a description of the function: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_json(meta)
job_record.save() | [
"Create information for given job.\n\n Meta file will be loaded if exists, and the job information will\n be saved in db backend.\n\n Args:\n job_dir (str): Directory path of the job.\n "
] |
Please provide a description of the function: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 job info for %s" % meta["job_id"])
JobRecord.objects \
.... | [
"Update information for given job.\n\n Meta file will be loaded if exists, and the job information in\n in db backend will be updated.\n\n Args:\n job_dir (str): Directory path of the job.\n\n Return:\n Updated dict of job meta info\n "
] |
Please provide a description of the function: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.from_json(meta)
trial_record.save() | [
"Create information for given trial.\n\n Meta file will be loaded if exists, and the trial information\n will be saved in db backend.\n\n Args:\n expr_dir (str): Directory path of the experiment.\n "
] |
Please provide a description of the function: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(meta_file)
result_file = os.path.join(expr_dir, EXPR_RESULT_FILE)
offset = self._result_of... | [
"Update information for given trial.\n\n Meta file will be loaded if exists, and the trial information\n in db backend will be updated.\n\n Args:\n expr_dir(str)\n "
] |
Please provide a description of the function: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 = job_dir.split("/")[-1]
user = os.environ.get("USER", None)
meta = {
... | [
"Build meta file for job.\n\n Args:\n job_dir (str): Directory path of the job.\n\n Return:\n A dict of job meta info.\n "
] |
Please provide a description of the function: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 = expr_dir.split("/")[-2]
trial_id = expr_dir[-8:]
params = parse_j... | [
"Build meta file for trial.\n\n Args:\n expr_dir (str): Directory path of the experiment.\n\n Return:\n A dict of trial meta info.\n "
] |
Please provide a description of the function:def _add_results(self, results, trial_id):
for result in results:
self.logger.debug("Appending result: %s" % result)
result["trial_id"] = trial_id
result_record = ResultRecord.from_json(result)
result_record.sa... | [
"Add a list of results into db.\n\n Args:\n results (list): A list of json results.\n trial_id (str): Id of the trial.\n "
] |
Please provide a description of the function: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.\n\n Arguments:\n padded_inputs (Tensor): a padded batch of sequences. That is,\n for seq_lens=[1, 2, 2], then inputs=[A, *, B, B, C, C], where\n A, B, C are sequence elements and * denotes padding.\n seq_lens (Tensor): the sequence leng... |
Please provide a description of the function:def chop_into_sequences(episode_ids,
unroll_ids,
agent_indices,
feature_columns,
state_columns,
max_seq_len,
dynamic_max=True,
... | [
"Truncate and pad experiences into fixed-length sequences.\n\n Arguments:\n episode_ids (list): List of episode ids for each step.\n unroll_ids (list): List of identifiers for the sample batch. This is\n used to make sure sequences are cut between sample batches.\n agent_indices (... |
Please provide a description of the function:def explore(config, mutations, resample_probability, custom_explore_fn):
new_config = copy.deepcopy(config)
for key, distribution in mutations.items():
if isinstance(distribution, dict):
new_config.update({
key: explore(config... | [
"Return a config perturbed as specified.\n\n Args:\n config (dict): Original hyperparameter configuration.\n mutations (dict): Specification of mutations to perform as documented\n in the PopulationBasedTraining scheduler.\n resample_probability (float): Probability of allowing re... |
Please provide a description of the function:def make_experiment_tag(orig_tag, config, mutations):
resolved_vars = {}
for k in mutations.keys():
resolved_vars[("config", k)] = config[k]
return "{}@perturbed[{}]".format(orig_tag, format_vars(resolved_vars)) | [
"Appends perturbed params to the trial name to show in the console."
] |
Please provide a description of the function: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_tag)
trial_id = "... | [
"Logs transition during exploit/exploit step.\n\n For each step, logs: [target trial tag, clone trial tag, target trial\n iteration, clone trial iteration, old config, new config].\n "
] |
Please provide a description of the function: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 new_state.last_checkpoint:
logger.info("[pbt]: no checkpoint for trial."
... | [
"Transfers perturbed state from trial_to_clone -> trial.\n\n If specified, also logs the updated hyperparam state."
] |
Please provide a description of the function:def _quantiles(self):
trials = []
for trial, state in self._trial_state.items():
if state.last_score is not None and not trial.is_finished():
trials.append(trial)
trials.sort(key=lambda t: self._trial_state[t].las... | [
"Returns trials in the lower and upper `quantile` of the population.\n\n If there is not enough data to compute this, returns empty lists."
] |
Please provide a description of the function:def choose_trial_to_run(self, trial_runner):
candidates = []
for trial in trial_runner.get_trials():
if trial.status in [Trial.PENDING, Trial.PAUSED] and \
trial_runner.has_resources(trial.resources):
... | [
"Ensures all trials get fair share of time (as defined by time_attr).\n\n This enables the PBT scheduler to support a greater number of\n concurrent trials than can fit in the cluster at any given time.\n "
] |
Please provide a description of the function:def key_pair(i, region):
if i == 0:
return ("{}_{}".format(RAY, region),
os.path.expanduser("~/.ssh/{}_{}.pem".format(RAY, region)))
return ("{}_{}_{}".format(RAY, i, region),
os.path.expanduser("~/.ssh/{}_{}_{}.pem".format(RA... | [
"Returns the ith default (aws_key_pair_name, key_pair_path)."
] |
Please provide a description of the function:def _build_layers(self, inputs, num_outputs, options):
hiddens = options.get("fcnet_hiddens")
activation = get_activation_fn(options.get("fcnet_activation"))
with tf.name_scope("fc_net"):
i = 1
last_layer = inputs
... | [
"Process the flattened inputs.\n\n Note that dict inputs will be flattened into a vector. To define a\n model that processes the components separately, use _build_layers_v2().\n "
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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(traceback.format_exc()) | [
"Returns the class of a known agent given its name."
] |
Please provide a description of the function:def determine_ip_address():
addrs = [
x.address for k, v in psutil.net_if_addrs().items() if k[0] == "e"
for x in v if x.family == AddressFamily.AF_INET
]
return addrs[0] | [
"Return the first IP address for an ethernet interface on the system."
] |
Please provide a description of the function: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."
] |
Please provide a description of the function:def run(self):
while True:
try:
self.perform_iteration()
except Exception:
traceback.print_exc()
pass
time.sleep(ray_constants.REPORTER_UPDATE_INTERVAL_MS / 1000) | [
"Run the reporter."
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.