Skip to content

rome

ROME: the RADICAL Optimizer for Model Enhancement.

ROME provides model improvement as a component you bolt onto a workflow you already have, rather than as a workflow you have to adopt. Three managers, each a configurable unit:

  • DataManager — gathers scored outputs from the workflow and builds them into a training dataset;
  • Trainer — schedules training tasks and publishes checkpoints back to the workflow;
  • Stream — runs inference and reward as persistent asynchronous streams and hot-swaps their weights when a checkpoint lands.

Manager wires the three together, so adoption is a few API calls::

from radical.asyncflow import WorkflowEngine
import rome

flow = await WorkflowEngine.create(backend=backend)
manager = rome.Manager(
    flow,
    data_config=rome.DataConfig(min_samples=64),
    trainer_config=rome.TrainerConfig(trainer=my_trainer),
    stream_configs=[rome.StreamConfig(name="infer", process_func=my_infer)],
)
await manager.start()

MODEL_PATH_KEY module-attribute

MODEL_PATH_KEY = 'model_path'

Key holding the checkpoint the workflow should currently be using.

MODEL_VERSION_KEY module-attribute

MODEL_VERSION_KEY = 'model_version'

Key holding the monotonically increasing checkpoint version.

Stream tasks poll this to decide when to hot-swap weights.

DataConfig dataclass

DataConfig(min_samples: int = 32, max_records: Optional[int] = None, score_key: str = 'score', min_score: Optional[float] = None, filter_func: Optional[Callable[[Dict[str, Any]], bool]] = None, dedup_key: Optional[Callable[[Dict[str, Any]], Any]] = None, sample_func: Optional[Callable[[List[Dict[str, Any]]], List[Dict[str, Any]]]] = None, sampling: str = 'all', shard_size: Optional[int] = None, consume_on_train: bool = True, metadata: Dict[str, Any] = dict())

Knobs for how the data manager turns raw scored outputs into a dataset.

Parameters:

  • min_samples (int, default: 32 ) –

    How many unconsumed records must accumulate before the training manager considers a round possible. This is the "training starts automatically once enough data accumulates" threshold.

  • max_records (Optional[int], default: None ) –

    Soft cap on corpus size. When exceeded, the oldest records are evicted on the next DataManager.add. None (the default) keeps everything.

    Warning

    On Dragon, leave this unset unless you have measured that you need it. Eviction is the only thing that pops from the corpus dictionary, and a Dragon DDict.keys() scan silently returns a truncated list when another client pops concurrently — one measured scan returned 39 of 400 keys and reported success. With no evictions the corpus is never popped, so scans are exact and the training shard is complete. See docs/dragon.md.

  • score_key (str, default: 'score' ) –

    Field of a record holding its scalar quality score. Used by the built-in top_k sampler and by min_score.

  • min_score (Optional[float], default: None ) –

    Reject records scoring below this on the way in. None accepts all.

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

    Arbitrary admission predicate, applied after min_score. Return False to drop the record. This is where IMPRESS-R plugs in its pLDDT/pTM/pAE thresholds.

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

    Returns a hashable identity for a record. Records whose identity was already seen are dropped. None disables deduplication.

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

    Builds the training shard from the corpus. Overrides sampling.

  • sampling (str, default: 'all' ) –

    Built-in shard builder: 'all' (default), 'top_k' (best shard_size by score_key) or 'recent' (newest shard_size).

  • shard_size (Optional[int], default: None ) –

    Number of records the built-in samplers draw. None means no limit.

  • consume_on_train (bool, default: True ) –

    When True (default) records handed to a training round count as consumed, so the next round waits for min_samples new records. The corpus itself is never deleted.

metadata class-attribute instance-attribute

metadata: Dict[str, Any] = field(default_factory=dict)

Extra fields stamped onto every record (run id, campaign name, ...).

DataManager

DataManager(ddict: Namespace, config: Optional[DataConfig] = None)

Gathers scored outputs from the host workflow and creates a dataset.

The public surface is deliberately tiny — the slide deck's promise is that adopting ROME costs a few API calls:

  • add / add_batch — call from anywhere in the workflow
  • get_dataset — what the training task trains on
  • ready_to_train / unconsumed_count — what the training manager polls

Parameters:

  • ddict (Namespace) –

    Shared state. Every ROME component in a run must be handed the same one (Manager does this for you).

  • config (DataConfig, default: None ) –

    Defaults are used when omitted.

Source code in rome/data.py
def __init__(self, ddict: Namespace, config: Optional[DataConfig] = None):
    self.config = config or DataConfig()
    self.ddict = ddict
    self._records = ddict.namespace(RECORD_NS)
    self._meta = ddict.namespace(META_NS)
    # Dedup identities seen by *this* process. The authoritative check is
    # the corpus scan in _is_duplicate; this is just a fast path.
    self._seen: set = set()

total_count property

total_count: int

Number of records currently in the corpus.

consumed_count property

consumed_count: int

Number of records already folded into a completed training round.

unconsumed_count property

unconsumed_count: int

Records added since the last training round consumed the corpus.

model_version property

model_version: int

Version of the model currently published by the training manager.

Stamped onto each record so a later analysis can tell which model generated it — the "produced_under_version" idea from IMPRESS-R.

add

add(score: Optional[float] = None, *, uid: Optional[str] = None, **fields: Any) -> Optional[str]

Add one scored output to the corpus.

Everything is keyword-driven so the same call works for any domain::

rome.data.add(prompt=p, completion=c, score=reward)
rome.data.add(sequence=seq, pdb_path=pdb, score=plddt, pTM=ptm)

Parameters:

  • score (float, default: None ) –

    The record's scalar quality. Stored under config.score_key.

  • uid (str, default: None ) –

    Caller-supplied identity. Generated when omitted.

  • **fields (Any, default: {} ) –

    Arbitrary payload, stored verbatim.

Returns:

  • Optional[str] –

    The record uid, or None when the record was filtered out.

