Skip to content

feat(forest): add terminal fallback and physical row limits - #5167

Merged
yuki-97 merged 69 commits into
mainfrom
biguo/forest-ppo-terminal-rows
Dec 4, 2026
Merged

yuki-97 merged 69 commits into
mainfrom
biguo/forest-ppo-terminal-rows

Conversation

@bg51717

@bg51717 bg51717 commented Nov 11, 2026 •

Copy link
Copy Markdown
Member
  • I, the PR author, have personally reviewed every line of this PR.

What and why

Previously, all_captured raised ValueError when the scored call could not be attributed. Forest receipts also labelled selected terminals as declared, and physical rows had no per-rollout limit.

This PR:

  • Falls back to Gym’s parent-link heuristic when direct attribution fails. An unverified declared terminal never falls back; unresolved rollouts are masked.
  • Records the actual terminal attribution method.
  • Adds token_capture.forest.max_rows_per_rollout. When capped, retain a row containing the scored call, then fill the remaining slots in planning order. The default null keeps all rows.
  • Preserves token checks on dropped rows when penalty_scope: all_segments applies.
  • Preserves the cap through checkpoint recovery; older checkpoints restore uncapped.

Extracted from #5126 and adapted from Jiaqi Zeng’s SWE PPO work (fab3ba82d). The optional continued_chains policy remains in #5126.

token_capture:
  forest:
    enabled: true
    selection_policy: all_captured
    max_rows_per_rollout: 16  # null keeps all rows

Issues

N/A: split from #5126.

Convergence / perf / functionality proof

Real-model validation: Qwen3-0.6B Forest PPO on 8 GB200 GPUs.

  • The default returned_history nightly passed training, checkpoint recovery, and metric checks over steps 1–4.
  • An 8-step real-task run with all_captured and max_rows_per_rollout=1 passed and exercised row capping in 5 steps. All terminals matched by response ID.
  • Added a corresponding real-task capped nightly. Deterministic unit tests cover terminal fallback together with row capping and scored-row retention.

These model runs used test commit 52f1fe6125, not the latest merged head. The new capped nightly driver has not yet been rerun end-to-end on the latest head.

Matched-step comparison of the default path, previous → tested run:

Metric Step 1 Step 2 Step 3 Step 4
Critic loss 0.42346 → 0.45338 0.40697 → 0.40053 0.35781 → 0.35901 0.27874 → 0.27367
Policy loss Critic-only warmup -0.01798 → -0.01811 -0.02386 → -0.01976 -0.01552 → -0.01606
Reward 0 → 0 0 → 0 0.25 → 0.25 0 → 0
Token probability ratio error Critic-only warmup 1.02265 → 1.02461 1.02398 → 1.02443 1.02149 → 1.01759

This is a short training sanity comparison, not long-run convergence evidence or a controlled measurement of this PR’s effect. The previous run (387b25e218) predates recipe penalty changes and intervening code changes.

Local regression after merging main:

  • Broad regression at 06f7cd8f0: 4,305 default tests passed; Gym had 967 passed, 7 skipped, and 3 legacy-checkpoint fixture failures.
  • After correcting those fixtures, targeted regression at 8f44f97b8 passed: 219 default tests and 265 Gym/Forest tests, including all three previously failing cases.
  • Pre-commit, including pyrefly, passed.

Needs upstream changes

None.

bg51717 and others added 27 commits November 3, 2026 07:13
Forest training was GRPO-only. A PPO run now runs GAE on every physical
row with that row's own critic values; the logical owner still decides
validity, so a filtered segment masks all of its owner's rows.

- ppo.adv_estimator.normalize_over: kept_rows (default) or all_rows,
  which also whitens over rows masked from the loss. Execution padding
  never counts.
- The critic takes every Forest row as one optimizer step.
- Forest row padding covers the critic's DP and microbatch sizes too.
- The complete-group check now runs on the PPO path as well.
- Forest requires ppo.value_training_mode=whole_batch: its row padding
  covers the whole step, while split mode shards each chunk on its own.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: bg51717 <[email protected]>
…tics

Execution padding and failed owners' borrowed inputs run through the
model, so with expert-bias updates enabled their tokens count toward the
router's expert loads. Forest keeps counting them by default, as
ordinary training does.

