Skip to content

[Fix] Use Ray reference counting for routed-expert lifetime - #2243

Closed
matrix72c wants to merge 47 commits into
InternLM:stack/rl-ppofrom
matrix72c:fix/routed-experts-reference-lifetime
Closed

matrix72c wants to merge 47 commits into
InternLM:stack/rl-ppofrom
matrix72c:fix/routed-experts-reference-lifetime

Conversation

@matrix72c

@matrix72c matrix72c commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #2186 (stack/rl-ppo), independently based on fixed snapshot a01303168cfc1a57863c0d85b10208a67ece8ff7.

Root Cause

Routed-expert Ray ObjectRefs are shared by partial rollouts, trace sessions, sibling samples, and repeated training passes. Explicitly freeing a shared object from one holder invalidates it for every other holder. The new stack makes TrainBatch own worker-local samples and materialization; it does not make trainer/trace-store force-free safe.

Fix

  • Retire routed-expert holders through Ray reference counting in reset/discard, partial concatenation, session release, and trainer cleanup.
  • Preserve TrainBatch release/materialization ownership; do not restore obsolete worker cache helpers.
  • Keep existing explicit pixel-payload cleanup unchanged.
  • Reject serialized ObjectRefs in vLLM HTTP responses, retaining array payload support: out-of-band serialized refs cannot use this reference-counted lifetime contract.

ProduceBatchResult impact: not affected; sample status, reward, and batch accounting are unchanged.

RoutedExperts impact: after transfer from LMDeploy, XTuner drops only each retiring holder; shared data remains readable until the final holder retires. This does not change pre-transfer LMDeploy cleanup.

Ray concurrency impact: existing RPC dispatch groups and scheduling are unchanged. No new concurrency lane or blocking actor RPC is added.

Test Plan — current head

  • 68 passed across routed lifetime, trace-store, TrainBatch lifecycle, partial rollout, prepare-train-data, and routed dtype regressions.
  • The 12 lifetime regressions include a real local Ray cluster, real TrainBatch materialization/repeated passes/release, competing consumers, final-reference retirement, and vLLM response handling.
  • Targeted Ruff checks and new-test formatting passed. pre-commit run --all-files was executed; mypy passed on 430 source files, but the overall run failed on existing autotest formatting/import-order violations. Unrelated formatter edits were not retained.
  • No GPU training, NCCL, or live inference-service verification on this head. This is a draft pending target-environment validation and clean CI.
  • No throughput benchmark: the change removes premature explicit frees and relies on Ray's existing ownership protocol. Local tests verify lifetime and final reclamation, not multi-node throughput or GPU memory peaks.

@jayhenry
jayhenry force-pushed the stack/rl-ppo branch 2 times, most recently from d42ce89 to a5842b5 Compare November 4, 2026 02:03
@matrix72c
matrix72c force-pushed the fix/routed-experts-reference-lifetime branch from 139519a to 76159e1 Compare November 4, 2026 02:55
@jayhenry
jayhenry force-pushed the stack/rl-ppo branch 2 times, most recently from 15dffbe to f020c41 Compare November 4, 2026 06:46
YanhuiDua and others added 24 commits November 4, 2026 13:34
…troller

- AgentLoop.canonicalize_train_fields (base + localhost/sandbox overrides)
  builds the unified full-sequence train fields (input_ids/labels/logprobs)
  at generation time; semantic holes are baked into labels by the loops.
- RolloutState drops response_mask; labels become the only supervision
  carrier. agent_loop_type records the producing loop class name and
  AGENTIC_AGENT_LOOP_TYPES discriminates agentic full-sequence samples.
- TrainingController.fit accepts list[list[RolloutState]] and absorbs
  validation, session-clustered advantages, shift/tensorization, seq_ctx,
  teacher fields and data_info; BaseRLTrainer._prepare_train_data is gone.
- calculate_group_effective_response_masks now bakes token staleness into
  labels in place (monotone, convergent) and its agentic exclusion uses
  agent_loop_type instead of the input_ids/labels presence heuristic.
…ut conversion

- response_ids now denotes the contiguous suffix of input_ids after the
  prompt (env/tool tokens included) in every loop; localhost/sandbox
  export input_ids[len(prompt_ids):] so response_model_steps stay aligned
  with the full response region.
- Token staleness baking becomes branch-free: effective mask = semantic
  mask (labels != -100 on the suffix) * per-token staleness mask; the
  zero-prompt suffix state becomes eligible and agent_loop_type plus
  AGENTIC_AGENT_LOOP_TYPES are removed.
