Skip to content

rome.trainer

Training Manager — creates and schedules training tasks, publishes checkpoints.

Responsibilities, straight off the design slide:

  • create and schedule training tasks on HPC — every round is submitted to the radical.asyncflow engine the host workflow handed to ROME, so the training task gets its own nodes and GPUs like any other workflow task;
  • publish updated checkpoints back to the workflow, so the stream manager and the host workflow pick up the improved model mid-campaign;
  • answer whether training is possible, running, or finished.

Training starts automatically once enough data accumulates (the data manager's min_samples threshold) or is triggered manually by the workflow awaiting Trainer.train.

TRAIN_COMPLETE_MARKER module-attribute

TRAIN_COMPLETE_MARKER = 'train_complete'

Filename an executable trainer's wrapper writes into a round's output_dir.

Written as the wrapper's final action, so the driver can detect completion even when the backend never delivers the task's result. It must appear only when the round has finished writing its checkpoint — unlike the checkpoint itself, which for publish_into_repo is a stable path that already exists from the previous round (or the initial weights). Kept in sync with the wrapper scripts; see rome.train.base.TrainTask.as_command.

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.

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.

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,
    }