Skip to content

Commit 62f28e1

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

29 files changed

Lines changed: 1193 additions & 132 deletions

‎README-zh.md‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ RayOrch 有意保持精简的公开编程模型:
153153
| 对象 | 职责 |
154154
| --- | --- |
155155
| UDF | 对一个批次执行普通 Python 计算的类或函数 |
156-
| `RayModule` | 声明 UDF 构造方式、副本数、批大小、恢复策略和 Ray Actor 选项 |
156+
| `RayModule` | 声明 UDF 构造方式、副本数、批大小、恢复策略和 Ray Actor 选项;同一对象被多次调用时自动复用 Actor |
157157
| `Pipeline` | 连接计算阶段形成静态拓扑,并提供精简的一次性入口 `pipeline.run(...)` |
158158
| `rayorch.F` | 显式声明展开、过滤、广播和归并 |
159159
| `Executor` | 管理持久化 Actor 和执行生命周期 |
@@ -196,6 +196,39 @@ print(result.outputs) # [3, 4, 5]
196196

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

199+
如果 DAG 中多个阶段使用同一个模型栈,只需保留一个 `RayModule` 对象,并通过 `run()` 的普通关键字参数选择操作:
200+
201+
```python
202+
class ModelStack:
203+
def __init__(self, model_path):
204+
self.model = load_model(model_path)
205+
206+
def run(self, values, *, stage):
207+
if stage == "layout":
208+
return self.model.layout(values)
209+
if stage == "recognize":
210+
return self.model.recognize(values)
211+
raise ValueError(stage)
212+
213+
214+
class DocumentPipeline(ro.Pipeline):
215+
def __init__(self, model_path):
216+
# 这一个 RayModule 描述一份完成初始化的模型栈。
217+
self.model = (
218+
ro.RayModule(ModelStack)
219+
.pre_init(model_path)
220+
.ray_options(replicas=4, num_gpus=1, batch_size=16)
221+
)
222+
223+
def forward(self, pages):
224+
# 每次调用都是独立 DAG Call,但会复用同一 RayModule 所拥有的
225+
# Actor 和模型状态。
226+
layouts = self.model(pages, stage="layout")
227+
return self.model(layouts, stage="recognize")
228+
```
229+
230+
这里的 `stage` 是编译期常量,`pages` 和 `layouts` 则是由 RayOrch 追踪血缘的符号 `Port` 输入。两个 Call 仍然拥有独立的数据依赖、READY 队列、恢复过程和指标;Actor 复用由 Python 对象身份自然推导,不增加额外的公开 Pool 抽象。目前共享同一 `RayModule` 的 Calls 也共享该模块的 `batch_size` 和恢复策略。
231+
199232
### 3.1 `rayorch.F`:显式的数据形态变换
200233

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

‎README.md‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ RayOrch deliberately keeps the public model small:
153153
| Object | Responsibility |
154154
| --- | --- |
155155
| UDF | Ordinary Python class or function that processes a batch |
156-
| `RayModule` | UDF construction, replicas, batch size, recovery, and Ray actor options |
156+
| `RayModule` | UDF construction, replicas, batch size, recovery, Ray actor options, and automatic actor reuse when the same object is called more than once |
157157
| `Pipeline` | Static topology connecting compute stages, plus the concise one-shot `pipeline.run(...)` entry point |
158158
| `rayorch.F` | Explicit expansion, filtering, broadcast, and reduction |
159159
| `Executor` | Persistent actor ownership and execution lifecycle |
@@ -196,6 +196,39 @@ Read it as: **write batched UDFs → connect them in a Pipeline → assign resou
196196

