text
stringlengths
81
112k
This is called whenever a trial makes progress. When all live trials in the bracket have no more iterations left, Trials will be successively halved. If bracket is done, all non-running trials will be stopped and cleaned up, and during each halving phase, bad trials will be stopped whil...
Notification when trial terminates. Trial info is removed from bracket. Triggers halving if bracket is not finished. def on_trial_remove(self, trial_runner, trial): """Notification when trial terminates. Trial info is removed from bracket. Triggers halving if bracket is not fi...
Fair scheduling within iteration by completion percentage. List of trials not used since all trials are tracked as state of scheduler. If iteration is occupied (ie, no trials to run), then look into next iteration. def choose_trial_to_run(self, trial_runner): """Fair scheduling within ...
This provides a progress notification for the algorithm. For each bracket, the algorithm will output a string as follows: Bracket(Max Size (n)=5, Milestone (r)=33, completed=14.6%): {PENDING: 2, RUNNING: 3, TERMINATED: 2} "Max Size" indicates the max number of pending/running ...
Add trial to bracket assuming bracket is not filled. At a later iteration, a newly added trial will be given equal opportunity to catch up. def add_trial(self, trial): """Add trial to bracket assuming bracket is not filled. At a later iteration, a newly added trial will be given equal...
Checks if all iterations have completed. TODO(rliaw): also check that `t.iterations == self._r` def cur_iter_done(self): """Checks if all iterations have completed. TODO(rliaw): also check that `t.iterations == self._r`""" return all( self._get_result_time(result) >= self....
Update result for trial. Called after trial has finished an iteration - will decrement iteration count. TODO(rliaw): The other alternative is to keep the trials in and make sure they're not set as pending later. def update_trial_stats(self, trial, result): """Update result for trial. C...
Cleans up bracket after bracket is completely finished. Lets the last trial continue to run until termination condition kicks in. def cleanup_full(self, trial_runner): """Cleans up bracket after bracket is completely finished. Lets the last trial continue to run until termination cond...
Read the client table. Args: redis_client: A client to the primary Redis shard. Returns: A list of information about the nodes in the cluster. def parse_client_table(redis_client): """Read the client table. Args: redis_client: A client to the primary Redis shard. Returns...
Initialize the GlobalState object by connecting to Redis. It's possible that certain keys in Redis may not have been fully populated yet. In this case, we will retry this method until they have been populated or we exceed a timeout. Args: redis_address: The Redis address to...
Execute a Redis command on the appropriate Redis shard based on key. Args: key: The object ID or the task ID that the query is about. args: The command to run. Returns: The value returned by the Redis command. def _execute_command(self, key, *args): """Exec...
Execute the KEYS command on all Redis shards. Args: pattern: The KEYS pattern to query. Returns: The concatenated list of results from all shards. def _keys(self, pattern): """Execute the KEYS command on all Redis shards. Args: pattern: The KEYS pa...
Fetch and parse the object table information for a single object ID. Args: object_id: An object ID to get information about. Returns: A dictionary with information about the object ID in question. def _object_table(self, object_id): """Fetch and parse the object table ...
Fetch and parse the object table info for one or more object IDs. Args: object_id: An object ID to fetch information about. If this is None, then the entire object table is fetched. Returns: Information from the object table. def object_table(self, object_id=No...
Fetch and parse the task table information for a single task ID. Args: task_id: A task ID to get information about. Returns: A dictionary with information about the task ID in question. def _task_table(self, task_id): """Fetch and parse the task table information for a...
Fetch and parse the task table information for one or more task IDs. Args: task_id: A hex string of the task ID to fetch information about. If this is None, then the task object table is fetched. Returns: Information from the task table. def task_table(self, ta...
Fetch and parse the function table. Returns: A dictionary that maps function IDs to information about the function. def function_table(self, function_id=None): """Fetch and parse the function table. Returns: A dictionary that maps function IDs to inform...
Get the profile events for a given batch of profile events. Args: batch_id: An identifier for a batch of profile events. Returns: A list of the profile events for the specified batch. def _profile_table(self, batch_id): """Get the profile events for a given batch of pr...
Return a list of profiling events that can viewed as a timeline. To view this information as a timeline, simply dump it as a json file by passing in "filename" or using using json.dump, and then load go to chrome://tracing in the Chrome web browser and load the dumped file. Make sure to...
Return a list of transfer events that can viewed as a timeline. To view this information as a timeline, simply dump it as a json file by passing in "filename" or using using json.dump, and then load go to chrome://tracing in the Chrome web browser and load the dumped file. Make sure to ...
Get a dictionary mapping worker ID to worker information. def workers(self): """Get a dictionary mapping worker ID to worker information.""" worker_keys = self.redis_client.keys("Worker*") workers_data = {} for worker_key in worker_keys: worker_info = self.redis_client.hget...
Get the current total cluster resources. Note that this information can grow stale as nodes are added to or removed from the cluster. Returns: A dictionary mapping resource name to the total quantity of that resource in the cluster. def cluster_resources(self): ...
Get the current available cluster resources. This is different from `cluster_resources` in that this will return idle (available) resources rather than total resources. Note that this information can grow stale as tasks start and finish. Returns: A dictionary mapping resou...
Get the error messages for a specific driver. Args: driver_id: The ID of the driver to get the errors for. Returns: A list of the error messages for this driver. def _error_messages(self, driver_id): """Get the error messages for a specific driver. Args: ...
Get the error messages for all drivers or a specific driver. Args: driver_id: The specific driver to get the errors for. If this is None, then this method retrieves the errors for all drivers. Returns: A dictionary mapping driver ID to a list of the error messag...
Get checkpoint info for the given actor id. Args: actor_id: Actor's ID. Returns: A dictionary with information about the actor's checkpoint IDs and their timestamps. def actor_checkpoint_info(self, actor_id): """Get checkpoint info for the given actor id. ...
Returns the total length of all of the flattened variables. Returns: The length of all flattened variables concatenated. def get_flat_size(self): """Returns the total length of all of the flattened variables. Returns: The length of all flattened variables concatenated....
Gets the weights and returns them as a flat array. Returns: 1D Array containing the flattened weights. def get_flat(self): """Gets the weights and returns them as a flat array. Returns: 1D Array containing the flattened weights. """ self._check_sess() ...
Sets the weights to new_weights, converting from a flat array. Note: You can only set all weights in the network using this function, i.e., the length of the array must match get_flat_size. Args: new_weights (np.ndarray): Flat array containing weights. def set_flat...
Returns a dictionary containing the weights of the network. Returns: Dictionary mapping variable names to their weights. def get_weights(self): """Returns a dictionary containing the weights of the network. Returns: Dictionary mapping variable names to their weights. ...
Sets the weights to new_weights. Note: Can set subsets of variables as well, by only passing in the variables you want to be set. Args: new_weights (Dict): Dictionary mapping variable names to their weights. def set_weights(self, new_weights): ...
Construct a serialized ErrorTableData object. Args: driver_id: The ID of the driver that the error should go to. If this is nil, then the error will go to all drivers. error_type: The type of the error. message: The error message. timestamp: The time of the error. R...
Initialize synchronously. def init(): """ Initialize synchronously. """ 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 " ...
Manually shutdown the async API. Cancels all related tasks and all the socket transportation. def shutdown(): """Manually shutdown the async API. Cancels all related tasks and all the socket transportation. """ global handler, transport, protocol if handler is not None: handler.close(...
This removes some non-critical state from the primary Redis shard. This removes the log files as well as the event log from Redis. This can be used to try to address out-of-memory errors caused by the accumulation of metadata in Redis. However, it will only partially address the issue as much of the da...
This removes some critical state from the Redis shards. In a multitenant environment, this will flush metadata for all jobs, which may be undesirable. This removes all of the object and task metadata. This can be used to try to address out-of-memory errors caused by the accumulation of metadata in ...
This removes some critical state from the Redis shards. In a multitenant environment, this will flush metadata for all jobs, which may be undesirable. This removes all of the metadata for finished tasks. This can be used to try to address out-of-memory errors caused by the accumulation of metadata ...
This removes some critical state from the Redis shards. In a multitenant environment, this will flush metadata for all jobs, which may be undesirable. This removes all of the metadata for objects that have been evicted. This can be used to try to address out-of-memory errors caused by the accumula...
Creates a copy of self using existing input placeholders. def copy(self, existing_inputs): """Creates a copy of self using existing input placeholders.""" return PPOPolicyGraph( self.observation_space, self.action_space, self.config, existing_inputs=exist...
deepnn builds the graph for a deep net for classifying digits. Args: x: an input tensor with the dimensions (N_examples, 784), where 784 is the number of pixels in a standard MNIST image. Returns: A tuple (y, keep_prob). y is a tensor of shape (N_examples, 10), with val...
Get signature parameters Support Cython functions by grabbing relevant attributes from the Cython function and attaching to a no-op function. This is somewhat brittle, since funcsigs may change, but given that funcsigs is written to a PEP, we hope it is relatively stable. Future versions of Python may ...
Check if we support the signature of this function. We currently do not allow remote functions to have **kwargs. We also do not support keyword arguments in conjunction with a *args argument. Args: func: The function whose signature should be checked. warn: If this is true, a warning will ...
Extract the function signature from the function. Args: func: The function whose signature should be extracted. ignore_first: True if the first argument should be ignored. This should be used when func is a method of a class. Returns: A function signature object, which incl...
Extend the arguments that were passed into a function. This extends the arguments that were passed into a function with the default arguments provided in the function definition. Args: function_signature: The function signature of the function being called. args: The non-keywor...
Poll for cloud resource manager operation until finished. def wait_for_crm_operation(operation): """Poll for cloud resource manager operation until finished.""" logger.info("wait_for_crm_operation: " "Waiting for operation {} to finish...".format(operation)) for _ in range(MAX_POLLS): ...
Poll for global compute operation until finished. def wait_for_compute_global_operation(project_name, operation): """Poll for global compute operation until finished.""" logger.info("wait_for_compute_global_operation: " "Waiting for operation {} to finish...".format( operati...
Returns the ith default gcp_key_pair_name. def key_pair_name(i, region, project_id, ssh_user): """Returns the ith default gcp_key_pair_name.""" key_name = "{}_gcp_{}_{}_{}".format(RAY, region, project_id, ssh_user, i) return key_name
Returns public and private key paths for a given key_name. def key_pair_paths(key_name): """Returns public and private key paths for a given 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...
Create public and private ssh-keys. def generate_rsa_key_pair(): """Create public and private ssh-keys.""" key = rsa.generate_private_key( backend=default_backend(), public_exponent=65537, key_size=2048) public_key = key.public_key().public_bytes( serialization.Encoding.OpenSSH, s...
Setup a Google Cloud Platform Project. Google Compute Platform organizes all the resources, such as storage buckets, users, and instances under projects. This is different from aws ec2 where everything is global. def _configure_project(config): """Setup a Google Cloud Platform Project. Google Com...
Setup a gcp service account with IAM roles. Creates a gcp service acconut and binds IAM roles which allow it to control control storage/compute services. Specifically, the head node needs to have an IAM role that allows it to create further gce instances and store items in google cloud storage. TO...
Configure SSH access, using an existing key pair if possible. Creates a project-wide ssh key that can be used to access all the instances unless explicitly prohibited by instance config. The ssh-keys created by ray are of format: [USERNAME]:ssh-rsa [KEY_VALUE] [USERNAME] where: [USERNAM...
Pick a reasonable subnet if not specified by the config. def _configure_subnet(config): """Pick a reasonable subnet if not specified by the config.""" # Rationale: avoid subnet lookup if the network is already # completely manually configured if ("networkInterfaces" in config["head_node"] ...
Add new IAM roles for the service account. def _add_iam_policy_binding(service_account, roles): """Add new IAM roles for the service account.""" project_id = service_account["projectId"] email = service_account["email"] member_id = "serviceAccount:" + email policy = crm.projects().getIamPolicy(res...
Inserts an ssh-key into project commonInstanceMetadata def _create_project_ssh_key_pair(project, public_key, ssh_user): """Inserts an ssh-key into project commonInstanceMetadata""" key_parts = public_key.split(" ") # Sanity checks to make sure that the generated key matches expectation assert len(key...
An experimental alternate way to submit remote functions. def _remote(self, args=None, kwargs=None, num_return_vals=None, num_cpus=None, num_gpus=None, resources=None): """An experimental alternate way to submit rem...
Append an object to the linked list. Args: future (PlasmaObjectFuture): A PlasmaObjectFuture instance. def append(self, future): """Append an object to the linked list. Args: future (PlasmaObjectFuture): A PlasmaObjectFuture instance. """ future.prev = ...
Remove an object from the linked list. Args: future (PlasmaObjectFuture): A PlasmaObjectFuture instance. def remove(self, future): """Remove an object from the linked list. Args: future (PlasmaObjectFuture): A PlasmaObjectFuture instance. """ if self._l...
Manually cancel all tasks assigned to this event loop. def cancel(self, *args, **kwargs): """Manually cancel all tasks assigned to this event loop.""" # Because remove all futures will trigger `set_result`, # we cancel itself first. super().cancel() for future in self.traverse()...
Complete all tasks. def set_result(self, result): """Complete all tasks. """ 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...
Traverse this linked list. Yields: PlasmaObjectFuture: PlasmaObjectFuture instances. def traverse(self): """Traverse this linked list. Yields: PlasmaObjectFuture: PlasmaObjectFuture instances. """ current = self.head while current is not None: ...
Process notifications. def process_notifications(self, messages): """Process notifications.""" 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._com...
Turn an object_id into a Future object. Args: object_id: A Ray's object_id. check_ready (bool): If true, check if the object_id is ready. Returns: PlasmaObjectFuture: A future object that waits the object_id. def as_future(self, object_id, check_ready=True): ...
Returns a list of all trials' information. def get_all_trials(self): """Returns a list of all trials' information.""" response = requests.get(urljoin(self._path, "trials")) return self._deserialize(response)
Returns trial information by trial_id. def get_trial(self, trial_id): """Returns trial information by trial_id.""" response = requests.get( urljoin(self._path, "trials/{}".format(trial_id))) return self._deserialize(response)
Adds a trial by name and specification (dict). def add_trial(self, name, specification): """Adds a trial by name and specification (dict).""" payload = {"name": name, "spec": specification} response = requests.post(urljoin(self._path, "trials"), json=payload) return self._deserialize(re...
Requests to stop trial by trial_id. def stop_trial(self, trial_id): """Requests to stop trial by trial_id.""" response = requests.put( urljoin(self._path, "trials/{}".format(trial_id))) return self._deserialize(response)
Apply the given function to each remote worker. Returns: List of results from applying the function. def foreach_worker(self, fn): """Apply the given function to each remote worker. Returns: List of results from applying the function. """ results = ray....
Apply the given function to each model replica in each worker. Returns: List of results from applying the function. def foreach_model(self, fn): """Apply the given function to each model replica in each worker. Returns: List of results from applying the function. ...
Apply the given function to a single model replica. Returns: Result from applying the function. def for_model(self, fn): """Apply the given function to a single model replica. Returns: Result from applying the function. """ return ray.get(self.workers[0...
Run a single SGD step. Arguments: fetch_stats (bool): Whether to return stats from the step. This can slow down the computation by acting as a global barrier. def step(self, fetch_stats=False): """Run a single SGD step. Arguments: fetch_stats (bool): Wh...
Wrapper for starting a router and register it. Args: router_class: The router class to instantiate. router_name: The name to give to the router. Returns: A handle to newly started router actor. def start_router(router_class, router_name): """Wrapper for starting a router and regis...
Returns a list of one-hot encodings for all parameters. 1 one-hot np.array for 1 parameter, and the 1's place is randomly chosen. def generate_random_one_hot_encoding(self): """Returns a list of one-hot encodings for all parameters. 1 one-hot np.array for 1 parameter, and the ...
Apply one hot encoding to generate a specific config. Arguments: one_hot_encoding (list): A list of one hot encodings, 1 for each parameter. The shape of each encoding should match that ``ParameterSpace`` Returns: A dict config with specific <na...
Pin an object in the object store. It will be available as long as the pinning process is alive. The pinned object can be retrieved by calling get_pinned_object on the identifier returned by this call. def pin_in_object_store(obj): """Pin an object in the object store. It will be available as lon...
Retrieve a pinned object from the object store. def get_pinned_object(pinned_id): """Retrieve a pinned object from the object store.""" from ray import ObjectID return _from_pinnable( ray.get( ObjectID(base64.b64decode(pinned_id[len(PINNED_OBJECT_PREFIX):]))))
Returns a new dict that is d1 and d2 deep merged. def merge_dicts(d1, d2): """Returns a new dict that is d1 and d2 deep merged.""" merged = copy.deepcopy(d1) deep_update(merged, d2, True, []) return merged
Updates original dict with values from new_dict recursively. If new key is introduced in new_dict, then if new_keys_allowed is not True, an error will be thrown. Further, for sub-dicts, if the key is in the whitelist, then new subkeys can be introduced. Args: original (dict): Dictionary with de...
Similar to completed but only returns once the object is local. Assumes obj_id only is one id. def completed_prefetch(self, blocking_wait=False, max_yield=999): """Similar to completed but only returns once the object is local. Assumes obj_id only is one id.""" for worker, obj_id in ...
Notify that some evaluators may be removed. def reset_evaluators(self, evaluators): """Notify that some evaluators may be removed.""" for obj_id, ev in self._tasks.copy().items(): if ev not in evaluators: del self._tasks[obj_id] del self._objects[obj_id] ...
Iterate over train batches. Arguments: max_yield (int): Max number of batches to iterate over in this cycle. Setting this avoids iter_train_batches returning too much data at once. def iter_train_batches(self, max_yield=999): """Iterate over train batches. ...
Create or updates an autoscaling Ray cluster from a config json. def create_or_update_cluster(config_file, override_min_workers, override_max_workers, no_restart, restart_only, yes, override_cluster_name): """Create or updates an autoscaling Ray cluster fro...
Destroys all nodes of a Ray cluster described by a config json. def teardown_cluster(config_file, yes, workers_only, override_cluster_name): """Destroys all nodes of a Ray cluster described by a config json.""" config = yaml.load(open(config_file).read()) if override_cluster_name is not None: conf...
Kills a random Raylet worker. def kill_node(config_file, yes, override_cluster_name): """Kills a random Raylet worker.""" config = yaml.load(open(config_file).read()) if override_cluster_name is not None: config["cluster_name"] = override_cluster_name config = _bootstrap_config(config) co...
Create the cluster head node, which in turn creates the workers. def get_or_create_head_node(config, config_file, no_restart, restart_only, yes, override_cluster_name): """Create the cluster head node, which in turn creates the workers.""" provider = get_node_provider(config["provid...
Attaches to a screen for the specified cluster. Arguments: config_file: path to the cluster yaml start: whether to start the cluster if it isn't up use_tmux: whether to use tmux as multiplexer override_cluster_name: set the name of the cluster new: whether to force a new scr...
Runs a command on the specified cluster. Arguments: config_file: path to the cluster yaml cmd: command to run docker: whether to run command in docker container of config screen: whether to run in a screen tmux: whether to run in a tmux session stop: whether to stop ...
Rsyncs files. Arguments: config_file: path to the cluster yaml source: source dir target: target dir override_cluster_name: set the name of the cluster down: whether we're syncing remote -> local def rsync(config_file, source, target, override_cluster_name, down): """Rs...
Returns head node IP for given configuration file if exists. def get_head_node_ip(config_file, override_cluster_name): """Returns head node IP for given configuration file if exists.""" config = yaml.load(open(config_file).read()) if override_cluster_name is not None: config["cluster_name"] = over...
Returns worker node IPs for given configuration file. def get_worker_node_ips(config_file, override_cluster_name): """Returns worker node IPs for given configuration file.""" config = yaml.load(open(config_file).read()) if override_cluster_name is not None: config["cluster_name"] = override_cluste...
Implements train() for a Function API. If the RunnerThread finishes without reporting "done", Tune will automatically provide a magic keyword __duplicate__ along with a result with "done=True". The TrialRunner will handle the result accordingly (see tune/trial_runner.py). def _train(se...
Returns logits and aux_logits from images. def build_network(self, images, phase_train=True, nclass=1001, image_depth=3, data_type=tf.float32, data_format="NCHW", us...
Helper class for renaming Agent => Trainer with a warning. def renamed_class(cls): """Helper class for renaming Agent => Trainer with a warning.""" class DeprecationWrapper(cls): def __init__(self, config=None, env=None, logger_creator=None): old_name = cls.__name__.replace("Trainer", "Age...
Profile a span of time so that it appears in the timeline visualization. Note that this only works in the raylet code path. This function can be used as follows (both on the driver or within a task). .. code-block:: python with ray.profile("custom event", extra_data={'key': 'value'}): ...
Drivers run this as a thread to flush profile data in the background. def _periodically_flush_profile_events(self): """Drivers run this as a thread to flush profile data in the background.""" # Note(rkn): This is run on a background thread in the driver. It uses # the raylet cli...
Push the logged profiling data to the global control store. def flush_profile_data(self): """Push the logged profiling data to the global control store.""" with self.lock: events = self.events self.events = [] if self.worker.mode == ray.WORKER_MODE: componen...
Add a key-value pair to the extra_data dict. This can be used to add attributes that are not available when ray.profile was called. Args: key: The attribute name. value: The attribute value. def set_attribute(self, key, value): """Add a key-value pair to the ex...
Syncs the local logdir on driver to worker if possible. Requires ray cluster to be started with the autoscaler. Also requires rsync to be installed. def sync_to_worker_if_possible(self): """Syncs the local logdir on driver to worker if possible. Requires ray cluster to be started with...
Forward pass for the mixer. Arguments: agent_qs: Tensor of shape [B, T, n_agents, n_actions] states: Tensor of shape [B, T, state_dim] def forward(self, agent_qs, states): """Forward pass for the mixer. Arguments: agent_qs: Tensor of shape [B, T, n_agents, ...
Passes the result to SigOpt unless early terminated or errored. If a trial fails, it will be reported as a failed Observation, telling the optimizer that the Suggestion led to a metric failure, which updates the feasible region and improves parameter recommendation. Creates SigOpt Obse...