Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def check_serializable(cls): if is_named_tuple(cls): # This case works. return if not hasattr(cls, "__new__"): print("The class {} does not have a '__new__' attribute and is " "probably an old-stye class. Please make it a ne...
[ "Throws an exception if Ray cannot serialize this class efficiently.\n\n Args:\n cls (type): The class to be serialized.\n\n Raises:\n Exception: An exception is raised if Ray cannot serialize this class\n efficiently.\n " ]
Please provide a description of the function:def is_named_tuple(cls): 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)
[ "Return True if cls is a namedtuple and False otherwise." ]
Please provide a description of the function:def register_trainable(name, trainable): from ray.tune.trainable import Trainable from ray.tune.function_runner import wrap_function if isinstance(trainable, type): logger.debug("Detected class for trainable.") elif isinstance(trainable, Functi...
[ "Register a trainable function or class.\n\n Args:\n name (str): Name to register.\n trainable (obj): Function or tune.Trainable class. Functions must\n take (config, status_reporter) as arguments and will be\n automatically converted into a class during registration.\n " ]
Please provide a description of the function:def register_env(name, env_creator): if not isinstance(env_creator, FunctionType): raise TypeError("Second argument must be a function.", env_creator) _global_registry.register(ENV_CREATOR, name, env_creator)
[ "Register a custom environment for use with RLlib.\n\n Args:\n name (str): Name to register.\n env_creator (obj): Function that creates an env.\n " ]
Please provide a description of the function:def get_learner_stats(grad_info): if LEARNER_STATS_KEY in grad_info: return grad_info[LEARNER_STATS_KEY] multiagent_stats = {} for k, v in grad_info.items(): if type(v) is dict: if LEARNER_STATS_KEY in v: multiag...
[ "Return optimization stats reported from the policy graph.\n\n Example:\n >>> grad_info = evaluator.learn_on_batch(samples)\n >>> print(get_stats(grad_info))\n {\"vf_loss\": ..., \"policy_loss\": ...}\n " ]
Please provide a description of the function:def collect_metrics(local_evaluator=None, remote_evaluators=[], timeout_seconds=180): episodes, num_dropped = collect_episodes( local_evaluator, remote_evaluators, timeout_seconds=timeout_seconds) metrics = summar...
[ "Gathers episode metrics from PolicyEvaluator instances." ]
Please provide a description of the function:def collect_episodes(local_evaluator=None, remote_evaluators=[], timeout_seconds=180): pending = [ a.apply.remote(lambda ev: ev.get_metrics()) for a in remote_evaluators ] collected, _ = ray.wait( pe...
[ "Gathers new episodes metrics tuples from the given evaluators." ]
Please provide a description of the function:def summarize_episodes(episodes, new_episodes, num_dropped): if num_dropped > 0: logger.warning("WARNING: {} workers have NOT returned metrics".format( num_dropped)) episodes, estimates = _partition(episodes) new_episodes, _ = _partitio...
[ "Summarizes a set of episode metrics tuples.\n\n Arguments:\n episodes: smoothed set of episodes including historical ones\n new_episodes: just the new episodes in this iteration\n num_dropped: number of workers haven't returned their metrics\n " ]
Please provide a description of the function:def _partition(episodes): from ray.rllib.evaluation.sampler import RolloutMetrics rollouts, estimates = [], [] for e in episodes: if isinstance(e, RolloutMetrics): rollouts.append(e) elif isinstance(e, OffPolicyEstimate): ...
[ "Divides metrics data into true rollouts vs off-policy estimates." ]
Please provide a description of the function:def set_status(self, trial, status): trial.status = status if status in [Trial.TERMINATED, Trial.ERROR]: self.try_checkpoint_metadata(trial)
[ "Sets status and checkpoints metadata if needed.\n\n Only checkpoints metadata if trial status is a terminal condition.\n PENDING, PAUSED, and RUNNING switches have checkpoints taken care of\n in the TrialRunner.\n\n Args:\n trial (Trial): Trial to checkpoint.\n sta...
Please provide a description of the function:def try_checkpoint_metadata(self, trial): if trial._checkpoint.storage == Checkpoint.MEMORY: logger.debug("Not saving data for trial w/ memory checkpoint.") return try: logger.debug("Saving trial metadata.") ...
[ "Checkpoints metadata.\n\n Args:\n trial (Trial): Trial to checkpoint.\n " ]
Please provide a description of the function:def pause_trial(self, trial): assert trial.status == Trial.RUNNING, trial.status try: self.save(trial, Checkpoint.MEMORY) self.stop_trial(trial, stop_logger=False) self.set_status(trial, Trial.PAUSED) excep...
[ "Pauses the trial.\n\n We want to release resources (specifically GPUs) when pausing an\n experiment. This results in PAUSED state that similar to TERMINATED.\n " ]
Please provide a description of the function:def unpause_trial(self, trial): assert trial.status == Trial.PAUSED, trial.status self.set_status(trial, Trial.PENDING)
[ "Sets PAUSED trial to pending to allow scheduler to start." ]
Please provide a description of the function:def resume_trial(self, trial): assert trial.status == Trial.PAUSED, trial.status self.start_trial(trial)
[ "Resumes PAUSED trials. This is a blocking call." ]
Please provide a description of the function:def on_trial_complete(self, trial_id, result=None, error=False, early_terminated=False): ng_trial_info = self._live_trial_mapping.pop(trial_id) if...
[ "Passes the result to Nevergrad unless early terminated or errored.\n\n The result is internally negated when interacting with Nevergrad\n so that Nevergrad Optimizers can \"maximize\" this value,\n as it minimizes on default.\n " ]
Please provide a description of the function:def start(self): 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()
[ "Start the import thread." ]
Please provide a description of the function:def _process_key(self, key): # 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_execu...
[ "Process the given export key from redis." ]
Please provide a description of the function:def fetch_and_execute_function_to_run(self, key): (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) ...
[ "Run on arbitrary function on the worker." ]
Please provide a description of the function:def clip_action(action, space): if isinstance(space, gym.spaces.Box): return np.clip(action, space.low, space.high) elif isinstance(space, gym.spaces.Tuple): if type(action) not in (tuple, list): raise ValueError("Expected tuple spac...
[ "Called to clip actions to the specified range of this policy.\n\n Arguments:\n action: Single action.\n space: Action space the actions should be present in.\n\n Returns:\n Clipped batch of actions.\n " ]
Please provide a description of the function:def on_trial_complete(self, trial_id, result=None, error=False, early_terminated=False): skopt_trial_info = self._live_trial_mapping.pop(trial_id) ...
[ "Passes the result to skopt unless early terminated or errored.\n\n The result is internally negated when interacting with Skopt\n so that Skopt Optimizers can \"maximize\" this value,\n as it minimizes on default.\n " ]
Please provide a description of the function:def address_to_ip(address): address_parts = address.split(":") ip_address = socket.gethostbyname(address_parts[0]) # Make sure localhost isn't resolved to the loopback ip if ip_address == "127.0.0.1": ip_address = get_node_ip_address() return...
[ "Convert a hostname to a numerical IP addresses in an address.\n\n This should be a no-op if address already contains an actual numerical IP\n address.\n\n Args:\n address: This can be either a string containing a hostname (or an IP\n address) and a port or it can be just an IP address.\n...
Please provide a description of the function:def get_node_ip_address(address="8.8.8.8:53"): ip_address, port = address.split(":") s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: # This command will raise an exception if there is no internet # connection. s.connect((ip_...
[ "Determine the IP address of the local node.\n\n Args:\n address (str): The IP address and port of any known live service on the\n network you care about.\n\n Returns:\n The IP address of the current node.\n " ]
Please provide a description of the function:def create_redis_client(redis_address, password=None): redis_ip_address, redis_port = redis_address.split(":") # For this command to work, some other client (on the same machine # as Redis) must have run "CONFIG SET protected-mode no". return redis.Stric...
[ "Create a Redis client.\n\n Args:\n The IP address, port, and password of the Redis server.\n\n Returns:\n A Redis client.\n " ]
Please provide a description of the function:def start_ray_process(command, process_type, env_updates=None, cwd=None, use_valgrind=False, use_gdb=False, use_valgrind_profiler=False, ...
[ "Start one of the Ray processes.\n\n TODO(rkn): We need to figure out how these commands interact. For example,\n it may only make sense to start a process in gdb if we also start it in\n tmux. Similarly, certain combinations probably don't make sense, like\n simultaneously running the process in valgri...
Please provide a description of the function:def wait_for_redis_to_start(redis_ip_address, redis_port, password=None, num_retries=5): redis_client = redis.StrictRedis( host=redis_ip_address, port=redis_port, password=pa...
[ "Wait for a Redis server to be available.\n\n This is accomplished by creating a Redis client and sending a random\n command to the server until the command gets through.\n\n Args:\n redis_ip_address (str): The IP address of the redis server.\n redis_port (int): The port of the redis server.\...
Please provide a description of the function:def _autodetect_num_gpus(): proc_gpus_path = "/proc/driver/nvidia/gpus" if os.path.isdir(proc_gpus_path): return len(os.listdir(proc_gpus_path)) return 0
[ "Attempt to detect the number of GPUs on this machine.\n\n TODO(rkn): This currently assumes Nvidia GPUs and Linux.\n\n Returns:\n The number of GPUs if any were detected, otherwise 0.\n " ]
Please provide a description of the function:def _compute_version_info(): ray_version = ray.__version__ python_version = ".".join(map(str, sys.version_info[:3])) pyarrow_version = pyarrow.__version__ return ray_version, python_version, pyarrow_version
[ "Compute the versions of Python, pyarrow, and Ray.\n\n Returns:\n A tuple containing the version information.\n " ]
Please provide a description of the function:def check_version_info(redis_client): redis_reply = redis_client.get("VERSION_INFO") # Don't do the check if there is no version information in Redis. This # is to make it easier to do things like start the processes by hand. if redis_reply is None: ...
[ "Check if various version info of this process is correct.\n\n This will be used to detect if workers or drivers are started using\n different versions of Python, pyarrow, or Ray. If the version\n information is not present in Redis, then no check is done.\n\n Args:\n redis_client: A client for t...
Please provide a description of the function: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, passw...
[ "Start the Redis global state store.\n\n Args:\n node_ip_address: The IP address of the current node. This is only used\n for recording the log filenames in Redis.\n redirect_files: The list of (stdout, stderr) file pairs.\n port (int): If provided, the primary Redis shard will be...
Please provide a description of the function:def _start_redis_instance(executable, modules, port=None, redis_max_clients=None, num_retries=20, stdout_file=None, std...
[ "Start a single Redis server.\n\n Notes:\n If \"port\" is not None, then we will only use this port and try\n only once. Otherwise, random ports will be used and the maximum\n retries count is \"num_retries\".\n\n Args:\n executable (str): Full path of the redis-server executable.\...
Please provide a description of the function:def start_log_monitor(redis_address, logs_dir, stdout_file=None, stderr_file=None, redis_password=None): log_monitor_filepath = os.path.join( os.path.dirname(os.path.absp...
[ "Start a log monitor process.\n\n Args:\n redis_address (str): The address of the Redis instance.\n logs_dir (str): The directory of logging files.\n stdout_file: A file handle opened for writing to redirect stdout to. If\n no redirection should happen, then this should be None.\n...
Please provide a description of the function:def start_reporter(redis_address, stdout_file=None, stderr_file=None, redis_password=None): reporter_filepath = os.path.join( os.path.dirname(os.path.abspath(__file__)), "reporter.py") command = [ ...
[ "Start a reporter process.\n\n Args:\n redis_address (str): The address of the Redis instance.\n stdout_file: A file handle opened for writing to redirect stdout to. If\n no redirection should happen, then this should be None.\n stderr_file: A file handle opened for writing to red...
Please provide a description of the function:def start_dashboard(redis_address, temp_dir, stdout_file=None, stderr_file=None, redis_password=None): port = 8080 while True: try: port_test_socket = socket.sock...
[ "Start a dashboard process.\n\n Args:\n redis_address (str): The address of the Redis instance.\n temp_dir (str): The temporary directory used for log files and\n information for this Ray session.\n stdout_file: A file handle opened for writing to redirect stdout to. If\n ...
Please provide a description of the function:def check_and_update_resources(num_cpus, num_gpus, resources): if resources is None: resources = {} resources = resources.copy() assert "CPU" not in resources assert "GPU" not in resources if num_cpus is not None: resources["CPU"] = n...
[ "Sanity check a resource dictionary and add sensible defaults.\n\n Args:\n num_cpus: The number of CPUs.\n num_gpus: The number of GPUs.\n resources: A dictionary mapping resource names to resource quantities.\n\n Returns:\n A new resource dictionary.\n " ]
Please provide a description of the function:def start_raylet(redis_address, node_ip_address, raylet_name, plasma_store_name, worker_path, temp_dir, num_cpus=None, num_gpus=None, resou...
[ "Start a raylet, which is a combined local scheduler and object manager.\n\n Args:\n redis_address (str): The address of the primary Redis server.\n node_ip_address (str): The IP address of this node.\n raylet_name (str): The name of the raylet socket to create.\n plasma_store_name (s...
Please provide a description of the function:def build_java_worker_command( java_worker_options, redis_address, plasma_store_name, raylet_name, redis_password, temp_dir, ): assert java_worker_options is not None command = "java ".format(java_worker_options) ...
[ "This method assembles the command used to start a Java worker.\n\n Args:\n java_worker_options (str): The command options for Java worker.\n redis_address (str): Redis address of GCS.\n plasma_store_name (str): The name of the plasma store socket to connect\n to.\n raylet_n...
Please provide a description of the function:def determine_plasma_store_config(object_store_memory=None, plasma_directory=None, huge_pages=False): system_memory = ray.utils.get_system_memory() # Choose a default object store size. if ...
[ "Figure out how to configure the plasma object store.\n\n This will determine which directory to use for the plasma store (e.g.,\n /tmp or /dev/shm) and how much memory to start the store with. On Linux,\n we will try to use /dev/shm unless the shared memory file system is too\n small, in which case we ...
Please provide a description of the function:def _start_plasma_store(plasma_store_memory, use_valgrind=False, use_profiler=False, stdout_file=None, stderr_file=None, plasma_directory=None, ...
[ "Start a plasma store process.\n\n Args:\n plasma_store_memory (int): The amount of memory in bytes to start the\n plasma store with.\n use_valgrind (bool): True if the plasma store should be started inside\n of valgrind. If this is True, use_profiler must be False.\n u...
Please provide a description of the function: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 process.\n\n Args:\n stdout_file: A file handle opened for writing to redirect stdout\n to. If no redirection should happen, then this should be None.\n stderr_file: A file handle opened for writing to redirect stderr\n to. If no redirection...
Please provide a description of the function:def start_worker(node_ip_address, object_store_name, raylet_name, redis_address, worker_path, temp_dir, stdout_file=None, stderr_file=None): comman...
[ "This method starts a worker process.\n\n Args:\n node_ip_address (str): The IP address of the node that this worker is\n running on.\n object_store_name (str): The socket name of the object store.\n raylet_name (str): The socket name of the raylet server.\n redis_address (...
Please provide a description of the function:def start_monitor(redis_address, stdout_file=None, stderr_file=None, autoscaling_config=None, redis_password=None): monitor_path = os.path.join( os.path.dirname(os.path.abspath(__file__)...
[ "Run a process to monitor the other processes.\n\n Args:\n redis_address (str): The address that the Redis server is listening on.\n stdout_file: A file handle opened for writing to redirect stdout to. If\n no redirection should happen, then this should be None.\n stderr_file: A f...
Please provide a description of the function:def start_raylet_monitor(redis_address, stdout_file=None, stderr_file=None, redis_password=None, config=None): gcs_ip_address, gcs_port = redis_address.split(":") ...
[ "Run a process to monitor the other processes.\n\n Args:\n redis_address (str): The address that the Redis server is listening on.\n stdout_file: A file handle opened for writing to redirect stdout to. If\n no redirection should happen, then this should be None.\n stderr_file: A f...
Please provide a description of the function:def restore_original_dimensions(obs, obs_space, tensorlib=tf): if hasattr(obs_space, "original_space"): return _unpack_obs(obs, obs_space.original_space, tensorlib=tensorlib) else: return obs
[ "Unpacks Dict and Tuple space observations into their original form.\n\n This is needed since we flatten Dict and Tuple observations in transit.\n Before sending them to the model though, we should unflatten them into\n Dicts or Tuples of tensors.\n\n Arguments:\n obs: The flattened observation t...
Please provide a description of the function:def _unpack_obs(obs, space, tensorlib=tf): if (isinstance(space, gym.spaces.Dict) or isinstance(space, gym.spaces.Tuple)): prep = get_preprocessor(space)(space) if len(obs.shape) != 2 or obs.shape[1] != prep.shape[0]: raise V...
[ "Unpack a flattened Dict or Tuple observation array/tensor.\n\n Arguments:\n obs: The flattened observation tensor\n space: The original space prior to flattening\n tensorlib: The library used to unflatten (reshape) the array/tensor\n " ]
Please provide a description of the function:def to_aws_format(tags): if TAG_RAY_NODE_NAME in tags: tags["Name"] = tags[TAG_RAY_NODE_NAME] del tags[TAG_RAY_NODE_NAME] return tags
[ "Convert the Ray node name tag to the AWS-specific 'Name' tag." ]
Please provide a description of the function:def _node_tag_update_loop(self): while True: self.tag_cache_update_event.wait() self.tag_cache_update_event.clear() batch_updates = defaultdict(list) with self.tag_cache_lock: for node_id, tag...
[ " Update the AWS tags for a cluster periodically.\n\n The purpose of this loop is to avoid excessive EC2 calls when a large\n number of nodes are being launched simultaneously.\n " ]
Please provide a description of the function:def _get_node(self, node_id): 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 query. This ...
[ "Refresh and get info for this node, updating the cache." ]
Please provide a description of the function:def validate(export_formats): for i in range(len(export_formats)): export_formats[i] = export_formats[i].strip().lower() if export_formats[i] not in [ ExportFormat.CHECKPOINT, ExportFormat.MODEL ]: ...
[ "Validates export_formats.\n\n Raises:\n ValueError if the format is unknown.\n " ]
Please provide a description of the function:def init_logger(self): 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="{}_{...
[ "Init logger." ]
Please provide a description of the function:def update_resources(self, cpu, gpu, **kwargs): if self.status is Trial.RUNNING: raise ValueError("Cannot update resources while Trial is running.") self.resources = Resources(cpu, gpu, **kwargs)
[ "EXPERIMENTAL: Updates the resource requirements.\n\n Should only be called when the trial is not running.\n\n Raises:\n ValueError if trial status is running.\n " ]
Please provide a description of the function:def should_stop(self, result): if result.get(DONE): return True for criteria, stop_value in self.stopping_criterion.items(): if criteria not in result: raise TuneError( "Stopping criteria ...
[ "Whether the given result meets this trial's stopping criteria." ]
Please provide a description of the function:def should_checkpoint(self): 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, 0)...
[ "Whether this trial is due for checkpointing." ]
Please provide a description of the function:def should_recover(self): return (self.checkpoint_freq > 0 and (self.num_failures < self.max_failures or self.max_failures < 0))
[ "Returns whether the trial qualifies for restoring.\n\n This is if a checkpoint frequency is set and has not failed more than\n max_failures. This may return true even when there may not yet\n be a checkpoint.\n " ]
Please provide a description of the function:def compare_checkpoints(self, attr_mean): if self._cmp_greater and attr_mean > self.best_checkpoint_attr_value: return True elif (not self._cmp_greater and attr_mean < self.best_checkpoint_attr_value): return Tru...
[ "Compares two checkpoints based on the attribute attr_mean param.\n Greater than is used by default. If command-line parameter\n checkpoint_score_attr starts with \"min-\" less than is used.\n\n Arguments:\n attr_mean: mean of attribute value for the current checkpoint\n\n Re...
Please provide a description of the function:def preprocess(img): # 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). img[img == 109] = 0 # Set...
[ "Preprocess 210x160x3 uint8 frame into 6400 (80x80) 1D float vector." ]
Please provide a description of the function:def discount_rewards(r): 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 running_add = ru...
[ "take 1D float array of rewards and compute discounted reward" ]
Please provide a description of the function:def policy_backward(eph, epx, epdlogp, model): 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}
[ "backward pass. (eph is array of intermediate hidden states)" ]
Please provide a description of the function:def load_class(path): class_data = path.split(".") if len(class_data) < 2: raise ValueError( "You need to pass a valid path like mymodule.provider_class") module_path = ".".join(class_data[:-1]) class_str = class_data[-1] module =...
[ "\n Load a class at runtime given a full path.\n\n Example of the path: mypkg.mysubpkg.myclass\n " ]
Please provide a description of the function:def terminate_nodes(self, node_ids): for node_id in node_ids: logger.info("NodeProvider: " "{}: Terminating node".format(node_id)) self.terminate_node(node_id)
[ "Terminates a set of nodes. May be overridden with a batch method." ]
Please provide a description of the function:def on_trial_complete(self, trial_id, result=None, error=False, early_terminated=False): if result: self.optimizer.register( p...
[ "Passes the result to BayesOpt unless early terminated or errored" ]
Please provide a description of the function:def _execute_and_seal_error(method, arg, method_name): try: return method(arg) except Exception: return ray.worker.RayTaskError(method_name, traceback.format_exc())
[ "Execute method with arg and return the result.\n\n If the method fails, return a RayTaskError so it can be sealed in the\n resultOID and retried by user.\n " ]
Please provide a description of the function:def _dispatch(self, input_batch: List[SingleQuery]): method = getattr(self, self.serve_method) if hasattr(method, "ray_serve_batched_input"): batch = [inp.data for inp in input_batch] result = _execute_and_seal_error(method, b...
[ "Helper method to dispatch a batch of input to self.serve_method." ]
Please provide a description of the function:def get_wrapper_by_cls(env, cls): currentenv = env while True: if isinstance(currentenv, cls): return currentenv elif isinstance(currentenv, gym.Wrapper): currentenv = currentenv.env else: return None
[ "Returns the gym env wrapper of the given class, or None." ]
Please provide a description of the function:def wrap_deepmind(env, dim=84, framestack=True): env = MonitorEnv(env) env = NoopResetEnv(env, noop_max=30) if "NoFrameskip" in env.spec.id: env = MaxAndSkipEnv(env, skip=4) env = EpisodicLifeEnv(env) if "FIRE" in env.unwrapped.get_action_mea...
[ "Configure environment for DeepMind-style Atari.\n\n Note that we assume reward clipping is done outside the wrapper.\n\n Args:\n dim (int): Dimension to resize observations to (dim x dim).\n framestack (bool): Whether to framestack observations.\n " ]
Please provide a description of the function:def valid_padding(in_size, filter_size, stride_size): in_height, in_width = in_size filter_height, filter_width = filter_size stride_height, stride_width = stride_size out_height = np.ceil(float(in_height) / float(stride_height)) out_width = np.ceil...
[ "Note: Padding is added to match TF conv2d `same` padding. See\n www.tensorflow.org/versions/r0.12/api_docs/python/nn/convolution\n\n Params:\n in_size (tuple): Rows (Height), Column (Width) for input\n stride_size (tuple): Rows (Height), Column (Width) for stride\n filter_size (tuple): R...
Please provide a description of the function:def ray_get_and_free(object_ids): global _last_free_time global _to_free result = ray.get(object_ids) if type(object_ids) is not list: object_ids = [object_ids] _to_free.extend(object_ids) # batch calls to free to reduce overheads ...
[ "Call ray.get and then queue the object ids for deletion.\n\n This function should be used whenever possible in RLlib, to optimize\n memory usage. The only exception is when an object_id is shared among\n multiple readers.\n\n Args:\n object_ids (ObjectID|List[ObjectID]): Object ids to fetch and ...
Please provide a description of the function:def aligned_array(size, dtype, align=64): n = size * dtype.itemsize empty = np.empty(n + (align - 1), dtype=np.uint8) data_align = empty.ctypes.data % align offset = 0 if data_align == 0 else (align - data_align) output = empty[offset:offset + n].vi...
[ "Returns an array of a given size that is 64-byte aligned.\n\n The returned array can be efficiently copied into GPU memory by TensorFlow.\n " ]
Please provide a description of the function:def concat_aligned(items): if len(items) == 0: return [] elif len(items) == 1: # we assume the input is aligned. In any case, it doesn't help # performance to force align it since that incurs a needless copy. return items[0] ...
[ "Concatenate arrays, ensuring the output is 64-byte aligned.\n\n We only align float arrays; other arrays are concatenated as normal.\n\n This should be used instead of np.concatenate() to improve performance\n when the output array is likely to be fed into TensorFlow.\n " ]
Please provide a description of the function:def put(self, item, block=True, timeout=None): if self.maxsize <= 0: self.actor.put.remote(item) elif not block: if not ray.get(self.actor.put.remote(item)): raise Full elif timeout is None: ...
[ "Adds an item to the queue.\n\n Uses polling if block=True, so there is no guarantee of order if\n multiple producers put to the same full queue.\n\n Raises:\n Full if the queue is full and blocking is False.\n " ]
Please provide a description of the function:def get(self, block=True, timeout=None): if not block: success, item = ray.get(self.actor.get.remote()) if not success: raise Empty elif timeout is None: # Polling # Use a not_empty cond...
[ "Gets an item from the queue.\n\n Uses polling if block=True, so there is no guarantee of order if\n multiple consumers get from the same empty queue.\n\n Returns:\n The next item in the queue.\n\n Raises:\n Empty if the queue is empty and blocking is False.\n ...
Please provide a description of the function:def override(cls): def check_override(method): if method.__name__ not in dir(cls): raise NameError("{} does not override any method of {}".format( method, cls)) return method return check_override
[ "Annotation for documenting method overrides.\n\n Arguments:\n cls (type): The superclass that provides the overriden method. If this\n cls does not actually have the method, an error is raised.\n " ]
Please provide a description of the function:def on_trial_add(self, trial_runner, trial): cur_bracket = self._state["bracket"] cur_band = self._hyperbands[self._state["band_idx"]] if cur_bracket is None or cur_bracket.filled(): retry = True while retry: ...
[ "Adds new trial.\n\n On a new trial add, if current bracket is not filled,\n add to current bracket. Else, if current band is not filled,\n create new bracket, add to current bracket.\n Else, create new iteration, create new bracket, add to bracket." ]
Please provide a description of the function:def _cur_band_filled(self): cur_band = self._hyperbands[self._state["band_idx"]] return len(cur_band) == self._s_max_1
[ "Checks if the current band is filled.\n\n The size of the current band should be equal to s_max_1" ]
Please provide a description of the function:def on_trial_result(self, trial_runner, trial, result): bracket, _ = self._trial_info[trial] bracket.update_trial_stats(trial, result) if bracket.continue_trial(trial): return TrialScheduler.CONTINUE action = self._proc...
[ "If bracket is finished, all trials will be stopped.\n\n If a given trial finishes and bracket iteration is not done,\n the trial will be paused and resources will be given up.\n\n This scheduler will not start trials but will stop trials.\n The current running trial will not be handled,...
Please provide a description of the function:def _process_bracket(self, trial_runner, bracket, trial): action = TrialScheduler.PAUSE if bracket.cur_iter_done(): if bracket.finished(): bracket.cleanup_full(trial_runner) return TrialScheduler.STOP ...
[ "This is called whenever a trial makes progress.\n\n When all live trials in the bracket have no more iterations left,\n Trials will be successively halved. If bracket is done, all\n non-running trials will be stopped and cleaned up,\n and during each halving phase, bad trials will be st...
Please provide a description of the function:def on_trial_remove(self, trial_runner, trial): bracket, _ = self._trial_info[trial] bracket.cleanup_trial(trial) if not bracket.finished(): self._process_bracket(trial_runner, bracket, trial)
[ "Notification when trial terminates.\n\n Trial info is removed from bracket. Triggers halving if bracket is\n not finished." ]
Please provide a description of the function:def choose_trial_to_run(self, trial_runner): for hyperband in self._hyperbands: # band will have None entries if no resources # are to be allocated to that bracket. scrubbed = [b for b in hyperband if b is not None] ...
[ "Fair scheduling within iteration by completion percentage.\n\n List of trials not used since all trials are tracked as state\n of scheduler. If iteration is occupied (ie, no trials to run),\n then look into next iteration.\n " ]
Please provide a description of the function:def debug_string(self): out = "Using HyperBand: " out += "num_stopped={} total_brackets={}".format( self._num_stopped, sum(len(band) for band in self._hyperbands)) for i, band in enumerate(self._hyperbands): out += "\n...
[ "This provides a progress notification for the algorithm.\n\n For each bracket, the algorithm will output a string as follows:\n\n Bracket(Max Size (n)=5, Milestone (r)=33, completed=14.6%):\n {PENDING: 2, RUNNING: 3, TERMINATED: 2}\n\n \"Max Size\" indicates the max number of pe...
Please provide a description of the function:def add_trial(self, trial): assert not self.filled(), "Cannot add trial to filled bracket!" self._live_trials[trial] = None self._all_trials.append(trial)
[ "Add trial to bracket assuming bracket is not filled.\n\n At a later iteration, a newly added trial will be given equal\n opportunity to catch up." ]
Please provide a description of the function:def cur_iter_done(self): return all( self._get_result_time(result) >= self._cumul_r for result in self._live_trials.values())
[ "Checks if all iterations have completed.\n\n TODO(rliaw): also check that `t.iterations == self._r`" ]
Please provide a description of the function:def update_trial_stats(self, trial, result): assert trial in self._live_trials assert self._get_result_time(result) >= 0 delta = self._get_result_time(result) - \ self._get_result_time(self._live_trials[trial]) assert de...
[ "Update result for trial. Called after trial has finished\n an iteration - will decrement iteration count.\n\n TODO(rliaw): The other alternative is to keep the trials\n in and make sure they're not set as pending later." ]
Please provide a description of the function:def cleanup_full(self, trial_runner): for trial in self.current_trials(): if (trial.status == Trial.PAUSED): trial_runner.stop_trial(trial)
[ "Cleans up bracket after bracket is completely finished.\n\n Lets the last trial continue to run until termination condition\n kicks in." ]
Please provide a description of the function:def parse_client_table(redis_client): NIL_CLIENT_ID = ray.ObjectID.nil().binary() message = redis_client.execute_command("RAY.TABLE_LOOKUP", ray.gcs_utils.TablePrefix.CLIENT, "...
[ "Read the client table.\n\n Args:\n redis_client: A client to the primary Redis shard.\n\n Returns:\n A list of information about the nodes in the cluster.\n " ]
Please provide a description of the function:def _initialize_global_state(self, redis_address, redis_password=None, timeout=20): self.redis_client = services.create_redis_client( redis_address...
[ "Initialize the GlobalState object by connecting to Redis.\n\n It's possible that certain keys in Redis may not have been fully\n populated yet. In this case, we will retry this method until they have\n been populated or we exceed a timeout.\n\n Args:\n redis_address: The Redi...
Please provide a description of the function:def _execute_command(self, key, *args): client = self.redis_clients[key.redis_shard_hash() % len( self.redis_clients)] return client.execute_command(*args)
[ "Execute a Redis command on the appropriate Redis shard based on key.\n\n Args:\n key: The object ID or the task ID that the query is about.\n args: The command to run.\n\n Returns:\n The value returned by the Redis command.\n " ]
Please provide a description of the function:def _keys(self, pattern): result = [] for client in self.redis_clients: result.extend(list(client.scan_iter(match=pattern))) return result
[ "Execute the KEYS command on all Redis shards.\n\n Args:\n pattern: The KEYS pattern to query.\n\n Returns:\n The concatenated list of results from all shards.\n " ]
Please provide a description of the function:def _object_table(self, object_id): # Allow the argument to be either an ObjectID or a hex string. if not isinstance(object_id, ray.ObjectID): object_id = ray.ObjectID(hex_to_binary(object_id)) # Return information about a single...
[ "Fetch and parse the object table information for a single object ID.\n\n Args:\n object_id: An object ID to get information about.\n\n Returns:\n A dictionary with information about the object ID in question.\n " ]
Please provide a description of the function:def object_table(self, object_id=None): self._check_connected() if object_id is not None: # Return information about a single object ID. return self._object_table(object_id) else: # Return the entire object...
[ "Fetch and parse the object table info for one or more object IDs.\n\n Args:\n object_id: An object ID to fetch information about. If this is\n None, then the entire object table is fetched.\n\n Returns:\n Information from the object table.\n " ]
Please provide a description of the function:def _task_table(self, task_id): assert isinstance(task_id, ray.TaskID) message = self._execute_command(task_id, "RAY.TABLE_LOOKUP", ray.gcs_utils.TablePrefix.RAYLET_TASK, ...
[ "Fetch and parse the task table information for a single task ID.\n\n Args:\n task_id: A task ID to get information about.\n\n Returns:\n A dictionary with information about the task ID in question.\n " ]
Please provide a description of the function:def task_table(self, task_id=None): self._check_connected() if task_id is not None: task_id = ray.TaskID(hex_to_binary(task_id)) return self._task_table(task_id) else: task_table_keys = self._keys( ...
[ "Fetch and parse the task table information for one or more task IDs.\n\n Args:\n task_id: A hex string of the task ID to fetch information about. If\n this is None, then the task object table is fetched.\n\n Returns:\n Information from the task table.\n " ]
Please provide a description of the function:def function_table(self, function_id=None): self._check_connected() function_table_keys = self.redis_client.keys( ray.gcs_utils.FUNCTION_PREFIX + "*") results = {} for key in function_table_keys: info = self.re...
[ "Fetch and parse the function table.\n\n Returns:\n A dictionary that maps function IDs to information about the\n function.\n " ]
Please provide a description of the function:def _profile_table(self, batch_id): # TODO(rkn): This method should support limiting the number of log # events and should also support returning a window of events. message = self._execute_command(batch_id, "RAY.TABLE_LOOKUP", ...
[ "Get the profile events for a given batch of profile events.\n\n Args:\n batch_id: An identifier for a batch of profile events.\n\n Returns:\n A list of the profile events for the specified batch.\n " ]
Please provide a description of the function:def chrome_tracing_dump(self, filename=None): # TODO(rkn): Support including the task specification data in the # timeline. # TODO(rkn): This should support viewing just a window of time or a # limited number of events. profi...
[ "Return a list of profiling events that can viewed as a timeline.\n\n To view this information as a timeline, simply dump it as a json file\n by passing in \"filename\" or using using json.dump, and then load go to\n chrome://tracing in the Chrome web browser and load the dumped file.\n ...
Please provide a description of the function:def chrome_tracing_object_transfer_dump(self, filename=None): client_id_to_address = {} for client_info in ray.global_state.client_table(): client_id_to_address[client_info["ClientID"]] = "{}:{}".format( client_info["NodeM...
[ "Return a list of transfer events that can viewed as a timeline.\n\n To view this information as a timeline, simply dump it as a json file\n by passing in \"filename\" or using using json.dump, and then load go to\n chrome://tracing in the Chrome web browser and load the dumped file.\n M...
Please provide a description of the function:def workers(self): 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(worker_key[len("Workers...
[ "Get a dictionary mapping worker ID to worker information." ]
Please provide a description of the function:def cluster_resources(self): resources = defaultdict(int) clients = self.client_table() for client in clients: # Only count resources from live clients. if client["IsInsertion"]: for key, value in clien...
[ "Get the current total cluster resources.\n\n Note that this information can grow stale as nodes are added to or\n removed from the cluster.\n\n Returns:\n A dictionary mapping resource name to the total quantity of that\n resource in the cluster.\n " ]
Please provide a description of the function:def available_resources(self): available_resources_by_id = {} subscribe_clients = [ redis_client.pubsub(ignore_subscribe_messages=True) for redis_client in self.redis_clients ] for subscribe_client in subscrib...
[ "Get the current available cluster resources.\n\n This is different from `cluster_resources` in that this will return\n idle (available) resources rather than total resources.\n\n Note that this information can grow stale as tasks start and finish.\n\n Returns:\n A dictionary ...
Please provide a description of the function:def _error_messages(self, driver_id): assert isinstance(driver_id, ray.DriverID) message = self.redis_client.execute_command( "RAY.TABLE_LOOKUP", ray.gcs_utils.TablePrefix.ERROR_INFO, "", driver_id.binary()) # If ther...
[ "Get the error messages for a specific driver.\n\n Args:\n driver_id: The ID of the driver to get the errors for.\n\n Returns:\n A list of the error messages for this driver.\n " ]
Please provide a description of the function:def error_messages(self, driver_id=None): if driver_id is not None: assert isinstance(driver_id, ray.DriverID) return self._error_messages(driver_id) error_table_keys = self.redis_client.keys( ray.gcs_utils.TableP...
[ "Get the error messages for all drivers or a specific driver.\n\n Args:\n driver_id: The specific driver to get the errors for. If this is\n None, then this method retrieves the errors for all drivers.\n\n Returns:\n A dictionary mapping driver ID to a list of the ...
Please provide a description of the function:def actor_checkpoint_info(self, actor_id): self._check_connected() message = self._execute_command( actor_id, "RAY.TABLE_LOOKUP", ray.gcs_utils.TablePrefix.ACTOR_CHECKPOINT_ID, "", actor_id....
[ "Get checkpoint info for the given actor id.\n Args:\n actor_id: Actor's ID.\n Returns:\n A dictionary with information about the actor's checkpoint IDs and\n their timestamps.\n " ]