Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +5 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/__pycache__/data_batch_type.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/__pycache__/result.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/__pycache__/session.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/__pycache__/__init__.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/__pycache__/config.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/__pycache__/filelock.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/__pycache__/json.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/__pycache__/mlflow.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/__pycache__/tensorflow_utils.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/__pycache__/torch_utils.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/__pycache__/uri_utils.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/__pycache__/usage.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/__pycache__/util.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/device_manager/__init__.py +92 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/device_manager/__pycache__/__init__.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/device_manager/__pycache__/cpu.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/device_manager/__pycache__/hpu.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/device_manager/__pycache__/npu.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/device_manager/__pycache__/nvidia_gpu.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/device_manager/__pycache__/torch_device_manager.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/device_manager/cpu.py +30 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/device_manager/hpu.py +50 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/device_manager/npu.py +104 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/device_manager/nvidia_gpu.py +79 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/device_manager/torch_device_manager.py +40 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/examples/__pycache__/__init__.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/examples/__pycache__/custom_trainer.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/__pycache__/__init__.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/_internal/__init__.py +5 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/_internal/__pycache__/__init__.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/_internal/__pycache__/actor_manager.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/_internal/__pycache__/barrier.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/_internal/__pycache__/event_manager.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/_internal/__pycache__/tracked_actor.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/_internal/__pycache__/tracked_actor_task.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/_internal/actor_manager.py +894 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/_internal/barrier.py +93 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/_internal/event_manager.py +148 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/_internal/tracked_actor.py +54 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/_internal/tracked_actor_task.py +42 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/resources/__init__.py +12 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/resources/__pycache__/__init__.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/resources/__pycache__/fixed.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/resources/__pycache__/placement_group.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/resources/__pycache__/request.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/resources/__pycache__/resource_manager.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/resources/fixed.py +147 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/resources/placement_group.py +214 -0
- tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/resources/request.py +255 -0
.gitattributes
CHANGED
|
@@ -4438,3 +4438,8 @@ tool_server/.venv/lib/python3.12/site-packages/ray/_private/runtime_env/agent/th
|
|
| 4438 |
tool_server/.venv/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/reader_c.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 4439 |
tool_server/.venv/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/idna/__pycache__/uts46data.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 4440 |
tool_server/.venv/lib/python3.12/site-packages/ray/_private/thirdparty/pynvml/__pycache__/pynvml.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4438 |
tool_server/.venv/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/reader_c.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 4439 |
tool_server/.venv/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/idna/__pycache__/uts46data.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 4440 |
tool_server/.venv/lib/python3.12/site-packages/ray/_private/thirdparty/pynvml/__pycache__/pynvml.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 4441 |
+
tool_server/.venv/lib/python3.12/site-packages/ray/core/src/ray/gcs/gcs_server filter=lfs diff=lfs merge=lfs -text
|
| 4442 |
+
tool_server/.venv/lib/python3.12/site-packages/ray/core/src/ray/raylet/raylet filter=lfs diff=lfs merge=lfs -text
|
| 4443 |
+
tool_server/.venv/lib/python3.12/site-packages/ray/dag/__pycache__/compiled_dag_node.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 4444 |
+
tool_server/.venv/lib/python3.12/site-packages/ray/data/__pycache__/dataset.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 4445 |
+
tool_server/.venv/lib/python3.12/site-packages/ray/data/__pycache__/read_api.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/__pycache__/data_batch_type.cpython-312.pyc
ADDED
|
Binary file (454 Bytes). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/__pycache__/result.cpython-312.pyc
ADDED
|
Binary file (13.3 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/__pycache__/session.cpython-312.pyc
ADDED
|
Binary file (225 Bytes). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (187 Bytes). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/__pycache__/config.cpython-312.pyc
ADDED
|
Binary file (1.97 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/__pycache__/filelock.cpython-312.pyc
ADDED
|
Binary file (2.86 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/__pycache__/json.cpython-312.pyc
ADDED
|
Binary file (1.9 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/__pycache__/mlflow.cpython-312.pyc
ADDED
|
Binary file (14.2 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/__pycache__/tensorflow_utils.cpython-312.pyc
ADDED
|
Binary file (7.04 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/__pycache__/torch_utils.cpython-312.pyc
ADDED
|
Binary file (23.9 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/__pycache__/uri_utils.cpython-312.pyc
ADDED
|
Binary file (5.77 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/__pycache__/usage.cpython-312.pyc
ADDED
|
Binary file (10.4 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/__pycache__/util.cpython-312.pyc
ADDED
|
Binary file (6.33 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/device_manager/__init__.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import threading
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
import ray
|
| 6 |
+
import ray._private.ray_constants as ray_constants
|
| 7 |
+
from ray.air._internal.device_manager.cpu import CPUTorchDeviceManager
|
| 8 |
+
from ray.air._internal.device_manager.hpu import HPUTorchDeviceManager
|
| 9 |
+
from ray.air._internal.device_manager.npu import NPUTorchDeviceManager
|
| 10 |
+
from ray.air._internal.device_manager.nvidia_gpu import CUDATorchDeviceManager
|
| 11 |
+
from ray.air._internal.device_manager.torch_device_manager import TorchDeviceManager
|
| 12 |
+
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
DEFAULT_TORCH_DEVICE_MANAGER_CLS = CPUTorchDeviceManager
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
SUPPORTED_ACCELERATOR_TORCH_DEVICE_MANAGER = {
|
| 20 |
+
ray_constants.GPU: CUDATorchDeviceManager,
|
| 21 |
+
ray_constants.HPU: HPUTorchDeviceManager,
|
| 22 |
+
ray_constants.NPU: NPUTorchDeviceManager,
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def register_custom_torch_dist_backend(backend: Optional[str] = None) -> None:
|
| 27 |
+
if backend == "hccl":
|
| 28 |
+
# The name for the communication backend of Habana and torch-npu is the same.
|
| 29 |
+
HPUTorchDeviceManager.register_custom_torch_dist_backend()
|
| 30 |
+
|
| 31 |
+
NPUTorchDeviceManager.register_custom_torch_dist_backend()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
_torch_device_manager = None
|
| 35 |
+
_torch_device_manager_lock = threading.Lock()
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def get_torch_device_manager_by_context() -> TorchDeviceManager:
|
| 39 |
+
global _torch_device_manager
|
| 40 |
+
|
| 41 |
+
with _torch_device_manager_lock:
|
| 42 |
+
if not _torch_device_manager:
|
| 43 |
+
existing_device_manager_cls = None
|
| 44 |
+
resources = ray.get_runtime_context().get_accelerator_ids()
|
| 45 |
+
|
| 46 |
+
# select correct accelerator type from resources
|
| 47 |
+
for resource_type, resource_value in resources.items():
|
| 48 |
+
device_manager_cls = SUPPORTED_ACCELERATOR_TORCH_DEVICE_MANAGER.get(
|
| 49 |
+
resource_type, None
|
| 50 |
+
)
|
| 51 |
+
if resource_value and device_manager_cls:
|
| 52 |
+
# An error will raise when multiple accelerators are specified.
|
| 53 |
+
if existing_device_manager_cls:
|
| 54 |
+
raise RuntimeError(
|
| 55 |
+
"Unable to determine the appropriate DeviceManager "
|
| 56 |
+
f"for the specified resources {resources}."
|
| 57 |
+
)
|
| 58 |
+
else:
|
| 59 |
+
existing_device_manager_cls = device_manager_cls
|
| 60 |
+
|
| 61 |
+
device_manager_cls = (
|
| 62 |
+
existing_device_manager_cls or DEFAULT_TORCH_DEVICE_MANAGER_CLS
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
_torch_device_manager = device_manager_cls()
|
| 66 |
+
|
| 67 |
+
return _torch_device_manager
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def get_torch_device_manager_by_device_type(device_type: str):
|
| 71 |
+
if device_type.lower() == ray_constants.GPU.lower() or device_type == "cuda":
|
| 72 |
+
return CUDATorchDeviceManager()
|
| 73 |
+
elif device_type.lower() == ray_constants.NPU.lower():
|
| 74 |
+
return NPUTorchDeviceManager()
|
| 75 |
+
elif device_type.lower() == ray_constants.HPU.lower():
|
| 76 |
+
return HPUTorchDeviceManager()
|
| 77 |
+
elif device_type.lower() == "cpu":
|
| 78 |
+
return CPUTorchDeviceManager()
|
| 79 |
+
|
| 80 |
+
raise RuntimeError(f"Device type {device_type} cannot be recognized.")
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
__all__ = [
|
| 84 |
+
TorchDeviceManager,
|
| 85 |
+
CPUTorchDeviceManager,
|
| 86 |
+
CUDATorchDeviceManager,
|
| 87 |
+
HPUTorchDeviceManager,
|
| 88 |
+
NPUTorchDeviceManager,
|
| 89 |
+
register_custom_torch_dist_backend,
|
| 90 |
+
get_torch_device_manager_by_context,
|
| 91 |
+
get_torch_device_manager_by_device_type,
|
| 92 |
+
]
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/device_manager/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (3.49 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/device_manager/__pycache__/cpu.cpython-312.pyc
ADDED
|
Binary file (1.82 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/device_manager/__pycache__/hpu.cpython-312.pyc
ADDED
|
Binary file (2.82 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/device_manager/__pycache__/npu.cpython-312.pyc
ADDED
|
Binary file (5.1 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/device_manager/__pycache__/nvidia_gpu.cpython-312.pyc
ADDED
|
Binary file (4.2 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/device_manager/__pycache__/torch_device_manager.cpython-312.pyc
ADDED
|
Binary file (2.25 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/device_manager/cpu.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from contextlib import contextmanager
|
| 2 |
+
from typing import List
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from ray.air._internal.device_manager.torch_device_manager import TorchDeviceManager
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class CPUTorchDeviceManager(TorchDeviceManager):
|
| 10 |
+
"""CPU device manager"""
|
| 11 |
+
|
| 12 |
+
def is_available(self) -> bool():
|
| 13 |
+
return True
|
| 14 |
+
|
| 15 |
+
def get_devices(self) -> List[torch.device]:
|
| 16 |
+
"""Gets the correct torch device list configured for this process."""
|
| 17 |
+
return [torch.device("cpu")]
|
| 18 |
+
|
| 19 |
+
def supports_stream(self) -> bool:
|
| 20 |
+
"""Validate if the device type support create a stream"""
|
| 21 |
+
return False
|
| 22 |
+
|
| 23 |
+
def get_stream_context(self, stream):
|
| 24 |
+
"""Return empty context mananger for CPU."""
|
| 25 |
+
|
| 26 |
+
@contextmanager
|
| 27 |
+
def default_context_manager():
|
| 28 |
+
yield
|
| 29 |
+
|
| 30 |
+
return default_context_manager()
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/device_manager/hpu.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from contextlib import contextmanager
|
| 2 |
+
from typing import List, Union
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from ray._private.accelerators.hpu import HPU_PACKAGE_AVAILABLE
|
| 7 |
+
from ray.air._internal.device_manager.torch_device_manager import TorchDeviceManager
|
| 8 |
+
|
| 9 |
+
if HPU_PACKAGE_AVAILABLE:
|
| 10 |
+
import habana_frameworks.torch.hpu as torch_hpu
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class HPUTorchDeviceManager(TorchDeviceManager):
|
| 14 |
+
"""HPU device manager"""
|
| 15 |
+
|
| 16 |
+
@staticmethod
|
| 17 |
+
def register_custom_torch_dist_backend():
|
| 18 |
+
if HPU_PACKAGE_AVAILABLE:
|
| 19 |
+
import habana_frameworks.torch.core # noqa: F401
|
| 20 |
+
import habana_frameworks.torch.distributed.hccl # noqa: F401
|
| 21 |
+
|
| 22 |
+
def is_available(self) -> bool():
|
| 23 |
+
if not HPU_PACKAGE_AVAILABLE:
|
| 24 |
+
return False
|
| 25 |
+
|
| 26 |
+
return torch_hpu.is_available()
|
| 27 |
+
|
| 28 |
+
def get_devices(self) -> List[torch.device]:
|
| 29 |
+
if not self.is_available():
|
| 30 |
+
raise RuntimeError(
|
| 31 |
+
"Using HPUTorchDeviceManager but torch hpu is not available."
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
return [torch.device("hpu")]
|
| 35 |
+
|
| 36 |
+
def set_device(self, device: Union[torch.device, int, str, None]):
|
| 37 |
+
torch_hpu.set_device(device)
|
| 38 |
+
|
| 39 |
+
def supports_stream(self) -> bool:
|
| 40 |
+
"""Validate if the device type support create a stream"""
|
| 41 |
+
return False
|
| 42 |
+
|
| 43 |
+
def get_stream_context(self, stream):
|
| 44 |
+
"""Get HPU stream context manager, empty so far."""
|
| 45 |
+
|
| 46 |
+
@contextmanager
|
| 47 |
+
def default_context_manager():
|
| 48 |
+
yield
|
| 49 |
+
|
| 50 |
+
return default_context_manager()
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/device_manager/npu.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from importlib.util import find_spec
|
| 3 |
+
from typing import List, Union
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
import ray
|
| 8 |
+
import ray._private.ray_constants as ray_constants
|
| 9 |
+
from ray.air._internal.device_manager.torch_device_manager import TorchDeviceManager
|
| 10 |
+
from ray._private.accelerators.npu import ASCEND_RT_VISIBLE_DEVICES_ENV_VAR
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def is_package_present(package_name: str) -> bool:
|
| 14 |
+
try:
|
| 15 |
+
return find_spec(package_name) is not None
|
| 16 |
+
except ModuleNotFoundError:
|
| 17 |
+
return False
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
NPU_TORCH_PACKAGE_AVAILABLE = is_package_present("torch_npu")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
if NPU_TORCH_PACKAGE_AVAILABLE:
|
| 24 |
+
import torch_npu # noqa: F401
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class NPUTorchDeviceManager(TorchDeviceManager):
|
| 28 |
+
"""Ascend NPU device manager"""
|
| 29 |
+
|
| 30 |
+
@staticmethod
|
| 31 |
+
def register_custom_torch_dist_backend():
|
| 32 |
+
if NPU_TORCH_PACKAGE_AVAILABLE:
|
| 33 |
+
import torch_npu # noqa: F401, F811
|
| 34 |
+
|
| 35 |
+
def is_available(self) -> bool:
|
| 36 |
+
if not NPU_TORCH_PACKAGE_AVAILABLE:
|
| 37 |
+
return False
|
| 38 |
+
|
| 39 |
+
return torch.npu.is_available()
|
| 40 |
+
|
| 41 |
+
def get_devices(self) -> List[torch.device]:
|
| 42 |
+
"""Gets the correct torch device list configured for this process.
|
| 43 |
+
|
| 44 |
+
Returns a list of torch NPU devices allocated for the current worker.
|
| 45 |
+
If no NPUs are assigned, then it returns a list with a single CPU device.
|
| 46 |
+
"""
|
| 47 |
+
if NPU_TORCH_PACKAGE_AVAILABLE and torch.npu.is_available():
|
| 48 |
+
npu_ids = [
|
| 49 |
+
str(id)
|
| 50 |
+
for id in ray.get_runtime_context().get_accelerator_ids()[
|
| 51 |
+
ray_constants.NPU
|
| 52 |
+
]
|
| 53 |
+
]
|
| 54 |
+
|
| 55 |
+
device_ids = []
|
| 56 |
+
|
| 57 |
+
if len(npu_ids) > 0:
|
| 58 |
+
npu_visible_str = os.environ.get(ASCEND_RT_VISIBLE_DEVICES_ENV_VAR, "")
|
| 59 |
+
if npu_visible_str and npu_visible_str != "NoDevFiles":
|
| 60 |
+
npu_visible_list = npu_visible_str.split(",")
|
| 61 |
+
else:
|
| 62 |
+
npu_visible_list = []
|
| 63 |
+
|
| 64 |
+
for npu_id in npu_ids:
|
| 65 |
+
try:
|
| 66 |
+
device_ids.append(npu_visible_list.index(npu_id))
|
| 67 |
+
except IndexError:
|
| 68 |
+
raise RuntimeError(
|
| 69 |
+
"ASCEND_RT_VISIBLE_DEVICES set incorrectly. "
|
| 70 |
+
f"Got {npu_visible_str}, expected to include {npu_id}. "
|
| 71 |
+
"Did you override the `ASCEND_RT_VISIBLE_DEVICES` "
|
| 72 |
+
"environment variable?"
|
| 73 |
+
)
|
| 74 |
+
else:
|
| 75 |
+
# If called on the driver or outside of Ray Train, return the
|
| 76 |
+
# 0th device.
|
| 77 |
+
device_ids.append(0)
|
| 78 |
+
|
| 79 |
+
devices = [torch.device(f"npu:{device_id}") for device_id in device_ids]
|
| 80 |
+
else:
|
| 81 |
+
raise RuntimeError(
|
| 82 |
+
"Using NPUTorchDeviceManager but torch npu is not available."
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
return devices
|
| 86 |
+
|
| 87 |
+
def set_device(self, device: Union[torch.device, int]):
|
| 88 |
+
torch.npu.set_device(device)
|
| 89 |
+
|
| 90 |
+
def supports_stream(self) -> bool:
|
| 91 |
+
"""Validate if the device type support to create a stream"""
|
| 92 |
+
return True
|
| 93 |
+
|
| 94 |
+
def create_stream(self, device):
|
| 95 |
+
"""Create a stream on NPU device"""
|
| 96 |
+
return torch.npu.Stream(device)
|
| 97 |
+
|
| 98 |
+
def get_stream_context(self, stream):
|
| 99 |
+
"""Get a torch.stream context on NPU device"""
|
| 100 |
+
return torch.npu.stream(stream)
|
| 101 |
+
|
| 102 |
+
def get_current_stream(self):
|
| 103 |
+
"""Get current stream for NPU device"""
|
| 104 |
+
return torch.npu.current_stream()
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/device_manager/nvidia_gpu.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from typing import List, Union
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
import ray
|
| 7 |
+
from ray.air._internal.device_manager.torch_device_manager import TorchDeviceManager
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class CUDATorchDeviceManager(TorchDeviceManager):
|
| 11 |
+
"""CUDA device manager"""
|
| 12 |
+
|
| 13 |
+
def is_available(self) -> bool():
|
| 14 |
+
return torch.cuda.is_available()
|
| 15 |
+
|
| 16 |
+
def get_devices(self) -> List[torch.device]:
|
| 17 |
+
"""Gets the correct torch device list configured for this process.
|
| 18 |
+
|
| 19 |
+
Returns a list of torch CUDA devices allocated for the current worker.
|
| 20 |
+
If no GPUs are assigned, then it returns a list with a single CPU device.
|
| 21 |
+
|
| 22 |
+
Assumes that `CUDA_VISIBLE_DEVICES` is set and is a
|
| 23 |
+
superset of the `ray.get_gpu_ids()`.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
# GPU IDs are assigned by Ray after you specify "use_gpu"
|
| 27 |
+
# GPU `ray.get_gpu_ids()` may return ints or may return strings.
|
| 28 |
+
# We should always convert to strings.
|
| 29 |
+
gpu_ids = [str(id) for id in ray.get_gpu_ids()]
|
| 30 |
+
|
| 31 |
+
device_ids = []
|
| 32 |
+
|
| 33 |
+
if len(gpu_ids) > 0:
|
| 34 |
+
cuda_visible_str = os.environ.get("CUDA_VISIBLE_DEVICES", "")
|
| 35 |
+
if cuda_visible_str and cuda_visible_str != "NoDevFiles":
|
| 36 |
+
cuda_visible_list = cuda_visible_str.split(",")
|
| 37 |
+
else:
|
| 38 |
+
cuda_visible_list = []
|
| 39 |
+
|
| 40 |
+
# By default, there should only be one GPU ID if `use_gpu=True`.
|
| 41 |
+
# If there are multiple GPUs, return a list of devices.
|
| 42 |
+
# If using fractional GPUs, these IDs are not guaranteed
|
| 43 |
+
# to be unique across different processes.
|
| 44 |
+
for gpu_id in gpu_ids:
|
| 45 |
+
try:
|
| 46 |
+
device_ids.append(cuda_visible_list.index(gpu_id))
|
| 47 |
+
except IndexError:
|
| 48 |
+
raise RuntimeError(
|
| 49 |
+
"CUDA_VISIBLE_DEVICES set incorrectly. "
|
| 50 |
+
f"Got {cuda_visible_str}, expected to include {gpu_id}. "
|
| 51 |
+
"Did you override the `CUDA_VISIBLE_DEVICES` environment"
|
| 52 |
+
" variable? If not, please help file an issue on Github."
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
else:
|
| 56 |
+
# If called on the driver or outside of Ray Train, return the
|
| 57 |
+
# 0th device.
|
| 58 |
+
device_ids.append(0)
|
| 59 |
+
|
| 60 |
+
return [torch.device(f"cuda:{device_id}") for device_id in device_ids]
|
| 61 |
+
|
| 62 |
+
def set_device(self, device: Union[torch.device, int, str, None]):
|
| 63 |
+
torch.cuda.set_device(device)
|
| 64 |
+
|
| 65 |
+
def supports_stream(self) -> bool:
|
| 66 |
+
"""Validate if the device type support create a stream"""
|
| 67 |
+
return True
|
| 68 |
+
|
| 69 |
+
def create_stream(self, device: torch.device) -> torch.cuda.Stream:
|
| 70 |
+
"""Create a stream on cuda device"""
|
| 71 |
+
return torch.cuda.Stream(device)
|
| 72 |
+
|
| 73 |
+
def get_stream_context(self, stream):
|
| 74 |
+
"""Get a stream context for cuda device"""
|
| 75 |
+
return torch.cuda.stream(stream)
|
| 76 |
+
|
| 77 |
+
def get_current_stream(self) -> torch.cuda.Stream:
|
| 78 |
+
"""Get current stream for cuda device"""
|
| 79 |
+
return torch.cuda.current_stream()
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/_internal/device_manager/torch_device_manager.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import ABC
|
| 2 |
+
from typing import List, Union
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class TorchDeviceManager(ABC):
|
| 8 |
+
"""This class contains the function needed for supporting
|
| 9 |
+
an acclerator family in Ray AI Library.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
def is_available(self) -> bool:
|
| 13 |
+
"""Validate if device is available."""
|
| 14 |
+
...
|
| 15 |
+
|
| 16 |
+
def get_devices(self) -> List[torch.device]:
|
| 17 |
+
"""Gets the correct torch device configured for this process"""
|
| 18 |
+
...
|
| 19 |
+
|
| 20 |
+
def set_device(self, device: Union[torch.device, int, str, None]):
|
| 21 |
+
"""Set the correct device for this process"""
|
| 22 |
+
...
|
| 23 |
+
|
| 24 |
+
def supports_stream(self) -> bool:
|
| 25 |
+
"""Validate if the device type support create a stream"""
|
| 26 |
+
...
|
| 27 |
+
|
| 28 |
+
def create_stream(self, device: torch.device):
|
| 29 |
+
"""Create a device stream"""
|
| 30 |
+
...
|
| 31 |
+
|
| 32 |
+
def get_stream_context(self, stream):
|
| 33 |
+
"""Get a stream context of device. If device didn't support stream,
|
| 34 |
+
this should return a empty context manager instead of None.
|
| 35 |
+
"""
|
| 36 |
+
...
|
| 37 |
+
|
| 38 |
+
def get_current_stream(self):
|
| 39 |
+
"""Get current stream on accelerators like torch.cuda.current_stream"""
|
| 40 |
+
...
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/examples/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (186 Bytes). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/examples/__pycache__/custom_trainer.cpython-312.pyc
ADDED
|
Binary file (2.5 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (606 Bytes). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/_internal/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ray.air.execution._internal.actor_manager import RayActorManager
|
| 2 |
+
from ray.air.execution._internal.barrier import Barrier
|
| 3 |
+
from ray.air.execution._internal.tracked_actor import TrackedActor
|
| 4 |
+
|
| 5 |
+
__all__ = ["Barrier", "RayActorManager", "TrackedActor"]
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/_internal/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (467 Bytes). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/_internal/__pycache__/actor_manager.cpython-312.pyc
ADDED
|
Binary file (34.4 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/_internal/__pycache__/barrier.cpython-312.pyc
ADDED
|
Binary file (4.02 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/_internal/__pycache__/event_manager.cpython-312.pyc
ADDED
|
Binary file (6.49 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/_internal/__pycache__/tracked_actor.cpython-312.pyc
ADDED
|
Binary file (2.85 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/_internal/__pycache__/tracked_actor_task.cpython-312.pyc
ADDED
|
Binary file (1.79 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/_internal/actor_manager.py
ADDED
|
@@ -0,0 +1,894 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import random
|
| 3 |
+
import time
|
| 4 |
+
import uuid
|
| 5 |
+
from collections import Counter, defaultdict
|
| 6 |
+
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Type, Union
|
| 7 |
+
|
| 8 |
+
import ray
|
| 9 |
+
from ray.air.execution._internal.event_manager import RayEventManager
|
| 10 |
+
from ray.air.execution._internal.tracked_actor import TrackedActor
|
| 11 |
+
from ray.air.execution._internal.tracked_actor_task import TrackedActorTask
|
| 12 |
+
from ray.air.execution.resources import (
|
| 13 |
+
AcquiredResources,
|
| 14 |
+
ResourceManager,
|
| 15 |
+
ResourceRequest,
|
| 16 |
+
)
|
| 17 |
+
from ray.exceptions import RayActorError, RayTaskError
|
| 18 |
+
|
| 19 |
+
logger = logging.getLogger(__name__)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class RayActorManager:
|
| 23 |
+
"""Management class for Ray actors and actor tasks.
|
| 24 |
+
|
| 25 |
+
This class provides an event-based management interface for actors, and
|
| 26 |
+
actor tasks.
|
| 27 |
+
|
| 28 |
+
The manager can be used to start actors, stop actors, and schedule and
|
| 29 |
+
track task futures on these actors.
|
| 30 |
+
The manager will then invoke callbacks related to the tracked entities.
|
| 31 |
+
|
| 32 |
+
For instance, when an actor is added with
|
| 33 |
+
:meth:`add_actor() <RayActorManager.add_actor>`,
|
| 34 |
+
a :ref:`TrackedActor <ray.air.execution._internal.tracked_actor.TrackedActor`
|
| 35 |
+
object is returned. An ``on_start`` callback can be specified that is invoked
|
| 36 |
+
once the actor successfully started. Similarly, ``on_stop`` and ``on_error``
|
| 37 |
+
can be used to specify callbacks relating to the graceful or ungraceful
|
| 38 |
+
end of an actor's lifetime.
|
| 39 |
+
|
| 40 |
+
When scheduling an actor task using
|
| 41 |
+
:meth:`schedule_actor_task()
|
| 42 |
+
<ray.air.execution._internal.actor_manager.RayActorManager.schedule_actor_task>`,
|
| 43 |
+
an ``on_result`` callback can be specified that is invoked when the task
|
| 44 |
+
successfully resolves, and an ``on_error`` callback will resolve when the
|
| 45 |
+
task fails.
|
| 46 |
+
|
| 47 |
+
The RayActorManager does not implement any true asynchronous processing. Control
|
| 48 |
+
has to be explicitly yielded to the event manager via :meth:`RayActorManager.next`.
|
| 49 |
+
Callbacks will only be invoked when control is with the RayActorManager, and
|
| 50 |
+
callbacks will always be executed sequentially in order of arriving events.
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
resource_manager: Resource manager used to request resources for the actors.
|
| 54 |
+
|
| 55 |
+
Example:
|
| 56 |
+
|
| 57 |
+
.. code-block:: python
|
| 58 |
+
|
| 59 |
+
from ray.air.execution import ResourceRequest
|
| 60 |
+
from ray.air.execution._internal import RayActorManager
|
| 61 |
+
|
| 62 |
+
actor_manager = RayActorManager()
|
| 63 |
+
|
| 64 |
+
# Request an actor
|
| 65 |
+
tracked_actor = actor_manager.add_actor(
|
| 66 |
+
ActorClass,
|
| 67 |
+
kwargs={},
|
| 68 |
+
resource_request=ResourceRequest([{"CPU": 1}]),
|
| 69 |
+
on_start=actor_start_callback,
|
| 70 |
+
on_stop=actor_stop_callback,
|
| 71 |
+
on_error=actor_error_callback
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
# Yield control to event manager to start actor
|
| 75 |
+
actor_manager.next()
|
| 76 |
+
|
| 77 |
+
# Start task on the actor (ActorClass.foo.remote())
|
| 78 |
+
tracked_actor_task = actor_manager.schedule_actor_task(
|
| 79 |
+
tracked_actor,
|
| 80 |
+
method_name="foo",
|
| 81 |
+
on_result=task_result_callback,
|
| 82 |
+
on_error=task_error_callback
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
# Again yield control to event manager to process task futures
|
| 86 |
+
actor_manager.wait()
|
| 87 |
+
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
def __init__(self, resource_manager: ResourceManager):
|
| 91 |
+
self._resource_manager: ResourceManager = resource_manager
|
| 92 |
+
|
| 93 |
+
self._actor_state_events = RayEventManager()
|
| 94 |
+
self._actor_task_events = RayEventManager()
|
| 95 |
+
|
| 96 |
+
# ---
|
| 97 |
+
# Tracked actor futures.
|
| 98 |
+
|
| 99 |
+
# This maps TrackedActor objects to their futures. We use this to see if an
|
| 100 |
+
# actor has any futures scheduled and to remove them when we terminate an actor.
|
| 101 |
+
|
| 102 |
+
# Actors to actor task futures
|
| 103 |
+
self._tracked_actors_to_task_futures: Dict[
|
| 104 |
+
TrackedActor, Set[ray.ObjectRef]
|
| 105 |
+
] = defaultdict(set)
|
| 106 |
+
|
| 107 |
+
# Actors to actor state futures (start/terminate)
|
| 108 |
+
self._tracked_actors_to_state_futures: Dict[
|
| 109 |
+
TrackedActor, Set[ray.ObjectRef]
|
| 110 |
+
] = defaultdict(set)
|
| 111 |
+
|
| 112 |
+
# ---
|
| 113 |
+
# Pending actors.
|
| 114 |
+
# We use three dicts for actors that are requested but not yet started.
|
| 115 |
+
|
| 116 |
+
# This dict keeps a list of actors associated with each resource request.
|
| 117 |
+
# We use this to start actors in the correct order when their resources
|
| 118 |
+
# become available.
|
| 119 |
+
self._resource_request_to_pending_actors: Dict[
|
| 120 |
+
ResourceRequest, List[TrackedActor]
|
| 121 |
+
] = defaultdict(list)
|
| 122 |
+
|
| 123 |
+
# This dict stores the actor class, kwargs, and resource request of
|
| 124 |
+
# pending actors. Once the resources are available, we start the remote
|
| 125 |
+
# actor class with its args. We need the resource request to cancel it
|
| 126 |
+
# if needed.
|
| 127 |
+
self._pending_actors_to_attrs: Dict[
|
| 128 |
+
TrackedActor, Tuple[Type, Dict[str, Any], ResourceRequest]
|
| 129 |
+
] = {}
|
| 130 |
+
|
| 131 |
+
# This dict keeps track of cached actor tasks. We can't schedule actor
|
| 132 |
+
# tasks before the actor is actually scheduled/live. So when the caller
|
| 133 |
+
# tries to schedule a task, we cache it here, and schedule it once the
|
| 134 |
+
# actor is started.
|
| 135 |
+
self._pending_actors_to_enqueued_actor_tasks: Dict[
|
| 136 |
+
TrackedActor, List[Tuple[TrackedActorTask, str, Tuple[Any], Dict[str, Any]]]
|
| 137 |
+
] = defaultdict(list)
|
| 138 |
+
|
| 139 |
+
# ---
|
| 140 |
+
# Live actors.
|
| 141 |
+
# We keep one dict for actors that are currently running and a set of
|
| 142 |
+
# actors that we should forcefully kill.
|
| 143 |
+
|
| 144 |
+
# This dict associates the TrackedActor object with the Ray actor handle
|
| 145 |
+
# and the resources associated to the actor. We use it to schedule the
|
| 146 |
+
# actual ray tasks, and to return the resources when the actor stopped.
|
| 147 |
+
self._live_actors_to_ray_actors_resources: Dict[
|
| 148 |
+
TrackedActor, Tuple[ray.actor.ActorHandle, AcquiredResources]
|
| 149 |
+
] = {}
|
| 150 |
+
self._live_resource_cache: Optional[Dict[str, Any]] = None
|
| 151 |
+
|
| 152 |
+
# This dict contains all actors that should be killed (after calling
|
| 153 |
+
# `remove_actor()`). Kill requests will be handled in wait().
|
| 154 |
+
self._live_actors_to_kill: Set[TrackedActor] = set()
|
| 155 |
+
|
| 156 |
+
# Track failed actors
|
| 157 |
+
self._failed_actor_ids: Set[int] = set()
|
| 158 |
+
|
| 159 |
+
def next(self, timeout: Optional[Union[int, float]] = None) -> bool:
|
| 160 |
+
"""Yield control to event manager to await the next event and invoke callbacks.
|
| 161 |
+
|
| 162 |
+
Calling this method will wait for up to ``timeout`` seconds for the next
|
| 163 |
+
event to arrive.
|
| 164 |
+
|
| 165 |
+
When events arrive, callbacks relating to the events will be
|
| 166 |
+
invoked. A timeout of ``None`` will block until the next event arrives.
|
| 167 |
+
|
| 168 |
+
Note:
|
| 169 |
+
If an actor task fails with a ``RayActorError``, this is one event,
|
| 170 |
+
but it may trigger _two_ `on_error` callbacks: One for the actor,
|
| 171 |
+
and one for the task.
|
| 172 |
+
|
| 173 |
+
Note:
|
| 174 |
+
The ``timeout`` argument is used for pure waiting time for events. It does
|
| 175 |
+
not include time spent on processing callbacks. Depending on the processing
|
| 176 |
+
time of the callbacks, it can take much longer for this function to
|
| 177 |
+
return than the specified timeout.
|
| 178 |
+
|
| 179 |
+
Args:
|
| 180 |
+
timeout: Timeout in seconds to wait for next event.
|
| 181 |
+
|
| 182 |
+
Returns:
|
| 183 |
+
True if at least one event was processed.
|
| 184 |
+
|
| 185 |
+
"""
|
| 186 |
+
# First issue any pending forceful actor kills
|
| 187 |
+
actor_killed = self._try_kill_actor()
|
| 188 |
+
|
| 189 |
+
# We always try to start actors as this won't trigger an event callback
|
| 190 |
+
self._try_start_actors()
|
| 191 |
+
|
| 192 |
+
# If an actor was killed, this was our event, and we return.
|
| 193 |
+
if actor_killed:
|
| 194 |
+
return True
|
| 195 |
+
|
| 196 |
+
# Otherwise, collect all futures and await the next.
|
| 197 |
+
resource_futures = self._resource_manager.get_resource_futures()
|
| 198 |
+
actor_state_futures = self._actor_state_events.get_futures()
|
| 199 |
+
actor_task_futures = self._actor_task_events.get_futures()
|
| 200 |
+
|
| 201 |
+
# Shuffle state futures
|
| 202 |
+
shuffled_state_futures = list(actor_state_futures)
|
| 203 |
+
random.shuffle(shuffled_state_futures)
|
| 204 |
+
|
| 205 |
+
# Shuffle task futures
|
| 206 |
+
shuffled_task_futures = list(actor_task_futures)
|
| 207 |
+
random.shuffle(shuffled_task_futures)
|
| 208 |
+
|
| 209 |
+
# Prioritize resource futures over actor state over task futures
|
| 210 |
+
all_futures = resource_futures + shuffled_state_futures + shuffled_task_futures
|
| 211 |
+
|
| 212 |
+
start_wait = time.monotonic()
|
| 213 |
+
ready, _ = ray.wait(all_futures, num_returns=1, timeout=timeout)
|
| 214 |
+
|
| 215 |
+
if not ready:
|
| 216 |
+
return False
|
| 217 |
+
|
| 218 |
+
[future] = ready
|
| 219 |
+
|
| 220 |
+
if future in actor_state_futures:
|
| 221 |
+
self._actor_state_events.resolve_future(future)
|
| 222 |
+
elif future in actor_task_futures:
|
| 223 |
+
self._actor_task_events.resolve_future(future)
|
| 224 |
+
else:
|
| 225 |
+
self._handle_ready_resource_future()
|
| 226 |
+
# Ready resource futures don't count as one event as they don't trigger
|
| 227 |
+
# any callbacks. So we repeat until we hit anything that is not a resource
|
| 228 |
+
# future.
|
| 229 |
+
time_taken = time.monotonic() - start_wait
|
| 230 |
+
return self.next(
|
| 231 |
+
timeout=max(1e-9, timeout - time_taken) if timeout is not None else None
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
self._try_start_actors()
|
| 235 |
+
return True
|
| 236 |
+
|
| 237 |
+
def _actor_start_resolved(self, tracked_actor: TrackedActor, future: ray.ObjectRef):
|
| 238 |
+
"""Callback to be invoked when actor started"""
|
| 239 |
+
self._tracked_actors_to_state_futures[tracked_actor].remove(future)
|
| 240 |
+
|
| 241 |
+
if tracked_actor._on_start:
|
| 242 |
+
tracked_actor._on_start(tracked_actor)
|
| 243 |
+
|
| 244 |
+
def _actor_stop_resolved(self, tracked_actor: TrackedActor):
|
| 245 |
+
"""Callback to be invoked when actor stopped"""
|
| 246 |
+
self._cleanup_actor(tracked_actor=tracked_actor)
|
| 247 |
+
|
| 248 |
+
if tracked_actor._on_stop:
|
| 249 |
+
tracked_actor._on_stop(tracked_actor)
|
| 250 |
+
|
| 251 |
+
def _actor_start_failed(self, tracked_actor: TrackedActor, exception: Exception):
|
| 252 |
+
"""Callback to be invoked when actor start/stop failed"""
|
| 253 |
+
self._failed_actor_ids.add(tracked_actor.actor_id)
|
| 254 |
+
|
| 255 |
+
self._cleanup_actor(tracked_actor=tracked_actor)
|
| 256 |
+
|
| 257 |
+
if tracked_actor._on_error:
|
| 258 |
+
tracked_actor._on_error(tracked_actor, exception)
|
| 259 |
+
|
| 260 |
+
def _actor_task_failed(
|
| 261 |
+
self, tracked_actor_task: TrackedActorTask, exception: Exception
|
| 262 |
+
):
|
| 263 |
+
"""Handle an actor task future that became ready.
|
| 264 |
+
|
| 265 |
+
- On actor error, trigger actor error callback AND error task error callback
|
| 266 |
+
- On task error, trigger actor task error callback
|
| 267 |
+
- On success, trigger actor task result callback
|
| 268 |
+
"""
|
| 269 |
+
tracked_actor = tracked_actor_task._tracked_actor
|
| 270 |
+
|
| 271 |
+
if isinstance(exception, RayActorError):
|
| 272 |
+
self._failed_actor_ids.add(tracked_actor.actor_id)
|
| 273 |
+
|
| 274 |
+
# Clean up any references to the actor and its futures
|
| 275 |
+
self._cleanup_actor(tracked_actor=tracked_actor)
|
| 276 |
+
|
| 277 |
+
# Handle actor state callbacks
|
| 278 |
+
if tracked_actor._on_error:
|
| 279 |
+
tracked_actor._on_error(tracked_actor, exception)
|
| 280 |
+
|
| 281 |
+
# Then trigger actor task error callback
|
| 282 |
+
if tracked_actor_task._on_error:
|
| 283 |
+
tracked_actor_task._on_error(tracked_actor, exception)
|
| 284 |
+
|
| 285 |
+
elif isinstance(exception, RayTaskError):
|
| 286 |
+
# Otherwise only the task failed. Invoke callback
|
| 287 |
+
if tracked_actor_task._on_error:
|
| 288 |
+
tracked_actor_task._on_error(tracked_actor, exception)
|
| 289 |
+
else:
|
| 290 |
+
raise RuntimeError(
|
| 291 |
+
f"Caught unexpected exception: {exception}"
|
| 292 |
+
) from exception
|
| 293 |
+
|
| 294 |
+
def _actor_task_resolved(self, tracked_actor_task: TrackedActorTask, result: Any):
|
| 295 |
+
tracked_actor = tracked_actor_task._tracked_actor
|
| 296 |
+
|
| 297 |
+
# Trigger actor task result callback
|
| 298 |
+
if tracked_actor_task._on_result:
|
| 299 |
+
tracked_actor_task._on_result(tracked_actor, result)
|
| 300 |
+
|
| 301 |
+
def _handle_ready_resource_future(self):
|
| 302 |
+
"""Handle a resource future that became ready.
|
| 303 |
+
|
| 304 |
+
- Update state of the resource manager
|
| 305 |
+
- Try to start one actor
|
| 306 |
+
"""
|
| 307 |
+
# Force resource manager to update internal state
|
| 308 |
+
self._resource_manager.update_state()
|
| 309 |
+
# We handle resource futures one by one, so only try to start 1 actor at a time
|
| 310 |
+
self._try_start_actors(max_actors=1)
|
| 311 |
+
|
| 312 |
+
def _try_start_actors(self, max_actors: Optional[int] = None) -> int:
|
| 313 |
+
"""Try to start up to ``max_actors`` actors.
|
| 314 |
+
|
| 315 |
+
This function will iterate through all resource requests we collected for
|
| 316 |
+
pending actors. As long as a resource request can be fulfilled (resources
|
| 317 |
+
are available), we try to start as many actors as possible.
|
| 318 |
+
|
| 319 |
+
This will schedule a `Actor.__ray_ready__()` future which, once resolved,
|
| 320 |
+
will trigger the `TrackedActor.on_start` callback.
|
| 321 |
+
"""
|
| 322 |
+
started_actors = 0
|
| 323 |
+
|
| 324 |
+
# Iterate through all resource requests
|
| 325 |
+
for resource_request in self._resource_request_to_pending_actors:
|
| 326 |
+
if max_actors is not None and started_actors >= max_actors:
|
| 327 |
+
break
|
| 328 |
+
|
| 329 |
+
# While we have resources ready and there are actors left to schedule
|
| 330 |
+
while (
|
| 331 |
+
self._resource_manager.has_resources_ready(resource_request)
|
| 332 |
+
and self._resource_request_to_pending_actors[resource_request]
|
| 333 |
+
):
|
| 334 |
+
# Acquire resources for actor
|
| 335 |
+
acquired_resources = self._resource_manager.acquire_resources(
|
| 336 |
+
resource_request
|
| 337 |
+
)
|
| 338 |
+
assert acquired_resources
|
| 339 |
+
|
| 340 |
+
# Get tracked actor to start
|
| 341 |
+
candidate_actors = self._resource_request_to_pending_actors[
|
| 342 |
+
resource_request
|
| 343 |
+
]
|
| 344 |
+
assert candidate_actors
|
| 345 |
+
|
| 346 |
+
tracked_actor = candidate_actors.pop(0)
|
| 347 |
+
|
| 348 |
+
# Get actor class and arguments
|
| 349 |
+
actor_cls, kwargs, _ = self._pending_actors_to_attrs.pop(tracked_actor)
|
| 350 |
+
|
| 351 |
+
if not isinstance(actor_cls, ray.actor.ActorClass):
|
| 352 |
+
actor_cls = ray.remote(actor_cls)
|
| 353 |
+
|
| 354 |
+
# Associate to acquired resources
|
| 355 |
+
[remote_actor_cls] = acquired_resources.annotate_remote_entities(
|
| 356 |
+
[actor_cls]
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
# Start Ray actor
|
| 360 |
+
actor = remote_actor_cls.remote(**kwargs)
|
| 361 |
+
|
| 362 |
+
# Track
|
| 363 |
+
self._live_actors_to_ray_actors_resources[tracked_actor] = (
|
| 364 |
+
actor,
|
| 365 |
+
acquired_resources,
|
| 366 |
+
)
|
| 367 |
+
self._live_resource_cache = None
|
| 368 |
+
|
| 369 |
+
# Schedule ready future
|
| 370 |
+
future = actor.__ray_ready__.remote()
|
| 371 |
+
|
| 372 |
+
self._tracked_actors_to_state_futures[tracked_actor].add(future)
|
| 373 |
+
|
| 374 |
+
# We need to create the callbacks in a function so tracked_actors
|
| 375 |
+
# are captured correctly.
|
| 376 |
+
def create_callbacks(
|
| 377 |
+
tracked_actor: TrackedActor, future: ray.ObjectRef
|
| 378 |
+
):
|
| 379 |
+
def on_actor_start(result: Any):
|
| 380 |
+
self._actor_start_resolved(
|
| 381 |
+
tracked_actor=tracked_actor, future=future
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
def on_error(exception: Exception):
|
| 385 |
+
self._actor_start_failed(
|
| 386 |
+
tracked_actor=tracked_actor, exception=exception
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
return on_actor_start, on_error
|
| 390 |
+
|
| 391 |
+
on_actor_start, on_error = create_callbacks(
|
| 392 |
+
tracked_actor=tracked_actor, future=future
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
self._actor_state_events.track_future(
|
| 396 |
+
future=future,
|
| 397 |
+
on_result=on_actor_start,
|
| 398 |
+
on_error=on_error,
|
| 399 |
+
)
|
| 400 |
+
|
| 401 |
+
self._enqueue_cached_actor_tasks(tracked_actor=tracked_actor)
|
| 402 |
+
|
| 403 |
+
started_actors += 1
|
| 404 |
+
|
| 405 |
+
return started_actors
|
| 406 |
+
|
| 407 |
+
def _enqueue_cached_actor_tasks(self, tracked_actor: TrackedActor):
|
| 408 |
+
assert tracked_actor in self._live_actors_to_ray_actors_resources
|
| 409 |
+
|
| 410 |
+
# Enqueue cached futures
|
| 411 |
+
cached_tasks = self._pending_actors_to_enqueued_actor_tasks.pop(
|
| 412 |
+
tracked_actor, []
|
| 413 |
+
)
|
| 414 |
+
for tracked_actor_task, method_name, args, kwargs in cached_tasks:
|
| 415 |
+
self._schedule_tracked_actor_task(
|
| 416 |
+
tracked_actor_task=tracked_actor_task,
|
| 417 |
+
method_name=method_name,
|
| 418 |
+
args=args,
|
| 419 |
+
kwargs=kwargs,
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
def _try_kill_actor(self) -> bool:
|
| 423 |
+
"""Try to kill actor scheduled for termination."""
|
| 424 |
+
if not self._live_actors_to_kill:
|
| 425 |
+
return False
|
| 426 |
+
|
| 427 |
+
tracked_actor = self._live_actors_to_kill.pop()
|
| 428 |
+
|
| 429 |
+
# Remove from tracked actors
|
| 430 |
+
(
|
| 431 |
+
ray_actor,
|
| 432 |
+
acquired_resources,
|
| 433 |
+
) = self._live_actors_to_ray_actors_resources[tracked_actor]
|
| 434 |
+
|
| 435 |
+
# Hard kill if requested
|
| 436 |
+
ray.kill(ray_actor)
|
| 437 |
+
|
| 438 |
+
self._cleanup_actor_futures(tracked_actor)
|
| 439 |
+
|
| 440 |
+
self._actor_stop_resolved(tracked_actor)
|
| 441 |
+
|
| 442 |
+
return True
|
| 443 |
+
|
| 444 |
+
def _cleanup_actor(self, tracked_actor: TrackedActor):
|
| 445 |
+
self._cleanup_actor_futures(tracked_actor)
|
| 446 |
+
|
| 447 |
+
# Remove from tracked actors
|
| 448 |
+
(
|
| 449 |
+
ray_actor,
|
| 450 |
+
acquired_resources,
|
| 451 |
+
) = self._live_actors_to_ray_actors_resources.pop(tracked_actor)
|
| 452 |
+
self._live_resource_cache = None
|
| 453 |
+
|
| 454 |
+
# Return resources
|
| 455 |
+
self._resource_manager.free_resources(acquired_resource=acquired_resources)
|
| 456 |
+
|
| 457 |
+
@property
|
| 458 |
+
def all_actors(self) -> List[TrackedActor]:
|
| 459 |
+
"""Return all ``TrackedActor`` objects managed by this manager instance."""
|
| 460 |
+
return self.live_actors + self.pending_actors
|
| 461 |
+
|
| 462 |
+
@property
|
| 463 |
+
def live_actors(self) -> List[TrackedActor]:
|
| 464 |
+
"""Return all ``TrackedActor`` objects that are currently alive."""
|
| 465 |
+
return list(self._live_actors_to_ray_actors_resources)
|
| 466 |
+
|
| 467 |
+
@property
|
| 468 |
+
def pending_actors(self) -> List[TrackedActor]:
|
| 469 |
+
"""Return all ``TrackedActor`` objects that are currently pending."""
|
| 470 |
+
return list(self._pending_actors_to_attrs)
|
| 471 |
+
|
| 472 |
+
@property
|
| 473 |
+
def num_live_actors(self):
|
| 474 |
+
"""Return number of started actors."""
|
| 475 |
+
return len(self.live_actors)
|
| 476 |
+
|
| 477 |
+
@property
|
| 478 |
+
def num_pending_actors(self) -> int:
|
| 479 |
+
"""Return number of pending (not yet started) actors."""
|
| 480 |
+
return len(self.pending_actors)
|
| 481 |
+
|
| 482 |
+
@property
|
| 483 |
+
def num_total_actors(self):
|
| 484 |
+
"""Return number of total actors."""
|
| 485 |
+
return len(self.all_actors)
|
| 486 |
+
|
| 487 |
+
@property
|
| 488 |
+
def num_actor_tasks(self):
|
| 489 |
+
"""Return number of pending tasks"""
|
| 490 |
+
return self._actor_task_events.num_futures
|
| 491 |
+
|
| 492 |
+
def get_live_actors_resources(self):
|
| 493 |
+
if self._live_resource_cache:
|
| 494 |
+
return self._live_resource_cache
|
| 495 |
+
|
| 496 |
+
counter = Counter()
|
| 497 |
+
for _, acq in self._live_actors_to_ray_actors_resources.values():
|
| 498 |
+
for bdl in acq.resource_request.bundles:
|
| 499 |
+
counter.update(bdl)
|
| 500 |
+
self._live_resource_cache = dict(counter)
|
| 501 |
+
return self._live_resource_cache
|
| 502 |
+
|
| 503 |
+
def add_actor(
|
| 504 |
+
self,
|
| 505 |
+
cls: Union[Type, ray.actor.ActorClass],
|
| 506 |
+
kwargs: Dict[str, Any],
|
| 507 |
+
resource_request: ResourceRequest,
|
| 508 |
+
*,
|
| 509 |
+
on_start: Optional[Callable[[TrackedActor], None]] = None,
|
| 510 |
+
on_stop: Optional[Callable[[TrackedActor], None]] = None,
|
| 511 |
+
on_error: Optional[Callable[[TrackedActor, Exception], None]] = None,
|
| 512 |
+
) -> TrackedActor:
|
| 513 |
+
"""Add an actor to be tracked.
|
| 514 |
+
|
| 515 |
+
This method will request resources to start the actor. Once the resources
|
| 516 |
+
are available, the actor will be started and the
|
| 517 |
+
:meth:`TrackedActor.on_start
|
| 518 |
+
<ray.air.execution._internal.tracked_actor.TrackedActor.on_start>` callback
|
| 519 |
+
will be invoked.
|
| 520 |
+
|
| 521 |
+
Args:
|
| 522 |
+
cls: Actor class to schedule.
|
| 523 |
+
kwargs: Keyword arguments to pass to actor class on construction.
|
| 524 |
+
resource_request: Resources required to start the actor.
|
| 525 |
+
on_start: Callback to invoke when the actor started.
|
| 526 |
+
on_stop: Callback to invoke when the actor stopped.
|
| 527 |
+
on_error: Callback to invoke when the actor failed.
|
| 528 |
+
|
| 529 |
+
Returns:
|
| 530 |
+
Tracked actor object to reference actor in subsequent API calls.
|
| 531 |
+
|
| 532 |
+
"""
|
| 533 |
+
tracked_actor = TrackedActor(
|
| 534 |
+
uuid.uuid4().int, on_start=on_start, on_stop=on_stop, on_error=on_error
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
self._pending_actors_to_attrs[tracked_actor] = cls, kwargs, resource_request
|
| 538 |
+
self._resource_request_to_pending_actors[resource_request].append(tracked_actor)
|
| 539 |
+
|
| 540 |
+
self._resource_manager.request_resources(resource_request=resource_request)
|
| 541 |
+
|
| 542 |
+
return tracked_actor
|
| 543 |
+
|
| 544 |
+
def remove_actor(
|
| 545 |
+
self,
|
| 546 |
+
tracked_actor: TrackedActor,
|
| 547 |
+
kill: bool = False,
|
| 548 |
+
stop_future: Optional[ray.ObjectRef] = None,
|
| 549 |
+
) -> bool:
|
| 550 |
+
"""Remove a tracked actor.
|
| 551 |
+
|
| 552 |
+
If the actor has already been started, this will stop the actor. This will
|
| 553 |
+
trigger the :meth:`TrackedActor.on_stop
|
| 554 |
+
<ray.air.execution._internal.tracked_actor.TrackedActor.on_stop>`
|
| 555 |
+
callback once the actor stopped.
|
| 556 |
+
|
| 557 |
+
If the actor has only been requested, but not started, yet, this will cancel
|
| 558 |
+
the actor request. This will not trigger any callback.
|
| 559 |
+
|
| 560 |
+
If ``kill=True``, this will use ``ray.kill()`` to forcefully terminate the
|
| 561 |
+
actor. Otherwise, graceful actor deconstruction will be scheduled after
|
| 562 |
+
all currently tracked futures are resolved.
|
| 563 |
+
|
| 564 |
+
This method returns a boolean, indicating if a stop future is tracked and
|
| 565 |
+
the ``on_stop`` callback will be invoked. If the actor has been alive,
|
| 566 |
+
this will be ``True``. If the actor hasn't been scheduled, yet, or failed
|
| 567 |
+
(and triggered the ``on_error`` callback), this will be ``False``.
|
| 568 |
+
|
| 569 |
+
Args:
|
| 570 |
+
tracked_actor: Tracked actor to be removed.
|
| 571 |
+
kill: If set, will forcefully terminate the actor instead of gracefully
|
| 572 |
+
scheduling termination.
|
| 573 |
+
stop_future: If set, use this future to track actor termination.
|
| 574 |
+
Otherwise, schedule a ``__ray_terminate__`` future.
|
| 575 |
+
|
| 576 |
+
Returns:
|
| 577 |
+
Boolean indicating if the actor was previously alive, and thus whether
|
| 578 |
+
a callback will be invoked once it is terminated.
|
| 579 |
+
|
| 580 |
+
"""
|
| 581 |
+
if tracked_actor.actor_id in self._failed_actor_ids:
|
| 582 |
+
logger.debug(
|
| 583 |
+
f"Tracked actor already failed, no need to remove: {tracked_actor}"
|
| 584 |
+
)
|
| 585 |
+
return False
|
| 586 |
+
elif tracked_actor in self._live_actors_to_ray_actors_resources:
|
| 587 |
+
# Ray actor is running.
|
| 588 |
+
|
| 589 |
+
if not kill:
|
| 590 |
+
# Schedule __ray_terminate__ future
|
| 591 |
+
ray_actor, _ = self._live_actors_to_ray_actors_resources[tracked_actor]
|
| 592 |
+
|
| 593 |
+
# Clear state futures here to avoid resolving __ray_ready__ futures
|
| 594 |
+
for future in list(
|
| 595 |
+
self._tracked_actors_to_state_futures[tracked_actor]
|
| 596 |
+
):
|
| 597 |
+
self._actor_state_events.discard_future(future)
|
| 598 |
+
self._tracked_actors_to_state_futures[tracked_actor].remove(future)
|
| 599 |
+
|
| 600 |
+
# If the __ray_ready__ future hasn't resolved yet, but we already
|
| 601 |
+
# scheduled the actor via Actor.remote(), we just want to stop
|
| 602 |
+
# it but not trigger any callbacks. This is in accordance with
|
| 603 |
+
# the contract defined in the docstring.
|
| 604 |
+
tracked_actor._on_start = None
|
| 605 |
+
tracked_actor._on_stop = None
|
| 606 |
+
tracked_actor._on_error = None
|
| 607 |
+
|
| 608 |
+
def on_actor_stop(*args, **kwargs):
|
| 609 |
+
self._actor_stop_resolved(tracked_actor=tracked_actor)
|
| 610 |
+
|
| 611 |
+
if stop_future:
|
| 612 |
+
# If the stop future was schedule via the actor manager,
|
| 613 |
+
# discard (track it as state future instead).
|
| 614 |
+
self._actor_task_events.discard_future(stop_future)
|
| 615 |
+
else:
|
| 616 |
+
stop_future = ray_actor.__ray_terminate__.remote()
|
| 617 |
+
|
| 618 |
+
self._actor_state_events.track_future(
|
| 619 |
+
future=stop_future,
|
| 620 |
+
on_result=on_actor_stop,
|
| 621 |
+
on_error=on_actor_stop,
|
| 622 |
+
)
|
| 623 |
+
|
| 624 |
+
self._tracked_actors_to_state_futures[tracked_actor].add(stop_future)
|
| 625 |
+
else:
|
| 626 |
+
# kill = True
|
| 627 |
+
self._live_actors_to_kill.add(tracked_actor)
|
| 628 |
+
|
| 629 |
+
return True
|
| 630 |
+
|
| 631 |
+
elif tracked_actor in self._pending_actors_to_attrs:
|
| 632 |
+
# Actor is pending, stop
|
| 633 |
+
_, _, resource_request = self._pending_actors_to_attrs.pop(tracked_actor)
|
| 634 |
+
self._resource_request_to_pending_actors[resource_request].remove(
|
| 635 |
+
tracked_actor
|
| 636 |
+
)
|
| 637 |
+
self._resource_manager.cancel_resource_request(
|
| 638 |
+
resource_request=resource_request
|
| 639 |
+
)
|
| 640 |
+
return False
|
| 641 |
+
else:
|
| 642 |
+
raise ValueError(f"Unknown tracked actor: {tracked_actor}")
|
| 643 |
+
|
| 644 |
+
def is_actor_started(self, tracked_actor: TrackedActor) -> bool:
|
| 645 |
+
"""Returns True if the actor has been started.
|
| 646 |
+
|
| 647 |
+
Args:
|
| 648 |
+
tracked_actor: Tracked actor object.
|
| 649 |
+
"""
|
| 650 |
+
return (
|
| 651 |
+
tracked_actor in self._live_actors_to_ray_actors_resources
|
| 652 |
+
and tracked_actor.actor_id not in self._failed_actor_ids
|
| 653 |
+
)
|
| 654 |
+
|
| 655 |
+
def is_actor_failed(self, tracked_actor: TrackedActor) -> bool:
|
| 656 |
+
return tracked_actor.actor_id in self._failed_actor_ids
|
| 657 |
+
|
| 658 |
+
def get_actor_resources(
|
| 659 |
+
self, tracked_actor: TrackedActor
|
| 660 |
+
) -> Optional[AcquiredResources]:
|
| 661 |
+
"""Returns the acquired resources of an actor that has been started.
|
| 662 |
+
|
| 663 |
+
This will return ``None`` if the actor has not been started, yet.
|
| 664 |
+
|
| 665 |
+
Args:
|
| 666 |
+
tracked_actor: Tracked actor object.
|
| 667 |
+
"""
|
| 668 |
+
if not self.is_actor_started(tracked_actor):
|
| 669 |
+
return None
|
| 670 |
+
|
| 671 |
+
return self._live_actors_to_ray_actors_resources[tracked_actor][1]
|
| 672 |
+
|
| 673 |
+
def schedule_actor_task(
|
| 674 |
+
self,
|
| 675 |
+
tracked_actor: TrackedActor,
|
| 676 |
+
method_name: str,
|
| 677 |
+
args: Optional[Tuple] = None,
|
| 678 |
+
kwargs: Optional[Dict] = None,
|
| 679 |
+
on_result: Optional[Callable[[TrackedActor, Any], None]] = None,
|
| 680 |
+
on_error: Optional[Callable[[TrackedActor, Exception], None]] = None,
|
| 681 |
+
_return_future: bool = False,
|
| 682 |
+
) -> Optional[ray.ObjectRef]:
|
| 683 |
+
"""Schedule and track a task on an actor.
|
| 684 |
+
|
| 685 |
+
This method will schedule a remote task ``method_name`` on the
|
| 686 |
+
``tracked_actor``.
|
| 687 |
+
|
| 688 |
+
This method accepts two optional callbacks that will be invoked when
|
| 689 |
+
their respective events are triggered.
|
| 690 |
+
|
| 691 |
+
The ``on_result`` callback is triggered when a task resolves successfully.
|
| 692 |
+
It should accept two arguments: The actor for which the
|
| 693 |
+
task resolved, and the result received from the remote call.
|
| 694 |
+
|
| 695 |
+
The ``on_error`` callback is triggered when a task fails.
|
| 696 |
+
It should accept two arguments: The actor for which the
|
| 697 |
+
task threw an error, and the exception.
|
| 698 |
+
|
| 699 |
+
Args:
|
| 700 |
+
tracked_actor: Actor to schedule task on.
|
| 701 |
+
method_name: Remote method name to invoke on the actor. If this is
|
| 702 |
+
e.g. ``foo``, then ``actor.foo.remote(*args, **kwargs)`` will be
|
| 703 |
+
scheduled.
|
| 704 |
+
args: Arguments to pass to the task.
|
| 705 |
+
kwargs: Keyword arguments to pass to the task.
|
| 706 |
+
on_result: Callback to invoke when the task resolves.
|
| 707 |
+
on_error: Callback to invoke when the task fails.
|
| 708 |
+
|
| 709 |
+
Raises:
|
| 710 |
+
ValueError: If the ``tracked_actor`` is not managed by this event manager.
|
| 711 |
+
|
| 712 |
+
"""
|
| 713 |
+
args = args or tuple()
|
| 714 |
+
kwargs = kwargs or {}
|
| 715 |
+
|
| 716 |
+
if tracked_actor.actor_id in self._failed_actor_ids:
|
| 717 |
+
return
|
| 718 |
+
|
| 719 |
+
tracked_actor_task = TrackedActorTask(
|
| 720 |
+
tracked_actor=tracked_actor, on_result=on_result, on_error=on_error
|
| 721 |
+
)
|
| 722 |
+
|
| 723 |
+
if tracked_actor not in self._live_actors_to_ray_actors_resources:
|
| 724 |
+
# Actor is not started, yet
|
| 725 |
+
if tracked_actor not in self._pending_actors_to_attrs:
|
| 726 |
+
raise ValueError(
|
| 727 |
+
f"Tracked actor is not managed by this event manager: "
|
| 728 |
+
f"{tracked_actor}"
|
| 729 |
+
)
|
| 730 |
+
|
| 731 |
+
# Cache tasks for future execution
|
| 732 |
+
self._pending_actors_to_enqueued_actor_tasks[tracked_actor].append(
|
| 733 |
+
(tracked_actor_task, method_name, args, kwargs)
|
| 734 |
+
)
|
| 735 |
+
else:
|
| 736 |
+
res = self._schedule_tracked_actor_task(
|
| 737 |
+
tracked_actor_task=tracked_actor_task,
|
| 738 |
+
method_name=method_name,
|
| 739 |
+
args=args,
|
| 740 |
+
kwargs=kwargs,
|
| 741 |
+
_return_future=_return_future,
|
| 742 |
+
)
|
| 743 |
+
if _return_future:
|
| 744 |
+
return res[1]
|
| 745 |
+
|
| 746 |
+
def _schedule_tracked_actor_task(
|
| 747 |
+
self,
|
| 748 |
+
tracked_actor_task: TrackedActorTask,
|
| 749 |
+
method_name: str,
|
| 750 |
+
*,
|
| 751 |
+
args: Optional[Tuple] = None,
|
| 752 |
+
kwargs: Optional[Dict] = None,
|
| 753 |
+
_return_future: bool = False,
|
| 754 |
+
) -> Union[TrackedActorTask, Tuple[TrackedActorTask, ray.ObjectRef]]:
|
| 755 |
+
tracked_actor = tracked_actor_task._tracked_actor
|
| 756 |
+
ray_actor, _ = self._live_actors_to_ray_actors_resources[tracked_actor]
|
| 757 |
+
|
| 758 |
+
try:
|
| 759 |
+
remote_fn = getattr(ray_actor, method_name)
|
| 760 |
+
except AttributeError as e:
|
| 761 |
+
raise AttributeError(
|
| 762 |
+
f"Remote function `{method_name}()` does not exist for this actor."
|
| 763 |
+
) from e
|
| 764 |
+
|
| 765 |
+
def on_result(result: Any):
|
| 766 |
+
self._actor_task_resolved(
|
| 767 |
+
tracked_actor_task=tracked_actor_task, result=result
|
| 768 |
+
)
|
| 769 |
+
|
| 770 |
+
def on_error(exception: Exception):
|
| 771 |
+
self._actor_task_failed(
|
| 772 |
+
tracked_actor_task=tracked_actor_task, exception=exception
|
| 773 |
+
)
|
| 774 |
+
|
| 775 |
+
future = remote_fn.remote(*args, **kwargs)
|
| 776 |
+
|
| 777 |
+
self._actor_task_events.track_future(
|
| 778 |
+
future=future, on_result=on_result, on_error=on_error
|
| 779 |
+
)
|
| 780 |
+
|
| 781 |
+
self._tracked_actors_to_task_futures[tracked_actor].add(future)
|
| 782 |
+
|
| 783 |
+
if _return_future:
|
| 784 |
+
return tracked_actor_task, future
|
| 785 |
+
|
| 786 |
+
return tracked_actor_task
|
| 787 |
+
|
| 788 |
+
def schedule_actor_tasks(
|
| 789 |
+
self,
|
| 790 |
+
tracked_actors: List[TrackedActor],
|
| 791 |
+
method_name: str,
|
| 792 |
+
*,
|
| 793 |
+
args: Optional[Union[Tuple, List[Tuple]]] = None,
|
| 794 |
+
kwargs: Optional[Union[Dict, List[Dict]]] = None,
|
| 795 |
+
on_result: Optional[Callable[[TrackedActor, Any], None]] = None,
|
| 796 |
+
on_error: Optional[Callable[[TrackedActor, Exception], None]] = None,
|
| 797 |
+
) -> None:
|
| 798 |
+
"""Schedule and track tasks on a list of actors.
|
| 799 |
+
|
| 800 |
+
This method will schedule a remote task ``method_name`` on all
|
| 801 |
+
``tracked_actors``.
|
| 802 |
+
|
| 803 |
+
``args`` and ``kwargs`` can be a single tuple/dict, in which case the same
|
| 804 |
+
(keyword) arguments are passed to all actors. If a list is passed instead,
|
| 805 |
+
they are mapped to the respective actors. In that case, the list of
|
| 806 |
+
(keyword) arguments must be the same length as the list of actors.
|
| 807 |
+
|
| 808 |
+
This method accepts two optional callbacks that will be invoked when
|
| 809 |
+
their respective events are triggered.
|
| 810 |
+
|
| 811 |
+
The ``on_result`` callback is triggered when a task resolves successfully.
|
| 812 |
+
It should accept two arguments: The actor for which the
|
| 813 |
+
task resolved, and the result received from the remote call.
|
| 814 |
+
|
| 815 |
+
The ``on_error`` callback is triggered when a task fails.
|
| 816 |
+
It should accept two arguments: The actor for which the
|
| 817 |
+
task threw an error, and the exception.
|
| 818 |
+
|
| 819 |
+
Args:
|
| 820 |
+
tracked_actors: List of actors to schedule tasks on.
|
| 821 |
+
method_name: Remote actor method to invoke on the actors. If this is
|
| 822 |
+
e.g. ``foo``, then ``actor.foo.remote(*args, **kwargs)`` will be
|
| 823 |
+
scheduled on all actors.
|
| 824 |
+
args: Arguments to pass to the task.
|
| 825 |
+
kwargs: Keyword arguments to pass to the task.
|
| 826 |
+
on_result: Callback to invoke when the task resolves.
|
| 827 |
+
on_error: Callback to invoke when the task fails.
|
| 828 |
+
|
| 829 |
+
"""
|
| 830 |
+
if not isinstance(args, List):
|
| 831 |
+
args_list = [args] * len(tracked_actors)
|
| 832 |
+
else:
|
| 833 |
+
if len(tracked_actors) != len(args):
|
| 834 |
+
raise ValueError(
|
| 835 |
+
f"Length of args must be the same as tracked_actors "
|
| 836 |
+
f"list. Got `len(kwargs)={len(kwargs)}` and "
|
| 837 |
+
f"`len(tracked_actors)={len(tracked_actors)}"
|
| 838 |
+
)
|
| 839 |
+
args_list = args
|
| 840 |
+
|
| 841 |
+
if not isinstance(kwargs, List):
|
| 842 |
+
kwargs_list = [kwargs] * len(tracked_actors)
|
| 843 |
+
else:
|
| 844 |
+
if len(tracked_actors) != len(kwargs):
|
| 845 |
+
raise ValueError(
|
| 846 |
+
f"Length of kwargs must be the same as tracked_actors "
|
| 847 |
+
f"list. Got `len(args)={len(args)}` and "
|
| 848 |
+
f"`len(tracked_actors)={len(tracked_actors)}"
|
| 849 |
+
)
|
| 850 |
+
kwargs_list = kwargs
|
| 851 |
+
|
| 852 |
+
for tracked_actor, args, kwargs in zip(tracked_actors, args_list, kwargs_list):
|
| 853 |
+
self.schedule_actor_task(
|
| 854 |
+
tracked_actor=tracked_actor,
|
| 855 |
+
method_name=method_name,
|
| 856 |
+
args=args,
|
| 857 |
+
kwargs=kwargs,
|
| 858 |
+
on_result=on_result,
|
| 859 |
+
on_error=on_error,
|
| 860 |
+
)
|
| 861 |
+
|
| 862 |
+
def clear_actor_task_futures(self, tracked_actor: TrackedActor):
|
| 863 |
+
"""Discard all actor task futures from a tracked actor."""
|
| 864 |
+
futures = self._tracked_actors_to_task_futures.pop(tracked_actor, [])
|
| 865 |
+
for future in futures:
|
| 866 |
+
self._actor_task_events.discard_future(future)
|
| 867 |
+
|
| 868 |
+
def _cleanup_actor_futures(self, tracked_actor: TrackedActor):
|
| 869 |
+
# Remove all actor task futures
|
| 870 |
+
self.clear_actor_task_futures(tracked_actor=tracked_actor)
|
| 871 |
+
|
| 872 |
+
# Remove all actor state futures
|
| 873 |
+
futures = self._tracked_actors_to_state_futures.pop(tracked_actor, [])
|
| 874 |
+
for future in futures:
|
| 875 |
+
self._actor_state_events.discard_future(future)
|
| 876 |
+
|
| 877 |
+
def cleanup(self):
|
| 878 |
+
for (
|
| 879 |
+
actor,
|
| 880 |
+
acquired_resources,
|
| 881 |
+
) in self._live_actors_to_ray_actors_resources.values():
|
| 882 |
+
ray.kill(actor)
|
| 883 |
+
self._resource_manager.free_resources(acquired_resources)
|
| 884 |
+
|
| 885 |
+
for (
|
| 886 |
+
resource_request,
|
| 887 |
+
pending_actors,
|
| 888 |
+
) in self._resource_request_to_pending_actors.items():
|
| 889 |
+
for i in range(len(pending_actors)):
|
| 890 |
+
self._resource_manager.cancel_resource_request(resource_request)
|
| 891 |
+
|
| 892 |
+
self._resource_manager.clear()
|
| 893 |
+
|
| 894 |
+
self.__init__(resource_manager=self._resource_manager)
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/_internal/barrier.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Callable, List, Optional, Tuple
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class Barrier:
|
| 5 |
+
"""Barrier to collect results and process them in bulk.
|
| 6 |
+
|
| 7 |
+
A barrier can be used to collect multiple results and process them in bulk once
|
| 8 |
+
a certain count or a timeout is reached.
|
| 9 |
+
|
| 10 |
+
For instance, if ``max_results=N``, the ``on_completion`` callback will be
|
| 11 |
+
invoked once :meth:`arrive` has been called ``N`` times.
|
| 12 |
+
|
| 13 |
+
The completion callback will only be invoked once, even if more results
|
| 14 |
+
arrive after completion. The collected results can be resetted
|
| 15 |
+
with :meth:`reset`, after which the callback may be invoked again.
|
| 16 |
+
|
| 17 |
+
The completion callback should expect one argument, which is the barrier
|
| 18 |
+
object that completed.
|
| 19 |
+
|
| 20 |
+
Args:
|
| 21 |
+
max_results: Maximum number of results to collect before a call to
|
| 22 |
+
:meth:`wait` resolves or the :meth:`on_completion` callback is invoked.
|
| 23 |
+
on_completion: Callback to invoke when ``max_results`` results
|
| 24 |
+
arrived at the barrier.
|
| 25 |
+
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
max_results: int,
|
| 31 |
+
*,
|
| 32 |
+
on_completion: Optional[Callable[["Barrier"], None]] = None,
|
| 33 |
+
):
|
| 34 |
+
self._max_results = max_results
|
| 35 |
+
|
| 36 |
+
# on_completion callback
|
| 37 |
+
self._completed = False
|
| 38 |
+
self._on_completion = on_completion
|
| 39 |
+
|
| 40 |
+
# Collect received results
|
| 41 |
+
self._results: List[Tuple[Any]] = []
|
| 42 |
+
|
| 43 |
+
def arrive(self, *data):
|
| 44 |
+
"""Notify barrier that a result successfully arrived.
|
| 45 |
+
|
| 46 |
+
This will count against the ``max_results`` limit. The received result
|
| 47 |
+
will be included in a call to :meth:`get_results`.
|
| 48 |
+
|
| 49 |
+
Args:
|
| 50 |
+
*data: Result data to be cached. Can be obtained via :meth:`get_results`.
|
| 51 |
+
|
| 52 |
+
"""
|
| 53 |
+
if len(data) == 1:
|
| 54 |
+
data = data[0]
|
| 55 |
+
|
| 56 |
+
self._results.append(data)
|
| 57 |
+
self._check_completion()
|
| 58 |
+
|
| 59 |
+
def _check_completion(self):
|
| 60 |
+
if self._completed:
|
| 61 |
+
# Already fired completion callback
|
| 62 |
+
return
|
| 63 |
+
|
| 64 |
+
if self.num_results >= self._max_results:
|
| 65 |
+
# Barrier is complete
|
| 66 |
+
self._completed = True
|
| 67 |
+
|
| 68 |
+
if self._on_completion:
|
| 69 |
+
self._on_completion(self)
|
| 70 |
+
|
| 71 |
+
@property
|
| 72 |
+
def completed(self) -> bool:
|
| 73 |
+
"""Returns True if the barrier is completed."""
|
| 74 |
+
return self._completed
|
| 75 |
+
|
| 76 |
+
@property
|
| 77 |
+
def num_results(self) -> int:
|
| 78 |
+
"""Number of received (successful) results."""
|
| 79 |
+
return len(self._results)
|
| 80 |
+
|
| 81 |
+
def get_results(self) -> List[Tuple[Any]]:
|
| 82 |
+
"""Return list of received results."""
|
| 83 |
+
return self._results
|
| 84 |
+
|
| 85 |
+
def reset(self) -> None:
|
| 86 |
+
"""Reset barrier, removing all received results.
|
| 87 |
+
|
| 88 |
+
Resetting the barrier will reset the completion status. When ``max_results``
|
| 89 |
+
is set and enough new events arrive after resetting, the
|
| 90 |
+
:meth:`on_completion` callback will be invoked again.
|
| 91 |
+
"""
|
| 92 |
+
self._completed = False
|
| 93 |
+
self._results = []
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/_internal/event_manager.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
from typing import Any, Callable, Dict, Iterable, Optional, Set, Tuple, Union
|
| 3 |
+
|
| 4 |
+
import ray
|
| 5 |
+
|
| 6 |
+
_ResultCallback = Callable[[Any], None]
|
| 7 |
+
_ErrorCallback = Callable[[Exception], None]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class RayEventManager:
|
| 11 |
+
"""Event manager for Ray futures.
|
| 12 |
+
|
| 13 |
+
The event manager can be used to track futures and invoke callbacks when
|
| 14 |
+
they resolve.
|
| 15 |
+
|
| 16 |
+
Futures are tracked with :meth:`track_future`. Future can then be awaited with
|
| 17 |
+
:meth:`wait`. When futures successfully resolve, they trigger an optional
|
| 18 |
+
``on_result`` callback that can be passed to :meth:`track_future`. If they
|
| 19 |
+
fail, they trigger an optional ``on_error`` callback.
|
| 20 |
+
|
| 21 |
+
Args:
|
| 22 |
+
shuffle_futures: If True, futures will be shuffled before awaited. This
|
| 23 |
+
will avoid implicit prioritization of futures within Ray.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def __init__(self, shuffle_futures: bool = True):
|
| 27 |
+
self._shuffle_futures = shuffle_futures
|
| 28 |
+
|
| 29 |
+
# Map of futures to callbacks (result, error)
|
| 30 |
+
self._tracked_futures: Dict[
|
| 31 |
+
ray.ObjectRef, Tuple[Optional[_ResultCallback], Optional[_ErrorCallback]]
|
| 32 |
+
] = {}
|
| 33 |
+
|
| 34 |
+
def track_future(
|
| 35 |
+
self,
|
| 36 |
+
future: ray.ObjectRef,
|
| 37 |
+
on_result: Optional[_ResultCallback] = None,
|
| 38 |
+
on_error: Optional[_ErrorCallback] = None,
|
| 39 |
+
):
|
| 40 |
+
"""Track a single future and invoke callbacks on resolution.
|
| 41 |
+
|
| 42 |
+
Control has to be yielded to the event manager for the callbacks to
|
| 43 |
+
be invoked, either via :meth:`wait` or via :meth:`resolve_future`.
|
| 44 |
+
|
| 45 |
+
Args:
|
| 46 |
+
future: Ray future to await.
|
| 47 |
+
on_result: Callback to invoke when the future resolves successfully.
|
| 48 |
+
on_error: Callback to invoke when the future fails.
|
| 49 |
+
|
| 50 |
+
"""
|
| 51 |
+
self._tracked_futures[future] = (on_result, on_error)
|
| 52 |
+
|
| 53 |
+
def track_futures(
|
| 54 |
+
self,
|
| 55 |
+
futures: Iterable[ray.ObjectRef],
|
| 56 |
+
on_result: Optional[_ResultCallback] = None,
|
| 57 |
+
on_error: Optional[_ErrorCallback] = None,
|
| 58 |
+
):
|
| 59 |
+
"""Track multiple futures and invoke callbacks on resolution.
|
| 60 |
+
|
| 61 |
+
Control has to be yielded to the event manager for the callbacks to
|
| 62 |
+
be invoked, either via :meth:`wait` or via :meth:`resolve_future`.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
futures: Ray futures to await.
|
| 66 |
+
on_result: Callback to invoke when the future resolves successfully.
|
| 67 |
+
on_error: Callback to invoke when the future fails.
|
| 68 |
+
|
| 69 |
+
"""
|
| 70 |
+
for future in futures:
|
| 71 |
+
self.track_future(future, on_result=on_result, on_error=on_error)
|
| 72 |
+
|
| 73 |
+
def discard_future(self, future: ray.ObjectRef):
|
| 74 |
+
"""Remove future from tracking.
|
| 75 |
+
|
| 76 |
+
The future will not be awaited anymore, and it will not trigger any callbacks.
|
| 77 |
+
|
| 78 |
+
Args:
|
| 79 |
+
future: Ray futures to discard.
|
| 80 |
+
"""
|
| 81 |
+
self._tracked_futures.pop(future, None)
|
| 82 |
+
|
| 83 |
+
def get_futures(self) -> Set[ray.ObjectRef]:
|
| 84 |
+
"""Get futures tracked by the event manager."""
|
| 85 |
+
return set(self._tracked_futures)
|
| 86 |
+
|
| 87 |
+
@property
|
| 88 |
+
def num_futures(self) -> int:
|
| 89 |
+
return len(self._tracked_futures)
|
| 90 |
+
|
| 91 |
+
def resolve_future(self, future: ray.ObjectRef):
|
| 92 |
+
"""Resolve a single future.
|
| 93 |
+
|
| 94 |
+
This method will block until the future is available. It will then
|
| 95 |
+
trigger the callback associated to the future and the event (success
|
| 96 |
+
or error), if specified.
|
| 97 |
+
|
| 98 |
+
Args:
|
| 99 |
+
future: Ray future to resolve.
|
| 100 |
+
|
| 101 |
+
"""
|
| 102 |
+
try:
|
| 103 |
+
on_result, on_error = self._tracked_futures.pop(future)
|
| 104 |
+
except KeyError as e:
|
| 105 |
+
raise ValueError(
|
| 106 |
+
f"Future {future} is not tracked by this RayEventManager"
|
| 107 |
+
) from e
|
| 108 |
+
|
| 109 |
+
try:
|
| 110 |
+
result = ray.get(future)
|
| 111 |
+
except Exception as e:
|
| 112 |
+
if on_error:
|
| 113 |
+
on_error(e)
|
| 114 |
+
else:
|
| 115 |
+
raise e
|
| 116 |
+
else:
|
| 117 |
+
if on_result:
|
| 118 |
+
on_result(result)
|
| 119 |
+
|
| 120 |
+
def wait(
|
| 121 |
+
self,
|
| 122 |
+
timeout: Optional[Union[float, int]] = None,
|
| 123 |
+
num_results: Optional[int] = 1,
|
| 124 |
+
):
|
| 125 |
+
"""Wait up to ``timeout`` seconds for ``num_results`` futures to resolve.
|
| 126 |
+
|
| 127 |
+
If ``timeout=None``, this method will block until all `num_results`` futures
|
| 128 |
+
resolve. If ``num_results=None``, this method will await all tracked futures.
|
| 129 |
+
|
| 130 |
+
For every future that resolves, the respective associated callbacks will be
|
| 131 |
+
invoked.
|
| 132 |
+
|
| 133 |
+
Args:
|
| 134 |
+
timeout: Timeout in second to wait for futures to resolve.
|
| 135 |
+
num_results: Number of futures to await. If ``None``, will wait for
|
| 136 |
+
all tracked futures to resolve.
|
| 137 |
+
|
| 138 |
+
"""
|
| 139 |
+
futures = list(self.get_futures())
|
| 140 |
+
|
| 141 |
+
if self._shuffle_futures:
|
| 142 |
+
random.shuffle(futures)
|
| 143 |
+
|
| 144 |
+
num_results = num_results or len(futures)
|
| 145 |
+
|
| 146 |
+
ready, _ = ray.wait(list(futures), timeout=timeout, num_returns=num_results)
|
| 147 |
+
for future in ready:
|
| 148 |
+
self.resolve_future(future)
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/_internal/tracked_actor.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Callable, Optional
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class TrackedActor:
|
| 5 |
+
"""Actor tracked by an actor manager.
|
| 6 |
+
|
| 7 |
+
This object is used to reference a Ray actor on an actor manager
|
| 8 |
+
|
| 9 |
+
Existence of this object does not mean that the Ray actor has already been started.
|
| 10 |
+
Actor state can be inquired from the actor manager tracking the Ray actor.
|
| 11 |
+
|
| 12 |
+
Note:
|
| 13 |
+
Objects of this class are returned by the :class:`RayActorManager`.
|
| 14 |
+
This class should not be instantiated manually.
|
| 15 |
+
|
| 16 |
+
Attributes:
|
| 17 |
+
actor_id: ID for identification of the actor within the actor manager. This
|
| 18 |
+
ID is not related to the Ray actor ID.
|
| 19 |
+
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
def __init__(
|
| 23 |
+
self,
|
| 24 |
+
actor_id: int,
|
| 25 |
+
on_start: Optional[Callable[["TrackedActor"], None]] = None,
|
| 26 |
+
on_stop: Optional[Callable[["TrackedActor"], None]] = None,
|
| 27 |
+
on_error: Optional[Callable[["TrackedActor", Exception], None]] = None,
|
| 28 |
+
):
|
| 29 |
+
self.actor_id = actor_id
|
| 30 |
+
self._on_start = on_start
|
| 31 |
+
self._on_stop = on_stop
|
| 32 |
+
self._on_error = on_error
|
| 33 |
+
|
| 34 |
+
def set_on_start(self, on_start: Optional[Callable[["TrackedActor"], None]]):
|
| 35 |
+
self._on_start = on_start
|
| 36 |
+
|
| 37 |
+
def set_on_stop(self, on_stop: Optional[Callable[["TrackedActor"], None]]):
|
| 38 |
+
self._on_stop = on_stop
|
| 39 |
+
|
| 40 |
+
def set_on_error(
|
| 41 |
+
self, on_error: Optional[Callable[["TrackedActor", Exception], None]]
|
| 42 |
+
):
|
| 43 |
+
self._on_error = on_error
|
| 44 |
+
|
| 45 |
+
def __repr__(self):
|
| 46 |
+
return f"<TrackedActor {self.actor_id}>"
|
| 47 |
+
|
| 48 |
+
def __eq__(self, other):
|
| 49 |
+
if not isinstance(other, self.__class__):
|
| 50 |
+
return False
|
| 51 |
+
return self.actor_id == other.actor_id
|
| 52 |
+
|
| 53 |
+
def __hash__(self):
|
| 54 |
+
return hash(self.actor_id)
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/_internal/tracked_actor_task.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Callable, Optional
|
| 2 |
+
|
| 3 |
+
from ray.air.execution._internal.tracked_actor import TrackedActor
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TrackedActorTask:
|
| 7 |
+
"""Actor task tracked by a Ray event manager.
|
| 8 |
+
|
| 9 |
+
This container class is used to define callbacks to be invoked when
|
| 10 |
+
the task resolves, errors, or times out.
|
| 11 |
+
|
| 12 |
+
Note:
|
| 13 |
+
Objects of this class are returned by the :class:`RayActorManager`.
|
| 14 |
+
This class should not be instantiated manually.
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
tracked_actor: Tracked actor object this task is scheduled on.
|
| 18 |
+
on_result: Callback to invoke when the task resolves.
|
| 19 |
+
on_error: Callback to invoke when the task fails.
|
| 20 |
+
|
| 21 |
+
Example:
|
| 22 |
+
|
| 23 |
+
.. code-block:: python
|
| 24 |
+
|
| 25 |
+
tracked_futures = actor_manager.schedule_actor_tasks(
|
| 26 |
+
actor_manager.live_actors,
|
| 27 |
+
"foo",
|
| 28 |
+
on_result=lambda actor, result: print(result)
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
def __init__(
|
| 34 |
+
self,
|
| 35 |
+
tracked_actor: TrackedActor,
|
| 36 |
+
on_result: Optional[Callable[[TrackedActor, Any], None]] = None,
|
| 37 |
+
on_error: Optional[Callable[[TrackedActor, Exception], None]] = None,
|
| 38 |
+
):
|
| 39 |
+
self._tracked_actor = tracked_actor
|
| 40 |
+
|
| 41 |
+
self._on_result = on_result
|
| 42 |
+
self._on_error = on_error
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/resources/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ray.air.execution.resources.fixed import FixedResourceManager
|
| 2 |
+
from ray.air.execution.resources.placement_group import PlacementGroupResourceManager
|
| 3 |
+
from ray.air.execution.resources.request import AcquiredResources, ResourceRequest
|
| 4 |
+
from ray.air.execution.resources.resource_manager import ResourceManager
|
| 5 |
+
|
| 6 |
+
__all__ = [
|
| 7 |
+
"ResourceRequest",
|
| 8 |
+
"AcquiredResources",
|
| 9 |
+
"ResourceManager",
|
| 10 |
+
"FixedResourceManager",
|
| 11 |
+
"PlacementGroupResourceManager",
|
| 12 |
+
]
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/resources/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (616 Bytes). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/resources/__pycache__/fixed.cpython-312.pyc
ADDED
|
Binary file (7.17 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/resources/__pycache__/placement_group.cpython-312.pyc
ADDED
|
Binary file (9.86 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/resources/__pycache__/request.cpython-312.pyc
ADDED
|
Binary file (11.6 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/resources/__pycache__/resource_manager.cpython-312.pyc
ADDED
|
Binary file (7.45 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/resources/fixed.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
from typing import Dict, List, Optional
|
| 3 |
+
|
| 4 |
+
import ray
|
| 5 |
+
from ray import LOCAL_MODE, SCRIPT_MODE
|
| 6 |
+
from ray.air.execution.resources.request import (
|
| 7 |
+
AcquiredResources,
|
| 8 |
+
RemoteRayEntity,
|
| 9 |
+
ResourceRequest,
|
| 10 |
+
)
|
| 11 |
+
from ray.air.execution.resources.resource_manager import ResourceManager
|
| 12 |
+
from ray.util.annotations import DeveloperAPI
|
| 13 |
+
|
| 14 |
+
# Avoid numerical errors by multiplying and subtracting with this number.
|
| 15 |
+
# Compare: 0.99 - 0.33 = 0.65999... vs (0.99 * 1000 - 0.33 * 1000) / 1000 = 0.66
|
| 16 |
+
_DIGITS = 100000
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@DeveloperAPI
|
| 20 |
+
@dataclass
|
| 21 |
+
class FixedAcquiredResources(AcquiredResources):
|
| 22 |
+
bundles: List[Dict[str, float]]
|
| 23 |
+
|
| 24 |
+
def _annotate_remote_entity(
|
| 25 |
+
self, entity: RemoteRayEntity, bundle: Dict[str, float], bundle_index: int
|
| 26 |
+
) -> RemoteRayEntity:
|
| 27 |
+
bundle = bundle.copy()
|
| 28 |
+
num_cpus = bundle.pop("CPU", 0)
|
| 29 |
+
num_gpus = bundle.pop("GPU", 0)
|
| 30 |
+
memory = bundle.pop("memory", 0.0)
|
| 31 |
+
|
| 32 |
+
return entity.options(
|
| 33 |
+
num_cpus=num_cpus,
|
| 34 |
+
num_gpus=num_gpus,
|
| 35 |
+
memory=memory,
|
| 36 |
+
resources=bundle,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@DeveloperAPI
|
| 41 |
+
class FixedResourceManager(ResourceManager):
|
| 42 |
+
"""Fixed budget based resource manager.
|
| 43 |
+
|
| 44 |
+
This resource manager keeps track of a fixed set of resources. When resources
|
| 45 |
+
are acquired, they are subtracted from the budget. When resources are freed,
|
| 46 |
+
they are added back to the budget.
|
| 47 |
+
|
| 48 |
+
The resource manager still requires resources to be requested before they become
|
| 49 |
+
available. However, because the resource requests are virtual, this will not
|
| 50 |
+
trigger autoscaling.
|
| 51 |
+
|
| 52 |
+
Additionally, resources are not reserved on request, only on acquisition. Thus,
|
| 53 |
+
acquiring a resource can change the availability of other requests. Note that
|
| 54 |
+
this behavior may be changed in future implementations.
|
| 55 |
+
|
| 56 |
+
The fixed resource manager does not support placement strategies. Using
|
| 57 |
+
``STRICT_SPREAD`` will result in an error. ``STRICT_PACK`` will succeed only
|
| 58 |
+
within a placement group bundle. All other placement group arguments will be
|
| 59 |
+
ignored.
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
total_resources: Budget of resources to manage. Defaults to all available
|
| 63 |
+
resources in the current task or all cluster resources (if outside a task).
|
| 64 |
+
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
_resource_cls: AcquiredResources = FixedAcquiredResources
|
| 68 |
+
|
| 69 |
+
def __init__(self, total_resources: Optional[Dict[str, float]] = None):
|
| 70 |
+
rtc = ray.get_runtime_context()
|
| 71 |
+
|
| 72 |
+
if not total_resources:
|
| 73 |
+
if rtc.worker.mode in {None, SCRIPT_MODE, LOCAL_MODE}:
|
| 74 |
+
total_resources = ray.cluster_resources()
|
| 75 |
+
else:
|
| 76 |
+
total_resources = rtc.get_assigned_resources()
|
| 77 |
+
|
| 78 |
+
# If we are in a placement group, all of our resources will be in a bundle
|
| 79 |
+
# and thus fulfill requirements of STRICT_PACK - but only if child tasks
|
| 80 |
+
# are captured by the pg.
|
| 81 |
+
self._allow_strict_pack = (
|
| 82 |
+
ray.util.get_current_placement_group() is not None
|
| 83 |
+
and rtc.should_capture_child_tasks_in_placement_group
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
self._total_resources = total_resources
|
| 87 |
+
self._requested_resources = []
|
| 88 |
+
self._used_resources = []
|
| 89 |
+
|
| 90 |
+
@property
|
| 91 |
+
def _available_resources(self) -> Dict[str, float]:
|
| 92 |
+
available_resources = self._total_resources.copy()
|
| 93 |
+
|
| 94 |
+
for used_resources in self._used_resources:
|
| 95 |
+
all_resources = used_resources.required_resources
|
| 96 |
+
for k, v in all_resources.items():
|
| 97 |
+
available_resources[k] = (
|
| 98 |
+
available_resources[k] * _DIGITS - v * _DIGITS
|
| 99 |
+
) / _DIGITS
|
| 100 |
+
return available_resources
|
| 101 |
+
|
| 102 |
+
def request_resources(self, resource_request: ResourceRequest):
|
| 103 |
+
if resource_request.strategy == "STRICT_SPREAD" or (
|
| 104 |
+
not self._allow_strict_pack and resource_request.strategy == "STRICT_PACK"
|
| 105 |
+
):
|
| 106 |
+
raise RuntimeError(
|
| 107 |
+
f"Requested a resource with placement strategy "
|
| 108 |
+
f"{resource_request.strategy}, but this cannot be fulfilled by a "
|
| 109 |
+
f"FixedResourceManager. In a nested setting, please set the inner "
|
| 110 |
+
f"placement strategy to be less restrictive (i.e. no STRICT_ strategy)."
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
self._requested_resources.append(resource_request)
|
| 114 |
+
|
| 115 |
+
def cancel_resource_request(self, resource_request: ResourceRequest):
|
| 116 |
+
self._requested_resources.remove(resource_request)
|
| 117 |
+
|
| 118 |
+
def has_resources_ready(self, resource_request: ResourceRequest) -> bool:
|
| 119 |
+
if resource_request not in self._requested_resources:
|
| 120 |
+
return False
|
| 121 |
+
|
| 122 |
+
available_resources = self._available_resources
|
| 123 |
+
all_resources = resource_request.required_resources
|
| 124 |
+
for k, v in all_resources.items():
|
| 125 |
+
if available_resources.get(k, 0.0) < v:
|
| 126 |
+
return False
|
| 127 |
+
return True
|
| 128 |
+
|
| 129 |
+
def acquire_resources(
|
| 130 |
+
self, resource_request: ResourceRequest
|
| 131 |
+
) -> Optional[AcquiredResources]:
|
| 132 |
+
if not self.has_resources_ready(resource_request):
|
| 133 |
+
return None
|
| 134 |
+
|
| 135 |
+
self._used_resources.append(resource_request)
|
| 136 |
+
return self._resource_cls(
|
| 137 |
+
bundles=resource_request.bundles, resource_request=resource_request
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
def free_resources(self, acquired_resource: AcquiredResources):
|
| 141 |
+
resources = acquired_resource.resource_request
|
| 142 |
+
self._used_resources.remove(resources)
|
| 143 |
+
|
| 144 |
+
def clear(self):
|
| 145 |
+
# Reset internal state
|
| 146 |
+
self._requested_resources = []
|
| 147 |
+
self._used_resources = []
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/resources/placement_group.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
from collections import defaultdict
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from typing import Dict, List, Optional, Set
|
| 5 |
+
|
| 6 |
+
import ray
|
| 7 |
+
from ray.air.execution.resources.request import (
|
| 8 |
+
AcquiredResources,
|
| 9 |
+
RemoteRayEntity,
|
| 10 |
+
ResourceRequest,
|
| 11 |
+
)
|
| 12 |
+
from ray.air.execution.resources.resource_manager import ResourceManager
|
| 13 |
+
from ray.util.annotations import DeveloperAPI
|
| 14 |
+
from ray.util.placement_group import PlacementGroup, remove_placement_group
|
| 15 |
+
from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@DeveloperAPI
|
| 19 |
+
@dataclass
|
| 20 |
+
class PlacementGroupAcquiredResources(AcquiredResources):
|
| 21 |
+
placement_group: PlacementGroup
|
| 22 |
+
|
| 23 |
+
def _annotate_remote_entity(
|
| 24 |
+
self, entity: RemoteRayEntity, bundle: Dict[str, float], bundle_index: int
|
| 25 |
+
) -> RemoteRayEntity:
|
| 26 |
+
bundle = bundle.copy()
|
| 27 |
+
num_cpus = bundle.pop("CPU", 0)
|
| 28 |
+
num_gpus = bundle.pop("GPU", 0)
|
| 29 |
+
memory = bundle.pop("memory", 0.0)
|
| 30 |
+
|
| 31 |
+
return entity.options(
|
| 32 |
+
scheduling_strategy=PlacementGroupSchedulingStrategy(
|
| 33 |
+
placement_group=self.placement_group,
|
| 34 |
+
placement_group_bundle_index=bundle_index,
|
| 35 |
+
placement_group_capture_child_tasks=True,
|
| 36 |
+
),
|
| 37 |
+
num_cpus=num_cpus,
|
| 38 |
+
num_gpus=num_gpus,
|
| 39 |
+
memory=memory,
|
| 40 |
+
resources=bundle,
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@DeveloperAPI
|
| 45 |
+
class PlacementGroupResourceManager(ResourceManager):
|
| 46 |
+
"""Resource manager using placement groups as the resource backend.
|
| 47 |
+
|
| 48 |
+
This manager will use placement groups to fulfill resource requests. Requesting
|
| 49 |
+
a resource will schedule the placement group. Acquiring a resource will
|
| 50 |
+
return a ``PlacementGroupAcquiredResources`` that can be used to schedule
|
| 51 |
+
Ray tasks and actors on the placement group. Freeing an acquired resource
|
| 52 |
+
will destroy the associated placement group.
|
| 53 |
+
|
| 54 |
+
Ray core does not emit events when resources are available. Instead, the
|
| 55 |
+
scheduling state has to be periodically updated.
|
| 56 |
+
|
| 57 |
+
Per default, placement group scheduling state is refreshed every time when
|
| 58 |
+
resource state is inquired, but not more often than once every ``update_interval_s``
|
| 59 |
+
seconds. Alternatively, staging futures can be retrieved (and awaited) with
|
| 60 |
+
``get_resource_futures()`` and state update can be force with ``update_state()``.
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
update_interval_s: Minimum interval in seconds between updating scheduling
|
| 64 |
+
state of placement groups.
|
| 65 |
+
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
_resource_cls: AcquiredResources = PlacementGroupAcquiredResources
|
| 69 |
+
|
| 70 |
+
def __init__(self, update_interval_s: float = 0.1):
|
| 71 |
+
# Internally, the placement group lifecycle is like this:
|
| 72 |
+
# - Resources are requested with ``request_resources()``
|
| 73 |
+
# - A placement group is scheduled ("staged")
|
| 74 |
+
# - A ``PlacementGroup.ready()`` future is scheduled ("staging future")
|
| 75 |
+
# - We update the scheduling state when we need to
|
| 76 |
+
# (e.g. when ``has_resources_ready()`` is called)
|
| 77 |
+
# - When staging futures resolve, a placement group is moved from "staging"
|
| 78 |
+
# to "ready"
|
| 79 |
+
# - When a resource request is canceled, we remove a placement group from
|
| 80 |
+
# "staging". If there are not staged placement groups
|
| 81 |
+
# (because they are already "ready"), we remove one from "ready" instead.
|
| 82 |
+
# - When a resource is acquired, the pg is removed from "ready" and moved
|
| 83 |
+
# to "acquired"
|
| 84 |
+
# - When a resource is freed, the pg is removed from "acquired" and destroyed
|
| 85 |
+
|
| 86 |
+
# Mapping of placement group to request
|
| 87 |
+
self._pg_to_request: Dict[PlacementGroup, ResourceRequest] = {}
|
| 88 |
+
|
| 89 |
+
# PGs that are staged but not "ready", yet (i.e. not CREATED)
|
| 90 |
+
self._request_to_staged_pgs: Dict[
|
| 91 |
+
ResourceRequest, Set[PlacementGroup]
|
| 92 |
+
] = defaultdict(set)
|
| 93 |
+
|
| 94 |
+
# PGs that are CREATED and can be used by tasks and actors
|
| 95 |
+
self._request_to_ready_pgs: Dict[
|
| 96 |
+
ResourceRequest, Set[PlacementGroup]
|
| 97 |
+
] = defaultdict(set)
|
| 98 |
+
|
| 99 |
+
# Staging futures used to update internal state.
|
| 100 |
+
# We keep a double mapping here for better lookup efficiency.
|
| 101 |
+
self._staging_future_to_pg: Dict[ray.ObjectRef, PlacementGroup] = dict()
|
| 102 |
+
self._pg_to_staging_future: Dict[PlacementGroup, ray.ObjectRef] = dict()
|
| 103 |
+
|
| 104 |
+
# Set of acquired PGs. We keep track of these here to make sure we
|
| 105 |
+
# only free PGs that this manager managed.
|
| 106 |
+
self._acquired_pgs: Set[PlacementGroup] = set()
|
| 107 |
+
|
| 108 |
+
# Minimum time between updates of the internal state
|
| 109 |
+
self.update_interval_s = update_interval_s
|
| 110 |
+
self._last_update = time.monotonic() - self.update_interval_s - 1
|
| 111 |
+
|
| 112 |
+
def get_resource_futures(self) -> List[ray.ObjectRef]:
|
| 113 |
+
return list(self._staging_future_to_pg.keys())
|
| 114 |
+
|
| 115 |
+
def _maybe_update_state(self):
|
| 116 |
+
now = time.monotonic()
|
| 117 |
+
if now > self._last_update + self.update_interval_s:
|
| 118 |
+
self.update_state()
|
| 119 |
+
|
| 120 |
+
def update_state(self):
|
| 121 |
+
ready, not_ready = ray.wait(
|
| 122 |
+
list(self._staging_future_to_pg.keys()),
|
| 123 |
+
num_returns=len(self._staging_future_to_pg),
|
| 124 |
+
timeout=0,
|
| 125 |
+
)
|
| 126 |
+
for future in ready:
|
| 127 |
+
# Remove staging future
|
| 128 |
+
pg = self._staging_future_to_pg.pop(future)
|
| 129 |
+
self._pg_to_staging_future.pop(pg)
|
| 130 |
+
# Fetch resource request
|
| 131 |
+
request = self._pg_to_request[pg]
|
| 132 |
+
# Remove from staging, add to ready
|
| 133 |
+
self._request_to_staged_pgs[request].remove(pg)
|
| 134 |
+
self._request_to_ready_pgs[request].add(pg)
|
| 135 |
+
self._last_update = time.monotonic()
|
| 136 |
+
|
| 137 |
+
def request_resources(self, resource_request: ResourceRequest):
|
| 138 |
+
pg = resource_request.to_placement_group()
|
| 139 |
+
self._pg_to_request[pg] = resource_request
|
| 140 |
+
self._request_to_staged_pgs[resource_request].add(pg)
|
| 141 |
+
|
| 142 |
+
future = pg.ready()
|
| 143 |
+
self._staging_future_to_pg[future] = pg
|
| 144 |
+
self._pg_to_staging_future[pg] = future
|
| 145 |
+
|
| 146 |
+
def cancel_resource_request(self, resource_request: ResourceRequest):
|
| 147 |
+
if self._request_to_staged_pgs[resource_request]:
|
| 148 |
+
pg = self._request_to_staged_pgs[resource_request].pop()
|
| 149 |
+
|
| 150 |
+
# PG was staging
|
| 151 |
+
future = self._pg_to_staging_future.pop(pg)
|
| 152 |
+
self._staging_future_to_pg.pop(future)
|
| 153 |
+
|
| 154 |
+
# Cancel the pg.ready task.
|
| 155 |
+
# Otherwise, it will be pending node assignment forever.
|
| 156 |
+
ray.cancel(future)
|
| 157 |
+
else:
|
| 158 |
+
# PG might be ready
|
| 159 |
+
pg = self._request_to_ready_pgs[resource_request].pop()
|
| 160 |
+
if not pg:
|
| 161 |
+
raise RuntimeError(
|
| 162 |
+
"Cannot cancel resource request: No placement group was "
|
| 163 |
+
f"staged or is ready. Make sure to not cancel more resource "
|
| 164 |
+
f"requests than you've created. Request: {resource_request}"
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
self._pg_to_request.pop(pg)
|
| 168 |
+
ray.util.remove_placement_group(pg)
|
| 169 |
+
|
| 170 |
+
def has_resources_ready(self, resource_request: ResourceRequest) -> bool:
|
| 171 |
+
if not bool(len(self._request_to_ready_pgs[resource_request])):
|
| 172 |
+
# Only update state if needed
|
| 173 |
+
self._maybe_update_state()
|
| 174 |
+
|
| 175 |
+
return bool(len(self._request_to_ready_pgs[resource_request]))
|
| 176 |
+
|
| 177 |
+
def acquire_resources(
|
| 178 |
+
self, resource_request: ResourceRequest
|
| 179 |
+
) -> Optional[PlacementGroupAcquiredResources]:
|
| 180 |
+
if not self.has_resources_ready(resource_request):
|
| 181 |
+
return None
|
| 182 |
+
|
| 183 |
+
pg = self._request_to_ready_pgs[resource_request].pop()
|
| 184 |
+
self._acquired_pgs.add(pg)
|
| 185 |
+
|
| 186 |
+
return self._resource_cls(placement_group=pg, resource_request=resource_request)
|
| 187 |
+
|
| 188 |
+
def free_resources(self, acquired_resource: PlacementGroupAcquiredResources):
|
| 189 |
+
pg = acquired_resource.placement_group
|
| 190 |
+
|
| 191 |
+
self._acquired_pgs.remove(pg)
|
| 192 |
+
remove_placement_group(pg)
|
| 193 |
+
self._pg_to_request.pop(pg)
|
| 194 |
+
|
| 195 |
+
def clear(self):
|
| 196 |
+
if not ray.is_initialized():
|
| 197 |
+
return
|
| 198 |
+
|
| 199 |
+
for staged_pgs in self._request_to_staged_pgs.values():
|
| 200 |
+
for staged_pg in staged_pgs:
|
| 201 |
+
remove_placement_group(staged_pg)
|
| 202 |
+
|
| 203 |
+
for ready_pgs in self._request_to_ready_pgs.values():
|
| 204 |
+
for ready_pg in ready_pgs:
|
| 205 |
+
remove_placement_group(ready_pg)
|
| 206 |
+
|
| 207 |
+
for acquired_pg in self._acquired_pgs:
|
| 208 |
+
remove_placement_group(acquired_pg)
|
| 209 |
+
|
| 210 |
+
# Reset internal state
|
| 211 |
+
self.__init__(update_interval_s=self.update_interval_s)
|
| 212 |
+
|
| 213 |
+
def __del__(self):
|
| 214 |
+
self.clear()
|
tool_server/.venv/lib/python3.12/site-packages/ray/air/execution/resources/request.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import abc
|
| 2 |
+
import json
|
| 3 |
+
from copy import deepcopy
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from inspect import signature
|
| 6 |
+
from typing import Dict, List, Union
|
| 7 |
+
|
| 8 |
+
import ray
|
| 9 |
+
from ray.util import placement_group
|
| 10 |
+
from ray.util.annotations import DeveloperAPI
|
| 11 |
+
|
| 12 |
+
RemoteRayEntity = Union[ray.remote_function.RemoteFunction, ray.actor.ActorClass]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _sum_bundles(bundles: List[Dict[str, float]]) -> Dict[str, float]:
|
| 16 |
+
"""Sum all resources in a list of resource bundles.
|
| 17 |
+
|
| 18 |
+
Args:
|
| 19 |
+
bundles: List of resource bundles.
|
| 20 |
+
|
| 21 |
+
Returns: Dict containing all resources summed up.
|
| 22 |
+
"""
|
| 23 |
+
resources = {}
|
| 24 |
+
for bundle in bundles:
|
| 25 |
+
for k, v in bundle.items():
|
| 26 |
+
resources[k] = resources.get(k, 0) + v
|
| 27 |
+
return resources
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@DeveloperAPI
|
| 31 |
+
class ResourceRequest:
|
| 32 |
+
"""Request for resources.
|
| 33 |
+
|
| 34 |
+
This class is used to define a resource request. A resource request comprises one
|
| 35 |
+
or more bundles of resources and instructions on the scheduling behavior.
|
| 36 |
+
|
| 37 |
+
The resource request can be submitted to a resource manager, which will
|
| 38 |
+
schedule the resources. Depending on the resource backend, this may instruct
|
| 39 |
+
Ray to scale up (autoscaling).
|
| 40 |
+
|
| 41 |
+
Resource requests are compatible with the most fine-grained low-level resource
|
| 42 |
+
backend, which are Ray placement groups.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
bundles: A list of bundles which represent the resources requirements.
|
| 46 |
+
E.g. ``[{"CPU": 1, "GPU": 1}]``.
|
| 47 |
+
strategy: The scheduling strategy to acquire the bundles.
|
| 48 |
+
|
| 49 |
+
- "PACK": Packs Bundles into as few nodes as possible.
|
| 50 |
+
- "SPREAD": Places Bundles across distinct nodes as even as possible.
|
| 51 |
+
- "STRICT_PACK": Packs Bundles into one node. The group is
|
| 52 |
+
not allowed to span multiple nodes.
|
| 53 |
+
- "STRICT_SPREAD": Packs Bundles across distinct nodes.
|
| 54 |
+
*args: Passed to the call of ``placement_group()``, if applicable.
|
| 55 |
+
**kwargs: Passed to the call of ``placement_group()``, if applicable.
|
| 56 |
+
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
def __init__(
|
| 60 |
+
self,
|
| 61 |
+
bundles: List[Dict[str, Union[int, float]]],
|
| 62 |
+
strategy: str = "PACK",
|
| 63 |
+
*args,
|
| 64 |
+
**kwargs,
|
| 65 |
+
):
|
| 66 |
+
if not bundles:
|
| 67 |
+
raise ValueError("Cannot initialize a ResourceRequest with zero bundles.")
|
| 68 |
+
|
| 69 |
+
# Remove empty resource keys
|
| 70 |
+
self._bundles = [
|
| 71 |
+
{k: float(v) for k, v in bundle.items() if v != 0} for bundle in bundles
|
| 72 |
+
]
|
| 73 |
+
|
| 74 |
+
# Check if the head bundle is empty (no resources defined or all resources
|
| 75 |
+
# are 0 (and thus removed in the previous step)
|
| 76 |
+
if not self._bundles[0]:
|
| 77 |
+
# This is when the head bundle doesn't need resources.
|
| 78 |
+
self._head_bundle_is_empty = True
|
| 79 |
+
self._bundles.pop(0)
|
| 80 |
+
|
| 81 |
+
if not self._bundles:
|
| 82 |
+
raise ValueError(
|
| 83 |
+
"Cannot initialize a ResourceRequest with an empty head "
|
| 84 |
+
"and zero worker bundles."
|
| 85 |
+
)
|
| 86 |
+
else:
|
| 87 |
+
self._head_bundle_is_empty = False
|
| 88 |
+
|
| 89 |
+
self._strategy = strategy
|
| 90 |
+
self._args = args
|
| 91 |
+
self._kwargs = kwargs
|
| 92 |
+
|
| 93 |
+
self._hash = None
|
| 94 |
+
self._bound = None
|
| 95 |
+
|
| 96 |
+
self._bind()
|
| 97 |
+
|
| 98 |
+
@property
|
| 99 |
+
def head_bundle_is_empty(self):
|
| 100 |
+
"""Returns True if head bundle is empty while child bundles
|
| 101 |
+
need resources.
|
| 102 |
+
|
| 103 |
+
This is considered an internal API within Tune.
|
| 104 |
+
"""
|
| 105 |
+
return self._head_bundle_is_empty
|
| 106 |
+
|
| 107 |
+
@property
|
| 108 |
+
@DeveloperAPI
|
| 109 |
+
def head_cpus(self) -> float:
|
| 110 |
+
"""Returns the number of cpus in the head bundle."""
|
| 111 |
+
return 0.0 if self._head_bundle_is_empty else self._bundles[0].get("CPU", 0.0)
|
| 112 |
+
|
| 113 |
+
@property
|
| 114 |
+
@DeveloperAPI
|
| 115 |
+
def bundles(self) -> List[Dict[str, float]]:
|
| 116 |
+
"""Returns a deep copy of resource bundles"""
|
| 117 |
+
return deepcopy(self._bundles)
|
| 118 |
+
|
| 119 |
+
@property
|
| 120 |
+
def required_resources(self) -> Dict[str, float]:
|
| 121 |
+
"""Returns a dict containing the sums of all resources"""
|
| 122 |
+
return _sum_bundles(self._bundles)
|
| 123 |
+
|
| 124 |
+
@property
|
| 125 |
+
@DeveloperAPI
|
| 126 |
+
def strategy(self) -> str:
|
| 127 |
+
"""Returns the placement strategy"""
|
| 128 |
+
return self._strategy
|
| 129 |
+
|
| 130 |
+
def _bind(self):
|
| 131 |
+
"""Bind the args and kwargs to the `placement_group()` signature.
|
| 132 |
+
|
| 133 |
+
We bind the args and kwargs, so we can compare equality of two resource
|
| 134 |
+
requests. The main reason for this is that the `placement_group()` API
|
| 135 |
+
can evolve independently from the ResourceRequest API (e.g. adding new
|
| 136 |
+
arguments). Then, `ResourceRequest(bundles, strategy, arg=arg)` should
|
| 137 |
+
be the same as `ResourceRequest(bundles, strategy, arg)`.
|
| 138 |
+
"""
|
| 139 |
+
sig = signature(placement_group)
|
| 140 |
+
try:
|
| 141 |
+
self._bound = sig.bind(
|
| 142 |
+
self._bundles, self._strategy, *self._args, **self._kwargs
|
| 143 |
+
)
|
| 144 |
+
except Exception as exc:
|
| 145 |
+
raise RuntimeError(
|
| 146 |
+
"Invalid definition for resource request. Please check "
|
| 147 |
+
"that you passed valid arguments to the ResourceRequest "
|
| 148 |
+
"object."
|
| 149 |
+
) from exc
|
| 150 |
+
|
| 151 |
+
def to_placement_group(self):
|
| 152 |
+
return placement_group(*self._bound.args, **self._bound.kwargs)
|
| 153 |
+
|
| 154 |
+
def __eq__(self, other: "ResourceRequest"):
|
| 155 |
+
return (
|
| 156 |
+
isinstance(other, ResourceRequest)
|
| 157 |
+
and self._bound == other._bound
|
| 158 |
+
and self.head_bundle_is_empty == other.head_bundle_is_empty
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
def __hash__(self):
|
| 162 |
+
if not self._hash:
|
| 163 |
+
# Cache hash
|
| 164 |
+
self._hash = hash(
|
| 165 |
+
json.dumps(
|
| 166 |
+
{"args": self._bound.args, "kwargs": self._bound.kwargs},
|
| 167 |
+
sort_keys=True,
|
| 168 |
+
indent=0,
|
| 169 |
+
ensure_ascii=True,
|
| 170 |
+
)
|
| 171 |
+
)
|
| 172 |
+
return self._hash
|
| 173 |
+
|
| 174 |
+
def __getstate__(self):
|
| 175 |
+
state = self.__dict__.copy()
|
| 176 |
+
state.pop("_hash", None)
|
| 177 |
+
state.pop("_bound", None)
|
| 178 |
+
return state
|
| 179 |
+
|
| 180 |
+
def __setstate__(self, state):
|
| 181 |
+
self.__dict__.update(state)
|
| 182 |
+
self._hash = None
|
| 183 |
+
self._bound = None
|
| 184 |
+
self._bind()
|
| 185 |
+
|
| 186 |
+
def __repr__(self) -> str:
|
| 187 |
+
return (
|
| 188 |
+
f"<ResourceRequest (_bound={self._bound}, "
|
| 189 |
+
f"head_bundle_is_empty={self.head_bundle_is_empty})>"
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
@DeveloperAPI
|
| 194 |
+
@dataclass
|
| 195 |
+
class AcquiredResources(abc.ABC):
|
| 196 |
+
"""Base class for resources that have been acquired.
|
| 197 |
+
|
| 198 |
+
Acquired resources can be associated to Ray objects, which can then be
|
| 199 |
+
scheduled using these resources.
|
| 200 |
+
|
| 201 |
+
Internally this can point e.g. to a placement group, a placement
|
| 202 |
+
group bundle index, or just raw resources.
|
| 203 |
+
|
| 204 |
+
The main API is the `annotate_remote_entities` method. This will associate
|
| 205 |
+
remote Ray objects (tasks and actors) with the acquired resources by setting
|
| 206 |
+
the Ray remote options to use the acquired resources.
|
| 207 |
+
"""
|
| 208 |
+
|
| 209 |
+
resource_request: ResourceRequest
|
| 210 |
+
|
| 211 |
+
def annotate_remote_entities(
|
| 212 |
+
self, entities: List[RemoteRayEntity]
|
| 213 |
+
) -> List[Union[RemoteRayEntity]]:
|
| 214 |
+
"""Return remote ray entities (tasks/actors) to use the acquired resources.
|
| 215 |
+
|
| 216 |
+
The first entity will be associated with the first bundle, the second
|
| 217 |
+
entity will be associated with the second bundle, etc.
|
| 218 |
+
|
| 219 |
+
Args:
|
| 220 |
+
entities: Remote Ray entities to annotate with the acquired resources.
|
| 221 |
+
"""
|
| 222 |
+
bundles = self.resource_request.bundles
|
| 223 |
+
|
| 224 |
+
# Also count the empty head bundle as a bundle
|
| 225 |
+
num_bundles = len(bundles) + int(self.resource_request.head_bundle_is_empty)
|
| 226 |
+
|
| 227 |
+
if len(entities) > num_bundles:
|
| 228 |
+
raise RuntimeError(
|
| 229 |
+
f"The number of callables to annotate ({len(entities)}) cannot "
|
| 230 |
+
f"exceed the number of available bundles ({num_bundles})."
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
annotated = []
|
| 234 |
+
|
| 235 |
+
if self.resource_request.head_bundle_is_empty:
|
| 236 |
+
# The empty head bundle is place on the first bundle index with empty
|
| 237 |
+
# resources.
|
| 238 |
+
annotated.append(
|
| 239 |
+
self._annotate_remote_entity(entities[0], {}, bundle_index=0)
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
# Shift the remaining entities
|
| 243 |
+
entities = entities[1:]
|
| 244 |
+
|
| 245 |
+
for i, (entity, bundle) in enumerate(zip(entities, bundles)):
|
| 246 |
+
annotated.append(
|
| 247 |
+
self._annotate_remote_entity(entity, bundle, bundle_index=i)
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
return annotated
|
| 251 |
+
|
| 252 |
+
def _annotate_remote_entity(
|
| 253 |
+
self, entity: RemoteRayEntity, bundle: Dict[str, float], bundle_index: int
|
| 254 |
+
) -> RemoteRayEntity:
|
| 255 |
+
raise NotImplementedError
|