Skip to content

rome.stream

Stream Manager — persistent asynchronous inference and reward streams.

Inference and reward are not one-shot calls in ROME; they are long-lived tasks that sit on their nodes and keep processing requests for the whole campaign. The stream manager owns them: it submits them to asyncflow as services, feeds them requests from anywhere in the host workflow, collects their outputs, and — the part that closes ROME's loop — hot-swaps their weights whenever the training manager publishes a newer checkpoint.

The workflow supplies the actual inference and reward code. ROME supplies the loop around it::

await rome.stream.start(StreamConfig(
    name="generate",
    kind=StreamKind.INFERENCE,
    load_func=lambda path, ctx: load_my_model(path),
    process_func=lambda prompts, ctx: ctx.model.generate(prompts),
    num_streams=4,
    num_gpus=1,
))

A workflow that would rather own its own loop passes stream_func instead and gets the same context object, including the reload signal.

REQUEST_NS module-attribute

REQUEST_NS = 'req'

Sub-namespace holding one key per pending request, inside a group's DDict.

OUTPUT_NS module-attribute

OUTPUT_NS = 'out'

Sub-namespace holding one key per finished result.

STATUS_NS module-attribute

STATUS_NS = 'status'

Sub-namespace holding one key per replica's status.

DEFAULT_STREAM_DDICT_KWARGS module-attribute

DEFAULT_STREAM_DDICT_KWARGS: Dict[str, Any] = {'managers_per_node': 1, 'n_nodes': 1, 'total_mem': 256 * 1024 ** 2}

Defaults for a stream group's DDict.

Much smaller than the manager's, because a group only ever holds requests in flight and results not yet collected -- it does not accumulate. Override per group via StreamConfig.ddict_kwargs.

StreamStatus

Bases: Enum

Status of a single inference/reward stream task.

StreamKind

Bases: str, Enum

What a stream is for.

Both kinds run the same loop; the distinction is for routing and reporting. It matters because reward streams are the ones whose outputs feed the data manager.

StreamConfig dataclass

StreamConfig(name: str = 'default', kind: StreamKind = INFERENCE, process_func: Optional[Callable] = None, load_func: Optional[Callable] = None, stream_func: Optional[Callable] = None, model_path: Optional[str] = None, num_streams: int = 1, num_gpus: int = 1, num_nodes: int = 1, task_description: Optional[Dict[str, Any]] = None, as_service: bool = True, batch_size: int = 1, poll_interval: float = 0.1, auto_reload: bool = True, drain_on_stop: bool = True, on_output: Optional[Callable[[Dict[str, Any]], None]] = None, load_kwargs: Dict[str, Any] = dict(), ddict: Any = None, ddict_kwargs: Optional[Dict[str, Any]] = None)

Configuration for a group of identical stream tasks.

