Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def get_flat_size(self):
return sum(
np.prod(v.get_shape().as_list()) for v in self.variables.values()) | [
"Returns the total length of all of the flattened variables.\n\n Returns:\n The length of all flattened variables concatenated.\n "
] |
Please provide a description of the function:def get_flat(self):
self._check_sess()
return np.concatenate([
v.eval(session=self.sess).flatten()
for v in self.variables.values()
]) | [
"Gets the weights and returns them as a flat array.\n\n Returns:\n 1D Array containing the flattened weights.\n "
] |
Please provide a description of the function:def set_flat(self, new_weights):
self._check_sess()
shapes = [v.get_shape().as_list() for v in self.variables.values()]
arrays = unflatten(new_weights, shapes)
placeholders = [
self.placeholders[k] for k, v in self.variabl... | [
"Sets the weights to new_weights, converting from a flat array.\n\n Note:\n You can only set all weights in the network using this function,\n i.e., the length of the array must match get_flat_size.\n\n Args:\n new_weights (np.ndarray): Flat array containing weights.\n... |
Please provide a description of the function:def get_weights(self):
self._check_sess()
return {
k: v.eval(session=self.sess)
for k, v in self.variables.items()
} | [
"Returns a dictionary containing the weights of the network.\n\n Returns:\n Dictionary mapping variable names to their weights.\n "
] |
Please provide a description of the function:def set_weights(self, new_weights):
self._check_sess()
assign_list = [
self.assignment_nodes[name] for name in new_weights.keys()
if name in self.assignment_nodes
]
assert assign_list, ("No variables in the inp... | [
"Sets the weights to new_weights.\n\n Note:\n Can set subsets of variables as well, by only passing in the\n variables you want to be set.\n\n Args:\n new_weights (Dict): Dictionary mapping variable names to their\n weights.\n "
] |
Please provide a description of the function:def construct_error_message(driver_id, error_type, message, timestamp):
builder = flatbuffers.Builder(0)
driver_offset = builder.CreateString(driver_id.binary())
error_type_offset = builder.CreateString(error_type)
message_offset = builder.CreateString(m... | [
"Construct a serialized ErrorTableData object.\n\n Args:\n driver_id: The ID of the driver that the error should go to. If this is\n nil, then the error will go to all drivers.\n error_type: The type of the error.\n message: The error message.\n timestamp: The time of the e... |
Please provide a description of the function:def init():
loop = asyncio.get_event_loop()
if loop.is_running():
raise Exception("You must initialize the Ray async API by calling "
"async_api.init() or async_api.as_future(obj) before "
"the event loop s... | [
"\n Initialize synchronously.\n "
] |
Please provide a description of the function:def shutdown():
global handler, transport, protocol
if handler is not None:
handler.close()
transport.close()
handler = None
transport = None
protocol = None | [
"Manually shutdown the async API.\n\n Cancels all related tasks and all the socket transportation.\n "
] |
Please provide a description of the function:def flush_redis_unsafe(redis_client=None):
if redis_client is None:
ray.worker.global_worker.check_connected()
redis_client = ray.worker.global_worker.redis_client
# Delete the log files from the primary Redis shard.
keys = redis_client.keys... | [
"This removes some non-critical state from the primary Redis shard.\n\n This removes the log files as well as the event log from Redis. This can\n be used to try to address out-of-memory errors caused by the accumulation\n of metadata in Redis. However, it will only partially address the issue as\n much... |
Please provide a description of the function:def flush_task_and_object_metadata_unsafe():
ray.worker.global_worker.check_connected()
def flush_shard(redis_client):
# Flush the task table. Note that this also flushes the driver tasks
# which may be undesirable.
num_task_keys_deleted... | [
"This removes some critical state from the Redis shards.\n\n In a multitenant environment, this will flush metadata for all jobs, which\n may be undesirable.\n\n This removes all of the object and task metadata. This can be used to try\n to address out-of-memory errors caused by the accumulation of meta... |
Please provide a description of the function:def flush_finished_tasks_unsafe():
ray.worker.global_worker.check_connected()
for shard_index in range(len(ray.global_state.redis_clients)):
_flush_finished_tasks_unsafe_shard(shard_index) | [
"This removes some critical state from the Redis shards.\n\n In a multitenant environment, this will flush metadata for all jobs, which\n may be undesirable.\n\n This removes all of the metadata for finished tasks. This can be used to\n try to address out-of-memory errors caused by the accumulation of m... |
Please provide a description of the function:def flush_evicted_objects_unsafe():
ray.worker.global_worker.check_connected()
for shard_index in range(len(ray.global_state.redis_clients)):
_flush_evicted_objects_unsafe_shard(shard_index) | [
"This removes some critical state from the Redis shards.\n\n In a multitenant environment, this will flush metadata for all jobs, which\n may be undesirable.\n\n This removes all of the metadata for objects that have been evicted. This\n can be used to try to address out-of-memory errors caused by the\n... |
Please provide a description of the function:def copy(self, existing_inputs):
return PPOPolicyGraph(
self.observation_space,
self.action_space,
self.config,
existing_inputs=existing_inputs) | [
"Creates a copy of self using existing input placeholders."
] |
Please provide a description of the function:def deepnn(x):
# Reshape to use within a convolutional neural net.
# Last dimension is for "features" - there is only one here, since images
# are grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc.
with tf.name_scope("reshape"):
x_imag... | [
"deepnn builds the graph for a deep net for classifying digits.\n\n Args:\n x: an input tensor with the dimensions (N_examples, 784), where 784 is\n the number of pixels in a standard MNIST image.\n\n Returns:\n A tuple (y, keep_prob). y is a tensor of shape (N_examples, 10), with\n ... |
Please provide a description of the function:def get_signature_params(func):
# The first condition for Cython functions, the latter for Cython instance
# methods
if is_cython(func):
attrs = [
"__code__", "__annotations__", "__defaults__", "__kwdefaults__"
]
if all(h... | [
"Get signature parameters\n\n Support Cython functions by grabbing relevant attributes from the Cython\n function and attaching to a no-op function. This is somewhat brittle, since\n funcsigs may change, but given that funcsigs is written to a PEP, we hope\n it is relatively stable. Future versions of P... |
Please provide a description of the function:def check_signature_supported(func, warn=False):
function_name = func.__name__
sig_params = get_signature_params(func)
has_kwargs_param = False
has_kwonly_param = False
for keyword_name, parameter in sig_params:
if parameter.kind == Paramete... | [
"Check if we support the signature of this function.\n\n We currently do not allow remote functions to have **kwargs. We also do not\n support keyword arguments in conjunction with a *args argument.\n\n Args:\n func: The function whose signature should be checked.\n warn: If this is true, a w... |
Please provide a description of the function:def extract_signature(func, ignore_first=False):
sig_params = get_signature_params(func)
if ignore_first:
if len(sig_params) == 0:
raise Exception("Methods must take a 'self' argument, but the "
"method '{}' does ... | [
"Extract the function signature from the function.\n\n Args:\n func: The function whose signature should be extracted.\n ignore_first: True if the first argument should be ignored. This should\n be used when func is a method of a class.\n\n Returns:\n A function signature objec... |
Please provide a description of the function:def extend_args(function_signature, args, kwargs):
arg_names = function_signature.arg_names
arg_defaults = function_signature.arg_defaults
arg_is_positionals = function_signature.arg_is_positionals
keyword_names = function_signature.keyword_names
fun... | [
"Extend the arguments that were passed into a function.\n\n This extends the arguments that were passed into a function with the\n default arguments provided in the function definition.\n\n Args:\n function_signature: The function signature of the function being\n called.\n args: T... |
Please provide a description of the function:def wait_for_crm_operation(operation):
logger.info("wait_for_crm_operation: "
"Waiting for operation {} to finish...".format(operation))
for _ in range(MAX_POLLS):
result = crm.operations().get(name=operation["name"]).execute()
i... | [
"Poll for cloud resource manager operation until finished."
] |
Please provide a description of the function:def wait_for_compute_global_operation(project_name, operation):
logger.info("wait_for_compute_global_operation: "
"Waiting for operation {} to finish...".format(
operation["name"]))
for _ in range(MAX_POLLS):
result =... | [
"Poll for global compute operation until finished."
] |
Please provide a description of the function:def key_pair_name(i, region, project_id, ssh_user):
key_name = "{}_gcp_{}_{}_{}".format(RAY, region, project_id, ssh_user, i)
return key_name | [
"Returns the ith default gcp_key_pair_name."
] |
Please provide a description of the function:def key_pair_paths(key_name):
public_key_path = os.path.expanduser("~/.ssh/{}.pub".format(key_name))
private_key_path = os.path.expanduser("~/.ssh/{}.pem".format(key_name))
return public_key_path, private_key_path | [
"Returns public and private key paths for a given key_name."
] |
Please provide a description of the function:def generate_rsa_key_pair():
key = rsa.generate_private_key(
backend=default_backend(), public_exponent=65537, key_size=2048)
public_key = key.public_key().public_bytes(
serialization.Encoding.OpenSSH,
serialization.PublicFormat.OpenSSH... | [
"Create public and private ssh-keys."
] |
Please provide a description of the function:def _configure_project(config):
project_id = config["provider"].get("project_id")
assert config["provider"]["project_id"] is not None, (
"'project_id' must be set in the 'provider' section of the autoscaler"
" config. Notice that the project id m... | [
"Setup a Google Cloud Platform Project.\n\n Google Compute Platform organizes all the resources, such as storage\n buckets, users, and instances under projects. This is different from\n aws ec2 where everything is global.\n "
] |
Please provide a description of the function:def _configure_iam_role(config):
email = SERVICE_ACCOUNT_EMAIL_TEMPLATE.format(
account_id=DEFAULT_SERVICE_ACCOUNT_ID,
project_id=config["provider"]["project_id"])
service_account = _get_service_account(email, config)
if service_account is N... | [
"Setup a gcp service account with IAM roles.\n\n Creates a gcp service acconut and binds IAM roles which allow it to control\n control storage/compute services. Specifically, the head node needs to have\n an IAM role that allows it to create further gce instances and store items\n in google cloud storag... |
Please provide a description of the function:def _configure_key_pair(config):
if "ssh_private_key" in config["auth"]:
return config
ssh_user = config["auth"]["ssh_user"]
project = compute.projects().get(
project=config["provider"]["project_id"]).execute()
# Key pairs associated ... | [
"Configure SSH access, using an existing key pair if possible.\n\n Creates a project-wide ssh key that can be used to access all the instances\n unless explicitly prohibited by instance config.\n\n The ssh-keys created by ray are of format:\n\n [USERNAME]:ssh-rsa [KEY_VALUE] [USERNAME]\n\n where:\n... |
Please provide a description of the function:def _configure_subnet(config):
# Rationale: avoid subnet lookup if the network is already
# completely manually configured
if ("networkInterfaces" in config["head_node"]
and "networkInterfaces" in config["worker_nodes"]):
return config
... | [
"Pick a reasonable subnet if not specified by the config."
] |
Please provide a description of the function:def _add_iam_policy_binding(service_account, roles):
project_id = service_account["projectId"]
email = service_account["email"]
member_id = "serviceAccount:" + email
policy = crm.projects().getIamPolicy(resource=project_id).execute()
already_config... | [
"Add new IAM roles for the service account."
] |
Please provide a description of the function:def _create_project_ssh_key_pair(project, public_key, ssh_user):
key_parts = public_key.split(" ")
# Sanity checks to make sure that the generated key matches expectation
assert len(key_parts) == 2, key_parts
assert key_parts[0] == "ssh-rsa", key_parts... | [
"Inserts an ssh-key into project commonInstanceMetadata"
] |
Please provide a description of the function:def _remote(self,
args=None,
kwargs=None,
num_return_vals=None,
num_cpus=None,
num_gpus=None,
resources=None):
worker = ray.worker.get_global_worker()
wor... | [
"An experimental alternate way to submit remote functions."
] |
Please provide a description of the function:def append(self, future):
future.prev = self.tail
if self.tail is None:
assert self.head is None
self.head = future
else:
self.tail.next = future
self.tail = future
# Once done, it will be r... | [
"Append an object to the linked list.\n\n Args:\n future (PlasmaObjectFuture): A PlasmaObjectFuture instance.\n "
] |
Please provide a description of the function:def remove(self, future):
if self._loop.get_debug():
logger.debug("Removing %s from the linked list.", future)
if future.prev is None:
assert future is self.head
self.head = future.next
if self.head is ... | [
"Remove an object from the linked list.\n\n Args:\n future (PlasmaObjectFuture): A PlasmaObjectFuture instance.\n "
] |
Please provide a description of the function:def cancel(self, *args, **kwargs):
# Because remove all futures will trigger `set_result`,
# we cancel itself first.
super().cancel()
for future in self.traverse():
# All cancelled futures should have callbacks to removed ... | [
"Manually cancel all tasks assigned to this event loop."
] |
Please provide a description of the function:def set_result(self, result):
for future in self.traverse():
# All cancelled futures should have callbacks to removed itself
# from this linked list. However, these callbacks are scheduled in
# an event loop, so we could s... | [
"Complete all tasks. "
] |
Please provide a description of the function:def traverse(self):
current = self.head
while current is not None:
yield current
current = current.next | [
"Traverse this linked list.\n\n Yields:\n PlasmaObjectFuture: PlasmaObjectFuture instances.\n "
] |
Please provide a description of the function:def process_notifications(self, messages):
for object_id, object_size, metadata_size in messages:
if object_size > 0 and object_id in self._waiting_dict:
linked_list = self._waiting_dict[object_id]
self._complete_f... | [
"Process notifications."
] |
Please provide a description of the function:def as_future(self, object_id, check_ready=True):
if not isinstance(object_id, ray.ObjectID):
raise TypeError("Input should be an ObjectID.")
plain_object_id = plasma.ObjectID(object_id.binary())
fut = PlasmaObjectFuture(loop=sel... | [
"Turn an object_id into a Future object.\n\n Args:\n object_id: A Ray's object_id.\n check_ready (bool): If true, check if the object_id is ready.\n\n Returns:\n PlasmaObjectFuture: A future object that waits the object_id.\n "
] |
Please provide a description of the function:def get_all_trials(self):
response = requests.get(urljoin(self._path, "trials"))
return self._deserialize(response) | [
"Returns a list of all trials' information."
] |
Please provide a description of the function:def get_trial(self, trial_id):
response = requests.get(
urljoin(self._path, "trials/{}".format(trial_id)))
return self._deserialize(response) | [
"Returns trial information by trial_id."
] |
Please provide a description of the function:def add_trial(self, name, specification):
payload = {"name": name, "spec": specification}
response = requests.post(urljoin(self._path, "trials"), json=payload)
return self._deserialize(response) | [
"Adds a trial by name and specification (dict)."
] |
Please provide a description of the function:def stop_trial(self, trial_id):
response = requests.put(
urljoin(self._path, "trials/{}".format(trial_id)))
return self._deserialize(response) | [
"Requests to stop trial by trial_id."
] |
Please provide a description of the function:def foreach_worker(self, fn):
results = ray.get([w.foreach_worker.remote(fn) for w in self.workers])
return results | [
"Apply the given function to each remote worker.\n\n Returns:\n List of results from applying the function.\n "
] |
Please provide a description of the function:def foreach_model(self, fn):
results = ray.get([w.foreach_model.remote(fn) for w in self.workers])
out = []
for r in results:
out.extend(r)
return out | [
"Apply the given function to each model replica in each worker.\n\n Returns:\n List of results from applying the function.\n "
] |
Please provide a description of the function:def for_model(self, fn):
return ray.get(self.workers[0].for_model.remote(fn)) | [
"Apply the given function to a single model replica.\n\n Returns:\n Result from applying the function.\n "
] |
Please provide a description of the function:def step(self, fetch_stats=False):
if self.strategy == "ps":
return _distributed_sgd_step(
self.workers,
self.ps_list,
write_timeline=False,
fetch_stats=fetch_stats)
else:
... | [
"Run a single SGD step.\n\n Arguments:\n fetch_stats (bool): Whether to return stats from the step. This can\n slow down the computation by acting as a global barrier.\n "
] |
Please provide a description of the function:def start_router(router_class, router_name):
handle = router_class.remote(router_name)
ray.experimental.register_actor(router_name, handle)
handle.start.remote()
return handle | [
"Wrapper for starting a router and register it.\n\n Args:\n router_class: The router class to instantiate.\n router_name: The name to give to the router.\n\n Returns:\n A handle to newly started router actor.\n "
] |
Please provide a description of the function:def generate_random_one_hot_encoding(self):
encoding = []
for ps in self.param_list:
one_hot = np.zeros(ps.choices_count())
choice = random.randrange(ps.choices_count())
one_hot[choice] = 1
encoding.app... | [
"Returns a list of one-hot encodings for all parameters.\n\n 1 one-hot np.array for 1 parameter,\n and the 1's place is randomly chosen.\n "
] |
Please provide a description of the function:def apply_one_hot_encoding(self, one_hot_encoding):
config = {}
for ps, one_hot in zip(self.param_list, one_hot_encoding):
index = np.argmax(one_hot)
config[ps.name] = ps.choices[index]
return config | [
"Apply one hot encoding to generate a specific config.\n\n\n Arguments:\n one_hot_encoding (list): A list of one hot encodings,\n 1 for each parameter. The shape of each encoding\n should match that ``ParameterSpace``\n\n Returns:\n A dict config wit... |
Please provide a description of the function:def pin_in_object_store(obj):
obj_id = ray.put(_to_pinnable(obj))
_pinned_objects.append(ray.get(obj_id))
return "{}{}".format(PINNED_OBJECT_PREFIX,
base64.b64encode(obj_id.binary()).decode("utf-8")) | [
"Pin an object in the object store.\n\n It will be available as long as the pinning process is alive. The pinned\n object can be retrieved by calling get_pinned_object on the identifier\n returned by this call.\n "
] |
Please provide a description of the function:def get_pinned_object(pinned_id):
from ray import ObjectID
return _from_pinnable(
ray.get(
ObjectID(base64.b64decode(pinned_id[len(PINNED_OBJECT_PREFIX):])))) | [
"Retrieve a pinned object from the object store."
] |
Please provide a description of the function:def merge_dicts(d1, d2):
merged = copy.deepcopy(d1)
deep_update(merged, d2, True, [])
return merged | [
"Returns a new dict that is d1 and d2 deep merged."
] |
Please provide a description of the function:def deep_update(original, new_dict, new_keys_allowed, whitelist):
for k, value in new_dict.items():
if k not in original:
if not new_keys_allowed:
raise Exception("Unknown config parameter `{}` ".format(k))
if isinstance(o... | [
"Updates original dict with values from new_dict recursively.\n If new key is introduced in new_dict, then if new_keys_allowed is not\n True, an error will be thrown. Further, for sub-dicts, if the key is\n in the whitelist, then new subkeys can be introduced.\n\n Args:\n original (dict): Diction... |
Please provide a description of the function:def completed_prefetch(self, blocking_wait=False, max_yield=999):
for worker, obj_id in self.completed(blocking_wait=blocking_wait):
plasma_id = ray.pyarrow.plasma.ObjectID(obj_id.binary())
(ray.worker.global_worker.raylet_client.fet... | [
"Similar to completed but only returns once the object is local.\n\n Assumes obj_id only is one id."
] |
Please provide a description of the function:def reset_evaluators(self, evaluators):
for obj_id, ev in self._tasks.copy().items():
if ev not in evaluators:
del self._tasks[obj_id]
del self._objects[obj_id]
ok = []
for ev, obj_id in self._fetch... | [
"Notify that some evaluators may be removed."
] |
Please provide a description of the function:def iter_train_batches(self, max_yield=999):
for ev, sample_batch in self._augment_with_replay(
self.sample_tasks.completed_prefetch(
blocking_wait=True, max_yield=max_yield)):
sample_batch.decompress_if_neede... | [
"Iterate over train batches.\n\n Arguments:\n max_yield (int): Max number of batches to iterate over in this\n cycle. Setting this avoids iter_train_batches returning too\n much data at once.\n "
] |
Please provide a description of the function:def create_or_update_cluster(config_file, override_min_workers,
override_max_workers, no_restart, restart_only,
yes, override_cluster_name):
config = yaml.load(open(config_file).read())
if override_min_wo... | [
"Create or updates an autoscaling Ray cluster from a config json."
] |
Please provide a description of the function:def teardown_cluster(config_file, yes, workers_only, override_cluster_name):
config = yaml.load(open(config_file).read())
if override_cluster_name is not None:
config["cluster_name"] = override_cluster_name
validate_config(config)
config = fillo... | [
"Destroys all nodes of a Ray cluster described by a config json."
] |
Please provide a description of the function:def kill_node(config_file, yes, override_cluster_name):
config = yaml.load(open(config_file).read())
if override_cluster_name is not None:
config["cluster_name"] = override_cluster_name
config = _bootstrap_config(config)
confirm("This will kill... | [
"Kills a random Raylet worker."
] |
Please provide a description of the function:def get_or_create_head_node(config, config_file, no_restart, restart_only, yes,
override_cluster_name):
provider = get_node_provider(config["provider"], config["cluster_name"])
try:
head_node_tags = {
TAG_RAY_NODE_... | [
"Create the cluster head node, which in turn creates the workers."
] |
Please provide a description of the function:def attach_cluster(config_file, start, use_tmux, override_cluster_name, new):
if use_tmux:
if new:
cmd = "tmux new"
else:
cmd = "tmux attach || tmux new"
else:
if new:
cmd = "screen -L"
else:
... | [
"Attaches to a screen for the specified cluster.\n\n Arguments:\n config_file: path to the cluster yaml\n start: whether to start the cluster if it isn't up\n use_tmux: whether to use tmux as multiplexer\n override_cluster_name: set the name of the cluster\n new: whether to for... |
Please provide a description of the function:def exec_cluster(config_file, cmd, docker, screen, tmux, stop, start,
override_cluster_name, port_forward):
assert not (screen and tmux), "Can specify only one of `screen` or `tmux`."
config = yaml.load(open(config_file).read())
if override... | [
"Runs a command on the specified cluster.\n\n Arguments:\n config_file: path to the cluster yaml\n cmd: command to run\n docker: whether to run command in docker container of config\n screen: whether to run in a screen\n tmux: whether to run in a tmux session\n stop: whe... |
Please provide a description of the function:def rsync(config_file, source, target, override_cluster_name, down):
config = yaml.load(open(config_file).read())
if override_cluster_name is not None:
config["cluster_name"] = override_cluster_name
config = _bootstrap_config(config)
head_node =... | [
"Rsyncs files.\n\n Arguments:\n config_file: path to the cluster yaml\n source: source dir\n target: target dir\n override_cluster_name: set the name of the cluster\n down: whether we're syncing remote -> local\n "
] |
Please provide a description of the function:def get_head_node_ip(config_file, override_cluster_name):
config = yaml.load(open(config_file).read())
if override_cluster_name is not None:
config["cluster_name"] = override_cluster_name
provider = get_node_provider(config["provider"], config["clu... | [
"Returns head node IP for given configuration file if exists."
] |
Please provide a description of the function:def get_worker_node_ips(config_file, override_cluster_name):
config = yaml.load(open(config_file).read())
if override_cluster_name is not None:
config["cluster_name"] = override_cluster_name
provider = get_node_provider(config["provider"], config["... | [
"Returns worker node IPs for given configuration file."
] |
Please provide a description of the function:def _train(self):
if self._runner.is_alive():
# if started and alive, inform the reporter to continue and
# generate the next result
self._continue_semaphore.release()
else:
# if not alive, try to start... | [
"Implements train() for a Function API.\n\n If the RunnerThread finishes without reporting \"done\",\n Tune will automatically provide a magic keyword __duplicate__\n along with a result with \"done=True\". The TrialRunner will handle the\n result accordingly (see tune/trial_runner.py).\... |
Please provide a description of the function:def build_network(self,
images,
phase_train=True,
nclass=1001,
image_depth=3,
data_type=tf.float32,
data_format="NCHW",
u... | [
"Returns logits and aux_logits from images."
] |
Please provide a description of the function:def renamed_class(cls):
class DeprecationWrapper(cls):
def __init__(self, config=None, env=None, logger_creator=None):
old_name = cls.__name__.replace("Trainer", "Agent")
new_name = cls.__name__
logger.warn("DeprecationWa... | [
"Helper class for renaming Agent => Trainer with a warning."
] |
Please provide a description of the function:def profile(event_type, extra_data=None):
worker = ray.worker.global_worker
return RayLogSpanRaylet(worker.profiler, event_type, extra_data=extra_data) | [
"Profile a span of time so that it appears in the timeline visualization.\n\n Note that this only works in the raylet code path.\n\n This function can be used as follows (both on the driver or within a task).\n\n .. code-block:: python\n\n with ray.profile(\"custom event\", extra_data={'key': 'value... |
Please provide a description of the function:def _periodically_flush_profile_events(self):
# Note(rkn): This is run on a background thread in the driver. It uses
# the raylet client. This should be ok because it doesn't read
# from the raylet client and we have the GIL here. However,
... | [
"Drivers run this as a thread to flush profile data in the\n background."
] |
Please provide a description of the function:def flush_profile_data(self):
with self.lock:
events = self.events
self.events = []
if self.worker.mode == ray.WORKER_MODE:
component_type = "worker"
else:
component_type = "driver"
se... | [
"Push the logged profiling data to the global control store."
] |
Please provide a description of the function:def set_attribute(self, key, value):
if not isinstance(key, str) or not isinstance(value, str):
raise ValueError("The arguments 'key' and 'value' must both be "
"strings. Instead they are {} and {}.".format(
... | [
"Add a key-value pair to the extra_data dict.\n\n This can be used to add attributes that are not available when\n ray.profile was called.\n\n Args:\n key: The attribute name.\n value: The attribute value.\n "
] |
Please provide a description of the function:def sync_to_worker_if_possible(self):
if self.worker_ip == self.local_ip:
return
ssh_key = get_ssh_key()
ssh_user = get_ssh_user()
global _log_sync_warned
if ssh_key is None or ssh_user is None:
if not ... | [
"Syncs the local logdir on driver to worker if possible.\n\n Requires ray cluster to be started with the autoscaler. Also requires\n rsync to be installed.\n ",
"rsync -savz -e \"ssh -i {} -o ConnectTimeout=120s ",
"-o StrictHostKeyChecking=no\" {} {}"
] |
Please provide a description of the function:def forward(self, agent_qs, states):
bs = agent_qs.size(0)
states = states.reshape(-1, self.state_dim)
agent_qs = agent_qs.view(-1, 1, self.n_agents)
# First layer
w1 = th.abs(self.hyper_w_1(states))
b1 = self.hyper_b_... | [
"Forward pass for the mixer.\n\n Arguments:\n agent_qs: Tensor of shape [B, T, n_agents, n_actions]\n states: Tensor of shape [B, T, state_dim]\n "
] |
Please provide a description of the function:def on_trial_complete(self,
trial_id,
result=None,
error=False,
early_terminated=False):
if result:
self.conn.experiments(self.experiment.id).... | [
"Passes the result to SigOpt unless early terminated or errored.\n\n If a trial fails, it will be reported as a failed Observation, telling\n the optimizer that the Suggestion led to a metric failure, which\n updates the feasible region and improves parameter recommendation.\n\n Creates ... |
Please provide a description of the function:def compute_ranks(x):
assert x.ndim == 1
ranks = np.empty(len(x), dtype=int)
ranks[x.argsort()] = np.arange(len(x))
return ranks | [
"Returns ranks in [0, len(x))\n\n Note: This is different from scipy.stats.rankdata, which returns ranks in\n [1, len(x)].\n "
] |
Please provide a description of the function:def bottleneck_block_v1(cnn, depth, depth_bottleneck, stride):
input_layer = cnn.top_layer
in_size = cnn.top_size
name_key = "resnet_v1"
name = name_key + str(cnn.counts[name_key])
cnn.counts[name_key] += 1
with tf.variable_scope(name):
... | [
"Bottleneck block with identity short-cut for ResNet v1.\n\n Args:\n cnn: the network to append bottleneck blocks.\n depth: the number of output filters for this bottleneck block.\n depth_bottleneck: the number of bottleneck filters for this block.\n stride: Stride used in the first layer of the bottle... |
Please provide a description of the function:def bottleneck_block(cnn, depth, depth_bottleneck, stride, pre_activation):
if pre_activation:
bottleneck_block_v2(cnn, depth, depth_bottleneck, stride)
else:
bottleneck_block_v1(cnn, depth, depth_bottleneck, stride) | [
"Bottleneck block with identity short-cut.\n\n Args:\n cnn: the network to append bottleneck blocks.\n depth: the number of output filters for this bottleneck block.\n depth_bottleneck: the number of bottleneck filters for this block.\n stride: Stride used in the first layer of the bottleneck block.\n ... |
Please provide a description of the function:def residual_block(cnn, depth, stride, pre_activation):
input_layer = cnn.top_layer
in_size = cnn.top_size
if in_size != depth:
# Plan A of shortcut.
shortcut = cnn.apool(
1,
1,
stride,
stride,
... | [
"Residual block with identity short-cut.\n\n Args:\n cnn: the network to append residual blocks.\n depth: the number of output filters for this residual block.\n stride: Stride used in the first layer of the residual block.\n pre_activation: use pre_activation structure or not.\n "
] |
Please provide a description of the function:def apply_changes(self, other, with_buffer=False):
self.rs.update(other.buffer)
if with_buffer:
self.buffer = other.buffer.copy() | [
"Applies updates from the buffer of another filter.\n\n Params:\n other (MeanStdFilter): Other filter to apply info from\n with_buffer (bool): Flag for specifying if the buffer should be\n copied from other.\n\n Examples:\n >>> a = MeanStdFilter(())\n ... |
Please provide a description of the function:def copy(self):
other = MeanStdFilter(self.shape)
other.sync(self)
return other | [
"Returns a copy of Filter."
] |
Please provide a description of the function:def sync(self, other):
assert other.shape == self.shape, "Shapes don't match!"
self.demean = other.demean
self.destd = other.destd
self.clip = other.clip
self.rs = other.rs.copy()
self.buffer = other.buffer.copy() | [
"Syncs all fields together from other filter.\n\n Examples:\n >>> a = MeanStdFilter(())\n >>> a(1)\n >>> a(2)\n >>> print([a.rs.n, a.rs.mean, a.buffer.n])\n [2, array(1.5), 2]\n >>> b = MeanStdFilter(())\n >>> b(10)\n >>>... |
Please provide a description of the function:def as_serializable(self):
other = MeanStdFilter(self.shape)
other.sync(self)
return other | [
"Returns non-concurrent version of current class"
] |
Please provide a description of the function:def copy(self):
other = ConcurrentMeanStdFilter(self.shape)
other.sync(self)
return other | [
"Returns a copy of Filter."
] |
Please provide a description of the function:def michalewicz_function(config, reporter):
import numpy as np
x = np.array(
[config["x1"], config["x2"], config["x3"], config["x4"], config["x5"]])
sin_x = np.sin(x)
z = (np.arange(1, 6) / np.pi * (x * x))
sin_z = np.power(np.sin(z), 20) # ... | [
"f(x) = -sum{sin(xi) * [sin(i*xi^2 / pi)]^(2m)}"
] |
Please provide a description of the function:def parse_general_int(s):
mo = re.match(r"(\d+)([KkMGT]?)$", s)
if mo:
i, suffix = mo.group(1, 2)
v = int(i)
if suffix:
if suffix == "K" or suffix == "k":
v *= 1024
elif suffix == "M":
... | [
"Parse integer with power-of-2 suffix eg. 32k."
] |
Please provide a description of the function:def parse_all_reduce_spec(all_reduce_spec):
range_parts = all_reduce_spec.split(":") + ["-1"]
if len(range_parts) % 2:
raise ValueError(
"all_reduce_spec not well formed: %s" % all_reduce_spec)
limit = 0
spec = []
alg = None
s... | [
"Parse all_reduce_spec.\n\n Args:\n all_reduce_spec: a string specifying a combination of all-reduce\n algorithms to apply for gradient reduction.\n\n Returns:\n a list of AllReduceSpecTuple.\n\n Raises:\n ValueError: all_reduce_spec is not well-formed.\n\n An all_reduce_spec has BNF form:\n i... |
Please provide a description of the function:def build_all_reduce_device_prefixes(job_name, num_tasks):
if job_name != "localhost":
return ["/job:%s/task:%d" % (job_name, d) for d in range(0, num_tasks)]
else:
assert num_tasks == 1
return ["/job:%s" % job_name] | [
"Build list of device prefix names for all_reduce.\n\n Args:\n job_name: \"worker\", \"ps\" or \"localhost\".\n num_tasks: number of jobs across which device names should be generated.\n\n Returns:\n A list of device name prefix strings. Each element spells out the full\n host name without adding th... |
Please provide a description of the function:def group_device_names(devices, group_size):
num_devices = len(devices)
if group_size > num_devices:
raise ValueError(
"only %d devices, but group_size=%d" % (num_devices, group_size))
num_groups = (
num_devices // group_size + (1... | [
"Group device names into groups of group_size.\n\n Args:\n devices: list of strings naming devices.\n group_size: int >= 1\n\n Returns:\n list of lists of devices, where each inner list is group_size long,\n and each device appears at least once in an inner list. If\n len(devices) % group_size... |
Please provide a description of the function:def split_grads_by_size(threshold_size, device_grads):
small_grads = []
large_grads = []
for dl in device_grads:
small_dl = []
large_dl = []
for (g, v) in dl:
tensor_size = g.get_shape().num_elements()
if tenso... | [
"Break gradients into two sets according to tensor size.\n\n Args:\n threshold_size: int size cutoff for small vs large tensor.\n device_grads: List of lists of (gradient, variable) tuples. The outer\n list is over devices. The inner list is over individual gradients.\n\n Returns:\n small_grads: ... |
Please provide a description of the function:def aggregate_single_gradient(grad_and_vars, use_mean, check_inf_nan):
grads = [g for g, _ in grad_and_vars]
grad = tf.add_n(grads)
if use_mean and len(grads) > 1:
grad = tf.multiply(grad, 1.0 / len(grads))
v = grad_and_vars[0][1]
if check_... | [
"Calculate the average gradient for a shared variable across all towers.\n\n Note that this function provides a synchronization point across all towers.\n\n Args:\n grad_and_vars: A list or tuple of (gradient, variable) tuples. Each\n (gradient, variable) pair within the outer list represents the gradient... |
Please provide a description of the function:def aggregate_gradients_using_copy_with_device_selection(
tower_grads, avail_devices, use_mean=True, check_inf_nan=False):
agg_grads = []
has_nan_or_inf_list = []
for i, single_grads in enumerate(zip(*tower_grads)):
with tf.device(avail_devic... | [
"Aggregate gradients, controlling device for the aggregation.\n\n Args:\n tower_grads: List of lists of (gradient, variable) tuples. The outer list\n is over towers. The inner list is over individual gradients.\n use_mean: if True, mean is taken, else sum of gradients is taken.\n check_inf_nan: If tr... |
Please provide a description of the function:def sum_grad_and_var_all_reduce(grad_and_vars,
num_workers,
alg,
gpu_indices,
aux_devices=None,
num_shards=1):
... | [
"Apply all-reduce algorithm over specified gradient tensors."
] |
Please provide a description of the function:def sum_gradients_all_reduce(dev_prefixes,
tower_grads,
num_workers,
alg,
num_shards,
gpu_indices,
ag... | [
"Apply all-reduce algorithm over specified gradient tensors.\n\n Args:\n dev_prefixes: list of prefix strings to use to generate PS device names.\n tower_grads: the gradients to reduce.\n num_workers: number of worker processes across entire job.\n alg: the all-reduce algorithm to apply.\n num_shard... |
Please provide a description of the function:def extract_ranges(index_list, range_size_limit=32):
if not index_list:
return [], []
first = index_list[0]
last = first
ranges = []
singles = []
for i in index_list[1:]:
if i == last + 1 and (last - first) <= range_size_limit:
... | [
"Extract consecutive ranges and singles from index_list.\n\n Args:\n index_list: List of monotone increasing non-negative integers.\n range_size_limit: Largest size range to return. If a larger\n consecutive range exists it will be returned as multiple\n ranges.\n\n Returns:\n ranges, singles w... |
Please provide a description of the function:def pack_range(key, packing, grad_vars, rng):
to_pack = grad_vars[rng[0]:rng[1] + 1]
members = []
variables = []
restore_shapes = []
with tf.name_scope("pack"):
for g, v in to_pack:
variables.append(v)
restore_shapes.a... | [
"Form the concatenation of a specified range of gradient tensors.\n\n Args:\n key: Value under which to store meta-data in packing that will be used\n later to restore the grad_var list structure.\n packing: Dict holding data describing packed ranges of small tensors.\n grad_vars: List of (grad, var)... |
Please provide a description of the function:def unpack_grad_tuple(gv, gpt):
elt_widths = [x.num_elements() for x in gpt.shapes]
with tf.device(gv[0][0].device):
with tf.name_scope("unpack"):
splits = tf.split(gv[0], elt_widths)
unpacked_gv = []
for idx, s in enu... | [
"Unpack a previously packed collection of gradient tensors.\n\n Args:\n gv: A (grad, var) pair to be unpacked.\n gpt: A GradPackTuple describing the packing operation that produced gv.\n\n Returns:\n A list of (grad, var) pairs corresponding to the values that were\n originally packed into gv, maybe ... |
Please provide a description of the function:def pack_small_tensors(tower_grads, max_bytes=0):
assert max_bytes >= 0
orig_grads = [g for g, _ in tower_grads[0]]
# Check to make sure sizes are accurate; not entirely important
assert all(g.dtype == tf.float32 for g in orig_grads)
sizes = [4 * g.s... | [
"Concatenate gradients together more intelligently.\n\n Does binpacking\n Args:\n tower_grads: List of lists of (gradient, variable) tuples.\n max_bytes: Int giving max number of bytes in a tensor that\n may be considered small.\n "
] |
Please provide a description of the function:def unpack_small_tensors(tower_grads, packing):
if not packing:
return tower_grads
new_tower_grads = []
num_devices = len(tower_grads)
num_packed = len(packing.keys()) // num_devices
for dev_idx, gv_list in enumerate(tower_grads):
new... | [
"Undo the structure alterations to tower_grads done by pack_small_tensors.\n\n Args:\n tower_grads: List of List of (grad, var) tuples.\n packing: A dict generated by pack_small_tensors describing the changes\n it made to tower_grads.\n\n Returns:\n new_tower_grads: identical to tower_grads except t... |
Please provide a description of the function:def _init(self):
# Note that we assume params.json was already created by JsonLogger
progress_file = os.path.join(self.logdir, "progress.csv")
self._continuing = os.path.exists(progress_file)
self._file = open(progress_file, "a")
... | [
"CSV outputted with Headers as first set of results."
] |
Please provide a description of the function:def sync_results_to_new_location(self, worker_ip):
if worker_ip != self._log_syncer.worker_ip:
self._log_syncer.set_worker_ip(worker_ip)
self._log_syncer.sync_to_worker_if_possible() | [
"Sends the current log directory to the remote node.\n\n Syncing will not occur if the cluster is not started\n with the Ray autoscaler.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.