Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def delete_checkpoint(self, checkpoint_dir):
if os.path.isfile(checkpoint_dir):
shutil.rmtree(os.path.dirname(checkpoint_dir))
else:
shutil.rmtree(checkpoint_dir) | [
"Removes subdirectory within checkpoint_folder\n Parameters\n ----------\n checkpoint_dir : path to checkpoint\n "
] |
Please provide a description of the function:def save(self, checkpoint_dir=None):
checkpoint_dir = os.path.join(checkpoint_dir or self.logdir,
"checkpoint_{}".format(self._iteration))
if not os.path.exists(checkpoint_dir):
os.makedirs(checkpoin... | [
"Saves the current model state to a checkpoint.\n\n Subclasses should override ``_save()`` instead to save state.\n This method dumps additional metadata alongside the saved path.\n\n Args:\n checkpoint_dir (str): Optional dir to place the checkpoint.\n\n Returns:\n ... |
Please provide a description of the function:def save_to_object(self):
tmpdir = tempfile.mkdtemp("save_to_object", dir=self.logdir)
checkpoint_prefix = self.save(tmpdir)
data = {}
base_dir = os.path.dirname(checkpoint_prefix)
for path in os.listdir(base_dir):
... | [
"Saves the current model state to a Python object. It also\n saves to disk but does not return the checkpoint path.\n\n Returns:\n Object holding checkpoint data.\n "
] |
Please provide a description of the function:def restore(self, checkpoint_path):
with open(checkpoint_path + ".tune_metadata", "rb") as f:
metadata = pickle.load(f)
self._experiment_id = metadata["experiment_id"]
self._iteration = metadata["iteration"]
self._timeste... | [
"Restores training state from a given model checkpoint.\n\n These checkpoints are returned from calls to save().\n\n Subclasses should override ``_restore()`` instead to restore state.\n This method restores additional metadata saved with the checkpoint.\n "
] |
Please provide a description of the function:def restore_from_object(self, obj):
info = pickle.loads(obj)
data = info["data"]
tmpdir = tempfile.mkdtemp("restore_from_object", dir=self.logdir)
checkpoint_path = os.path.join(tmpdir, info["checkpoint_name"])
for file_name... | [
"Restores training state from a checkpoint object.\n\n These checkpoints are returned from calls to save_to_object().\n "
] |
Please provide a description of the function:def export_model(self, export_formats, export_dir=None):
export_dir = export_dir or self.logdir
return self._export_model(export_formats, export_dir) | [
"Exports model based on export_formats.\n\n Subclasses should override _export_model() to actually\n export model to local directory.\n\n Args:\n export_formats (list): List of formats that should be exported.\n export_dir (str): Optional dir to place the exported model.\n... |
Please provide a description of the function:def value(self, t):
fraction = min(float(t) / max(1, self.schedule_timesteps), 1.0)
return self.initial_p + fraction * (self.final_p - self.initial_p) | [
"See Schedule.value"
] |
Please provide a description of the function:def dump_json(json_info, json_file, overwrite=True):
if overwrite:
mode = "w"
else:
mode = "w+"
try:
with open(json_file, mode) as f:
f.write(json.dumps(json_info))
except BaseException as e:
logging.error(e.m... | [
"Dump a whole json record into the given file.\n\n Overwrite the file if the overwrite flag set.\n\n Args:\n json_info (dict): Information dict to be dumped.\n json_file (str): File path to be dumped to.\n overwrite(boolean)\n "
] |
Please provide a description of the function:def parse_json(json_file):
if not os.path.exists(json_file):
return None
try:
with open(json_file, "r") as f:
info_str = f.readlines()
info_str = "".join(info_str)
json_info = json.loads(info_str)
... | [
"Parse a whole json record from the given file.\n\n Return None if the json file does not exists or exception occurs.\n\n Args:\n json_file (str): File path to be parsed.\n\n Returns:\n A dict of json info.\n "
] |
Please provide a description of the function:def parse_multiple_json(json_file, offset=None):
json_info_list = []
if not os.path.exists(json_file):
return json_info_list
try:
with open(json_file, "r") as f:
if offset:
f.seek(offset)
for line in f... | [
"Parse multiple json records from the given file.\n\n Seek to the offset as the start point before parsing\n if offset set. return empty list if the json file does\n not exists or exception occurs.\n\n Args:\n json_file (str): File path to be parsed.\n offset (int): Initial seek position o... |
Please provide a description of the function:def unicode2str(content):
if isinstance(content, dict):
result = {}
for key in content.keys():
result[unicode2str(key)] = unicode2str(content[key])
return result
elif isinstance(content, list):
return [unicode2str(elem... | [
"Convert the unicode element of the content to str recursively."
] |
Please provide a description of the function:def loss(self, xs, ys):
return float(
self.sess.run(
self.cross_entropy, feed_dict={
self.x: xs,
self.y_: ys
})) | [
"Computes the loss of the network."
] |
Please provide a description of the function:def grad(self, xs, ys):
return self.sess.run(
self.cross_entropy_grads, feed_dict={
self.x: xs,
self.y_: ys
}) | [
"Computes the gradients of the network."
] |
Please provide a description of the function:def build_data(data_path, size, dataset):
image_size = 32
if dataset == "cifar10":
label_bytes = 1
label_offset = 0
elif dataset == "cifar100":
label_bytes = 1
label_offset = 1
depth = 3
image_bytes = image_size * imag... | [
"Creates the queue and preprocessing operations for the dataset.\n\n Args:\n data_path: Filename for cifar10 data.\n size: The number of images in the dataset.\n dataset: The dataset we are using.\n\n Returns:\n queue: A Tensorflow queue for extracting the images and labels.\n "... |
Please provide a description of the function:def build_input(data, batch_size, dataset, train):
image_size = 32
depth = 3
num_classes = 10 if dataset == "cifar10" else 100
images, labels = data
num_samples = images.shape[0] - images.shape[0] % batch_size
dataset = tf.contrib.data.Dataset.fr... | [
"Build CIFAR image and labels.\n\n Args:\n data_path: Filename for cifar10 data.\n batch_size: Input batch size.\n train: True if we are training and false if we are testing.\n\n Returns:\n images: Batches of images of size\n [batch_size, image_size, image_size, 3].\n ... |
Please provide a description of the function:def create_or_update(cluster_config_file, min_workers, max_workers, no_restart,
restart_only, yes, cluster_name):
if restart_only or no_restart:
assert restart_only != no_restart, "Cannot set both 'restart_only' " \
"and 'no_... | [
"Create or update a Ray cluster."
] |
Please provide a description of the function:def teardown(cluster_config_file, yes, workers_only, cluster_name):
teardown_cluster(cluster_config_file, yes, workers_only, cluster_name) | [
"Tear down the Ray cluster."
] |
Please provide a description of the function:def kill_random_node(cluster_config_file, yes, cluster_name):
click.echo("Killed node with IP " +
kill_node(cluster_config_file, yes, cluster_name)) | [
"Kills a random Ray node. For testing purposes only."
] |
Please provide a description of the function:def submit(cluster_config_file, docker, screen, tmux, stop, start,
cluster_name, port_forward, script, script_args):
assert not (screen and tmux), "Can specify only one of `screen` or `tmux`."
if start:
create_or_update_cluster(cluster_config... | [
"Uploads and runs a script on the specified cluster.\n\n The script is automatically synced to the following location:\n\n os.path.join(\"~\", os.path.basename(script))\n "
] |
Please provide a description of the function:def build_graph(self):
self.global_step = tf.Variable(0, trainable=False)
self._build_model()
if self.mode == "train":
self._build_train_op()
else:
# Additional initialization for the test network.
... | [
"Build a whole graph for the model."
] |
Please provide a description of the function:def _build_model(self):
with tf.variable_scope("init"):
x = self._conv("init_conv", self._images, 3, 3, 16,
self._stride_arr(1))
strides = [1, 2, 2]
activate_before_residual = [True, False, False]
... | [
"Build the core model within the graph."
] |
Please provide a description of the function:def _build_train_op(self):
num_gpus = self.hps.num_gpus if self.hps.num_gpus != 0 else 1
# The learning rate schedule is dependent on the number of gpus.
boundaries = [int(20000 * i / np.sqrt(num_gpus)) for i in range(2, 5)]
values = ... | [
"Build training specific ops for the graph."
] |
Please provide a description of the function:def _batch_norm(self, name, x):
with tf.variable_scope(name):
params_shape = [x.get_shape()[-1]]
beta = tf.get_variable(
"beta",
params_shape,
tf.float32,
initializer=tf... | [
"Batch normalization."
] |
Please provide a description of the function:def _decay(self):
costs = []
for var in tf.trainable_variables():
if var.op.name.find(r"DW") > 0:
costs.append(tf.nn.l2_loss(var))
return tf.multiply(self.hps.weight_decay_rate, tf.add_n(costs)) | [
"L2 weight decay loss."
] |
Please provide a description of the function:def _conv(self, name, x, filter_size, in_filters, out_filters, strides):
with tf.variable_scope(name):
n = filter_size * filter_size * out_filters
kernel = tf.get_variable(
"DW", [filter_size, filter_size, in_filters, ... | [
"Convolution."
] |
Please provide a description of the function:def _fully_connected(self, x, out_dim):
x = tf.reshape(x, [self.hps.batch_size, -1])
w = tf.get_variable(
"DW", [x.get_shape()[1], out_dim],
initializer=tf.uniform_unit_scaling_initializer(factor=1.0))
b = tf.get_varia... | [
"FullyConnected layer for final output."
] |
Please provide a description of the function:def _mac(model, obs, h):
B, n_agents = obs.size(0), obs.size(1)
obs_flat = obs.reshape([B * n_agents, -1])
h_flat = [s.reshape([B * n_agents, -1]) for s in h]
q_flat, _, _, h_flat = model.forward({"obs": obs_flat}, h_flat)
return q_flat.reshape(
... | [
"Forward pass of the multi-agent controller.\n\n Arguments:\n model: TorchModel class\n obs: Tensor of shape [B, n_agents, obs_size]\n h: List of tensors of shape [B, n_agents, h_size]\n\n Returns:\n q_vals: Tensor of shape [B, n_agents, n_actions]\n h: Tensor of shape [B, n... |
Please provide a description of the function:def forward(self, rewards, actions, terminated, mask, obs, action_mask):
B, T = obs.size(0), obs.size(1)
# Calculate estimated Q-Values
mac_out = []
h = [s.expand([B, self.n_agents, -1]) for s in self.model.state_init()]
for... | [
"Forward pass of the loss.\n\n Arguments:\n rewards: Tensor of shape [B, T-1, n_agents]\n actions: Tensor of shape [B, T-1, n_agents]\n terminated: Tensor of shape [B, T-1, n_agents]\n mask: Tensor of shape [B, T-1, n_agents]\n obs: Tensor of shape [B, T... |
Please provide a description of the function:def _unpack_observation(self, obs_batch):
unpacked = _unpack_obs(
np.array(obs_batch),
self.observation_space.original_space,
tensorlib=np)
if self.has_action_mask:
obs = np.concatenate(
... | [
"Unpacks the action mask / tuple obs from agent grouping.\n\n Returns:\n obs (Tensor): flattened obs tensor of shape [B, n_agents, obs_size]\n mask (Tensor): action mask, if any\n "
] |
Please provide a description of the function:def get_actor(name):
actor_name = _calculate_key(name)
pickled_state = _internal_kv_get(actor_name)
if pickled_state is None:
raise ValueError("The actor with name={} doesn't exist".format(name))
handle = pickle.loads(pickled_state)
return ha... | [
"Get a named actor which was previously created.\n\n If the actor doesn't exist, an exception will be raised.\n\n Args:\n name: The name of the named actor.\n\n Returns:\n The ActorHandle object corresponding to the name.\n "
] |
Please provide a description of the function:def register_actor(name, actor_handle):
if not isinstance(name, str):
raise TypeError("The name argument must be a string.")
if not isinstance(actor_handle, ray.actor.ActorHandle):
raise TypeError("The actor_handle argument must be an ActorHandle... | [
"Register a named actor under a string key.\n\n Args:\n name: The name of the named actor.\n actor_handle: The actor object to be associated with this name\n "
] |
Please provide a description of the function:def check_extraneous(config, schema):
if not isinstance(config, dict):
raise ValueError("Config {} is not a dictionary".format(config))
for k in config:
if k not in schema:
raise ValueError("Unexpected config key `{}` not in {}".forma... | [
"Make sure all items of config are in schema"
] |
Please provide a description of the function:def validate_config(config, schema=CLUSTER_CONFIG_SCHEMA):
if not isinstance(config, dict):
raise ValueError("Config {} is not a dictionary".format(config))
check_required(config, schema)
check_extraneous(config, schema) | [
"Required Dicts indicate that no extra fields can be introduced."
] |
Please provide a description of the function:def update(self, **kwargs):
for arg in kwargs:
if hasattr(self, arg):
setattr(self, arg, kwargs[arg])
else:
raise ValueError("Invalid RayParams parameter in"
" update: %... | [
"Update the settings according to the keyword arguments.\n\n Args:\n kwargs: The keyword arguments to set corresponding fields.\n "
] |
Please provide a description of the function:def update_if_absent(self, **kwargs):
for arg in kwargs:
if hasattr(self, arg):
if getattr(self, arg) is None:
setattr(self, arg, kwargs[arg])
else:
raise ValueError("Invalid RayPara... | [
"Update the settings when the target fields are None.\n\n Args:\n kwargs: The keyword arguments to set corresponding fields.\n "
] |
Please provide a description of the function:def compute_actor_handle_id(actor_handle_id, num_forks):
assert isinstance(actor_handle_id, ActorHandleID)
handle_id_hash = hashlib.sha1()
handle_id_hash.update(actor_handle_id.binary())
handle_id_hash.update(str(num_forks).encode("ascii"))
handle_id... | [
"Deterministically compute an actor handle ID.\n\n A new actor handle ID is generated when it is forked from another actor\n handle. The new handle ID is computed as hash(old_handle_id || num_forks).\n\n Args:\n actor_handle_id (common.ObjectID): The original actor handle ID.\n num_forks: The... |
Please provide a description of the function:def compute_actor_handle_id_non_forked(actor_handle_id, current_task_id):
assert isinstance(actor_handle_id, ActorHandleID)
assert isinstance(current_task_id, TaskID)
handle_id_hash = hashlib.sha1()
handle_id_hash.update(actor_handle_id.binary())
han... | [
"Deterministically compute an actor handle ID in the non-forked case.\n\n This code path is used whenever an actor handle is pickled and unpickled\n (for example, if a remote function closes over an actor handle). Then,\n whenever the actor handle is used, a new actor handle ID will be generated\n on th... |
Please provide a description of the function:def method(*args, **kwargs):
assert len(args) == 0
assert len(kwargs) == 1
assert "num_return_vals" in kwargs
num_return_vals = kwargs["num_return_vals"]
def annotate_method(method):
method.__ray_num_return_vals__ = num_return_vals
r... | [
"Annotate an actor method.\n\n .. code-block:: python\n\n @ray.remote\n class Foo(object):\n @ray.method(num_return_vals=2)\n def bar(self):\n return 1, 2\n\n f = Foo.remote()\n\n _, _ = f.bar.remote()\n\n Args:\n num_return_vals: The num... |
Please provide a description of the function:def exit_actor():
worker = ray.worker.global_worker
if worker.mode == ray.WORKER_MODE and not worker.actor_id.is_nil():
# Disconnect the worker from the raylet. The point of
# this is so that when the worker kills itself below, the
# rayl... | [
"Intentionally exit the current actor.\n\n This function is used to disconnect an actor and exit the worker.\n\n Raises:\n Exception: An exception is raised if this is a driver or this\n worker is not an actor.\n "
] |
Please provide a description of the function:def get_checkpoints_for_actor(actor_id):
checkpoint_info = ray.worker.global_state.actor_checkpoint_info(actor_id)
if checkpoint_info is None:
return []
checkpoints = [
Checkpoint(checkpoint_id, timestamp) for checkpoint_id, timestamp in
... | [
"Get the available checkpoints for the given actor ID, return a list\n sorted by checkpoint timestamp in descending order.\n "
] |
Please provide a description of the function:def remote(self, *args, **kwargs):
return self._remote(args=args, kwargs=kwargs) | [
"Create an actor.\n\n Args:\n args: These arguments are forwarded directly to the actor\n constructor.\n kwargs: These arguments are forwarded directly to the actor\n constructor.\n\n Returns:\n A handle to the newly created actor.\n ... |
Please provide a description of the function:def _remote(self,
args=None,
kwargs=None,
num_cpus=None,
num_gpus=None,
resources=None):
if args is None:
args = []
if kwargs is None:
kwargs = {}... | [
"Create an actor.\n\n This method allows more flexibility than the remote method because\n resource requirements can be specified and override the defaults in the\n decorator.\n\n Args:\n args: The arguments to forward to the actor constructor.\n kwargs: The keyword... |
Please provide a description of the function:def _actor_method_call(self,
method_name,
args=None,
kwargs=None,
num_return_vals=None):
worker = ray.worker.get_global_worker()
worker.check... | [
"Method execution stub for an actor handle.\n\n This is the function that executes when\n `actor.method_name.remote(*args, **kwargs)` is called. Instead of\n executing locally, the method is packaged as a task and scheduled\n to the remote actor instance.\n\n Args:\n me... |
Please provide a description of the function:def _serialization_helper(self, ray_forking):
if ray_forking:
actor_handle_id = compute_actor_handle_id(
self._ray_actor_handle_id, self._ray_actor_forks)
else:
actor_handle_id = self._ray_actor_handle_id
... | [
"This is defined in order to make pickling work.\n\n Args:\n ray_forking: True if this is being called because Ray is forking\n the actor handle and false if it is being called by pickling.\n\n Returns:\n A dictionary of the information needed to reconstruct the ob... |
Please provide a description of the function:def _deserialization_helper(self, state, ray_forking):
worker = ray.worker.get_global_worker()
worker.check_connected()
if state["ray_forking"]:
actor_handle_id = state["actor_handle_id"]
else:
# Right now, if... | [
"This is defined in order to make pickling work.\n\n Args:\n state: The serialized state of the actor handle.\n ray_forking: True if this is being called because Ray is forking\n the actor handle and false if it is being called by pickling.\n "
] |
Please provide a description of the function:def load_data(self, sess, inputs, state_inputs):
if log_once("load_data"):
logger.info(
"Training on concatenated sample batches:\n\n{}\n".format(
summarize({
"placeholders": self.loss_... | [
"Bulk loads the specified inputs into device memory.\n\n The shape of the inputs must conform to the shapes of the input\n placeholders this optimizer was constructed with.\n\n The data is split equally across all the devices. If the data is not\n evenly divisible by the batch size, exce... |
Please provide a description of the function:def optimize(self, sess, batch_index):
feed_dict = {
self._batch_index: batch_index,
self._per_device_batch_size: self._loaded_per_device_batch_size,
self._max_seq_len: self._loaded_max_seq_len,
}
for tower... | [
"Run a single step of SGD.\n\n Runs a SGD step over a slice of the preloaded batch with size given by\n self._loaded_per_device_batch_size and offset given by the batch_index\n argument.\n\n Updates shared model weights based on the averaged per-device\n gradients.\n\n Args... |
Please provide a description of the function:def _next_generation(self, sorted_trials):
candidate = []
next_generation = []
num_population = self._next_population_size(len(sorted_trials))
top_num = int(max(num_population * self._keep_top_ratio, 2))
for i in range(top_n... | [
"Generate genes (encodings) for the next generation.\n\n Use the top K (_keep_top_ratio) trials of the last generation\n as candidates to generate the next generation. The action could\n be selection, crossover and mutation according corresponding\n ratio (_selection_bound, _crossover_bo... |
Please provide a description of the function:def _selection(candidate):
sample_index1 = np.random.choice(len(candidate))
sample_index2 = np.random.choice(len(candidate))
sample_1 = candidate[sample_index1]
sample_2 = candidate[sample_index2]
select_index = np.random.choi... | [
"Perform selection action to candidates.\n\n For example, new gene = sample_1 + the 5th bit of sample2.\n\n Args:\n candidate: List of candidate genes (encodings).\n\n Examples:\n >>> # Genes that represent 3 parameters\n >>> gene1 = np.array([[0, 0, 1], [0, 1],... |
Please provide a description of the function:def _crossover(candidate):
sample_index1 = np.random.choice(len(candidate))
sample_index2 = np.random.choice(len(candidate))
sample_1 = candidate[sample_index1]
sample_2 = candidate[sample_index2]
cross_index = int(len(sample_... | [
"Perform crossover action to candidates.\n\n For example, new gene = 60% sample_1 + 40% sample_2.\n\n Args:\n candidate: List of candidate genes (encodings).\n\n Examples:\n >>> # Genes that represent 3 parameters\n >>> gene1 = np.array([[0, 0, 1], [0, 1], [1, 0... |
Please provide a description of the function:def _mutation(candidate, rate=0.1):
sample_index = np.random.choice(len(candidate))
sample = candidate[sample_index]
idx_list = []
for i in range(int(max(len(sample) * rate, 1))):
idx = np.random.choice(len(sample))
... | [
"Perform mutation action to candidates.\n\n For example, randomly change 10% of original sample\n\n Args:\n candidate: List of candidate genes (encodings).\n rate: Percentage of mutation bits\n\n Examples:\n >>> # Genes that represent 3 parameters\n >... |
Please provide a description of the function:def list_trials(experiment_path, sort, output, filter_op, columns,
result_columns):
if columns:
columns = columns.split(",")
if result_columns:
result_columns = result_columns.split(",")
commands.list_trials(experiment_path, s... | [
"Lists trials in the directory subtree starting at the given path."
] |
Please provide a description of the function:def list_experiments(project_path, sort, output, filter_op, columns):
if columns:
columns = columns.split(",")
commands.list_experiments(project_path, sort, output, filter_op, columns) | [
"Lists experiments in the directory subtree."
] |
Please provide a description of the function:def _train(self, trial):
assert trial.status == Trial.RUNNING, trial.status
remote = trial.runner.train.remote()
# Local Mode
if isinstance(remote, dict):
remote = _LocalWrapper(remote)
self._running[remote] = t... | [
"Start one iteration of training and save remote id."
] |
Please provide a description of the function:def _start_trial(self, trial, checkpoint=None):
prior_status = trial.status
self.set_status(trial, Trial.RUNNING)
trial.runner = self._setup_runner(
trial,
reuse_allowed=checkpoint is not None
or trial._che... | [
"Starts trial and restores last result if trial was paused.\n\n Raises:\n ValueError if restoring from checkpoint fails.\n "
] |
Please provide a description of the function:def _stop_trial(self, trial, error=False, error_msg=None,
stop_logger=True):
if stop_logger:
trial.close_logger()
if error:
self.set_status(trial, Trial.ERROR)
else:
self.set_status(tr... | [
"Stops this trial.\n\n Stops this trial, releasing all allocating resources. If stopping the\n trial fails, the run will be marked as terminated in error, but no\n exception will be thrown.\n\n Args:\n error (bool): Whether to mark this trial as terminated in error.\n ... |
Please provide a description of the function:def start_trial(self, trial, checkpoint=None):
self._commit_resources(trial.resources)
try:
self._start_trial(trial, checkpoint)
except Exception as e:
logger.exception("Error starting runner for Trial %s", str(trial)... | [
"Starts the trial.\n\n Will not return resources if trial repeatedly fails on start.\n\n Args:\n trial (Trial): Trial to be started.\n checkpoint (Checkpoint): A Python object or path storing the state\n of trial.\n "
] |
Please provide a description of the function:def stop_trial(self, trial, error=False, error_msg=None, stop_logger=True):
prior_status = trial.status
self._stop_trial(
trial, error=error, error_msg=error_msg, stop_logger=stop_logger)
if prior_status == Trial.RUNNING:
... | [
"Only returns resources if resources allocated."
] |
Please provide a description of the function:def pause_trial(self, trial):
trial_future = self._find_item(self._running, trial)
if trial_future:
self._paused[trial_future[0]] = trial
super(RayTrialExecutor, self).pause_trial(trial) | [
"Pauses the trial.\n\n If trial is in-flight, preserves return value in separate queue\n before pausing, which is restored when Trial is resumed.\n "
] |
Please provide a description of the function:def reset_trial(self, trial, new_config, new_experiment_tag):
trial.experiment_tag = new_experiment_tag
trial.config = new_config
trainable = trial.runner
with warn_if_slow("reset_config"):
reset_val = ray.get(trainable.re... | [
"Tries to invoke `Trainable.reset_config()` to reset trial.\n\n Args:\n trial (Trial): Trial to be reset.\n new_config (dict): New configuration for Trial\n trainable.\n new_experiment_tag (str): New experiment name\n for trial.\n\n Return... |
Please provide a description of the function:def fetch_result(self, trial):
trial_future = self._find_item(self._running, trial)
if not trial_future:
raise ValueError("Trial was not running.")
self._running.pop(trial_future[0])
with warn_if_slow("fetch_result"):
... | [
"Fetches one result of the running trials.\n\n Returns:\n Result of the most recent trial training run."
] |
Please provide a description of the function:def has_resources(self, resources):
if time.time() - self._last_resource_refresh > self._refresh_period:
self._update_avail_resources()
currently_available = Resources.subtract(self._avail_resources,
... | [
"Returns whether this runner has at least the specified resources.\n\n This refreshes the Ray cluster resources if the time since last update\n has exceeded self._refresh_period. This also assumes that the\n cluster is not resizing very frequently.\n "
] |
Please provide a description of the function:def debug_string(self):
if self._resources_initialized:
status = "Resources requested: {}/{} CPUs, {}/{} GPUs".format(
self._committed_resources.cpu, self._avail_resources.cpu,
self._committed_resources.gpu, self.... | [
"Returns a human readable message for printing to the console."
] |
Please provide a description of the function:def resource_string(self):
if self._resources_initialized:
res_str = "{} CPUs, {} GPUs".format(self._avail_resources.cpu,
self._avail_resources.gpu)
if self._avail_resources.custom_reso... | [
"Returns a string describing the total resources available."
] |
Please provide a description of the function:def save(self, trial, storage=Checkpoint.DISK):
trial._checkpoint.storage = storage
trial._checkpoint.last_result = trial.last_result
if storage == Checkpoint.MEMORY:
trial._checkpoint.value = trial.runner.save_to_object.remote()
... | [
"Saves the trial's state to a checkpoint."
] |
Please provide a description of the function:def _checkpoint_and_erase(self, trial):
with warn_if_slow("save_to_disk"):
trial._checkpoint.value = ray.get(trial.runner.save.remote())
if len(trial.history) >= trial.keep_checkpoints_num:
ray.get(trial.runner.delete_checkp... | [
"Checkpoints the model and erases old checkpoints\n if needed.\n Parameters\n ----------\n trial : trial to save\n "
] |
Please provide a description of the function:def restore(self, trial, checkpoint=None):
if checkpoint is None or checkpoint.value is None:
checkpoint = trial._checkpoint
if checkpoint is None or checkpoint.value is None:
return True
if trial.runner is None:
... | [
"Restores training state from a given model checkpoint.\n\n This will also sync the trial results to a new location\n if restoring on a different node.\n "
] |
Please provide a description of the function:def export_trial_if_needed(self, trial):
if trial.export_formats and len(trial.export_formats) > 0:
return ray.get(
trial.runner.export_model.remote(trial.export_formats))
return {} | [
"Exports model of this trial based on trial.export_formats.\n\n Return:\n A dict that maps ExportFormats to successfully exported models.\n "
] |
Please provide a description of the function:def __generate_actor(self, instance_id, operator, input, output):
actor_id = (operator.id, instance_id)
# Record the physical dataflow graph (for debugging purposes)
self.__add_channel(actor_id, input, output)
# Select actor to constr... | [
"Generates an actor that will execute a particular instance of\n the logical operator\n\n Attributes:\n instance_id (UUID): The id of the instance the actor will execute.\n operator (Operator): The metadata of the logical operator.\n input (DataInput): The input gate t... |
Please provide a description of the function:def __generate_actors(self, operator, upstream_channels,
downstream_channels):
num_instances = operator.num_instances
logger.info("Generating {} actors of type {}...".format(
num_instances, operator.type))
... | [
"Generates one actor for each instance of the given logical\n operator.\n\n Attributes:\n operator (Operator): The logical operator metadata.\n upstream_channels (list): A list of all upstream channels for\n all instances of the operator.\n downstream_channe... |
Please provide a description of the function:def _generate_channels(self, operator):
channels = {} # destination operator id -> channels
strategies = operator.partitioning_strategies
for dst_operator, p_scheme in strategies.items():
num_dest_instances = self.operators[dst_o... | [
"Generates all output data channels\n (see: DataChannel in communication.py) for all instances of\n the given logical operator.\n\n The function constructs one data channel for each pair of\n communicating operator instances (instance_1,instance_2),\n where instance_1 is an instan... |
Please provide a description of the function:def execute(self):
self._collect_garbage() # Make sure everything is clean
# TODO (john): Check if dataflow has any 'logical inconsistencies'
# For example, if there is a forward partitioning strategy but
# the number of downstream i... | [
"Deploys and executes the physical dataflow."
] |
Please provide a description of the function:def __register(self, operator):
self.env.operators[operator.id] = operator
self.dst_operator_id = operator.id
logger.debug("Adding new dataflow edge ({},{}) --> ({},{})".format(
self.src_operator_id,
self.env.operators... | [
"Registers the given logical operator to the environment and\n connects it to its upstream operator (if any).\n\n A call to this function adds a new edge to the logical topology.\n\n Attributes:\n operator (Operator): The metadata of the logical operator.\n "
] |
Please provide a description of the function:def set_parallelism(self, num_instances):
assert (num_instances > 0)
self.env._set_parallelism(self.src_operator_id, num_instances)
return self | [
"Sets the number of instances for the source operator of the stream.\n\n Attributes:\n num_instances (int): The level of parallelism for the source\n operator of the stream.\n "
] |
Please provide a description of the function:def map(self, map_fn, name="Map"):
op = Operator(
_generate_uuid(),
OpType.Map,
name,
map_fn,
num_instances=self.env.config.parallelism)
return self.__register(op) | [
"Applies a map operator to the stream.\n\n Attributes:\n map_fn (function): The user-defined logic of the map.\n "
] |
Please provide a description of the function:def flat_map(self, flatmap_fn):
op = Operator(
_generate_uuid(),
OpType.FlatMap,
"FlatMap",
flatmap_fn,
num_instances=self.env.config.parallelism)
return self.__register(op) | [
"Applies a flatmap operator to the stream.\n\n Attributes:\n flatmap_fn (function): The user-defined logic of the flatmap\n (e.g. split()).\n "
] |
Please provide a description of the function:def key_by(self, key_selector):
op = Operator(
_generate_uuid(),
OpType.KeyBy,
"KeyBy",
other=key_selector,
num_instances=self.env.config.parallelism)
return self.__register(op) | [
"Applies a key_by operator to the stream.\n\n Attributes:\n key_attribute_index (int): The index of the key attributed\n (assuming tuple records).\n "
] |
Please provide a description of the function:def reduce(self, reduce_fn):
op = Operator(
_generate_uuid(),
OpType.Reduce,
"Sum",
reduce_fn,
num_instances=self.env.config.parallelism)
return self.__register(op) | [
"Applies a rolling sum operator to the stream.\n\n Attributes:\n sum_attribute_index (int): The index of the attribute to sum\n (assuming tuple records).\n "
] |
Please provide a description of the function:def sum(self, attribute_selector, state_keeper=None):
op = Operator(
_generate_uuid(),
OpType.Sum,
"Sum",
_sum,
other=attribute_selector,
state_actor=state_keeper,
num_instan... | [
"Applies a rolling sum operator to the stream.\n\n Attributes:\n sum_attribute_index (int): The index of the attribute to sum\n (assuming tuple records).\n "
] |
Please provide a description of the function:def time_window(self, window_width_ms):
op = Operator(
_generate_uuid(),
OpType.TimeWindow,
"TimeWindow",
num_instances=self.env.config.parallelism,
other=window_width_ms)
return self.__regi... | [
"Applies a system time window to the stream.\n\n Attributes:\n window_width_ms (int): The length of the window in ms.\n "
] |
Please provide a description of the function:def filter(self, filter_fn):
op = Operator(
_generate_uuid(),
OpType.Filter,
"Filter",
filter_fn,
num_instances=self.env.config.parallelism)
return self.__register(op) | [
"Applies a filter to the stream.\n\n Attributes:\n filter_fn (function): The user-defined filter function.\n "
] |
Please provide a description of the function:def inspect(self, inspect_logic):
op = Operator(
_generate_uuid(),
OpType.Inspect,
"Inspect",
inspect_logic,
num_instances=self.env.config.parallelism)
return self.__register(op) | [
"Inspects the content of the stream.\n\n Attributes:\n inspect_logic (function): The user-defined inspect function.\n "
] |
Please provide a description of the function:def sink(self):
op = Operator(
_generate_uuid(),
OpType.Sink,
"Sink",
num_instances=self.env.config.parallelism)
return self.__register(op) | [
"Closes the stream with a sink operator."
] |
Please provide a description of the function:def close_all_files(self):
while len(self.open_file_infos) > 0:
file_info = self.open_file_infos.pop(0)
file_info.file_handle.close()
file_info.file_handle = None
self.closed_file_infos.append(file_info)
... | [
"Close all open files (so that we can open more)."
] |
Please provide a description of the function:def update_log_filenames(self):
log_filenames = os.listdir(self.logs_dir)
for log_filename in log_filenames:
full_path = os.path.join(self.logs_dir, log_filename)
if full_path not in self.log_filenames:
self.l... | [
"Update the list of log files to monitor."
] |
Please provide a description of the function:def open_closed_files(self):
if not self.can_open_more_files:
# If we can't open any more files. Close all of the files.
self.close_all_files()
files_with_no_updates = []
while len(self.closed_file_infos) > 0:
... | [
"Open some closed files if they may have new lines.\n\n Opening more files may require us to close some of the already open\n files.\n "
] |
Please provide a description of the function:def check_log_files_and_publish_updates(self):
anything_published = False
for file_info in self.open_file_infos:
assert not file_info.file_handle.closed
lines_to_publish = []
max_num_lines_to_read = 100
... | [
"Get any changes to the log files and push updates to Redis.\n\n Returns:\n True if anything was published and false otherwise.\n "
] |
Please provide a description of the function:def run(self):
while True:
self.update_log_filenames()
self.open_closed_files()
anything_published = self.check_log_files_and_publish_updates()
# If nothing was published, then wait a little bit before checking... | [
"Run the log monitor.\n\n This will query Redis once every second to check if there are new log\n files to monitor. It will also store those log files in Redis.\n "
] |
Please provide a description of the function:def add_configurations(self, experiments):
experiment_list = convert_to_experiment_list(experiments)
for experiment in experiment_list:
self._trial_generator = itertools.chain(
self._trial_generator,
self._... | [
"Chains generator given experiment specifications.\n\n Arguments:\n experiments (Experiment | list | dict): Experiments to run.\n "
] |
Please provide a description of the function:def next_trials(self):
trials = []
for trial in self._trial_generator:
if trial is None:
return trials
trials += [trial]
self._finished = True
return trials | [
"Provides a batch of Trial objects to be queued into the TrialRunner.\n\n A batch ends when self._trial_generator returns None.\n\n Returns:\n trials (list): Returns a list of trials.\n "
] |
Please provide a description of the function:def _generate_trials(self, experiment_spec, output_path=""):
if "run" not in experiment_spec:
raise TuneError("Must specify `run` in {}".format(experiment_spec))
for _ in range(experiment_spec.get("num_samples", 1)):
trial_id ... | [
"Generates trials with configurations from `_suggest`.\n\n Creates a trial_id that is passed into `_suggest`.\n\n Yields:\n Trial objects constructed according to `spec`\n "
] |
Please provide a description of the function:def generate_variants(unresolved_spec):
for resolved_vars, spec in _generate_variants(unresolved_spec):
assert not _unresolved_values(spec)
yield format_vars(resolved_vars), spec | [
"Generates variants from a spec (dict) with unresolved values.\n\n There are two types of unresolved values:\n\n Grid search: These define a grid search over values. For example, the\n following grid search values in a spec will produce six distinct\n variants in combination:\n\n ... |
Please provide a description of the function:def resolve_nested_dict(nested_dict):
res = {}
for k, v in nested_dict.items():
if isinstance(v, dict):
for k_, v_ in resolve_nested_dict(v).items():
res[(k, ) + k_] = v_
else:
res[(k, )] = v
return res | [
"Flattens a nested dict by joining keys into tuple of paths.\n\n Can then be passed into `format_vars`.\n "
] |
Please provide a description of the function:def run_board(args):
init_config(args)
# backend service, should import after django settings initialized
from backend.collector import CollectorService
service = CollectorService(
args.logdir,
args.reload_interval,
standalone=F... | [
"\n Run main entry for AutoMLBoard.\n\n Args:\n args: args parsed from command line\n "
] |
Please provide a description of the function:def init_config(args):
os.environ["AUTOMLBOARD_LOGDIR"] = args.logdir
os.environ["AUTOMLBOARD_LOGLEVEL"] = args.log_level
os.environ["AUTOMLBOARD_RELOAD_INTERVAL"] = str(args.reload_interval)
if args.db:
try:
db_address_reg = re.comp... | [
"\n Initialize configs of the service.\n\n Do the following things:\n 1. automl board settings\n 2. database settings\n 3. django settings\n "
] |
Please provide a description of the function:def get_gpu_ids():
if _mode() == LOCAL_MODE:
raise Exception("ray.get_gpu_ids() currently does not work in PYTHON "
"MODE.")
all_resource_ids = global_worker.raylet_client.resource_ids()
assigned_ids = [
resource_id f... | [
"Get the IDs of the GPUs that are available to the worker.\n\n If the CUDA_VISIBLE_DEVICES environment variable was set when the worker\n started up, then the IDs returned by this method will be a subset of the\n IDs in CUDA_VISIBLE_DEVICES. If not, the IDs will fall in the range\n [0, NUM_GPUS - 1], wh... |
Please provide a description of the function:def error_info():
worker = global_worker
worker.check_connected()
return (global_state.error_messages(driver_id=worker.task_driver_id) +
global_state.error_messages(driver_id=DriverID.nil())) | [
"Return information about failed tasks."
] |
Please provide a description of the function:def _initialize_serialization(driver_id, worker=global_worker):
serialization_context = pyarrow.default_serialization_context()
# Tell the serialization context to use the cloudpickle version that we
# ship with Ray.
serialization_context.set_pickle(pick... | [
"Initialize the serialization library.\n\n This defines a custom serializer for object IDs and also tells ray to\n serialize several exception classes that we define for error handling.\n "
] |
Please provide a description of the function:def init(redis_address=None,
num_cpus=None,
num_gpus=None,
resources=None,
object_store_memory=None,
redis_max_memory=None,
log_to_driver=True,
node_ip_address=None,
object_id_seed=None,
local_m... | [
"Connect to an existing Ray cluster or start one and connect to it.\n\n This method handles two cases. Either a Ray cluster already exists and we\n just attach this driver to it, or we start all of the processes associated\n with a Ray cluster and attach to the newly started cluster.\n\n To start Ray an... |
Please provide a description of the function:def shutdown(exiting_interpreter=False):
if exiting_interpreter and global_worker.mode == SCRIPT_MODE:
# This is a duration to sleep before shutting down everything in order
# to make sure that log messages finish printing.
time.sleep(0.5)
... | [
"Disconnect the worker, and terminate processes started by ray.init().\n\n This will automatically run at the end when a Python process that uses Ray\n exits. It is ok to run this twice in a row. The primary use case for this\n function is to cleanup state between tests.\n\n Note that this will clear an... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.