Parameters:

  • name (str, default: 'default' ) –

    Identifies the stream group. Requests are routed by name, so a workflow can run several independent groups side by side.

  • kind (StreamKind, default: INFERENCE ) –

    INFERENCE or REWARD.

  • process_func (Callable, default: None ) –

    The workflow's per-batch work: (inputs, ctx) -> results, where inputs is a list of payloads and results is a list of the same length. May be sync or async. A plain (inputs) function is accepted too, so existing code needs no signature change.

  • load_func (Optional[Callable], default: None ) –

    (model_path, ctx) -> model, called at startup and on every reload. The result becomes ctx.model. Omit for streams that need no model (most reward functions).

  • stream_func (Optional[Callable], default: None ) –

    Full override: (ctx) -> None, replacing the managed loop. The implementation must honour ctx.should_stop() and call ctx.maybe_reload() between batches. process_func is ignored.

  • model_path (Optional[str], default: None ) –

    Initial checkpoint. When None the stream starts from whatever the training manager has already published, if anything.

  • num_streams (int, default: 1 ) –

    How many identical tasks to run for this group.

  • num_gpus (int, default: 1 ) –

    Per-task resources, turned into an asyncflow task_description.

  • num_nodes (int, default: 1 ) –

    Per-task resources, turned into an asyncflow task_description.

  • task_description (Optional[dict], default: None ) –

    Backend-specific resource request, passed through to asyncflow verbatim. Overrides num_gpus/num_nodes when set.

  • as_service (bool, default: True ) –

    Submit as an asyncflow service task (default). Streams outlive individual workflow stages, which is exactly what services are for.

  • batch_size (int, default: 1 ) –

    Maximum requests handed to process_func in one call.

  • poll_interval (float, default: 0.1 ) –

    Seconds to idle when the request queue is empty.

  • auto_reload (bool, default: True ) –

    Watch the published model version and reload without being asked — "the model is reloaded when the Stream Manager sees that a new model checkpoint is available". Turn off to reload only on an explicit Stream.reload_model.

  • drain_on_stop (bool, default: True ) –

    Finish already-queued requests before stopping.

  • on_output (Optional[Callable[[dict], None]], default: None ) –

    Called with each output record as it is produced. The manager uses this to pipe reward-stream results into the data manager.

  • load_kwargs (dict, default: dict() ) –

    Extra keyword arguments for load_func.

  • ddict (DDict, default: None ) –

    Dictionary backing this group's request and result queues. When None the stream manager allocates one and destroys it on stop.

  • ddict_kwargs (dict, default: None ) –

    Passed to DDict(...) when the manager allocates the group's dictionary. Defaults to DEFAULT_STREAM_DDICT_KWARGS.

StreamContext

StreamContext(task: 'StreamTask')

Handle given to workflow code running inside a stream task.

Exposes the loaded model, the reload/stop signals and the shared DDict, so a self-driven stream_func has everything the managed loop has.

Source code in rome/stream.py
def __init__(self, task: "StreamTask"):
    self._task = task
    self.model: Any = None

index property

index: int

Which replica of the group this is (0..num_streams-1).

ddict property

ddict: Namespace

ROME's shared state — the same view the managers use.

stream_ddict property

stream_ddict: Namespace

This stream group's own slice of the shared state.

maybe_reload

maybe_reload() -> bool

Reload weights if a newer checkpoint is available; returns whether it did.

Source code in rome/stream.py
def maybe_reload(self) -> bool:
    """Reload weights if a newer checkpoint is available; returns whether it did."""
    return self._task.maybe_reload(self)

next_requests

next_requests(limit: Optional[int] = None) -> List[Tuple[str, Any]]

Claim up to limit pending requests as (request_id, payload).

Source code in rome/stream.py
def next_requests(self, limit: Optional[int] = None) -> List[Tuple[str, Any]]:
    """Claim up to ``limit`` pending requests as ``(request_id, payload)``."""
    return self._task.claim(limit)

emit

emit(request_id: str, result: Any) -> Dict[str, Any]

Publish one result back to the workflow.

Source code in rome/stream.py
def emit(self, request_id: str, result: Any) -> Dict[str, Any]:
    """Publish one result back to the workflow."""
    return self._task.emit(request_id, result)

StreamTask

StreamTask(index: int, config: StreamConfig, ddict: Namespace, root: Namespace, task_fut: Any = None)

One persistent inference or reward stream task.

Holds the asyncflow future for the running task plus its control signals. Status lives in the DDict rather than on the object, so a manager on another node can read it.

Source code in rome/stream.py
def __init__(self, index: int, config: StreamConfig, ddict: Namespace,
             root: Namespace, task_fut: Any = None):
    self.index = index
    self.config = config
    self.ddict = ddict
    """This stream group's slice of the DDict (requests, results, status)."""
    self.root = root
    """ROME's root namespace, where the published checkpoint lives."""
    self.task_fut = task_fut
    self.reload_event = Event()
    self.stop_event = Event()
    self.local_version = 0
    self.model_path: Optional[str] = config.model_path
    self._requests = ddict.namespace(REQUEST_NS, index)
    self._outputs = ddict.namespace(OUTPUT_NS)
    self._status_key = f"{STATUS_NS}|{index}"
    self.status = StreamStatus.NOT_STARTED