token_capture.exclude_padding_from_router_stats opts into masking them.
The finalizer publishes router_excluded_rows for Forest rows; the policy
and a PPO critic then fetch it, and the Megatron microbatch builder
gives those rows no router-visible tokens in the existing padding mask,
packed or not. The critic also masks sequence-packing padding.

Both workers check the mask only with the option on, and raise an error
naming it when the model cannot honour it, such as an expert-bias MoE
with HybridBlock chunkwise context parallelism.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: bg51717 <[email protected]>
Forest pads every published group to the policy and critic row multiple.
With one rollout per group, most rows a step trains on are then padding:
a DP of 4 turns ~154 real rows into ~512.

token_capture.forest_padding_scope: step pads each training batch once
instead. Pad rows copy real rows under new sample IDs with no loss,
borrowed-input tags, and router exclusion flags;
token_capture.forest_pad_source picks row0 or cyclic copies.
ppo.adv_estimator.whiten_execution_padding lets those copies join
all_rows whitening. Defaults are unchanged.

A rollout snapshot taken during a step accepts that step's padding copies
(<sample_id>_padN) of replayed rows, and restore deletes them before
checking the replay inventory. Full trainer checkpoints run after the step
clears its padding and stay strict.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: bg51717 <[email protected]>
SingleController PPO rejects a rollout-failure drop budget because the
critic expected a full step. A Forest critic trains on the step's actual
rows, so a short step fits and Forest PPO now accepts the budget.

Streaming PPO selects chunks in multiples of whole prompt groups so the
rows split evenly across the policy and critic data-parallel ranks.
Forest groups vary in row count and execution padding already aligns each
chunk to both models, so that alignment only held back ready groups,
rejected some num_prompts_per_step values, and made the sampler raise once
a dropped rollout shrank the step. Forest streaming PPO now selects any
group count, as streaming GRPO does. With forest_padding_scope=step, each
chunk is padded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: bg51717 <[email protected]>
Unit tests, as PPO counterparts of the Forest GRPO tests:
- Full-batch PPO trains every segment row per epoch and the critic takes
  the step's rows (gbs = rows); streaming PPO steps the policy once and
  trains the critic on all chunks after the refit.
- Invalid logical batches and all-invalid owners never train either model;
  a partial step trains the critic on the surviving rows.
- Whole-owner overlong filtering; the GAE advantage stage is never sharded.
- Forest PPO startup rejections, policy/critic padding validation order,
  checkpoint restore with a critic, the critic row multiple pinned in
  data-plane checkpoints, and value-loss equivalence across packing bins
  and segments.

Functional tests, both in L1_Functional_Tests_SingleController_3:
- ppo_async_gym_single_controller_context_compaction.sh: PPO (GAE,
  Megatron critic) on the context-compaction Forest rows, two steps with
  checkpoints, then a resume to step 4. Its config,
  examples/nemo_gym/ppo_qwen3_0_6b_single_controller.yaml, composes the PPO
  SingleController exemplar with the Gym GRPO config.
- grpo_async_gym_single_controller_context_compaction_resume.sh: the same
  checkpoint/resume for Forest GRPO.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: bg51717 <[email protected]>
Forest training rejected reward penalties. They now run on Forest
owners: rollout-scoped text checks and token checks run once on the
scored segment, and the owner's rows share the resulting reward.

token_capture.forest_penalty_scope chooses which segments the token
checks cover: scored_segment (default) or all_segments, where a hit in
any segment zeroes the owner's reward. Penalty counts ride the scored
row so the finalizer metrics count each owner once.

Forest results keep scalar fields only, so the duplicated-reasoning and
empty-final-answer checks run on the agent's scored response when Gym
post-processes the receipt, and are passed to compute_reward_checks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: bg51717 <[email protected]>
whiten_execution_padding only changes whitening under Forest step padding,
normalize_over=all_rows only with normalize_advantages=true, and the legacy
PPO entrypoint reads neither. Reject each of these at startup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: bg51717 <[email protected]>
…on note

PPO advantages are per physical row, each row a GAE episode, and Forest PPO
needs whole_batch critic training. Restore the truncation and
unsupported-features paragraph, which also applies to PPO overlong filtering.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: bg51717 <[email protected]>
…ler exemplars

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: bg51717 <[email protected]>
…sets