Source code in rome/data.py
def add(
    self,
    score: Optional[float] = None,
    *,
    uid: Optional[str] = None,
    **fields: Any,
) -> Optional[str]:
    """Add one scored output to the corpus.

    Everything is keyword-driven so the same call works for any domain::

        rome.data.add(prompt=p, completion=c, score=reward)
        rome.data.add(sequence=seq, pdb_path=pdb, score=plddt, pTM=ptm)

    Parameters
    ----------
    score : float, optional
        The record's scalar quality. Stored under ``config.score_key``.
    uid : str, optional
        Caller-supplied identity. Generated when omitted.
    **fields
        Arbitrary payload, stored verbatim.

    Returns
    -------
    Optional[str]
        The record uid, or ``None`` when the record was filtered out.
    """
    record = dict(self.config.metadata)
    record.update(fields)
    if score is not None:
        record[self.config.score_key] = score
    record["uid"] = uid or uuid.uuid4().hex
    record.setdefault("added_at", time.time())
    record.setdefault("model_version", self.model_version)

    if not self._accepts(record):
        _log.info("rejected design %s (filtered: %s)",
                  record["uid"][:8], self._reject_reason(record))
        return None
    if self._is_duplicate(record):
        _log.info("rejected design %s (duplicate)", record["uid"][:8])
        return None

    self._records[record["uid"]] = record
    self._meta.increment("total")
    self._evict_if_needed()
    _log.info("received design %s%s — corpus %d (%d unconsumed)",
              record["uid"][:8], self._score_note(record),
              self.total_count, self.unconsumed_count)
    return record["uid"]

add_batch

add_batch(records: Iterable[Dict[str, Any]]) -> List[str]

Add many records at once; returns the uids that were accepted.

Source code in rome/data.py
def add_batch(self, records: Iterable[Dict[str, Any]]) -> List[str]:
    """Add many records at once; returns the uids that were accepted."""
    added = []
    for record in records:
        payload = dict(record)
        uid = payload.pop("uid", None)
        score = payload.pop(self.config.score_key, None)
        result = self.add(score=score, uid=uid, **payload)
        if result is not None:
            added.append(result)
    return added

get_records

get_records() -> List[Dict[str, Any]]

Every record in the corpus, oldest first.

Source code in rome/data.py
def get_records(self) -> List[Dict[str, Any]]:
    """Every record in the corpus, oldest first."""
    records = [r for r in self._records.values() if isinstance(r, dict)]
    records.sort(key=lambda r: (r.get("added_at", 0.0), str(r.get("uid", ""))))
    return records

get_dataset

get_dataset(as_hf_dataset: bool = False) -> Any

Build the training dataset from the corpus.

Applies config.sample_func when set, otherwise the built-in config.sampling strategy.

Parameters:

  • as_hf_dataset (bool, default: False ) –

    Return a datasets.Dataset instead of a list of dicts. Requires datasets to be installed; the LLM trainer needs it, the MPNN trainer does not, which is why it is opt-in.

Source code in rome/data.py
def get_dataset(self, as_hf_dataset: bool = False) -> Any:
    """Build the training dataset from the corpus.

    Applies ``config.sample_func`` when set, otherwise the built-in
    ``config.sampling`` strategy.

    Parameters
    ----------
    as_hf_dataset : bool
        Return a ``datasets.Dataset`` instead of a list of dicts. Requires
        ``datasets`` to be installed; the LLM trainer needs it, the MPNN
        trainer does not, which is why it is opt-in.
    """
    records = self._sample(self.get_records())
    if not as_hf_dataset:
        return records
    from datasets import Dataset

    return Dataset.from_list(records)

ready_to_train

ready_to_train() -> bool

Whether enough fresh data has accumulated for a training round.

Source code in rome/data.py
def ready_to_train(self) -> bool:
    """Whether enough fresh data has accumulated for a training round."""
    return self.unconsumed_count >= self.config.min_samples

mark_consumed

mark_consumed(count: Optional[int] = None) -> int

Record that count records were used for training.

Called by the training manager when a round completes. Defaults to the whole current corpus. No-op when config.consume_on_train is off, so a workflow that wants to retrain on everything every round can.

Source code in rome/data.py
def mark_consumed(self, count: Optional[int] = None) -> int:
    """Record that ``count`` records were used for training.

    Called by the training manager when a round completes. Defaults to the
    whole current corpus. No-op when ``config.consume_on_train`` is off, so
    a workflow that wants to retrain on everything every round can.
    """
    if not self.config.consume_on_train:
        return self.consumed_count
    total = self.total_count if count is None else self.consumed_count + count
    self._meta[CONSUMED_KEY] = min(total, self.total_count)
    return self.consumed_count

clear

clear() -> int

Drop the entire corpus. Returns the number of records removed.

Source code in rome/data.py
def clear(self) -> int:
    """Drop the entire corpus. Returns the number of records removed."""
    removed = self._records.clear()
    self._meta[CONSUMED_KEY] = 0
    self._meta["total"] = 0
    self._seen.clear()
    return removed

Manager

Manager(asyncflow: Optional[WorkflowEngine] = None, *, backend: Any = None, data_config: Optional[DataConfig] = None, trainer_config: Optional[TrainerConfig] = None, stream_configs: Optional[List[StreamConfig]] = None, ddict: Optional[DDict] = None, ddict_kwargs: Optional[Dict[str, Any]] = None, auto_reload_streams: bool = True)

Manager class for handling tasks and data in the ROME framework.

Parameters:

  • asyncflow (WorkflowEngine, default: None ) –

    The engine ROME submits its tasks to. Pass the host workflow's — for an IMPRESS campaign that is impress_manager.flow, available once the manager has started — and ROME's rounds and streams are scheduled against the same allocation as the campaign's own tasks.

    Leave it None and ROME builds its own engine at start and shuts it down at stop. That is the right choice when ROME should manage its own tasks independently of the host, or when the host creates its engine internally and does not hand one out.

  • backend (optional, default: None ) –

    Execution backend for the engine ROME builds for itself. Ignored when asyncflow is given. When both are omitted, asyncflow falls back to a local, in-process backend — fine for tests and CPU work, but wrong for a GPU fine-tune: a training round then runs inside this driver process, so the model's CUDA context stays resident for the whole campaign instead of being freed when the round ends. Pass a process-based backend (DragonExecutionBackendV3 on Delta, or a ConcurrentExecutionBackend(ProcessPoolExecutor())) so each round runs in a task process that releases its VRAM on exit. See examples/impress_r/run_protein_binding_rome.py.

  • data_config (DataConfig, default: None ) –

    How scored outputs become a dataset, and how much data a training round needs.

  • trainer_config (TrainerConfig, default: None ) –

    Which training algorithm to run and when. Required before training can start; may also be passed to start.

  • stream_configs (list[StreamConfig], default: None ) –

    Inference and reward streams to bring up at start. Streams can equally be started later via manager.stream.start(...), or omitted entirely by workflows that only want the data + training halves.

  • ddict (DDict, default: None ) –

    Share the host workflow's dictionary instead of allocating one. ROME namespaces all of its keys, so sharing is safe, and passing the DDict object into a task is all it takes to reach it from another node — Dragon attaches the receiving process automatically.

  • ddict_kwargs (dict, default: None ) –

    Passed to DDict(...) when ROME allocates its own. Worth setting on a real campaign: Dragon's default total_mem is 3 MiB, which a corpus of a few thousand records will exhaust, so ROME asks for DEFAULT_DDICT_KWARGS instead.

  • auto_reload_streams (bool, default: True ) –

    Wire published checkpoints to stream reloads (default). Turn off if the workflow would rather decide when inference switches models.

Source code in rome/manager.py
def __init__(
    self,
    asyncflow: Optional[WorkflowEngine] = None,
    *,
    backend: Any = None,
    data_config: Optional[DataConfig] = None,
    trainer_config: Optional[TrainerConfig] = None,
    stream_configs: Optional[List[StreamConfig]] = None,
    ddict: Optional[DDict] = None,
    ddict_kwargs: Optional[Dict[str, Any]] = None,
    auto_reload_streams: bool = True,
):
    self.asyncflow = asyncflow
    self.backend = backend
    #: True when ROME built the engine and is therefore responsible for
    #: shutting it down. An engine handed in belongs to the host workflow.
    self._owns_asyncflow = False
    if ddict is not None:
        self.manager_ddict = ddict
    else:
        self.manager_ddict = DDict(**{**DEFAULT_DDICT_KWARGS, **(ddict_kwargs or {})})
    self.ns = Namespace(self.manager_ddict, f"{ROME_NS}|")
    self.stop_event = Event()
    self.auto_reload_streams = auto_reload_streams
    self._stream_configs = list(stream_configs or [])
    self._started = False

    self.data = DataManager(self.ns, data_config)
    self.trainer = Trainer(self.ns, self.data, asyncflow, trainer_config)
    self.stream = Stream(self.ns, asyncflow)

model_version property

model_version: int

Version of the newest published checkpoint (0 = never trained).

start async

start(trainer_config: Optional[TrainerConfig] = None, stream_configs: Optional[List[StreamConfig]] = None) -> 'Manager'

Start the ROME manager: bring up the streams, then the trainer.

Order matters. Streams come up first so they are already draining requests by the time the first checkpoint lands, and the checkpoint hook is registered before the trainer can fire a round — otherwise a very fast first round could publish weights nobody is listening for.

Source code in rome/manager.py
async def start(
    self,
    trainer_config: Optional[TrainerConfig] = None,
    stream_configs: Optional[List[StreamConfig]] = None,
) -> "Manager":
    """Start the ROME manager: bring up the streams, then the trainer.

    Order matters. Streams come up first so they are already draining
    requests by the time the first checkpoint lands, and the checkpoint hook
    is registered before the trainer can fire a round — otherwise a very
    fast first round could publish weights nobody is listening for.
    """
    if trainer_config is not None:
        self.trainer.config = trainer_config
    if stream_configs is not None:
        self._stream_configs = list(stream_configs)

    await self._ensure_asyncflow()
    self.stop_event.clear()

    if self.auto_reload_streams:
        self.trainer.on_checkpoint(self.stream.on_checkpoint)

    for config in self._stream_configs:
        if config.kind is StreamKind.REWARD and config.on_output is None:
            # A reward stream's whole point is to score things for training,
            # so its results go straight into the corpus unless the workflow
            # has said otherwise.
            config.on_output = self._reward_output_to_corpus
        await self.stream.start(config)

    if self.trainer.config.trainer is not None:
        await self.trainer.start()

    self._started = True
    log.info("started — %d stream group%s, min_samples=%d, trainer %s",
             len(self._stream_configs),
             "" if len(self._stream_configs) == 1 else "s",
             self.data.config.min_samples,
             type(self.trainer.config.trainer).__name__
             if self.trainer.config.trainer is not None else "none")
    return self

stop async

stop(wait: bool = True, timeout: float = 300.0) -> None

Stop the ROME manager.

Trainer first: an in-flight round is waited out rather than cancelled, and letting the streams keep serving while it finishes means the final checkpoint still reaches them.

Source code in rome/manager.py
async def stop(self, wait: bool = True, timeout: float = 300.0) -> None:
    """Stop the ROME manager.

    Trainer first: an in-flight round is waited out rather than cancelled,
    and letting the streams keep serving while it finishes means the final
    checkpoint still reaches them.
    """
    self.stop_event.set()
    log.info("stopping — corpus %d, %d round%s completed, model v%d",
             self.data.total_count, self.trainer.rounds_completed,
             "" if self.trainer.rounds_completed == 1 else "s",
             self.model_version)
    await self.trainer.stop(wait_for_stop=wait, timeout=timeout)
    await self.stream.stop(wait_for_stop=wait, timeout=timeout)
    # Each stream group owns a dictionary; the manager's teardown is where
    # they are released, after the streams have finished draining.
    self.stream.close()
    if self._owns_asyncflow and self.asyncflow is not None:
        # Only an engine ROME built is ROME's to shut down; the host
        # workflow's is still running its own tasks.
        await self.asyncflow.shutdown()
        self.asyncflow = None
        self._owns_asyncflow = False
    self._started = False

add_training_data

add_training_data(prompt: Any = None, completion: Any = None, score: Optional[float] = None, **fields: Any) -> Optional[str]

Add training data to the manager, from anywhere in the workflow.

The prompt/completion/score triple is the LLM-shaped convenience form; any other domain passes keywords instead::

rome.add_training_data(sequence=seq, pdb_path=pdb, score=plddt)

Returns the record uid, or None when the data manager's filters rejected the sample.

Source code in rome/manager.py
def add_training_data(self, prompt: Any = None, completion: Any = None,
                      score: Optional[float] = None, **fields: Any) -> Optional[str]:
    """Add training data to the manager, from anywhere in the workflow.

    The ``prompt``/``completion``/``score`` triple is the LLM-shaped
    convenience form; any other domain passes keywords instead::

        rome.add_training_data(sequence=seq, pdb_path=pdb, score=plddt)

    Returns the record uid, or ``None`` when the data manager's filters
    rejected the sample.
    """
    if prompt is not None:
        fields["prompt"] = prompt
    if completion is not None:
        fields["completion"] = completion
    return self.data.add(score=score, **fields)

add_training_batch

add_training_batch(records: List[Dict[str, Any]]) -> List[str]

Add many scored outputs at once; returns the accepted uids.

Source code in rome/manager.py
def add_training_batch(self, records: List[Dict[str, Any]]) -> List[str]:
    """Add many scored outputs at once; returns the accepted uids."""
    return self.data.add_batch(records)

get_training_dataset

get_training_dataset(as_hf_dataset: bool = False) -> Any

The dataset the next training round would train on.

Source code in rome/manager.py
def get_training_dataset(self, as_hf_dataset: bool = False) -> Any:
    """The dataset the next training round would train on."""
    return self.data.get_dataset(as_hf_dataset=as_hf_dataset)

start_training async

start_training(force: bool = True, **kwargs: Any) -> Optional[str]

Trigger a training round by hand; returns the new checkpoint path.

Source code in rome/manager.py
async def start_training(self, force: bool = True, **kwargs: Any) -> Optional[str]:
    """Trigger a training round by hand; returns the new checkpoint path."""
    return await self.trainer.train(force=force, **kwargs)

get_training_status

get_training_status() -> TrainerStatus

Get the status of the training tasks.

Source code in rome/manager.py
def get_training_status(self) -> TrainerStatus:
    """Get the status of the training tasks."""
    return self.trainer.status

get_current_model

get_current_model() -> Optional[str]

Path to the newest published checkpoint, or None before round 1.

Source code in rome/manager.py
def get_current_model(self) -> Optional[str]:
    """Path to the newest published checkpoint, or ``None`` before round 1."""
    return self.trainer.get_current_model()

ready_to_train

ready_to_train() -> bool

Whether enough fresh data has accumulated for a round.

Source code in rome/manager.py
def ready_to_train(self) -> bool:
    """Whether enough fresh data has accumulated for a round."""
    return self.data.ready_to_train()

submit

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

Queue one inference or scoring request; returns its request id.

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

get_outputs

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

Collect finished stream results.

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

reload_model async

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

Push a checkpoint into the running streams.

Source code in rome/manager.py
async def reload_model(self, model_path: Optional[str] = None,
                       wait_for_reload: bool = True) -> None:
    """Push a checkpoint into the running streams."""
    await self.stream.reload_model(model_path, wait_for_reload=wait_for_reload)

get_stream_status

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

Status of the running stream tasks.

Source code in rome/manager.py
def get_stream_status(self, stream: Optional[str] = None) -> List[StreamStatus]:
    """Status of the running stream tasks."""
    return self.stream.get_status(stream=stream)

report

report() -> Dict[str, Any]

One-call snapshot of all three components.

Source code in rome/manager.py
def report(self) -> Dict[str, Any]:
    """One-call snapshot of all three components."""
    return {
        "started": self._started,
        "data": {
            "total": self.data.total_count,
            "unconsumed": self.data.unconsumed_count,
            "ready_to_train": self.data.ready_to_train(),
        },
        "training": self.trainer.report(),
        "streams": self.stream.report(),
        "model_path": self.ns.get(MODEL_PATH_KEY),
    }

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)

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)

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.

StreamStatus

Bases: Enum

Status of a single inference/reward stream task.

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

FunctionTrainer

FunctionTrainer(func, *, gpus: int = 1, nodes: int = 1, name: Optional[str] = None, wants_hf_dataset: bool = False)

Bases: TrainTask

Adapter that turns a bare function into a TrainTask.

The cheapest possible way to plug an existing training script into ROME::

rome = Manager(trainer=FunctionTrainer(my_finetune, gpus=4))

where my_finetune(dataset, output_dir, **kwargs) -> checkpoint_path.

Source code in rome/train/base.py
def __init__(self, func, *, gpus: int = 1, nodes: int = 1, name: Optional[str] = None,
             wants_hf_dataset: bool = False):
    super().__init__(gpus=gpus, nodes=nodes, name=name or getattr(func, "__name__", "function"))
    self._func = func
    self.wants_hf_dataset = wants_hf_dataset

as_command

as_command(dataset: Any, output_dir: str, **kwargs: Any) -> Optional[Tuple[str, str]]

Optionally run this round as an executable task instead of a function.

Return (shell_command, checkpoint_path) to have the training manager submit shell_command as an executable task — a subprocess on the allocation's resources, the way IMPRESS submits its wrapper scripts — rather than pickling train into a worker. checkpoint_path is where the command will write the checkpoint, since an executable task's return value is not the path.

Return None (the default) to run train in-process as a function task. A GPU fine-tune should prefer the command form: the subprocess exits when the round ends, releasing its VRAM.

Completion contract: the command MUST write a file named train_complete (rome.trainer.TRAIN_COMPLETE_MARKER) into its output_dir as its final action, after the checkpoint is safely on disk. The training manager polls for that marker to detect the round finished, because on Dragon a task can run to completion and never resolve its future (a running service blocks result delivery — see docs/dragon.md). The marker, not the checkpoint, is the signal: with publish-in-place the checkpoint path already exists from the prior round.