ddict instance-attribute

ddict = ddict

This stream group's slice of the DDict (requests, results, status).

root instance-attribute

root = root

ROME's root namespace, where the published checkpoint lives.

claim

claim(limit: Optional[int] = None) -> List[Tuple[str, Any]]

Pop pending requests for this task.

Popping is what makes a request owned: each key is removed by exactly one claimer, so replicas never double-process a request.

Source code in rome/stream.py
def claim(self, limit: Optional[int] = None) -> List[Tuple[str, Any]]:
    """Pop pending requests for this task.

    Popping is what makes a request owned: each key is removed by exactly
    one claimer, so replicas never double-process a request.
    """
    limit = limit or self.config.batch_size
    return self._requests.drain(limit=limit)

maybe_reload

maybe_reload(ctx: 'StreamContext') -> bool

Load the newest published checkpoint into this task, if there is one.

Source code in rome/stream.py
def maybe_reload(self, ctx: "StreamContext") -> bool:
    """Load the newest published checkpoint into this task, if there is one."""
    if not self.needs_reload():
        return False
    path = self.root.get(MODEL_PATH_KEY) or self.model_path
    version = self.published_version()
    self.status = StreamStatus.RELOADING
    try:
        if self.config.load_func is not None and path is not None:
            ctx.model = _call_user(
                self.config.load_func, path, ctx, **self.config.load_kwargs
            )
        self.model_path = path
        self.local_version = max(version, self.local_version)
        log.info("%s[%d] reloaded weights -> v%d (%s)",
                 self.config.name, self.index, self.local_version,
                 os.path.basename(path) if path else "no checkpoint")
        # Cleared last, so a waiter in reload_model() only unblocks once the
        # new weights are actually in memory.
        self.reload_event.clear()
        self.status = StreamStatus.RUNNING
        return True
    except Exception:
        # Leave status=FAILED so waiters in reload_model() don't incorrectly
        # assume the reload succeeded.
        self.status = StreamStatus.FAILED
        self.reload_event.clear()
        raise

Stream

Stream(ddict: Namespace, asyncflow: Any)

Stream manager: owns every inference and reward stream in a run.

Each stream group gets its own DDict for requests and results, rather than sharing the manager's. A dictionary has no server-side prefix query, so a scan lists every key in it and filters client-side; sharing one dictionary would make the cost of a replica's poll grow with the corpus, coupling two rates that have nothing to do with each other. Per group, a scan covers only that group's in-flight work, which does not accumulate.

The manager's own dictionary is still used, read-only from here, for the published checkpoint — that is what the streams reload from.

Parameters:

  • ddict (Namespace) –

    ROME's shared state, holding the published checkpoint.

  • asyncflow (WorkflowEngine) –

    Engine the stream tasks are submitted to, as services.

Source code in rome/stream.py
def __init__(self, ddict: Namespace, asyncflow: Any):
    self.ddict = ddict
    self.asyncflow = asyncflow
    self.stream_tasks: List[StreamTask] = []
    self._configs: Dict[str, StreamConfig] = {}
    self._round_robin: Dict[str, int] = {}
    #: group name -> Namespace over that group's dictionary.
    self._group_ns: Dict[str, Namespace] = {}
    #: Groups whose dictionary this manager allocated, and must destroy.
    self._owned: Dict[str, Any] = {}

start async

start(config: StreamConfig) -> List[StreamTask]

Start config.num_streams persistent tasks for one stream group.

Call it once per group — typically an inference group and a reward group — against the same manager.

