翼度科技»论坛 编程开发 python 查看内容

Python中的分布式框架Ray的安装与使用教程

4

主题

4

帖子

12

积分

新手上路

Rank: 1

积分
12
技术背景

假设我们在一个局域网内有多台工作站(不是服务器),那么有没有一个简单的方案可以实现一个小集群,提交分布式的任务呢?Ray为我们提供了一个很好的解决方案,允许你通过conda和Python灵活的构建集群环境,并提交分布式的任务。其基本架构为:

那么本文简单的介绍一下Ray的安装与基本使用。

安装

由于是一个Python的框架,Ray可以直接使用pip进行安装和管理:
  1. $ python3 -m pip install ray[default]
复制代码
但是需要注意的是,在所有需要构建集群的设备上,需要统一Python和Ray的版本,因此建议先使用conda创建同样的虚拟环境之后,再安装统一版本的ray。否则在添加集群节点的时候就有可能出现如下问题:
  1. RuntimeError: Version mismatch: The cluster was started with:    Ray: 2.7.2    Python: 3.7.13This process on node 172.17.0.2 was started with:    Ray: 2.7.2    Python: 3.7.5
复制代码
启动和连接服务

一般在配置集群的时候可以先配置下密钥登陆:
  1. $ ssh-keygen -t rsa
  2. $ ssh-copy-id user_name@ip_address
复制代码
就这么两步,就可以配置远程服务器ssh免密登陆(配置的过程中有可能需要输入一次密码)。然后在主节点(配置一个master节点)启动ray服务:
  1. $ ray start --head --dashboard-host='0.0.0.0' --dashboard-port=8265
  2. Usage stats collection is enabled. To disable this, add `--disable-usage-stats` to the command that starts the cluster, or run the following command: `ray disable-usage-stats` before starting the cluster. See https://docs.ray.io/en/master/cluster/usage-stats.html for more details.
  3. Local node IP: xxx.xxx.xxx.xxx
  4. --------------------
  5. Ray runtime started.
  6. --------------------
  7. Next steps
  8.   To add another node to this Ray cluster, run
  9.     ray start --address='xxx.xxx.xxx.xxx:6379'
  10.   To connect to this Ray cluster:
  11.     import ray
  12.     ray.init()
  13.   To submit a Ray job using the Ray Jobs CLI:
  14.     RAY_ADDRESS='http://xxx.xxx.xxx.xxx:8265' ray job submit --working-dir . -- python my_script.py
  15.   See https://docs.ray.io/en/latest/cluster/running-applications/job-submission/index.html
  16.   for more information on submitting Ray jobs to the Ray cluster.
  17.   To terminate the Ray runtime, run
  18.     ray stop
  19.   To view the status of the cluster, use
  20.     ray status
  21.   To monitor and debug Ray, view the dashboard at
  22.     xxx.xxx.xxx.xxx:8265
  23.   If connection to the dashboard fails, check your firewall settings and network configuration.
复制代码
这就启动完成了,并给你指示了下一步的操作,例如在另一个节点上配置添加到集群中,可以使用指令:
  1. $ ray start --address='xxx.xxx.xxx.xxx:6379'
复制代码
但是前面提到了,这里要求Python和Ray版本要一致,如果版本不一致就会出现这样的报错:
  1. RuntimeError: Version mismatch: The cluster was started with:    Ray: 2.7.2    Python: 3.7.13This process on node 172.17.0.2 was started with:    Ray: 2.7.2    Python: 3.7.5
复制代码
到这里其实Ray集群就已经部署完成了,非常的简单方便。

基础使用

我们先用一个最简单的案例来测试一下:
  1. # test_ray.py
  2. import os
  3. import ray
  4. ray.init()
  5. print('''This cluster consists of
  6.     {} nodes in total
  7.     {} CPU resources in total
  8. '''.format(len(ray.nodes()), ray.cluster_resources()['CPU']))
