INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Run the reporter.
def run(self): """Run the reporter.""" while True: try: self.perform_iteration() except Exception: traceback.print_exc() pass time.sleep(ray_constants.REPORTER_UPDATE_INTERVAL_MS / 1000)
Throws an exception if Ray cannot serialize this class efficiently.
def check_serializable(cls): """Throws an exception if Ray cannot serialize this class efficiently. Args: cls (type): The class to be serialized. Raises: Exception: An exception is raised if Ray cannot serialize this class efficiently. """ if is_named_tuple(cls): ...
Return True if cls is a namedtuple and False otherwise.
def is_named_tuple(cls): """Return True if cls is a namedtuple and False otherwise.""" b = cls.__bases__ if len(b) != 1 or b[0] != tuple: return False f = getattr(cls, "_fields", None) if not isinstance(f, tuple): return False return all(type(n) == str for n in f)
Register a trainable function or class.
def register_trainable(name, trainable): """Register a trainable function or class. Args: name (str): Name to register. trainable (obj): Function or tune.Trainable class. Functions must take (config, status_reporter) as arguments and will be automatically converted into ...
Register a custom environment for use with RLlib.
def register_env(name, env_creator): """Register a custom environment for use with RLlib. Args: name (str): Name to register. env_creator (obj): Function that creates an env. """ if not isinstance(env_creator, FunctionType): raise TypeError("Second argument must be a function."...
Return optimization stats reported from the policy graph.
def get_learner_stats(grad_info): """Return optimization stats reported from the policy graph. Example: >>> grad_info = evaluator.learn_on_batch(samples) >>> print(get_stats(grad_info)) {"vf_loss": ..., "policy_loss": ...} """ if LEARNER_STATS_KEY in grad_info: return g...
Gathers episode metrics from PolicyEvaluator instances.
def collect_metrics(local_evaluator=None, remote_evaluators=[], timeout_seconds=180): """Gathers episode metrics from PolicyEvaluator instances.""" episodes, num_dropped = collect_episodes( local_evaluator, remote_evaluators, timeout_seconds=timeout_seconds) ...
Gathers new episodes metrics tuples from the given evaluators.
def collect_episodes(local_evaluator=None, remote_evaluators=[], timeout_seconds=180): """Gathers new episodes metrics tuples from the given evaluators.""" pending = [ a.apply.remote(lambda ev: ev.get_metrics()) for a in remote_evaluators ] collected, _...
Summarizes a set of episode metrics tuples.
def summarize_episodes(episodes, new_episodes, num_dropped): """Summarizes a set of episode metrics tuples. Arguments: episodes: smoothed set of episodes including historical ones new_episodes: just the new episodes in this iteration num_dropped: number of workers haven't returned their...
Divides metrics data into true rollouts vs off - policy estimates.
def _partition(episodes): """Divides metrics data into true rollouts vs off-policy estimates.""" from ray.rllib.evaluation.sampler import RolloutMetrics rollouts, estimates = [], [] for e in episodes: if isinstance(e, RolloutMetrics): rollouts.append(e) elif isinstance(e, O...
Sets status and checkpoints metadata if needed.
def set_status(self, trial, status): """Sets status and checkpoints metadata if needed. Only checkpoints metadata if trial status is a terminal condition. PENDING, PAUSED, and RUNNING switches have checkpoints taken care of in the TrialRunner. Args: trial (Trial): T...
Checkpoints metadata.
def try_checkpoint_metadata(self, trial): """Checkpoints metadata. Args: trial (Trial): Trial to checkpoint. """ if trial._checkpoint.storage == Checkpoint.MEMORY: logger.debug("Not saving data for trial w/ memory checkpoint.") return try: ...
Pauses the trial.
def pause_trial(self, trial): """Pauses the trial. We want to release resources (specifically GPUs) when pausing an experiment. This results in PAUSED state that similar to TERMINATED. """ assert trial.status == Trial.RUNNING, trial.status try: self.save(tria...
Sets PAUSED trial to pending to allow scheduler to start.
def unpause_trial(self, trial): """Sets PAUSED trial to pending to allow scheduler to start.""" assert trial.status == Trial.PAUSED, trial.status self.set_status(trial, Trial.PENDING)
Resumes PAUSED trials. This is a blocking call.
def resume_trial(self, trial): """Resumes PAUSED trials. This is a blocking call.""" assert trial.status == Trial.PAUSED, trial.status self.start_trial(trial)
Passes the result to Nevergrad unless early terminated or errored.
def on_trial_complete(self, trial_id, result=None, error=False, early_terminated=False): """Passes the result to Nevergrad unless early terminated or errored. The result is internally negated when in...
Start the import thread.
def start(self): """Start the import thread.""" self.t = threading.Thread(target=self._run, name="ray_import_thread") # Making the thread a daemon causes it to exit # when the main thread exits. self.t.daemon = True self.t.start()
Process the given export key from redis.
def _process_key(self, key): """Process the given export key from redis.""" # Handle the driver case first. if self.mode != ray.WORKER_MODE: if key.startswith(b"FunctionsToRun"): with profiling.profile("fetch_and_run_function"): self.fetch_and_exec...
Run on arbitrary function on the worker.
def fetch_and_execute_function_to_run(self, key): """Run on arbitrary function on the worker.""" (driver_id, serialized_function, run_on_other_drivers) = self.redis_client.hmget( key, ["driver_id", "function", "run_on_other_drivers"]) if (utils.decode(run_on_other_drivers)...
Called to clip actions to the specified range of this policy.
def clip_action(action, space): """Called to clip actions to the specified range of this policy. Arguments: action: Single action. space: Action space the actions should be present in. Returns: Clipped batch of actions. """ if isinstance(space, gym.spaces.Box): ret...
Passes the result to skopt unless early terminated or errored.
def on_trial_complete(self, trial_id, result=None, error=False, early_terminated=False): """Passes the result to skopt unless early terminated or errored. The result is internally negated when intera...
Convert a hostname to a numerical IP addresses in an address.
def address_to_ip(address): """Convert a hostname to a numerical IP addresses in an address. This should be a no-op if address already contains an actual numerical IP address. Args: address: This can be either a string containing a hostname (or an IP address) and a port or it can b...
Determine the IP address of the local node.
def get_node_ip_address(address="8.8.8.8:53"): """Determine the IP address of the local node. Args: address (str): The IP address and port of any known live service on the network you care about. Returns: The IP address of the current node. """ ip_address, port = addres...
Create a Redis client.
def create_redis_client(redis_address, password=None): """Create a Redis client. Args: The IP address, port, and password of the Redis server. Returns: A Redis client. """ redis_ip_address, redis_port = redis_address.split(":") # For this command to work, some other client (on ...
Start one of the Ray processes.
def start_ray_process(command, process_type, env_updates=None, cwd=None, use_valgrind=False, use_gdb=False, use_valgrind_profiler=False, use_perftools_profiler=False,...
Wait for a Redis server to be available.
def wait_for_redis_to_start(redis_ip_address, redis_port, password=None, num_retries=5): """Wait for a Redis server to be available. This is accomplished by creating a Redis client and sending a random command to the server...
Attempt to detect the number of GPUs on this machine.
def _autodetect_num_gpus(): """Attempt to detect the number of GPUs on this machine. TODO(rkn): This currently assumes Nvidia GPUs and Linux. Returns: The number of GPUs if any were detected, otherwise 0. """ proc_gpus_path = "/proc/driver/nvidia/gpus" if os.path.isdir(proc_gpus_path):...
Compute the versions of Python pyarrow and Ray.
def _compute_version_info(): """Compute the versions of Python, pyarrow, and Ray. Returns: A tuple containing the version information. """ ray_version = ray.__version__ python_version = ".".join(map(str, sys.version_info[:3])) pyarrow_version = pyarrow.__version__ return ray_version...
Check if various version info of this process is correct.
def check_version_info(redis_client): """Check if various version info of this process is correct. This will be used to detect if workers or drivers are started using different versions of Python, pyarrow, or Ray. If the version information is not present in Redis, then no check is done. Args: ...
Start the Redis global state store.
def start_redis(node_ip_address, redirect_files, port=None, redis_shard_ports=None, num_redis_shards=1, redis_max_clients=None, redirect_worker_output=False, password=None, use_credis=None, ...
Start a single Redis server.
def _start_redis_instance(executable, modules, port=None, redis_max_clients=None, num_retries=20, stdout_file=None, stderr_file=None, pass...
Start a log monitor process.
def start_log_monitor(redis_address, logs_dir, stdout_file=None, stderr_file=None, redis_password=None): """Start a log monitor process. Args: redis_address (str): The address of the Redis instance. logs_dir...
Start a reporter process.
def start_reporter(redis_address, stdout_file=None, stderr_file=None, redis_password=None): """Start a reporter process. Args: redis_address (str): The address of the Redis instance. stdout_file: A file handle opened for writing to redire...
Start a dashboard process.
def start_dashboard(redis_address, temp_dir, stdout_file=None, stderr_file=None, redis_password=None): """Start a dashboard process. Args: redis_address (str): The address of the Redis instance. temp_dir (str): The ...
Sanity check a resource dictionary and add sensible defaults.
def check_and_update_resources(num_cpus, num_gpus, resources): """Sanity check a resource dictionary and add sensible defaults. Args: num_cpus: The number of CPUs. num_gpus: The number of GPUs. resources: A dictionary mapping resource names to resource quantities. Returns: ...
Start a raylet which is a combined local scheduler and object manager.
def start_raylet(redis_address, node_ip_address, raylet_name, plasma_store_name, worker_path, temp_dir, num_cpus=None, num_gpus=None, resources=None, object_manager_po...
This method assembles the command used to start a Java worker.
def build_java_worker_command( java_worker_options, redis_address, plasma_store_name, raylet_name, redis_password, temp_dir, ): """This method assembles the command used to start a Java worker. Args: java_worker_options (str): The command options for Java...
Figure out how to configure the plasma object store.
def determine_plasma_store_config(object_store_memory=None, plasma_directory=None, huge_pages=False): """Figure out how to configure the plasma object store. This will determine which directory to use for the plasma store (e.g., /tmp or /d...
Start a plasma store process.
def _start_plasma_store(plasma_store_memory, use_valgrind=False, use_profiler=False, stdout_file=None, stderr_file=None, plasma_directory=None, huge_pages=False, ...
This method starts an object store process.
def start_plasma_store(stdout_file=None, stderr_file=None, object_store_memory=None, plasma_directory=None, huge_pages=False, plasma_store_socket_name=None): """This method starts an object store proce...
This method starts a worker process.
def start_worker(node_ip_address, object_store_name, raylet_name, redis_address, worker_path, temp_dir, stdout_file=None, stderr_file=None): """This method starts a worker process. Args: ...
Run a process to monitor the other processes.
def start_monitor(redis_address, stdout_file=None, stderr_file=None, autoscaling_config=None, redis_password=None): """Run a process to monitor the other processes. Args: redis_address (str): The address that the Redis server is li...
Run a process to monitor the other processes.
def start_raylet_monitor(redis_address, stdout_file=None, stderr_file=None, redis_password=None, config=None): """Run a process to monitor the other processes. Args: redis_address (str): The address that...
Unpacks Dict and Tuple space observations into their original form.
def restore_original_dimensions(obs, obs_space, tensorlib=tf): """Unpacks Dict and Tuple space observations into their original form. This is needed since we flatten Dict and Tuple observations in transit. Before sending them to the model though, we should unflatten them into Dicts or Tuples of tensors...
Unpack a flattened Dict or Tuple observation array/ tensor.
def _unpack_obs(obs, space, tensorlib=tf): """Unpack a flattened Dict or Tuple observation array/tensor. Arguments: obs: The flattened observation tensor space: The original space prior to flattening tensorlib: The library used to unflatten (reshape) the array/tensor """ if (is...
Convert the Ray node name tag to the AWS - specific Name tag.
def to_aws_format(tags): """Convert the Ray node name tag to the AWS-specific 'Name' tag.""" if TAG_RAY_NODE_NAME in tags: tags["Name"] = tags[TAG_RAY_NODE_NAME] del tags[TAG_RAY_NODE_NAME] return tags
Update the AWS tags for a cluster periodically.
def _node_tag_update_loop(self): """ Update the AWS tags for a cluster periodically. The purpose of this loop is to avoid excessive EC2 calls when a large number of nodes are being launched simultaneously. """ while True: self.tag_cache_update_event.wait() ...
Refresh and get info for this node updating the cache.
def _get_node(self, node_id): """Refresh and get info for this node, updating the cache.""" self.non_terminated_nodes({}) # Side effect: updates cache if node_id in self.cached_nodes: return self.cached_nodes[node_id] # Node not in {pending, running} -- retry with a point ...
Validates export_formats.
def validate(export_formats): """Validates export_formats. Raises: ValueError if the format is unknown. """ for i in range(len(export_formats)): export_formats[i] = export_formats[i].strip().lower() if export_formats[i] not in [ Ex...
Init logger.
def init_logger(self): """Init logger.""" if not self.result_logger: if not os.path.exists(self.local_dir): os.makedirs(self.local_dir) if not self.logdir: self.logdir = tempfile.mkdtemp( prefix="{}_{}".format( ...
EXPERIMENTAL: Updates the resource requirements.
def update_resources(self, cpu, gpu, **kwargs): """EXPERIMENTAL: Updates the resource requirements. Should only be called when the trial is not running. Raises: ValueError if trial status is running. """ if self.status is Trial.RUNNING: raise ValueError(...
Whether the given result meets this trial s stopping criteria.
def should_stop(self, result): """Whether the given result meets this trial's stopping criteria.""" if result.get(DONE): return True for criteria, stop_value in self.stopping_criterion.items(): if criteria not in result: raise TuneError( ...
Whether this trial is due for checkpointing.
def should_checkpoint(self): """Whether this trial is due for checkpointing.""" result = self.last_result or {} if result.get(DONE) and self.checkpoint_at_end: return True if self.checkpoint_freq: return result.get(TRAINING_ITERATION, ...
Returns a progress message for printing out to the console.
def progress_string(self): """Returns a progress message for printing out to the console.""" if not self.last_result: return self._status_string() def location_string(hostname, pid): if hostname == os.uname()[1]: return "pid={}".format(pid) e...
Returns whether the trial qualifies for restoring.
def should_recover(self): """Returns whether the trial qualifies for restoring. This is if a checkpoint frequency is set and has not failed more than max_failures. This may return true even when there may not yet be a checkpoint. """ return (self.checkpoint_freq > 0 ...
Compares two checkpoints based on the attribute attr_mean param. Greater than is used by default. If command - line parameter checkpoint_score_attr starts with min - less than is used.
def compare_checkpoints(self, attr_mean): """Compares two checkpoints based on the attribute attr_mean param. Greater than is used by default. If command-line parameter checkpoint_score_attr starts with "min-" less than is used. Arguments: attr_mean: mean of attribute value...
Preprocess 210x160x3 uint8 frame into 6400 ( 80x80 ) 1D float vector.
def preprocess(img): """Preprocess 210x160x3 uint8 frame into 6400 (80x80) 1D float vector.""" # Crop the image. img = img[35:195] # Downsample by factor of 2. img = img[::2, ::2, 0] # Erase background (background type 1). img[img == 144] = 0 # Erase background (background type 2). i...
take 1D float array of rewards and compute discounted reward
def discount_rewards(r): """take 1D float array of rewards and compute discounted reward""" discounted_r = np.zeros_like(r) running_add = 0 for t in reversed(range(0, r.size)): # Reset the sum, since this was a game boundary (pong specific!). if r[t] != 0: running_add = 0 ...
backward pass. ( eph is array of intermediate hidden states )
def policy_backward(eph, epx, epdlogp, model): """backward pass. (eph is array of intermediate hidden states)""" dW2 = np.dot(eph.T, epdlogp).ravel() dh = np.outer(epdlogp, model["W2"]) # Backprop relu. dh[eph <= 0] = 0 dW1 = np.dot(dh.T, epx) return {"W1": dW1, "W2": dW2}
Load a class at runtime given a full path.
def load_class(path): """ Load a class at runtime given a full path. Example of the path: mypkg.mysubpkg.myclass """ class_data = path.split(".") if len(class_data) < 2: raise ValueError( "You need to pass a valid path like mymodule.provider_class") module_path = ".".joi...
Terminates a set of nodes. May be overridden with a batch method.
def terminate_nodes(self, node_ids): """Terminates a set of nodes. May be overridden with a batch method.""" for node_id in node_ids: logger.info("NodeProvider: " "{}: Terminating node".format(node_id)) self.terminate_node(node_id)
Passes the result to BayesOpt unless early terminated or errored
def on_trial_complete(self, trial_id, result=None, error=False, early_terminated=False): """Passes the result to BayesOpt unless early terminated or errored""" if result: self.optimizer.re...
Execute method with arg and return the result.
def _execute_and_seal_error(method, arg, method_name): """Execute method with arg and return the result. If the method fails, return a RayTaskError so it can be sealed in the resultOID and retried by user. """ try: return method(arg) except Exception: return ray.worker.RayTaskEr...
Helper method to dispatch a batch of input to self. serve_method.
def _dispatch(self, input_batch: List[SingleQuery]): """Helper method to dispatch a batch of input to self.serve_method.""" method = getattr(self, self.serve_method) if hasattr(method, "ray_serve_batched_input"): batch = [inp.data for inp in input_batch] result = _execute...
Returns the gym env wrapper of the given class or None.
def get_wrapper_by_cls(env, cls): """Returns the gym env wrapper of the given class, or None.""" currentenv = env while True: if isinstance(currentenv, cls): return currentenv elif isinstance(currentenv, gym.Wrapper): currentenv = currentenv.env else: ...
Configure environment for DeepMind - style Atari.
def wrap_deepmind(env, dim=84, framestack=True): """Configure environment for DeepMind-style Atari. Note that we assume reward clipping is done outside the wrapper. Args: dim (int): Dimension to resize observations to (dim x dim). framestack (bool): Whether to framestack observations. ...
Note: Padding is added to match TF conv2d same padding. See www. tensorflow. org/ versions/ r0. 12/ api_docs/ python/ nn/ convolution
def valid_padding(in_size, filter_size, stride_size): """Note: Padding is added to match TF conv2d `same` padding. See www.tensorflow.org/versions/r0.12/api_docs/python/nn/convolution Params: in_size (tuple): Rows (Height), Column (Width) for input stride_size (tuple): Rows (Height), Column...
Call ray. get and then queue the object ids for deletion.
def ray_get_and_free(object_ids): """Call ray.get and then queue the object ids for deletion. This function should be used whenever possible in RLlib, to optimize memory usage. The only exception is when an object_id is shared among multiple readers. Args: object_ids (ObjectID|List[ObjectI...
Returns an array of a given size that is 64 - byte aligned.
def aligned_array(size, dtype, align=64): """Returns an array of a given size that is 64-byte aligned. The returned array can be efficiently copied into GPU memory by TensorFlow. """ n = size * dtype.itemsize empty = np.empty(n + (align - 1), dtype=np.uint8) data_align = empty.ctypes.data % al...
Concatenate arrays ensuring the output is 64 - byte aligned.
def concat_aligned(items): """Concatenate arrays, ensuring the output is 64-byte aligned. We only align float arrays; other arrays are concatenated as normal. This should be used instead of np.concatenate() to improve performance when the output array is likely to be fed into TensorFlow. """ ...
Adds an item to the queue.
def put(self, item, block=True, timeout=None): """Adds an item to the queue. Uses polling if block=True, so there is no guarantee of order if multiple producers put to the same full queue. Raises: Full if the queue is full and blocking is False. """ if self....
Gets an item from the queue.
def get(self, block=True, timeout=None): """Gets an item from the queue. Uses polling if block=True, so there is no guarantee of order if multiple consumers get from the same empty queue. Returns: The next item in the queue. Raises: Empty if the queue i...
Annotation for documenting method overrides.
def override(cls): """Annotation for documenting method overrides. Arguments: cls (type): The superclass that provides the overriden method. If this cls does not actually have the method, an error is raised. """ def check_override(method): if method.__name__ not in dir(cls)...
Adds new trial.
def on_trial_add(self, trial_runner, trial): """Adds new trial. On a new trial add, if current bracket is not filled, add to current bracket. Else, if current band is not filled, create new bracket, add to current bracket. Else, create new iteration, create new bracket, add to b...
Checks if the current band is filled.
def _cur_band_filled(self): """Checks if the current band is filled. The size of the current band should be equal to s_max_1""" cur_band = self._hyperbands[self._state["band_idx"]] return len(cur_band) == self._s_max_1
If bracket is finished all trials will be stopped.
def on_trial_result(self, trial_runner, trial, result): """If bracket is finished, all trials will be stopped. If a given trial finishes and bracket iteration is not done, the trial will be paused and resources will be given up. This scheduler will not start trials but will stop trials...
This is called whenever a trial makes progress.
def _process_bracket(self, trial_runner, bracket, trial): """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, ...
Notification when trial terminates.
def on_trial_remove(self, trial_runner, trial): """Notification when trial terminates. Trial info is removed from bracket. Triggers halving if bracket is not finished.""" bracket, _ = self._trial_info[trial] bracket.cleanup_trial(trial) if not bracket.finished(): ...
Fair scheduling within iteration by completion percentage.
def choose_trial_to_run(self, trial_runner): """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. """ for...
This provides a progress notification for the algorithm.
def debug_string(self): """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...
Add trial to bracket assuming bracket is not filled.
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 opportunity to catch up.""" assert not self.filled(), "Cannot add trial to filled bracket!" self._live_trials[trial] = None s...
Checks if all iterations have completed.
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._cumul_r for result in self._live_trials.values())
Update result for trial. Called after trial has finished an iteration - will decrement iteration count.
def update_trial_stats(self, trial, result): """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.""" assert trial in...
Cleans up bracket after bracket is completely finished.
def cleanup_full(self, trial_runner): """Cleans up bracket after bracket is completely finished. Lets the last trial continue to run until termination condition kicks in.""" for trial in self.current_trials(): if (trial.status == Trial.PAUSED): trial_runner.s...
Read the client table.
def parse_client_table(redis_client): """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. """ NIL_CLIENT_ID = ray.ObjectID.nil().binary() message = redis_client.execute_command("RAY.TA...
Initialize the GlobalState object by connecting to Redis.
def _initialize_global_state(self, redis_address, redis_password=None, timeout=20): """Initialize the GlobalState object by connecting to Redis. It's possible that certain keys in Redis may not have been ...
Execute a Redis command on the appropriate Redis shard based on key.
def _execute_command(self, key, *args): """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. ...
Execute the KEYS command on all Redis shards.
def _keys(self, pattern): """Execute the KEYS command on all Redis shards. Args: pattern: The KEYS pattern to query. Returns: The concatenated list of results from all shards. """ result = [] for client in self.redis_clients: result.e...
Fetch and parse the object table information for a single object ID.
def _object_table(self, object_id): """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. """ # Allow the ar...
Fetch and parse the object table info for one or more object IDs.
def object_table(self, object_id=None): """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...
Fetch and parse the task table information for a single task ID.
def _task_table(self, task_id): """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. """ assert isinstance(task_id, ra...
Fetch and parse the task table information for one or more task IDs.
def task_table(self, task_id=None): """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: Informatio...
Fetch and parse the function table.
def function_table(self, function_id=None): """Fetch and parse the function table. Returns: A dictionary that maps function IDs to information about the function. """ self._check_connected() function_table_keys = self.redis_client.keys( ra...
Get the profile events for a given batch of profile events.
def _profile_table(self, batch_id): """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. """ # TODO(rkn): This method sh...
Return a list of profiling events that can viewed as a timeline.
def chrome_tracing_dump(self, filename=None): """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 w...
Return a list of transfer events that can viewed as a timeline.
def chrome_tracing_object_transfer_dump(self, filename=None): """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 ...
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.hgetall(worker_key) worker_id = binary_to_hex(worke...
Get the current total cluster resources.
def cluster_resources(self): """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 cl...
Get the current available cluster resources.
def available_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. Retur...
Get the error messages for a specific driver.
def _error_messages(self, driver_id): """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. """ assert isinstance(driver_id, ray.DriverID) ...