Source code in rome/stream.py
async def start(self, config: StreamConfig) -> List[StreamTask]:
    """Start ``config.num_streams`` persistent tasks for one stream group.

    Call it once per group — typically an inference group and a reward
    group — against the same manager.
    """
    config.validate()
    self._configs[config.name] = config
    self._round_robin.setdefault(config.name, 0)
    ns = self._open_group(config)
    description = config.describe_resources()

    started: List[StreamTask] = []
    for i in range(config.num_streams):
        task = StreamTask(index=i, config=config, ddict=ns, root=self.ddict)
        task.status = StreamStatus.STARTING

        # Captures the StreamTask and nothing else. A Dragon execution
        # backend runs a task body in a *different process*, so the entry
        # point has to pickle; capturing ``self`` would drag the workflow
        # engine along, which does not pickle -- and the submission then
        # hangs rather than raising. See docs/delta.md.
        async def stream_entry(_task=task):
            await run_stream_task(_task)

        stream_entry.__name__ = f"rome_stream_{config.name}_{i}"
        task.task_fut = submit_task(
            self.asyncflow,
            stream_entry,
            task_description=description,
            service=config.as_service,
        )
        self.stream_tasks.append(task)
        started.append(task)
    log.info("started %s stream '%s' (%d replica%s, %d gpu%s each)",
             config.kind.value, config.name, config.num_streams,
             "" if config.num_streams == 1 else "s", config.num_gpus,
             "" if config.num_gpus == 1 else "s")
    return started

submit

submit(payload: Any, stream: Optional[str] = None, request_id: Optional[str] = None) -> str

Queue one request and return its id.

Requests round-robin across the group's replicas, so every task gets an even share without needing a shared claim protocol.

Source code in rome/stream.py
def submit(self, payload: Any, stream: Optional[str] = None,
           request_id: Optional[str] = None) -> str:
    """Queue one request and return its id.

    Requests round-robin across the group's replicas, so every task gets an
    even share without needing a shared claim protocol.
    """
    name = self._resolve_name(stream)
    tasks = self.tasks_for(name)
    if not tasks:
        raise RuntimeError(f"stream {name!r} has not been started")
    rid = request_id or uuid.uuid4().hex
    index = self._round_robin[name] % len(tasks)
    self._round_robin[name] = index + 1
    tasks[index].submit(rid, payload)
    return rid

submit_batch

submit_batch(payloads: List[Any], stream: Optional[str] = None) -> List[str]

Queue many requests; returns their ids in order.

Source code in rome/stream.py
def submit_batch(self, payloads: List[Any], stream: Optional[str] = None) -> List[str]:
    """Queue many requests; returns their ids in order."""
    return [self.submit(p, stream=stream) for p in payloads]

get_outputs

get_outputs(stream: Optional[str] = None, consume: bool = True) -> List[Dict[str, Any]]

Collect finished results, oldest first.

Parameters:

  • stream (str, default: None ) –

    Which group to read. Defaults to the only started group.

  • consume (bool, default: True ) –

    Remove results as they are read (default). Pass False to peek without draining — useful for progress displays.

Source code in rome/stream.py
def get_outputs(self, stream: Optional[str] = None,
                consume: bool = True) -> List[Dict[str, Any]]:
    """Collect finished results, oldest first.

    Parameters
    ----------
    stream : str, optional
        Which group to read. Defaults to the only started group.
    consume : bool
        Remove results as they are read (default). Pass ``False`` to peek
        without draining — useful for progress displays.
    """
    ns = self._namespace(self._resolve_name(stream)).namespace(OUTPUT_NS)
    pairs = ns.drain() if consume else ns.items()
    records = [v for _, v in pairs if isinstance(v, dict)]
    records.sort(key=lambda r: r.get("completed_at", 0.0))
    return records

get_output async

get_output(request_id: str, stream: Optional[str] = None, timeout: Optional[float] = None, poll_interval: float = 0.05) -> Optional[Dict[str, Any]]

Await one specific request's result.

Returns None on timeout rather than raising, so a caller polling several requests can keep going.

Source code in rome/stream.py
async def get_output(self, request_id: str, stream: Optional[str] = None,
                     timeout: Optional[float] = None,
                     poll_interval: float = 0.05) -> Optional[Dict[str, Any]]:
    """Await one specific request's result.

    Returns ``None`` on timeout rather than raising, so a caller polling
    several requests can keep going.
    """
    ns = self._namespace(self._resolve_name(stream)).namespace(OUTPUT_NS)
    deadline = None if timeout is None else time.time() + timeout
    while True:
        record = ns.pop(request_id, None)
        if record is not None:
            return record
        if deadline is not None and time.time() >= deadline:
            return None
        await asyncio.sleep(poll_interval)

pending

pending(stream: Optional[str] = None) -> int

How many requests are queued and not yet claimed.

Source code in rome/stream.py
def pending(self, stream: Optional[str] = None) -> int:
    """How many requests are queued and not yet claimed."""
    return sum(t.pending for t in self.tasks_for(self._resolve_name(stream)))

signal_reload

signal_reload(model_path: Optional[str] = None, stream: Optional[str] = None) -> List[StreamTask]

Raise the reload flag on the targeted tasks without waiting.

Each task swaps weights between batches on its own schedule, so this never interrupts an in-flight inference call.

Source code in rome/stream.py
def signal_reload(self, model_path: Optional[str] = None,
                  stream: Optional[str] = None) -> List[StreamTask]:
    """Raise the reload flag on the targeted tasks without waiting.

    Each task swaps weights between batches on its own schedule, so this
    never interrupts an in-flight inference call.
    """
    if model_path is not None:
        self.ddict[MODEL_PATH_KEY] = model_path
    targets = self.stream_tasks if stream is None else self.tasks_for(stream)
    for task in targets:
        if model_path is not None:
            task.config.model_path = model_path
        task.reload_event.set()
    return targets

reload_model async

reload_model(model_path: Optional[str] = None, stream: Optional[str] = None, wait_for_reload: bool = True, timeout: float = 300.0) -> None

Tell the streams to pick up new weights.

Called explicitly by the workflow, or implicitly by on_checkpoint when the training manager publishes. model_path=None means "reload whatever is currently published".

Source code in rome/stream.py
async def reload_model(self, model_path: Optional[str] = None,
                       stream: Optional[str] = None,
                       wait_for_reload: bool = True,
                       timeout: float = 300.0) -> None:
    """Tell the streams to pick up new weights.

    Called explicitly by the workflow, or implicitly by :meth:`on_checkpoint`
    when the training manager publishes. ``model_path=None`` means "reload
    whatever is currently published".
    """
    targets = self.signal_reload(model_path, stream)
    if not wait_for_reload:
        return
    deadline = time.time() + timeout
    for task in targets:
        while task.reload_event.is_set() and time.time() < deadline:
            if task.status in (StreamStatus.STOPPED, StreamStatus.FAILED):
                break
            await asyncio.sleep(0.05)

on_checkpoint

on_checkpoint(checkpoint_path: str, version: int) -> None

Training-manager hook: a new checkpoint just landed.

Registered by Manager, so publishing a checkpoint and hot-swapping the streams are the same event. Non-blocking by design.

Source code in rome/stream.py
def on_checkpoint(self, checkpoint_path: str, version: int) -> None:
    """Training-manager hook: a new checkpoint just landed.

    Registered by :class:`~rome.manager.Manager`, so publishing a checkpoint
    and hot-swapping the streams are the same event. Non-blocking by design.
    """
    self.signal_reload(checkpoint_path)

get_status

get_status(stream: Optional[str] = None) -> List[StreamStatus]

Status of every task, or of one group's tasks.