Source code in rome/train/base.py
def as_command(self, dataset: Any, output_dir: str,
               **kwargs: Any) -> Optional[Tuple[str, str]]:
    """Optionally run this round as an executable task instead of a function.

    Return ``(shell_command, checkpoint_path)`` to have the training manager
    submit ``shell_command`` as an *executable* task — a subprocess on the
    allocation's resources, the way IMPRESS submits its wrapper scripts —
    rather than pickling :meth:`train` into a worker. ``checkpoint_path`` is
    where the command will write the checkpoint, since an executable task's
    return value is not the path.

    Return ``None`` (the default) to run :meth:`train` in-process as a
    function task. A GPU fine-tune should prefer the command form: the
    subprocess exits when the round ends, releasing its VRAM.

    Completion contract: the command MUST write a file named
    ``train_complete`` (``rome.trainer.TRAIN_COMPLETE_MARKER``) into its
    ``output_dir`` as its *final* action, after the checkpoint is safely on
    disk. The training manager polls for that marker to detect the round
    finished, because on Dragon a task can run to completion and never
    resolve its future (a running service blocks result delivery — see
    ``docs/dragon.md``). The marker, not the checkpoint, is the signal: with
    publish-in-place the checkpoint path already exists from the prior round.
    """
    return None

validate

validate(dataset: Any) -> None

Raise if dataset cannot be trained on.

Called by the training manager before a task is scheduled, so an unusable corpus fails fast on the manager instead of burning an HPC allocation. The default check is just "not empty".

Source code in rome/train/base.py
def validate(self, dataset: Any) -> None:
    """Raise if ``dataset`` cannot be trained on.

    Called by the training manager *before* a task is scheduled, so an
    unusable corpus fails fast on the manager instead of burning an HPC
    allocation. The default check is just "not empty".
    """
    try:
        size = len(dataset)
    except TypeError:
        return
    if size == 0:
        raise ValueError(f"{self.name}: refusing to train on an empty dataset")

prepare_output_dir staticmethod

prepare_output_dir(base_dir: str, version: int, name: str) -> str

Standard checkpoint layout: <base_dir>/<name>/v<version>.

Source code in rome/train/base.py
@staticmethod
def prepare_output_dir(base_dir: str, version: int, name: str) -> str:
    """Standard checkpoint layout: ``<base_dir>/<name>/v<version>``."""
    path = os.path.join(base_dir, name, f"v{version}")
    os.makedirs(path, exist_ok=True)
    return path

TrainTask

TrainTask(*, gpus: int = 1, nodes: int = 1, name: Optional[str] = None)

Abstract base for ROME training algorithms.

Subclasses implement train. Everything else — when to run, where the data comes from, who hears about the new checkpoint — belongs to the training manager.

Parameters:

  • gpus (int, default: 1 ) –

    GPUs a single training task needs. The training manager forwards this to the workflow engine when submitting the task.

  • nodes (int, default: 1 ) –

    Nodes a single training task needs.

  • name (str, default: None ) –

    Human-readable label used in status reporting and checkpoint paths. Defaults to the class name.

Source code in rome/train/base.py
def __init__(self, *, gpus: int = 1, nodes: int = 1, name: Optional[str] = None):
    self.gpus = gpus
    self.nodes = nodes
    self.name = name or type(self).__name__

wants_hf_dataset class-attribute instance-attribute

wants_hf_dataset: bool = False

Set on subclasses that want a datasets.Dataset rather than a list.

train

train(dataset: Any, output_dir: str, **kwargs: Any) -> str

Train on dataset and write a checkpoint under output_dir.

Parameters:

  • dataset (Any) –

    Whatever rome.data.DataManager.get_dataset produced — a list of record dicts by default, or a datasets.Dataset when the trainer asked for one via wants_hf_dataset.

  • output_dir (str) –

    Directory the checkpoint should be written to. Already created.

  • **kwargs (Any, default: {} ) –

    Forwarded from rome.trainer.Trainer.train; implementations should tolerate unknown keys.

Returns:

  • str –

    Path to the checkpoint the stream manager should load. Returning output_dir itself is the common case.

Source code in rome/train/base.py
def train(self, dataset: Any, output_dir: str, **kwargs: Any) -> str:
    """Train on ``dataset`` and write a checkpoint under ``output_dir``.

    Parameters
    ----------
    dataset : Any
        Whatever :meth:`rome.data.DataManager.get_dataset` produced — a
        list of record dicts by default, or a ``datasets.Dataset`` when the
        trainer asked for one via :attr:`wants_hf_dataset`.
    output_dir : str
        Directory the checkpoint should be written to. Already created.
    **kwargs
        Forwarded from :meth:`rome.trainer.Trainer.train`; implementations
        should tolerate unknown keys.

    Returns
    -------
    str
        Path to the checkpoint the stream manager should load. Returning
        ``output_dir`` itself is the common case.
    """
    raise NotImplementedError("TrainTask.train() must be implemented by subclasses")

as_command

as_command(dataset: Any, output_dir: str, **kwargs: Any) -> Optional[Tuple[str, str]]

Optionally run this round as an executable task instead of a function.

Return (shell_command, checkpoint_path) to have the training manager submit shell_command as an executable task — a subprocess on the allocation's resources, the way IMPRESS submits its wrapper scripts — rather than pickling train into a worker. checkpoint_path is where the command will write the checkpoint, since an executable task's return value is not the path.

Return None (the default) to run train in-process as a function task. A GPU fine-tune should prefer the command form: the subprocess exits when the round ends, releasing its VRAM.

Completion contract: the command MUST write a file named train_complete (rome.trainer.TRAIN_COMPLETE_MARKER) into its output_dir as its final action, after the checkpoint is safely on disk. The training manager polls for that marker to detect the round finished, because on Dragon a task can run to completion and never resolve its future (a running service blocks result delivery — see docs/dragon.md). The marker, not the checkpoint, is the signal: with publish-in-place the checkpoint path already exists from the prior round.

