├── src └── cmlextensions │ ├── __init__.py │ ├── workers_v2 │ ├── __init__.py │ └── workers.py │ ├── dask_cluster │ ├── __init__.py │ └── dask_cluster.py │ └── ray_cluster │ ├── __init__.py │ └── ray_cluster.py ├── .gitignore ├── pyproject.toml ├── setup.cfg ├── test ├── test_ray.py ├── test_dask.py └── test_workers.py ├── README.md └── LICENSE /src/cmlextensions/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | R 2 | node_modules 3 | *.pyc 4 | __pycache__ 5 | .* 6 | !.gitignore 7 | !.experiments -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = [ 3 | "setuptools>=42", 4 | "wheel" 5 | ] 6 | build-backend = "setuptools.build_meta" -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | name = cmlextensions 3 | version = 0.1 4 | description = extra functionality to the cml library 5 | long_description = file: README.md 6 | long_description_content_type = text/markdown 7 | author = peter.ableda 8 | author_email = peter.ableda@gmail.com 9 | 10 | [options] 11 | package_dir = =src 12 | packages = find: 13 | python_requires = >=3.6 14 | 15 | [options.packages.find] 16 | where = src -------------------------------------------------------------------------------- /src/cmlextensions/workers_v2/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2022 Cloudera. All Rights Reserved. 2 | # 3 | # This file is licensed under the Apache License Version 2.0 4 | # (the "License"). You may not use this file except in compliance 5 | # with the License. You may obtain a copy of the License at 6 | # http://www.apache.org/licenses/LICENSE-2.0. 7 | # 8 | # This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES 9 | # OR CONDITIONS OF ANY KIND, either express or implied. Refer to the 10 | # License for the specific permissions and limitations governing your 11 | # use of the file. 12 | 13 | from .workers import * 14 | -------------------------------------------------------------------------------- /src/cmlextensions/dask_cluster/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2022 Cloudera. All Rights Reserved. 2 | # 3 | # This file is licensed under the Apache License Version 2.0 4 | # (the "License"). You may not use this file except in compliance 5 | # with the License. You may obtain a copy of the License at 6 | # http://www.apache.org/licenses/LICENSE-2.0. 7 | # 8 | # This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES 9 | # OR CONDITIONS OF ANY KIND, either express or implied. Refer to the 10 | # License for the specific permissions and limitations governing your 11 | # use of the file. 12 | 13 | from .dask_cluster import * 14 | 15 | try: 16 | import cdsw 17 | except ImportError as error: 18 | raise ImportError( 19 | "Could not import cdsw, for this module to work you need to execute this code in a CML session" 20 | ) 21 | -------------------------------------------------------------------------------- /src/cmlextensions/ray_cluster/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2022 Cloudera. All Rights Reserved. 2 | # 3 | # This file is licensed under the Apache License Version 2.0 4 | # (the "License"). You may not use this file except in compliance 5 | # with the License. You may obtain a copy of the License at 6 | # http://www.apache.org/licenses/LICENSE-2.0. 7 | # 8 | # This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES 9 | # OR CONDITIONS OF ANY KIND, either express or implied. Refer to the 10 | # License for the specific permissions and limitations governing your 11 | # use of the file. 12 | 13 | from .ray_cluster import * 14 | 15 | try: 16 | import cml.utils_v1 as utils 17 | 18 | cdsw = utils._emulate_cdsw() 19 | except ImportError: 20 | import cdsw 21 | 22 | if "cdsw" not in locals(): 23 | raise ImportError( 24 | "Could not import cdsw, for this module to work you need to execute this code in a CML session" 25 | ) 26 | -------------------------------------------------------------------------------- /test/test_ray.py: -------------------------------------------------------------------------------- 1 | # Copyright 2022 Cloudera. All Rights Reserved. 2 | # 3 | # This file is licensed under the Apache License Version 2.0 4 | # (the "License"). You may not use this file except in compliance 5 | # with the License. You may obtain a copy of the License at 6 | # http://www.apache.org/licenses/LICENSE-2.0. 7 | # 8 | # This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES 9 | # OR CONDITIONS OF ANY KIND, either express or implied. Refer to the 10 | # License for the specific permissions and limitations governing your 11 | # use of the file. 12 | 13 | # Add cmlextensions to the path 14 | import sys 15 | sys.path.append('../src') 16 | 17 | import ray 18 | from cmlextensions.ray_cluster import RayCluster 19 | 20 | c = RayCluster(num_workers=2, env={'OMP_NUM_THREADS':'2'}) 21 | c.init() 22 | 23 | # Connect to the cluster 24 | ray.init(address=c.get_client_url()) 25 | 26 | # Define the square task. 27 | @ray.remote 28 | def square(x): 29 | return x * x 30 | 31 | # Launch four parallel square tasks. 32 | futures = [square.remote(i) for i in range(4)] 33 | 34 | # Retrieve results. 35 | print(ray.get(futures)) 36 | 37 | # Delete cluster 38 | c.terminate() 39 | -------------------------------------------------------------------------------- /test/test_dask.py: -------------------------------------------------------------------------------- 1 | # Copyright 2022 Cloudera. All Rights Reserved. 2 | # 3 | # This file is licensed under the Apache License Version 2.0 4 | # (the "License"). You may not use this file except in compliance 5 | # with the License. You may obtain a copy of the License at 6 | # http://www.apache.org/licenses/LICENSE-2.0. 7 | # 8 | # This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES 9 | # OR CONDITIONS OF ANY KIND, either express or implied. Refer to the 10 | # License for the specific permissions and limitations governing your 11 | # use of the file. 12 | 13 | ## Dependencies 14 | # !pip install dask[complete] 15 | 16 | # Add cmlextensions to the path 17 | import sys 18 | sys.path.append('../src') 19 | 20 | from cmlextensions.dask_cluster import DaskCluster 21 | 22 | cluster = DaskCluster(num_workers=2) 23 | cluster.init() 24 | 25 | # Connect to the cluster 26 | from dask.distributed import Client 27 | client = Client(cluster.get_client_url()) 28 | 29 | client 30 | 31 | import dask.array as da 32 | 33 | # Create a dask array from a NumPy array 34 | x = da.from_array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], chunks=(2, 2)) 35 | 36 | # Perform a computation on the dask array 37 | y = (x + 1) * 2 38 | 39 | # Submit the computation to the cluster for execution 40 | future = client.submit(y.compute) 41 | 42 | # Wait for the computation to complete and retrieve the result 43 | result = future.result() 44 | 45 | print(result) # Outputs: [[ 4 6 8] [10 12 14] [14 16 18]] 46 | 47 | # Delete cluster 48 | cluster.terminate() 49 | -------------------------------------------------------------------------------- /test/test_workers.py: -------------------------------------------------------------------------------- 1 | # Copyright 2022 Cloudera. All Rights Reserved. 2 | # 3 | # This file is licensed under the Apache License Version 2.0 4 | # (the "License"). You may not use this file except in compliance 5 | # with the License. You may obtain a copy of the License at 6 | # http://www.apache.org/licenses/LICENSE-2.0. 7 | # 8 | # This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES 9 | # OR CONDITIONS OF ANY KIND, either express or implied. Refer to the 10 | # License for the specific permissions and limitations governing your 11 | # use of the file. 12 | 13 | from cmlextensions.workers_v2 import WorkerGroup 14 | import cmlextensions.workers_v2 as workers 15 | import time 16 | import sys 17 | sys.path.append('../src') 18 | 19 | # check no workers 20 | workers.get_workers() 21 | 22 | # test get and describe workers 23 | wg = WorkerGroup(2, code="import time;time.sleep(30)") 24 | wg.get_workers() 25 | wg.describe_workers() 26 | 27 | 28 | # test stop workers 29 | wg2 = WorkerGroup(1, code="import time;time.sleep(300)") 30 | time.sleep(10) 31 | wg2.get_workers() 32 | wg2.stop_workers() 33 | 34 | # test active workload filter 35 | workers.get_workers() 36 | wg4 = WorkerGroup(1, code="import time;time.sleep(300)") 37 | wg4.get_workers() 38 | workers.get_workers(active=True) 39 | 40 | # test awaits 41 | start = time.time() 42 | wg4 = WorkerGroup(1, wait_for_running=True, code="import time;time.sleep(1)") 43 | end = time.time() 44 | print("Time waited for getting to running status: ", end - start) 45 | 46 | start2 = time.time() 47 | wg5 = WorkerGroup(1, wait_for_running=True, 48 | wait_for_completion=True, code="import time;time.sleep(30)") 49 | end2 = time.time() 50 | print("Time waited for completion: ", end2 - start2) 51 | 52 | workers.stop_workers() 53 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cmlextensions 2 | 3 | This python library has added functionality for [Cloudera Machine Learning (CML)](https://docs.cloudera.com/machine-learning/cloud/product/topics/ml-product-overview.html#cdsw_overview)'s cml (or legacy cdsw) library. The library is organized in modules and is built on the [CML Workers API](https://docs.cloudera.com/machine-learning/cloud/distributed-computing/topics/ml-workers-api.html) and other CML functionalities. 4 | 5 | ## Installation 6 | This library can be installed directly from GitHub: 7 | 8 | ```%pip install git+https://github.com/cloudera/cmlextensions.git``` 9 | 10 | ## Modules 11 | 12 | ### Ray 13 | Ray is a unified framework for scaling AI and Python applications. We can create a cluster on CML infrastructure to scale out Ray processes. This `cmlextensions.ray_cluster` module abstracts the ray cluster provisioning and operations so users can focus on their application code instead of infrastructure management. 14 | 15 | Example usage: 16 | ``` 17 | > from cmlextensions.ray_cluster import RayCluster 18 | 19 | > cluster = RayCluster(num_workers=2) 20 | > cluster.init() 21 | 22 | -------------------- 23 | Ray cluster started 24 | -------------------- 25 | 26 | The Ray dashboard is running at 27 | https://024d0wpuw0eain8r.ml-4c5feac0-3ec.go01-dem.ylcu-atmi.cloudera.site/ 28 | 29 | To connect to this Ray cluster from this CML Session, 30 | use the following Python code: 31 | import ray 32 | ray.init(address='ray://100.100.127.74:10001') 33 | 34 | ``` 35 | 36 | ### Dask 37 | Dask is a flexible parallel computing library for analytics in Python. We can create a cluster on CML infrastructure to scale out Dask processes. This `cmlextensions.dask_cluster` module abstracts the dask cluster provisioning and operations so users can focus on their application code instead of infrastructure management. 38 | 39 | Example usage: 40 | ``` 41 | > from cmlextensions.dask_cluster import DaskCluster 42 | 43 | > cluster = DaskCluster(num_workers=2) 44 | > cluster.init() 45 | 46 | -------------------- 47 | Dask cluster started 48 | -------------------- 49 | 50 | The Dask dashboard is running at 51 | https://024d0wpuw0eain8r.ml-4c5feac0-3ec.go01-dem.ylcu-atmi.cloudera.site/ 52 | 53 | To connect to this Dask cluster from this CML Session, 54 | use the following Python code: 55 | from dask.distributed import Client 56 | client = Client('tcp://100.100.225.149:8786') 57 | ``` 58 | 59 | ### Workers_v2 60 | The cml (or legacy cdsw) library has a workers module already. The v2 module is experimenting with a new management interface for the CML Workers infrastructure. The v2 module has more defaults and a more OOP approach for managing groups of workers. There is no added functionality, the v2 library relies on the functionality available in the orignal version. 61 | 62 | Example usage: 63 | ``` 64 | > import cmlextensions.workers_v2 as workers 65 | > from cmlextensions.workers_v2 import WorkerGroup 66 | 67 | > wg1 = WorkerGroup(1, code="import time;time.sleep(300)") 68 | > wg1.get_workers() 69 | id status created_at running_at finished_at duration ip_address 70 | 221pa78rmzau93zf running 2022-09-09T12:02:14.031Z 2022-09-09T12:02:27.945Z None 1 100.100.209.35 71 | 72 | > workers.get_workers(active=True) 73 | id status created_at running_at finished_at duration ip_address 74 | 221pa78rmzau93zf running 2022-09-09T12:02:14.031Z 2022-09-09T12:02:27.945Z None 7 100.100.209.35 75 | 6tyvg0kuu0wrlcyl running 2022-09-09T12:01:50.282Z 2022-09-09T12:02:04.387Z None 30 100.100.127.80 76 | 77 | > wg1.stop_workers() 78 | ``` 79 | -------------------------------------------------------------------------------- /src/cmlextensions/workers_v2/workers.py: -------------------------------------------------------------------------------- 1 | # Copyright 2022 Cloudera. All Rights Reserved. 2 | # 3 | # This file is licensed under the Apache License Version 2.0 4 | # (the "License"). You may not use this file except in compliance 5 | # with the License. You may obtain a copy of the License at 6 | # http://www.apache.org/licenses/LICENSE-2.0. 7 | # 8 | # This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES 9 | # OR CONDITIONS OF ANY KIND, either express or implied. Refer to the 10 | # License for the specific permissions and limitations governing your 11 | # use of the file. 12 | 13 | import cdsw 14 | import pandas as pd 15 | import uuid 16 | 17 | pd.set_option('display.max_columns', None) 18 | 19 | def get_workers(active=False): 20 | if active: 21 | workers = _get_active_workers() 22 | else: 23 | workers = cdsw.list_workers() 24 | 25 | # TODO: it would be nice to return the worker group_ids 26 | return _worker_dict_to_df(workers) 27 | 28 | def describe_workers(active=False): 29 | if active: 30 | return _get_active_workers() 31 | else: 32 | return cdsw.list_workers() 33 | 34 | def stop_workers(): 35 | return cdsw.stop_workers() 36 | 37 | def _worker_dict_to_df(worker_dict): 38 | df = pd.DataFrame.from_dict(worker_dict) 39 | 40 | # TODO once we can set the worker 'name' we should show it 41 | columns = ['id', 'status', 'created_at', 'running_at', 'finished_at', 'duration', 'ip_address'] 42 | 43 | # constructing df in case of missing columns 44 | for col in columns: 45 | if col not in df: 46 | df[col] = None 47 | 48 | return df[columns] 49 | 50 | def _get_active_workers(): 51 | workers = cdsw.list_workers() 52 | 53 | stopped_statuses = ['failed', 'succeeded', 'stopped'] 54 | 55 | return [ 56 | worker for worker in workers if worker["status"] not in stopped_statuses 57 | ] 58 | 59 | class WorkerGroup(): 60 | """New interface for the CML Worker infrastructure""" 61 | 62 | def __init__(self, n, cpu=2, memory=4, nvidia_gpu=0, script="", code="", env={}, wait_for_running=False, wait_for_completion=False, timeout_seconds=90): 63 | 64 | self.id = str(uuid.uuid4())[:8] 65 | # env['group_id'] = self.id 66 | 67 | workers = cdsw.launch_workers( 68 | n=n, 69 | cpu=cpu, 70 | memory=memory, 71 | nvidia_gpu=nvidia_gpu, 72 | script=script, 73 | code=code, 74 | env=env, 75 | ) 76 | 77 | self.worker_ids = [ 78 | worker["id"] for worker in workers 79 | ] 80 | 81 | if wait_for_running or wait_for_completion: 82 | self.failures = cdsw.await_workers( 83 | workers, 84 | wait_for_completion=wait_for_completion, 85 | timeout_seconds=timeout_seconds 86 | )['failures'] 87 | 88 | 89 | def _get_fresh_worker_data(self): 90 | refreshed_workers = cdsw.list_workers() 91 | 92 | return [ 93 | worker for worker in refreshed_workers if worker["id"] in self.worker_ids 94 | ] 95 | 96 | def describe_workers(self): 97 | return self._get_fresh_worker_data() 98 | 99 | def get_workers(self): 100 | return _worker_dict_to_df(self._get_fresh_worker_data()) 101 | 102 | def stop_workers(self): 103 | return cdsw.stop_workers(*self.worker_ids) 104 | -------------------------------------------------------------------------------- /src/cmlextensions/dask_cluster/dask_cluster.py: -------------------------------------------------------------------------------- 1 | # Copyright 2022 Cloudera. All Rights Reserved. 2 | # 3 | # This file is licensed under the Apache License Version 2.0 4 | # (the "License"). You may not use this file except in compliance 5 | # with the License. You may obtain a copy of the License at 6 | # http://www.apache.org/licenses/LICENSE-2.0. 7 | # 8 | # This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES 9 | # OR CONDITIONS OF ANY KIND, either express or implied. Refer to the 10 | # License for the specific permissions and limitations governing your 11 | # use of the file. 12 | 13 | import os 14 | import cdsw 15 | 16 | DEFAULT_DASHBOARD_PORT = os.environ["CDSW_APP_PORT"] 17 | 18 | 19 | class DaskCluster: 20 | """Dask Cluster built on CML Worker infrastructure""" 21 | 22 | def __init__( 23 | self, 24 | num_workers, 25 | worker_cpu=2, 26 | worker_memory=4, 27 | scheduler_cpu=2, 28 | scheduler_memory=4, 29 | dashboard_port=DEFAULT_DASHBOARD_PORT, 30 | ): 31 | self.num_workers = num_workers 32 | self.worker_cpu = worker_cpu 33 | self.worker_memory = worker_memory 34 | self.scheduler_cpu = scheduler_cpu 35 | self.scheduler_memory = scheduler_memory 36 | self.dashboard_port = dashboard_port 37 | 38 | self.dask_scheduler_details = None 39 | self.dask_worker_details = None 40 | 41 | def _start_dask_scheduler(self): 42 | dask_scheduler_cmd = f"!dask scheduler --host 0.0.0.0 --dashboard-address 127.0.0.1:{self.dashboard_port}" 43 | 44 | args = { 45 | 'n': 1, 46 | 'cpu': self.scheduler_cpu, 47 | 'memory': self.scheduler_memory, 48 | 'code': dask_scheduler_cmd, 49 | } 50 | 51 | if hasattr(cdsw.launch_workers, 'name'): 52 | args['name'] = 'Dask Scheduler' 53 | 54 | dask_scheduler = cdsw.launch_workers(**args) 55 | 56 | self.dask_scheduler_details = cdsw.await_workers( 57 | dask_scheduler, wait_for_completion=False, timeout_seconds=90 58 | ) 59 | 60 | def _add_dask_workers(self, scheduler_addr): 61 | worker_start_cmd = f"!dask worker {scheduler_addr}" 62 | 63 | args = { 64 | 'n': self.num_workers, 65 | 'cpu': self.worker_cpu, 66 | 'memory': self.worker_memory, 67 | 'code': worker_start_cmd, 68 | } 69 | 70 | if hasattr(cdsw.launch_workers, 'name'): 71 | args['name'] = 'Dask Worker' 72 | 73 | dask_workers = cdsw.launch_workers(**args) 74 | 75 | self.dask_worker_details = cdsw.await_workers( 76 | dask_workers, wait_for_completion=False 77 | ) 78 | 79 | def get_client_url(self): 80 | dask_scheduler_ip = self.dask_scheduler_details["workers"][0]["ip_address"] 81 | return f"tcp://{dask_scheduler_ip}:8786" 82 | 83 | def init(self): 84 | """ 85 | Creates a Dask Cluster on the CML Workers infrastructure. 86 | """ 87 | try: 88 | import dask # pylint: disable=unused-import 89 | except ImportError as error: 90 | raise ImportError( 91 | "Could not import dask, for this module to work please run `pip install dask[complete]` \n -> " 92 | + str(error) 93 | ) from error 94 | 95 | # Start the dask scheduler process 96 | self._start_dask_scheduler() 97 | 98 | dask_scheduler_addr = self.get_client_url() 99 | 100 | self._add_dask_workers(dask_scheduler_addr) 101 | 102 | # TODO: could add cluster details, e.g., worker count and resources 103 | print( 104 | f""" 105 | -------------------- 106 | Dask cluster started 107 | -------------------- 108 | 109 | The Dask dashboard is running at 110 | {self.get_dashboard_url()} 111 | 112 | To connect to this Dask cluster from this CML Session, 113 | use the following Python code: 114 | from dask.distributed import Client 115 | client = Client('{self.get_client_url()}') 116 | """ 117 | ) 118 | 119 | def get_dashboard_url(self): 120 | """ 121 | Return the Dask dashboard url. 122 | """ 123 | try: 124 | return self.dask_scheduler_details["workers"][0]["app_url"] + "status" 125 | except Error as error: 126 | raise Error("ERROR: Dask cluster is not running!") 127 | 128 | def terminate(self): 129 | """ 130 | Terminates the Dask Cluster. 131 | """ 132 | 133 | # TODO: stop workers only when they were created for this Dask Cluster 134 | cdsw.stop_workers() 135 | 136 | # Reset instance state 137 | self.dask_scheduler_ip = None 138 | self.dask_scheduler_addr = None 139 | self.dask_scheduler_details = None 140 | self.dask_worker_details = None 141 | -------------------------------------------------------------------------------- /src/cmlextensions/ray_cluster/ray_cluster.py: -------------------------------------------------------------------------------- 1 | # Copyright 2022 Cloudera. All Rights Reserved. 2 | # 3 | # This file is licensed under the Apache License Version 2.0 4 | # (the "License"). You may not use this file except in compliance 5 | # with the License. You may obtain a copy of the License at 6 | # http://www.apache.org/licenses/LICENSE-2.0. 7 | # 8 | # This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES 9 | # OR CONDITIONS OF ANY KIND, either express or implied. Refer to the 10 | # License for the specific permissions and limitations governing your 11 | # use of the file. 12 | 13 | import os 14 | import inspect 15 | 16 | # PBJ Runtimes do not have the cdsw library installed. 17 | # Instead, the cml library is added to workloads in recent CML releases. 18 | try: 19 | import cml.utils_v1 as utils 20 | cdsw = utils._emulate_cdsw() 21 | except ImportError: 22 | import cdsw 23 | 24 | 25 | DEFAULT_DASHBOARD_PORT = os.environ['CDSW_APP_PORT'] 26 | 27 | class RayCluster(): 28 | """Ray Cluster built on CML Worker infrastructure""" 29 | 30 | def __init__(self, num_workers, worker_cpu=2, worker_memory=4, worker_nvidia_gpu=0, head_cpu=2, head_memory=4, head_nvidia_gpu=0, dashboard_port=DEFAULT_DASHBOARD_PORT, env 31 | ={}): 32 | self.num_workers = num_workers 33 | self.worker_cpu = worker_cpu 34 | self.worker_memory = worker_memory 35 | self.worker_nvidia_gpu = worker_nvidia_gpu 36 | self.head_cpu = head_cpu 37 | self.head_memory = head_memory 38 | self.head_nvidia_gpu = head_nvidia_gpu 39 | self.dashboard_port = dashboard_port 40 | self.env = env 41 | 42 | self.ray_head_details = None 43 | self.ray_worker_details = None 44 | 45 | def _stop_ray_workloads(self): 46 | for workload_details in [self.ray_head_details, self.ray_worker_details]: 47 | for status in ["workers" , "failures"]: 48 | if workload_details is not None and status in workload_details: 49 | stop_responses = cdsw.stop_workers(*[workload["id"] for workload in workload_details[status]]) 50 | stop_response_statuses = [response.status_code for response in stop_responses] 51 | if(any([status >= 300 for status in stop_response_statuses])): 52 | print("Could not stop all Ray workloads. Trying to force stop all CML workers created in this session.") 53 | cdsw.stop_workers() 54 | 55 | def _start_ray_workload(self, args, startup_timeout_seconds): 56 | workloads = cdsw.launch_workers(**args) 57 | workloads_with_ids = [wl for wl in workloads if "id" in wl] 58 | workloads_with_no_ids = [wl for wl in workloads if "id" not in wl] 59 | no_id_messages = set([wl.get("message", "") for wl in workloads_with_no_ids]) 60 | if len(workloads_with_no_ids) > 0: 61 | print("Could not create all requested workloads. Error messages received:" , no_id_messages) 62 | # Clean up all workloads 63 | ids = [wl["id"] for wl in workloads_with_ids ] + [wl.get("engineId", "") for wl in workloads_with_no_ids] 64 | ids = [id for id in ids if len(id) > 0] 65 | cdsw.stop_workers(*ids) 66 | return None 67 | workload_details = cdsw.await_workers( 68 | workloads_with_ids, 69 | wait_for_completion=False, 70 | timeout_seconds=startup_timeout_seconds 71 | ) 72 | return workload_details 73 | 74 | 75 | 76 | 77 | def _start_ray_head(self, startup_timeout_seconds): 78 | # We need to start the ray process with --block else the command completes and the CML Worker terminates 79 | head_start_cmd = f"!ray start --head --block --disable-usage-stats --num-cpus={self.head_cpu} --num-gpus={self.head_nvidia_gpu} --include-dashboard=true --dashboard-port={self.dashboard_port}" 80 | 81 | args = { 82 | 'n': 1, 83 | 'cpu': self.head_cpu, 84 | 'memory': self.head_memory, 85 | "nvidia_gpu" : self.head_nvidia_gpu, 86 | 'code': head_start_cmd, 87 | 'env': self.env, 88 | } 89 | if "name" in inspect.signature(cdsw.launch_workers).parameters: 90 | args['name'] = 'Ray Head' 91 | 92 | self.ray_head_details = self._start_ray_workload(args, startup_timeout_seconds) 93 | 94 | def _add_ray_workers(self, head_addr, startup_timeout_seconds): 95 | # We need to start the ray process with --block else the command completes and the CML Worker terminates 96 | worker_start_cmd = f"!ray start --block --num-cpus={self.worker_cpu} --num-gpus={self.worker_nvidia_gpu} --address={head_addr}" 97 | 98 | args = { 99 | 'n': self.num_workers, 100 | 'cpu': self.worker_cpu, 101 | 'memory': self.worker_memory, 102 | "nvidia_gpu" : self.worker_nvidia_gpu, 103 | 'code': worker_start_cmd, 104 | 'env': self.env, 105 | } 106 | 107 | if "name" in inspect.signature(cdsw.launch_workers).parameters: 108 | args['name'] = 'Ray Worker' 109 | 110 | self.ray_worker_details = self._start_ray_workload(args, startup_timeout_seconds) 111 | 112 | def init(self, startup_timeout_seconds = 90): 113 | """ 114 | Creates a Ray Cluster on the CML Workers infrastructure. 115 | """ 116 | try: 117 | import ray # pylint: disable=unused-import 118 | except ImportError as error: 119 | raise ImportError( 120 | "Could not import ray, for this module to work please run `pip install ray[default]` \n -> " 121 | + str(error) 122 | ) from error 123 | 124 | # Start the ray head process 125 | print("Starting ray head...") 126 | startup_failed = False 127 | self._start_ray_head(startup_timeout_seconds = startup_timeout_seconds) 128 | 129 | if len(self.ray_head_details.get("workers",[])) < 1: 130 | print(f"Could not start ray head.") 131 | startup_failed = True 132 | 133 | else: 134 | ray_head_ip = self.ray_head_details['workers'][0]['ip_address'] 135 | ray_head_addr = ray_head_ip + ':6379' 136 | print(f"Starting {self.num_workers} ray workers...") 137 | self._add_ray_workers(ray_head_addr, startup_timeout_seconds = startup_timeout_seconds) 138 | if self.ray_worker_details is None or len(self.ray_worker_details.get("workers", [])) < self.num_workers: 139 | print(f"Could not start {self.num_workers} requested ray workers.\n") 140 | startup_failed = True 141 | 142 | if startup_failed: 143 | print("Could not start some of the ray workloads. Ensure ray is able to run in your environment and you have the resources in your CML workspace to provision the specified amount of ray workloads.") 144 | print("Set a longer timeout period if your CML workspace needs time to scale.") 145 | print("Shutting down Ray cluster..") 146 | self.terminate() 147 | return 148 | 149 | #TODO: could add cluster details, e.g., worker count and resources 150 | print(f""" 151 | -------------------- 152 | Ray cluster started 153 | -------------------- 154 | 155 | The Ray dashboard is running at 156 | {self.get_dashboard_url()} 157 | 158 | To connect to this Ray cluster from this CML Session, 159 | use the following Python code: 160 | import ray 161 | ray.init(address='{self.get_client_url()}') 162 | """) 163 | 164 | def get_dashboard_url(self): 165 | """ 166 | Return the Ray dashboard url. 167 | """ 168 | try: 169 | return self.ray_head_details['workers'][0]['app_url'] 170 | except Error as error: 171 | raise Error("ERROR: Ray cluster is not running!") 172 | 173 | def get_client_url(self): 174 | ray_head_ip = self.ray_head_details['workers'][0]['ip_address'] 175 | return f"ray://{ray_head_ip}:10001" 176 | 177 | def terminate(self): 178 | """ 179 | Terminates the Ray Cluster. 180 | """ 181 | 182 | self._stop_ray_workloads() 183 | 184 | # Reset instance state 185 | self.ray_head_ip = None 186 | self.ray_head_addr = None 187 | self.ray_head_details = None 188 | self.ray_worker_details = None 189 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------