global_chunk_id int64 0 478 | text stringlengths 288 999 |
|---|---|
400 | Retrying failed tasks#
When a worker is executing a task, if the worker dies unexpectedly, either
because the process crashed or because the machine failed, Ray will rerun
the task until either the task succeeds or the maximum number of retries is
exceeded. The default number of retries is 3 and can be overridden by
sp... |
401 | @ray.remote(max_retries=1)
def potentially_fail(failure_probability):
time.sleep(0.2)
if np.random.random() < failure_probability:
os._exit(0)
return 0
for _ in range(3):
try:
# If this task crashes, Ray will retry it up to one additional
# time. If either of the attempts succee... |
402 | When a task returns a result in the Ray object store, it is possible for the
resulting object to be lost after the original task has already finished.
In these cases, Ray will also try to automatically recover the object by
re-executing the tasks that created the object. This can be configured through
the same max_retr... |
403 | ray.init(ignore_reinit_error=True)
class RandomError(Exception):
pass
@ray.remote(max_retries=1, retry_exceptions=True)
def potentially_fail(failure_probability):
if failure_probability < 0 or failure_probability > 1:
raise ValueError(
"failure_probability must be between 0 and 1, but got:... |
404 | # Provide the exceptions that we want to retry as an allowlist.
retry_on_exception = potentially_fail.options(retry_exceptions=[RandomError])
try:
# This will fail since we're passing in -1 for the failure_probability,
# which will raise a ValueError in the task and does not match the RandomError
# exceptio... |
405 | Cancelling misbehaving tasks#
If a task is hanging, you may want to cancel the task to continue to make
progress. You can do this by calling ray.cancel on an ObjectRef
returned by the task. By default, this will send a KeyboardInterrupt to the
task’s worker if it is mid-execution. Passing force=True to ray.cancel
will... |
406 | Actor Fault Tolerance#
Actors can fail if the actor process dies, or if the owner of the actor
dies. The owner of an actor is the worker that originally created the actor by
calling ActorClass.remote(). Detached actors do
not have an owner process and are cleaned up when the Ray cluster is destroyed. |
407 | Actor process failure#
Ray can automatically restart actors that crash unexpectedly.
This behavior is controlled using max_restarts,
which sets the maximum number of times that an actor will be restarted.
The default value of max_restarts is 0, meaning that the actor won’t be
restarted. If set to -1, the actor will be ... |
408 | ray.get is called on the future returned by the task. Note that this
exception may be thrown even though the task did indeed execute successfully.
For example, this can happen if the actor dies immediately after executing the
task.
Ray also offers at-least-once execution semantics for actor tasks
(max_task_retries=-1 o... |
409 | ray.init()
# This actor kills itself after executing 10 tasks.
@ray.remote(max_restarts=4, max_task_retries=-1)
class Actor:
def __init__(self):
self.counter = 0
def increment_and_possibly_fail(self):
# Exit after every 10 tasks.
if self.counter == 10:
os._exit(0)
s... |
410 | # After the actor has been restarted 4 times, all subsequent methods will
# raise a `RayActorError`.
for _ in range(10):
try:
counter = ray.get(actor.increment_and_possibly_fail.remote())
print(counter) # Unreachable.
except ray.exceptions.RayActorError:
print("FAILURE") # Prints 10 ti... |
411 | Note
For async or threaded actors, tasks might be
executed out of order. Upon actor restart, the system
will only retry incomplete tasks. Previously completed tasks will not be
re-executed.
At-least-once execution is best suited for read-only actors or actors with
ephemeral state that does not need to be rebuilt after... |
412 | Actor checkpointing#
max_restarts automatically restarts the crashed actor,
but it doesn’t automatically restore application level state in your actor.
Instead, you should manually checkpoint your actor’s state and recover upon actor restart.
For actors that are restarted manually, the actor’s creator should manage the... |
413 | class Controller:
def __init__(self):
self.worker = Worker.remote()
self.worker_state = ray.get(self.worker.checkpoint.remote())
def execute_task_with_fault_tolerance(self):
i = 0
while True:
i = i + 1
try:
ray.get(self.worker.execute_task... |
414 | Alternatively, if you are using Ray’s automatic actor restart, the actor can checkpoint itself manually and restore from a checkpoint in the constructor:
@ray.remote(max_restarts=-1, max_task_retries=-1)
class ImmortalActor:
def __init__(self, checkpoint_file):
self.checkpoint_file = checkpoint_file
... |
415 | # Checkpoint the latest state
with open(self.checkpoint_file, "w") as f:
json.dump(self.state, f)
def get(self, key):
return self.state[key]
checkpoint_dir = tempfile.mkdtemp()
actor = ImmortalActor.remote(os.path.join(checkpoint_dir, "checkpoint.json"))
ray.get(actor.update.remote("1... |
416 | Actor creator failure#
For non-detached actors, the owner of an actor is the
worker that created it, i.e. the worker that called ActorClass.remote(). Similar to
objects, if the owner of an actor dies, then
the actor will also fate-share with the owner. Ray will not automatically
recover an actor whose owner is dead, e... |
417 | @ray.remote(max_restarts=-1)
class Actor:
def ping(self):
return "hello"
@ray.remote
class Parent:
def generate_actors(self):
self.child = Actor.remote()
self.detached_actor = Actor.options(name="actor", lifetime="detached").remote()
return self.child, self.detached_actor, os.ge... |
418 | try:
print("detached_actor.ping:", ray.get(detached_actor.ping.remote()))
except ray.exceptions.RayActorError as e:
print("Failed to submit detached actor call", e)
# detached_actor.ping: hello
Force-killing a misbehaving actor#
Sometimes application-level code can cause an actor to hang or leak resources.... |
419 | Actor method calls are executed at-most-once. When a ray.get() call raises the ActorUnavailableError exception, there’s no guarantee on
whether the actor executed the task or not. If the method has side effects, they may or may not
be observable. Ray does guarantee that the method won’t be executed twice, unless the ac... |
420 | “quarantine” the actor and stop sending traffic to the actor. It can then periodically ping
the actor until it raises ActorDiedError or returns OK.
If a task has max_task_retries > 0 and it received ActorUnavailableError, Ray will retry the task up to max_task_retries times. If the actor is restarting in its constructo... |
421 | Actor method exceptions#
Sometime you want to retry when an actor method raises exceptions. Use max_task_retries with retry_exceptions to retry.
Note that by default, retrying on user raised exceptions is disabled. To enable it, make sure the method is idempotent, that is, invoking it multiple times should be equivalen... |
422 | - retry_exceptions is a list of exceptions: Ray retries a method on user exception up to max_task_retries times, only if the method raises an exception from these specific classes.
max_task_retries applies to both exceptions and actor crashes. A Ray actor can set this option to apply to all of its methods. A method can... |
423 | The method call’s value, for example, actor.method.options(max_task_retries=2). Ray ignores this value if you don’t set it.
The method definition’s value, for example, @ray.method(max_task_retries=2). Ray ignores this value if you don’t set it.
The actor creation call’s value, for example, Actor.options(max_task_retrie... |
424 | Object Fault Tolerance#
A Ray object has both data (the value returned when calling ray.get) and
metadata (e.g., the location of the value). Data is stored in the Ray object
store while the metadata is stored at the object’s owner. The owner of an
object is the worker process that creates the original ObjectRef, e.g., ... |
425 | Ray can automatically recover from data loss but not owner failure.
Recovering from data loss#
When an object value is lost from the object store, such as during node
failures, Ray will use lineage reconstruction to recover the object.
Ray will first automatically attempt to recover the value by looking
for copies of ... |
426 | The object, and any of its transitive dependencies, must have been generated
by a task (actor or non-actor). This means that objects created by
ray.put are not recoverable.
Tasks are assumed to be deterministic and idempotent. Thus,
by default, objects created by actor tasks are not reconstructable. To allow
reconstruc... |
427 | Lineage reconstruction can cause higher than usual driver memory
usage because the driver keeps the descriptions of any tasks that may be
re-executed in case of failure. To limit the amount of memory used by
lineage, set the environment variable RAY_max_lineage_bytes (default 1GB)
to evict lineage if the threshold is e... |
428 | Understanding ObjectLostErrors#
Ray throws an ObjectLostError to the application when an object cannot be
retrieved due to application or system error. This can occur during a
ray.get() call or when fetching a task’s arguments, and can happen for a
number of reasons. Here is a guide to understanding the root cause for
... |
429 | OwnerDiedError: The owner of an object, i.e., the Python worker that
first created the ObjectRef via .remote() or ray.put(), has died.
The owner stores critical object metadata and an object cannot be retrieved
if this process is lost.
ObjectReconstructionFailedError: This error is thrown if an object, or
another objec... |
430 | Node Fault Tolerance#
A Ray cluster consists of one or more worker nodes,
each of which consists of worker processes and system processes (e.g. raylet).
One of the worker nodes is designated as the head node and has extra processes like the GCS.
Here, we describe node failures and their impact on tasks, actors, and obj... |
431 | Raylet failure#
When a raylet process fails, the corresponding node will be marked as dead and is treated the same as node failure.
Each raylet is associated with a unique id, so even if the raylet restarts on the same physical machine,
it’ll be treated as a new raylet/node to the Ray cluster. |
432 | Pattern: Using nested tasks to achieve nested parallelism
Pattern: Using generators to reduce heap memory usage
Pattern: Using ray.wait to limit the number of pending tasks
Pattern: Using resources to limit the number of concurrently running tasks
Pattern: Using asyncio to run actor methods concurrently
Pattern: Using ... |
433 | Anti-pattern: Fetching too many objects at once with ray.get causes failure
Anti-pattern: Over-parallelizing with too fine-grained tasks harms speedup
Anti-pattern: Redefining the same remote function or class harms performance
Anti-pattern: Passing the same large argument by value repeatedly harms performance
Anti-pat... |
434 | GCS Fault Tolerance#
Global Control Service (GCS) is a server that manages cluster-level metadata.
It also provides a handful of cluster-level operations including actor, placement groups and node management.
By default, the GCS is not fault tolerant since all the data is stored in-memory and its failure means that the... |
435 | Setting up Redis#
KubeRay (officially supported)
If you are using KubeRay, refer to KubeRay docs on GCS Fault Tolerance.
ray start
If you are using ray start to start the Ray head node,
set the OS environment RAY_REDIS_ADDRESS to
the Redis address, and supply the --redis-password flag with the password when calli... |
436 | Kubernetes
If you are using Kubernetes but not KubeRay, please refer to this doc.
Once the GCS is backed by Redis, when it restarts, it’ll recover the
state by reading from Redis. When the GCS is recovering from its failed state, the raylet
will try to reconnect to the GCS.
If the raylet fails to reconnect to the GCS... |
437 | Note
GCS fault tolerance with external Redis is officially supported
ONLY if you are using KubeRay for Ray serve fault tolerance.
For other cases, you can use it at your own risk and
you need to implement additional mechanisms to detect the failure of GCS or the head node
and restart it. |
438 | Pattern: Using nested tasks to achieve nested parallelism#
In this pattern, a remote task can dynamically call other remote tasks (including itself) for nested parallelism.
This is useful when sub-tasks can be parallelized.
Keep in mind, though, that nested tasks come with their own cost: extra worker processes, schedu... |
439 | Tree of tasks#
Code example#
import ray
import time
from numpy import random
def partition(collection):
# Use the last element as the pivot
pivot = collection.pop()
greater, lesser = [], []
for element in collection:
if element > pivot:
greater.append(element)
else:
... |
440 | @ray.remote
def quick_sort_distributed(collection):
# Tiny tasks are an antipattern.
# Thus, in our example we have a "magic number" to
# toggle when distributed recursion should be used vs
# when the sorting should be done in place. The rule
# of thumb is that the duration of an individual task
... |
441 | for size in [200000, 4000000, 8000000]:
print(f"Array size: {size}")
unsorted = random.randint(1000000, size=(size)).tolist()
s = time.time()
quick_sort(unsorted)
print(f"Sequential execution: {(time.time() - s):.3f}")
s = time.time()
ray.get(quick_sort_distributed.remote(unsorted))
prin... |
442 | We call ray.get() after both quick_sort_distributed function invocations take place.
This allows you to maximize parallelism in the workload. See Anti-pattern: Calling ray.get in a loop harms parallelism for more details.
Notice in the execution times above that with smaller tasks, the non-distributed version is faster... |
443 | Pattern: Using generators to reduce heap memory usage#
In this pattern, we use generators in Python to reduce the total heap memory usage during a task. The key idea is that for tasks that return multiple objects, we can return them one at a time instead of all at once. This allows a worker to free the heap memory used... |
444 | @ray.remote
def large_values(num_returns):
return [
np.random.randint(np.iinfo(np.int8).max, size=(100_000_000, 1), dtype=np.int8)
for _ in range(num_returns)
]
However, this will require the task to hold all num_returns arrays in heap memory at the same time at the end of the task. If there a... |
445 | Code example#
import sys
import ray
# fmt: off
# __large_values_start__
import numpy as np
@ray.remote
def large_values(num_returns):
return [
np.random.randint(np.iinfo(np.int8).max, size=(100_000_000, 1), dtype=np.int8)
for _ in range(num_returns)
]
# __large_values_end__
# fmt: on
# fmt:... |
446 | # A large enough value (e.g. 100).
num_returns = int(sys.argv[1])
# Worker will likely OOM using normal returns.
print("Using normal functions...")
try:
ray.get(
large_values.options(num_returns=num_returns, max_retries=0).remote(
num_returns
)[0]
)
except ray.exceptions.WorkerCrashe... |
447 | $ RAY_IGNORE_UNHANDLED_ERRORS=1 python test.py 100
Using normal functions...
... -- A worker died or was killed while executing a task by an unexpected system error. To troubleshoot the problem, check the logs for the dead worker...
Worker failed
Using generators...
(large_values_generator pid=373609) yielded return v... |
448 | Pattern: Using ray.wait to limit the number of pending tasks#
In this pattern, we use ray.wait() to limit the number of pending tasks.
If we continuously submit tasks faster than their process time, we will accumulate tasks in the pending task queue, which can eventually cause OOM.
With ray.wait(), we can apply backpre... |
449 | Note
This method is meant primarily to limit how many tasks should be in flight at the same time.
It can also be used to limit how many tasks can run concurrently, but it is not recommended, as it can hurt scheduling performance.
Ray automatically decides task parallelism based on resource availability, so the recommen... |
450 | ray.init()
@ray.remote
class Actor:
async def heavy_compute(self):
# taking a long time...
# await asyncio.sleep(5)
return
actor = Actor.remote()
NUM_TASKS = 1000
result_refs = []
# When NUM_TASKS is large enough, this will eventually OOM.
for _ in range(NUM_TASKS):
result_refs.appe... |
451 | Pattern: Using asyncio to run actor methods concurrently#
By default, a Ray actor runs in a single thread and
actor method calls are executed sequentially. This means that a long running method call blocks all the following ones.
In this pattern, we use await to yield control from the long running method call so other ... |
452 | @ray.remote
class TaskStore:
def get_next_task(self):
return "task"
@ray.remote
class TaskExecutor:
def __init__(self, task_store):
self.task_store = task_store
self.num_executed_tasks = 0
def run(self):
while True:
task = ray.get(task_store.get_next_task.remot... |
453 | This is problematic because TaskExecutor.run method runs forever and never yield the control to run other methods.
We can solve this problem by using async actors and use await to yield control:
@ray.remote
class AsyncTaskExecutor:
def __init__(self, task_store):
self.task_store = task_store
self.nu... |
454 | def get_num_executed_tasks(self):
return self.num_executed_tasks
async_task_executor = AsyncTaskExecutor.remote(task_store)
async_task_executor.run.remote()
# We are able to run get_num_executed_tasks while run method is running.
num_executed_tasks = ray.get(async_task_executor.get_num_executed_tasks.remote()... |
455 | Pattern: Using resources to limit the number of concurrently running tasks#
In this pattern, we use resources to limit the number of concurrently running tasks.
By default, Ray tasks require 1 CPU each and Ray actors require 0 CPU each, so the scheduler limits task concurrency to the available CPUs and actor concurrenc... |
456 | Note
For actor tasks, the number of running actors limits the number of concurrently running actor tasks we can have.
Example use case#
You have a data processing workload that processes each input file independently using Ray remote functions.
Since each task needs to load the input data into heap memory and do the ... |
457 | @ray.remote
def process(file):
# Actual work is reading the file and process the data.
# Assume it needs to use 2G memory.
pass
NUM_FILES = 1000
result_refs = []
for i in range(NUM_FILES):
# By default, process task will use 1 CPU resource and no other resources.
# This means 16 tasks can run conc... |
458 | Pattern: Using an actor to synchronize other tasks and actors#
When you have multiple tasks that need to wait on some condition or otherwise
need to synchronize across tasks & actors on a cluster, you can use a central
actor to coordinate among them.
Example use case#
You can use an actor to implement a distributed as... |
459 | @ray.remote
def wait_and_go(signal):
ray.get(signal.wait.remote())
print("go!")
signal = SignalActor.remote()
tasks = [wait_and_go.remote(signal) for _ in range(4)]
print("ready...")
# Tasks will all be waiting for the signals.
print("set..")
ray.get(signal.send.remote())
# Tasks are unblocked.
ray.get(task... |
460 | Pattern: Using a supervisor actor to manage a tree of actors#
Actor supervision is a pattern in which a supervising actor manages a collection of worker actors.
The supervisor delegates tasks to subordinates and handles their failures.
This pattern simplifies the driver since it manages only a few supervisors and does ... |
461 | Note
For data parallel training and hyperparameter tuning, it’s recommended to use Ray Train (DataParallelTrainer and Ray Tune’s Tuner)
which applies this pattern under the hood.
Code example#
import ray
@ray.remote(num_cpus=1)
class Trainer:
def __init__(self, hyperparameter, data):
self.hyperparamete... |
462 | def fit(self):
# Train with different data shard in parallel.
return ray.get([trainer.fit.remote() for trainer in self.trainers])
data = [1, 2, 3]
supervisor1 = Supervisor.remote(1, data)
supervisor2 = Supervisor.remote(2, data)
# Train with different hyperparameters in parallel.
model1 = supervisor1.... |
463 | Pattern: Using pipelining to increase throughput#
If you have multiple work items and each requires several steps to complete,
you can use the pipelining technique to improve the cluster utilization and increase the throughput of your system.
Note
Pipelining is an important technique to improve the performance and is ... |
464 | @ray.remote
class WorkerWithoutPipelining:
def __init__(self, work_queue):
self.work_queue = work_queue
def process(self, work_item):
print(work_item)
def run(self):
while True:
# Get work from the remote queue.
work_item = ray.get(self.work_queue.get_work_i... |
465 | if work_item is None:
break
self.work_item_ref = self.work_queue.get_work_item.remote()
# Do work while we are fetching the next work item.
self.process(work_item)
work_queue = WorkQueue.remote()
worker_without_pipelining = WorkerWithoutPipelining.remote(work_queu... |
466 | It disallows inlining small return values: Ray has a performance optimization to return small (<= 100KB) values inline directly to the caller, avoiding going through the distributed object store.
On the other hand, ray.put() will unconditionally store the value to the object store which makes the optimization for small... |
467 | Code example#
If you want to return a single value regardless if it’s small or large, you should return it directly.
import ray
import numpy as np
@ray.remote
def task_with_single_small_return_value_bad():
small_return_value = 1
# The value will be stored in the object store
# and the reference is returne... |
468 | @ray.remote
def task_with_single_large_return_value_good():
# Both approaches will store the large array to the object store
# but this is better since it's faster and more fault tolerant.
large_return_value = np.zeros(10 * 1024 * 1024)
return large_return_value
assert np.array_equal(
ray.get(ray.... |
469 | actor = Actor.remote()
assert np.array_equal(
ray.get(ray.get(actor.task_with_single_return_value_bad.remote())),
ray.get(actor.task_with_single_return_value_good.remote()),
)
If you want to return multiple values and you know the number of returns before calling the task, you should use the num_returns optio... |
470 | # This will return two objects each of which is the actual value.
@ray.remote(num_returns=2)
def task_with_static_multiple_returns_good():
return_value_1 = 1
return_value_2 = 2
return (return_value_1, return_value_2)
assert (
ray.get(ray.get(task_with_static_multiple_returns_bad1.remote())[0])
== ... |
471 | @ray.method(num_returns=2)
def task_with_static_multiple_returns_good(self):
# This is faster and more fault tolerant.
return_value_1 = 1
return_value_2 = 2
return (return_value_1, return_value_2)
actor = Actor.remote()
assert (
ray.get(ray.get(actor.task_with_static_multiple_r... |
472 | Anti-pattern: Calling ray.get in a loop harms parallelism#
TLDR: Avoid calling ray.get() in a loop since it’s a blocking call; use ray.get() only for the final result.
A call to ray.get() fetches the results of remotely executed functions. However, it is a blocking call, which means that it always waits until the reque... |
473 | The solution here is to separate the call to ray.get() from the call to the remote functions. That way all remote functions are spawned before we wait for the results and can run in parallel in the background. Additionally, you can pass a list of object references to ray.get() instead of calling it one by one to wait f... |
474 | Code example#
import ray
ray.init()
@ray.remote
def f(i):
return i
# Anti-pattern: no parallelism due to calling ray.get inside of the loop.
sequential_returns = []
for i in range(100):
sequential_returns.append(ray.get(f.remote(i)))
# Better approach: parallelism because the tasks are executed in paralle... |
475 | Anti-pattern: Calling ray.get unnecessarily harms performance#
TLDR: Avoid calling ray.get() unnecessarily for intermediate steps. Work with object references directly, and only call ray.get() at the end to get the final result.
When ray.get() is called, objects must be transferred to the worker/node that calls ray.get... |
476 | # `ray.get()` downloads the result here.
rollout = ray.get(generate_rollout.remote())
# Now we have to reupload `rollout`
reduced = ray.get(reduce.remote(rollout))
Better approach:
# Don't need ray.get here.
rollout_obj_ref = generate_rollout.remote()
# Rollout object is passed by reference.
reduced = ray.get(reduc... |
477 | Anti-pattern: Processing results in submission order using ray.get increases runtime#
TLDR: Avoid processing independent results in submission order using ray.get() since results may be ready in a different order than the submission order.
A batch of tasks is submitted, and we need to process their results individually... |
478 | Processing results in submission order vs completion order#
Code example#
import random
import time
import ray
ray.init()
@ray.remote
def f(i):
time.sleep(random.random())
return i
# Anti-pattern: process results in the submission order.
sum_in_submission_order = 0
refs = [f.remote(i) for i in range(100... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.