复制代码
这个Python脚本打印了远程节点的计算资源,那么我们可以用这样的方式去提交一个本地的job:
  1. $ RAY_ADDRESS='http://xxx.xxx.xxx.xxx:8265' ray job submit --working-dir . -- python test_ray.py
  2. Job submission server address: http://xxx.xxx.xxx.xxx:8265
  3. 2024-08-27 07:35:10,751 INFO dashboard_sdk.py:338 -- Uploading package gcs://_ray_pkg_4b79155b5de665ce.zip.
  4. 2024-08-27 07:35:10,751 INFO packaging.py:518 -- Creating a file package for local directory '.'.
  5. -------------------------------------------------------
  6. Job 'raysubmit_7Uqy8LjP4dxjZxGa' submitted successfully
  7. -------------------------------------------------------
  8. Next steps
  9.   Query the logs of the job:
  10.     ray job logs raysubmit_7Uqy8LjP4dxjZxGa
  11.   Query the status of the job:
  12.     ray job status raysubmit_7Uqy8LjP4dxjZxGa
  13.   Request the job to be stopped:
  14.     ray job stop raysubmit_7Uqy8LjP4dxjZxGa
  15. Tailing logs until the job exits (disable with --no-wait):
  16. 2024-08-27 15:35:14,079 INFO worker.py:1330 -- Using address xxx.xxx.xxx.xxx:6379 set in the environment variable RAY_ADDRESS
  17. 2024-08-27 15:35:14,079 INFO worker.py:1458 -- Connecting to existing Ray cluster at address: xxx.xxx.xxx.xxx:6379...
  18. 2024-08-27 15:35:14,103 INFO worker.py:1639 -- Connected to Ray cluster. View the dashboard at http://xxx.xxx.xxx.xxx:8265
  19. This cluster consists of
  20.     1 nodes in total
  21.     48.0 CPU resources in total
  22. ------------------------------------------
  23. Job 'raysubmit_7Uqy8LjP4dxjZxGa' succeeded
  24. ------------------------------------------
复制代码
这里的信息说明,远程的集群只有一个节点,该节点上有48个可用的CPU核资源。这些输出信息不仅可以在终端窗口上看到,还可以从这里给出的dashboard链接里面看到更加详细的任务管理情况:

这里也顺便提交一个输出软件位置信息的指令,确认下任务是在远程执行而不是在本地执行:
  1. import ray
  2. ray.init()
  3. import numpy as np
  4. print (np.__file__)
复制代码
返回的日志为:
  1. $ RAY_ADDRESS='http://xxx.xxx.xxx.xxx:8265' ray job submit --working-dir . -- python test_ray.py
  2. Job submission server address: http://xxx.xxx.xxx.xxx:8265
  3. 2024-08-27 07:46:10,645 INFO dashboard_sdk.py:338 -- Uploading package gcs://_ray_pkg_5bba1a7144beb522.zip.
  4. 2024-08-27 07:46:10,658 INFO packaging.py:518 -- Creating a file package for local directory '.'.
  5. -------------------------------------------------------
  6. Job 'raysubmit_kQ3XgE4Hxp3dkmuU' submitted successfully
  7. -------------------------------------------------------
  8. Next steps
  9.   Query the logs of the job:
  10.     ray job logs raysubmit_kQ3XgE4Hxp3dkmuU
  11.   Query the status of the job:
  12.     ray job status raysubmit_kQ3XgE4Hxp3dkmuU
  13.   Request the job to be stopped:
  14.     ray job stop raysubmit_kQ3XgE4Hxp3dkmuU
  15. Tailing logs until the job exits (disable with --no-wait):
  16. 2024-08-27 15:46:12,456 INFO worker.py:1330 -- Using address xxx.xxx.xxx.xxx:6379 set in the environment variable RAY_ADDRESS
  17. 2024-08-27 15:46:12,457 INFO worker.py:1458 -- Connecting to existing Ray cluster at address: xxx.xxx.xxx.xxx:6379...
  18. 2024-08-27 15:46:12,470 INFO worker.py:1639 -- Connected to Ray cluster. View the dashboard at http://xxx.xxx.xxx.xxx:8265
  19. /home/dechin/anaconda3/envs/mindspore-latest/lib/python3.7/site-packages/numpy/__init__.py
  20. ------------------------------------------
  21. Job 'raysubmit_kQ3XgE4Hxp3dkmuU' succeeded
  22. ------------------------------------------
  23. $ python3 -m pip show numpy
  24. Name: numpy
  25. Version: 1.21.6
  26. Summary: NumPy is the fundamental package for array computing with Python.
  27. Home-page: https://www.numpy.org
  28. Author: Travis E. Oliphant et al.
  29. Author-email:
  30. License: BSD
  31. Location: /usr/local/python-3.7.5/lib/python3.7/site-packages
  32. Requires:
  33. Required-by: CyFES, h5py, hadder, matplotlib, mindinsight, mindspore, mindspore-serving, pandas, ray, scikit-learn, scipy
