Skip to content

Commit a43a025

Browse files
committed
feat: support shared actor pools across DAG stages
1 parent 4a1140e commit a43a025

29 files changed

Lines changed: 1132 additions & 125 deletions

‎README-zh.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,7 @@ RayOrch 有意保持精简的公开编程模型:
154154
| --- | --- |
155155
| UDF | 对一个批次执行普通 Python 计算的类或函数 |
156156
| `RayModule` | 声明 UDF 构造方式、副本数、批大小、恢复策略和 Ray Actor 选项 |
157+
| `ActorPool` | 让多个逻辑 Call 显式复用同一组已初始化的有状态 Actor |
157158
| `Pipeline` | 连接计算阶段形成静态拓扑,并提供精简的一次性入口 `pipeline.run(...)` |
158159
| `rayorch.F` | 显式声明展开、过滤、广播和归并 |
159160
| `Executor` | 管理持久化 Actor 和执行生命周期 |
@@ -196,6 +197,14 @@ print(result.outputs) # [3, 4, 5]
196197

197198
一次有限输入直接使用 `pipeline.run(...)`:它会创建一个 `Executor`、返回 `RunResult`,然后关闭临时 Actor 池;如果多次调用需要复用同一批 Actor 和已加载模型,则使用 `Executor(pipeline)`。函数式写法 `ro.run(pipeline, ...)` 仍与 `pipeline.run(...)` 完全等价。
198199

200+
如果 DAG 中两个阶段本来就是同一个模型栈的不同方法,可以显式复用一个物理 Actor 池,同时保留各自独立的批大小、血缘、恢复策略和指标:
201+
202+
```python
203+
pool = ro.ActorPool(ModelStack).pre_init(model_path).ray_options(replicas=4, num_gpus=1)
204+
layout = pool.entrypoint("layout").ray_options(batch_size=8)
205+
recognize = pool.entrypoint("recognize").ray_options(batch_size=16)
206+
```
207+
199208
### 3.1 `rayorch.F`:显式的数据形态变换
200209

201210
结构关系通过显式 API 表达,而不是隐藏在框架约定中。下表使用 `A:[a0, a1]` 表示挂在父项 A 上的一个有序分组,使用 `A/a0` 表示一个可以独立调度、同时保留父项 A 和序号 0 的子项。

‎README.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,7 @@ RayOrch deliberately keeps the public model small:
154154
| --- | --- |
155155
| UDF | Ordinary Python class or function that processes a batch |
156156
| `RayModule` | UDF construction, replicas, batch size, recovery, and Ray actor options |
157+
| `ActorPool` | Explicitly share one initialized stateful actor pool across several logical Calls |
157158
| `Pipeline` | Static topology connecting compute stages, plus the concise one-shot `pipeline.run(...)` entry point |
158159
| `rayorch.F` | Explicit expansion, filtering, broadcast, and reduction |
159160
| `Executor` | Persistent actor ownership and execution lifecycle |
@@ -196,6 +197,14 @@ Read it as: **write batched UDFs → connect them in a Pipeline → assign resou
196197

197198
Use `pipeline.run(...)` for one finite execution. It creates an `Executor`, returns the `RunResult`, and closes the temporary actor pools; use `Executor(pipeline)` when several calls should reuse the same actors and loaded models. The functional form `ro.run(pipeline, ...)` remains equivalent to `pipeline.run(...)`.
198199

200+
When two DAG stages are methods of the same model stack, opt in to one shared physical pool while keeping separate batching, lineage, recovery, and metrics:
201+
202+
```python
203+
pool = ro.ActorPool(ModelStack).pre_init(model_path).ray_options(replicas=4, num_gpus=1)
204+
layout = pool.entrypoint("layout").ray_options(batch_size=8)
205+
recognize = pool.entrypoint("recognize").ray_options(batch_size=16)
206+
```
207+
199208
### 3.1 `rayorch.F`: explicit shape transformations
200209

201210
Structural relationships are explicit rather than hidden in framework conventions. In the table below, `A:[a0, a1]` is one ordered group attached to parent A, while `A/a0` is one independently schedulable child that retains both parent A and ordinal 0.

‎docs/runtime_architecture.md‎

