nemo_rl.models.generation.prefix_recovery.recovery#
Cut live model calls at a checkpoint and resume them after a restore.
The worker builds one PrefixRecovery in setup_token_capture when
target_level is prefix, or a NoPrefixRecovery otherwise, and calls
it at fixed points: when a call begins and gets its sampling settings, when its
final output arrives and its terminal row is written, at every checkpoint cut
and snapshot flush. Only the ProgressReader it is given knows the engine.
Module Contents#
Classes#
A verified restored prefix, with its call’s routes and sampler top-k. |
|
Generation-prefix cuts and restores for one worker’s captured calls. |
|
What a worker without generation-prefix cuts does at each recovery point. |
Functions#
Zeroed progress-read counters, so each is reported from the first step. |
|
Refuse a cut whose inventory entry names another episode than the call. |
|
Join the fetched chunks’ sampler top-k, or None when score centering is off. |
|
Whether the generated text stops partway through a multi-byte character. |
Data#
API#
- nemo_rl.models.generation.prefix_recovery.recovery.LOGGER#
‘getLogger(…)’
- nemo_rl.models.generation.prefix_recovery.recovery._COMPLETED_CAPTURE_RETENTION_S#
None
- nemo_rl.models.generation.prefix_recovery.recovery._LOGGED_UNCUTTABLE_REASONS: set[str]#
‘set(…)’
- nemo_rl.models.generation.prefix_recovery.recovery._PREFIX_BOUNDARY_TAIL_TOKENS#
8
- nemo_rl.models.generation.prefix_recovery.recovery.initial_generation_cut_counts() dict[str, int]#
Zeroed progress-read counters, so each is reported from the first step.
How many reads of the engine’s decoding progress, for how many calls, and the total microseconds spent waiting for and holding its output lock.
- nemo_rl.models.generation.prefix_recovery.recovery._require_inventory_identity(
- prefix: Any,
- worker_capture_key: str,
- *,
- call_kind: str,
Refuse a cut whose inventory entry names another episode than the call.
- class nemo_rl.models.generation.prefix_recovery.recovery._ResolvedGenerationCut#
A verified restored prefix, with its call’s routes and sampler top-k.
- snapshot: Any#
None
- routed_experts: torch.Tensor | None#
None
- sampler_topk: tuple[torch.Tensor, torch.Tensor] | None#
None
- nemo_rl.models.generation.prefix_recovery.recovery._join_chunk_sampler_topk(
- chunks: collections.abc.Sequence[Any],
- top_k: int,
Join the fetched chunks’ sampler top-k, or None when score centering is off.
- Raises:
RuntimeError – a chunk carries no top-k, or not one row per generated token, e.g. it was cut before score centering was on.
- nemo_rl.models.generation.prefix_recovery.recovery._ends_inside_character(
- tokenizer: Any,
- generated_token_ids: list[int],
Whether the generated text stops partway through a multi-byte character.
The engine detokenizes a resumed call’s tail with a stream primed on the prompt, which ends with the restored prefix. A prefix ending inside a character makes that stream emit the whole decoded prompt as the tail’s first text.
- class nemo_rl.models.generation.prefix_recovery.recovery.PrefixRecovery( )#
Generation-prefix cuts and restores for one worker’s captured calls.
Initialization
- property control_token: str | None#
The bearer token the cut route requires; None refuses every cut.
- on_begin(admission: Any) None#
Count a call Gym’s
begin_callaccepted with a restored cut.
- on_sampling_params(
- request: Any,
- sampling_params: Any,
Record the engine’s resolved output budget, and whether a cut can resume.
- observe(request: Any, request_output: Any) None#
Record the tokens a finished output adds past the last cut.
- retire(staging_keys: collections.abc.Sequence[str]) None#
Queue an ended call’s chunk rows for the next snapshot to delete.
A snapshot in progress may still name them, so they wait until the next one starts, after this one is saved.
- async flush(epoch: int) None#
Delete the chunk rows retired before snapshot
epochstarted.Returns once the delete is done: TQ must not clear rows while the snapshot is saved.
- _flush_retired(epoch: int) None#
- counts() dict[str, int]#
Restore and progress-read counts since this process started.
- Returns:
restored_callsand their totalrestored_prefix_tokens, plusprogress_reads,progress_read_callsand the microseconds they waited for and held the engine’s output lock, and the write pipeline’spipeline_*counts (see :meth:PrefixWritePipeline.counts).
- shutdown() None#
- async run_cut(
- inventory: Any,
- *,
- deadline: float | None = None,
Cut every call Gym’s inventory names, off the serving loop.
deadlineis atime.monotonic()bound from a caller that waits on one of its own (the Dynamo frontend). Without it the cut getscontrol_timeout_sfrom its arrival here.
- _record_progress(
- states: list[nemo_rl.models.generation.prefix_recovery.state._RequestCaptureState],
- *,
- deadline: float | None,
Record the tokens each call decoded since its last record.
One read at an engine output boundary copies every call’s new token IDs, so all calls are read at the same point; their logprobs are then read outside it, from positions that read saw published. A call the engine has finished but whose consumer has not yet taken the output is read whole, with its finish reason. One the engine does not hold (not yet submitted, or aborted) keeps what it has recorded.
- Returns:
The route pieces the same read copied, by model call ID, for each router-replay call whose final output has not already brought its routes; a cut stages its routes from these.
- static _failed_ack(
- prefix: Any,
- *,
- reason: str,
- uncut: collections.Counter[str],
Acknowledge one uncut call and tally it under
reason.
- _completed_ack(
- prefix: Any,
- checkpoint_id: str,
- uncut: collections.Counter[str],
Describe a call whose terminal path won the cut/abort race.
- _cut_transaction(
- prefix: Any,
- state: nemo_rl.models.generation.prefix_recovery.state._RequestCaptureState,
- checkpoint_id: str,
- uncut: collections.Counter[str],
- *,
- route_pieces: list[Any] | None = None,
Hold one live call’s cut frozen until its row is written and acknowledged.
Yields
(record, chunk_sequence, attachments), receives the staged key, then seals and returns its acknowledgement. A call with nothing new to stage returns its acknowledgement (orNoneif abort won the race) without yielding. Closing it before the seal rolls the cut back and clears its row.route_piecesare the call’s router-replay route pieces, copied with its tokens by the cut’s progress read.
- static _chunk_routes(
- owned: Any,
- state: nemo_rl.models.generation.prefix_recovery.state._RequestCaptureState,
- progress: Any,
- frozen: Any,
- route_pieces: list[Any] | None,
The router-replay routes of the chunk a cut stages, or None.
A finished call’s own output carries its routes; otherwise the cut’s progress read copied the engine’s route pieces with its tokens.
- Raises:
ValueError – the routes do not cover every token the cut stages.
- _chunk_sampler_topk(
- state: nemo_rl.models.generation.prefix_recovery.state._RequestCaptureState,
- frozen: Any,
Score centering’s sampler top-k for the tokens a cut stages, or None.
Read from the engine container the call’s tokens were recorded from, so the chunk carries what the call’s final response would have.
- Raises:
RuntimeError, ValueError – the container lacks a staged position, or its candidates are malformed.
- checkpoint_cut(
- inventory: Any,
- *,
- deadline: float | None = None,
Run one cut through the write pipeline and wait for its receipt.
- _cut_writes(
- inventory: Any,
- *,
- deadline: float | None,
Prepare transactions, then seal their rows after durable write replies.
deadlineis atime.monotonic()bound. Gym stops waiting for the receipt at its own control deadline, so calls not reached by then are acknowledged as failures (they regenerate after restore) instead of holding the cut-control or pipeline preparation thread for the next checkpoint.
- _cut_batched(
- inventory: Any,
- uncut: collections.Counter[str],
- *,
- route_pieces: dict[str, list[Any]],
- deadline: float | None,
Cut every call of the inventory, writing their rows in batches.
Each call’s cut stays frozen until its batch is written and every acknowledgement in the batch is built. A batch holds at most
prefix_write_max_rowsrows and, unless one row alone is larger,prefix_write_max_tokenstokens.Gym acknowledges cuts per call, so a call that cannot be cut (a failed freeze, write, acknowledgement or seal) is acknowledged as a failure and regenerates after a restore; the other calls keep their cuts. A failed batch write is retried one row per write, so one bad row fails only its own call. Past
deadlineno further write starts, and the calls not yet written are acknowledged as failures.A batch also stays within
max_batch_payload_bytes(estimated), unless one row alone is larger; that row is written alone.
- _fetch_rows(staging_keys: list[str]) list[Any]#
Fetch cut rows with their extras, routes and top-k, in the requested order.
Also the fetch callback of the restore reader, which coalesces the keys of concurrent restores into one call.
- async aclose() None#
Fail pending restore reads; call before
shutdown.
- _rebuild_prefix(
- admission: Any,
- prefix_token_ids: list[int],
- chunks: list[Any],
Rebuild and verify the cumulative prefix from an admission’s fetched chunks.
With router replay on, each chunk’s routes are verified and joined too.
- async resolve_restore(
- admission: Any,
- prefix_token_ids: list[int],
Resolve an admission’s restored prefix, or drop it so the call regenerates.
Gym has already consumed the restored cut when it sends this call, and generating the whole response from the turn boundary is always valid, so a prefix that cannot be fetched or does not match its admission costs time, not the rollout. Returns the admission to serve and the verified prefix with its routes, or the admission without its cut and None. Call it on the serving loop: restores arriving together share one TQ read there.
- remember_completed(
- model_call_id: str,
- coords: Any,
- generation_token_count: int,
- *,
- effective_output_limit: int | None = None,
- terminal_finish_reason: Literal[stop, length] | None = None,
- terminal_stop_reason: str | int | None = None,
Keep a finished call’s terminal row for a cut that still names it.
- class nemo_rl.models.generation.prefix_recovery.recovery.NoPrefixRecovery#
What a worker without generation-prefix cuts does at each recovery point.
Every hook is a no-op, so the worker never asks whether cuts are on.
- control_token: str | None#
None
- async resolve_restore(
- admission: Any,
- prefix_token_ids: list[int],
- on_begin(admission: Any) None#
- on_sampling_params(
- request: Any,
- sampling_params: Any,
- observe(request: Any, request_output: Any) None#
- remember_completed(
- model_call_id: str,
- coords: Any,
- generation_token_count: int,
- *,
- effective_output_limit: int | None = None,
- terminal_finish_reason: Literal[stop, length] | None = None,
- terminal_stop_reason: str | int | None = None,
- retire(staging_keys: collections.abc.Sequence[str]) None#
- async flush(epoch: int) None#
- async aclose() None#
- counts() dict[str, int]#
- shutdown() None#
- async run_cut(
- inventory: Any,
- *,
- deadline: float | None = None,