Source code in rome/stream.py
def get_status(self, stream: Optional[str] = None) -> List[StreamStatus]:
    """Status of every task, or of one group's tasks."""
    targets = self.stream_tasks if stream is None else self.tasks_for(stream)
    return [task.status for task in targets]

report

report() -> Dict[str, Any]

Per-group summary for dashboards and logs.

Source code in rome/stream.py
def report(self) -> Dict[str, Any]:
    """Per-group summary for dashboards and logs."""
    out: Dict[str, Any] = {}
    for name, config in self._configs.items():
        tasks = self.tasks_for(name)
        out[name] = {
            "kind": config.kind.value,
            "tasks": len(tasks),
            "status": [t.status.name for t in tasks],
            "pending": sum(t.pending for t in tasks),
            # The *published* version, read from shared state — authoritative
            # and cross-process. A replica's own local_version lives in its
            # task process and does not come back to the driver, so reading
            # that would report 0 on a multi-process backend even while the
            # replica is serving the latest checkpoint.
            "model_version": int(self.ddict.get(MODEL_VERSION_KEY, 0)),
        }
    return out

stop async

stop(stream: Optional[str] = None, wait_for_stop: bool = True, timeout: float = 60.0) -> None

Signal the stream tasks to stop, optionally waiting for them to finish.

Stopping does not release the group dictionaries — results drained on the way down stay readable, which is the whole point of drain_on_stop. Call close once those have been collected.

Source code in rome/stream.py
async def stop(self, stream: Optional[str] = None, wait_for_stop: bool = True,
               timeout: float = 60.0) -> None:
    """Signal the stream tasks to stop, optionally waiting for them to finish.

    Stopping does not release the group dictionaries — results drained on
    the way down stay readable, which is the whole point of
    ``drain_on_stop``. Call :meth:`close` once those have been collected.
    """
    targets = self.stream_tasks if stream is None else self.tasks_for(stream)
    for task in targets:
        task.stop_event.set()
    if not wait_for_stop:
        return
    deadline = time.time() + timeout
    for task in targets:
        while time.time() < deadline:
            if task.status in (StreamStatus.STOPPED, StreamStatus.FAILED,
                               StreamStatus.NOT_STARTED):
                break
            await asyncio.sleep(0.05)

close

close(stream: Optional[str] = None) -> None

Release the dictionaries this manager allocated for its groups.

Separate from stop so a workflow can collect what the streams drained on the way down before their storage goes away. Idempotent.

Source code in rome/stream.py
def close(self, stream: Optional[str] = None) -> None:
    """Release the dictionaries this manager allocated for its groups.

    Separate from :meth:`stop` so a workflow can collect what the streams
    drained on the way down before their storage goes away. Idempotent.
    """
    for name in (list(self._owned) if stream is None else [stream]):
        self._release_group(name)

run_stream_task async

run_stream_task(task: 'StreamTask') -> None

The persistent loop: load a model, then process until told to stop.

Source code in rome/stream.py
async def run_stream_task(task: "StreamTask") -> None:
    """The persistent loop: load a model, then process until told to stop."""
    ctx = StreamContext(task)
    config = task.config
    try:
        initial_path = config.model_path or task.root.get(MODEL_PATH_KEY)
        if config.load_func is not None and initial_path is not None:
            ctx.model = _call_user(
                config.load_func, initial_path, ctx, **config.load_kwargs
            )
            task.model_path = initial_path
        task.local_version = int(task.root.get(MODEL_VERSION_KEY, 0))
        task.status = StreamStatus.RUNNING

        if config.stream_func is not None:
            await _call_user_async(config.stream_func, ctx)
        else:
            await _managed_loop(task, ctx)
    except asyncio.CancelledError:
        task.status = StreamStatus.STOPPED
        raise
    except Exception:  # noqa: BLE001 - status carries the failure
        task.status = StreamStatus.FAILED
        traceback.print_exc()
        raise
    else:
        task.status = StreamStatus.STOPPED