Source code in rome/train/base.py
def as_command(self, dataset: Any, output_dir: str,
               **kwargs: Any) -> Optional[Tuple[str, str]]:
    """Optionally run this round as an executable task instead of a function.

    Return ``(shell_command, checkpoint_path)`` to have the training manager
    submit ``shell_command`` as an *executable* task — a subprocess on the
    allocation's resources, the way IMPRESS submits its wrapper scripts —
    rather than pickling :meth:`train` into a worker. ``checkpoint_path`` is
    where the command will write the checkpoint, since an executable task's
    return value is not the path.

    Return ``None`` (the default) to run :meth:`train` in-process as a
    function task. A GPU fine-tune should prefer the command form: the
    subprocess exits when the round ends, releasing its VRAM.

    Completion contract: the command MUST write a file named
    ``train_complete`` (``rome.trainer.TRAIN_COMPLETE_MARKER``) into its
    ``output_dir`` as its *final* action, after the checkpoint is safely on
    disk. The training manager polls for that marker to detect the round
    finished, because on Dragon a task can run to completion and never
    resolve its future (a running service blocks result delivery — see
    ``docs/dragon.md``). The marker, not the checkpoint, is the signal: with
    publish-in-place the checkpoint path already exists from the prior round.
    """
    return None

validate

validate(dataset: Any) -> None

Raise if dataset cannot be trained on.

Called by the training manager before a task is scheduled, so an unusable corpus fails fast on the manager instead of burning an HPC allocation. The default check is just "not empty".

Source code in rome/train/base.py
def validate(self, dataset: Any) -> None:
    """Raise if ``dataset`` cannot be trained on.

    Called by the training manager *before* a task is scheduled, so an
    unusable corpus fails fast on the manager instead of burning an HPC
    allocation. The default check is just "not empty".
    """
    try:
        size = len(dataset)
    except TypeError:
        return
    if size == 0:
        raise ValueError(f"{self.name}: refusing to train on an empty dataset")

prepare_output_dir staticmethod

prepare_output_dir(base_dir: str, version: int, name: str) -> str

Standard checkpoint layout: <base_dir>/<name>/v<version>.

Source code in rome/train/base.py
@staticmethod
def prepare_output_dir(base_dir: str, version: int, name: str) -> str:
    """Standard checkpoint layout: ``<base_dir>/<name>/v<version>``."""
    path = os.path.join(base_dir, name, f"v{version}")
    os.makedirs(path, exist_ok=True)
    return path

Trainer

Trainer(ddict: Namespace, data: DataManager, asyncflow: Any, config: Optional[TrainerConfig] = None)

Training manager in the ROME framework.

Parameters:

  • ddict (Namespace) –

    Shared state — the same DDict view every other ROME component uses.

  • data (DataManager) –

    Corpus the training rounds draw from.

  • asyncflow (WorkflowEngine) –

    Engine training tasks are submitted to.

  • config (TrainerConfig, default: None ) –

    May also be supplied later to start.

Source code in rome/trainer.py
def __init__(
    self,
    ddict: Namespace,
    data: DataManager,
    asyncflow: Any,
    config: Optional[TrainerConfig] = None,
):
    self.ddict = ddict
    self.data = data
    self.asyncflow = asyncflow
    self.config = config or TrainerConfig()
    self.stop_event = Event()
    self.listener_fut: Optional[asyncio.Task] = None

    self._status = TrainerStatus.NOT_STARTED
    self._rounds_completed = 0
    self._last_error: Optional[str] = None
    self._in_flight = False
    #: Future for the round currently in flight, for diagnostics only.
    self._round_fut = None
    self._extra_callbacks: List[Callable[[str, int], None]] = []

status property

status: TrainerStatus

Whether training is possible, running, or finished.

model_version property

model_version: int

Version of the newest published checkpoint (0 = never trained).

last_error property

last_error: Optional[str]

Traceback of the most recent failed round, if any.

train_task property

train_task: TrainTask

The configured trainer, wrapping a bare callable if needed.

start async

start(config: Optional[TrainerConfig] = None) -> Optional[Task]

Start the training manager.

With auto_train on this spawns the polling loop that fires a round whenever the corpus crosses min_samples. With it off the manager simply becomes available for manual train calls.

The poll loop is a plain asyncio task in the manager's own process — only the training rounds themselves go to the execution backend.

Source code in rome/trainer.py
async def start(self, config: Optional[TrainerConfig] = None) -> Optional[asyncio.Task]:
    """Start the training manager.

    With ``auto_train`` on this spawns the polling loop that fires a round
    whenever the corpus crosses ``min_samples``. With it off the manager
    simply becomes available for manual :meth:`train` calls.

    The poll loop is a plain asyncio task in the manager's own process —
    only the training rounds themselves go to the execution backend.
    """
    if config is not None:
        self.config = config
    if self.config.trainer is None:
        raise ValueError("TrainerConfig.trainer must be set before start()")

    self._status = TrainerStatus.STARTING
    self.stop_event.clear()
    os.makedirs(self.config.checkpoint_dir, exist_ok=True)

    # Settle on a real status before returning: a caller that checks
    # get_training_status() immediately after start() should see whether a
    # round is possible, not that the loop has not been scheduled yet.
    self._status = self._idle_status()
    if not self.config.auto_train:
        return None

    self.listener_fut = asyncio.create_task(self._trainer_listener())
    return self.listener_fut

stop async

stop(wait_for_stop: bool = True, timeout: float = 300.0) -> None

Stop the training manager.

An in-flight round is not cancelled — killing a half-finished fine-tune would leave a torn checkpoint — so this waits it out instead.

Source code in rome/trainer.py
async def stop(self, wait_for_stop: bool = True, timeout: float = 300.0) -> None:
    """Stop the training manager.

    An in-flight round is *not* cancelled — killing a half-finished
    fine-tune would leave a torn checkpoint — so this waits it out instead.
    """
    self._status = TrainerStatus.STOPPING
    self.stop_event.set()
    if not wait_for_stop:
        return
    deadline = time.time() + timeout
    while self._in_flight and time.time() < deadline:
        await asyncio.sleep(0.05)
    if self.listener_fut is not None:
        try:
            await asyncio.wait_for(
                asyncio.shield(self.listener_fut),
                timeout=max(0.0, deadline - time.time()) or 0.1,
            )
        except (asyncio.TimeoutError, asyncio.CancelledError):
            pass
    if self._status is not TrainerStatus.FAILED:
        self._status = TrainerStatus.STOPPED