197197
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(...)`.
198198

199+
When several DAG stages use the same model stack, keep one `RayModule` object and select the operation through an ordinary keyword argument to `run()`:
200+
201+
```python
202+
class ModelStack:
203+
def __init__(self, model_path):
204+
self.model = load_model(model_path)
205+
206+
def run(self, values, *, stage):
207+
if stage == "layout":
208+
return self.model.layout(values)
209+
if stage == "recognize":
210+
return self.model.recognize(values)
211+
raise ValueError(stage)
212+
213+
214+
class DocumentPipeline(ro.Pipeline):
215+
def __init__(self, model_path):
216+
# This one RayModule describes one initialized model stack.
217+
self.model = (
218+
ro.RayModule(ModelStack)
219+
.pre_init(model_path)
220+
.ray_options(replicas=4, num_gpus=1, batch_size=16)
221+
)
222+
223+
def forward(self, pages):
224+
# Each invocation is an independent DAG Call, while both Calls reuse
225+
# the actors and model state owned by the same RayModule object.
226+
layouts = self.model(pages, stage="layout")
227+
return self.model(layouts, stage="recognize")
228+
```
229+
230+
Here `stage` is a compile-time constant, while `pages` and `layouts` are symbolic `Port` inputs whose lineage is tracked by RayOrch. The two Calls retain independent dependencies, READY queues, recovery, and metrics; actor sharing is inferred from Python object identity and introduces no additional public pool abstraction. Calls sharing one `RayModule` currently also share its `batch_size` and recovery policy.
231+
199232
### 3.1 `rayorch.F`: explicit shape transformations
200233

201234
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: 46 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,11 @@ _execution/ Ray actors, RPC lifecycle, and worker ABI
1010
```
1111