The critic's method also sets its router padding-mask flag, so call it
configure_forest_router_padding; setup calls the policy's check and the
critic's setup by their own names.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: bg51717 <[email protected]>
…loss

With every microbatch size 1 the run never padded. A critic microbatch of 2
and step-scope padding pad steps with an odd row count, in the checkpointed
run and the resumed one. The critic-loss check gets an upper bound.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: bg51717 <[email protected]>
Full-batch and streaming PPO: the padding copies reach the policy and the
critic, the critic gbs counts them, and the step deletes them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: bg51717 <[email protected]>
Main moved rollout checkpointing into nemo_rl/algorithms/rollout_checkpointing
(#5011). Step padding handling of the replay inventory check now lives in
rollout_checkpointing.inventory.validate_replay_inventory, called from the
restorer ("clear") and the snapshotter ("allow"). Forest's estimator check
keeps main's new seq_logprob_error_in_loss rejection.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: bg51717 <[email protected]>
The stage zeroed advantages outside the mask by multiplying with it, so a
dataset loss weight of 0.5 scaled the stored advantage again on top of GAE
and the loss. Zero the tokens outside the mask without rescaling the rest.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: bg51717 <[email protected]>
The inventory exception for forest_padding_scope=step also applied to full
trainer checkpoints, so an extra _pad row passed the save check and restore
deleted it. A full checkpoint never owns a streamed step's rows, so gate the
exception on a rollout snapshot on save and from_rollout_snapshot on restore.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: bg51717 <[email protected]>
raw_reward reads neither normalize_over nor whiten_execution_padding, so
setting them promised a whitening change that never happened. Fail at
config validation instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: bg51717 <[email protected]>
The PPO exemplar and three guide summaries said every logical rollout keeps
one advantage, which only holds for GRPO.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: bg51717 <[email protected]>
…uo/forest-ppo-penalty

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: bg51717 <[email protected]>
- List token_capture.forest_penalty_scope in the single-controller exemplars.
- Say text penalties read the scored response, not a segment.
- Set scored_text_checks on both receipt paths and index it, so a missing
  key fails instead of silently recomputing.
- Cover penalize_malformed_think_tag at Forest startup and pin
  once-per-owner penalty counts when two segments hit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: bg51717 <[email protected]>
Add the continued_chains selection policy, which trains the scored chain and
one continued chain per other root (for example, subagents), and
token_capture.max_rows_per_rollout, which keeps the scored root plus the first
N-1 other roots.

Both non-default policies now name the scored call through
resolve_scored_terminal: a witness first, else the parent-link heuristic. A
rollout neither stage resolves, or whose declared terminal no witness confirms,
is masked instead of failing the run. Receipts record the stage that named the
scored call.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: bg51717 <[email protected]>
- Fail loudly on a Gym attribution method the receipt table does not know.
- Clear terminal_model_call_id when the scored terminal is not identified.
- Share LENGTH_FINISH_REASONS across call_selection.py and nemo_gym.py.
- Require selection_policy=continued_chains for max_rows_per_rollout.
- Test the row cap through the env, with admission order and a failed side call.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: bg51717 <[email protected]>
@bg51717 bg51717 added the CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) label Nov 11, 2026
@copy-pr-bot

copy-pr-bot Bot commented Nov 11, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@github-actions github-actions Bot added the Documentation Improvements or additions to documentation label Nov 11, 2026
bg51717 added a commit that referenced this pull request Dec 1, 2026
token_capture.forest.owner_failure_scope: row masks a failed segment alone
unless it holds the scored call; sequence-logprob and overlong filtering then
mask each failing row alone. token_capture.forest.mask_retried_roots masks an
uncontinued root whose prompt also started a continued root (a retried first
request). Both default to the current behaviour. A dropped row that fails
verification under #5167's cap check still masks the owner.

Signed-off-by: bg51717 <[email protected]>
… the code does

The scored segment is token-checked up to the scored call under both penalty
scopes; all_segments also checks every other segment in full. Name the new
key for each moved Forest key, call all_captured a selection_policy value,
and use token_capture.forest.enabled in the two replay-buffer errors about
the current run.

Signed-off-by: bg51717 <[email protected]>
…l-rows

