How #5176's new prefix write path differs from the one #4508 already has

NVIDIA-NeMo/RL #5176, part 11 of 11 in the partial-checkpointing stack. Only the PR's own commit counts: 788133a..981376a, +2,281 / −49 (GitHub shows more because the base branch moved). Permalinks pin the PR head 981376a.

Before
At a checkpoint, one thread per generation worker prepares a batch of cut rows, writes it to TransferQueue, waits, seals it, then starts the next batch.
This PR
Adds three opt-in pieces: a faster column encoder, a pipeline that prepares the next batch while the last one is written, and a separate CPU process that does the writes.
Status
New feature, off by default. Review open: the design holds up; the review asks to make it the default with no settings, shrink it by about 560 lines, and make CI check that it runs.

Four pages on this PR. This one: how the new write path runs next to the old one, as a timeline and as pseudocode.

Background. During a long generation, a checkpoint can save each request's tokens so far (its "prefix") instead of throwing them away. Gym sends each generation worker an inventory; the worker cuts each call, writes one row per call to TransferQueue (TQ), and only after the write is acknowledged does it seal the row. Dotted words have a short explanation: hover or tap them.

Today, run_cut hands each inventory to one control thread, which runs checkpoint_cut from start to end. The PR turns the cut into a generator that stops at each write (keys = yield PrefixWrite(...)). With the pipeline off, checkpoint_cut drives that generator itself, so the old behavior stays. With it on, _advance prepares on one thread and _write writes on another, merging rows from different inventories into one write.

prepare rows (cut calls, encode) TQ write (waits for the ack) seal rows, build Gym's receipt example: inventory A = 3 calls, B = 2 calls Before (#4508): one control thread prep A·3 write 3 rows seal prep B·2 write 2 rows seal checkpoint_cut 2 writes, each waits alone This PR, pipeline on: a prepare thread and a writer thread _advance prep A·3 prep B·2 seal A,B _write write 5 rows finishes sooner: A and B share one write merged by _collect (≤ 256 rows, ≤ 128 MiB) after a 10 ms wait The data at each hop (same 5 rows in both) old encoder _encode_record × 5 → 5 one-row tensor dicts → stack_or_nest new encoder encode_prefix_groups → one TensorDict [rows=5], ids/mask/logprobs jagged by row TQ client old: worker's own client new (optional): RayPrefixWriterClient → CPU actor → its client Both paths meet at stage_generation_prefix_batch and seal with the same loop: transaction.send(key) (times are illustrative)

The same change as pseudocode

The cut, before (#4508)

# serving event loop -> one control thread per worker
async def run_cut(inventory):
    return await loop.run_in_executor(control_thread, cut, inventory)

# control thread: the whole cut runs here, start to end
def cut(inventory):
    for call in inventory.calls:
        tx = cut_transaction(call)                   # generator; holds call.lifecycle_lock
        pending.append(tx, row)
        if pending is full: flush()                  # 256 rows / 4M tokens
    flush()

def flush():
    keys = stage(pending)                            # encode + TQ put, waits for the ack
    for tx, key in zip(pending, keys): tx.send(key)  # seal the row
    for tx in pending: tx.send(None)                 # build the ack, release the lock

Real code: run_cut, checkpoint_cut, _cut_batched (at 788133a).

The cut, after (this PR): the same steps, paused at each write

# serving event loop
async def run_cut(inventory):
    if pipeline: return await pipeline.submit(inventory)               # pipeline on
    return await loop.run_in_executor(control_thread, cut, inventory)  # pipeline off

# whoever drives it: the control thread (off) or the prepare thread (on)
def cut_steps(inventory):                                              # now a generator
    for call in inventory.calls:
        tx = cut_transaction(call)                                     # holds call.lifecycle_lock
        pending.append(tx, row)
        if pending is full: yield from flush()

def flush():
    keys = stage(pending)
    keys = yield PrefixWrite(rows, fallback=stage)                     # pause; locks stay held
    for tx, key in zip(pending, keys): tx.send(key)                    # seal, back on this thread
    for tx in pending: tx.send(None)
    yield BatchReleased()                                              # locks released

def cut(inventory):                                                    # pipeline off: drive it inline
    for req in steps: steps.send(req.fallback())                       # fallback = stage()

Real code: run_cut, checkpoint_cut, _checkpoint_steps, flush.

New: the two pipeline threads and the writer actor (all new code)

# prepare thread, one per worker (owns every generator and lock)
def _run():
    loop:
        if a write finished: _complete(jobs)            # send keys -> seal
        elif rows waited 10 ms: _writers.submit(_write, _collect())
        elif buffer has room: _advance(next inventory)  # run to next yield

# writer thread, one per worker (one write in flight)
def _write(jobs):                                       # rows of several inventories
    try: keys = sink.stage_generation_prefix_batch(all rows)
    except: keys = [job.fallback() for job in jobs]     # each inventory alone

# writer thread, inside the sink (writer actor on)
cols = encode_prefix_groups(rows)                       # one TensorDict
ref = ray.put(PrefixPut(pack_columns(cols)))            # NumPy byte buffers
ray.get(writer_actor.put.remote(ref))                   # blocks until TQ acks

# PrefixWriterActor process (CPU only, same node)
def put(batch):
    fields = unpack_columns(batch.columns)
    own_tq_client.put_samples(keys, fields, tags)       # the TQ write

Real code: PrefixWritePipeline._run, _write, RayPrefixWriterClient.put_samples, PrefixWriterService.put. A call's lock is taken and released only on the prepare thread; the writer thread and the actor only move bytes. The generator can pause while it holds locks, which is why the pipeline caps how many prepared batches wait (the byte budget).

Where they join, and what still differs

Old path (#4508)New path (#5176, all three pieces on)
Who runs the cutOne control thread, start to endPrepare thread owns every call's lock; writer thread only writes. A write's rows are sealed back on the prepare thread.
Rows per writeOne inventory, up to generation_prefix_batch_size (256)Rows from several inventories, up to the smaller of that and max_batch_rows (also 256)
Encoder_encode_record per rowencode_prefix_groups per batch; same columns and tags (a parity test checks this)
Who talks to TQThe worker's clientA CPU actor on the same node, reached through NumPy byte buffers
Oversized single rowWritten aloneFails its cut and regenerates (documented)

They meet at stage_generation_prefix_batch: same staging keys, same columns, same seal loop. Before that point the difference is only when rows are prepared and who sends them. The measured gain (single runs, prefix cut + save): 52.4 s → 31.7 s with the encoder and pipeline, → 25.2 s with the actor added.

So what. The design is sound: one generator serves both the old and the new path, and nothing is acknowledged before TQ confirms the write. The review's asks are about size and CI. The NumPy packing layer and its client wrapper can go, since Ray already sends a TensorDict and the author's own data says packing did not change total time. The three new settings allow six write paths; the review asks to drop them and use the new path wherever it can run. CI never runs the 78 new tests. Page 2 lists each cut and why it is safe.

🔴 Review comments: C2 · drop packingC15 · no settingsC1 · tests never run in CIC10 · end-to-end run