global_chunk_id
int64
0
478
text
stringlengths
288
999
300
Specifying Node Resources# By default, Ray nodes start with pre-defined CPU, GPU, and memory resources. The quantities of these logical resources on each node are set to the physical quantities auto detected by Ray. By default, logical resources are configured by the following rule. Warning Ray does not permit dynamic...
301
However, you can always override that by manually specifying the quantities of pre-defined resources and adding custom resources. There are several ways to do that depending on how you start the Ray cluster: ray.init() If you are using ray.init() to start a single node Ray cluster, you can do the following to manual...
302
Specifying Task or Actor Resource Requirements# Ray allows specifying a task or actor’s logical resource requirements (e.g., CPU, GPU, and custom resources). The task or actor will only run on a node if there are enough required logical resources available to execute the task or actor. By default, Ray tasks use 1 logic...
303
Python # Specify the default resource requirements for this remote function. @ray.remote(num_cpus=2, num_gpus=2, resources={"special_hardware": 1}) def func(): return 1 # You can override the default resource requirements. func.options(num_cpus=3, num_gpus=1, resources={"special_hardware": 0}).remote() @ray.rem...
304
ray::Actor(CreateCounter).SetResource("CPU", 2.0).SetResource("GPU", 1.0).Remote(); Task and actor resource requirements have implications for the Ray’s scheduling concurrency. In particular, the sum of the logical resource requirements of all of the concurrently executing tasks and actors on a given node cannot ex...
305
time.sleep(1) return 2 io_bound_task.remote() @ray.remote(num_gpus=0.5) class IOActor: def ping(self): import os print(f"CUDA_VISIBLE_DEVICES: {os.environ['CUDA_VISIBLE_DEVICES']}") # Two actors can share the same GPU. io_actor1 = IOActor.remote() io_actor2 = IOActor.remote() ray.get(io_a...
306
Accelerator Support# Accelerators like GPUs are critical for many machine learning apps. Ray Core natively supports many accelerators as pre-defined resource types and allows tasks and actors to specify their accelerator resource requirements. The accelerators natively supported by Ray Core are: Accelerator Ray Resou...
307
Nvidia GPU Tip You can set the CUDA_VISIBLE_DEVICES environment variable before starting a Ray node to limit the Nvidia GPUs that are visible to Ray. For example, CUDA_VISIBLE_DEVICES=1,3 ray start --head --num-gpus=2 lets Ray only see devices 1 and 3. AMD GPU Tip You can set the ROCR_VISIBLE_DEVICES environment ...
308
AWS Neuron Core Tip You can set the NEURON_RT_VISIBLE_CORES environment variable before starting a Ray node to limit the AWS Neuro Cores that are visible to Ray. For example, NEURON_RT_VISIBLE_CORES=1,3 ray start --head --resources='{"neuron_cores": 2}' lets Ray only see devices 1 and 3. See the Amazon documentation<h...
309
Intel Gaudi Tip You can set the HABANA_VISIBLE_MODULES environment variable before starting a Ray node to limit the Intel Gaudi HPUs that are visible to Ray. For example, HABANA_VISIBLE_MODULES=1,3 ray start --head --resources='{"HPU": 2}' lets Ray only see devices 1 and 3. Huawei Ascend Tip You can set the ASCEN...
310
Note There’s nothing preventing you from specifying a larger number of accelerator resources (e.g., num_gpus) than the true number of accelerators on the machine given Ray resources are logical. In this case, Ray acts as if the machine has the number of accelerators you specified for the purposes of scheduling tasks an...
311
Nvidia GPU import os import ray ray.init(num_gpus=2) @ray.remote(num_gpus=1) class GPUActor: def ping(self): print("GPU IDs: {}".format(ray.get_runtime_context().get_accelerator_ids()["GPU"])) print("CUDA_VISIBLE_DEVICES: {}".format(os.environ["CUDA_VISIBLE_DEVICES"])) @ray.remote(num_gpus=1) def...
312
AMD GPU import os import ray ray.init(num_gpus=2) @ray.remote(num_gpus=1) class GPUActor: def ping(self): print("GPU IDs: {}".format(ray.get_runtime_context().get_accelerator_ids()["GPU"])) print("ROCR_VISIBLE_DEVICES: {}".format(os.environ["ROCR_VISIBLE_DEVICES"])) @ray.remote(num_gpus=1) def gp...
313
Intel GPU import os import ray ray.init(num_gpus=2) @ray.remote(num_gpus=1) class GPUActor: def ping(self): print("GPU IDs: {}".format(ray.get_runtime_context().get_accelerator_ids()["GPU"])) print("ONEAPI_DEVICE_SELECTOR: {}".format(os.environ["ONEAPI_DEVICE_SELECTOR"])) @ray.remote(num_gpus=1) ...
314
AWS Neuron Core import os import ray ray.init(resources={"neuron_cores": 2}) @ray.remote(resources={"neuron_cores": 1}) class NeuronCoreActor: def ping(self): print("Neuron Core IDs: {}".format(ray.get_runtime_context().get_accelerator_ids()["neuron_cores"])) print("NEURON_RT_VISIBLE_CORES: {}".fo...
315
neuron_core_actor = NeuronCoreActor.remote() ray.get(neuron_core_actor.ping.remote()) # The actor uses the first Neuron Core so the task uses the second one. ray.get(neuron_core_task.remote()) (NeuronCoreActor pid=52420) Neuron Core IDs: [0] (NeuronCoreActor pid=52420) NEURON_RT_VISIBLE_CORES: 0 (neuron_core_task pid...
316
tpu_actor = TPUActor.remote() ray.get(tpu_actor.ping.remote()) # The actor uses the first TPU so the task uses the second one. ray.get(tpu_task.remote()) (TPUActor pid=52420) TPU IDs: [0] (TPUActor pid=52420) TPU_VISIBLE_CHIPS: 0 (tpu_task pid=51830) TPU IDs: [1] (tpu_task pid=51830) TPU_VISIBLE_CHIPS: 1 Intel G...
317
hpu_actor = HPUActor.remote() ray.get(hpu_actor.ping.remote()) # The actor uses the first HPU so the task uses the second one. ray.get(hpu_task.remote()) (HPUActor pid=52420) HPU IDs: [0] (HPUActor pid=52420) HABANA_VISIBLE_MODULES: 0 (hpu_task pid=51830) HPU IDs: [1] (hpu_task pid=51830) HABANA_VISIBLE_MODULES: 1 ...
318
Inside a task or actor, ray.get_runtime_context().get_accelerator_ids() returns a list of accelerator IDs that are available to the task or actor. Typically, it is not necessary to call get_accelerator_ids() because Ray automatically sets the corresponding environment variable (e.g. CUDA_VISIBLE_DEVICES), which most ML...
319
# Create a TensorFlow session. TensorFlow restricts itself to use the # GPUs specified by the CUDA_VISIBLE_DEVICES environment variable. tf.Session() Note: It is certainly possible for the person to ignore assigned accelerators and to use all of the accelerators on the machine. Ray does not prevent this from ...
320
Nvidia GPU ray.init(num_cpus=4, num_gpus=1) @ray.remote(num_gpus=0.25) def f(): import time time.sleep(1) # The four tasks created here can execute concurrently # and share the same GPU. ray.get([f.remote() for _ in range(4)]) AMD GPU ray.init(num_cpus=4, num_gpus=1) @ray.remote(num_gpus=0.25) def f():...
321
Google TPU Google TPU doesn’t support fractional resource. Intel Gaudi Intel Gaudi doesn’t support fractional resource. Huawei Ascend ray.init(num_cpus=4, resources={"NPU": 1}) @ray.remote(resources={"NPU": 0.25}) def f(): import time time.sleep(1) # The four tasks created here can execute concurrently...
322
(FractionalGPUActor pid=57417) GPU id: [0] (FractionalGPUActor pid=57416) GPU id: [0] (FractionalGPUActor pid=57418) GPU id: [1] Workers not Releasing GPU Resources# Currently, when a worker executes a task that uses a GPU (e.g., through TensorFlow), the task may allocate memory on the GPU and may not release it wh...
323
# This task allocates memory on the GPU and then never release it. tf.Session() Accelerator Types# Ray supports resource specific accelerator types. The accelerator_type option can be used to force to a task or actor to run on a node with a specific type of accelerator. Under the hood, the accelerator type opti...
324
Placement Groups# Placement groups allow users to atomically reserve groups of resources across multiple nodes (i.e., gang scheduling). They can then be used to schedule Ray tasks and actors packed together for locality (PACK), or spread apart (SPREAD). Placement groups are generally used for gang-scheduling actors, bu...
325
Distributed Machine Learning Training: Distributed Training (e.g., Ray Train and Ray Tune) uses the placement group APIs to enable gang scheduling. In these settings, all resources for a trial must be available at the same time. Gang scheduling is a critical technique to enable all-or-nothing scheduling for deep learni...
326
Key Concepts# Bundles# A bundle is a collection of “resources”. It could be a single resource, {"CPU": 1}, or a group of resources, {"CPU": 1, "GPU": 4}. A bundle is a unit of reservation for placement groups. “Scheduling a bundle” means we find a node that fits the bundle and reserve the resources specified by the bu...
327
Placement Group# A placement group reserves the resources from the cluster. The reserved resources can only be used by tasks or actors that use the PlacementGroupSchedulingStrategy. Placement groups are represented by a list of bundles. For example, {"CPU": 1} * 4 means you’d like to reserve 4 bundles of 1 CPU (i.e., ...
328
Create a Placement Group (Reserve Resources)# You can create a placement group using ray.util.placement_group(). Placement groups take in a list of bundles and a placement strategy. Note that each bundle must be able to fit on a single node on the Ray cluster. For example, if you only have a 8 CPU node, and if you have...
329
Placement group scheduling is asynchronous. The ray.util.placement_group returns immediately. Python from pprint import pprint import time # Import placement group APIs. from ray.util.placement_group import ( placement_group, placement_group_table, remove_placement_group, ) from ray.util.scheduling_stra...
330
Java // Initialize Ray. Ray.init(); // Construct a list of bundles. Map<String, Double> bundle = ImmutableMap.of("CPU", 1.0); List<Map<String, Double>> bundles = ImmutableList.of(bundle); // Make a creation option with bundles and strategy. PlacementGroupCreationOptions options = new PlacementGroupCreationOptions.B...
331
ray::PlacementGroup pg = ray::CreatePlacementGroup(options); You can block your program until the placement group is ready using one of two APIs: ready, which is compatible with ray.get wait, which blocks the program until the placement group is ready) Python # Wait until placement group is created. ray.get(pg...
332
C++ // Wait for the placement group to be ready within the specified time(unit is seconds). bool ready = pg.Wait(60); assert(ready); // You can look at placement group states using this API. std::vector<ray::PlacementGroup> all_placement_group = ray::GetAllPlacementGroups(); for (const ray::PlacementGroup &group : all...
333
Table: ------------------------------ PLACEMENT_GROUP_ID NAME CREATOR_JOB_ID STATE 0 3cd6174711f47c14132155039c0501000000 01000000 CREATED The placement group is successfully created. Out of the {"CPU": 2, "GPU": 2} resources, the placement group reserves {"CPU": 1, "GP...
334
Python # Cannot create this placement group because we # cannot create a {"GPU": 2} bundle. pending_pg = placement_group([{"CPU": 1}, {"GPU": 2}]) # This raises the timeout exception! try: ray.get(pending_pg.ready(), timeout=5) except Exception as e: print( "Cannot create a placement group because " ...
335
You can also verify that the {"CPU": 1, "GPU": 2} bundles cannot be allocated, using the ray status CLI command. ray status Resources --------------------------------------------------------------- Usage: 0.0/2.0 CPU (0.0 used of 1.0 reserved in placement groups) 0.0/2.0 GPU (0.0 used of 1.0 reserved in placement gro...
336
When the placement group cannot be scheduled in any way, it is called “infeasible”. Imagine you schedule {"CPU": 4} bundle, but you only have a single node with 2 CPUs. There’s no way to create this bundle in your cluster. The Ray Autoscaler is aware of placement groups, and auto-scales the cluster to ensure pending gr...
337
Python @ray.remote(num_cpus=1) class Actor: def __init__(self): pass def ready(self): pass # Create an actor to a placement group. actor = Actor.options( scheduling_strategy=PlacementGroupSchedulingStrategy( placement_group=pg, ) ).remote() # Verify the actor is scheduled. ra...
338
C++ class Counter { public: Counter(int init_value) : value(init_value){} int GetValue() {return value;} std::string Ping() { return "pong"; } private: int value; }; // Factory function of Counter class. static Counter *CreateCounter() { return new Counter(); }; RAY_REMOTE(&Counter::Ping, &Counter::Ge...
339
// Create GPU actors on a gpu bundle. for (int index = 0; index < 1; index++) { ray::Actor(CreateCounter) .SetPlacementGroup(pg, 0) .Remote(1); } Note By default, Ray actors require 1 logical CPU at schedule time, but after being scheduled, they do not acquire any CPU resources. In other words, by defaul...
340
The actor is scheduled now! One bundle can be used by multiple tasks and actors (i.e., the bundle to task (or actor) is a one-to-many relationship). In this case, since the actor uses 1 CPU, 1 GPU remains from the bundle. You can verify this from the CLI command ray status. You can see the 1 CPU is reserved by the plac...
341
You can also verify the actor is created using ray list actors. # This API is only available when you download Ray via `pip install "ray[default]"` ray list actors --detail - actor_id: b5c990f135a7b32bfbb05e1701000000 class_name: Actor death_cause: null is_detached: false job_id: '01000000' name...
342
Since 1 GPU remains, let’s create a new actor that requires 1 GPU. This time, we also specify the placement_group_bundle_index. Each bundle is given an “index” within the placement group. For example, a placement group of 2 bundles [{"CPU": 1}, {"GPU": 1}] has index 0 bundle {"CPU": 1} and index 1 bundle {"GPU": 1}. Si...
343
# Verify that the GPU actor is scheduled. ray.get(actor2.ready.remote(), timeout=10) We succeed to schedule the GPU actor! The below image describes 2 actors scheduled into the placement group. You can also verify that the reserved resources are all used, with the ray status command. ray status Resources -------...
344
Placement Strategy# One of the features the placement group provides is to add placement constraints among bundles. For example, you’d like to pack your bundles to the same node or spread out to multiple nodes as much as possible. You can specify the strategy via strategy argument. This way, you can make sure your acto...
345
The image below demonstrates the PACK policy. Three of the {"CPU": 2} bundles are located in the same node. The image below demonstrates the SPREAD policy. Each of three of the {"CPU": 2} bundles are located in three different nodes. Ray supports four placement group strategies. The default scheduling policy is PACK....
346
Remove Placement Groups (Free Reserved Resources)# By default, a placement group’s lifetime is scoped to the driver that creates placement groups (unless you make it a detached placement group). When the placement group is created from a detached actor, the lifetime is scoped to the detached actor. In Ray, the driver i...
347
Python # This API is asynchronous. remove_placement_group(pg) # Wait until placement group is killed. time.sleep(1) # Check that the placement group has died. pprint(placement_group_table(pg)) """ {'bundles': {0: {'GPU': 1.0}, 1: {'CPU': 1.0}}, 'name': 'unnamed_group', 'placement_group_id': '40816b6ad474a6942b0edb458...
348
ray::PlacementGroup removed_placement_group = ray::GetPlacementGroup(placement_group.GetID()); assert(removed_placement_group.GetState(), ray::PlacementGroupState::REMOVED); Observe and Debug Placement Groups# Ray provides several useful tools to inspect the placement group states and resource usage. Ray Status ...
349
ray status (CLI) The CLI command ray status provides the autoscaling status of the cluster. It provides the “resource demands” from unscheduled placement groups as well as the resource reservation status. Resources --------------------------------------------------------------- Usage: 1.0/2.0 CPU (1.0 used of 1.0 reser...
350
Note Ray dashboard is only available when you install Ray is with pip install "ray[default]". Ray State API Ray state API is a CLI tool for inspecting the state of Ray resources (tasks, actors, placement groups, etc.). ray list placement-groups provides the metadata and the scheduling state of the placement group. ...
351
Python import ray from ray.util.placement_group import placement_group from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy ray.init(num_cpus=2) # Create a placement group. pg = placement_group([{"CPU": 2}]) ray.get(pg.ready()) @ray.remote(num_cpus=1) def child(): import time time.sl...
352
Java It’s not implemented for Java APIs yet. When placement_group_capture_child_tasks is True, but you don’t want to schedule child tasks and actors to the same placement group, specify PlacementGroupSchedulingStrategy(placement_group=None). @ray.remote def parent(): # In this case, the child task isn't # sch...
353
# This times out because we cannot schedule the child task. # The cluster has {"CPU": 2}, and both of them are reserved by # the placement group with a bundle {"CPU": 2}. Since the child shouldn't # be scheduled within this placement group, it cannot be scheduled because # there's no available CPU resources. try: r...
354
[Advanced] Named Placement Group# Within a namespace, you can name a placement group. You can use the name of a placement group to retrieve the placement group from any job in the Ray cluster, as long as the job is within the same namespace. This is useful if you can’t directly pass the placement group handle to the ac...
355
# second_driver.py # Retrieve a placement group with a unique name within a namespace. # Start Ray or connect to a Ray cluster using: ray.init(namespace="pg_namespace") pg = ray.util.get_placement_group("pg_name") Java // Create a placement group with a unique name. Map<String, Double> bundle = ImmutableMap.of("CP...
356
C++ // Create a placement group with a globally unique name. std::vector<std::unordered_map<std::string, double>> bundles{{{"CPU", 1.0}}}; ray::PlacementGroupCreationOptions options{ true/*global*/, "global_name", bundles, ray::PlacementStrategy::STRICT_SPREAD}; ray::PlacementGroup pg = ray::CreatePlacementGroup(...
357
ray::PlacementGroupCreationOptions options{ false/*non-global*/, "non_global_name", bundles, ray::PlacementStrategy::STRICT_SPREAD}; ray::PlacementGroup pg = ray::CreatePlacementGroup(options); pg.Wait(60); ... // Retrieve the placement group later somewhere in the same job. ray::PlacementGroup group = ray::GetP...
358
To keep the placement group alive regardless of its job or detached actor, specify lifetime="detached". For example: Python # driver_1.py # Create a detached placement group that survives even after # the job terminates. pg = placement_group([{"CPU": 1}], lifetime="detached", name="global_name") ray.get(pg.ready()) ...
359
[Advanced] Fault Tolerance# Rescheduling Bundles on a Dead Node# If nodes that contain some bundles of a placement group die, all the bundles are rescheduled on different nodes by GCS (i.e., we try reserving resources again). This means that the initial creation of placement group is “atomic”, but once it is created, ...
360
Fault tolerance# Ray is a distributed system, and that means failures can happen. Generally, Ray classifies failures into two classes: 1. application-level failures 2. system-level failures Bugs in user-level code or external system failures trigger application-level failures. Node failures, network failures, or just b...
361
How to write fault tolerant Ray applications# There are several recommendations to make Ray applications fault tolerant: First, if the fault tolerance mechanisms provided by Ray don’t work for you, you can always catch exceptions caused by failures and recover manually. @ray.remote class Actor: def read_only(self):...
362
Second, avoid letting an ObjectRef outlive its owner task or actor (the task or actor that creates the initial ObjectRef by calling ray.put() or foo.remote()). As long as there are still references to an object, the owner worker of the object keeps running even after the corresponding task or actor finishes. If the own...
363
In the preceding example, object x outlives its owner task a. If the worker process running task a fails, calling ray.get on x_ref afterwards results in an OwnerDiedError exception. The following example is a fault tolerant version which returns x directly. In this example, the driver owns x and you only access it with...
364
# The owner of x is the driver # so x is accessible and can be auto recovered # during the entire lifetime of the driver. x_ref = a.remote() print(ray.get(x_ref)) Third, avoid using custom resource requirements that only particular nodes can satisfy. If that particular node fails, Ray won’t retry the running tasks or...
365
# If the node with ip 127.0.0.3 fails while task b is running, # Ray cannot retry the task on other nodes. b.options(resources={"node:127.0.0.3": 1}).remote() If you prefer running a task on a particular node, you can use the NodeAffinitySchedulingStrategy. It allows you to specify the affinity as a soft constraint s...
366
Memory Management# This page describes how memory management works in Ray. Also view Debugging Out of Memory to learn how to troubleshoot out-of-memory issues. Concepts# There are several ways that Ray applications use memory: Ray system memory: this is memory used internally by Ray GCS: memory used for storing the l...
367
Application memory: this is memory used by your application Worker heap: memory used by your application (e.g., in Python code or TensorFlow), best measured as the resident set size (RSS) of your application minus its shared memory usage (SHR) in commands such as top. The reason you need to subtract SHR is that object ...
368
Object store memory: memory used when your application creates objects in the object store via ray.put and when it returns values from remote functions. Objects are reference counted and evicted when they fall out of scope. An object store server runs on each node. By default, when starting an instance, Ray reserves 30...
369
ObjectRef Reference Counting# Ray implements distributed reference counting so that any ObjectRef in scope in the cluster is pinned in the object store. This includes local python references, arguments to pending tasks, and IDs serialized inside of other objects. Debugging using ‘ray memory’# The ray memory command ...
370
--- Summary for node address: 192.168.0.15 --- Mem Used by Objects Local References Pinned Count Pending Tasks Captured in Objects Actor Handles 287 MiB 4 0 0 1 0 --- Object references for node address: 192.168.0.15 --- IP Address PID ...
371
--- Aggregate object store stats across all nodes --- Plasma memory usage 0 MiB, 4 objects, 0.0% full Each entry in this output corresponds to an ObjectRef that’s currently pinning an object in the object store along with where the reference is (in the driver, in a worker, etc.), what type of reference it is (see bel...
372
@ray.remote def f(arg): return arg a = ray.put(None) b = f.remote(None) In this example, we create references to two objects: one that is ray.put() in the object store and another that’s the return value from f.remote(). --- Summary for node address: 192.168.0.15 --- Mem Used by Objects Local References Pinned...
373
In the output from ray memory, we can see that each of these is marked as a LOCAL_REFERENCE in the driver process, but the annotation in the “Reference Creation Site” indicates that the first was created as a “put object” and the second from a “task call.” 2. Objects pinned in memory import numpy as np a = ray.put(np....
374
--- Object references for node address: 192.168.0.15 --- IP Address PID Type Object Ref Size Reference Type Call Site 192.168.0.15 7066 Driver ffffffffffffffffffffffffffffffffffffffff0100000001000000 243 MiB PINNED_IN_MEMORY test. ...
375
a = ray.put(None) b = f.remote(a) In this example, we first create an object via ray.put() and then submit a task that depends on the object. --- Summary for node address: 192.168.0.15 --- Mem Used by Objects Local References Pinned Count Pending Tasks Captured in Objects Actor Handles 25 MiB 1 ...
376
While the task is running, we see that ray memory shows both a LOCAL_REFERENCE and a USED_BY_PENDING_TASK reference for the object in the driver process. The worker process also holds a reference to the object because the Python arg is directly referencing the memory in the plasma, so it can’t be evicted; therefore it ...
377
192.168.0.15 7373 Driver ffffffffffffffffffffffffffffffffffffffff0100000001000000 15 MiB USED_BY_PENDING_TASK (put object) | test.py: ...
378
In this example, we first create an object via ray.put(), then capture its ObjectRef inside of another ray.put() object, and delete the first ObjectRef. In this case, both objects are still pinned. --- Summary for node address: 192.168.0.15 --- Mem Used by Objects Local References Pinned Count Pending Tasks Capture...
379
In the output of ray memory, we see that the second object displays as a normal LOCAL_REFERENCE, but the first object is listed as CAPTURED_IN_OBJECT. Memory Aware Scheduling# By default, Ray does not take into account the potential memory usage of a task or actor when scheduling. This is simply because it cannot est...
380
To tell the Ray scheduler a task or actor requires a certain amount of available memory to run, set the memory argument. The Ray scheduler will then reserve the specified amount of available memory during scheduling, similar to how it handles CPU and GPU resources: # reserve 500MiB of available memory to place this tas...
381
# override the memory quota to 1GiB when creating the actor SomeActor.options(memory=1000 * 1024 * 1024).remote(a=1, b=2) Questions or Issues?# You can post questions or issues or feedback through the following channels: Discussion Board: For questions about Ray usage or feature requests. GitHub Issues: For bug rep...
382
Out-Of-Memory Prevention# If application tasks or actors consume a large amount of heap space, it can cause the node to run out of memory (OOM). When that happens, the operating system will start killing worker or raylet processes, disrupting the application. OOM may also stall metrics and if this happens on the head n...
383
Also view Debugging Out of Memory to learn how to troubleshoot out-of-memory issues. What is the memory monitor?# The memory monitor is a component that runs within the raylet process on each node. It periodically checks the memory usage, which includes the worker heap, the object store, and the raylet as described in...
384
How do I configure the memory monitor?# The memory monitor is controlled by the following environment variables: RAY_memory_monitor_refresh_ms (int, defaults to 250) is the interval to check memory usage and kill tasks or actors if needed. Task killing is disabled when this value is 0. The memory monitor selects and k...
385
Using the Memory Monitor# Retry policy# When a task or actor is killed by the memory monitor it will be retried with exponential backoff. There is a cap on the retry delay, which is 60 seconds. If tasks are killed by the memory monitor, it retries infinitely (not respecting max_retries). If actors are killed by the me...
386
Worker killing policy# The memory monitor avoids infinite loops of task retries by ensuring at least one task is able to run for each caller on each node. If it is unable to ensure this, the workload will fail with an OOM error. Note that this is only an issue for tasks, since the memory monitor will not indefinitely r...
387
When there are multiple callers that has created tasks, the policy will pick a task from the caller with the most number of running tasks. If two callers have the same number of tasks it picks the caller whose earliest task has a later start time. This is done to ensure fairness and allow each caller to make progress. ...
388
If, at this point, the node runs out of memory, it will pick a task from the caller with the most number of tasks, and kill its task whose started the last: If, at this point, the node still runs out of memory, the process will repeat: Example: Workloads fails if the last task of the caller is killed Let’s crea...
389
@ray.remote(max_retries=-1) def leaks_memory(): chunks = [] bits_to_allocate = 8 * 100 * 1024 * 1024 # ~100 MiB while True: chunks.append([0] * bits_to_allocate) try: ray.get(leaks_memory.remote()) except ray.exceptions.OutOfMemoryError as ex: print("task failed with OutOfMemoryError, whi...
390
(raylet) node_manager.cc:3040: 1 Workers (tasks / actors) killed due to memory pressure (OOM), 0 Workers crashed due to other reasons at node (ID: 2c82620270df6b9dd7ae2791ef51ee4b5a9d5df9f795986c10dd219c, IP: 172.31.183.172) over the last time period. To see more information about the Workers killed on this node, use `...
391
Example: memory monitor prefers to kill a retriable task Let’s first start ray and specify the memory threshold. RAY_memory_usage_threshold=0.4 ray start --head Let’s create an application two_actors.py that submits two actors, where the first one is retriable and the second one is non-retriable. from math import...
392
# estimates the number of bytes to allocate to reach the desired memory usage percentage. def get_additional_bytes_to_reach_memory_usage_pct(pct: float) -> int: used = get_used_memory() total = get_system_memory() bytes_needed = int(total * pct) - used assert ( bytes_needed > 0 ), "memory us...
393
# each task requests 0.3 of the system memory when the memory threshold is 0.4. allocate_bytes = get_additional_bytes_to_reach_memory_usage_pct(0.3) first_actor_task = first_actor.allocate.remote(allocate_bytes) second_actor_task = second_actor.allocate.remote(allocate_bytes) error_thrown = False try: ray.get(fir...
394
First started actor, which is retriable, was killed by the memory monitor. Second started actor, which is not-retriable, finished. Addressing memory issues# When the application fails due to OOM, consider reducing the memory usage of the tasks and actors, increasing the memory capacity of the node, or limit the n...
395
Catching application-level failures# Ray surfaces application-level failures as Python-level exceptions. When a task on a remote worker or actor fails due to a Python-level exception, Ray wraps the original exception in a RayTaskError and stores this as the task’s return value. This wrapped exception will be thrown to ...
396
import ray @ray.remote def f(): raise Exception("the real error") @ray.remote def g(x): return try: ray.get(f.remote()) except ray.exceptions.RayTaskError as e: print(e) # ray::f() (pid=71867, ip=XXX.XX.XXX.XX) # File "errors.py", line 5, in f # raise Exception("the real error") ...
397
Example code of catching the user exception type when the exception type can be subclassed: class MyException(Exception): ... @ray.remote def raises_my_exc(): raise MyException("a user exception") try: ray.get(raises_my_exc.remote()) except MyException as e: print(e) # ray::raises_my_exc() (pid=15...
398
@ray.remote def raises_my_final_exc(): raise MyFinalException("a *final* user exception") try: ray.get(raises_my_final_exc.remote()) except ray.exceptions.RayTaskError as e: assert isinstance(e.cause, MyFinalException) print(e) # 2024-04-08 21:11:47,417 WARNING exceptions.py:177 -- User exception ty...
399
If Ray can’t serialize the user’s exception, it converts the exception to a RayError. import threading class UnserializableException(Exception): def __init__(self): self.lock = threading.Lock() @ray.remote def raise_unserializable_error(): raise UnserializableException try: ray.get(raise_unseria...