使用 uv 进行 KubeRay 中的 Python 包管理#

uv 是一个用 Rust 编写的现代 Python 包管理器。

从 Ray 2.45 开始,rayproject/ray:2.45.0 镜像包含了 uv 作为其依赖之一。本指南提供了一个在 KubeRay 上使用 uv 管理 Python 依赖的简单示例。

要了解有关 Ray 中 uv 集成的更多信息,请参阅

示例#

步骤 1:创建 Kind 集群#

kind create cluster

步骤 2:安装 KubeRay operator#

按照 KubeRay Operator 安装,通过 Helm 仓库安装最新的稳定版 KubeRay Operator。

步骤 3:创建启用了 uv 的 RayCluster#

ray-cluster.uv.yaml YAML 文件包含一个 RayCluster 自定义资源和一个包含示例 Ray Python 脚本的 ConfigMap。

  • RAY_RUNTIME_ENV_HOOK 功能标志启用了 Ray 中 uv 的集成。未来版本可能会默认启用此功能。

    env:
    - name: RAY_RUNTIME_ENV_HOOK
      value: ray._private.runtime_env.uv_runtime_env_hook.hook
    
  • sample_code.py 是一个简单的 Ray Python 脚本,它使用了 emoji 包。

    import emoji
    import ray
    
    @ray.remote
    def f():
        return emoji.emojize('Python is :thumbs_up:')
    
    # Execute 10 copies of f across a cluster.
    print(ray.get([f.remote() for _ in range(10)]))
    
kubectl apply -f https://raw.githubusercontent.com/ray-project/kuberay/master/ray-operator/config/samples/ray-cluster.uv.yaml

步骤 4:使用 uv 执行 Ray Python 脚本#

export HEAD_POD=$(kubectl get pods --selector=ray.io/node-type=head -o custom-columns=POD:metadata.name --no-headers)
kubectl exec -it $HEAD_POD -- /bin/bash -c "cd samples && uv run --with emoji /home/ray/samples/sample_code.py"

# [Example output]:
#
# Installed 1 package in 1ms
# 2025-06-01 14:49:15,021 INFO worker.py:1554 -- Using address 127.0.0.1:6379 set in the environment variable RAY_ADDRESS
# 2025-06-01 14:49:15,024 INFO worker.py:1694 -- Connecting to existing Ray cluster at address: 10.244.0.6:6379...
# 2025-06-01 14:49:15,035 INFO worker.py:1879 -- Connected to Ray cluster. View the dashboard at 10.244.0.6:8265
# 2025-06-01 14:49:15,040 INFO packaging.py:576 -- Creating a file package for local module '/home/ray/samples'.
# 2025-06-01 14:49:15,041 INFO packaging.py:368 -- Pushing file package 'gcs://_ray_pkg_d4da2ce33cf6d176.zip' (0.00MiB) to Ray cluster...
# 2025-06-01 14:49:15,042 INFO packaging.py:381 -- Successfully pushed file package 'gcs://_ray_pkg_d4da2ce33cf6d176.zip'.
# ['Python is 👍', 'Python is 👍', 'Python is 👍', 'Python is 👍', 'Python is 👍', 'Python is 👍', 'Python is 👍', 'Python is 👍', 'Python is 👍', 'Python is 👍']

注意:使用 /bin/bash -c 在更改当前目录到 /home/ray/samples 的同时执行命令。默认情况下,working_dir 设置为当前目录。这可以防止上传 /home/ray 下的所有文件,因为在执行 uv run 时这可能会花费很长时间。或者,您可以使用 ray job submit --runtime-env-json ... 手动指定 working_dir