train async

train(force: bool = False, **kwargs: Any) -> Optional[str]

Run one training round now — the workflow's manual trigger.

Returns the path to the new checkpoint, or None when the round was skipped because the corpus was not ready (pass force=True to train anyway) or another round is already in flight.

Failures propagate: a manual call is expected to surface its own errors, unlike the auto-train loop which records them in status.

Source code in rome/trainer.py
async def train(self, force: bool = False, **kwargs: Any) -> Optional[str]:
    """Run one training round now — the workflow's manual trigger.

    Returns the path to the new checkpoint, or ``None`` when the round was
    skipped because the corpus was not ready (pass ``force=True`` to train
    anyway) or another round is already in flight.

    Failures propagate: a manual call is expected to surface its own
    errors, unlike the auto-train loop which records them in
    :attr:`status`.
    """
    if not force and not self.data.ready_to_train():
        self._status = TrainerStatus.NOT_ENOUGH_DATA
        return None
    return await self._run_round(**kwargs)

on_checkpoint

on_checkpoint(callback: Callable[[str, int], None]) -> Callable

Register an extra (checkpoint_path, version) callback.

Source code in rome/trainer.py
def on_checkpoint(self, callback: Callable[[str, int], None]) -> Callable:
    """Register an extra ``(checkpoint_path, version)`` callback."""
    self._extra_callbacks.append(callback)
    return callback

get_status

get_status() -> TrainerStatus

Alias for status — the API-call form from the design slide.

Source code in rome/trainer.py
def get_status(self) -> TrainerStatus:
    """Alias for :attr:`status` — the API-call form from the design slide."""
    return self.status

get_current_model

get_current_model() -> Optional[str]

Path to the newest published checkpoint, or None before round 1.

Source code in rome/trainer.py
def get_current_model(self) -> Optional[str]:
    """Path to the newest published checkpoint, or ``None`` before round 1."""
    return self.ddict.get(MODEL_PATH_KEY)

report

report() -> Dict[str, Any]

One-call summary for dashboards and logs.

Source code in rome/trainer.py
def report(self) -> Dict[str, Any]:
    """One-call summary for dashboards and logs."""
    return {
        "status": self.status.name,
        "model_version": self.model_version,
        "model_path": self.get_current_model(),
        "rounds_completed": self._rounds_completed,
        "corpus_size": self.data.total_count,
        "unconsumed": self.data.unconsumed_count,
        "last_error": self._last_error,
    }

TrainerConfig dataclass

TrainerConfig(trainer: Any = None, checkpoint_dir: str = './rome_checkpoints', auto_train: bool = True, max_rounds: Optional[int] = None, poll_interval: float = 5.0, result_fallback_seconds: Optional[float] = 60.0, task_description: Optional[Dict[str, Any]] = None, train_kwargs: Dict[str, Any] = dict(), on_checkpoint: Optional[Callable[[str, int], None]] = None, stop_on_failure: bool = False, max_consecutive_failures: Optional[int] = None)

Configuration for the training manager.

Parameters:

  • trainer (TrainTask or Callable, default: None ) –

    The training algorithm. A bare callable (dataset, output_dir, **kwargs) -> checkpoint_path is wrapped in a FunctionTrainer automatically.

  • checkpoint_dir (str, default: './rome_checkpoints' ) –

    Root for published checkpoints; rounds land in <checkpoint_dir>/<trainer name>/v<version>.

  • auto_train (bool, default: True ) –

    Poll the data manager and fire a round as soon as enough data has accumulated. Turn off to drive training purely by hand.

  • max_rounds (Optional[int], default: None ) –

    Stop after this many completed rounds. None runs until stopped.

  • poll_interval (float, default: 5.0 ) –

    Seconds between data-threshold checks in the auto-train loop.

  • result_fallback_seconds (Optional[float], default: 60.0 ) –

    Grace period before a round whose checkpoint is already on disk is treated as finished even though the execution backend never delivered its result. None disables the fallback and waits on the backend forever.

    This exists because of a real backend defect, not as a convenience. Dragon pre-registers a running task's result key, so reading that key blocks rather than raising KeyError. rhapsody's monitor sweeps its outstanding tasks in order, so a task that never completes -- which is exactly what a ROME inference stream is -- blocks the sweep on its own key forever, and every result behind it, including a finished training round, is never delivered. Confirmed by direct measurement::

    manager(0)['0-0'] -> STILL BLOCKED after 20s   # the stream service
    manager(0)['0-1'] -> returned in 0.12s         # the finished round
    

    The round itself is fine: it runs, and its checkpoint is on disk. Only the notification is lost, so the checkpoint is the sounder signal.

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

    Backend-specific resource request forwarded to asyncflow. When None, one is derived from the trainer's gpus/nodes.

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

    Extra keyword arguments forwarded to every TrainTask.train call.

  • on_checkpoint (Optional[Callable[[str, int], None]], default: None ) –

    Called with (checkpoint_path, version) after each successful round. The manager registers the stream manager's hot-swap hook here.

  • stop_on_failure (bool, default: False ) –

    Move to FAILED and end the auto-train loop when a round raises. When False (default) the failure is recorded and polling continues.

  • max_consecutive_failures (Optional[int], default: None ) –

    Stop the auto-train loop after this many consecutive failed rounds. None (default) retries indefinitely. Resets to zero on a successful round.

TrainerStatus

Bases: Enum

Status of the ROME training manager.

NOT_ENOUGH_DATA and WAITING are both idle, but they answer different questions: the first says a round is not currently possible, the second says it is possible and about to start.

Namespace

Namespace(ddict: MutableMapping, prefix: str = '')

Bases: MutableMapping

A prefixed view over a Dragon DDict (or any mapping).

Every operation goes through a handle owned by the calling thread — see thread_handle — so views may be shared freely across the manager and its stream workers.