复制代码
这里可以看到,提交的任务中numpy是保存在mindspore-latest虚拟环境中的,而本地的numpy不在虚拟环境中,说明任务确实是在远程执行的。类似的可以在dashboard上面看到提交日志:

接下来测试一下分布式框架ray的并发特性:
  1. import ray
  2. ray.init()
  3. @ray.remote(num_returns=1)
  4. def cpu_task():
  5.     import time
  6.     time.sleep(2)
  7.     import numpy as np
  8.     nums = 100000
  9.     arr = np.random.random((2, nums))
  10.     arr2 = arr[1]**2 + arr[0]**2
  11.     pi = np.where(arr2<=1, 1, 0).sum() * 4 / nums
  12.     return pi
  13. num_conc = 10
  14. res = ray.get([cpu_task.remote() for _ in range(num_conc)])
  15. print (sum(res) / num_conc)
复制代码
这个案例的内容是用蒙特卡洛算法计算圆周率的值,一次提交10个任务,每个任务中撒点100000个,并休眠2s。那么如果是顺序执行的话,理论上需要休眠20s。而这里提交任务之后,输出如下:
  1. $ time RAY_ADDRESS='http://xxx.xxx.xxx.xxx:8265' ray job submit --working-dir . --entrypoint-num-cpus 10 -- python te
  2. st_ray.py
  3. Job submission server address: http://xxx.xxx.xxx.xxx:8265
  4. 2024-08-27 08:30:13,315 INFO dashboard_sdk.py:385 -- Package gcs://_ray_pkg_d66b052eb6944465.zip already exists, skipping upload.
  5. -------------------------------------------------------
  6. Job 'raysubmit_Ur6MAvP7DYiCT6Uz' submitted successfully
  7. -------------------------------------------------------
  8. Next steps
  9.   Query the logs of the job:
  10.     ray job logs raysubmit_Ur6MAvP7DYiCT6Uz
  11.   Query the status of the job:
  12.     ray job status raysubmit_Ur6MAvP7DYiCT6Uz
  13.   Request the job to be stopped:
  14.     ray job stop raysubmit_Ur6MAvP7DYiCT6Uz
  15. Tailing logs until the job exits (disable with --no-wait):
  16. 2024-08-27 16:30:15,032 INFO worker.py:1330 -- Using address xxx.xxx.xxx.xxx:6379 set in the environment variable RAY_ADDRESS
  17. 2024-08-27 16:30:15,033 INFO worker.py:1458 -- Connecting to existing Ray cluster at address: xxx.xxx.xxx.xxx:6379...
  18. 2024-08-27 16:30:15,058 INFO worker.py:1639 -- Connected to Ray cluster. View the dashboard at http://xxx.xxx.xxx.xxx:8265
  19. 3.141656
  20. ------------------------------------------
  21. Job 'raysubmit_Ur6MAvP7DYiCT6Uz' succeeded
  22. ------------------------------------------
  23. real    0m7.656s
  24. user    0m0.414s
  25. sys     0m0.010s
