global_chunk_id
int64
0
478
text
stringlengths
288
999
100
# Retrieve final actor state. print(ray.get(c.get.remote())) # -> 10 The preceding example demonstrates basic actor usage. For a more comprehensive example that combines both tasks and actors, see the Monte Carlo Pi estimation example. Passing Objects# Ray’s distributed object store efficiently manages data across ...
101
Here’s an example showing these techniques: import numpy as np # Define a task that sums the values in a matrix. @ray.remote def sum_matrix(matrix): return np.sum(matrix) # Call the task with a literal argument value. print(ray.get(sum_matrix.remote(np.ones((100, 100))))) # -> 10000.0 # Put a large array into th...
102
Key Concepts# This section overviews Ray’s key concepts. These primitives work together to enable Ray to flexibly support a broad range of distributed applications. Tasks# Ray enables arbitrary functions to execute asynchronously on separate Python workers. These asynchronous Ray functions are called tasks. Ray enable...
103
Objects# Tasks and actors create objects and compute on objects. You can refer to these objects as remote objects because Ray stores them anywhere in a Ray cluster, and you use object refs to refer to them. Ray caches remote objects in its distributed shared-memory object store and creates one object store per node in ...
104
Environment Dependencies# When Ray executes tasks and actors on remote machines, their environment dependencies, such as Python packages, local files, and environment variables, must be available on the remote machines. To address this problem, you can 1. Prepare your dependencies on the cluster in advance using the Ra...
105
User Guides# This section explains how to use Ray’s key concepts to build distributed applications. If you’re brand new to Ray, we recommend starting with the walkthrough. Tasks Specifying required resources Passing object refs to Ray tasks Waiting for Partial Results Generators Multiple returns Cancelling tasks Sche...
106
Terminating Actors Manual termination via an actor handle Manual termination within the actor AsyncIO / Concurrency for Actors AsyncIO for Actors Threaded Actors AsyncIO for Remote Tasks Limiting Concurrency Per-Method with Concurrency Groups Defining Concurrency Groups Default Concurrency Group Setting the Concurr...
107
Object Spilling Spilling to a custom directory Stats Environment Dependencies Concepts Preparing an environment using the Ray Cluster launcher Runtime environments Specifying a Runtime Environment Per-Job Specifying a Runtime Environment Per-Task or Per-Actor Common Workflows Using Local Files Using conda or pip ...
108
Remote URIs Hosting a Dependency on a Remote Git Provider: Step-by-Step Guide Option 1: Download Zip (quicker to implement, but not recommended for production environments) Option 2: Manually Create URL (slower to implement, but recommended for production environments) Debugging Scheduling Resources Scheduling Stra...
109
Accelerator Support Starting Ray nodes with accelerators Using accelerators in Tasks and Actors Fractional Accelerators Workers not Releasing GPU Resources Accelerator Types Placement Groups Key Concepts Create a Placement Group (Reserve Resources) Schedule Tasks and Actors to Placement Groups (Use Reserved Resources...
110
Fault tolerance How to write fault tolerant Ray applications More about Ray fault tolerance Task Fault Tolerance Catching application-level failures Retrying failed tasks Cancelling misbehaving tasks Actor Fault Tolerance Actor process failure Actor creator failure Force-killing a misbehaving actor Unavailable actors...
111
Pattern: Using ray.wait to limit the number of pending tasks Example use case Code example Pattern: Using resources to limit the number of concurrently running tasks Example use case Code example Pattern: Using asyncio to run actor methods concurrently Example use case Pattern: Using an actor to synchronize other...
112
Anti-pattern: Processing results in submission order using ray.get increases runtime Code example Anti-pattern: Fetching too many objects at once with ray.get causes failure Code example Anti-pattern: Over-parallelizing with too fine-grained tasks harms speedup Code example Anti-pattern: Redefining the same remot...
113
Anti-pattern: Serialize ray.ObjectRef out of band Code example Anti-pattern: Forking new processes in application code Code example Ray Compiled Graph (beta) Use Cases More Resources Table of Contents Quickstart Hello World Specifying data dependencies asyncio support Execution and failure semantics Execution Tim...
114
Advanced topics Tips for first-time users Tip 1: Delay ray.get() Tip 2: Avoid tiny tasks Tip 3: Avoid passing same object repeatedly to remote tasks Tip 4: Pipeline data processing Starting Ray What is the Ray runtime? Starting Ray on a single machine Starting Ray via the CLI (ray start) Launching a Ray cluster (ray ...
115
Working with Jupyter Notebooks & JupyterLab Setting Up Notebook Lazy Computation Graphs with the Ray DAG API Ray DAG with functions Ray DAG with classes and class methods Ray DAG with custom InputNode Ray DAG with multiple MultiOutputNode Reuse Ray Actors in DAGs More resources Miscellaneous Topics Dynamic Remote P...
116
Tasks# Ray enables arbitrary functions to be executed asynchronously on separate Python workers. Such functions are called Ray remote functions and their asynchronous invocations are called Ray tasks. Here is an example. Python import ray import time # A regular Python function. def normal_function(): return 1...
117
# The result can be retrieved with ``ray.get``. assert ray.get(obj_ref) == 1 @ray.remote def slow_function(): time.sleep(10) return 1 # Ray tasks are executed in parallel. # All computation is performed in the background, driven by Ray's internal event loop. for _ in range(4): # This doesn't block. ...
118
public class MyRayApp { public static int slowFunction() throws InterruptedException { TimeUnit.SECONDS.sleep(10); return 1; } } // Ray tasks are executed in parallel. // All computation is performed in the background, driven by Ray's internal event loop. for(int i = 0; i < 4; i++) { // This doesn't bloc...
119
int SlowFunction() { std::this_thread::sleep_for(std::chrono::seconds(10)); return 1; } RAY_REMOTE(SlowFunction); // Ray tasks are executed in parallel. // All computation is performed in the background, driven by Ray's internal event loop. for(int i = 0; i < 4; i++) { // This doesn't block. ray::Task(SlowFunc...
120
Specifying required resources# You can specify resource requirements in tasks (see Specifying Task or Actor Resource Requirements for more details.) Python # Specify required resources. @ray.remote(num_cpus=4, num_gpus=2) def my_function(): return 1 # Override the default resource requirements. my_function.opt...
121
Python @ray.remote def function_with_an_argument(value): return value + 1 obj_ref1 = my_function.remote() assert ray.get(obj_ref1) == 1 # You can pass an object ref as an argument to another Ray task. obj_ref2 = function_with_an_argument.remote(obj_ref1) assert ray.get(obj_ref2) == 2 Java public class MyRay...
122
C++ static int FunctionWithAnArgument(int value) { return value + 1; } RAY_REMOTE(FunctionWithAnArgument); auto obj_ref1 = ray::Task(MyFunction).Remote(); assert(*obj_ref1.Get() == 1); // You can pass an object ref as an argument to another Ray task. auto obj_ref2 = ray::Task(FunctionWithAnArgument).Remote(obj_re...
123
Waiting for Partial Results# Calling ray.get on Ray task results will block until the task finished execution. After launching a number of tasks, you may want to know which ones have finished executing without blocking on all of them. This could be achieved by ray.wait(). The function works as follows. Python object...
124
Generators# Ray is compatible with Python generator syntax. See Ray Generators for more details. Multiple returns# By default, a Ray task only returns a single Object Ref. However, you can configure Ray tasks to return multiple Object Refs, by setting the num_returns option. Python # By default, a Ray task only re...
125
object_ref0, object_ref1, object_ref2 = return_multiple.remote() assert ray.get(object_ref0) == 0 assert ray.get(object_ref1) == 1 assert ray.get(object_ref2) == 2 For tasks that return multiple objects, Ray also supports remote generators that allow a task to return one object at a time to reduce memory usage at t...
126
Cancelling tasks# Ray tasks can be canceled by calling ray.cancel() on the returned Object ref. Python @ray.remote def blocking_operation(): time.sleep(10e6) obj_ref = blocking_operation.remote() ray.cancel(obj_ref) try: ray.get(obj_ref) except ray.exceptions.TaskCancelledError: print("Object referenc...
127
Task Events# By default, Ray traces the execution of tasks, reporting task status events and profiling events that the Ray Dashboard and State API use. You can change this behavior by setting enable_task_events options in ray.remote() and .options() to disable task events, which reduces the overhead of task execution, ...
128
Nested Remote Functions# Remote functions can call other remote functions, resulting in nested tasks. For example, consider the following. import ray @ray.remote def f(): return 1 @ray.remote def g(): # Call f 4 times and return the resulting object refs. return [f.remote() for _ in range(4)] @ray.rem...
129
>>> ray.get(h.remote()) [1, 1, 1, 1] One limitation is that the definition of f must come before the definitions of g and h because as soon as g is defined, it will be pickled and shipped to the workers, and so if f hasn’t been defined yet, the definition will be incomplete. Yielding Resources While Blocked# Ray wil...
130
Dynamic generators# Python generators are functions that behave like iterators, yielding one value per iteration. Ray supports remote generators for two use cases: To reduce max heap memory usage when returning multiple values from a remote function. See the design pattern guide for an example. When the number of retu...
131
num_returns set by the task caller# Where possible, the caller should set the remote function’s number of return values using @ray.remote(num_returns=x) or foo.options(num_returns=x).remote(). Ray will return this many ObjectRefs to the caller. The remote task should then return the same number of values, usually as a ...
132
@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) ] for this code, which uses a generator function: @ray.remote def large_values_generator(num_returns): for i in range(num_returns):...
133
num_returns set by the task executor# In some cases, the caller may not know the number of return values to expect from a remote function. For example, suppose we want to write a task that breaks up its argument into equal-size chunks and returns these. We may not know the size of the argument until we execute the task...
134
# Returns an ObjectRef[DynamicObjectRefGenerator]. dynamic_ref = split.remote(array_ref, block_size) print(dynamic_ref) # ObjectRef(c8ef45ccd0112571ffffffffffffffffffffffff0100000001000000) i = -1 ref_generator = ray.get(dynamic_ref) print(ref_generator) # <ray._raylet.DynamicObjectRefGenerator object at 0x7f7e2116b29...
135
# NOTE: The dynamic_ref points to the generated ObjectRefs. Make sure that this # ObjectRef goes out of scope so that Ray can garbage-collect the internal # ObjectRefs. del dynamic_ref We can also pass the ObjectRef returned by a task with num_returns="dynamic" to another task. The task will receive the DynamicObject...
136
# This also works, but should be avoided because you have to call an additional # `ray.get`, which blocks the driver. ref_generator = ray.get(dynamic_ref) assert array_size == ray.get(get_size.remote(ref_generator)) # (get_size pid=1504184) # <ray._raylet.DynamicObjectRefGenerator object at 0x7f81c4251b50> Exceptio...
137
ref1, ref2, ref3, ref4 = generator.options(num_returns=4).remote() assert ray.get([ref1, ref2]) == [0, 1] # All remaining ObjectRefs will contain the error. try: ray.get([ref3, ref4]) except Exception as error: print(error) dynamic_ref = generator.options(num_returns="dynamic").remote() ref_generator = ray.get...
138
Note that there is currently a known bug where exceptions will not be propagated for generators that yield more values than expected. This can occur in two cases: When num_returns is set by the caller, but the generator task returns more than this value. When a generator task with num_returns="dynamic" is re-executed,...
139
# Generators that yield more values than expected currently do not throw an # exception (the error is only logged). # See https://github.com/ray-project/ray/issues/28689. ref1, ref2 = generator.options(num_returns=2).remote() assert ray.get([ref1, ref2]) == [0, 1] """ (generator pid=2375938) 2022-09-28 11:08:51,386 ERR...
140
Actors# Actors extend the Ray API from functions (tasks) to classes. An actor is essentially a stateful worker (or a service). When you instantiate a new actor, Ray creates a new worker and schedules methods of the actor on that specific worker. The methods can access and mutate the state of that worker. Python The ...
141
private int value = 0; public int increment() { this.value += 1; return this.value; } } // Create an actor from this class. // `Ray.actor` takes a factory method that can produce // a `Counter` object. Here, we pass `Counter`'s constructor // as the argument. ActorHandle<Counter> counter = Ray.actor(Count...
142
Use ray list actors from State API to see actors states: # This API is only available when you install Ray with `pip install "ray[default]"`. ray list actors ======== List: 2023-05-25 10:10:50.095099 ======== Stats: ------------------------------ Total: 1 Table: ------------------------------ ACTOR_ID ...
143
Python # Specify required resources for an actor. @ray.remote(num_cpus=2, num_gpus=0.5) class Actor: pass Java // Specify required resources for an actor. Ray.actor(Counter::new).setResource("CPU", 2.0).setResource("GPU", 0.5).remote(); C++ // Specify required resources for an actor. ray::Actor(CreateCoun...
144
C++ // Call the actor. auto object_ref = counter.Task(&Counter::increment).Remote(); assert(*object_ref.Get() == 1); Methods called on different actors execute in parallel, and methods called on the same actor execute serially in the order you call them. Methods on the same actor share state with one another, as sh...
145
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1] [2, 3, 4, 5, 6] Java // Create ten Counter actors. List<ActorHandle<Counter>> counters = new ArrayList<>(); for (int i = 0; i < 10; i++) { counters.add(Ray.actor(Counter::new).remote()); } // Increment each Counter once and get the results. These tasks all happen in // parallel....
146
C++ // Create ten Counter actors. std::vector<ray::ActorHandle<Counter>> counters; for (int i = 0; i < 10; i++) { counters.emplace_back(ray::Actor(CreateCounter).Remote()); } // Increment each Counter once and get the results. These tasks all happen in // parallel. std::vector<ray::ObjectRef<int>> object_refs; for...
147
Passing around actor handles# You can pass actor handles into other tasks. You can also define remote functions or actor methods that use actor handles. Python import time @ray.remote def f(counter): for _ in range(10): time.sleep(0.1) counter.increment.remote() Java public static class MyR...
148
If you instantiate an actor, you can pass the handle around to various tasks. Python counter = Counter.remote() # Start some tasks that use the actor. [f.remote(counter) for _ in range(3)] # Print the counter value. for _ in range(10): time.sleep(0.1) print(ray.get(counter.get_counter.remote())) 0 3 8 10...
149
C++ auto counter = ray::Actor(CreateCounter).Remote(); // Start some tasks that use the actor. for (int i = 0; i < 3; i++) { ray::Task(Foo).Remote(counter); } // Print the counter value. for (int i = 0; i < 10; i++) { std::this_thread::sleep_for(std::chrono::seconds(1)); std::cout << *counter.Task(&Counter::Get...
150
In Ray, Task cancellation behavior is contingent on the Task’s current state: Unscheduled tasks: If Ray hasn’t scheduled an Actor Task yet, Ray attempts to cancel the scheduling. When Ray successfully cancels at this stage, it invokes ray.get(actor_task_ref) which produces a TaskCancelledError. Running actor tasks (reg...
151
Cancellation guarantee: Ray attempts to cancel Tasks on a best-effort basis, meaning cancellation isn’t always guaranteed. For example, if the cancellation request doesn’t get through to the executor, the Task might not be cancelled. You can check if a Task was successfully cancelled using ray.get(actor_task_ref). Recu...
152
Scheduling# For each actor, Ray chooses a node to run it on, and bases the scheduling decision on a few factors like the actor’s resource requirements and the specified scheduling strategy. See Ray scheduling for more details. Fault Tolerance# By default, Ray actors won’t be restarted and actor tasks won’t be retried...
153
Tasks: When Ray starts on a machine, a number of Ray workers start automatically (1 per CPU by default). Ray uses them to execute tasks (like a process pool). If you execute 8 tasks with num_cpus=2, and total number of CPUs is 16 (ray.cluster_resources()["CPU"] == 16), you end up with 8 of your 16 workers idling. Actor...
154
To maximally utilize your resources, you want to maximize the time that your workers work. You also want to allocate enough cluster resources so Ray can run all of your needed actors and any other tasks you define. This also implies that Ray schedules tasks more flexibly, and that if you don’t need the stateful part of...
155
Task Events# By default, Ray traces the execution of actor tasks, reporting task status events and profiling events that Ray Dashboard and State API use. You can disable task event reporting for the actor by setting the enable_task_events option to False in ray.remote() and .options(). This setting reduces the overhead...
156
Named Actors# An actor can be given a unique name within their namespace. This allows you to retrieve the actor from any job in the Ray cluster. This can be useful if you cannot directly pass the actor handle to the task that needs it, or if you are trying to access an actor launched by another driver. Note that the ac...
157
... // Retrieve the actor later somewhere Optional<ActorHandle<Counter>> counter = Ray.getActor("some_name"); Assert.assertTrue(counter.isPresent()); C++ // Create an actor with a globally unique name ActorHandle<Counter> counter = ray::Actor(CreateCounter).SetGlobalName("some_name").Remote(); ... // Retrieve t...
158
... // Retrieve the actor later somewhere in the same job boost::optional<ray::ActorHandle<Counter>> counter = ray::GetActor("some_name"); Note Named actors are scoped by namespace. If no namespace is assigned, they will be placed in an anonymous namespace by default. Python import ray @ray.remote class Acto...
159
# driver_3.py # Job 3 connects to the original "colors" namespace ray.init(address="auto", namespace="colors") # This returns the "orange" actor we created in the first job. ray.get_actor("orange") Java import ray class Actor { } // Driver1.java // Job 1 creates an actor, "orange" in the "colors" namespace. Syst...
160
// Driver3.java System.setProperty("ray.job.namespace", "colors"); Ray.init(); // This returns the "orange" actor we created in the first job. Optional<ActorHandle<Actor>> actor = Ray.getActor("orange"); Assert.assertTrue(actor.isPresent()); // actor.isPresent() is true. Get-Or-Create a Named Actor# A common use ...
161
Python import ray @ray.remote class Greeter: def __init__(self, value): self.value = value def say_hello(self): return self.value # Actor `g1` doesn't yet exist, so it is created with the given args. a = Greeter.options(name="g1", get_if_exists=True).remote("Old Greeting") assert ray.get(a....
162
Python counter = Counter.options(name="CounterActor", lifetime="detached").remote() The CounterActor will be kept alive even after the driver running above script exits. Therefore it is possible to run the following script in a different driver: counter = ray.get_actor("CounterActor") Note that an actor can be name...
163
Java System.setProperty("ray.job.namespace", "lifetime"); Ray.init(); ActorHandle<Counter> counter = Ray.actor(Counter::new).setName("some_name").setLifetime(ActorLifetime.DETACHED).remote(); The CounterActor will be kept alive even after the driver running above process exits. Therefore it is possible to run the fol...
164
Terminating Actors# Actor processes will be terminated automatically when all copies of the actor handle have gone out of scope in Python, or if the original creator process dies. Note that automatic termination of actors is not yet supported in Java or C++. Manual termination via an actor handle# In most cases, Ray w...
165
ray.kill(actor_handle) # This will not go through the normal Python sys.exit # teardown logic, so any exit handlers installed in # the actor using ``atexit`` will not be called. Java actorHandle.kill(); // This will not go through the normal Java System.exit teardown logic, so any // shutdown hooks installed in th...
166
C++ actor_handle.Kill(); // This will not go through the normal C++ std::exit // teardown logic, so any exit handlers installed in // the actor using ``std::atexit`` will not be called. This will cause the actor to immediately exit its process, causing any current, pending, and future tasks to fail with a RayActorE...
167
--- - actor_id: e8702085880657b355bf7ef001000000 class_name: Actor state: DEAD job_id: '01000000' name: '' node_id: null pid: 0 ray_namespace: dbab546b-7ce5-4cbb-96f1-d0f64588ae60 serialized_runtime_env: '{}' required_resources: {} death_cause: actor_died_error_context:...
168
Manual termination within the actor# If necessary, you can manually terminate an actor from within one of the actor methods. This will kill the actor process and release resources associated/assigned to the actor. Python @ray.remote class Actor: def exit(self): ray.actor.exit_actor() actor = Actor.remot...
169
C++ ray::ExitActor(); Garbage collection for actors haven’t been implemented yet, so this is currently the only way to terminate an actor gracefully. The ObjectRef resulting from the task can be waited on to wait for the actor to exit (calling ObjectRef::Get on it will throw a RayActorException). Note that this met...
170
--- - actor_id: 070eb5f0c9194b851bb1cf1602000000 class_name: Actor state: DEAD job_id: '02000000' name: '' node_id: 47ccba54e3ea71bac244c015d680e202f187fbbd2f60066174a11ced pid: 47978 ray_namespace: 18898403-dda0-485a-9c11-e9f94dffcbed serialized_runtime_env: '{}' required_resource...
171
AsyncIO / Concurrency for Actors# Within a single actor process, it is possible to execute concurrent threads. Ray offers two types of concurrency within an actor: async execution threading Keep in mind that the Python’s Global Interpreter Lock (GIL) will only allow one thread of Python code running at once. This m...
172
@ray.remote class AsyncActor: # multiple invocation of this method can be running in # the event loop at the same time async def run_concurrent(self): print("started") await asyncio.sleep(2) # concurrent workload here print("finished") actor = AsyncActor.remote() # regular ray.get ...
173
@ray.remote def some_task(): return 1 ray.get(some_task.remote()) ray.wait([some_task.remote()]) you can do: import ray import asyncio @ray.remote def some_task(): return 1 async def await_obj_ref(): await some_task.remote() await asyncio.wait([some_task.remote()]) asyncio.run(await_obj_ref()) P...
174
refs = [some_task.remote() for _ in range(4)] futs = [ref.future() for ref in refs] for fut in concurrent.futures.as_completed(futs): assert fut.done() print(fut.result()) 1 1 1 1 Defining an Async Actor# By using async method definitions, Ray will automatically detect whether an actor support async calls...
175
Under the hood, Ray runs all of the methods inside a single python event loop. Please note that running blocking ray.get or ray.wait inside async actor method is not allowed, because ray.get will block the execution of the event loop. In async actors, only one task can be running at any point in time (though tasks can ...
176
actor = AsyncActor.options(max_concurrency=2).remote() # Only 2 tasks will be running concurrently. Once 2 finish, the next 2 should run. ray.get([actor.run_task.remote() for _ in range(8)]) (AsyncActor pid=5859) started (AsyncActor pid=5859) started (AsyncActor pid=5859) ended (AsyncActor pid=5859) ended (AsyncActo...
177
Threaded Actors# Sometimes, asyncio is not an ideal solution for your actor. For example, you may have one method that performs some computation heavy task while blocking the event loop, not giving up control via await. This would hurt the performance of an Async Actor because Async Actors can only execute 1 task at a ...
178
a = ThreadedActor.options(max_concurrency=2).remote() ray.get([a.task_1.remote(), a.task_2.remote()]) (ThreadedActor pid=4822) I'm running in a thread! (ThreadedActor pid=4822) I'm running in another thread! Each invocation of the threaded actor will be running in a thread pool. The size of the threadpool is limite...
179
Limiting Concurrency Per-Method with Concurrency Groups# Besides setting the max concurrency overall for an actor, Ray allows methods to be separated into concurrency groups, each with its own threads(s). This allows you to limit the concurrency per-method, e.g., allow a health-check method to be given its own concurre...
180
Python You can define concurrency groups for actors using the concurrency_group decorator argument: import ray @ray.remote(concurrency_groups={"io": 2, "compute": 4}) class AsyncIOActor: def __init__(self): pass @ray.method(concurrency_group="io") async def f1(self): pass @ray.method(...
181
Java You can define concurrency groups for concurrent actors using the API setConcurrencyGroups() argument: class ConcurrentActor { public long f1() { return Thread.currentThread().getId(); } public long f2() { return Thread.currentThread().getId(); } public long f3(int a, int b) {...
182
ActorHandle<ConcurrentActor> myActor = Ray.actor(ConcurrentActor::new) .setConcurrencyGroups(group1, group2) .remote(); myActor.task(ConcurrentActor::f1).remote(); // executed in the "io" group. myActor.task(ConcurrentActor::f2).remote(); // executed in the "io" group. myActor.task(ConcurrentActor::f3, 3, 5)...
183
Python The following actor has 2 concurrency groups: “io” and “default”. The max concurrency of “io” is 2, and the max concurrency of “default” is 10. @ray.remote(concurrency_groups={"io": 2}) class AsyncIOActor: async def f1(self): pass actor = AsyncIOActor.options(max_concurrency=10).remote() Java T...
184
ActorHandle<ConcurrentActor> myActor = Ray.actor(ConcurrentActor::new) .setConcurrencyGroups(group1) .setMaxConcurrency(10) .remote(); Setting the Concurrency Group at Runtime# You can also dispatch actor methods into a specific concurrency group at runtime. The following snippet demonstrates se...
185
Utility Classes# Actor Pool# Python The ray.util module contains a utility class, ActorPool. This class is similar to multiprocessing.Pool and lets you schedule Ray tasks over a fixed pool of actors. import ray from ray.util import ActorPool @ray.remote class Actor: def double(self, n): return n * 2 ...
186
ray.init() # You can pass this object around to different tasks/actors queue = Queue(maxsize=100) @ray.remote def consumer(id, queue): try: while True: next_item = queue.get(block=True, timeout=1) print(f"consumer {id} got work {next_item}") except Empty: pass [queue....
187
Out-of-band Communication# Typically, Ray actor communication is done through actor method calls and data is shared through the distributed object store. However, in some use cases out-of-band communication can be useful. Wrapping Library Processes# Many libraries already have mature, high-performance internal communi...
188
HTTP Server# You can start a http server inside the actor and expose http endpoints to clients so users outside of the ray cluster can communicate with the actor. Python import ray import asyncio import requests from aiohttp import web @ray.remote class Counter: async def __init__(self): self.counter =...
189
ray.init() counter = Counter.remote() [ray.get(counter.increment.remote()) for i in range(5)] r = requests.get("http://127.0.0.1:25001/") assert r.text == "5" Similarly, you can expose other types of servers as well (e.g., gRPC servers). Limitations# When using out-of-band communication with Ray actors, keep in m...
190
Actor Task Execution Order# Synchronous, Single-Threaded Actor# In Ray, an actor receives tasks from multiple submitters (including driver and workers). For tasks received from the same submitter, a synchronous, single-threaded actor executes them in the order they were submitted, if the actor tasks never retry. In ot...
191
counter = Counter.remote() # For tasks from the same submitter, # they are executed according to submission order. value0 = counter.add.remote(1) value1 = counter.add.remote(2) # Output: 1. The first submitted task is executed first. print(ray.get(value0)) # Output: 3. The later submitted task is executed later. prin...
192
counter = Counter.remote() # Submit task from a worker @ray.remote def submitter(value): return ray.get(counter.add.remote(value)) # Simulate delayed result resolution. @ray.remote def delayed_resolution(value): time.sleep(5) return value # Submit tasks from different workers, with # the first submitted ...
193
Python import time import ray @ray.remote class AsyncCounter: def __init__(self): self.value = 0 async def add(self, addition): self.value += addition return self.value counter = AsyncCounter.remote() # Simulate delayed result resolution. @ray.remote def delayed_resolution(value): ...
194
Objects# In Ray, tasks and actors create and compute on objects. We refer to these objects as remote objects because they can be stored anywhere in a Ray cluster, and we use object refs to refer to them. Remote objects are cached in Ray’s distributed shared-memory object store, and there is one object store per node in...
195
Python import ray # Put an object in Ray's object store. y = 1 object_ref = ray.put(y) Java // Put an object in Ray's object store. int y = 1; ObjectRef<Integer> objectRef = Ray.put(y); C++ // Put an object in Ray's object store. int y = 1; ray::ObjectRef<int> object_ref = ray::Put(y); Note Remote objec...
196
# Get the value of one object ref. obj_ref = ray.put(1) assert ray.get(obj_ref) == 1 # Get the values of multiple object refs in parallel. assert ray.get([ray.put(i) for i in range(3)]) == [0, 1, 2] # You can also set a timeout to return early from a ``get`` # that's blocking for too long. from ray.exceptions import ...
197
// Get the values of multiple object refs in parallel. List<ObjectRef<Integer>> objectRefs = new ArrayList<>(); for (int i = 0; i < 3; i++) { objectRefs.add(Ray.put(i)); } List<Integer> results = Ray.get(objectRefs); Assert.assertEquals(results, ImmutableList.of(0, 1, 2)); // Ray.get timeout example: Ray.get will th...
198
C++ // Get the value of one object ref. ray::ObjectRef<int> obj_ref = ray::Put(1); assert(*obj_ref.Get() == 1); // Get the values of multiple object refs in parallel. std::vector<ray::ObjectRef<int>> obj_refs; for (int i = 0; i < 3; i++) { obj_refs.emplace_back(ray::Put(i)); } auto results = ray::Get(obj_refs); asse...
199
Passing Object Arguments# Ray object references can be freely passed around a Ray application. This means that they can be passed as arguments to tasks, actor methods, and even stored in other objects. Objects are tracked via distributed reference counting, and their data is automatically freed once all references to t...