Parameters:

  • ddict (MutableMapping) –

    The shared dictionary. Normally a dragon.data.ddict.DDict; any mapping works, which is what makes the components unit-testable.

  • prefix (str, default: '' ) –

    Prepended to every key this view touches.

Source code in rome/utils.py
def __init__(self, ddict: MutableMapping, prefix: str = ""):
    self._ddict = ddict
    self._prefix = prefix
    # Serialized once, here, rather than per access: serialize() is itself
    # a client operation, and calling it from many threads would be the
    # very race this is meant to avoid.
    self._serialized = ddict.serialize() if hasattr(ddict, "serialize") else None

ddict property

ddict: MutableMapping

The underlying shared dictionary.

namespace

namespace(*segments: Any) -> 'Namespace'

Derive a child view: ns.namespace("record") -> keys record|….

Source code in rome/utils.py
def namespace(self, *segments: Any) -> "Namespace":
    """Derive a child view: ``ns.namespace("record")`` -> keys ``record|…``."""
    suffix = SEP.join(str(s) for s in segments)
    child = Namespace.__new__(Namespace)
    child._ddict = self._ddict
    child._prefix = f"{self._prefix}{suffix}{SEP}"
    # Inherited rather than recomputed: serialize() is a client operation,
    # and child views are created on hot paths.
    child._serialized = self._serialized
    return child

get

get(key: str, default: Any = None) -> Any

Read key, returning default when absent.

Goes through __getitem__ rather than DDict.get so the behaviour is identical whichever mapping is underneath.

Source code in rome/utils.py
def get(self, key: str, default: Any = None) -> Any:
    """Read ``key``, returning ``default`` when absent.

    Goes through ``__getitem__`` rather than ``DDict.get`` so the behaviour
    is identical whichever mapping is underneath.
    """
    try:
        return self._target[self._full(key)]
    except (KeyError, TypeError):
        return default

pop

pop(key: str, default: Any = _MISSING) -> Any

Remove key and return its value.

This is ROME's claim protocol: whoever pops a key owns that item, so two stream replicas draining the same queue never process a request twice. Correctness rests on the underlying pop being atomic, which is why it delegates rather than doing read-then-delete — a Dragon DDict resolves the contention manager-side, and measurably: four threads racing over 120 keys claim 120 with zero duplicates.

The single-argument form is deliberate. dict.pop(k, default) returns the default while DDict.pop(k, default) raises DDictKeyError regardless, so asking for the default would behave differently on the two backings; catching KeyError (which DDictKeyError subclasses) behaves the same on both.

Source code in rome/utils.py
def pop(self, key: str, default: Any = _MISSING) -> Any:
    """Remove ``key`` and return its value.

    This is ROME's claim protocol: whoever pops a key owns that item, so
    two stream replicas draining the same queue never process a request
    twice. Correctness rests on the underlying pop being atomic, which is
    why it delegates rather than doing read-then-delete — a Dragon DDict
    resolves the contention manager-side, and measurably: four threads
    racing over 120 keys claim 120 with zero duplicates.

    The single-argument form is deliberate. ``dict.pop(k, default)``
    returns the default while ``DDict.pop(k, default)`` raises
    ``DDictKeyError`` regardless, so asking for the default would behave
    differently on the two backings; catching ``KeyError`` (which
    ``DDictKeyError`` subclasses) behaves the same on both.
    """
    try:
        return self._target.pop(self._full(key))
    except (KeyError, TypeError):
        if default is _MISSING:
            raise KeyError(key)
        return default

increment

increment(key: str, amount: int = 1) -> int

Bump an integer counter and return the new value.

Only safe when a single component owns the counter — ROME keeps to that (the training manager owns model_version, and so on).

Source code in rome/utils.py
def increment(self, key: str, amount: int = 1) -> int:
    """Bump an integer counter and return the new value.

    Only safe when a single component owns the counter — ROME keeps to
    that (the training manager owns ``model_version``, and so on).
    """
    new = int(self.get(key, 0)) + amount
    self[key] = new
    return new

keys

keys(prefix: str = '') -> List[str]

Namespace-relative keys, optionally filtered by a further prefix.

Source code in rome/utils.py
def keys(self, prefix: str = "") -> List[str]:  # type: ignore[override]
    """Namespace-relative keys, optionally filtered by a further prefix."""
    full_prefix = self._full(prefix)
    cut = len(self._prefix)
    return sorted(k[cut:] for k in self._raw_keys() if k.startswith(full_prefix))

items

items(prefix: str = '') -> List[Tuple[str, Any]]

(key, value) pairs under prefix, skipping keys that vanish mid-scan.

Source code in rome/utils.py
def items(self, prefix: str = "") -> List[Tuple[str, Any]]:  # type: ignore[override]
    """``(key, value)`` pairs under ``prefix``, skipping keys that vanish mid-scan."""
    out: List[Tuple[str, Any]] = []
    for key in self.keys(prefix):
        value = self.get(key, _MISSING)
        if value is not _MISSING:
            out.append((key, value))
    return out

drain

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

Pop and return up to limit (key, value) pairs under prefix.

Source code in rome/utils.py
def drain(self, prefix: str = "", limit: Optional[int] = None) -> List[Tuple[str, Any]]:
    """Pop and return up to ``limit`` ``(key, value)`` pairs under ``prefix``."""
    out: List[Tuple[str, Any]] = []
    for key in self.keys(prefix):
        if limit is not None and len(out) >= limit:
            break
        value = self.pop(key, _MISSING)
        if value is not _MISSING:
            out.append((key, value))
    return out

clear

clear(prefix: str = '') -> int

Delete every key under prefix; returns how many were removed.

Source code in rome/utils.py
def clear(self, prefix: str = "") -> int:  # type: ignore[override]
    """Delete every key under ``prefix``; returns how many were removed."""
    return len(self.drain(prefix))

snapshot

snapshot(prefix: str = '') -> Dict[str, Any]

A plain dict copy of this view — handy when logging or debugging.

Source code in rome/utils.py
def snapshot(self, prefix: str = "") -> Dict[str, Any]:
    """A plain ``dict`` copy of this view — handy when logging or debugging."""
    return dict(self.items(prefix))