复制代码
总的运行时间在7.656秒,其中5s左右的时间是来自网络delay。所以实际上并发之后的总运行时间就在2s左右,跟单任务休眠的时间差不多。也就是说,远程提交的任务确实是并发执行的。最终返回的结果进行加和处理,得到的圆周率估计为:
  1. 3.141656
复制代码
。而且除了普通的CPU任务之外,还可以上传GPU任务:
  1. import ray
  2. ray.init()
  3. @ray.remote(num_returns=1, num_gpus=1)
  4. def test_ms():
  5.     import os
  6.     os.environ['GLOG_v']='4'
  7.     os.environ['CUDA_VISIBLE_DEVICE']='0'
  8.     import mindspore as ms
  9.     ms.set_context(device_target="GPU", device_id=0)
  10.     a = ms.Tensor([1, 2, 3], ms.float32)
  11.     return a.asnumpy().sum()
  12. res = ray.get(test_ms.remote())
  13. ray.shutdown()
  14. print (res)
复制代码
这个任务是用mindspore简单创建了一个Tensor,并计算了Tensor的总和返回给本地,输出内容为:
  1. $ RAY_ADDRESS='http://xxx.xxx.xxx.xxx:8265' ray job submit --working-dir . --entrypoint-num-gpus 1 -- python test_ray.py Job submission server address: http://xxx.xxx.xxx.xxx:82652024-08-28 01:16:38,712 INFO dashboard_sdk.py:338 -- Uploading package gcs://_ray_pkg_10019cd9fa9bdc38.zip.2024-08-28 01:16:38,712 INFO packaging.py:518 -- Creating a file package for local directory '.'.
  2. -------------------------------------------------------Job 'raysubmit_RUvkEqnkjNitKmnJ' submitted successfully-------------------------------------------------------
  3. Next steps  Query the logs of the job:    ray job logs raysubmit_RUvkEqnkjNitKmnJ  Query the status of the job:    ray job status raysubmit_RUvkEqnkjNitKmnJ  Request the job to be stopped:    ray job stop raysubmit_RUvkEqnkjNitKmnJ
  4. Tailing logs until the job exits (disable with --no-wait):2024-08-28 09:16:41,960 INFO worker.py:1330 -- Using address xxx.xxx.xxx.xxx:6379 set in the environment variable RAY_ADDRESS2024-08-28 09:16:41,960 INFO worker.py:1458 -- Connecting to existing Ray cluster at address: xxx.xxx.xxx.xxx:6379...2024-08-28 09:16:41,974 INFO worker.py:1639 -- Connected to Ray cluster. View the dashboard at http://xxx.xxx.xxx.xxx:8265 6.0
  5. ------------------------------------------Job 'raysubmit_RUvkEqnkjNitKmnJ' succeeded------------------------------------------
复制代码
返回的计算结果是6.0,那么也是正确的。

查看和管理任务

前面的任务输出信息中,都有相应的job_id,我们可以根据这个job_id在主节点上面查看相关任务的执行情况:
  1. $ ray job status raysubmit_RUvkEqnkjNitKmnJ
复制代码
可以查看该任务的输出内容:
  1. $ ray job logs raysubmit_RUvkEqnkjNitKmnJ
复制代码
还可以终止该任务的运行:
  1. $ ray job stop raysubmit_RUvkEqnkjNitKmnJ
复制代码
总结概要

本文介绍了基于Python的分布式框架Ray的基本安装与使用。Ray框架下不仅可以通过conda和Python十分方便的构建一个集群,还可以自动的对分布式任务进行并发处理,且支持GPU分布式任务的提交,极大的简化了手动分布式开发的工作量。

版权声明

本文首发链接为:https://www.cnblogs.com/dechinphy/p/ray.html
作者ID:DechinPhy
更多原著文章:https://www.cnblogs.com/dechinphy/
请博主喝咖啡:https://www.cnblogs.com/dechinphy/gallery/image/379634.html
到此这篇关于Python中的分布式框架Ray的安装与使用教程的文章就介绍到这了,更多相关Python 分布式框架Ray内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

来源:https://www.jb51.net/python/326631kdo.htm
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具