Skip to content

Commit

Permalink
Add RayParallelization (anyoptimization#444)
Browse files Browse the repository at this point in the history
  • Loading branch information
zhiruiluo authored Jun 25, 2023
1 parent 695cb26 commit 73ae27b
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions pymoo/core/problem.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@
from pymoo.util.cache import Cache
from pymoo.util.misc import at_least_2d_array

try:
import ray
except ImportError:
ray = None


class ElementwiseEvaluationFunction:

Expand Down Expand Up @@ -75,6 +80,43 @@ def __getstate__(self):
return state


class RayParallelization:
"""Use Ray as backend to parallelize problem evaluation.
Ray is an open-source unified framework for scaling AI and Python applicaitons.
Read more here: https://docs.ray.io.
You will need to install Ray to use this.
"""
def __init__(self, job_resources: dict = {'num_cpus': 1}) -> None:
"""
Parameters
----------
job_resources: A resource in Ray is a key-value pair where the key denotes a
resource name and the value is a float quantity. Ray has native support for CPU,
GPU, and memory resource types; `'num_cpus'`, `'num_gpus'`, and `'memory'`.
Read more here:
https://docs.ray.io/en/latest/ray-core/scheduling/resources.html.
"""
assert ray is not None, (
"Ray must be installed! "
"You can install Ray with the command: "
'`pip install -U "ray[default]"`'
)
super().__init__()
self.job_resources = job_resources

def __call__(self, f, X):
runnable = ray.remote(f.__call__.__func__)
runnable = runnable.options(**self.job_resources)
futures = [runnable.remote(f, x) for x in X]
return ray.get(futures)

def __getstate__(self):
state = self.__dict__.copy()
return state


class Problem:
def __init__(self,
n_var=-1,
Expand Down

0 comments on commit 73ae27b

Please sign in to comment.