Compare commits

...
Author SHA1 Message Date
Mika SenghaasandGitHub 421198cb93 feat: constant trainer batch size (#3463) 2026-09-01 20:22:40 -07:00
8 changed files with 83 additions and 8 deletions
+4 -2
View File
@@ -413,7 +413,9 @@ demo_key = "demonstration"
Scoring runs before curriculum admission, so a rollout that is later rejected still costs its reference compute.
By default, zero-advantage RL tokens are removed after a complete batch cohort has been collected and before its payload is packed for the trainer. This does not backfill the batch. Samples that still carry CE or reference-KL components are retained, while pure zero-advantage RL samples are not shipped. Removing an RL token also removes its trainer/inference mismatch-KL contribution. Set `orchestrator.train.filter_zero_advantages = false` to retain them.
The orchestrator filters samples with no training signal. This includes samples with zero advantage on all RL tokens. Samples that still carry CE or reference-KL components are retained. Filtering an RL token also removes its trainer/inference mismatch-KL contribution.
`orchestrator.constant_trainer_batch_size` defaults to `true`. The orchestrator filters samples before they count toward the batch target. It collects replacements, so rollout-based batches contain `orchestrator.batch_size` training traces. Set the option to `false` to filter after collection without replacement. This setting can improve orchestrator throughput, but it produces smaller trainer batches.
## Curricula
@@ -425,7 +427,7 @@ Three small implementations are included:
- `StandardSampler` is the default: it advances the task iterator and cycles finite tasksets in source order.
- `DifficultyPoolSampler` samples finite tasksets with replacement and tracks each task's latest valid mean group reward. Each named pool has an inclusive reward threshold and a relative per-task sampling weight; weight `0` disables sampling from that pool. Unseen tasks use neutral weight `1.0`, so pool observations affect sampling immediately without waiting for a full taskset pass.
- `AdvRangeGate` rejects a group when every trainable-token advantage falls inside `reject_min` through `reject_max`. Unlike the built-in post-batch zero-advantage filtering, rejection requests replacement work. Groups without an advantage stream are admitted.
- `AdvRangeGate` rejects a group when every trainable-token advantage falls inside `reject_min` through `reject_max`. Unlike the built-in token filter, it can reject a configurable advantage range. Groups without an advantage stream are admitted.
```toml
[orchestrator.train.source.curriculum.sampler]
+4 -1
View File
@@ -58,6 +58,7 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
| Knob | What it does |
|---|---|
| `orchestrator.batch_size` | Tasks per trainer step. |
| `orchestrator.constant_trainer_batch_size` | Keep trainer batches constant when samples have no training signal, such as zero advantage on all tokens. Enabled by default. Disable it for faster collection with variable trainer batch sizes. |
| `orchestrator.group_size` | Rollouts generated per task. |
| `orchestrator.max_off_policy_steps` | Maximum staleness of a trained rollout (default 8): the version a batch trains on minus the oldest version that generated the rollout, queue time included. Episodes past the bound are dropped; a group shares one dispatch version, so its episodes age out together. The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `off_policy/*` and `mismatch_kl/all/mean` when tuning. |
| `[orchestrator.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `rae`, `hierarchical_grpo`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
@@ -133,7 +134,9 @@ Pulled from the console logs and mirrored to W&B.
| Source | Metric | Reading |
|---|---|---|
| trainer | `time/wait_for_batch` | **high → orchestrator bottleneck** |
| orchestrator | `time/wait_for_ckpt` | **high → trainer bottleneck** |
| orchestrator | `time/wait_for_policy` | **high → trainer bottleneck** |
The trainer warns when batch wait time exceeds active trainer time. Add inference nodes when this warning persists. The orchestrator warns when policy wait time exceeds active orchestrator time. Add trainer nodes when this warning persists. The orchestrator also warns when it discards more than half of an episode window. This warning reports stale, errored, and no-signal counts.
## SFT Trainer
@@ -304,9 +304,6 @@ class TrainConfig(BaseConfig):
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Shared training sampling configuration."""
filter_zero_advantages: bool = True
"""Remove zero-advantage RL tokens after collecting a batch, before shipping it."""
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling (the worker ``pool``
@@ -554,6 +551,9 @@ class OrchestratorConfig(BaseConfig):
batch_size: int | None = Field(None, ge=1)
"""Samples to train on per step (rollout-based batching). Set this OR ``token_batch_size``."""
constant_trainer_batch_size: bool = True
"""Require each batch to reach its effective sample target."""
token_batch_size: int | None = Field(None, ge=1)
"""Tokens to train on per step (token-based batching). Set this OR ``batch_size``."""
+4
View File
@@ -152,6 +152,10 @@ All metrics print to the console log (and W&B when configured).
| orchestrator | `off_policy/{mean,max}`, `off_policy/{in_flight,in_queue}/{mean,max}`, `off_policy/dropped` | per-step staleness of trained rollouts |
| env server | event loop lag (min/mean/p90/p99/max), active task distribution | periodic |
The trainer warns when batch wait time exceeds active trainer time. Add inference nodes when this warning persists. The orchestrator warns when policy wait time exceeds active orchestrator time. Add trainer nodes when this warning persists. The orchestrator also warns when it discards more than half of an episode window and reports stale, errored, and no-signal counts.
`orchestrator.constant_trainer_batch_size` defaults to `true`. It keeps each rollout batch at `orchestrator.batch_size` effective episodes. Set it to `false` for faster collection with variable trainer batch sizes.
For live vLLM stats, query Prometheus directly:
```bash
+32
View File
@@ -735,6 +735,38 @@ class Orchestrator:
metrics[f"batch/{env_name}"] = env_pool.num_traces / batch.episodes.num_traces
metrics |= self.train_source.metrics()
await monitors.log(metrics, step=step)
active_step_time = max(step_time - self.wait_for_policy_time, 0.0)
if step_time > 0 and self.wait_for_policy_time >= active_step_time:
get_logger().warning(
f"Orchestrator waited {format_time(self.wait_for_policy_time)} for policy updates, at least as long "
f"as its {format_time(active_step_time)} active step time. Train-inference compute is imbalanced; "
"add more trainer nodes."
)
shipped_episode_ids = {episode.id for episode in batch.cohort}
discarded_episodes = [
episode
for episode in batch.episodes
if episode.id not in shipped_episode_ids and episode.id not in batch.buffered_episode_ids
]
stale_episodes = sum(episode.id in batch.episodes.cancelled for episode in discarded_episodes)
errored_episodes = sum(
episode.id not in batch.episodes.cancelled
and (not episode.ok or any(trace.has_error for trace in episode.traces))
for episode in discarded_episodes
)
num_attempts = len(batch.episodes) + len(batch.failures) + batch.cancelled_attempts
num_discarded = len(discarded_episodes) + len(batch.failures) + batch.cancelled_attempts
num_stale = stale_episodes + batch.stale_attempts
num_errored = errored_episodes + len(batch.failures)
num_no_signal = num_discarded - num_stale - num_errored
if num_attempts and num_discarded / num_attempts > 0.5:
get_logger().warning(
f"Discarded {num_discarded}/{num_attempts} episodes ({num_discarded / num_attempts:.1%}): "
f"stale={num_stale}, errored={num_errored}, no_signal={num_no_signal}. Review max_off_policy_steps, "
"episode errors, and reward signal."
)
self.wait_for_policy_time = 0.0
if self.heart is not None:
+23 -2
View File
@@ -88,6 +88,8 @@ class TrainSink:
self.pending_episodes = TrainEpisodes()
self.pending_failures: list[DispatchFailure] = []
self.pending_cancelled_attempts = 0
self.pending_stale_attempts = 0
self.pending_groups: dict[str, list[vf.Episode]] = defaultdict(list)
self.pending_group_failures: dict[str, list[DispatchFailure]] = defaultdict(list)
# A dropped group's terminal marker; its ``count`` fills in for the
@@ -243,6 +245,10 @@ class TrainSink:
)
n_owed = len(group) + len(failures) + (cancellation.count if cancellation is not None else 0)
self.pending_failures.extend(failures)
if cancellation is not None:
self.pending_cancelled_attempts += cancellation.count
if cancellation.reason == "stale":
self.pending_stale_attempts += cancellation.count
# A stale drop voids the whole group: every member shares the dispatch
# version, so the arrived episodes are exactly as stale as the
@@ -287,6 +293,8 @@ class TrainSink:
"it requires vLLM's native sampling-mask capture (>= 0.28)."
)
stamp_loss_routing(sample, env.algorithm.action_loss_type)
if self.config.constant_trainer_batch_size:
samples = [sample for sample in samples if _prune_zero_advantages(sample)]
if samples:
samples_by_trace[trace.id] = samples
@@ -375,7 +383,7 @@ class TrainSink:
for trace_id in selected_ids:
del self.pending_batch[trace_id]
if self.config.train.filter_zero_advantages:
if not self.config.constant_trainer_batch_size:
selected_by_trace = {
trace_id: [sample for sample in samples if _prune_zero_advantages(sample)]
for trace_id, samples in selected
@@ -384,6 +392,7 @@ class TrainSink:
samples = [sample for trace_samples in selected_by_trace.values() for sample in trace_samples]
shipped_ids = set(selected_by_trace)
buffered_episode_ids = {self.episode_by_trace[trace_id].id for trace_id in self.pending_batch}
traces_by_episode: dict[int, list[vf.Trace]] = defaultdict(list)
selected_episodes: dict[int, vf.Episode] = {}
for trace_id in selected_ids:
@@ -399,7 +408,19 @@ class TrainSink:
episodes = self.pending_episodes
failures = self.pending_failures
cancelled_attempts = self.pending_cancelled_attempts
stale_attempts = self.pending_stale_attempts
if samples:
self.pending_episodes = TrainEpisodes()
self.pending_failures = []
return TrainBatch(episodes=episodes, cohort=cohort, samples=samples, failures=failures)
self.pending_cancelled_attempts = 0
self.pending_stale_attempts = 0
return TrainBatch(
episodes=episodes,
cohort=cohort,
samples=samples,
failures=failures,
buffered_episode_ids=buffered_episode_ids,
cancelled_attempts=cancelled_attempts,
stale_attempts=stale_attempts,
)
+6
View File
@@ -124,6 +124,12 @@ class TrainBatch:
cohort: TrainEpisodes
samples: list[TrainingSample]
failures: list[DispatchFailure]
# Episodes with traces retained for a later batch are not discarded.
buffered_episode_ids: set[str]
# Group cancellations can account for attempts that returned no episode.
cancelled_attempts: int = 0
# Stale attempts are a subset of cancelled_attempts.
stale_attempts: int = 0
@dataclass
+7
View File
@@ -658,6 +658,13 @@ def train(config: TrainerConfig):
# Log step metrics
step_time = time.perf_counter() - step_start_time
active_step_time = step_time - wait_for_batch_time
if progress.step > start_step and wait_for_batch_time >= active_step_time:
logger.warning(
f"Trainer waited {format_time(wait_for_batch_time)} for a batch, at least as long as its "
f"{format_time(active_step_time)} active step time. Train-inference compute is imbalanced; "
"add more inference nodes."
)
step_message = f"Step {progress.step} | {format_time(step_time):>7} | Loss {tensor_stats['loss/mean']:.4f} | Entropy {tensor_stats['entropy/all/mean']:.4f}"
if "mismatch_kl/all/mean" in tensor_stats:
step_message += f" | Mismatch KL {tensor_stats['mismatch_kl/all/mean']:.4f}"