1212
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`.
13+
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,47 @@ 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+
One `RayModule` object describes one initialized stateful compute resource.
45+
Calling that object more than once creates distinct logical Calls that
46+
automatically share its actors:
47+
48+
```python
49+
model = (
50+
RayModule(ModelStack)
51+
.pre_init(model_path)
52+
.ray_options(replicas=4, num_gpus=1, batch_size=16)
53+
)
54+
layout = model(pages, stage="layout")
55+
recognize = model(layout, stage="recognize")
56+
```
57+
58+
`pages` and `layout` are dynamic `Port` inputs. Ordinary keyword values such as
59+
`stage="layout"` are immutable Call metadata forwarded to `run()` with every
60+
Worker batch. Static positional arguments are intentionally unsupported, so
61+
data dependencies remain visually explicit.
62+
63+
Calls retain distinct `CallRef`s, READY queues, Worker layouts, recovery state,
64+
metrics, and lineage. Calls created from the same `RayModule` map to one private
65+
`PoolRef`; calls created from different `RayModule` objects map to different
66+
pools even when they use the same UDF class. This object-identity rule is the
67+
whole public contract—physical pool types remain implementation details. The
68+
module's batching and recovery options apply to all its Calls.
69+
70+
Pool scheduling is round-robin across runnable Calls; after choosing a Call,
71+
its existing immediate-retry/READY/deferred-recovery priority and input-batch
72+
order apply. Each actor executes one microbatch to completion before another
73+
Call can use it, so this is stage multiplexing at RPC boundaries rather than
74+
preemption.
75+
76+
Shared actors may hold stable model state, but request data must flow through
77+
DAG Ports. A UDF must not synchronously wait for a downstream Call using the
78+
same module, and the runtime does not provide lineage-to-replica affinity for
79+
hidden actor-local request state. An infrastructure failure requeues only the
80+
failed Call's microbatch, replaces that physical replica, waits for its
81+
initialization to complete, and then returns it to scheduling.
82+
4283
## Group shape
4384

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

‎rayorch/_builder.py‎

Lines changed: 80 additions & 9 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,35 @@
3637
)
3738

3839

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

4253
def __init__(self, source_names: tuple[str, ...]) -> None:
4354
self.owner = next(_TRACE_IDS)
4455
self.next_port = 0
4556
self.next_call = 0
57+
self.next_pool = 0
4658
self.next_domain = 1
4759
self.calls: dict[CallRef, CallSpec] = {}
4860
self.ports: dict[PortRef, PortSpec] = {}
4961
self.domains: dict[DomainRef, DomainSpec] = {
5062
DomainRef(0): DomainSpec(DomainRef(0), debug_name="root")
5163
}
5264
self.call_options: dict[CallRef, tuple[tuple[str, Any], ...]] = {}
65+
self.call_pools: dict[CallRef, PoolRef] = {}
66+
self.pool_udfs: dict[PoolRef, UdfSpec] = {}
67+
self.pool_options: dict[PoolRef, tuple[tuple[str, Any], ...]] = {}
68+
self._module_bindings: dict[RayModule, _ExecutionBinding] = {}
5369
self._view_intern: dict[tuple[Any, ...], tuple[PortRef, ...]] = {}
5470

5571
self.source_ports = tuple(
@@ -74,16 +90,19 @@ def call(
7490
args: tuple[Any, ...],
7591
kwargs: dict[str, Any],
7692
) -> Port | tuple[Port, ...]:
77-
if not args and not kwargs:
78-
raise CompileError("RayModule requires at least one Port input")
79-
8093
positional_inputs = [
8194
self._input(value, f"arg_{index}") for index, value in enumerate(args)
8295
]
83-
keyword_inputs = [
84-
(name, self._input(value, name)) for name, value in kwargs.items()
85-
]
96+
keyword_inputs = []
97+
static_kwargs = []
98+
for name, value in kwargs.items():
99+
if isinstance(value, Port):
100+
keyword_inputs.append((name, self._input(value, name)))
101+
else:
102+
static_kwargs.append((name, value))
86103
inputs = (*positional_inputs, *(item for _, item in keyword_inputs))
104+
if not inputs:
105+
raise CompileError("RayModule requires at least one Port input")
87106
domains = {self.ports[port].domain for port in inputs}
88107
if len(domains) != 1:
89108
raise CompileError(
@@ -94,14 +113,17 @@ def call(
94113

95114
call = CallRef(self.next_call)
96115
self.next_call += 1
116+
binding = self._execution_binding(module)
97117
self.calls[call] = CallSpec(
98118
call,
99-
UdfSpec(module.udf, module.init_args, tuple(module.init_kwargs.items())),
119+
binding.udf,
100120
execution_domain,
101121
tuple(positional_inputs),
102122
tuple(keyword_inputs),
123+
tuple(static_kwargs),
103124
)
104-
self.call_options[call] = tuple(module.options.items())
125+
self.call_options[call] = binding.call_options
126+
self.call_pools[call] = binding.pool
105127
outputs = tuple(
106128
self._new_port(execution_domain, CallOutputOrigin(call, output_index))
107129
for output_index in range(module.num_outputs)
@@ -233,9 +255,58 @@ def build(self, output_tree: object, *, optimize: bool) -> CompiledProgram:
233255
return compile_logical(
234256
logical,
235257
freeze_mapping(self.call_options),
258+
freeze_mapping(self.call_pools),
259+
freeze_mapping(self.pool_udfs),
260+
freeze_mapping(self.pool_options),
236261
optimize=optimize,
237262
)
238263

264+
def _execution_binding(self, module: RayModule) -> _ExecutionBinding:
265+
"""Resolve one module invocation to a Call contract and actor pool."""
266+
267+
binding = self._module_bindings.get(module)
268+
if binding is not None:
269+
return binding
270+
271+
dispatch_names = {
272+
"batch_size",
273+
"recovery",
274+
"max_retries",
275+
"batch_scope",
276+
"batching_policy",
277+
}
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+
udf = UdfSpec(
289+
module.udf,
290+
tuple(module.init_args),
291+
tuple(module.init_kwargs.items()),
292+
)
293+
binding = _ExecutionBinding(
294+
self._new_pool(),
295+
udf,
296+
call_options,
297+
pool_options,
298+
)
299+
self._module_bindings[module] = binding
300+
301+
self.pool_udfs[binding.pool] = binding.udf
302+
self.pool_options[binding.pool] = binding.pool_options
303+
return binding
304+
305+
def _new_pool(self) -> PoolRef:
306+
pool = PoolRef(self.next_pool)
307+
self.next_pool += 1
308+
return pool
309+
239310
def _new_port(self, domain: DomainRef, origin: PortOrigin) -> PortRef:
240311
ref = PortRef(self.next_port)
241312
self.next_port += 1

0 commit comments

Comments
 (0)