Lines changed: 37 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,12 @@ _runtime/ input batch state, dispatch indexes, and result materialization
99
_execution/ Ray actors, RPC lifecycle, and worker ABI
1010
```
1111

12-
The package root exports authoring (`Pipeline`, `RayModule`, `Port`, `F.*`),
13-
execution (`Executor`, `run`, `RunResult`), and recovery (`RecoveryPolicy`).
14-
Internal identity and worker-protocol types stay private so their representation
15-
can evolve without expanding the compatibility surface. The UDF-facing
16-
`RecordFailure` and `GroupFailure` values remain available from the package root
17-
and can also be imported from `rayorch.failures`.
12+
The package root exports authoring (`Pipeline`, `RayModule`, `ActorPool`, `Port`,
13+
`F.*`), execution (`Executor`, `run`, `RunResult`), and recovery
14+
(`RecoveryPolicy`). Internal identity and worker-protocol types stay private so
15+
their representation can evolve without expanding the compatibility surface.
16+
The UDF-facing `RecordFailure` and `GroupFailure` values remain available from
17+
the package root and can also be imported from `rayorch.failures`.
1818

1919
Every Call input follows one propagation rule. The Grain becomes runnable only
2020
when all inputs are `PRESENT`; a `DROPPED` input drops its outputs, while a
@@ -39,6 +39,37 @@ the Call's `batch_size`. `input_batch_size` instead counts source rows, while
3939
identity remains part of runtime state only for lineage and `GroupFailure`
4040
isolation, not as a batching policy.
4141

42+
## Calls and shared actor pools
43+
44+
A normal `RayModule` Call owns an implicit actor pool, preserving the original
45+
one-Call/one-pool behavior. `ActorPool` is the explicit opt-in for several
46+
logical Calls to share one stateful object:
47+
48+
```python
49+
pool = (
50+
ActorPool(ModelStack)
51+
.pre_init(model_path)
52+
.ray_options(replicas=4, num_gpus=1)
53+
)
54+
layout = pool.entrypoint("layout").ray_options(batch_size=8)
55+
recognize = pool.entrypoint("recognize").ray_options(batch_size=16)
56+
```
57+
58+
Calls retain distinct `CallRef`s, READY queues, Worker layouts, recovery
59+
policies, metrics, and lineage. They map to one private `PoolRef` that owns actor
60+
construction, replicas, Ray resources, and runtime environment. Pool scheduling
61+
is round-robin across runnable Calls; after choosing a Call, its existing
62+
immediate-retry/READY/deferred-recovery priority and input-batch order apply.
63+
Each actor executes one microbatch to completion before another Call can use it,
64+
so this is stage multiplexing at RPC boundaries rather than preemption.
65+
66+
Entrypoints may share stable model state but must exchange request data through
67+
DAG Ports. An entrypoint must not synchronously wait for another Call assigned
68+
to the same pool, and the runtime does not provide lineage-to-replica affinity
69+
for hidden actor-local request state. An infrastructure failure requeues only
70+
the failed Call's microbatch, replaces that actor replica, waits for its
71+
initialization to complete, and then returns it to the shared pool.
72+
4273
## Group shape
4374

4475
Compiler analysis records each Port's structural group depth; it does not infer

‎rayorch/__init__.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from . import benchmark, functional as F
44
from ._execution.executor import Executor
55
from ._model import ItemOutcome
6-
from .api import Pipeline, Port, RayModule, function
6+
from .api import ActorPool, Pipeline, Port, RayModule, function
77
from .errors import CompileError, ExecutionError
88
from .failures import GroupFailure, RecordFailure
99
from .recovery import RecoveryPolicy
@@ -13,6 +13,7 @@
1313

1414
__all__ = [
1515
"CompileError",
16+
"ActorPool",
1617
"ExecutionError",
1718
"Executor",
1819
"F",

‎rayorch/_builder.py‎

Lines changed: 81 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@
55
import contextvars
66
import inspect
77
import itertools
8+
from dataclasses import dataclass
89
from typing import Any
910

10-
from ._model import CallRef, DomainRef, PortRef
11+
from ._model import CallRef, DomainRef, PoolRef, PortRef
1112
from .api import Pipeline, Port, RayModule
1213
from .errors import CompileError
1314
from ._program.compiler import compile_logical
@@ -36,20 +37,36 @@
3637
)
3738

3839

40+
@dataclass(frozen=True, slots=True)
41+
class _ExecutionBinding:
42+
"""One traced Call's logical entrypoint and physical pool assignment."""
43+
44+
pool: PoolRef
45+
udf: UdfSpec
46+
call_options: tuple[tuple[str, Any], ...]
47+
pool_options: tuple[tuple[str, Any], ...]
48+
entrypoint: str
49+
50+
3951
class ProgramBuilder:
4052
"""Capture authoring operations without deriving runtime facts or Effects."""
4153

4254
def __init__(self, source_names: tuple[str, ...]) -> None:
4355
self.owner = next(_TRACE_IDS)
4456
self.next_port = 0
4557
self.next_call = 0
58+
self.next_pool = 0
4659
self.next_domain = 1
4760
self.calls: dict[CallRef, CallSpec] = {}
4861
self.ports: dict[PortRef, PortSpec] = {}
4962
self.domains: dict[DomainRef, DomainSpec] = {
5063
DomainRef(0): DomainSpec(DomainRef(0), debug_name="root")
5164
}
5265
self.call_options: dict[CallRef, tuple[tuple[str, Any], ...]] = {}
66+
self.call_pools: dict[CallRef, PoolRef] = {}
67+
self.pool_udfs: dict[PoolRef, UdfSpec] = {}
68+
self.pool_options: dict[PoolRef, tuple[tuple[str, Any], ...]] = {}
69+
self._shared_pool_refs: dict[int, PoolRef] = {}
5370
self._view_intern: dict[tuple[Any, ...], tuple[PortRef, ...]] = {}
5471

5572
self.source_ports = tuple(
@@ -94,14 +111,17 @@ def call(
94111

95112
call = CallRef(self.next_call)
96113
self.next_call += 1
114+
binding = self._execution_binding(module)
97115
self.calls[call] = CallSpec(
98116
call,
99-
UdfSpec(module.udf, module.init_args, tuple(module.init_kwargs.items())),
117+
binding.udf,
100118
execution_domain,
101119
tuple(positional_inputs),
102120
tuple(keyword_inputs),
121+
binding.entrypoint,
103122
)
104-
self.call_options[call] = tuple(module.options.items())
123+
self.call_options[call] = binding.call_options
124+
self.call_pools[call] = binding.pool
105125
outputs = tuple(
106126
self._new_port(execution_domain, CallOutputOrigin(call, output_index))
107127
for output_index in range(module.num_outputs)
@@ -233,9 +253,67 @@ def build(self, output_tree: object, *, optimize: bool) -> CompiledProgram:
233253
return compile_logical(
234254
logical,
235255
freeze_mapping(self.call_options),
256+
freeze_mapping(self.call_pools),
257+
freeze_mapping(self.pool_udfs),
258+
freeze_mapping(self.pool_options),
236259
optimize=optimize,
237260
)
238261

262+
def _execution_binding(self, module: RayModule) -> _ExecutionBinding:
263+
"""Resolve one module invocation to a Call contract and actor pool."""
264+
265+
dispatch_names = {
266+
"batch_size",
267+
"recovery",
268+
"max_retries",
269+
"batch_scope",
270+
"batching_policy",
271+
}
272+
shared = module._actor_pool
273+
if shared is None:
274+
pool = self._new_pool()
275+
target = module.udf
276+
init_args = module.init_args
277+
init_kwargs = module.init_kwargs
278+
call_options = tuple(
279+
(name, value)
280+
for name, value in module.options.items()
281+
if name in dispatch_names
282+
)
283+
pool_options = tuple(
284+
(name, value)
285+
for name, value in module.options.items()
286+
if name not in dispatch_names
287+
)
288+
else:
289+
pool = self._shared_pool_refs.get(id(shared))
290+
if pool is None:
291+
pool = self._new_pool()
292+
self._shared_pool_refs[id(shared)] = pool
293+
target = shared.udf
294+
init_args = shared.init_args
295+
init_kwargs = shared.init_kwargs
296+
call_options = tuple(module.options.items())
297+
pool_options = tuple(shared.options.items())
298+
299+
udf = UdfSpec(target, tuple(init_args), tuple(init_kwargs.items()))
300+
prior_udf = self.pool_udfs.setdefault(pool, udf)
301+
prior_options = self.pool_options.setdefault(pool, pool_options)
302+
if prior_udf != udf or prior_options != pool_options:
303+
raise CompileError("shared ActorPool configuration changed during tracing")
304+
return _ExecutionBinding(
305+
pool,
306+
udf,
307+
call_options,
308+
pool_options,
309+
module._entrypoint,
310+
)
311+
312+
def _new_pool(self) -> PoolRef:
313+
pool = PoolRef(self.next_pool)
314+
self.next_pool += 1
315+
return pool
316+
239317
def _new_port(self, domain: DomainRef, origin: PortOrigin) -> PortRef:
240318
ref = PortRef(self.next_port)
241319
self.next_port += 1

0 commit comments

Comments
 (0)