- data_info stats: prompt_len reports the original prompt length and
  response_len the supervised (LLM-generated) token count; env/tool
  injected tokens count in neither.
- _rollout_groups_to_colate_items is phase-split into session reward
  clustering, group advantage estimation, per-state ColateItem conversion
  and data_info summarization.
RolloutState now publishes, masks, resets and validates its own training
fields and a frozen TrainMeta summary. AgentLoop, produce_utils,
ReplayBuffer and rollout workers call the state methods instead of
manually syncing labels and metadata.
Trajectory logging consumes RolloutState.train_meta; the legacy extra_fields
key remains only as a fallback for recovered/debug states. Covers the state's
Ray round-trip so metadata and methods survive transport.
Pad real and empty loss packs consistently, preserve singleton routed-expert
structure, and align shuffled indices with their token lengths.

Validate canonical training fields and replay token versions before use,
refresh supervised token metadata after staleness masking, and separate
packing layouts from advantage payload assembly.

Add regression coverage and update fixtures to the canonical contracts.
… scope

TrainBatch now owns the one-time shift, CPU samples, pack materialization,
row unpacking and advantage installation. PackPlan makes the controller-side
plan index-only, the controller loads/releases one local batch per worker,
and RLTrainer releases the consumed batch's trace sessions plus remaining
routed/pixel refs instead of freeing them inside the worker.
Move the LPT index planner into S2's RLDataPacker (it is an index-only
strategy, not PPO-specific) and split multimodal ref resolution from the
pack-level resolver so roles can reuse it. iter_cpu_packs accepts any pack
index sequence.
PengchengShi00 and others added 21 commits November 4, 2026 15:35
…step

CE, critic, log-prob and MTP builders now accept complete samples, compute
full-sample weights and only then pad/split to the local sequence-parallel
shard. build_batches performs denominator calibration only. The critic build
also owns target-shape validation and supervision weights, and the strict
checkpoint load and value-head initialization share one global-key decision.

Adds an SP parity test that checks the actor PPO loss and critic value loss,
their head gradients and one optimizer update against the SP=1 reference.
The loss context accepts one pack's frozen local labels, old/ref logprobs, IS
weights and teacher targets through a structural snapshot contract and only
moves them to the context device, never splitting again.
compute_rollout_is replaced ignored positions in the caller's tensor. It now
installs a new masked label tensor, so the complete source data handed to the
builder is never mutated.
Squashed original PPO implementation: role-first Actor/Critic workers,
controller-side value collection and advantage dispatch, segment/session
GAE, residencies, critic multi-pass updates and PPO recipes.
First refactor round: controller builds an index-only PackPlan, loads/releases
one local batch per worker and reads RolloutState.train_meta; workers receive
RankPlan, RLTrainer releases consumed trace/routed/pixel refs, and GAE modes no
longer precompute group advantages. Includes the design note and pseudocode.
Second refactor round:
- TokenAdvantageEstimator is a parallel interface; session targets use
  TrainMeta segment order and full CPU rows; TokenStats standardises the
  normalized action-token logging.
- TrainBatch gains old-value/PPO-target installation and trajectory export;
  the worker holds the only batch and roles receive it by argument.
- Roles track their own placement; set_residency replaces the role shadow
  and the prefetch thread is replaced by iter_cpu_packs.
- Actor freezes per-pack ActorSnapshot records and binds them through the
  loss context; critic collects SP-local values and installs complete
  segment targets; critic passes always honour num_passes.
- step_optimizer reports whether an update applied; role checkpoints store
  counters, scheduler definition and per-rank RNG.
Retire routed-reference holders without forcing shared Ray objects free; preserve pixel cleanup and reject out-of-band serialized vLLM ObjectRefs. Exercise actual TrainBatch materialization and release across remote consumers, repeated passes and final holder retirement.
@matrix72c
matrix72c force-pushed the fix/routed-experts-reference-lifetime branch from 76159e1 to ee41379 Compare November 5, 2026 01:33
@matrix72c
matrix72c marked this pull request as draft November 5, 2026 01:34
@jayhenry
jayhenry deleted the branch InternLM:stack/rl-ppo November 6, 2026 04:03
@jayhenry jayhenry closed this Nov 6, 2026
@matrix72c

Copy link
Copy Markdown
Contributor Author

Replaced by #2263, independently based on main after the PPO merge. The shared-reference lifetime fix remains necessary. GitHub rejected retargeting this closed PR after its base branch was deleted. The replacement remains draft with current local-Ray regressions and GPU/CI limitations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants