Skip to content

[rl][metrics] Time each data-plane hop and log its payload bytes - #6268

Closed
wwwjn wants to merge 1 commit into
wwwjn/rl-rdma-objectfrom
wwwjn/data-plane/0-hop-metrics
Closed

wwwjn wants to merge 1 commit into
wwwjn/rl-rdma-objectfrom
wwwjn/data-plane/0-hop-metrics

Conversation

@wwwjn

@wwwjn wwwjn commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Human note: Add logging for measure data plane transfer time

TLDR: Logs the time and payload of each by-value data-plane hop (controller -> rollout worker, controller -> batcher, controller -> trainer), so every later PR in the data-plane stack is measured against them. Metrics only: loss is bitwise identical, and the cost is ~4 ms of controller CPU per step at 256 prompts per step.

# PR Independent? Needs
0 RDMA object for microbatches and prompts (#5862) yes -
1 Time each data-plane hop and log its payload bytes (#6268, this PR) yes stacked on 0 for merge order only
2 Wake one waiter per work-buffer event; release slots by group id (#6269) yes 1 (test fixtures)
3 Rollout workers return a slim group (#6301) yes 2 (same controller loop)
4 Split the batcher into a metadata half and a bytes half (#6302) no -- merges with 5 3
5 Trainer DP replica leaders pack their own microbatches from the plan (#6303) no 4
6 Rollout groups reach the trainer by RDMA handle (#6323) no 5
7 Read the next step's rollout groups during the optimizer step (#6324) no 6
8 Prompt image files share the rollout worker's torch transport pool (#6334) no 6 (not 7)

Merge bottom-up. 7 and 8 each need 6, and not each other.

Problem

  1. Each group crosses three Monarch calls before it trains: the reply of run_group (rollout worker -> controller), add_group (controller -> batcher) and forward_backward (controller -> trainer).
  2. None of them is timed end to end. timing/step/forward_backward exists, but nothing separates the trainer's own work from serialization, transport and queueing.
  3. Nothing logs how many bytes each hop carries, and features grow them: score centering at k=32 adds 256 B per completion token, 15x a group's size on the alphabet-sort task.
  4. So a data-plane change has no before/after number for the hop it changes.

Solution

  1. The caller times each call (wall). The callee returns the time spent in its handler. transfer = wall - handler: serialization, transport, the callee's endpoint queue and the caller's event-loop lag. Each side measures a duration on its own clock, so no clock sync.
  2. Each Monarch endpoint returns (result, handler_s): run_group, add_group, and forward_backward on every trainer rank. Trainer.forward_backward is unchanged.
  3. forward_backward's collectives make every last-stage rank leave its handler at about the same time, so the rank whose column arrived last spends the least time in it. Its transfer is wall - min(handler_s) over the ranks that return metrics (under PP, the last stage); handler/max is the longest.
  4. One helper, compute_hop_metrics in controller/metrics.py, builds the metrics for run_group and add_group.
  5. payload/rollout_group_array_bytes sums .nbytes of every numpy array field of each turn (dataclasses.fields), plus the image file bytes. Arrays a feature adds are counted without a code change. It is not the pickled size: messages, metrics and logs are not counted.
  6. Controller._rollout_loop now extends group.metrics instead of overwriting them, so the rollouter's metrics survive.
  7. Unchanged: what each hop sends, the order of calls, the losses.

New metric keys:

timing/hop/run_group/{wall,handler}/mean, timing/hop/run_group/transfer/{mean,max}     controller, per group
timing/hop/add_group/{wall,handler}/mean, timing/hop/add_group/transfer/{mean,max}     controller, per call, ride with the next batch
timing/hop/forward_backward/handler/max                                                max over the trainer ranks that return metrics
timing/hop/forward_backward/transfer/mean                                              forward_backward wall - min handler over those ranks
payload/rollout_group_array_bytes/mean                                                 per group: arrays + image files
payload/forward_backward_bytes_per_dp_rank/mean                                        mean over DP ranks; by-value path only

Not covered: rollout worker -> generator generate. With rdma_min_tensor_bytes set, the microbatches stay in the batcher, so there is no forward_backward bytes metric.

Results

Qwen3-0.6B alphabet sort (T1), 4 GPUs on one host (trainer FSDP 2, two generators TP 1), 256 prompts x 4 samples, 12 steps
Q0's cost: 15 us per group + 86 us per batch = ~4 ms controller CPU per step (microbenchmark), 5 of 5,810 py-spy samples
baseline per hop (low-load run):
  run_group          wall 0.85 s   handler 0.70 s   transfer 146 ms mean / 374 ms max   4.6 KB per group
  add_group          wall 33 ms    handler 1.7 ms   transfer 31 ms mean / 481 ms max
  forward_backward   wall 28.8 s   handler 28.3 s   transfer 200 ms                      4.36 MB per DP rank
with score centering (k=32): 4.6 KB -> 72 KB per group, 4.36 -> 13 MB per DP rank
correctness: loss/mean, grad_norm, logprob_diff bitwise equal to main at every step
  (rl_grpo_qwen3_0_6b_varlen_batch_invariant, seed 42, 10 steps)

You may ask:

  • Why not put the handler time in group.metrics and look it up by key? Implicit coupling through a string lookup in a list. The tuple return is explicit at the one call site.
  • Why not a field on RolloutGroup or a reply dataclass? It changes a core type, or adds a type with two users, for one float.
  • Why not Monarch's own telemetry? Not evaluated. It would not give payload bytes per hop.
  • Why not log the pickled size of the group? It costs one more pickle per group on the worker. The array bytes are what grows with features and sequence length; logging fields are dropped by the next PRs.

NOTE:

  • Rebased onto main af04091d6 (2026-11-23). Rerun on the rebased heads: the CPU suite and pre-commit at every PR of the stack, and bitwise at the top of the stack ([WIP] [rl] Read the next step's rollout groups during the optimizer step #6324, with and without [rl] Rollout groups reach the trainer by RDMA handle #6323's knob) against main af04091d6 (rl_grpo_qwen3_0_6b_varlen_batch_invariant, seed 42, 10 steps): every non-timing TensorBoard tag equal at every step, TP 2 52/52 and PP 2 x FSDP 2 53/53, sorted rollout_samples.jsonl md5 equal. The other numbers here were measured before the rebase.
  • Transfer includes the caller's event-loop lag. In a saturated run, add_group transfer was 142 ms mean and 6.3 s max for a 1.8 ms handler; the next PR removes that lag.
  • Results come from the same change on main (cc020983a), before restacking on [WIP][rl] One RDMA object for microbatches and prompts; rollout workers send images as RDMA handles #5862 and before two review fixes: forward_backward transfer now subtracts the shortest handler over ranks instead of the longest, so the 200 ms above is a lower bound; and the payload keys were renamed. Bitwise is unaffected (metrics only).
  • Score centering was measured on a local test merge of that PR onto main.

Test plan

  • pytest tests/rl/unit_tests/cpu: 720 passed, 8 skipped ([WIP][rl] One RDMA object for microbatches and prompts; rollout workers send images as RDMA handles #5862: 714 passed, 8 skipped).
  • test_run_group_rollouts_logs_the_hop_and_the_payload: handler from the reply, wall >= the fake's 50 ms delay, transfer = wall - handler, exact payload bytes. The test turn carries an extra [2, 4] float32 array that a sum over named fields would miss (128 vs 160 B). Fails without this PR.
  • test_forward_backward_transfer_is_the_wall_time_minus_the_handler_time: two last-stage ranks with handler times 20 and 35 ms and an early-stage rank (no metrics) at 1 ms; transfer = wall - 20 ms, handler/max = 35 ms. Fails without this PR.
  • test_batcher_loop_times_each_add_group_call, test_rollout_loop_keeps_the_rollouter_metrics, test_batcher_logs_the_bytes_each_rank_receives_by_value[False]: fail without this PR.
  • pre-commit run --files <touched files>: clean.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 20, 2026
@wwwjn
wwwjn force-pushed the wwwjn/data-plane/0-hop-metrics branch from 43d7c83 to 7a0d11b Compare November 20, 2026 16:55
@wwwjn

wwwjn commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @wwwjn's task in 2m 52s —— View job


Approve, with two items to fix before merging: under PP, forward_backward/transfer takes the shortest handler time from the wrong ranks, and the human summary in the description is still a placeholder. See the review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Approve -- please address the items below before merging. This change only adds metrics. Loss is untouched, and the cost (~4 ms of controller CPU per step) is measured. Two small edits remain: one metric is computed wrong under PP, and the human summary is still a placeholder. The PR touches core RL controller and trainer code, so a maintainer still needs to review it.

What this PR does. Three Monarch endpoints now return (result, handler_s): run_group, add_group, and forward_backward on every trainer rank. The caller times each call itself. transfer = wall - handler is the time spent on serialization, transport, queueing and event-loop lag, and each process measures only durations on its own clock. The PR also logs two payload sizes: per-group numpy array bytes plus image bytes, and per-DP-rank tensor bytes for the by-value forward_backward path. _rollout_loop now extends group.metrics instead of overwriting them.

Example.

add_group, two calls before a batch:
  wall    = [0.030, 0.020] s   (controller perf_counter around call_one)
  handler = [0.010, 0.012] s   (batcher perf_counter around Batcher.add_group)
  -> timing/hop/add_group/transfer/mean 0.014, /max 0.020, attached to the batch they fill
forward_backward, DP 2 (FSDP), handlers 20 and 35 ms, wall 50 ms:
  the rank whose column landed last waits least in the FSDP all-gather
  -> transfer = 50 - 20 = 30 ms, handler/max = 35 ms

Must fix

  1. PR description: "Human note: TODO (Jiani)" is a placeholder. The human-written summary has to be filled in before merge.
  2. torchtitan/rl/controller/controller.py:1402 -- under PP, min(handler_s) is taken over ranks without the last stage. Those ranks return before the synced metrics reduction, so forward_backward/transfer picks up stage skew. Suggestion inline: keep only ranks whose metrics are not None. Unverified on GPU.

Should consider

  • torchtitan/rl/rollout/rollouter.py:25 -- rollout/ now imports controller/metrics.py for compute_hop_metrics. There is precedent (trainer.py imports combine_microbatch_metrics from there), and there is no import cycle today. Still, a helper that the rollouter and the controller both call fits better next to m.Mean / m.Max in torchtitan/rl/observability/metrics, or the rollouter could keep its three lines inline.
  • PR description, NOTE: "so the 200 ms below is a lower bound". The 200 ms figure is above that note. Also, the description's item 3 ("collectives make every rank leave its handler at about the same time") only holds for last-stage ranks under PP. See must-fix 2.
Details
  • Necessity: the problem is real. Nothing on the base branch separates trainer compute from transport for forward_backward, and the later PRs in the stack (#6269 and the ones after it) need a baseline. The tuple return touches three endpoints. All their callers are updated: run_group.choose is called only in rollouter.py, and add_group.call_one and forward_backward.call are called only in controller.py. No recipe or experiment calls them.
  • The _rollout_loop change from = to .extend: before this PR, group.metrics from run_group_rollouts was always empty, so overwriting lost nothing. With this PR it holds the hop and payload metrics, so .extend is needed and doesn't change any existing key.
  • The payload counts look right. TrainingMicrobatch.model_kwargs["image_files"] is a uint8 tensor, so VLM image bytes are counted on the trainer hop too. PromptImage.data is still present in the group the worker returns, because RDMAImageFiles only affects generate.
  • The forward_backward wall is timed separately from timing/step/forward_backward. The step timer also covers the finally broadcast and the NaN check, so the two values differ slightly. That's why the test needs abs=5e-3. This is harmless, but the comment at 1491 calls them the same thing.

Not verified: whether early-PP-stage ranks actually return before their GPU work ends. That depends on host blocking in the pipeline schedule's P2P waits.

Comment thread torchtitan/rl/controller/controller.py Outdated
Comment on lines +1402 to +1406
forward_backward_handler_s = [
handler_s
for replica_replies in fwd_bwd_results
for _, handler_s in replica_replies.values()
]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Under PP, min(forward_backward_handler_s) comes from the wrong rank. The comment at 1489 assumes every rank leaves its handler at about the same time. That holds for ranks with the last stage: they all run the metrics reduction in Trainer.forward_backward (trainer.py:336-354), which syncs. Ranks without the last stage return None right after engine.forward_backward (trainer.py:334-335). They skip that reduction, so they can leave their handler while their GPU work is still queued (unverified: depends on whether the PP schedule blocks the host). The shortest handler then belongs to an early stage, and transfer = wall - min(handler) includes the stage skew and the unsynced GPU tail instead of only transport. The by-value path supports PP, and PP is the path this metric covers, because RDMA rejects PP.

Smallest fix: take handler times only from ranks that returned metrics, which are the ranks that synced:

Suggested change
forward_backward_handler_s = [
handler_s
for replica_replies in fwd_bwd_results
for _, handler_s in replica_replies.values()
]
# Only ranks with the last stage run the synced metrics reduction; the others
# can leave their handler before their GPU work ends.
forward_backward_handler_s = [
handler_s
for replica_replies in fwd_bwd_results
for rank_metrics, handler_s in replica_replies.values()
if rank_metrics is not None
]

@wwwjn
wwwjn force-pushed the wwwjn/data-plane/0-hop-metrics branch from 7a0d11b to b1791f5 Compare November 20, 2026 17:05
@wwwjn

wwwjn commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @wwwjn's task in 55s —— View job


Approve: the PP handler fix is in; the only item left is the placeholder human summary in the PR description. See the review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Approve -- please address the item below before merging. The PP handler fix is in. The only must-fix left is the placeholder human summary. The PR touches core RL controller and trainer code, so a maintainer still needs to review it.

Changes since the last review (b1791f5)

  • Resolved: controller.py:1617 (diff line) now takes forward_backward_handler_s only from ranks whose metrics are not None, so under PP the early stages no longer set min(handler). test_trainer_loop.py now adds an early-stage rank (1 ms, metrics None) and checks transfer against wall - min(TRAINER_HANDLER_S). Without the filter, the test would fail.
  • Resolved: the description's NOTE now says "above", and item 3 now says "every last-stage rank".
  • Still open: the rollout/ -> controller/metrics.py import for compute_hop_metrics (should-consider, unchanged).

Example.

forward_backward, PP 2 x FSDP 2, wall 50 ms:
  last-stage ranks:  (metrics, 0.020), (metrics, 0.035)
  first-stage ranks: (None, 0.001),    (None, 0.001)
  before: transfer = 50 - 1  = 49 ms   (stage skew counted as transfer)
  now:    transfer = 50 - 20 = 30 ms,  handler/max = 35 ms

Must fix

  1. PR description: "Human note: TODO (Jiani)" is still a placeholder. The human-written summary has to be filled in before merge.

Should consider

  • torchtitan/rl/rollout/rollouter.py:25 -- still open from the last review. rollout/ imports compute_hop_metrics from controller/metrics.py. A helper that both the rollouter and the controller call fits better in torchtitan/rl/observability/metrics.
Details
  • I re-checked the callsites at HEAD. run_group.choose is called only in rollouter.py:265. add_group.call_one is called in controller.py:1275, in the actor docstring, and in test_batcher_actor.py, and all of them unpack three values. forward_backward.call is called only in controller.py:1379. Nothing in recipes or experiments calls these endpoints.
  • forward_backward_handler_s can't be empty: the next(...) just above it already requires at least one rank with metrics. If the call raises, the list is never read, because the exception propagates out of the try.
  • RolloutGroup.metrics uses default_factory=list (types.py:156), so the .extend in _rollout_loop doesn't alias metrics across groups.

Not verified: the GPU numbers in the description. They come from the pre-restack run, which the description already says.

wwwjn added a commit that referenced this pull request Nov 20, 2026
…plan

Stack: #5862 -> #6268 (hop metrics) -> #6269 (slots by group id) -> slim group
-> batcher split -> this.

Why: the batcher packed every microbatch of a step, so each step's bytes went
worker -> controller -> batcher -> controller -> every trainer rank (pp * cp * tp
copies per DP replica): four bulk pickles, two of them through the controller's
event loop, and serial image preprocessing on every trainer rank.

What changes:
1. The rollout worker returns its group split (`FinishedRolloutGroup(summary,
   arrays, recorder_lines)`); the work buffer holds it.
   `split_rollout_group` -> (`RolloutGroupSummary`, `RolloutGroupArrays`): the
   summary is the group with every ndarray field emptied (same dtype and
   trailing shape, not a view) and image files emptied, plus its turn lengths;
   the arrays hold every ndarray field by name and each image file once.
   `join_rollout_group` reverses it. Before splitting, the worker runs
   `check_prompt_prefixes` on every rollout, the one check that reads token
   values (in the batcher split PR it ran in `add_group`).
2. The batcher gets only summaries and returns the step's `StepPlan`: no
   tensors (`TrainerStepBatch` is deleted). `MicrobatchPacker` is a
   `Configurable`; its config (`per_sample_pad_multiple`, `num_mtp_layers`,
   `build_mrope_positions`) moves under `Batcher.Config.microbatch_packer`, so
   the planner and the packer read one source. The trainer builds the packer
   from it, with `pad_id`, `temperature` and `vision_processor`.
3. The controller keeps each trainable group's summary and arrays until its
   step, without the group metrics the batcher logs from its copy
   (`FinishedRolloutGroup.without_metrics`). It then sends each DP replica's
   leader (pipeline stage 0, CP and TP rank 0) its plan column and only the
   rollouts that column names (`Trainer.receive_replica_column`), under its
   own span and step timer (`timing/step/send_replica_columns`).
   `forward_backward` carries the group count and the global token counts.
4. On every trainer rank a `MicrobatchGroupReader` thread makes the step's
   microbatch groups up to two ahead of the one the engine waits on: the
   leader materializes and packs each group (`MicrobatchPacker.pack_planned`,
   which checks each sample's length and each microbatch's token counts
   against its specs) and broadcasts it, with its packing time, over a
   per-replica gloo group; the other ranks receive it; every rank
   preprocesses images. The replica groups come from the trainer's dense mesh
   (`build_dp_replica_group`). A leader that fails to pack broadcasts its
   error, so the replica fails instead of hanging. PP works from the start:
   every stage of a replica is in its group. The leader materializes one
   rollout group at a time and drops its arrays once its samples exist, and
   drops each microbatch group's samples once it is packed.
5. Deleted: the RDMA microbatch path (`Batcher.Config.rdma_min_tensor_bytes`,
   `RDMAMicrobatch`, `RDMAMicrobatchPrefetcher`, `maybe_release_oldest_batch`,
   the trainer's RDMA identity check, the controller's RDMA warning and PP
   rejection), the now-unused tensor and dataclass paths of
   `MonarchRDMAObject` (it registers bytes only: prompt image files), and
   `share_image_data` (the split keeps one copy per image).

Cost: the leaders pack only once forward_backward starts. With
training.preprocess_microbatch_groups_lazily=False (the default), the engine
reads every microbatch group before its first forward, so the column send and
the leaders' materialize, pack and broadcast are on the step's critical path;
with it on, the first group still waits for the column's materialize. Sending
the columns during the previous step (a follow-up) hides them.

Unchanged: the plan (FFD/LPT/zig-zag), the packing, the samples and the
numerics; the push/pull ordering; #5862's image-file path.
wwwjn added a commit that referenced this pull request Nov 20, 2026
…plan

Stack: #5862 -> #6268 (hop metrics) -> #6269 (slots by group id) -> slim group
-> batcher split -> this.

Why: the batcher packed every microbatch of a step, so each step's bytes went
worker -> controller -> batcher -> controller -> every trainer rank (pp * cp * tp
copies per DP replica): four bulk pickles, two of them through the controller's
event loop, and serial image preprocessing on every trainer rank.

What changes:
1. The rollout worker packs each finished group once
   (`pack_rollout_group`, new `rollout/packed_group.py`) and returns
   `FinishedRolloutGroup(summary, packed, recorder_lines)`; the work buffer
   holds it. The summary (`RolloutGroupSummary`, moved to `rollout/types.py`)
   is the group with every ndarray field emptied (same dtype and trailing
   shape) and image files emptied, plus its turn lengths. `PackedRolloutGroup`
   holds the bytes as uint8 regions of one buffer: per rollout, the rollout
   pickled without its arrays, then every ndarray field by name (64-byte
   aligned); per distinct image file, its bytes. `select` keeps the named
   rollouts' regions and their images' without copying;
   `unpack_rollout_group` rebuilds the rollouts, with arrays viewing the
   regions. Before packing, the worker runs `check_prompt_prefixes` on every
   rollout, the one check that reads token values (in the batcher split PR it
   ran in `add_group`).
2. The batcher gets only summaries and returns the step's `StepPlan`: no
   tensors (`TrainerStepBatch` is deleted). `MicrobatchPacker` is a
   `Configurable`; its config (`per_sample_pad_multiple`, `num_mtp_layers`,
   `build_mrope_positions`) moves under `Batcher.Config.microbatch_packer`, so
   the planner and the packer read one source. The trainer builds the packer
   from it, with `pad_id`, `temperature` and `vision_processor`.
3. The controller keeps only each trainable group's packed regions until its
   step: one GC-tracked object per group, not the per-turn object graph,
   which held for several steps made its full collections frequent and slow.
   It then sends each DP replica's leader (pipeline stage 0, CP and TP rank 0)
   its plan column and only the rollouts that column names
   (`Trainer.receive_replica_column`), under its own span and step timer
   (`timing/step/send_replica_columns`).
   `forward_backward` carries the group count and the global token counts.
4. On every trainer rank a `MicrobatchGroupReader` thread makes the step's
   microbatch groups up to two ahead of the one the engine waits on: the
   leader materializes and packs each group (`MicrobatchPacker.pack_planned`,
   which checks each sample's length and each microbatch's token counts
   against its specs) and broadcasts it, with its packing time, over a
   per-replica gloo group; the other ranks receive it; every rank
   preprocesses images. The replica groups come from the trainer's dense mesh
   (`build_dp_replica_group`). A leader that fails to pack broadcasts its
   error, so the replica fails instead of hanging. PP works from the start:
   every stage of a replica is in its group. The leader unpacks and materializes
   one rollout group at a time and drops its bytes once its samples exist, and
   drops each microbatch group's samples once it is packed.
5. Deleted: the RDMA microbatch path (`Batcher.Config.rdma_min_tensor_bytes`,
   `RDMAMicrobatch`, `RDMAMicrobatchPrefetcher`, `maybe_release_oldest_batch`,
   the trainer's RDMA identity check, the controller's RDMA warning and PP
   rejection), the now-unused tensor and dataclass paths of
   `MonarchRDMAObject` (it registers bytes only: prompt image files), and
   `share_image_data` (the packed group keeps one copy per image).

Cost: the leaders pack only once forward_backward starts. With
training.preprocess_microbatch_groups_lazily=False (the default), the engine
reads every microbatch group before its first forward, so the column send and
the leaders' materialize, pack and broadcast are on the step's critical path;
with it on, the first group still waits for the column's materialize. Sending
the columns during the previous step (a follow-up) hides them.

Unchanged: the plan (FFD/LPT/zig-zag), the packing, the samples and the
numerics; the push/pull ordering; #5862's image-file path.
wwwjn added a commit that referenced this pull request Nov 22, 2026
…plan

Stack: #5862 -> #6268 (hop metrics) -> #6269 (slots by group id) -> slim group
-> batcher split -> this.

Why: the batcher packed every microbatch of a step, so each step's bytes went
worker -> controller -> batcher -> controller -> every trainer rank (pp * cp * tp
copies per DP replica): four bulk pickles, two of them through the controller's
event loop, and serial image preprocessing on every trainer rank.

What changes:
1. The rollout worker packs each finished group once
   (`pack_rollout_group`, new `rollout/packed_group.py`) and returns
   `FinishedRolloutGroup(summary, packed, recorder_lines)`; the work buffer
   holds it. The summary (`RolloutGroupSummary`, moved to `rollout/types.py`)
   is the group with every ndarray field emptied (same dtype and trailing
   shape) and image files emptied, plus its turn lengths. `PackedRolloutGroup`
   holds the bytes as uint8 regions of one buffer: per rollout, the rollout
   pickled without its arrays, then every ndarray field by name (64-byte
   aligned); per distinct image file, its bytes. `select` keeps the named
   rollouts' regions and their images' without copying;
   `unpack_rollout_group` rebuilds the rollouts, with arrays viewing the
   regions. Before packing, the worker runs `check_prompt_prefixes` on every
   rollout, the one check that reads token values (in the batcher split PR it
   ran in `add_group`).
2. The batcher gets only summaries and returns the step's `StepPlan`: no
   tensors (`TrainerStepBatch` is deleted). `MicrobatchPacker` is a
   `Configurable`; its config (`per_sample_pad_multiple`, `num_mtp_layers`,
   `build_mrope_positions`) moves under `Batcher.Config.microbatch_packer`, so
   the planner and the packer read one source. The trainer builds the packer
   from it, with `pad_id`, `temperature` and `vision_processor`.
3. The controller keeps only each trainable group's packed regions until its
   step: one GC-tracked object per group, not the per-turn object graph,
   which held for several steps made its full collections frequent and slow.
   It then sends each DP replica's leader (pipeline stage 0, CP and TP rank 0)
   its plan column and only the rollouts that column names
   (`Trainer.receive_replica_column`), under its own span and step timer
   (`timing/step/send_replica_columns`).
   `forward_backward` carries the group count and the global token counts.
4. On every trainer rank a `MicrobatchGroupReader` thread makes the step's
   microbatch groups up to two ahead of the one the engine waits on: the
   leader materializes and packs each group (`MicrobatchPacker.pack_planned`,
   which checks each sample's length and each microbatch's token counts
   against its specs) and broadcasts it, with its packing time, over a
   per-replica gloo group; the other ranks receive it; every rank
   preprocesses images. The replica groups come from the trainer's dense mesh
   (`build_dp_replica_group`). A leader that fails to pack broadcasts its
   error, so the replica fails instead of hanging. PP works from the start:
   every stage of a replica is in its group. The leader unpacks and materializes
   one rollout group at a time and drops its bytes once its samples exist, and
   drops each microbatch group's samples once it is packed.
5. Deleted: the RDMA microbatch path (`Batcher.Config.rdma_min_tensor_bytes`,
   `RDMAMicrobatch`, `RDMAMicrobatchPrefetcher`, `maybe_release_oldest_batch`,
   the trainer's RDMA identity check, the controller's RDMA warning and PP
   rejection), the now-unused tensor and dataclass paths of
   `MonarchRDMAObject` (it registers bytes only: prompt image files), and
   `share_image_data` (the packed group keeps one copy per image).

Cost: the leaders pack only once forward_backward starts. With
training.preprocess_microbatch_groups_lazily=False (the default), the engine
reads every microbatch group before its first forward, so the column send and
the leaders' materialize, pack and broadcast are on the step's critical path;
with it on, the first group still waits for the column's materialize. Sending
the columns during the previous step (a follow-up) hides them.

Unchanged: the plan (FFD/LPT/zig-zag), the packing, the samples and the
numerics; the push/pull ordering; #5862's image-file path.
@wwwjn
wwwjn force-pushed the wwwjn/data-plane/0-hop-metrics branch from b1791f5 to 6e267e1 Compare November 23, 2026 20:35
@wwwjn
wwwjn force-pushed the wwwjn/rl-rdma-object branch from d1a7e4d to a2b3e76 Compare November 23, 2026 20:35
@wwwjn
wwwjn added this pull request to stack #6343 November 23, 2026 21:31
@wwwjn wwwjn changed the title [rl] Time each data-plane hop and log its payload bytes [rl][metrics] Time each data-plane hop and log its payload bytes Nov 23, 2026
) -> tuple[RolloutGroup, float]:
"""Returns the group and the seconds this handler took; the caller subtracts them from
its wall time to get the hop's transfer time (see `compute_hop_metrics`)."""
start = time.perf_counter()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there alternative way of logging this time spend instead of changing the API? Structured logging our existing logger?

# We put a group in. We may get a batch back
# if there are enough accumulated trainable groups to return one.
with sl.log_trace_span("batcher_add_group"):
start = time.perf_counter()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We already have sl.log_trace_span("batcher_add_group"): why adding time logging again?

The next data-plane PRs change how rollout groups and microbatches move
between the controller, the rollout workers, the batcher and the trainer.
This logs per-hop timing and payload sizes on main's by-value path, so each
of them can be measured against it. Metrics only: numerics and behavior are
unchanged, and no endpoint changes its signature.

For each hop, the caller times each call from sending it to reading the
reply (call_duration). That is the callee's handler plus the transfer:
request and reply serialization, the transport, queueing at the endpoint,
and the wait for the caller's event loop to resume. The handler's time is a
span in the callee's structured log, so where the handler is long, the
transfer is call_duration minus that span. Each side measures a duration on
its own clock, so no clock sync is needed.

  hop                                   metrics (call_duration: mean and max)
  controller -> worker run_group        timing/hop/run_group/call_duration
                                        payload/rollout_group_array_bytes
                                        handler: the worker's run_group span (new)
  controller -> batcher add_group       timing/hop/add_group/call_duration
                                        handler: the batcher's training_sample_builder
                                        and batcher_pack spans (existing)
  controller -> trainer forward_backward
                                        timing/step/forward_backward (existing)
                                        payload/forward_backward_bytes_per_dp_rank
                                        handler: the trainer's forward_backward span
                                        (existing)

The add_group handler is short next to the call, so its call_duration is
mostly transfer and shows the controller's event-loop lag directly.

Where the metrics land:
- run_group: in the group's metrics, so they log with the step that trains
  the group. Controller._rollout_loop now extends group.metrics instead of
  overwriting it.
- add_group: each call's duration rides with the next batch the batcher
  returns.
- payload/rollout_group_array_bytes: nbytes of every numpy array field of
  each turn plus its image files. Not the pickled size: messages, metrics
  and logs are not counted. Iterating the fields keeps per-token arrays that
  features add (top-k logprobs for score centering, routed experts for
  router replay) in the count. add_group sends the same group.
- payload/forward_backward_bytes_per_dp_rank: tensor nbytes of each DP
  rank's column, computed by the batcher; by value only (RDMA microbatches
  stay in the batcher). With TP or CP, each column goes to every rank of
  the replica.

Not covered: the worker -> generator generate hop (follow-up).

Loss and grad norm are bitwise identical to main (10 steps,
rl_grpo_qwen3_0_6b_varlen_batch_invariant, seed 42).

Tests: the new metrics are present with fake endpoints (run_group,
add_group: both calls counted, not only the one that returned a batch), the
payload counts every array field, and the controller keeps the rollouter's
group metrics. They fail on main.
@wwwjn
wwwjn force-pushed the wwwjn/data-plane/0-hop-metrics branch from 6e267e1 to c51e747 Compare November 24, 2026 17:53
@wwwjn
wwwjn removed this pull request from stack #6343 November 24, 2026 20:05
@wwwjn wwwjn closed this Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant