text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
worker.error_message_pubsub_client = worker.redis_client.pubsub( ignore_subscribe_messages=True) # Exports that are published after the call to # error_message_pubsub_client.subscribe and before the call to # error_message_pubsub_client.listen will still be processed in the loop. # Really ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 # tests. worker = global_worker if worker.connected: # Shutdown all ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
# Pickling, loading, and pickling again seems to produce more consistent # results than simply pickling. This is a bit class_id = pickle.dumps(cls) for _ in range(depth): new_class_id = pickle.dumps(pickle.loads(class_id)) if new_class_id == class_id: # We appear to have rea...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_custom_serializer(cls, use_pickle=False, use_dict=False, serializer=None, deserializer=None, local=False, driver_id=None, class_id=None): """Enable ...
worker = global_worker assert (serializer is None) == (deserializer is None), ( "The serializer/deserializer arguments must both be provided or " "both not be provided.") use_custom_serializer = (serializer is not None) assert use_custom_serializer + use_pickle + use_dict == 1, ( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
worker = global_worker worker.check_connected() with profiling.profile("ray.get"): if worker.mode == LOCAL_MODE: # In LOCAL_MODE, ray.get is the identity operation (the input will # actually be a value not an objectid). return object_ids global last_task_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: # In LOCAL_MODE, ray.put is the identity operation. return value object_id = ray._raylet.compute_put_id( worker.current_task_id, w...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: ....
worker = get_global_worker() if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): # This is the case where the decorator is just @ray.remote. return make_decorator(worker=worker)(args[0]) # Parse the keyword arguments from the decorator. error_string = ("The @ray.remote decor...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 cur...
if not hasattr(self._task_context, "initialized"): # Initialize task_context for the current thread. if ray.utils.is_main_thread(): # If this is running on the main thread, initialize it to # NIL. The actual value will set when the worker receives ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 driv...
# This function needs to be proctected by a lock, because it will be # called by`register_class_for_serialization`, as well as the import # thread, from different threads. Also, this function will recursively # call itself, so we use RLock here. with self.lock: if dr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
counter = 0 while True: if counter == depth: raise Exception("Ray exceeded the maximum number of classes " "that it will recursively serialize when " "attempting to serialize an object of " ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
# Make sure that the value is not an object ID. if isinstance(value, ObjectID): raise TypeError( "Calling 'put' on an ray.ObjectID is not allowed " "(similarly, returning an ray.ObjectID from a remote " "function is not allowed). If you really...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 objec...
# Make sure that the values are object IDs. for object_id in object_ids: if not isinstance(object_id, ObjectID): raise TypeError( "Attempting to call `get` on the value {}, " "which is not an ray.ObjectID.".format(object_id)) #...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
with profiling.profile("submit_task"): if actor_id is None: assert actor_handle_id is None actor_id = ActorID.nil() actor_handle_id = ActorHandleID.nil() else: assert actor_handle_id is not None if actor_creati...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
# If ray.init has not been called yet, then cache the function and # export it when connect is called. Otherwise, run the function on all # workers. if self.mode is None: self.cached_functions_to_run.append(function) else: # Attempt to pickle the function...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_arguments_for_execution(self, function_name, serialized_args): """Retrieve the arguments for the remote function. This retrieves the values for the argu...
arguments = [] for (i, arg) in enumerate(serialized_args): if isinstance(arg, ObjectID): # get the object from the local object store argument = self.get_object([arg])[0] if isinstance(argument, RayError): raise argument ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 w...
for i in range(len(object_ids)): if isinstance(outputs[i], ray.actor.ActorHandle): raise Exception("Returning an actor handle from a remote " "function is not allowed).") if outputs[i] is ray.experimental.no_return.NoReturn: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _process_task(self, task, function_execution_info): """Execute a task assigned to this worker. This method deserializes a task from the scheduler, and attemp...
assert self.current_task_id.is_nil() assert self.task_context.task_index == 0 assert self.task_context.put_index == 1 if task.actor_id().is_nil(): # If this worker is not an actor, check that `task_driver_id` # was reset when the worker finished the previous task...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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() # TODO(rkn): It would be preferable for actor creation tasks to share # more of the code path with regular task execution. if not task.actor_creat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. ray.utils.set_cuda_visible_devices(ray.get_gpu_ids()) return task
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_and_process_task(task)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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....
for key, val in weights.items(): new_shape = val.shape[0:start] + (-1, ) + val.shape[stop:] weights[key] = val.reshape(new_shape) return weights
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, "webui_url": self._webui_url, }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_redis_client(self): """Create a redis client."""
return ray.services.create_redis_client( self._redis_address, self._ray_params.redis_password)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_inc_temp(self, suffix="", prefix="", directory_name="/tmp/ray"): """Return a incremental temporary file name. The file is not created. Args: suffix (st...
directory_name = os.path.expanduser(directory_name) index = self._incremental_dict[suffix, prefix, directory_name] # `tempfile.TMP_MAX` could be extremely large, # so using `range` in Python2.x should be avoided. while index < tempfile.TMP_MAX: if index == 0: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def new_log_files(self, name, redirect_output=True): """Generate partially randomized filenames for log files. Args: name (str): descriptive string for this log...
if redirect_output is None: redirect_output = self._ray_params.redirect_output if not redirect_output: return None, None log_stdout = self._make_inc_temp( suffix=".out", prefix=name, directory_name=self._logs_dir) log_stderr = self._make_inc_temp( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. Mak...
if socket_path is not None: if os.path.exists(socket_path): raise Exception("Socket file {} exists!".format(socket_path)) socket_dir = os.path.dirname(socket_path) try_to_create_directory(socket_dir) return socket_path return self._make_in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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._redis_address, redis_shards, process_infos) = ray.servic...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_file, redis_password=self._ray_params.redis_password) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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=self._ray_params.redis_password) assert ray_constants....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_file=stderr_file, redis_password=self._ray_param...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.object_store_memory, plasma_directory=self._ray_params.pla...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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....
stdout_file, stderr_file = self.new_log_files("raylet") process_info = ray.services.start_raylet( self._redis_address, self._node_ip_address, self._raylet_socket_name, self._plasma_store_socket_name, self._ray_params.worker_path, s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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._ray_params.autoscaling_config, redis_password=s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, redis_password=self._ray_params.redis_password, config=sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 processes. self.start_redis() self.start_monitor() self.st...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_reporter() if self._ray_params.include_log_monitor: self.start_log_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
process_infos = self.all_processes[process_type] if process_type != ray_constants.PROCESS_TYPE_REDIS_SERVER: assert len(process_infos) == 1 for process_info in process_infos: process = process_info.process # Handle the case where the process has already exite...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_alive)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_constants.PROCESS_TYPE_REPORTER, check_alive=check_alive)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_alive)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
# Kill the raylet first. This is important for suppressing errors at # shutdown because we give the raylet a chance to exit gracefully and # clean up its child worker processes. If we were to kill the plasma # store (or Redis) first, that could cause the raylet to exit # ungrace...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.process.poll() is None: result.append((process_type, process_info.process)) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: return model_map[model_name]()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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\"" % (model_name, dataset_name)) model_map[model_name] = model_func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 d...
env_timestep_limit = env.spec.max_episode_steps timestep_limit = (env_timestep_limit if timestep_limit is None else min( timestep_limit, env_timestep_limit)) rews = [] t = 0 observation = env.reset() for _ in range(timestep_limit or 999999): ac = policy.compute(observation, add_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 return trials
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _generate_trials(self, unresolved_spec, output_path=""): """Generates Trial objects with the variant generation process. Uses a fixed point iteration to reso...
if "run" not in unresolved_spec: raise TuneError("Must specify `run` in {}".format(unresolved_spec)) for _ in range(unresolved_spec.get("num_samples", 1)): for resolved_vars, spec in generate_variants(unresolved_spec): experiment_tag = str(self._counter) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reduce(self, start=0, end=None): """Returns result of applying `self.operation` to a contiguous subsequence of the array. self.operation( Parameters start: i...
if end is None: end = self._capacity - 1 if end < 0: end += self._capacity return self._reduce_helper(start, end, 1, 0, self._capacity - 1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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." ) ray.worker.global_worker.check_connected() redis_client = ray.worker.global_work...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 a...
path = os.environ.get("TUNE_CLUSTER_SSH_KEY", os.path.expanduser("~/ray_bootstrap_key.pem")) if os.path.exists(path): return path return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
ho_trial = self._get_hyperopt_trial(trial_id) if ho_trial is None: return ho_trial["refresh_time"] = hpo.utils.coarse_utcnow() if error: ho_trial["state"] = hpo.base.JOB_STATE_ERROR ho_trial["misc"]["error"] = (str(TuneError), "Tune Error") el...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plasma_get(object_id): """Get an object directly from plasma without going through object table. Precondition: plasma_prefetch(object_id) has been called bef...
client = ray.worker.global_worker.plasma_client plasma_id = ray.pyarrow.plasma.ObjectID(object_id) while not client.contains(plasma_id): pass return client.get(plasma_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_kv._internal_kv_get(self.read_ack_key) if remote_offset is None: # logg...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.remote() agent_dict[fut_sample] = agent while agent_dict: [fut_sample], _ = ray.wait(list(agent_dict)) agent = agent_dict.pop(fut_sample) next_sample ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 lau...
num_timesteps_so_far = 0 trajectories = [] agent_dict = {} for agent in agents: fut_sample = agent.sample.remote() agent_dict[fut_sample] = agent while num_timesteps_so_far < train_batch_size: # TODO(pcm): Make wait support arbitrary iterators and remove the # con...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_error_message(exception_message, task_exception=False): """Improve the formatting of an exception thrown by a remote function. This method takes a tra...
lines = exception_message.split("\n") if task_exception: # For errors that occur inside of tasks, remove lines 1 and 2 which are # always the same, they just contain information about the worker code. lines = lines[0:1] + lines[3:] pass return "\n".join(lines)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 correct me if I'm wrong. def check_cython(x): return type(x).__nam...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 functi...
return inspect.isfunction(obj) or inspect.ismethod(obj) or is_cython(obj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. Ther...
# Get the state of the numpy random number generator. numpy_state = np.random.get_state() # Try to use true randomness. np.random.seed(None) # Generate the random ID. random_id = np.random.bytes(ray_constants.ID_SIZE) # Reset the state of the numpy random number generator. np.random.set...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
if byte_str is None and allow_none: return "" if not isinstance(byte_str, bytes): raise ValueError( "The argument {} must be a bytes object.".format(byte_str)) if sys.version_info >= (3, 0): return byte_str.decode("ascii") else: return byte_str
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 l...
gpu_ids_str = os.environ.get("CUDA_VISIBLE_DEVICES", None) if gpu_ids_str is None: return None if gpu_ids_str == "": return [] return [int(i) for i in gpu_ids_str.split(",")]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resources_from_resource_arguments(default_num_cpus, default_num_gpus, default_resources, runtime_num_cpus, runtime_num_gpus, runtime_resources): """Determine...
if runtime_resources is not None: resources = runtime_resources.copy() elif default_resources is not None: resources = default_resources.copy() else: resources = {} if "CPU" in resources or "GPU" in resources: raise ValueError("The resources dictionary must not " ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 None: _default_handler = logging.StreamHandler() logger.addHandler(_defa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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"): line = line.strip() if stat in line: return int(line.split(b" ")[0]) raise ValueError("Can't find {} in 'vmstat' output.".format(stat))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sysctl(command): """Run a sysctl command and parse the output. Args: command: A sysctl command with an argument, for example, ["sysctl", "hw.memsize"]. Retur...
out = subprocess.check_output(command) result = out.split(b" ")[1] try: return int(result) except ValueError: return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 # often much larger than the actual amount of memory. docker_limit = None memory_limit_filename = "/sys/fs/cgroup/memory/memory.limit_in_bytes" if os...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_RDONLY) try: shm_fs_stats = os.fstatvfs(shm_fd) # The value shm_fs_stats.f_bsize is the block size and the # value shm_fs_stats.f_bavail is the...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. nam...
length = len(pickled) if length <= ray_constants.PICKLE_OBJECT_WARNING_SIZE: return warning_message = ( "Warning: The {} {} has size {} when pickled. " "It will be stored in Redis, which could cause memory issues. " "This may mean that its definition uses a large array or ot...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 b...
if lock is None: lock = threading.Lock() return _ThreadSafeProxy(client, lock)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 = DistArray.compute_block_lower(index, self.shape) upper = DistArray.compute_block_upper...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
log_probs = [] for i in range(len(policy_logits)): log_probs.append(-tf.nn.sparse_softmax_cross_entropy_with_logits( logits=policy_logits[i], labels=actions[i])) return log_probs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_logits(behaviour_policy_logits, target_policy_logits, actions, discounts, rewards, values, bootstrap_value, clip_rho_threshold=1.0, clip_pg_rho_threshold...
res = multi_from_logits( [behaviour_policy_logits], [target_policy_logits], [actions], discounts, rewards, values, bootstrap_value, clip_rho_threshold=clip_rho_threshold, clip_pg_rho_threshold=clip_pg_rho_threshold, name=name) return VTraceFromL...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def multi_from_logits(behaviour_policy_logits, target_policy_logits, actions, discounts, rewards, values, bootstrap_value, clip_rho_threshold=1.0, clip_pg_rho_thr...
for i in range(len(behaviour_policy_logits)): behaviour_policy_logits[i] = tf.convert_to_tensor( behaviour_policy_logits[i], dtype=tf.float32) target_policy_logits[i] = tf.convert_to_tensor( target_policy_logits[i], dtype=tf.float32) actions[i] = tf.convert_to_tenso...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
t = tf.stack(target_action_log_probs) b = tf.stack(behaviour_action_log_probs) log_rhos = tf.reduce_sum(t - b, axis=0) return log_rhos
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_format_output(dataframe): """Prints output of given dataframe to fit into terminal. Returns: table (pd.DataFrame): Final outputted dataframe. dropped_...
print_df = pd.DataFrame() dropped_cols = [] empty_cols = [] # column display priority is based on the info_keys passed in for i, col in enumerate(dataframe): if dataframe[col].isnull().all(): # Don't add col to print_df if is fully empty empty_cols += [col] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
path = os.path.expanduser(path) assert os.path.isdir(path), "{} is not a valid directory.".format(path) filepath = os.path.join(path, filename) exists = os.path.isfile(filepath) try: subprocess.call([EDITOR, filepath]) except Exception as exc: logger.error("Editing note failed...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query_job(request): """Rest API to query the job info, with the given job_id. The url pattern should be like this: curl http://<server>:<port>/query_job?job_...
job_id = request.GET.get("job_id") jobs = JobRecord.objects.filter(job_id=job_id) trials = TrialRecord.objects.filter(job_id=job_id) total_num = len(trials) running_num = sum(t.trial_status == Trial.RUNNING for t in trials) success_num = sum(t.trial_status == Trial.TERMINATED for t in trials) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query_trial(request): """Rest API to query the trial info, with the given trial_id. The url pattern should be like this: curl http://<server>:<port>/query_tr...
trial_id = request.GET.get("trial_id") trials = TrialRecord.objects \ .filter(trial_id=trial_id) \ .order_by("-start_time") if len(trials) == 0: resp = "Unkonwn trial id %s.\n" % trials else: trial = trials[0] result = { "trial_id": trial.trial_id, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_trial_result(self, trial_runner, trial, result): """Callback for early stopping. This stopping rule stops a running trial if the trial's best objective va...
if trial in self._stopped_trials: assert not self._hard_stop return TrialScheduler.CONTINUE # fall back to FIFO time = result[self._time_attr] self._results[trial].append(result) median_result = self._get_median_result(time) best_result = self._best_re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_trial_remove(self, trial_runner, trial): """Marks trial as completed if it is paused and has previously ran."""
if trial.status is Trial.PAUSED and trial in self._results: self._completed_trials.add(trial)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_json(cls, json_info): """Build a Job instance from a json string."""
if json_info is None: return None return JobRecord( job_id=json_info["job_id"], name=json_info["job_name"], user=json_info["user"], type=json_info["type"], start_time=json_info["start_time"])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_json(cls, json_info): """Build a Trial instance from a json string."""
if json_info is None: return None return TrialRecord( trial_id=json_info["trial_id"], job_id=json_info["job_id"], trial_status=json_info["status"], start_time=json_info["start_time"], params=json_info["params"])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_json(cls, json_info): """Build a Result instance from a json string."""
if json_info is None: return None return ResultRecord( trial_id=json_info["trial_id"], timesteps_total=json_info["timesteps_total"], done=json_info.get("done", None), episode_reward_mean=json_info.get("episode_reward_mean", None), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compute_advantages(rollout, last_r, gamma=0.9, lambda_=1.0, use_gae=True): """Given a rollout, compute its value targets and the advantage. Args: rollout (Sa...
traj = {} trajsize = len(rollout[SampleBatch.ACTIONS]) for key in rollout: traj[key] = np.stack(rollout[key]) if use_gae: assert SampleBatch.VF_PREDS in rollout, "Values not found!" vpred_t = np.concatenate( [rollout[SampleBatch.VF_PREDS], np.array([la...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xray_heartbeat_batch_handler(self, unused_channel, data): """Handle an xray heartbeat batch message from Redis."""
gcs_entries = ray.gcs_utils.GcsTableEntry.GetRootAsGcsTableEntry( data, 0) heartbeat_data = gcs_entries.Entries(0) message = (ray.gcs_utils.HeartbeatBatchTableData. GetRootAsHeartbeatBatchTableData(heartbeat_data, 0)) for j in range(message.BatchLength(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xray_driver_removed_handler(self, unused_channel, data): """Handle a notification that a driver has been removed. Args: unused_channel: The message channel. ...
gcs_entries = ray.gcs_utils.GcsTableEntry.GetRootAsGcsTableEntry( data, 0) driver_data = gcs_entries.Entries(0) message = ray.gcs_utils.DriverTableData.GetRootAsDriverTableData( driver_data, 0) driver_id = message.DriverId() logger.info("Monitor: " ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_messages(self, max_messages=10000): """Process all messages ready in the subscription channels. This reads messages from the subscription channels an...
subscribe_clients = [self.primary_subscribe_client] for subscribe_client in subscribe_clients: for _ in range(max_messages): message = subscribe_client.get_message() if message is None: # Continue on to the next subscribe client. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """Run the monitor. This function loops forever, checking for messages about dead database clients and cleaning up state accordingly. """
# Initialize the subscription channel. self.subscribe(ray.gcs_utils.XRAY_HEARTBEAT_BATCH_CHANNEL) self.subscribe(ray.gcs_utils.XRAY_DRIVER_CHANNEL) # TODO(rkn): If there were any dead clients at startup, we should clean # up the associated state in the state tables. # ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def index(request): """View for the home page."""
recent_jobs = JobRecord.objects.order_by("-start_time")[0:100] recent_trials = TrialRecord.objects.order_by("-start_time")[0:500] total_num = len(recent_trials) running_num = sum(t.trial_status == Trial.RUNNING for t in recent_trials) success_num = sum( t.trial_status == Trial.TERMINATED f...