INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Disconnect the worker and terminate processes started by ray. init ().
def shutdown(exiting_interpreter=False): """Disconnect the worker, and terminate processes started by ray.init(). This will automatically run at the end when a Python process that uses Ray exits. It is ok to run this twice in a row. The primary use case for this function is to cleanup state between tes...
Prints log messages from workers on all of the nodes.
def print_logs(redis_client, threads_stopped): """Prints log messages from workers on all of the nodes. Args: redis_client: A client to the primary Redis shard. threads_stopped (threading.Event): A threading event used to signal to the thread that it should exit. """ pubsub_...
Prints message received in the given output queue.
def print_error_messages_raylet(task_error_queue, threads_stopped): """Prints message received in the given output queue. This checks periodically if any un-raised errors occured in the background. Args: task_error_queue (queue.Queue): A queue used to receive errors from the thread tha...
Listen to error messages in the background on the driver.
def listen_error_messages_raylet(worker, task_error_queue, threads_stopped): """Listen to error messages in the background on the driver. This runs in a separate thread on the driver and pushes (error, time) tuples to the output queue. Args: worker: The worker class that this thread belongs to...
Connect this worker to the raylet to Plasma and to Redis.
def connect(node, mode=WORKER_MODE, log_to_driver=False, worker=global_worker, driver_id=None, load_code_from_local=False): """Connect this worker to the raylet, to Plasma, and to Redis. Args: node (ray.node.Node): The node to connect. ...
Disconnect this worker from the raylet and object store.
def disconnect(): """Disconnect this worker from the raylet and object store.""" # Reset the list of cached remote functions and actors so that if more # remote functions or actors are defined and then connect is called again, # the remote functions will be exported. This is mostly relevant for the ...
Attempt to produce a deterministic class ID for a given class.
def _try_to_compute_deterministic_class_id(cls, depth=5): """Attempt to produce a deterministic class ID for a given class. The goal here is for the class ID to be the same when this is run on different worker processes. Pickling, loading, and pickling again seems to produce more consistent results tha...
Enable serialization and deserialization for a particular class.
def register_custom_serializer(cls, use_pickle=False, use_dict=False, serializer=None, deserializer=None, local=False, driver_id=None,...
Get a remote object or a list of remote objects from the object store.
def get(object_ids): """Get a remote object or a list of remote objects from the object store. This method blocks until the object corresponding to the object ID is available in the local object store. If this object is not in the local object store, it will be shipped from an object store that has it ...
Store an object in the object store.
def put(value): """Store an object in the object store. Args: value: The Python object to be stored. Returns: The object ID assigned to this value. """ worker = global_worker worker.check_connected() with profiling.profile("ray.put"): if worker.mode == LOCAL_MODE: ...
Return a list of IDs that are ready and a list of IDs that are not.
def wait(object_ids, num_returns=1, timeout=None): """Return a list of IDs that are ready and a list of IDs that are not. .. warning:: The **timeout** argument used to be in **milliseconds** (up through ``ray==0.6.1``) and now it is in **seconds**. If timeout is set, the function returns ...
Define a remote function or an actor class.
def remote(*args, **kwargs): """Define a remote function or an actor class. This can be used with no arguments to define a remote function or actor as follows: .. code-block:: python @ray.remote def f(): return 1 @ray.remote class Foo(object): ...
A thread - local that contains the following attributes.
def task_context(self): """A thread-local that contains the following attributes. current_task_id: For the main thread, this field is the ID of this worker's current running task; for other threads, this field is a fake random ID. task_index: The number of tasks that hav...
Get the SerializationContext of the driver that this worker is processing.
def get_serialization_context(self, driver_id): """Get the SerializationContext of the driver that this worker is processing. Args: driver_id: The ID of the driver that indicates which driver to get the serialization context for. Returns: The serializati...
Store an object and attempt to register its class if needed.
def store_and_register(self, object_id, value, depth=100): """Store an object and attempt to register its class if needed. Args: object_id: The ID of the object to store. value: The value to put in the object store. depth: The maximum number of classes to recursively...
Put value in the local object store with object id objectid.
def put_object(self, object_id, value): """Put value in the local object store with object id objectid. This assumes that the value for objectid has not yet been placed in the local object store. Args: object_id (object_id.ObjectID): The object ID of the value to be ...
Get the value or values in the object store associated with the IDs.
def get_object(self, object_ids): """Get the value or values in the object store associated with the IDs. Return the values from the local object store for object_ids. This will block until all the values for object_ids have been written to the local object store. Args: ...
Submit a remote task to the scheduler.
def submit_task(self, function_descriptor, args, actor_id=None, actor_handle_id=None, actor_counter=0, actor_creation_id=None, actor_creation_dummy_object_id=None, ...
Run arbitrary code on all of the workers.
def run_function_on_all_workers(self, function, run_on_other_drivers=False): """Run arbitrary code on all of the workers. This function will first be run on the driver, and then it will be exported to all of the workers to be run. It will also be run on any ...
Retrieve the arguments for the remote function.
def _get_arguments_for_execution(self, function_name, serialized_args): """Retrieve the arguments for the remote function. This retrieves the values for the arguments to the remote function that were passed in as object IDs. Arguments that were passed by value are not changed. This is c...
Store the outputs of a remote function in the local object store.
def _store_outputs_in_object_store(self, object_ids, outputs): """Store the outputs of a remote function in the local object store. This stores the values that were returned by a remote function in the local object store. If any of the return values are object IDs, then these object IDs...
Execute a task assigned to this worker.
def _process_task(self, task, function_execution_info): """Execute a task assigned to this worker. This method deserializes a task from the scheduler, and attempts to execute the task. If the task succeeds, the outputs are stored in the local object store. If the task throws an exceptio...
Wait for a task to be ready and process the task.
def _wait_for_and_process_task(self, task): """Wait for a task to be ready and process the task. Args: task: The task to execute. """ function_descriptor = FunctionDescriptor.from_bytes_list( task.function_descriptor_list()) driver_id = task.driver_id() ...
Get the next task from the raylet.
def _get_next_task_from_raylet(self): """Get the next task from the raylet. Returns: A task from the raylet. """ with profiling.profile("worker_idle"): task = self.raylet_client.get_task() # Automatically restrict the GPUs available to this task. ...
The main loop a worker runs to receive and execute tasks.
def main_loop(self): """The main loop a worker runs to receive and execute tasks.""" def exit(signum, frame): shutdown() sys.exit(0) signal.signal(signal.SIGTERM, exit) while True: task = self._get_next_task_from_raylet() self._wait_for_...
This methods reshapes all values in a dictionary.
def flatten(weights, start=0, stop=2): """This methods reshapes all values in a dictionary. The indices from start to stop will be flattened into a single index. Args: weights: A dictionary mapping keys to numpy arrays. start: The starting index. stop: The ending index. """ ...
Get a dictionary of addresses.
def address_info(self): """Get a dictionary of addresses.""" return { "node_ip_address": self._node_ip_address, "redis_address": self._redis_address, "object_store_address": self._plasma_store_socket_name, "raylet_socket_name": self._raylet_socket_name, ...
Create a redis client.
def create_redis_client(self): """Create a redis client.""" return ray.services.create_redis_client( self._redis_address, self._ray_params.redis_password)
Return a incremental temporary file name. The file is not created.
def _make_inc_temp(self, suffix="", prefix="", directory_name="/tmp/ray"): """Return a incremental temporary file name. The file is not created. Args: suffix (str): The suffix of the temp file. prefix (str): The prefix of the temp file. directory_name (str) : The bas...
Generate partially randomized filenames for log files.
def new_log_files(self, name, redirect_output=True): """Generate partially randomized filenames for log files. Args: name (str): descriptive string for this log file. redirect_output (bool): True if files should be generated for logging stdout and stderr and fals...
Prepare the socket file for raylet and plasma.
def _prepare_socket_file(self, socket_path, default_prefix): """Prepare the socket file for raylet and plasma. This method helps to prepare a socket file. 1. Make the directory if the directory does not exist. 2. If the socket file exists, raise exception. Args: soc...
Start the Redis servers.
def start_redis(self): """Start the Redis servers.""" assert self._redis_address is None redis_log_files = [self.new_log_files("redis")] for i in range(self._ray_params.num_redis_shards): redis_log_files.append(self.new_log_files("redis-shard_" + str(i))) (self._redi...
Start the log monitor.
def start_log_monitor(self): """Start the log monitor.""" stdout_file, stderr_file = self.new_log_files("log_monitor") process_info = ray.services.start_log_monitor( self.redis_address, self._logs_dir, stdout_file=stdout_file, stderr_file=stderr_fi...
Start the reporter.
def start_reporter(self): """Start the reporter.""" stdout_file, stderr_file = self.new_log_files("reporter", True) process_info = ray.services.start_reporter( self.redis_address, stdout_file=stdout_file, stderr_file=stderr_file, redis_password=sel...
Start the dashboard.
def start_dashboard(self): """Start the dashboard.""" stdout_file, stderr_file = self.new_log_files("dashboard", True) self._webui_url, process_info = ray.services.start_dashboard( self.redis_address, self._temp_dir, stdout_file=stdout_file, stderr...
Start the plasma store.
def start_plasma_store(self): """Start the plasma store.""" stdout_file, stderr_file = self.new_log_files("plasma_store") process_info = ray.services.start_plasma_store( stdout_file=stdout_file, stderr_file=stderr_file, object_store_memory=self._ray_params.obj...
Start the raylet.
def start_raylet(self, use_valgrind=False, use_profiler=False): """Start the raylet. Args: use_valgrind (bool): True if we should start the process in valgrind. use_profiler (bool): True if we should start the process in the valgrind profiler. ...
Create new logging files for workers to redirect its output.
def new_worker_redirected_log_file(self, worker_id): """Create new logging files for workers to redirect its output.""" worker_stdout_file, worker_stderr_file = (self.new_log_files( "worker-" + ray.utils.binary_to_hex(worker_id), True)) return worker_stdout_file, worker_stderr_file
Start the monitor.
def start_monitor(self): """Start the monitor.""" stdout_file, stderr_file = self.new_log_files("monitor") process_info = ray.services.start_monitor( self._redis_address, stdout_file=stdout_file, stderr_file=stderr_file, autoscaling_config=self._ra...
Start the raylet monitor.
def start_raylet_monitor(self): """Start the raylet monitor.""" stdout_file, stderr_file = self.new_log_files("raylet_monitor") process_info = ray.services.start_raylet_monitor( self._redis_address, stdout_file=stdout_file, stderr_file=stderr_file, ...
Start head processes on the node.
def start_head_processes(self): """Start head processes on the node.""" logger.info( "Process STDOUT and STDERR is being redirected to {}.".format( self._logs_dir)) assert self._redis_address is None # If this is the head node, start the relevant head node pro...
Start all of the processes on the node.
def start_ray_processes(self): """Start all of the processes on the node.""" logger.info( "Process STDOUT and STDERR is being redirected to {}.".format( self._logs_dir)) self.start_plasma_store() self.start_raylet() if PY3: self.start_repo...
Kill a process of a given type.
def _kill_process_type(self, process_type, allow_graceful=False, check_alive=True, wait=False): """Kill a process of a given type. If the process type is PROCESS_TYPE_REDIS_SERVER, then we will k...
Kill the Redis servers.
def kill_redis(self, check_alive=True): """Kill the Redis servers. Args: check_alive (bool): Raise an exception if any of the processes were already dead. """ self._kill_process_type( ray_constants.PROCESS_TYPE_REDIS_SERVER, check_alive=check_aliv...
Kill the plasma store.
def kill_plasma_store(self, check_alive=True): """Kill the plasma store. Args: check_alive (bool): Raise an exception if the process was already dead. """ self._kill_process_type( ray_constants.PROCESS_TYPE_PLASMA_STORE, check_alive=check_alive)
Kill the raylet.
def kill_raylet(self, check_alive=True): """Kill the raylet. Args: check_alive (bool): Raise an exception if the process was already dead. """ self._kill_process_type( ray_constants.PROCESS_TYPE_RAYLET, check_alive=check_alive)
Kill the log monitor.
def kill_log_monitor(self, check_alive=True): """Kill the log monitor. Args: check_alive (bool): Raise an exception if the process was already dead. """ self._kill_process_type( ray_constants.PROCESS_TYPE_LOG_MONITOR, check_alive=check_alive)
Kill the reporter.
def kill_reporter(self, check_alive=True): """Kill the reporter. Args: check_alive (bool): Raise an exception if the process was already dead. """ # reporter is started only in PY3. if PY3: self._kill_process_type( ray_cons...
Kill the dashboard.
def kill_dashboard(self, check_alive=True): """Kill the dashboard. Args: check_alive (bool): Raise an exception if the process was already dead. """ self._kill_process_type( ray_constants.PROCESS_TYPE_DASHBOARD, check_alive=check_alive)
Kill the monitor.
def kill_monitor(self, check_alive=True): """Kill the monitor. Args: check_alive (bool): Raise an exception if the process was already dead. """ self._kill_process_type( ray_constants.PROCESS_TYPE_MONITOR, check_alive=check_alive)
Kill the raylet monitor.
def kill_raylet_monitor(self, check_alive=True): """Kill the raylet monitor. Args: check_alive (bool): Raise an exception if the process was already dead. """ self._kill_process_type( ray_constants.PROCESS_TYPE_RAYLET_MONITOR, check_alive=check_al...
Kill all of the processes.
def kill_all_processes(self, check_alive=True, allow_graceful=False): """Kill all of the processes. Note that This is slower than necessary because it calls kill, wait, kill, wait, ... instead of kill, kill, ..., wait, wait, ... Args: check_alive (bool): Raise an exception ...
Return a list of the live processes.
def live_processes(self): """Return a list of the live processes. Returns: A list of the live processes. """ result = [] for process_type, process_infos in self.all_processes.items(): for process_info in process_infos: if process_info.proc...
Create a large array of noise to be shared by all workers.
def create_shared_noise(count): """Create a large array of noise to be shared by all workers.""" seed = 123 noise = np.random.RandomState(seed).randn(count).astype(np.float32) return noise
Map model name to model network configuration.
def get_model_config(model_name, dataset): """Map model name to model network configuration.""" model_map = _get_model_map(dataset.name) if model_name not in model_map: raise ValueError("Invalid model name \"%s\" for dataset \"%s\"" % (model_name, dataset.name)) else: ...
Register a new model that can be obtained with get_model_config.
def register_model(model_name, dataset_name, model_func): """Register a new model that can be obtained with `get_model_config`.""" model_map = _get_model_map(dataset_name) if model_name in model_map: raise ValueError("Model \"%s\" is already registered for dataset" "\"%s\"" ...
Do a rollout.
def rollout(policy, env, timestep_limit=None, add_noise=False, offset=0): """Do a rollout. If add_noise is True, the rollout will take noisy actions with noise drawn from that stream. Otherwise, no action noise will be added. Parameters ---------- policy: tf object policy from which to...
Provides Trial objects to be queued into the TrialRunner.
def next_trials(self): """Provides Trial objects to be queued into the TrialRunner. Returns: trials (list): Returns a list of trials. """ trials = list(self._trial_generator) if self._shuffle: random.shuffle(trials) self._finished = True r...
Generates Trial objects with the variant generation process.
def _generate_trials(self, unresolved_spec, output_path=""): """Generates Trial objects with the variant generation process. Uses a fixed point iteration to resolve variants. All trials should be able to be generated at once. See also: `ray.tune.suggest.variant_generator`. Yie...
Returns result of applying self. operation to a contiguous subsequence of the array.
def reduce(self, start=0, end=None): """Returns result of applying `self.operation` to a contiguous subsequence of the array. self.operation( arr[start], operation(arr[start+1], operation(... arr[end]))) Parameters ---------- start: int beginni...
Serialize this policy for Monitor to pick up.
def set_flushing_policy(flushing_policy): """Serialize this policy for Monitor to pick up.""" if "RAY_USE_NEW_GCS" not in os.environ: raise Exception( "set_flushing_policy() is only available when environment " "variable RAY_USE_NEW_GCS is present at both compile and run time." ...
Returns ssh key to connecting to cluster workers.
def get_ssh_key(): """Returns ssh key to connecting to cluster workers. If the env var TUNE_CLUSTER_SSH_KEY is provided, then this key will be used for syncing across different nodes. """ path = os.environ.get("TUNE_CLUSTER_SSH_KEY", os.path.expanduser("~/ray_bootstrap_key...
Passes the result to HyperOpt unless early terminated or errored.
def on_trial_complete(self, trial_id, result=None, error=False, early_terminated=False): """Passes the result to HyperOpt unless early terminated or errored. The result is internally negated when int...
Tells plasma to prefetch the given object_id.
def plasma_prefetch(object_id): """Tells plasma to prefetch the given object_id.""" local_sched_client = ray.worker.global_worker.raylet_client ray_obj_id = ray.ObjectID(object_id) local_sched_client.fetch_or_reconstruct([ray_obj_id], True)
Get an object directly from plasma without going through object table.
def plasma_get(object_id): """Get an object directly from plasma without going through object table. Precondition: plasma_prefetch(object_id) has been called before. """ client = ray.worker.global_worker.plasma_client plasma_id = ray.pyarrow.plasma.ObjectID(object_id) while not client.contains(...
Restores the state of the batched queue for writing.
def enable_writes(self): """Restores the state of the batched queue for writing.""" self.write_buffer = [] self.flush_lock = threading.RLock() self.flush_thread = FlushThread(self.max_batch_time, self._flush_writes)
Checks for backpressure by the downstream reader.
def _wait_for_reader(self): """Checks for backpressure by the downstream reader.""" if self.max_size <= 0: # Unlimited queue return if self.write_item_offset - self.cached_remote_offset <= self.max_size: return # Hasn't reached max size remote_offset = internal_...
Collects at least train_batch_size samples never discarding any.
def collect_samples(agents, sample_batch_size, num_envs_per_worker, train_batch_size): """Collects at least train_batch_size samples, never discarding any.""" num_timesteps_so_far = 0 trajectories = [] agent_dict = {} for agent in agents: fut_sample = agent.sample.remot...
Collects at least train_batch_size samples.
def collect_samples_straggler_mitigation(agents, train_batch_size): """Collects at least train_batch_size samples. This is the legacy behavior as of 0.6, and launches extra sample tasks to potentially improve performance but can result in many wasted samples. """ num_timesteps_so_far = 0 traje...
Improve the formatting of an exception thrown by a remote function.
def format_error_message(exception_message, task_exception=False): """Improve the formatting of an exception thrown by a remote function. This method takes a traceback from an exception and makes it nicer by removing a few uninformative lines and adding some space to indent the remaining lines nicely. ...
Push an error message to the driver to be printed in the background.
def push_error_to_driver(worker, error_type, message, driver_id=None): """Push an error message to the driver to be printed in the background. Args: worker: The worker to use. error_type (str): The type of the error. message (str): The message that will be printed in the background ...
Push an error message to the driver to be printed in the background.
def push_error_to_driver_through_redis(redis_client, error_type, message, driver_id=None): """Push an error message to the driver to be printed in the background. Normally the push_error_to_driv...
Check if an object is a Cython function or method
def is_cython(obj): """Check if an object is a Cython function or method""" # TODO(suo): We could split these into two functions, one for Cython # functions and another for Cython methods. # TODO(suo): There doesn't appear to be a Cython function 'type' we can # check against via isinstance. Please...
Check if an object is a function or method.
def is_function_or_method(obj): """Check if an object is a function or method. Args: obj: The Python object in question. Returns: True if the object is an function or method. """ return inspect.isfunction(obj) or inspect.ismethod(obj) or is_cython(obj)
Generate a random string to use as an ID.
def random_string(): """Generate a random string to use as an ID. Note that users may seed numpy, which could cause this function to generate duplicate IDs. Therefore, we need to seed numpy ourselves, but we can't interfere with the state of the user's random number generator, so we extract the sta...
Make this unicode in Python 3 otherwise leave it as bytes.
def decode(byte_str, allow_none=False): """Make this unicode in Python 3, otherwise leave it as bytes. Args: byte_str: The byte string to decode. allow_none: If true, then we will allow byte_str to be None in which case we will return an empty string. TODO(rkn): Remove this flag. ...
Coerce * s * to str.
def ensure_str(s, encoding="utf-8", errors="strict"): """Coerce *s* to `str`. To keep six with lower version, see Issue 4169, we copy this function from six == 1.12.0. TODO(yuhguo): remove this function when six >= 1.12.0. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str`...
Get the device IDs in the CUDA_VISIBLE_DEVICES environment variable.
def get_cuda_visible_devices(): """Get the device IDs in the CUDA_VISIBLE_DEVICES environment variable. Returns: if CUDA_VISIBLE_DEVICES is set, this returns a list of integers with the IDs of the GPUs. If it is not set, this returns None. """ gpu_ids_str = os.environ.get("CUDA_VISI...
Determine a task s resource requirements.
def resources_from_resource_arguments(default_num_cpus, default_num_gpus, default_resources, runtime_num_cpus, runtime_num_gpus, runtime_resources): """Determine a task's resource requirements. Args: default_num_cpus: The defau...
Setup default logging for ray.
def setup_logger(logging_level, logging_format): """Setup default logging for ray.""" logger = logging.getLogger("ray") if type(logging_level) is str: logging_level = logging.getLevelName(logging_level.upper()) logger.setLevel(logging_level) global _default_handler if _default_handler is...
Run vmstat and get a particular statistic.
def vmstat(stat): """Run vmstat and get a particular statistic. Args: stat: The statistic that we are interested in retrieving. Returns: The parsed output. """ out = subprocess.check_output(["vmstat", "-s"]) stat = stat.encode("ascii") for line in out.split(b"\n"): ...
Run a sysctl command and parse the output.
def sysctl(command): """Run a sysctl command and parse the output. Args: command: A sysctl command with an argument, for example, ["sysctl", "hw.memsize"]. Returns: The parsed output. """ out = subprocess.check_output(command) result = out.split(b" ")[1] try: ...
Return the total amount of system memory in bytes.
def get_system_memory(): """Return the total amount of system memory in bytes. Returns: The total amount of system memory in bytes. """ # Try to accurately figure out the memory limit if we are in a docker # container. Note that this file is not specific to Docker and its value is # oft...
Get the size of the shared memory file system.
def get_shared_memory_bytes(): """Get the size of the shared memory file system. Returns: The size of the shared memory file system in bytes. """ # Make sure this is only called on Linux. assert sys.platform == "linux" or sys.platform == "linux2" shm_fd = os.open("/dev/shm", os.O_RDONL...
Send a warning message if the pickled object is too large.
def check_oversized_pickle(pickled, name, obj_type, worker): """Send a warning message if the pickled object is too large. Args: pickled: the pickled object. name: name of the pickled object. obj_type: type of the pickled object, can be 'function', 'remote function', 'actor'...
Create a thread - safe proxy which locks every method call for the given client.
def thread_safe_client(client, lock=None): """Create a thread-safe proxy which locks every method call for the given client. Args: client: the client object to be guarded. lock: the lock object that will be used to lock client's methods. If None, a new lock will be used. Re...
Attempt to create a directory that is globally readable/ writable.
def try_to_create_directory(directory_path): """Attempt to create a directory that is globally readable/writable. Args: directory_path: The path of the directory to create. """ logger = logging.getLogger("ray") directory_path = os.path.expanduser(directory_path) if not os.path.exists(di...
This function produces a distributed array from a subset of the blocks in the a. The result and a will have the same number of dimensions. For example subblocks ( a [ 0 1 ] [ 2 4 ] ) will produce a DistArray whose objectids are [[ a. objectids [ 0 2 ] a. objectids [ 0 4 ]] [ a. objectids [ 1 2 ] a. objectids [ 1 4 ]]] ...
def subblocks(a, *ranges): """ This function produces a distributed array from a subset of the blocks in the `a`. The result and `a` will have the same number of dimensions. For example, subblocks(a, [0, 1], [2, 4]) will produce a DistArray whose objectids are [[a.objectids[0, 2], a....
Assemble an array from a distributed array of object IDs.
def assemble(self): """Assemble an array from a distributed array of object IDs.""" first_block = ray.get(self.objectids[(0, ) * self.ndim]) dtype = first_block.dtype result = np.zeros(self.shape, dtype=dtype) for index in np.ndindex(*self.num_blocks): lower = DistArr...
Computes action log - probs from policy logits and actions.
def multi_log_probs_from_logits_and_actions(policy_logits, actions): """Computes action log-probs from policy logits and actions. In the notation used throughout documentation and comments, T refers to the time dimension ranging from 0 to T-1. B refers to the batch size and ACTION_SPACE refers to the list of...
multi_from_logits wrapper used only for tests
def from_logits(behaviour_policy_logits, target_policy_logits, actions, discounts, rewards, values, bootstrap_value, clip_rho_threshold=1.0, clip_pg_rho_threshold=1.0, name="vt...
r V - trace for softmax policies.
def multi_from_logits(behaviour_policy_logits, target_policy_logits, actions, discounts, rewards, values, bootstrap_value, clip_rho_threshold=1.0, ...
r V - trace from log importance weights.
def from_importance_weights(log_rhos, discounts, rewards, values, bootstrap_value, clip_rho_threshold=1.0, clip_pg_rho_threshold=1.0, ...
With the selected log_probs for multi - discrete actions of behaviour and target policies we compute the log_rhos for calculating the vtrace.
def get_log_rhos(target_action_log_probs, behaviour_action_log_probs): """With the selected log_probs for multi-discrete actions of behaviour and target policies we compute the log_rhos for calculating the vtrace.""" t = tf.stack(target_action_log_probs) b = tf.stack(behaviour_action_log_probs) log_...
weight_variable generates a weight variable of a given shape.
def weight_variable(shape): """weight_variable generates a weight variable of a given shape.""" initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial)
bias_variable generates a bias variable of a given shape.
def bias_variable(shape): """bias_variable generates a bias variable of a given shape.""" initial = tf.constant(0.1, shape=shape) return tf.Variable(initial)
Prints output of given dataframe to fit into terminal.
def print_format_output(dataframe): """Prints output of given dataframe to fit into terminal. Returns: table (pd.DataFrame): Final outputted dataframe. dropped_cols (list): Columns dropped due to terminal size. empty_cols (list): Empty columns (dropped on default). """ print_df ...
Lists trials in the directory subtree starting at the given path.
def list_trials(experiment_path, sort=None, output=None, filter_op=None, info_keys=None, result_keys=None): """Lists trials in the directory subtree starting at the given path. Args: experiment_path (str): Directory where t...
Lists experiments in the directory subtree.
def list_experiments(project_path, sort=None, output=None, filter_op=None, info_keys=None): """Lists experiments in the directory subtree. Args: project_path (str): Directory where experiments are located. C...
Opens a txt file at the given path where user can add and save notes.
def add_note(path, filename="note.txt"): """Opens a txt file at the given path where user can add and save notes. Args: path (str): Directory where note will be saved. filename (str): Name of note. Defaults to "note.txt" """ path = os.path.expanduser(path) assert os.path.isdir(path)...