How to modify numpy elements via Ray

Hey all,

I have a big array A, I use for loop to modify elements in A. Now I want to use Ray to accelerate the for loop, but I always got an error like ValueError: assignment destination is read-only, how should I do…

import numpy as np
import ray

ray.init()

# Define the function to modify the elements in the array
@ray.remote
def modify_element(a):
    for i in range(len(a)):
        a[i] = a[i] + 2

# Create a NumPy array
A = np.random.rand(100)

# Modify the elements in the array using Ray
ray.get(modify_element.remote(A))
print(A)

Hi @Fuller , welcome to the community and great question.

So ray uses Ray’s object store to pass arguments around (Objects — Ray 2.3.0) and remote objects are not mutable to avoid synchronization. See more here: Serialization — Ray 2.3.0

You will need to deep copy the argument a which is an immutable object in ray’s object store into your function:

# Define the function to modify the elements in the array
@ray.remote
def modify_element(a):
    a_copy = np.copy(a)
    for i in range(len(a_copy)):
        a_copy[i] = a_copy[i] + 2
    return a_copy

# Create a NumPy array
A = np.random.rand(100)

# Modify the elements in the array using Ray
A_modified = ray.get(modify_element.remote(A))
print(A_modified)