rarg-ray-patterns 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- rarg_ray_patterns/__init__.py +3 -0
- rarg_ray_patterns/autoscaling.py +203 -0
- rarg_ray_patterns/utils.py +12 -0
- rarg_ray_patterns-0.0.1.dist-info/METADATA +24 -0
- rarg_ray_patterns-0.0.1.dist-info/RECORD +7 -0
- rarg_ray_patterns-0.0.1.dist-info/WHEEL +4 -0
- rarg_ray_patterns-0.0.1.dist-info/licenses/LICENSE +28 -0
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import time
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
import ray
|
|
6
|
+
from ray.util.scheduling_strategies import NodeAffinitySchedulingStrategy
|
|
7
|
+
|
|
8
|
+
from rarg_ray_patterns.utils import wrap_future
|
|
9
|
+
|
|
10
|
+
KEEPALIVE_DURATION = 60.0
|
|
11
|
+
|
|
12
|
+
# Sentinel distinguishing "head node id not yet looked up" from "no head found".
|
|
13
|
+
_UNSET = object()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@ray.remote
|
|
17
|
+
class MonitorActor:
|
|
18
|
+
async def heartbeat(self) -> None:
|
|
19
|
+
"""Block forever; the awaiter sees RayActorError when the actor dies."""
|
|
20
|
+
await asyncio.Event().wait()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@ray.remote
|
|
24
|
+
def keep_alive(timeout: float) -> None:
|
|
25
|
+
"""Sleep for timeout in order to keep the worker (and node) alive"""
|
|
26
|
+
time.sleep(timeout)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@ray.remote(num_cpus=0, num_returns=2)
|
|
30
|
+
def discover_node() -> tuple[Any, Any]:
|
|
31
|
+
"""Return this node's id and a keep-alive ref pinned to the same node.
|
|
32
|
+
|
|
33
|
+
The keep-alive task takes 1 CPU on *this* node specifically (via
|
|
34
|
+
NodeAffinity), so the autoscaler will not reap the node before the caller
|
|
35
|
+
has a chance to schedule a long-lived actor on it.
|
|
36
|
+
"""
|
|
37
|
+
node_id = ray.get_runtime_context().get_node_id()
|
|
38
|
+
keepalive_ref = keep_alive.options(
|
|
39
|
+
num_cpus=1,
|
|
40
|
+
scheduling_strategy=NodeAffinitySchedulingStrategy(node_id, soft=False),
|
|
41
|
+
).remote(KEEPALIVE_DURATION)
|
|
42
|
+
return node_id, keepalive_ref
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class ActorAutoscaler:
|
|
46
|
+
def __init__(
|
|
47
|
+
self, nworkers: int = 10, batch_size: int = 2, install_on_head: bool = False
|
|
48
|
+
):
|
|
49
|
+
self._nworkers: int = nworkers
|
|
50
|
+
self._batch_size: int = batch_size
|
|
51
|
+
self._install_on_head: bool = install_on_head
|
|
52
|
+
# Resolved lazily on first autoscale(); cached because the head node id is
|
|
53
|
+
# stable for the cluster's lifetime. _UNSET until looked up.
|
|
54
|
+
self._head_node_id: Any = _UNSET
|
|
55
|
+
self._workers: dict[str, ray.actor.ActorHandle[Any]] = {}
|
|
56
|
+
# node-id future -> (node-id ObjectRef, keepalive ObjectRef)
|
|
57
|
+
self._pending: dict[
|
|
58
|
+
asyncio.Future[Any], tuple[ray.ObjectRef[Any], ray.ObjectRef[Any]]
|
|
59
|
+
] = {}
|
|
60
|
+
# heartbeat futures held to keep them from being GC'd
|
|
61
|
+
self._heartbeats: set[asyncio.Future[Any]] = set()
|
|
62
|
+
self._closed: bool = False
|
|
63
|
+
|
|
64
|
+
async def close(self) -> None:
|
|
65
|
+
self._closed = True
|
|
66
|
+
|
|
67
|
+
# Cancel pending discovery tasks; collect their futures so we can drain
|
|
68
|
+
# them below. Without that drain, asyncio warns "Future exception was
|
|
69
|
+
# never retrieved" when the TaskCancelledError-bearing futures are GC'd.
|
|
70
|
+
pending_futures = list(self._pending.keys())
|
|
71
|
+
for node_ref, keepalive_ref in self._pending.values():
|
|
72
|
+
ray.cancel(node_ref, force=True)
|
|
73
|
+
ray.cancel(keepalive_ref, force=True)
|
|
74
|
+
self._pending.clear()
|
|
75
|
+
|
|
76
|
+
# Kill monitor actors. Their heartbeat futures will then resolve with
|
|
77
|
+
# RayActorError; same drain rule applies.
|
|
78
|
+
heartbeats = list(self._heartbeats)
|
|
79
|
+
self._heartbeats.clear()
|
|
80
|
+
for worker in self._workers.values():
|
|
81
|
+
ray.kill(worker)
|
|
82
|
+
self._workers.clear()
|
|
83
|
+
|
|
84
|
+
if pending_futures or heartbeats:
|
|
85
|
+
await asyncio.gather(*pending_futures, *heartbeats, return_exceptions=True)
|
|
86
|
+
|
|
87
|
+
def _resolve_head_node_id(self) -> str | None:
|
|
88
|
+
"""Return the head node's id (cached), or None if no head node is found.
|
|
89
|
+
|
|
90
|
+
The head node is the live node carrying Ray's auto-resource
|
|
91
|
+
``node:__internal_head__``.
|
|
92
|
+
"""
|
|
93
|
+
if self._head_node_id is _UNSET:
|
|
94
|
+
self._head_node_id = next(
|
|
95
|
+
(
|
|
96
|
+
n["NodeID"]
|
|
97
|
+
for n in ray.nodes() # type: ignore[no-untyped-call]
|
|
98
|
+
if n.get("Alive") and "node:__internal_head__" in n.get("Resources", {})
|
|
99
|
+
),
|
|
100
|
+
None,
|
|
101
|
+
)
|
|
102
|
+
return self._head_node_id # type: ignore[no-any-return]
|
|
103
|
+
|
|
104
|
+
async def autoscale(self, timeout: float = 1.0) -> None:
|
|
105
|
+
# Drain completed discoveries first so capacity decisions reflect them.
|
|
106
|
+
if self._pending:
|
|
107
|
+
ready, _ = await asyncio.wait(
|
|
108
|
+
self._pending.keys(),
|
|
109
|
+
return_when="ALL_COMPLETED",
|
|
110
|
+
timeout=timeout,
|
|
111
|
+
)
|
|
112
|
+
self._handle_ready(ready)
|
|
113
|
+
|
|
114
|
+
# If we hit capacity (e.g. nworkers shrunk, or a burst overshot),
|
|
115
|
+
# cancel surplus pending work instead of letting it leak extra nodes.
|
|
116
|
+
if len(self._workers) >= self._nworkers:
|
|
117
|
+
for node_ref, keepalive_ref in self._pending.values():
|
|
118
|
+
ray.cancel(node_ref, force=True)
|
|
119
|
+
ray.cancel(keepalive_ref, force=True)
|
|
120
|
+
self._pending.clear()
|
|
121
|
+
print(f"Autoscaler at capacity: {list(self._workers)}")
|
|
122
|
+
return
|
|
123
|
+
|
|
124
|
+
shortfall = self._nworkers - len(self._workers) - len(self._pending)
|
|
125
|
+
requested = min(shortfall, self._batch_size)
|
|
126
|
+
if requested <= 0:
|
|
127
|
+
return
|
|
128
|
+
|
|
129
|
+
# Keep discovery off already-monitored nodes and, unless explicitly enabled,
|
|
130
|
+
# off the head node too.
|
|
131
|
+
excluded = set(self._workers)
|
|
132
|
+
if not self._install_on_head:
|
|
133
|
+
if (head := self._resolve_head_node_id()) is not None:
|
|
134
|
+
excluded.add(head)
|
|
135
|
+
|
|
136
|
+
options: dict[str, Any] = {"num_cpus": 0, "scheduling_strategy": "SPREAD"}
|
|
137
|
+
if excluded:
|
|
138
|
+
options["label_selector"] = {"ray.io/node-id": f"!in({','.join(excluded)})"}
|
|
139
|
+
|
|
140
|
+
print(f"Requesting {requested} nodes")
|
|
141
|
+
for _ in range(requested):
|
|
142
|
+
# num_returns=2 makes .remote() yield a 2-tuple of ObjectRefs, but the
|
|
143
|
+
# type stubs only describe the single-return case.
|
|
144
|
+
node_ref, keepalive_ref = discover_node.options(**options).remote() # type: ignore[misc]
|
|
145
|
+
future = wrap_future(node_ref)
|
|
146
|
+
self._pending[future] = (node_ref, keepalive_ref)
|
|
147
|
+
|
|
148
|
+
def _handle_ready(self, ready: set[asyncio.Future[Any]]) -> None:
|
|
149
|
+
new_nodes = []
|
|
150
|
+
for future in ready:
|
|
151
|
+
_, keepalive_ref = self._pending.pop(future)
|
|
152
|
+
|
|
153
|
+
if future.cancelled():
|
|
154
|
+
ray.cancel(keepalive_ref, force=True)
|
|
155
|
+
continue
|
|
156
|
+
|
|
157
|
+
if exc := future.exception():
|
|
158
|
+
print(f"node discovery failed: {exc!r}")
|
|
159
|
+
ray.cancel(keepalive_ref, force=True)
|
|
160
|
+
continue
|
|
161
|
+
|
|
162
|
+
node_id = future.result()
|
|
163
|
+
if node_id in self._workers:
|
|
164
|
+
# Already monitored; release the keepalive so the node can return
|
|
165
|
+
# to its existing actor's exclusive use.
|
|
166
|
+
ray.cancel(keepalive_ref, force=True)
|
|
167
|
+
continue
|
|
168
|
+
|
|
169
|
+
if not self._install_on_head and node_id == self._resolve_head_node_id():
|
|
170
|
+
# Discovery raced ahead of head-node resolution and landed on the head
|
|
171
|
+
# node; drop it and release the keepalive.
|
|
172
|
+
ray.cancel(keepalive_ref, force=True)
|
|
173
|
+
continue
|
|
174
|
+
|
|
175
|
+
# Pin a long-lived monitor actor to this node. num_cpus=1 makes it the
|
|
176
|
+
# node's permanent CPU consumer so the autoscaler keeps the node alive.
|
|
177
|
+
monitor = MonitorActor.options( # type: ignore[attr-defined]
|
|
178
|
+
num_cpus=0,
|
|
179
|
+
label_selector={"ray.io/node-id": node_id},
|
|
180
|
+
).remote()
|
|
181
|
+
self._workers[node_id] = monitor
|
|
182
|
+
new_nodes.append(node_id)
|
|
183
|
+
|
|
184
|
+
# Free the CPU so the queued actor can claim it. The autoscaler treats
|
|
185
|
+
# the queued actor as resource demand and will not reap the node.
|
|
186
|
+
ray.cancel(keepalive_ref, force=True)
|
|
187
|
+
|
|
188
|
+
# Watch for actor death so we'll reprovision next iteration.
|
|
189
|
+
heartbeat = wrap_future(monitor.heartbeat.remote())
|
|
190
|
+
self._heartbeats.add(heartbeat)
|
|
191
|
+
heartbeat.add_done_callback(self._heartbeats.discard)
|
|
192
|
+
heartbeat.add_done_callback(lambda f, nid=node_id: self._on_actor_dead(nid, f)) # type: ignore[misc]
|
|
193
|
+
|
|
194
|
+
if new_nodes:
|
|
195
|
+
print(f"Procured {len(new_nodes)} nodes: {new_nodes}")
|
|
196
|
+
|
|
197
|
+
def _on_actor_dead(self, node_id: str, future: asyncio.Future[Any]) -> None:
|
|
198
|
+
# Always retrieve the exception so asyncio doesn't warn about it.
|
|
199
|
+
exc = None if future.cancelled() else future.exception()
|
|
200
|
+
if self._closed:
|
|
201
|
+
return
|
|
202
|
+
print(f"Worker on {node_id} died ({exc!r}); will reprovision")
|
|
203
|
+
self._workers.pop(node_id, None)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from typing import TYPE_CHECKING, Any
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
import ray
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def wrap_future(obj_ref: ray.ObjectRef[Any]) -> asyncio.Future[Any]:
|
|
11
|
+
"""Wrap a ray ObjectReference as an asyncio Future"""
|
|
12
|
+
return asyncio.wrap_future(obj_ref.future())
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: rarg-ray-patterns
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Common Ray distributed computing patterns for RARG codebases
|
|
5
|
+
Project-URL: Homepage, https://github.com/ratt-ru/rarg-ray-patterns
|
|
6
|
+
Project-URL: Repository, https://github.com/ratt-ru/rarg-ray-patterns
|
|
7
|
+
Author-email: Simon Perkins <simon.perkins@gmail.com>
|
|
8
|
+
License-Expression: BSD-3-Clause
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Python: >=3.11
|
|
11
|
+
Requires-Dist: ray>=2.55.1
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# rarg-ray-patterns
|
|
15
|
+
|
|
16
|
+
Common Ray distributed computing patterns for RARG codebases
|
|
17
|
+
|
|
18
|
+
## Development
|
|
19
|
+
This package is managed with [uv](https://docs.astral.sh/uv/).
|
|
20
|
+
|
|
21
|
+
- Install: `uv sync`
|
|
22
|
+
- Test: `uv run --group test pytest tests/`
|
|
23
|
+
- Pre-commit hooks gate commits: `uv run --group dev pre-commit run -a`
|
|
24
|
+
- Versioning is via `tbump` — never hand-edit version strings.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
rarg_ray_patterns/__init__.py,sha256=aF7anuHfrsV-HAIPSvOvM4QAfHxlITC3zKuhrydhTh0,90
|
|
2
|
+
rarg_ray_patterns/autoscaling.py,sha256=8A80p-StogvIBdC9Ca2XPKK6cRWqqxpzEeudO5av-A4,7580
|
|
3
|
+
rarg_ray_patterns/utils.py,sha256=twNZqtfSvSGMIEgGMxesm0QEHgjDorTRtkncrZq7yaw,295
|
|
4
|
+
rarg_ray_patterns-0.0.1.dist-info/METADATA,sha256=19rZ3HmxjUaNWApC1aUZ1utRffP7EVN1deU3VzLUZZU,834
|
|
5
|
+
rarg_ray_patterns-0.0.1.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
|
|
6
|
+
rarg_ray_patterns-0.0.1.dist-info/licenses/LICENSE,sha256=veUgsMKjhSCfiOLTWohxVUAuY0xwi3UpZnsXaWzFzjI,1564
|
|
7
|
+
rarg_ray_patterns-0.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
BSD 3-Clause License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026, Rhodes University Centre for Radio Astronomy Techniques & Technologies (RATT)
|
|
4
|
+
|
|
5
|
+
Redistribution and use in source and binary forms, with or without
|
|
6
|
+
modification, are permitted provided that the following conditions are met:
|
|
7
|
+
|
|
8
|
+
1. Redistributions of source code must retain the above copyright notice, this
|
|
9
|
+
list of conditions and the following disclaimer.
|
|
10
|
+
|
|
11
|
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
|
12
|
+
this list of conditions and the following disclaimer in the documentation
|
|
13
|
+
and/or other materials provided with the distribution.
|
|
14
|
+
|
|
15
|
+
3. Neither the name of the copyright holder nor the names of its
|
|
16
|
+
contributors may be used to endorse or promote products derived from
|
|
17
|
+
this software without specific prior written permission.
|
|
18
|
+
|
|
19
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
20
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
21
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
22
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
23
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
24
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
25
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
26
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
27
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
28
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|