main's #4968 took rollout recovery schema 9 for failure_kind, so the
Forest selection's max_rows_per_rollout moves to schema 10; ledgers before
10 load uncapped.

Signed-off-by: bg51717 <[email protected]>
…e check

main's privileged-value validation still read the old
token_capture.forest_training key, which no longer exists.

Signed-off-by: bg51717 <[email protected]>
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the proof:perf Needs performance proof. Set by Autobot PR classify (skills/pr-classify) label Dec 1, 2026
@bg51717

bg51717 commented Dec 2, 2026

Copy link
Copy Markdown
Member Author

/ok to test e3316b2

Base automatically changed from biguo/forest-ppo-penalty to main December 2, 2026 16:09
…inal-rows

Signed-off-by: bg51717 <[email protected]>

# Conflicts:
#	docs/guides/context-compaction.md
#	docs/guides/grpo.md
#	examples/configs/grpo_math_1B_megatron_single_controller.yaml
#	examples/configs/ppo_math_1B_megatron_single_controller.yaml
#	nemo_rl/algorithms/rollout_checkpointing/restore.py
#	nemo_rl/algorithms/rollout_checkpointing/snapshots.py
#	nemo_rl/algorithms/single_controller_utils/config.py
#	nemo_rl/algorithms/single_controller_utils/setup.py
#	nemo_rl/environments/nemo_gym.py
#	nemo_rl/experience/rollout_reassembler.py
#	tests/unit/environments/test_nemo_gym_episode_collection.py
#	tests/unit/environments/test_nemo_gym_utils.py
#	tests/unit/experience/test_selected_forest_boundaries.py
#	tests/unit/single_controller/test_checkpoint_borrow_restore.py
#	tests/unit/single_controller/test_checkpointing.py
#	tests/unit/single_controller/test_ppo_setup.py
#	tests/unit/single_controller/test_setup.py
@bg51717

bg51717 commented Dec 3, 2026

Copy link
Copy Markdown
Member Author

/ok to test 15b08ea

@yuki-97 yuki-97 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.

Thanks for adding terminal fallback and a per-rollout training-row limit to Forest.

Scope: The full PR at 15b08ea, including Gym attribution, Forest row selection and checkpoint recovery.

Checked:

  • The cap keeps the first row containing the scored call and preserves the order of retained rows.
  • With an all_segments token penalty, dropped rows are still checked and a failed check masks the rollout.
  • Older checkpoints restore without a row cap.

Remaining comments:

  • Compare returned_history convergence and add all_captured nightly coverage for terminal fallback and the row cap.
  • Remove the redundant attribution-method mapping.
  • Correct the terminal-selection guide and PR description.

nit

  • Make dropped_segments required.
  • Simplify the Forest guard and terminal-failure handler.
  • Remove duplicate row-cap validation.

nemo-rl-review: kind=expert harness=codex/0.173.0 model=gpt-6.2-astra effort=medium review-pr-team=v3 reviewed=15b08ea

Comment thread nemo_rl/environments/call_selection.py Resolved
Comment thread docs/guides/context-compaction.md Resolved
Comment thread nemo_rl/environments/nemo_gym.py Resolved
Comment thread nemo_rl/environments/call_selection.py Resolved
@bg51717

bg51717 commented Dec 4, 2026

Copy link
Copy Markdown
Member Author

/ok to test 5499d5d

@bg51717

bg51717 commented Dec 4, 2026

Copy link
Copy Markdown
Member Author

/ok to test 8f44f97

@yuki-97
yuki-97 enabled auto-merge (squash) December 4, 2026 07:27
@yuki-97
yuki-97 merged commit fee09e7 into main Dec 4, 2026
177 of 198 checks passed
@yuki-97
yuki-97 deleted the biguo/forest-ppo-terminal-rows branch December 4, 2026 07:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) complexity:high Large or cross-cutting change. Set by Autobot PR classify (skills/pr-classify) convergence-risk:high Likely to change training results. Set by Autobot PR classify (skills/pr-classify) proof:convergence Needs convergence proof (W&B runs). Set by Autobot PR classify (skills/pr-classify) proof:functionality Needs proof that it works. Set by Autobot PR classify (skills/pr-classify) proof:perf Needs performance proof. Set by Autobot PR classify (skills/pr-classify)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants