Compare commits

...
Author SHA1 Message Date
rasdaniandGitHub 845eb6e6f2 Scrub padded vLLM model inputs (#2506)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Scrub padded vLLM model inputs

* Fix padded input scrub vLLM wrapper

* Document vLLM patch removal points
2026-05-19 21:31:23 +02:00
eaf95997f7 feat: first-class sft+opd training modes (#2546)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: add student eval inference pool for SFT hard distillation

When teacher_rollout_model is configured for SFT distillation, the
orchestrator now supports a separate student inference pool for online
evals and weight sync. Previously, configuring [inference] alongside
teacher_rollout_model was forbidden — evals either ran on the teacher
or were skipped entirely.

Changes:
- Relax RLConfig validator to allow [inference] + teacher_rollout_model
- Create eval_inference_pool from config.client when teacher_rollout_model
  is set, pointing at the student vLLM server
- Route eval calls and weight updates to the student pool
- Add eval_inference_pool param to Scheduler for weight sync targeting
- All existing RL/soft-distill paths are unchanged (eval_inference_pool
  defaults to inference_pool when no teacher_rollout_model is configured)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: keep hard distill student eval pool optional

* fix: scope teacher rollout routing

* fix: address teacher rollout review comments

* fix: clarify teacher rollout client routing

* fix: honor teacher rollout client type

* refactor(orchestrator): rename model/teacher_model to student/teacher

Consolidates 3 training modes (rl, opd, sft) under a unified config
structure: `student` (always present) and `teacher` (optional, role
determined by `training_mode`). Removes scattered flags (`use_sft_loss`,
`update_student_inference_weights`) in favour of a single discriminator.

Backward-compat aliases (`model` → `student`, `teacher_model` → `teacher`)
keep existing TOML configs parsing without changes.

Also adds `configs/reverse_text/debug_{rl,opd,sft}.toml` for local
mode debugging.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(configs): cap reverse-text debug eval at 64 examples

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(configs): cap reverse-text debug eval completion tokens at 128

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(configs): use correct PI inference teacher model name

qwen/qwen3-4b-instruct doesn't exist on PI inference;
use Qwen/Qwen3-4B-Instruct-2507 instead.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(configs): use qwen3-30b-a3b-instruct as debug teacher model

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(configs): correct teacher model name to qwen3-30b-a3b-instruct-2507

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(client): add headers_from_env to ClientConfig

Maps header names to env var names, resolved at client setup time.
Analogous to api_key_var but for arbitrary headers. Useful for e.g.
X-Prime-Team-ID when hitting the PI inference API.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(client): auto-inject X-Prime-Team-ID header for PI inference

When ClientConfig.base_url targets pinference.ai, auto-add a
headers_from_env mapping for X-Prime-Team-ID -> PRIME_TEAM_ID so team
billing works without each config repeating the boilerplate.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(configs): set debug eval to 256 rollouts (64 examples x 4)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(configs): use local vLLM teacher for debug OPD instead of PI inference

PI inference is OpenAI-compatible but doesn't expose vLLM's
/inference/v1/generate prefill endpoint that compute_teacher_logprobs
needs - so OPD against PI inference 404s. SFT mode kept working
because that path only hits /chat/completions.

Switch debug_opd.toml to use the existing teacher_inference auto-setup:
set num_teacher_gpus = 1, and an empty [orchestrator.teacher] block to
satisfy the orchestrator validator (which runs before
auto_setup_teacher_inference can populate it). The validator chain
spins up a local vLLM teacher on port 8001 using the same reverse-text
student model.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs+validate: training modes grid + cross-config constraints

- Add docs/training_modes.md with the rl/opd/sft role grid, implications
  (e.g. OPD needs local vLLM teacher, SFT teacher is any OAI-compatible
  endpoint), and minimal config per mode. Linked from mint.json nav.
- Add validate_training_mode_loss_consistency on RLConfig enforcing:
  sft mode <-> sft loss type, opd mode requires teacher_tau > 0,
  non-sft modes forbid sft loss type. These cross orchestrator and
  trainer fields so they live on RLConfig (per-component validators in
  OrchestratorConfig already cover the within-orchestrator constraints).
- Fix debug_sft.toml to set trainer.loss.type = "sft" (was relying on
  default loss which is now explicitly rejected).
- Make training_mode explicit in debug_rl.toml and debug_opd.toml.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(configs): lift training_mode to RLConfig + point debug teacher at local vLLM

- Add shared training_mode field to RLConfig (rl | opd | sft). A mode="before"
  validator propagates it into orchestrator.training_mode and (for sft)
  trainer.loss.type before nested validation runs. Must be a before-validator
  because OrchestratorConfig.validate_training_mode would otherwise reject
  configs like training_mode = "opd" + [orchestrator.teacher] - the
  orchestrator-level default of "rl" would conflict with the teacher block
  before the after-validator could propagate the shared value.

- Point debug_opd and debug_sft at a manually-deployed teacher vLLM
  (Qwen3-0.6B-Reverse-Text-RL on localhost:8001). Add a comment with the
  exact teacher start command at the top of each config. Drop the
  num_teacher_gpus auto-launch from debug_opd since we now use the
  external teacher.

- Set student inference gpu_memory_utilization = 0.5 in all three debug
  configs (matches the teacher's mem budget, leaves room when both are
  co-located).

- Add configs/reverse_text/README.md with the start commands.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore: drop GPU-occupancy runtime check; teacher uses uv run inference

- Remove check_gpus_available in rl entrypoint - it raised RuntimeError
  when other processes held GPUs, which blocked iterating with a
  long-lived teacher inference server on a sibling GPU.
- Update debug_opd / debug_sft / README to start the teacher via
  uv run inference (the prime-rl variant) instead of raw vllm serve.
  Same port (8001), same model, same flags.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(configs): accept legacy flat [orchestrator.model.lora] layout

Pre-refactor, orchestrator.model was a ModelConfig directly (name, lora,
trust_remote_code, vlm). After the student/teacher rename it's a
RolloutModelConfig wrapping ModelConfig + ClientConfig, so existing
[orchestrator.model.lora] TOML sections stopped parsing because they
landed on the wrong nesting level.

Add a mode="before" validator on RolloutModelConfig that detects a flat
ModelConfig dict (any of {name, trust_remote_code, vlm, lora} at the top
level, no nested model/client keys) and re-nests it under "model". This
lets the three existing LoRA configs revert to their original syntax.

Also fix examples/alphabet_sort/sft_distill_hard.toml: hoist training_mode
to the top-level shared field so trainer.loss.type = "sft" gets auto-set
(previously the orchestrator-only flag triggered the new sft/loss
consistency validator).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(orchestrator): split into student_inference + teacher_inference pools

Replace the "one pool plus optional teacher-client overlay" model with two
explicit pools:

- student_inference: InferencePool | None
  - Required for rl/opd, optional for sft (set iff [inference] is configured)
  - Target for evals, weight broadcast, and inference metrics
  - When None, online evals and policy updates are skipped automatically
- teacher_inference: InferencePool | None
  - Set whenever orchestrator.teacher is configured (opd or sft)
  - Source of teacher logprobs in opd
  - Source of train rollouts in sft
  - Always MITO (chat completions) for simplicity; external OAI-compatible
    teachers (PI inference, OpenAI) work as drop-in endpoints

Scheduler now takes both pools and resolves the rollout target internally
(rollout_inference = teacher_inference if sft else student_inference).
The old _resolve_rollout_request_target overlay is gone - the rollout pool
serves rollouts directly. Fixes a latent bug where SFT-mode LoRA updates
would overwrite scheduler.model_name and route subsequent teacher requests
with the student's LoRA name.

Also:
- Drop setup_external_rollout_model (logic is now inline + clearer)
- Rename setup_rollout_inference_pool -> setup_student_inference_pool;
  always handles only the student pool, teacher is plain setup_inference_pool
- Log the resolved training_mode + one-line description at orchestrator start
- Update tests: cover both sft (rollout != student) and rl (rollout = student)
  LoRA paths; drop the now-obsolete teacher-overlay scheduler test

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs+configs: legacy [orchestrator.client] shim + merge OPD doc into training_modes

- Add _accept_top_level_client validator on OrchestratorConfig: legacy
  [orchestrator.client...] re-nests under [orchestrator.student.client...]
  matching the existing _accept_flat_model_layout shim pattern. Revert
  configs/elastic/rl.toml back to the original [orchestrator.client.elastic]
  syntax.
- Revert configs/ci/integration/reverse_text_multi_run/orchestrator.toml
  [model.model] -> [model]; the flat-layout shim on RolloutModelConfig
  already handles it (verified).
- Merge docs/on_policy_distillation.md into docs/training_modes.md. The
  training_modes page is now the single entry point; OPD-specific details
  (external teacher, pure distillation, monitoring, VLM, params) live as
  subsections. Delete the standalone OPD page.
- Drop the redundant "Initializing static inference pool" / WandbMonitor /
  PrimeMonitor init logs - they duplicate the immediately-preceding
  per-pool init line.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(orchestrator): probe teacher for prompt_logprobs before training

In OPD mode, send a tiny probe request to the teacher's /inference/v1/generate
endpoint after the pool is ready. If the endpoint 404s or doesn't return
prompt_logprobs, raise an informative error pointing at docs/training_modes.md
instead of crashing mid-training with a 404.

Verified that PI inference fails this probe on all three plausible routes:
- /inference/v1/generate -> 404
- /v1/chat/completions with logprobs=true -> logprobs:null in response
- /v1/completions with echo=true,logprobs=1 -> 404

Also add configs/reverse_text/debug_sft_thinking.toml: SFT from
qwen3-30b-a3b-thinking-2507 via PI inference (sft path needs only
chat completions, so PI inference is fine here).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(orchestrator): deprecate use_token_client (server-tokenized TITO)

Drop the server-tokenized TITO path (``openai_chat_completions_token`` /
``/v1/chat/completions/tokens``). The orchestrator now picks between
renderer-backed TITO (``use_renderer = true``, default) and MITO
(``use_renderer = false``, fallback for VLMs and external teacher rollouts).

- Remove ``OrchestratorConfig.use_token_client`` field and its validators
- Drop the TITO branch in ``setup_rollout_inference_pool``
- Drop the obsolete TITO warning in ``setup_inference_pool`` and flip the
  default ``train_client_type`` to ``openai_chat_completions`` in
  ``StaticInferencePool`` / ``ElasticInferencePool``
- Strip ``use_token_client = false`` from configs/examples/docs that
  carried the no-op fallback line
- CHANGELOG entry documenting the breaking removal

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(inference): remove server-side TITO route

Drop the ``/v1/chat/completions/tokens`` endpoint and the
``OpenAIServingChatWithTokens`` / ``ChatCompletionRequestWithTokens``
wrappers now that no client routes to them. Also drop the obsolete
``base()`` helper and unused imports from ``server.py``.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor: require student_inference in all training modes

Student inference was already required for rl/opd and optional for sft;
making it required everywhere simplifies the orchestrator + scheduler:

- Drop has_student_inference / enable_policy_updates gating
- student_inference: InferencePool (no longer Optional) in Scheduler.__init__
- Weight broadcast init, weight sync, metrics collector, eval routing, and
  shutdown all unconditionally use student_inference
- Drop the now-stale OPD probe (will revisit in a follow-up PR)
- Add is_vlm property on BaseModelConfig; replace local is_vlm vars in the
  orchestrator with config.student.model.is_vlm
- Merge the two legacy student-layout shims on OrchestratorConfig into one
  before-validator (_accept_legacy_student_layout) covering both
  [orchestrator.client.*] and flat [orchestrator.model.<k>] paths
- Drop redundant pool / WandbMonitor / PrimeMonitor init log lines
- Reorder OrchestratorConfig fields: training_mode > student > teacher
- Drop "OAI" from RolloutModelConfig.client description
- Update docs/training_modes.md: SFT student inference is now required;
  evals and weight sync are unconditional

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(configs): default OPD to pure distillation (teacher_tau=1, adv_tau=0)

auto_setup_training_mode now seeds trainer.loss defaults when training_mode
is opd: teacher_tau=1.0 and adv_tau=0.0 (pure distillation: drop the reward
signal, full weight on the teacher KL). User-provided values still win via
setdefault. Also accept training_mode set only inside [orchestrator] - same
auto-setup applies for both the shared top-level and orchestrator-local
forms.

Drop the redundant [trainer.loss] teacher_tau = 0.5 block from
configs/reverse_text/debug_opd.toml; verified the auto-setup applies
end-to-end (3 train steps, teacher logprobs computed each step, clean exit).

Also drop the now-redundant InferencePool type annotation on
self.rollout_inference - both branches assign a definite InferencePool now
that student_inference is non-Optional.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(configs): rename debug_sft_thinking -> debug_sft_external; drop examples/alphabet_sort/sft_distill_hard.toml

debug_sft_external describes the role better - external SFT teacher via
OAI-compatible endpoint (PI inference). The "thinking" label was about the
specific model the config picks (qwen3-30b-a3b-thinking-2507), not about
what the config demonstrates.

Drop examples/alphabet_sort/sft_distill_hard.toml: configs/reverse_text/
debug_sft* are the canonical SFT examples now.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(tests): unbreak CPU tests after student/teacher rename + headers_from_env

- tests/unit/train/test_runs.py: orchestrator config attribute access
  changed from config.model.name to config.student.model.name after the
  RolloutModelConfig rename.
- tests/unit/utils/test_elastic.py: MagicMock client_config needs
  headers_from_env set to {} - the field was added in this PR and the
  test's hand-built mock missed it (pydantic rejects MagicMock as a dict).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(orchestrator): strip logprobs from train sampling in sft mode

The trainer in sft mode reconstructs teacher tokens via the student
tokenizer - it never reads inference-side logprobs from the teacher
endpoint. Stripping logprobs at runtime lets external reasoning-model
endpoints (openai/gpt-5*, etc.) accept the rollout request - they
reject logprobs with 400 invalid_request "logprobs are not supported
with reasoning models".

Done at orchestrator-startup time on each TrainEnv's sampling_args
rather than as a public config field, since this is a mode-specific
runtime concern.

Also: bump configs/reverse_text/debug_sft_external.toml to use
openai/gpt-5-mini (faster than qwen3-30b-a3b-thinking-2507).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(configs): bump debug_sft_external for gpt-5-mini reasoning budget

gpt-5-mini's max_completion_tokens budget includes reasoning tokens.
At 128 the model burned the whole budget on internal CoT before
producing the final answer, returning empty content. Raise to 2048
and set reasoning_effort=minimal so the chat-completions response
includes the actual output.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: fix stale SFT references after the student/teacher refactor

- skills/config/SKILL.md: update the SFT hard distill section -
  orchestrator.teacher_model -> orchestrator.teacher, drop the
  "student inference is optional" guidance (the orchestrator now
  unconditionally sets up student_inference), and add a note that
  shared training_mode auto-propagates to trainer.loss.type.
- rl.py: auto_setup_inference_client docstring referenced the deleted
  setup_external_rollout_model function. Rewrite to explain what the
  validator actually does for each mode.

Also note the behavior change in the PR description: SFT now requires
[inference] (was previously optional).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(loss): batch-driven loss dispatch via TrainingSample.training_mode

Replace TrainingSample/MicroBatch.sft_loss bool with training_mode literal
(rl|opd|sft). The trainer's compute_loss reads training_mode from the
micro batch and dispatches:

- "sft"     -> sft_loss_fn (masked NLL on teacher tokens)
- "rl"      -> default_loss_fn with (adv_tau=1.0, teacher_tau=0.0)
- "opd"     -> default_loss_fn with (adv_tau=0.0, teacher_tau=1.0)

Taus move from trainer.loss config to compute_loss's mode->tau table and
flow into LossInputs per batch; DefaultLossConfig drops the teacher_tau /
adv_tau fields. The orchestrator stamps each sample with
config.training_mode at the same point it used to set sft_loss.

Packer enforces same-mode packing (samples with different training_mode
cannot share a micro batch). RLConfig drops the OPD tau auto-setup +
"opd requires teacher_tau > 0" validator + the validate_teacher_model
teacher_tau gate (all redundant under batch-driven dispatch).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(loss): dedicated opd_loss_fn instead of routing taus through inputs

Replace the per-batch adv_tau/teacher_tau routing through LossInputs with a
dedicated opd_loss_fn that lives alongside default_loss_fn and sft_loss_fn.
A bit of code dup in opd_loss_fn (clone of default's DPPO math) makes the
two paths read as separate losses rather than the same function with magic
multipliers.

- setup_loss_fn -> setup_loss_fns: returns a dict {training_mode: LossFn}.
  rl uses the configured loss (default/custom). opd uses opd_loss_fn (only
  available when loss_config is DefaultLossConfig). sft is always available.
- compute_loss takes loss_fns + training_mode, looks up the right fn.
- opd_loss_fn requires teacher_logprobs (raises otherwise).
- LossInputs no longer carries adv_tau/teacher_tau - those values are baked
  into each loss fn.
- Add validator: opd mode requires trainer.loss.type = "default".

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(loss): drop trainer.loss type discriminator + shared training_mode

Now that loss dispatch is fully batch-driven (TrainingSample.training_mode),
the trainer.loss type union and the shared RLConfig.training_mode propagator
are redundant. Flatten:

- Delete SFTLossConfig (the mode implies it; no fields).
- trainer.loss: DefaultLossConfig = DefaultLossConfig() (flat, not a union).
- trainer.custom_loss: CustomLossConfig | None = None - optional override
  for rl-mode loss only; opd and sft always use opd_loss_fn / sft_loss_fn.
- setup_loss_fns(loss_config, custom_loss) always returns all three keys -
  mixed-mode batches dispatch correctly at the trainer level (orchestrator
  still stamps a single mode per run; that's a separate concern).
- Drop RLConfig.training_mode shared field, the auto_setup_training_mode
  before-validator, and validate_training_mode_loss_consistency. The
  orchestrator-level [orchestrator] training_mode is the single source.

Move training_mode = "sft" out of top-level into [orchestrator] in the
three SFT debug configs.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(rl entrypoint): warn for missing [inference] in all modes (incl. sft)

After the always-require-student refactor, sft runs need a student
inference pool too (orchestrator unconditionally creates it for evals +
weight sync). The old "sft mode, using teacher for rollouts" info log
was correct under the old semantics but now silently puts the user on a
path where the orchestrator hangs waiting for a non-existent student
server at the default localhost:8000. Replace with a single warning
that prints the configured student base_url and flags the hang risk.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(loss): make opd_loss_fn's tau values explicit (adv_tau=0, teacher_tau=1)

Mirror default_loss_fn's structure literally: declare the two tau locals at
the top, then use them in the same `adv_tau * advantages + teacher_tau *
teacher_kl.detach()` expression. The "this is the default loss with those
specific knobs baked in" relationship is now visible in the code rather than
hidden in a substituted expression.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(loss): restore DefaultLossConfig.adv_tau + LossConfig union (rl-only)

- DefaultLossConfig regains adv_tau (= 1.0). default_loss_fn reads it.
- trainer.loss is back to a discriminated union of DefaultLossConfig |
  CustomLossConfig (drop SFTLossConfig stays dropped). type discriminator
  restored.
- trainer.loss only applies to rl-mode batches. opd and sft batches dispatch
  unconditionally to opd_loss_fn / sft_loss_fn - they don't read trainer.loss.
- opd_loss_fn is self-contained: the DPPO/KL knobs (dppo_mask_*, kl_tau)
  are baked in as module-level _OPD_* constants matching DefaultLossConfig's
  defaults. No loss_config parameter.
- Drop the trainer.custom_loss sibling field (subsumed by the union).

Also add debug_opd_lora.toml + bump lr to 1e-4 in both lora debug configs.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(loss): inline opd_loss_fn knobs (no named locals/constants)

Drop the module-level _OPD_* constants and the local adv_tau/teacher_tau
bindings - inline the literal values into the math. Keeps the parallel
structure to default_loss_fn visible: `0.0 * advantages + 1.0 * teacher_kl`
in the same place default_loss_fn has `loss_config.adv_tau * advantages`.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(loss): trim opd_loss_fn docstring

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: update reverse_text README — add lora configs

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* polish: auto-disable renderer in sft + CHANGELOG + log/shim cleanup

- OrchestratorConfig auto-sets use_renderer=False when training_mode='sft'
  via an after-validator placed before the renderer validators in
  declaration order, so the user doesn't have to set it. Drop the rejecting
  branch in validate_training_mode + the explicit use_renderer=false lines
  in the three sft debug configs.
- CHANGELOG: add a "first-class training_mode + batch-driven loss dispatch"
  entry covering the breaking removals (orchestrator.use_sft_loss,
  orchestrator.teacher_rollout_model, trainer.loss.type='sft' /
  SFTLossConfig, trainer.loss.teacher_tau) with migration notes.
- _accept_legacy_student_layout: use set(ModelConfig.model_fields) instead
  of hardcoding the field list, so new ModelConfig fields are picked up
  automatically.
- Trim the orchestrator startup log to just '(<training_mode>)'; the
  prose description was redundant with docs/training_modes.md.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(configs): unbreak OPD auto-wiring when num_teacher_gpus is set

Add a mode="before" validator on RLConfig that stubs an empty
[orchestrator.teacher] block when deployment.num_teacher_gpus is set and
the user didn't write one. Without this, OrchestratorConfig.validate_training_mode
("opd requires orchestrator.teacher") fires during nested validation - before
auto_setup_teacher_inference can wire the teacher from teacher_inference.

Repro that now passes:

  RLConfig.model_validate({
      "deployment": {"num_teacher_gpus": 1},
      "trainer": {},
      "orchestrator": {"training_mode": "opd"},
      "inference": {},
  })

-> auto_setup_teacher_inference fills in orchestrator.teacher.client.base_url
   = ["http://localhost:8001/v1"] and model.name from teacher_inference.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(training_modes): shrink mode-comparison table + add sft/opd teacher note

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(configs): move training-mode debug configs to configs/debug/training_modes/

The reverse-text debug configs are about exercising the training modes, not
about reverse-text specifically. Move to configs/debug/training_modes/ and
drop the debug_ prefix from each filename (the directory name carries it).

  configs/reverse_text/debug_rl.toml          -> configs/debug/training_modes/rl.toml
  configs/reverse_text/debug_opd.toml         -> configs/debug/training_modes/opd.toml
  configs/reverse_text/debug_opd_lora.toml    -> configs/debug/training_modes/opd_lora.toml
  configs/reverse_text/debug_sft.toml         -> configs/debug/training_modes/sft.toml
  configs/reverse_text/debug_sft_lora.toml    -> configs/debug/training_modes/sft_lora.toml
  configs/reverse_text/debug_sft_external.toml -> configs/debug/training_modes/sft_external.toml
  configs/reverse_text/README.md              -> configs/debug/training_modes/README.md

Update path references in each TOML's header comment, the README, and
docs/training_modes.md.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(configs): drop auto pinference team-id, rename student-shortcut shim

- ClientConfig.auto_setup_pinference_team_header dropped. The hostname-sniff
  was implicit magic. Configs that need the X-Prime-Team-ID header against
  PI inference set it explicitly under [...client.headers_from_env] now.
  Update configs/debug/training_modes/sft_external.toml accordingly and
  drop the auto-injection note from the file header.
- Rename OrchestratorConfig._accept_legacy_student_layout (with leading
  underscore + "backward-compat" framing) to fold_student_shortcuts. The
  shim is more than a back-compat: it's the ergonomic path for rl configs
  too, letting users write [orchestrator.model.name] / [orchestrator.client]
  rather than [orchestrator.student.model.name] / [orchestrator.student.client].
  Docstring reframed accordingly. Teacher has no equivalent shortcut on
  purpose: rl mode forbids teacher, so the same shortcut routing to two
  roles would be ambiguous.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(tests): update multi_run CLI args after student rename

test_reverse_text_multi_run.start_orchestrator passes --client.base-url
and --model.lora.name as CLI flags to `uv run orchestrator`. After the
student rename, those tyro args don't exist anymore (they're now
--student.client.base-url and --student.model.lora.name). tyro rejects
them before the fold_student_shortcuts before-validator can re-nest the
dict, so the orchestrator process exits immediately and the test times
out waiting for "Step 11" to appear in the log.

Rename both CLI args to their new student-scoped form.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Timothy Kostolansky <39891386+tim0120@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-19 10:39:58 -07:00
45 changed files with 1307 additions and 669 deletions
+7
View File
@@ -2,6 +2,13 @@
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
- **First-class `training_mode` + batch-driven loss dispatch** (collection of removals/renames). Loss selection is now driven by `TrainingSample.training_mode` (`rl` / `opd` / `sft`), set under `[orchestrator]`. The trainer is mode-agnostic and dispatches per batch.
- **`orchestrator.use_sft_loss` removed**: replaced by `[orchestrator] training_mode = "sft"`. The orchestrator stamps each sample's `training_mode` and the trainer dispatches to `sft_loss_fn` per batch.
- **`orchestrator.teacher_rollout_model` removed (no alias)**: configs must rename to `[orchestrator.teacher]` (`teacher_model` is also accepted as a back-compat alias for `teacher`). Used in both opd and sft modes; the role is determined by `training_mode`.
- **`orchestrator.model` → `orchestrator.student`**: renamed for symmetry with `orchestrator.teacher`. Legacy `[orchestrator.model]` and a flat `[orchestrator.model.lora]`-style layout are aliased via a back-compat shim, so most existing configs still parse. New code should use `[orchestrator.student.*]`.
- **`trainer.loss.type = "sft"` removed (`SFTLossConfig` deleted)**: zero-field discriminator that is now implied by `training_mode = "sft"`. `trainer.loss` collapsed to a `DefaultLossConfig | CustomLossConfig` union. Existing configs setting `[trainer.loss] type = "sft"` must remove that line; the orchestrator-level `training_mode = "sft"` is enough.
- **`trainer.loss.teacher_tau` removed from `DefaultLossConfig`**: the teacher-KL term is now exclusive to `opd_loss_fn` (which inlines `teacher_tau = 1.0`). `default_loss_fn` only handles reward-driven RL and no longer accepts a `teacher_tau`. Configs that set `teacher_tau` on `[trainer.loss]` will fail validation — switch to `[orchestrator] training_mode = "opd"` (which uses `opd_loss_fn` with the value baked in).
- **`trainer.loss` only applies to rl-mode batches**: opd and sft don't read `trainer.loss`. `opd_loss_fn`'s knobs (dppo_mask_*, kl_tau) are inlined as literals; tweak them by editing the function. `CustomLossConfig` overrides the rl-mode loss only — opd and sft always use their dedicated fns. (2026-05-19)
- **`orchestrator.use_token_client` removed**: The server-tokenized TITO path has been deprecated end-to-end. The orchestrator-side config flag (`use_token_client`), the verifiers client_type (`openai_chat_completions_token`), and the inference server's `/v1/chat/completions/tokens` route (along with the `OpenAIServingChatWithTokens` wrapper) are all gone. The orchestrator now picks between renderer-backed TITO (`use_renderer = true`, default) and MITO (`use_renderer = false`, fallback). Existing configs with `use_token_client = true` must migrate to `use_renderer = true` (or `use_renderer = false` for MITO); configs with `use_token_client = false` can simply drop the field. (2026-05-19)
- **`orchestrator.advantage.length_penalty` → discriminated sub-config**: The scalar `length_penalty: Literal["tokens","turns"] | None` is replaced by a `LengthPenaltyConfig | None` discriminated on `type`. Token shaping now takes weighted completion + tool-response token costs. Migration: `length_penalty = "tokens"` becomes `[orchestrator.advantage.length_penalty]\ntype = "tokens"` (default weights `completion_weight = 1.0`, `tool_response_weight = 1.0` — total context). `length_penalty = "turns"` becomes `[orchestrator.advantage.length_penalty]\ntype = "turns"`. (2026-05-06)
- **`orchestrator.advantage.length_shaping` → `orchestrator.advantage.length_penalty`**: The boolean `length_shaping` flag has been replaced by `length_penalty: Literal["tokens", "turns"] | None` (default: `None`). `length_shaping = true` becomes `length_penalty = "tokens"`; `length_shaping = false` becomes `length_penalty = None`. The new `"turns"` option applies the same correctness-gated efficiency shaping using trajectory turn count instead of completion-token count. (2026-05-01)
+47
View File
@@ -0,0 +1,47 @@
# Training Mode — Debug Configs
Minimal end-to-end configs for the three training modes (`rl` / `opd` / `sft`) against the `reverse-text` env, using `PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT` as the student.
| Config | Mode | Teacher | Notes |
|---|---|---|---|
| `rl.toml` | `rl` | none | |
| `opd.toml` | `opd` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | |
| `opd_lora.toml` | `opd` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | trains a LoRA adapter (rank 8) |
| `sft.toml` | `sft` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | |
| `sft_lora.toml` | `sft` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | trains a LoRA adapter (rank 8) |
| `sft_external.toml` | `sft` | PI inference (`openai/gpt-5-mini`) | external OAI endpoint; no local teacher |
The student inference server is auto-launched on GPU 0 at `http://localhost:8000/v1` with `gpu_memory_utilization=0.5`. The local teacher (used by everything except `rl.toml` and `sft_external.toml`) is **not** auto-launched — start it manually on GPU 1.
## Start the local teacher
Needed for `opd*.toml` and `sft.toml` / `sft_lora.toml`:
```bash
CUDA_VISIBLE_DEVICES=1 uv run inference \
--model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
--server.port 8001 \
--gpu-memory-utilization 0.5 \
--model.enforce-eager
```
## Run the debug configs
```bash
# RL (no teacher)
uv run rl @ configs/debug/training_modes/rl.toml
# OPD (needs teacher on port 8001)
uv run rl @ configs/debug/training_modes/opd.toml
uv run rl @ configs/debug/training_modes/opd_lora.toml
# SFT hard distill (needs teacher on port 8001)
uv run rl @ configs/debug/training_modes/sft.toml
uv run rl @ configs/debug/training_modes/sft_lora.toml
# SFT hard distill from openai/gpt-5-mini via PI inference
# (requires PRIME_API_KEY + PRIME_TEAM_ID in env; no local teacher needed)
uv run rl @ configs/debug/training_modes/sft_external.toml
```
See [docs/training_modes.md](../../docs/training_modes.md) for what each mode does.
+54
View File
@@ -0,0 +1,54 @@
# Start the teacher inference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/training_modes/opd.toml
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
name = "debug-opd"
[orchestrator]
training_mode = "opd"
batch_size = 128
rollouts_per_example = 16
[orchestrator.renderer]
name = "qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 3e-6
[ckpt]
[inference]
gpu_memory_utilization = 0.5
@@ -0,0 +1,60 @@
# Start the teacher inference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/training_modes/opd_lora.toml
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
name = "debug-opd-lora"
[orchestrator]
training_mode = "opd"
batch_size = 128
rollouts_per_example = 16
[orchestrator.renderer]
name = "qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 1e-4
[trainer.model.lora]
rank = 8
[trainer.ckpt.weights]
save_adapter_separately = true
[ckpt]
[inference]
gpu_memory_utilization = 0.5
+41
View File
@@ -0,0 +1,41 @@
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
name = "debug-rl"
[orchestrator]
training_mode = "rl"
batch_size = 128
rollouts_per_example = 16
[orchestrator.renderer]
name = "qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[trainer.optim]
lr = 3e-6
[ckpt]
[inference]
gpu_memory_utilization = 0.5
+51
View File
@@ -0,0 +1,51 @@
# Start the teacher inference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/training_modes/sft.toml
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
name = "debug-sft"
[orchestrator]
training_mode = "sft"
batch_size = 128
rollouts_per_example = 4
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 3e-6
[ckpt]
[inference]
gpu_memory_utilization = 0.5
@@ -0,0 +1,55 @@
# SFT from openai/gpt-5-mini via PI inference.
# Requires PRIME_API_KEY + PRIME_TEAM_ID in the environment.
#
# Run with:
# uv run rl @ configs/debug/training_modes/sft_external.toml
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
name = "debug-sft-external"
[orchestrator]
training_mode = "sft"
batch_size = 128
rollouts_per_example = 4
[orchestrator.train.sampling]
max_completion_tokens = 2048
extra_body = { reasoning_effort = "minimal" }
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "openai/gpt-5-mini"
[orchestrator.teacher.client]
base_url = ["https://api.pinference.ai/api/v1"]
api_key_var = "PRIME_API_KEY"
[orchestrator.teacher.client.headers_from_env]
X-Prime-Team-ID = "PRIME_TEAM_ID"
[trainer.optim]
lr = 3e-6
[ckpt]
[inference]
gpu_memory_utilization = 0.5
@@ -0,0 +1,57 @@
# Start the teacher inference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/training_modes/sft_lora.toml
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
name = "debug-sft-lora"
[orchestrator]
training_mode = "sft"
batch_size = 128
rollouts_per_example = 4
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 1e-4
[trainer.model.lora]
rank = 8
[trainer.ckpt.weights]
save_adapter_separately = true
[ckpt]
[inference]
gpu_memory_utilization = 0.5
+1
View File
@@ -7,6 +7,7 @@
"index",
"entrypoints",
"configs",
"training_modes",
"environments",
"async",
"logging",
-118
View File
@@ -1,118 +0,0 @@
# On-Policy Distillation
On-policy distillation uses a teacher model to provide dense token-level feedback during RL training. The student generates rollouts, and the teacher's logprobs guide the student to stay close to stronger behavior while still learning from rewards.
For more details, see [On-Policy Distillation](https://thinkingmachines.ai/blog/on-policy-distillation/) by Thinking Machines.
## Quick Start
Add `num_teacher_gpus` to `[deployment]` and set `teacher_tau > 0`:
```toml
[deployment]
num_teacher_gpus = 2
[trainer.loss]
teacher_tau = 0.5
```
This automatically starts a teacher inference server using the same model as inference. To use a different teacher model:
```toml
[deployment]
num_teacher_gpus = 2
[teacher_inference.model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
[trainer.loss]
teacher_tau = 0.5
```
## Using an External Teacher Server
If the teacher is already running elsewhere:
```toml
[trainer.loss]
teacher_tau = 0.5
[orchestrator.teacher_model.client]
base_url = ["http://teacher-server:8000/v1"]
[orchestrator.teacher_model.model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
```
## Pure Distillation (No Verification)
For agentic environments where verification is expensive (code execution, tool use, multi-turn interactions), you can skip verification entirely and use only the teacher signal:
```toml
[deployment]
num_teacher_gpus = 2
[trainer.loss]
teacher_tau = 1.0
adv_tau = 0.0 # Disable reward-based learning
[orchestrator.verification]
enabled = false # Skip expensive verification
```
This runs pure on-policy distillation: the student learns to match the teacher without needing any reward signal.
## SFT Distillation ("Hard Distillation") From Teacher Rollouts
Use this mode when you want to train from teacher-generated completions directly (hard distillation), without teacher token-level logprobs.
```toml
[trainer.loss]
type = "sft"
[orchestrator]
use_renderer = false
use_sft_loss = true
[orchestrator.teacher_rollout_model.client]
base_url = ["https://your-openai-compatible-endpoint/v1"]
skip_model_check = true
[orchestrator.teacher_rollout_model.model]
name = "teacher-model-name"
```
In this mode:
- Rollouts are generated from `orchestrator.teacher_rollout_model`
- The orchestrator uses text-level reconstruction with the student tokenizer
- The RL trainer optimizes masked NLL (`trainer.loss.type = "sft"`)
- Omit `[inference]` (no local inference server required)
### Image Input (VLM) Support
Yes, image input is supported in SFT/hard-distillation mode when the student model is multimodal (VLM).
- Prompts can include OpenAI-style image items in `message.content`, e.g. `{"type": "image_url", "image_url": {"url": "data:image/..."}}`
- The orchestrator extracts and preprocesses images from trajectory prompts and attaches `pixel_values`/`image_grid_thw` to training samples
- No teacher token IDs/logprobs are required; reconstruction still happens from messages
Notes:
- This path currently expects `data:image/...` payloads in message content
- The teacher rollout endpoint still needs to be able to handle the same multimodal prompts during generation
Reference configs:
- `configs/alphabet_sort/sft_distill_hard_qwen4b_lora_prime_teacher.toml`
- `examples/alphabet_sort/sft_distill_hard.toml`
## Parameters
| Parameter | Default | Description |
|-----------|---------|-------------|
| `deployment.num_teacher_gpus` | `None` | Number of GPUs for teacher server. Auto-starts server when set. |
| `trainer.loss.teacher_tau` | `0.0` | Distillation strength. Set `> 0` to enable. |
| `trainer.loss.adv_tau` | `1.0` | Weight for RL advantage signal. Set `0` for pure distillation. |
| `orchestrator.verification.enabled` | `true` | Enable/disable verification. Set to `false` for pure distillation with `adv_tau = 0`. |
## Monitoring
The `teacher_kl` metric shows the KL divergence from teacher to student. Lower values mean the student is closer to the teacher.
+39
View File
@@ -0,0 +1,39 @@
# Training Modes
PRIME-RL supports three training modes through our RL trainer, selected via `training_mode`:
- **`rl`** — reinforcement learning: student generates rollouts, no teacher
- **`opd`** — [on-policy distillation](https://thinkingmachines.ai/blog/on-policy-distillation/): students generates rollouts, train to minimize the KL divergence between the student and teacher's logprobs for each token in the rollout
- **`sft`** — supervised fine-tuning on teacher-generated rollouts
> Note: PRIME-RL also has a dedicated `sft` entrypoint for more traditional supervised fine-tuning from a HF dataset. When using the `sft` training mode on the orchestrator, teacher rollouts are generated on-the-fly and used for training.
The mode determines who generates rollouts, what role the teacher plays, and what must be configured.
| Mode | Student | Teacher |
|---|---|---|
| `rl` | required | forbidden |
| `opd` | required | required (local vLLM) |
| `sft` | required | required (any OAI-compatible endpoint) |
**SFT vs OPD teachers** differ in what the orchestrator asks of them. SFT only calls `/v1/chat/completions` to generate rollouts — any OpenAI-compatible endpoint works (PI inference, OpenAI, Anthropic, a local vLLM). OPD additionally needs token-level logprobs scored over the student's tokens, which today only vLLM's `/inference/v1/generate` with `prompt_logprobs` exposes — so the OPD teacher must be a vLLM server.
### Reference configs
Debug-scale configs for all three modes (and LoRA variants) live in [`configs/debug/training_modes/`](../configs/debug/training_modes/):
- `rl.toml` / `opd.toml` / `opd_lora.toml`
- `sft.toml` / `sft_lora.toml` (local vLLM teacher)
- `sft_external.toml` (PI inference teacher)
See [`configs/debug/training_modes/README.md`](../configs/debug/training_modes/README.md) for run commands.
## Parameter reference
| Parameter | Default | Description |
|-----------|---------|-------------|
| `training_mode` | `"rl"` | One of `rl`, `opd`, `sft`. Propagates to `orchestrator.training_mode` and (for sft) `trainer.loss.type`. |
| `deployment.num_teacher_gpus` | `None` | Number of GPUs for the teacher vLLM server. Auto-starts when set. OPD only. |
| `trainer.loss.teacher_tau` | `0.0` | Distillation strength. Must be `> 0` in OPD. |
| `trainer.loss.adv_tau` | `1.0` | Weight for the RL advantage signal. Set `0` for pure distillation. |
| `orchestrator.verification.enabled` | `true` | Enable/disable verification. Set to `false` for pure distillation with `adv_tau = 0`. |
@@ -1,49 +0,0 @@
max_steps = 24
seq_len = 2048
[deployment]
type = "single_node"
gpus_per_node = 2
num_train_gpus = 2
num_infer_gpus = 0
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[wandb]
project = "alphabet-sort-sft-distill"
name = "qwen3-4b-hard-distill"
[ckpt]
[trainer.optim]
lr = 1e-5
[trainer.model.lora]
rank = 16
alpha = 32
[trainer.ckpt.weights]
save_adapter_separately = true
[orchestrator]
batch_size = 256
rollouts_per_example = 4
use_renderer = false
use_sft_loss = true
[orchestrator.train.sampling]
max_completion_tokens = 512
temperature = 0.7
[orchestrator.teacher_rollout_model.client]
base_url = ["https://api.pinference.ai/api/v1"]
api_key_var = "PRIME_API_KEY"
[orchestrator.teacher_rollout_model.model]
name = "qwen/qwen3-235b-a22b-instruct-2507"
[[orchestrator.train.env]]
id = "primeintellect/alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
@@ -880,46 +880,60 @@ class OrchestratorExperimentalConfig(BaseConfig):
"""Experimental features for the orchestrator."""
class TeacherModelConfig(BaseConfig):
"""Configures the teacher model for computing teacher logprobs (e.g. for distillation)."""
client: Annotated[
ClientConfig,
Field(description="The OAI client configuration for the teacher model."),
] = ClientConfig()
class RolloutModelConfig(BaseConfig):
"""Model + client pair for a rollout participant (student or teacher)."""
model: Annotated[
ModelConfig,
Field(description="The model configuration for the teacher model."),
Field(description="The model configuration."),
] = ModelConfig()
class TeacherRolloutModelConfig(BaseConfig):
"""Configures an external teacher model used to generate rollout text."""
client: Annotated[
ClientConfig,
Field(description="The OAI client configuration for rollout generation."),
Field(description="The client configuration."),
] = ClientConfig()
model: Annotated[
ModelConfig,
Field(description="The model configuration for rollout generation."),
] = ModelConfig()
class OrchestratorConfig(BaseConfig):
"""Configures the orchestrator for RL training."""
# Training mode: drives validation and runtime wiring
training_mode: Annotated[
Literal["rl", "opd", "sft"],
Field(
description=(
"Training mode. "
"rl: student generates rollouts, no teacher. "
"opd: student generates rollouts, teacher computes logprobs (teacher_tau > 0). "
"sft: teacher generates rollouts, student inference pool used for evals and weight sync."
),
),
] = "rl"
# Student model + client (the model being trained)
student: Annotated[
RolloutModelConfig,
Field(
validation_alias=AliasChoices("student", "model"),
description="Student model configuration (the model being trained).",
),
] = RolloutModelConfig()
# Teacher model + client (optional; role determined by training_mode)
teacher: Annotated[
RolloutModelConfig | None,
Field(
validation_alias=AliasChoices("teacher", "teacher_model"),
description=(
"Teacher model configuration. Role depends on training_mode: "
"opd — teacher computes logprobs; sft — teacher generates rollouts."
),
),
] = None
# Training environments and sampling
train: TrainConfig = TrainConfig()
# The OAI client configuration
client: ClientConfig = ClientConfig()
# The model configuration
model: ModelConfig = ModelConfig()
# The tokenizer configuration
tokenizer: TokenizerConfig = TokenizerConfig()
@@ -929,38 +943,6 @@ class OrchestratorConfig(BaseConfig):
# The optimizer configuration (per-run LR for multi-run training)
optim: OptimizerConfig = OptimizerConfig()
# The teacher model configuration (optional)
teacher_model: Annotated[
TeacherModelConfig | None,
Field(
description="The teacher model configuration for computing teacher logprobs (e.g. for distillation). "
"If provided, teacher logprobs will be computed using the specified model. "
"If None, no teacher model will be used."
),
] = None
# External teacher rollout model configuration (optional)
teacher_rollout_model: Annotated[
TeacherRolloutModelConfig | None,
Field(
description=(
"Optional external teacher model used for rollout generation. "
"When set, rollouts are generated from this endpoint/model instead of the student inference server."
),
),
] = None
# When True, trainer uses SFT loss instead of RL loss (per-run override for hosted multi-tenant training)
use_sft_loss: Annotated[
bool,
Field(
description=(
"When True, use SFT masked NLL loss instead of the trainer's configured RL loss. "
"Requires a teacher_rollout_model to be configured."
),
),
] = False
# The evaluation configuration
eval: EvalConfig | None = None
@@ -1142,6 +1124,55 @@ class OrchestratorConfig(BaseConfig):
Field(description="Experimental features for the orchestrator."),
] = OrchestratorExperimentalConfig()
@model_validator(mode="before")
@classmethod
def fold_student_shortcuts(cls, data: Any) -> Any:
"""Accept top-level ``[orchestrator.model]`` / ``[orchestrator.client]``
as shorthand for the student sub-config. Useful for ergonomic rl configs
where ``[orchestrator.student.*]`` is overkill, and required for
pre-refactor configs that used the flat layout to keep parsing:
- [orchestrator.client.*] -> [orchestrator.student.client.*]
- [orchestrator.model.<k>] -> [orchestrator.student.model.<k>]
(where <k> is any ModelConfig field)
Teacher must always be configured under [orchestrator.teacher.*]
(no equivalent shortcut), because rl mode forbids a teacher and we
don't want the same shortcut to silently route to two different roles.
"""
if not isinstance(data, dict):
return data
# 1. Re-nest top-level [orchestrator.client] under student.client.
if "client" in data:
student = data.setdefault("student", {})
if isinstance(student, dict) and "client" not in student:
student["client"] = data.pop("client")
# 2. Consolidate the legacy `model` alias into `student` so the
# flat-layout fix-up below sees a single target.
legacy_model = data.pop("model", None)
if legacy_model is not None:
existing = data.get("student")
if existing is None:
data["student"] = legacy_model
elif isinstance(existing, dict) and isinstance(legacy_model, dict):
for k, v in legacy_model.items():
existing.setdefault(k, v)
else:
# Mismatched types - put it back and let pydantic surface the error.
data["model"] = legacy_model
# 3. Re-nest flat ModelConfig keys under student.model.
model_only_keys = set(ModelConfig.model_fields)
student = data.get("student")
if isinstance(student, dict):
flat = {k: student.pop(k) for k in list(student) if k in model_only_keys}
if flat:
student.setdefault("model", {}).update(flat)
return data
@model_validator(mode="before")
@classmethod
def _env_to_train(cls, data: Any) -> Any:
@@ -1172,9 +1203,9 @@ class OrchestratorConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_tokenizer(self):
if self.tokenizer.name is None:
self.tokenizer.name = self.model.name
self.tokenizer.name = self.student.model.name
if self.tokenizer.trust_remote_code is None:
self.tokenizer.trust_remote_code = self.model.trust_remote_code
self.tokenizer.trust_remote_code = self.student.model.trust_remote_code
return self
@model_validator(mode="after")
@@ -1185,25 +1216,23 @@ class OrchestratorConfig(BaseConfig):
return self
@model_validator(mode="after")
def validate_sft_distill_mode(self):
"""Enforce the SFT hard distill invariants that involve only orchestrator fields.
def _force_no_renderer_for_sft(self):
"""SFT rolls out via the teacher's plain chat-completions endpoint; the
renderer client doesn't apply. Force use_renderer=False so the user
doesn't have to remember to set it. Declared before the renderer
validators below so they see the corrected value."""
if self.training_mode == "sft":
self.use_renderer = False
return self
Runs at ``OrchestratorConfig`` level so hosted deployments (which load this
config standalone via the ``orchestrator`` entrypoint) get the same guarantees
as the combined ``rl`` entrypoint.
"""
has_teacher = self.teacher_rollout_model is not None
if self.use_sft_loss and not has_teacher:
raise ValueError(
"orchestrator.use_sft_loss = true requires orchestrator.teacher_rollout_model to be configured."
)
if has_teacher and not self.use_sft_loss:
raise ValueError("orchestrator.teacher_rollout_model requires orchestrator.use_sft_loss = true.")
if has_teacher and self.use_renderer:
raise ValueError(
"orchestrator.use_renderer must be false when orchestrator.teacher_rollout_model is configured "
"(external rollout uses MITO)."
)
@model_validator(mode="after")
def validate_training_mode(self):
"""Enforce training mode invariants that involve only orchestrator fields."""
has_teacher = self.teacher is not None
if self.training_mode == "rl" and has_teacher:
raise ValueError("orchestrator.teacher must not be set when training_mode = 'rl'.")
if self.training_mode in ("opd", "sft") and not has_teacher:
raise ValueError(f"orchestrator.teacher must be configured when training_mode = '{self.training_mode}'.")
return self
@model_validator(mode="after")
@@ -1212,7 +1241,7 @@ class OrchestratorConfig(BaseConfig):
them client-side. VLMs need server-side image preprocessing and
chat templating, so they must use MITO — fail
loudly when both are set."""
if self.use_renderer and self.model.vlm is not None:
if self.use_renderer and self.student.model.vlm is not None:
raise ValueError(
"orchestrator.use_renderer is not supported for VLMs. Use MITO "
"(``use_renderer=false``) so image preprocessing and chat templating stay on the "
@@ -1268,7 +1297,7 @@ class OrchestratorConfig(BaseConfig):
return self
from renderers.base import MODEL_RENDERER_MAP
model_id = self.tokenizer.name or self.model.name
model_id = self.tokenizer.name or self.student.model.name
if model_id in MODEL_RENDERER_MAP:
return self
raise ValueError(
@@ -1355,7 +1384,7 @@ class OrchestratorConfig(BaseConfig):
@model_validator(mode="after")
def resolve_env_config(self):
"""Populate extra_env_kwargs and vLLM sampling defaults from top-level fields."""
is_vllm = self.teacher_rollout_model is None
is_vllm = self.training_mode != "sft"
for env in self.train.env:
env.extra_env_kwargs.update(max_seq_len=self.seq_len)
if is_vllm:
@@ -367,6 +367,27 @@ class RLConfig(BaseConfig):
### Validate configs (e.g. raise for unsupported (combinations of) configs)
@model_validator(mode="before")
@classmethod
def _stub_orchestrator_teacher_for_auto_setup(cls, data):
"""When `deployment.num_teacher_gpus > 0` and the user didn't write an
`[orchestrator.teacher]` block, inject an empty one so
`OrchestratorConfig.validate_training_mode` (which fires during nested
validation) doesn't reject `training_mode = "opd"` for "missing teacher".
`auto_setup_teacher_inference` (after) then fills in client.base_url and
model.name from the auto-launched teacher_inference server."""
if not isinstance(data, dict):
return data
deployment = data.get("deployment")
if not isinstance(deployment, dict):
return data
if not deployment.get("num_teacher_gpus"):
return data
orch = data.setdefault("orchestrator", {})
if isinstance(orch, dict) and "teacher" not in orch and "teacher_model" not in orch:
orch["teacher"] = {}
return data
@model_validator(mode="after")
def validate_deployment(self):
if self.deployment.type == "multi_node":
@@ -422,32 +443,6 @@ class RLConfig(BaseConfig):
return self
@model_validator(mode="after")
def validate_teacher_model(self):
if (
self.trainer.loss.type == "default" and self.trainer.loss.teacher_tau > 0
) and not self.orchestrator.teacher_model:
raise ValueError(
"teacher_model must be configured when teacher_tau > 0. "
"Either set teacher_tau = 0, set deployment.num_teacher_gpus, or configure teacher_model manually."
)
return self
@model_validator(mode="after")
def validate_external_rollout_inference(self):
"""Forbid configuring a local inference server when rollouts come from an external teacher.
Orchestrator-only invariants (``use_sft_loss`` paired with ``teacher_rollout_model``,
and ``use_renderer`` coupling) live on ``OrchestratorConfig`` so the hosted
orchestrator entrypoint also enforces them.
"""
if self.orchestrator.teacher_rollout_model is not None and self.inference is not None:
raise ValueError(
"inference must be omitted when orchestrator.teacher_rollout_model is configured. "
"External rollout mode does not use the local inference server."
)
return self
### Auto-setup and validate shared configs
@model_validator(mode="after")
@@ -564,13 +559,13 @@ class RLConfig(BaseConfig):
inference_model_explicitly_set = "name" in self.inference.model.model_fields_set
if not inference_model_explicitly_set:
self.inference.model.name = self.model.name
self.orchestrator.model.name = self.inference.model.name
self.orchestrator.student.model.name = self.inference.model.name
else:
self.orchestrator.model.name = self.model.name
self.orchestrator.student.model.name = self.model.name
if self.model.vlm is not None:
self.trainer.model.vlm = self.model.vlm
self.orchestrator.model.vlm = self.model.vlm
self.orchestrator.student.model.vlm = self.model.vlm
if self.inference is not None:
self.inference.model.vlm = self.model.vlm
@@ -586,17 +581,21 @@ class RLConfig(BaseConfig):
# in name/trust_remote_code from model config where still unset.
self.trainer.tokenizer = self.tokenizer.model_copy()
self.orchestrator.tokenizer = self.tokenizer.model_copy()
for component in (self.trainer, self.orchestrator):
if component.tokenizer.name is None:
component.tokenizer.name = component.model.name
if component.tokenizer.trust_remote_code is None:
component.tokenizer.trust_remote_code = component.model.trust_remote_code
if self.trainer.tokenizer.name is None:
self.trainer.tokenizer.name = self.trainer.model.name
if self.trainer.tokenizer.trust_remote_code is None:
self.trainer.tokenizer.trust_remote_code = self.trainer.model.trust_remote_code
if self.orchestrator.tokenizer.name is None:
self.orchestrator.tokenizer.name = self.orchestrator.student.model.name
if self.orchestrator.tokenizer.trust_remote_code is None:
self.orchestrator.tokenizer.trust_remote_code = self.orchestrator.student.model.trust_remote_code
else:
# No shared tokenizer: re-derive from (now-correct) model names,
# since auto_setup_tokenizer on sub-configs already ran with defaults.
for component in (self.trainer, self.orchestrator):
component.tokenizer.name = component.model.name
component.tokenizer.trust_remote_code = component.model.trust_remote_code
self.trainer.tokenizer.name = self.trainer.model.name
self.trainer.tokenizer.trust_remote_code = self.trainer.model.trust_remote_code
self.orchestrator.tokenizer.name = self.orchestrator.student.model.name
self.orchestrator.tokenizer.trust_remote_code = self.orchestrator.student.model.trust_remote_code
# Propagate chat_template to inference (vLLM --chat-template)
if self.inference is not None:
@@ -720,40 +719,40 @@ class RLConfig(BaseConfig):
if self.trainer.weight_broadcast.type == "nccl":
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
if self.orchestrator.model.lora is None:
if self.orchestrator.student.model.lora is None:
from prime_rl.configs.orchestrator import LoRAConfig
self.orchestrator.model.lora = LoRAConfig()
self.orchestrator.student.model.lora = LoRAConfig()
if (
self.orchestrator.model.lora.rank is not None
and self.orchestrator.model.lora.rank != self.trainer.model.lora.rank
self.orchestrator.student.model.lora.rank is not None
and self.orchestrator.student.model.lora.rank != self.trainer.model.lora.rank
):
raise ValueError(
f"orchestrator.model.lora.rank ({self.orchestrator.model.lora.rank}) conflicts with "
f"orchestrator.student.model.lora.rank ({self.orchestrator.student.model.lora.rank}) conflicts with "
f"trainer.model.lora.rank ({self.trainer.model.lora.rank}). "
f"Remove orchestrator.model.lora.rank to inherit from trainer, or update trainer.model.lora.rank to match."
f"Remove orchestrator.student.model.lora.rank to inherit from trainer, or update trainer.model.lora.rank to match."
)
if (
self.orchestrator.model.lora.alpha is not None
and self.orchestrator.model.lora.alpha != self.trainer.model.lora.alpha
self.orchestrator.student.model.lora.alpha is not None
and self.orchestrator.student.model.lora.alpha != self.trainer.model.lora.alpha
):
raise ValueError(
f"orchestrator.model.lora.alpha ({self.orchestrator.model.lora.alpha}) conflicts with "
f"orchestrator.student.model.lora.alpha ({self.orchestrator.student.model.lora.alpha}) conflicts with "
f"trainer.model.lora.alpha ({self.trainer.model.lora.alpha}). "
f"Remove orchestrator.model.lora.alpha to inherit from trainer, or update trainer.model.lora.alpha to match."
f"Remove orchestrator.student.model.lora.alpha to inherit from trainer, or update trainer.model.lora.alpha to match."
)
if self.orchestrator.model.lora.rank is None:
self.orchestrator.model.lora.rank = self.trainer.model.lora.rank
if self.orchestrator.student.model.lora.rank is None:
self.orchestrator.student.model.lora.rank = self.trainer.model.lora.rank
if self.orchestrator.model.lora.alpha is None:
self.orchestrator.model.lora.alpha = self.trainer.model.lora.alpha
if self.orchestrator.student.model.lora.alpha is None:
self.orchestrator.student.model.lora.alpha = self.trainer.model.lora.alpha
if self.orchestrator.model.lora.name is None:
self.orchestrator.model.lora.name = (
f"r{self.orchestrator.model.lora.rank}-a{self.orchestrator.model.lora.alpha}"
if self.orchestrator.student.model.lora.name is None:
self.orchestrator.student.model.lora.name = (
f"r{self.orchestrator.student.model.lora.rank}-a{self.orchestrator.student.model.lora.alpha}"
)
if self.inference is not None:
@@ -771,7 +770,7 @@ class RLConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_session_headers(self):
"""Ensure X-Session-ID header is always set for sticky DP-aware routing at the inference router."""
self.orchestrator.client.extra_headers_from_state.setdefault("X-Session-ID", "example_id")
self.orchestrator.student.client.extra_headers_from_state.setdefault("X-Session-ID", "example_id")
return self
@model_validator(mode="after")
@@ -917,17 +916,23 @@ class RLConfig(BaseConfig):
return self
@model_validator(mode="after")
def auto_setup_dp_rank_count(self):
"""Auto-set orchestrator client dp_rank_count from inference DP size.
def auto_setup_inference_client(self):
"""Auto-configure orchestrator student client from the inference server config.
Uses data_parallel_size_local (per-node DP) when set, since each base URL
points to a single node whose API server only knows about its local ranks.
Falls back to the global parallel.dp for single-node setups.
For all modes, sets dp_rank_count from inference DP size. For SFT mode,
also sets base_url - rl/opd rely on the ClientConfig default
(``["http://localhost:8000/v1"]``) which already matches the auto-launched
student vLLM at inference.server.port = 8000.
"""
if self.inference is not None and "dp_rank_count" not in self.orchestrator.client.model_fields_set:
self.orchestrator.client.dp_rank_count = (
self.inference.data_parallel_size_local or self.inference.parallel.dp
)
if self.inference is None:
return self
client = self.orchestrator.student.client
if "dp_rank_count" not in client.model_fields_set:
client.dp_rank_count = self.inference.data_parallel_size_local or self.inference.parallel.dp
if self.orchestrator.training_mode == "sft" and "base_url" not in client.model_fields_set:
host = self.inference.server.host or "localhost"
port = self.inference.server.port
client.base_url = [f"http://{host}:{port}/v1"]
return self
@model_validator(mode="after")
@@ -940,7 +945,7 @@ class RLConfig(BaseConfig):
import copy
from prime_rl.configs.orchestrator import TeacherModelConfig
from prime_rl.configs.orchestrator import RolloutModelConfig
if self.teacher_inference is None:
if self.inference is None:
@@ -962,12 +967,12 @@ class RLConfig(BaseConfig):
assert num_teacher_gpus > 0, "num_teacher_gpus cannot be zero"
self.teacher_inference.parallel.dp = num_teacher_gpus // tp
if self.orchestrator.teacher_model is None:
self.orchestrator.teacher_model = TeacherModelConfig()
if self.orchestrator.teacher is None:
self.orchestrator.teacher = RolloutModelConfig()
host = self.teacher_inference.server.host or "localhost"
port = self.teacher_inference.server.port
self.orchestrator.teacher_model.client.base_url = [f"http://{host}:{port}/v1"]
self.orchestrator.teacher_model.model.name = self.teacher_inference.model.name
self.orchestrator.teacher.client.base_url = [f"http://{host}:{port}/v1"]
self.orchestrator.teacher.model.name = self.teacher_inference.model.name
return self
@@ -131,6 +131,10 @@ class BaseModelConfig(BaseConfig):
),
] = None
@property
def is_vlm(self) -> bool:
return self.vlm is not None
class RendererConfig(BaseConfig):
"""Configures the client-side renderer (chat-template + response parsing).
@@ -299,6 +303,13 @@ class ClientConfig(BaseConfig):
),
] = {}
headers_from_env: Annotated[
dict[str, str],
Field(
description='Maps HTTP header names to environment variable names. At runtime each entry is resolved via os.getenv and merged into the request headers. e.g. {"X-Prime-Team-ID": "PRIME_TEAM_ID"}.',
),
] = {}
extra_headers_from_state: Annotated[
dict[str, str],
Field(
@@ -682,25 +682,19 @@ class CheckpointConfig(BaseConfig):
class DefaultLossConfig(BaseModel):
"""Config for the default loss."""
"""Knobs for the default DPPO+KL loss. Only consumed by rl-mode batches
(``default_loss_fn``); opd and sft have their own self-contained loss fns."""
type: Literal["default"] = "default"
dppo_mask_low: Annotated[float, Field(ge=0, description="The low threshold for masking tokens.")] = 0.2
dppo_mask_high: Annotated[float, Field(ge=0, description="The high threshold for masking tokens.")] = 0.2
adv_tau: Annotated[float, Field(ge=0, description="The tau for advantages.")] = 1.0
teacher_tau: Annotated[float, Field(ge=0, description="The tau for teacher logprobs.")] = 0.0
kl_tau: Annotated[float, Field(ge=0, description="The tau for KL divergence.")] = 1e-3
class SFTLossConfig(BaseModel):
"""Config for SFT-style masked negative log-likelihood loss."""
type: Literal["sft"] = "sft"
class CustomLossConfig(BaseModel):
"""Config for a custom external loss function."""
"""Override for the rl-mode loss fn. opd and sft are unaffected."""
type: Literal["custom"] = "custom"
@@ -708,7 +702,7 @@ class CustomLossConfig(BaseModel):
kwargs: Annotated[dict[str, Any], Field(default_factory=dict, description="Kwargs to pass to the loss function")]
LossConfig: TypeAlias = Annotated[DefaultLossConfig | SFTLossConfig | CustomLossConfig, Field(discriminator="type")]
LossConfig: TypeAlias = Annotated[DefaultLossConfig | CustomLossConfig, Field(discriminator="type")]
class FakeDataLoaderConfig(BaseConfig):
@@ -783,7 +777,8 @@ class TrainerConfig(BaseConfig):
# The data configuration
data: DataLoaderConfig = DataLoaderConfig()
# The loss configuration
# Loss config for the rl-mode batches only. opd and sft batches dispatch to
# opd_loss_fn / sft_loss_fn unconditionally - they don't read trainer.loss.
loss: LossConfig = DefaultLossConfig()
# The optimizer configuration
@@ -36,18 +36,18 @@ def validate_shared_model_name(
) -> None:
# Orchestrator must match inference (it queries the inference server)
if inference is not None:
if inference.model.name != orchestrator.model.name:
if inference.model.name != orchestrator.student.model.name:
raise ValueError(
f"Inference model name ({inference.model.name}) and orchestrator model name ({orchestrator.model.name}) are not the same. "
f"Inference model name ({inference.model.name}) and orchestrator model name ({orchestrator.student.model.name}) are not the same. "
"The orchestrator queries the inference server and must use the same model name."
)
return
if trainer.model.name.startswith("Jackmin108/"): # The TT MoE models will have a different name on the orchestrator
return
if trainer.model.name != orchestrator.model.name:
if trainer.model.name != orchestrator.student.model.name:
raise ValueError(
f"Trainer model name ({trainer.model.name}) and orchestrator model name ({orchestrator.model.name}) are not the same. Please specify the same model name for both."
f"Trainer model name ({trainer.model.name}) and orchestrator model name ({orchestrator.student.model.name}) are not the same. Please specify the same model name for both."
)
+3 -1
View File
@@ -163,7 +163,9 @@ If you wish to configure values of the default variant, you don't need to set th
### SFT hard distill override
For hosted multi-tenant runs where the trainer image's `trainer.loss.type` is fixed, the orchestrator exposes a per-run override that forces SFT loss on every micro-batch without rebuilding the trainer. Set `orchestrator.use_sft_loss = true` alongside `orchestrator.teacher_rollout_model`; both must be configured together (the orchestrator validator enforces this). The orchestrator stamps each `TrainingSample.sft_loss = True`, which the trainer's `compute_loss` honors by dispatching to `sft_loss_fn` per batch — independent of the trainer's configured default loss.
Set `orchestrator.training_mode = "sft"` (or top-level `training_mode = "sft"`, which auto-propagates) and configure `orchestrator.teacher` with the teacher endpoint. The orchestrator stamps each `TrainingSample.sft_loss = True` and the shared `training_mode` validator sets `trainer.loss.type = "sft"`, which the trainer's `compute_loss` honors by dispatching to `sft_loss_fn` per batch.
`[inference]` is required (same as rl/opd) — it starts the student inference server and auto-configures `orchestrator.student.client.base_url`. The student pool is used for online evals and policy weight sync. For externally started student inference, set `orchestrator.student.client.base_url` explicitly instead.
### RL rollout client defaults
+13 -40
View File
@@ -78,26 +78,6 @@ def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
tomli_w.dump(teacher_inference.model_dump(exclude_none=True, mode="json"), f)
def check_gpus_available(gpu_ids: list[int]) -> None:
"""Raise error if there are existing processes on the specified GPUs."""
pynvml.nvmlInit()
occupied = []
for gpu_id in gpu_ids:
handle = pynvml.nvmlDeviceGetHandleByIndex(gpu_id)
processes = pynvml.nvmlDeviceGetComputeRunningProcesses(handle)
if processes:
pids = [p.pid for p in processes]
occupied.append((gpu_id, pids))
if occupied:
msg = "Existing processes found on GPUs:\n"
for gpu_id, pids in occupied:
msg += f" GPU {gpu_id}: PIDs {pids}\n"
msg += "Kill these processes or use different GPUs."
raise RuntimeError(msg)
def rl_local(config: RLConfig):
assert config.deployment.type == "single_node"
@@ -148,21 +128,17 @@ def rl_local(config: RLConfig):
wandb_shared_env["WANDB_SHARED_MODE"] = "1"
wandb_shared_env["WANDB_SHARED_RUN_ID"] = os.environ.get("WANDB_SHARED_RUN_ID", uuid.uuid4().hex)
# Check for existing processes on GPUs
all_gpu_ids = list(set(infer_gpu_ids + trainer_gpu_ids + teacher_gpu_ids))
check_gpus_available(all_gpu_ids)
# Validate client port matches inference server port
if config.inference is not None and not config.orchestrator.client.is_elastic:
if config.inference is not None and not config.orchestrator.student.client.is_elastic:
from urllib.parse import urlparse
base_url = config.orchestrator.client.base_url[0]
base_url = config.orchestrator.student.client.base_url[0]
parsed = urlparse(base_url)
client_port = parsed.port
expected_port = config.inference.server.port
if client_port != expected_port:
raise ValueError(
f"orchestrator.client.base_url port ({client_port}) does not match "
f"orchestrator.student.client.base_url port ({client_port}) does not match "
f"inference.server.port ({expected_port}). "
f"Update the base_url to use port {expected_port} to match the inference server."
)
@@ -215,14 +191,13 @@ def rl_local(config: RLConfig):
monitor_thread.start()
monitor_threads.append(monitor_thread)
else:
if config.orchestrator.teacher_rollout_model is None:
logger.warning(
"No inference config specified, skipping starting inference server. Make sure your inference server is running."
)
else:
logger.info(
"No inference config specified, using orchestrator.teacher_rollout_model for rollout generation."
)
logger.warning(
"No [inference] block configured - the student inference server will not be started here. "
"All training modes (rl/opd/sft) require a student inference pool for evals + weight sync; "
"make sure one is running at orchestrator.student.client.base_url "
f"({', '.join(config.orchestrator.student.client.base_url)}), otherwise the orchestrator "
"will hang waiting for it."
)
# Optionally, start teacher inference process
if config.teacher_inference:
@@ -230,7 +205,7 @@ def rl_local(config: RLConfig):
raise ValueError(
"teacher_inference is configured but deployment.num_teacher_gpus is not set. "
"Either set deployment.num_teacher_gpus to start a teacher inference server, "
"or omit teacher_inference and configure orchestrator.teacher_model to use an existing server."
"or omit teacher_inference and configure orchestrator.teacher to use an existing server."
)
teacher_inference_cmd = ["inference", "@", (config_dir / TEACHER_INFERENCE_TOML).as_posix()]
@@ -258,12 +233,10 @@ def rl_local(config: RLConfig):
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
elif (
config.trainer.loss.type == "default" and config.trainer.loss.teacher_tau > 0
) or config.orchestrator.teacher_model:
elif config.orchestrator.teacher:
logger.warning(
"No teacher_inference config specified, skipping starting teacher inference server. "
"Is your teacher inference server running? Make sure orchestrator.teacher_model is configured."
"Is your teacher inference server running? Make sure orchestrator.teacher is configured."
)
# Start orchestrator process
+5
View File
@@ -1,5 +1,7 @@
import torch
from prime_rl.inference.vllm.padded_input_scrub import monkey_patch_vllm_padded_input_scrub
def transformers_v5_compat():
"""vLLM general plugin: patch transformers v5 config attrs that vLLM still expects.
@@ -16,6 +18,7 @@ def transformers_v5_compat():
_patch_lora_key_prefix()
monkey_patch_dp_engine_core_pause_resume_deadlock()
monkey_patch_vllm_layerwise_reload_alias_buffers()
monkey_patch_vllm_padded_input_scrub()
def monkey_patch_vllm_layerwise_reload_alias_buffers():
@@ -26,6 +29,8 @@ def monkey_patch_vllm_layerwise_reload_alias_buffers():
# storage *after* the parameter has been correctly reloaded. Skip the copy
# for any buffer that shares storage with a parameter; _place_kernel_tensors
# re-registers the original view, which trivially reflects the parameter.
# Remove this patch once https://github.com/vllm-project/vllm/pull/42481 is
# included in the vLLM release we pin/use.
from vllm.logger import init_logger
from vllm.model_executor.model_loader.reload import layerwise as reload_layerwise
@@ -0,0 +1,88 @@
from __future__ import annotations
import logging
import threading
from collections.abc import Sequence
from typing import Any
logger = logging.getLogger(__name__)
_INSTALL_LOCK = threading.Lock()
_INSTALLED = False
def monkey_patch_vllm_padded_input_scrub() -> None:
"""Zero vLLM's padded model inputs before graph replay.
vLLM pads decode batches up to CUDA graph capture sizes. Some kernels read
model-input tensors past the scheduled-token prefix, so stale values in the
padded tail can affect replayed decode graphs. Keep this shim until the
vLLM-side fix is available in the pinned runtime.
Remove this patch once https://github.com/vllm-project/vllm/pull/42779 is
included in the vLLM release we pin/use.
"""
global _INSTALLED
with _INSTALL_LOCK:
if _INSTALLED:
return
from vllm.v1.worker.gpu_model_runner import GPUModelRunner
if getattr(GPUModelRunner, "_prime_rl_padded_input_scrub", False):
_INSTALLED = True
return
original_preprocess = GPUModelRunner._preprocess
def _patched_preprocess(
self: Any,
scheduler_output: Any,
num_input_tokens: int,
intermediate_tensors: Any | None = None,
) -> tuple[Any, ...]:
result = original_preprocess(
self,
scheduler_output,
num_input_tokens,
intermediate_tensors,
)
num_scheduled_tokens = int(scheduler_output.total_num_scheduled_tokens)
_zero_padded_model_inputs(
result,
num_scheduled_tokens,
int(num_input_tokens),
)
return result
GPUModelRunner._preprocess = _patched_preprocess
GPUModelRunner._prime_rl_padded_input_scrub = True
_INSTALLED = True
logger.warning("Enabled vLLM padded model-input scrub.")
def _zero_padded_model_inputs(
preprocess_result: Sequence[Any],
num_scheduled_tokens: int,
num_input_tokens: int,
) -> None:
"""Zero the model-input tail beyond scheduled tokens in-place."""
if num_input_tokens <= num_scheduled_tokens:
return
input_ids = preprocess_result[0]
inputs_embeds = preprocess_result[1]
positions = preprocess_result[2]
pad_slice = slice(num_scheduled_tokens, num_input_tokens)
if input_ids is not None:
input_ids[pad_slice].zero_()
if inputs_embeds is not None:
inputs_embeds[pad_slice].zero_()
if positions is not None:
if positions.ndim == 1:
positions[pad_slice].zero_()
else:
positions[..., pad_slice].zero_()
+4
View File
@@ -134,6 +134,7 @@ from prime_rl.inference.patches import (
monkey_patch_harmony_stop_token_propagation,
monkey_patch_load_lora_adapter,
monkey_patch_tokenize_params_validation,
monkey_patch_vllm_padded_input_scrub,
)
# NOTE: Fix harmony stop token propagation for GPT-OSS models
@@ -145,6 +146,9 @@ monkey_patch_load_lora_adapter()
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
# Still needed in vLLM 0.20 — upstream rejects prompt_len > max_model_len - max_tokens
monkey_patch_tokenize_params_validation()
# NOTE: Optional mitigation for vLLM padded decode inputs until the native fix
# is available in our pinned runtime.
monkey_patch_vllm_padded_input_scrub()
logger = init_logger("vllm.entrypoints.openai.api_server")
+97 -109
View File
@@ -47,7 +47,6 @@ from prime_rl.orchestrator.utils import (
get_weight_dir,
print_benchmark,
set_default_executor,
setup_external_rollout_model,
)
from prime_rl.orchestrator.vf_utils import (
get_seq_len,
@@ -93,9 +92,10 @@ async def orchestrate(config: OrchestratorConfig):
json_logging=config.log.json_logging,
)
intercept_vf_logging(logger="verifiers.serve", level="WARN") # show logs from env clients
logger.info("Starting orchestrator")
set_default_executor()
logger.info(f"Starting orchestrator ({config.training_mode})")
set_default_executor()
event_loop_lag_monitor = EventLoopLagMonitor()
event_loop_lag_monitor_task = asyncio.create_task(event_loop_lag_monitor.run())
@@ -118,45 +118,43 @@ async def orchestrate(config: OrchestratorConfig):
for env_id in env_ids_to_install:
install_env(env_id, prerelease=config.env_install_prerelease)
# Setup rollout inference pool (handles both static and elastic modes)
rollout_client_config, rollout_model_name, enable_policy_updates = setup_external_rollout_model(config, logger)
# Setup teacher inference pool if configured
if config.teacher_model:
logger.info(
f"Initializing teacher inference pool (base_url={', '.join(config.teacher_model.client.base_url)}, "
f"model={config.teacher_model.model.name})"
)
teacher_inference_pool = await setup_inference_pool(
config.teacher_model.client,
model_name=config.teacher_model.model.name,
train_client_type="openai_chat_completions",
)
else:
teacher_inference_pool = None
# Check if this is a vision-language model (used throughout for VLM-specific paths)
is_vlm = config.model.vlm is not None
# Load tokenizer and processor (processor only for VLM models)
logger.info(f"Initializing tokenizer ({config.tokenizer})")
tokenizer = setup_tokenizer(config.tokenizer)
processor = None
if is_vlm:
logger.info(f"Loading VLM processor for {config.model.name}")
if config.student.model.is_vlm:
logger.info(f"Loading VLM processor for {config.student.model.name}")
processor = AutoProcessor.from_pretrained(
config.model.name, trust_remote_code=config.model.trust_remote_code, use_fast=True
config.student.model.name, trust_remote_code=config.student.model.trust_remote_code, use_fast=True
)
renderer, inference_pool = await setup_rollout_inference_pool(
# Set up student inference pool (required for all training modes).
logger.info(
f"Initializing student inference pool (base_url={', '.join(config.student.client.base_url)}, "
f"model={config.student.model.name})"
)
renderer, student_inference = await setup_student_inference_pool(
config=config,
rollout_client_config=rollout_client_config,
rollout_model_name=rollout_model_name,
tokenizer=tokenizer,
logger=logger,
)
# Set up teacher inference pool (configured for opd or sft). Always MITO for
# simplicity - this also keeps external OAI-compatible teachers (PI inference,
# OpenAI) working as drop-in endpoints.
teacher_inference = None
if config.teacher is not None:
logger.info(
f"Initializing teacher inference pool (base_url={', '.join(config.teacher.client.base_url)}, "
f"model={config.teacher.model.name})"
)
teacher_inference = await setup_inference_pool(
config.teacher.client,
model_name=config.teacher.model.name,
train_client_type="openai_chat_completions",
)
# Setup monitor (may register the run and set RUN_ID in the environment)
logger.info(f"Initializing monitor (wandb={config.wandb}, prime_monitor={config.prime_monitor})")
monitor = setup_monitor(
@@ -196,6 +194,12 @@ async def orchestrate(config: OrchestratorConfig):
# Load environments
logger.info("Loading training environments")
train_envs = TrainEnvs(config.train.env)
if config.training_mode == "sft":
# Teacher rollouts don't need inference-side logprobs (the trainer
# reconstructs teacher tokens), and some external reasoning-model
# endpoints (e.g. openai/gpt-5*) reject the parameter.
for env in train_envs:
env.sampling_args.pop("logprobs", None)
logger.info(f"Loaded {len(train_envs)} training environment(s) ({', '.join(train_envs.names)})")
await train_envs.start(
@@ -236,54 +240,44 @@ async def orchestrate(config: OrchestratorConfig):
scheduler = Scheduler(
train_envs=train_envs,
buffer=buffer,
inference_pool=inference_pool,
student_inference=student_inference,
teacher_inference=teacher_inference,
max_inflight_rollouts=config.max_inflight_rollouts,
max_async_level=config.max_async_level,
max_off_policy_steps=config.max_off_policy_steps,
strict_async_level=config.strict_async_level,
tasks_per_minute=config.tasks_per_minute,
enable_policy_updates=enable_policy_updates,
lora_name=config.model.lora.name if config.model.lora else None,
lora_name=config.student.model.lora.name if config.student.model.lora else None,
config=config,
)
scheduler.model_name = rollout_model_name
if checkpoint_step is not None and config.model.lora is not None and enable_policy_updates:
assert config.model.lora.name is not None
scheduler.model_name = config.model.lora.name
# Check health of the inference pool
logger.info("Waiting for inference pool to be ready")
await inference_pool.wait_for_ready(rollout_model_name)
logger.success("Inference pool ready")
# Wait for pools to be ready
logger.info("Waiting for student inference pool to be ready")
await student_inference.wait_for_ready(config.student.model.name)
logger.success("Student inference pool ready")
if teacher_inference is not None:
assert config.teacher is not None
logger.info("Waiting for teacher inference pool to be ready")
await teacher_inference.wait_for_ready(config.teacher.model.name)
logger.success("Teacher inference pool ready")
# Start inference metrics collector (requires W&B)
inference_metrics_collector = None
if config.wandb is not None and config.collect_inference_metrics:
inference_metrics_collector = InferenceMetricsCollector(inference_pool.admin_clients)
inference_metrics_collector = InferenceMetricsCollector(student_inference.admin_clients)
await inference_metrics_collector.start()
# Check health of teacher inference server if configured
if config.teacher_model and teacher_inference_pool:
logger.info("Waiting for teacher inference pool to be ready")
await teacher_inference_pool.wait_for_ready(config.teacher_model.model.name)
logger.success("Teacher inference pool ready")
# Set up weight broadcast backend
if enable_policy_updates:
logger.info(f"Initializing weight broadcast ({config.weight_broadcast})")
if config.weight_broadcast.type == "nccl":
await init_nccl_broadcast(
inference_pool.admin_clients,
config.weight_broadcast.host,
config.weight_broadcast.port,
config.weight_broadcast.timeout,
inference_world_size=config.weight_broadcast.inference_world_size,
quantize_in_weight_transfer=config.weight_broadcast.quantize_in_weight_transfer,
)
else:
logger.info("Skipping weight broadcast initialization (SFT distillation mode)")
# Set up weight broadcast backend (targets student inference)
logger.info(f"Initializing weight broadcast ({config.weight_broadcast})")
if config.weight_broadcast.type == "nccl":
await init_nccl_broadcast(
student_inference.admin_clients,
config.weight_broadcast.host,
config.weight_broadcast.port,
config.weight_broadcast.timeout,
inference_world_size=config.weight_broadcast.inference_world_size,
quantize_in_weight_transfer=config.weight_broadcast.quantize_in_weight_transfer,
)
# Setup training batch sender for sending training examples to trainer
logger.info(f"Initializing training batch sender ({config.rollout_transport})")
@@ -309,15 +303,18 @@ async def orchestrate(config: OrchestratorConfig):
# Allow eval at resumed step by setting prev_ckpt_step one behind
prev_ckpt_step = scheduler.ckpt_step - 1
if enable_policy_updates:
# In NCCL mode, skip existence check - weights are broadcasted, not stored on disk
check_exists = config.weight_broadcast.type != "nccl"
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else None
weights_path = get_weight_dir(
config.output_dir, scheduler.ckpt_step, check_exists=check_exists, wait_timeout=wait_timeout
)
lora_name = config.model.lora.name if config.model.lora else None
await inference_pool.update_weights(weights_path, lora_name=lora_name, step=scheduler.ckpt_step)
# In NCCL mode, skip existence check - weights are broadcasted, not stored on disk
check_exists = config.weight_broadcast.type != "nccl"
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else None
weights_path = get_weight_dir(
config.output_dir, scheduler.ckpt_step, check_exists=check_exists, wait_timeout=wait_timeout
)
lora_name = config.student.model.lora.name if config.student.model.lora else None
await student_inference.update_weights(weights_path, lora_name=lora_name, step=scheduler.ckpt_step)
if lora_name is not None:
student_inference.update_model_name(lora_name)
if scheduler.rollout_inference is student_inference:
scheduler.model_name = lora_name
else:
logger.info("Training from scratch")
@@ -333,7 +330,7 @@ async def orchestrate(config: OrchestratorConfig):
raise RuntimeError(f"Run evicted by trainer: {reason}")
# Capture ckpt_step once for consistency (it's updated inside the scheduler)
ckpt_step = scheduler.ckpt_step if enable_policy_updates else progress.step
ckpt_step = scheduler.ckpt_step
scheduler.ckpt_step = ckpt_step
# Save checkpoint (if we are at an interval step and not at the first or last step)
@@ -391,8 +388,8 @@ async def orchestrate(config: OrchestratorConfig):
eval_results = await asyncio.gather(
*[
eval_env.evaluate(
model_name=scheduler.model_name,
get_client=inference_pool.get_eval_client,
model_name=student_inference.model_name,
get_client=student_inference.get_eval_client,
ckpt_step=ckpt_step,
step=progress.step,
cache_salt=str(ckpt_step),
@@ -472,7 +469,7 @@ async def orchestrate(config: OrchestratorConfig):
)
# VLM: offload base64 images to disk immediately to free memory
if is_vlm:
if config.student.model.is_vlm:
offload_start = time.perf_counter()
num_offloaded = offload_images_to_disk(train_rollouts, config.output_dir)
if num_offloaded:
@@ -504,7 +501,7 @@ async def orchestrate(config: OrchestratorConfig):
)
)
if is_vlm:
if config.student.model.is_vlm:
mm_token_type_ids_mapping = {}
if hasattr(processor, "image_token_id") and processor.image_token_id is not None:
mm_token_type_ids_mapping[processor.image_token_id] = 1
@@ -554,8 +551,7 @@ async def orchestrate(config: OrchestratorConfig):
sample.advantage = rollout["advantage"]
sample.reward = rollout["reward"]
sample.env_name = rollout["env_name"]
if config.use_sft_loss:
sample.sft_loss = True
sample.training_mode = config.training_mode
sample_decode_tokens = sum(sample.completion_mask)
sample_prefill_tokens = len(sample.prompt_ids) + len(sample.completion_mask) - sample_decode_tokens
rollout_decode_tokens += sample_decode_tokens
@@ -573,14 +569,15 @@ async def orchestrate(config: OrchestratorConfig):
f"to {len(train_examples)} training examples"
)
# Compute teacher logprobs if teacher model is configured
# Compute teacher logprobs (opd only - sft trains on teacher tokens directly)
teacher_logprobs_time = 0
if config.teacher_model and teacher_inference_pool:
if config.training_mode == "opd" and teacher_inference is not None:
assert config.teacher is not None
logger.info(f"Computing teacher logprobs for {len(train_examples)} training examples")
teacher_logprobs_start_time = time.perf_counter()
teacher_logprobs_list = await compute_teacher_logprobs(
clients=teacher_inference_pool.train_clients,
model_name=config.teacher_model.model.name,
clients=teacher_inference.train_clients,
model_name=config.teacher.model.name,
samples=train_examples,
)
for train_example, teacher_logprobs in zip(train_examples, teacher_logprobs_list):
@@ -818,8 +815,8 @@ async def orchestrate(config: OrchestratorConfig):
eval_results = await asyncio.gather(
*[
eval_env.evaluate(
model_name=scheduler.model_name,
get_client=inference_pool.get_eval_client,
model_name=student_inference.model_name,
get_client=student_inference.get_eval_client,
ckpt_step=ckpt_step,
step=progress.step,
cache_salt=str(ckpt_step),
@@ -855,9 +852,9 @@ async def orchestrate(config: OrchestratorConfig):
await scheduler.stop()
if inference_metrics_collector is not None:
await inference_metrics_collector.stop()
await inference_pool.stop()
if teacher_inference_pool is not None:
await teacher_inference_pool.stop()
await student_inference.stop()
if teacher_inference is not None:
await teacher_inference.stop()
event_loop_lag_monitor_task.cancel()
# Shutdown env processes (also registered as atexit handler for crash safety)
train_envs.shutdown()
@@ -895,36 +892,27 @@ def main():
asyncio.run(orchestrate(cli(OrchestratorConfig)))
async def setup_rollout_inference_pool(
async def setup_student_inference_pool(
*,
config: OrchestratorConfig,
rollout_client_config,
rollout_model_name: str,
tokenizer,
logger,
):
"""Set up rollout inference.
"""Set up the student inference pool (rollouts when rl/opd, evals + weight sync always).
Routing policy is driven by ``config.use_renderer``:
- external teacher rollout → MITO (``openai_chat_completions``),
forced regardless of the toggle (config-level validator rejects
``use_renderer`` in that case)
- ``use_renderer=True`` → renderer-backed TITO client (``/v1/generate``).
Default for text-only rollouts. Not allowed for VLMs (validated at
config time).
- ``use_renderer=False`` → MITO (``openai_chat_completions``). VLMs
land here too.
Eval clients always use MITO. In sft mode ``use_renderer`` is forced off
by a config validator, so the student pool is plain MITO end-to-end.
"""
if config.teacher_rollout_model is not None:
logger.info("Using external rollout model (MITO) without renderer client")
inference_pool = await setup_inference_pool(
rollout_client_config,
model_name=rollout_model_name,
train_client_type="openai_chat_completions",
eval_client_type="openai_chat_completions",
)
return None, inference_pool
client_config = config.student.client
model_name = config.student.model.name
if config.use_renderer:
renderer = create_renderer(
@@ -935,10 +923,10 @@ async def setup_rollout_inference_pool(
preserve_all_thinking=config.renderer.preserve_all_thinking,
preserve_thinking_between_tool_calls=config.renderer.preserve_thinking_between_tool_calls,
)
logger.info(f"Initialized {type(renderer).__name__} for {config.model.name}")
logger.info(f"Initialized {type(renderer).__name__} for {model_name}")
inference_pool = await setup_inference_pool(
rollout_client_config,
model_name=rollout_model_name,
client_config,
model_name=model_name,
train_client_type="renderer",
eval_client_type="openai_chat_completions",
renderer_name=config.renderer.name,
@@ -953,8 +941,8 @@ async def setup_rollout_inference_pool(
logger.info("Using MITO (openai_chat_completions) for rollouts")
inference_pool = await setup_inference_pool(
rollout_client_config,
model_name=rollout_model_name,
client_config,
model_name=model_name,
train_client_type="openai_chat_completions",
eval_client_type="openai_chat_completions",
)
+32 -29
View File
@@ -73,7 +73,8 @@ class Scheduler:
def __init__(
self,
train_envs: TrainEnvs,
inference_pool: InferencePool,
student_inference: InferencePool,
teacher_inference: InferencePool | None,
buffer: Buffer,
config: OrchestratorConfig,
max_inflight_rollouts: int,
@@ -81,7 +82,6 @@ class Scheduler:
max_off_policy_steps: int,
strict_async_level: bool,
tasks_per_minute: int | None,
enable_policy_updates: bool = True,
lora_name: str | None = None,
):
self.logger = get_logger()
@@ -99,13 +99,21 @@ class Scheduler:
self.max_async_level = max_async_level
self.max_off_policy_steps = max_off_policy_steps
self.strict_async_level = strict_async_level
self.enable_policy_updates = enable_policy_updates
self.lora_name = lora_name
self.model_name = self.config.model.name
self.json_logging = config.log.json_logging
# Inference pool - used for admin operations (adapter sync) and metrics
self.inference_pool = inference_pool
# student_inference is the weight-sync target. teacher_inference is set
# in opd (for logprobs) and sft (for rollouts). rollout_inference is
# whichever pool serves train rollouts for this mode.
self.student_inference = student_inference
self.teacher_inference = teacher_inference
if config.training_mode == "sft":
assert teacher_inference is not None
self.rollout_inference = teacher_inference
else:
self.rollout_inference = student_inference
# model_name is the name to send on rollout requests - matches the rollout pool
self.model_name = self.rollout_inference.model_name
group_scoring_envs = [env.name for env in train_envs if env.requires_group_scoring]
if group_scoring_envs:
@@ -175,10 +183,10 @@ class Scheduler:
Uses (api_base_url, dp_rank) as identity rather than client_idx so that
load tracking survives elastic pool refreshes (which reassign indices).
"""
clients = self.inference_pool.train_clients
clients = self.rollout_inference.train_clients
while not clients:
await asyncio.sleep(1)
clients = self.inference_pool.train_clients
clients = self.rollout_inference.train_clients
inflight = Counter(self._client_identity(info.client_config) for info in self.inflight_requests.values())
return min(clients, key=lambda c: inflight[self._client_identity(c)])
@@ -320,14 +328,18 @@ class Scheduler:
update_weights_start_time = time.perf_counter()
weights_path = get_step_path(get_broadcast_dir(self.config.output_dir), next_ckpt_step)
await self.inference_pool.update_weights(weights_path, lora_name=self.lora_name, step=next_ckpt_step)
await self.student_inference.update_weights(weights_path, lora_name=self.lora_name, step=next_ckpt_step)
self.update_weights_time = time.perf_counter() - update_weights_start_time
self.logger.debug(f"Updated weights to step {next_ckpt_step} in {self.update_weights_time:.2f}s")
self.ckpt_step = next_ckpt_step
if self.lora_name is not None:
self.model_name = self.lora_name
self.inference_pool.update_model_name(self.model_name)
self.student_inference.update_model_name(self.lora_name)
# Only redirect rollout requests to the new LoRA when rollouts come from
# student inference (rl/opd). In sft, rollouts go to the teacher and
# the student's LoRA name is irrelevant to them.
if self.rollout_inference is self.student_inference:
self.model_name = self.lora_name
self.checkpoint_ready.set()
await self._update_off_policy()
@@ -350,11 +362,6 @@ class Scheduler:
async def maybe_update_policy(self):
"""Updates the policy to the latest available checkpoint. Aborts rollout requests that are older than the max retention steps."""
if not self.enable_policy_updates:
self.ckpt_step = self.step
self.checkpoint_ready.set()
return
while True:
next_ckpt_step = self._compute_next_ckpt_step()
if next_ckpt_step <= self.ckpt_step:
@@ -394,18 +401,14 @@ class Scheduler:
"""Continuously generates a batch of rollouts."""
self.step = step
if self.enable_policy_updates:
# Cancel the previous update policy task to avoid concurrent updates
if self.update_policy_task is not None:
await safe_cancel(self.update_policy_task)
# Cancel the previous update policy task to avoid concurrent updates
if self.update_policy_task is not None:
await safe_cancel(self.update_policy_task)
# Manually check the async barrier before starting the step, then re-create the update policy loop
# This ensures that we respect max_async_level, while still listening for policy updates mid-step
await self.maybe_update_policy()
self.update_policy_task = asyncio.create_task(self.update_policy_loop())
else:
self.ckpt_step = step
self.checkpoint_ready.set()
# Manually check the async barrier before starting the step, then re-create the update policy loop
# This ensures that we respect max_async_level, while still listening for policy updates mid-step
await self.maybe_update_policy()
self.update_policy_task = asyncio.create_task(self.update_policy_loop())
batch_start_time = time.perf_counter()
@@ -598,7 +601,7 @@ class Scheduler:
self.total_rollouts_by_env.clear()
self.dropped_groups_by_env.clear()
# Add inference pool metrics (e.g. elastic pool server counts)
metrics.update(self.inference_pool.get_metrics())
# Add train pool metrics (e.g. elastic pool server counts)
metrics.update(self.rollout_inference.get_metrics())
return metrics
-19
View File
@@ -11,7 +11,6 @@ from rich.console import Console
from rich.table import Table
from verifiers.utils.client_utils import setup_openai_client
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.transport import TrainingSample
from prime_rl.utils.logger import get_logger
from prime_rl.utils.utils import (
@@ -177,21 +176,3 @@ def get_weight_dir(output_dir: Path, step: int, check_exists: bool = True, wait_
return broadcast_weight_dir
raise FileNotFoundError(f"No weight directory found for checkpoint step {step}")
def setup_external_rollout_model(config: OrchestratorConfig, logger) -> tuple[Any, str, bool]:
"""Resolve rollout client/model and whether policy updates should be enabled."""
rollout_client_config = config.client
rollout_model_name = config.model.name
enable_policy_updates = True
if config.teacher_rollout_model is not None:
rollout_client_config = config.teacher_rollout_model.client
rollout_model_name = config.teacher_rollout_model.model.name
enable_policy_updates = False
logger.info(
f"Using external teacher rollout model (base_url={', '.join(rollout_client_config.base_url)}, "
f"model={rollout_model_name})"
)
return rollout_client_config, rollout_model_name, enable_policy_updates
+2 -2
View File
@@ -81,7 +81,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
pixel_values=training_example.pixel_values,
pixel_values_shape=training_example.pixel_values_shape,
image_grid_thw=training_example.image_grid_thw,
sft_loss=training_example.sft_loss,
training_mode=training_example.training_mode,
)
@@ -123,7 +123,7 @@ def packed_samples_into_micro_bs(
# Check if sequence fits in this bin
if (
len(bin_content.input_ids) + len(sample.input_ids) <= max_seq_len
and bin_content.sft_loss == sample.sft_loss
and bin_content.training_mode == sample.training_mode
):
bin_content.input_ids.extend(sample.input_ids)
bin_content.loss_mask.extend(sample.loss_mask)
@@ -78,7 +78,7 @@ class FileSystemWeightBroadcast(WeightBroadcast):
self.logger.debug(f"Saving weights for run {idx} to {save_dir}")
save_state_dict(state_dict, save_dir, self.save_format, self.save_sharded, adapter=adapter_only)
if adapter_only:
orch_lora = self.multi_run_manager.config[idx].model.lora
orch_lora = self.multi_run_manager.config[idx].student.model.lora
save_lora_config(
model,
save_dir,
+6 -5
View File
@@ -40,8 +40,9 @@ class TensorMicroBatch(TypedDict):
# mm_token_type_ids: token type per token [batch seq], int64 (0=text, 1=image, 2=video)
mm_token_type_ids: Int[Tensor, "batch seq"] | None
# When True, trainer uses SFT loss instead of RL loss for this batch
sft_loss: bool
# Selects loss dispatch (rl/opd → default loss with mode-specific taus,
# sft → sft loss). All samples in a micro batch share the same mode.
training_mode: str
class FakeDataLoader:
@@ -116,7 +117,7 @@ class FakeDataLoader:
"pixel_values": None,
"image_grid_thw": None,
"mm_token_type_ids": None,
"sft_loss": False,
"training_mode": "rl",
}
def _get_micro_batch(self, generator: torch.Generator) -> TensorMicroBatch:
@@ -144,7 +145,7 @@ class FakeDataLoader:
"pixel_values": None,
"image_grid_thw": None,
"mm_token_type_ids": None,
"sft_loss": False,
"training_mode": "rl",
}
@@ -227,5 +228,5 @@ class DataLoader:
) # [1, seq_len, layers, topk]
if micro_batch.routed_experts is not None
else None,
sft_loss=micro_batch.sft_loss,
training_mode=micro_batch.training_mode,
)
+89 -27
View File
@@ -6,7 +6,7 @@ from beartype import beartype as typechecker
from jaxtyping import Bool, Float, Int, jaxtyped
from torch import Tensor
from prime_rl.configs.trainer import CustomLossConfig, DefaultLossConfig, LossConfig, SFTLossConfig
from prime_rl.configs.trainer import CustomLossConfig, DefaultLossConfig, LossConfig
from prime_rl.utils.utils import import_object
@@ -115,7 +115,7 @@ def compute_importance_ratio_and_mismatch_kl(
def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossOutputs:
"""
DPPO+KL loss, combining:
DPPO+KL loss for RL training, combining:
- DPPO-Binary TV Loss (https://arxiv.org/pdf/2602.04879)
- Kimi-K2.5 KL Loss (https://arxiv.org/pdf/2602.02276)
@@ -127,7 +127,6 @@ def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossO
"""
trainer_logprobs = inputs.trainer_logprobs
inference_logprobs = inputs.inference_logprobs
teacher_logprobs = inputs.teacher_logprobs
advantages = inputs.advantages
loss_mask = inputs.loss_mask
@@ -149,12 +148,6 @@ def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossO
keep_mask = loss_mask & ~is_masked
advantages = loss_config.adv_tau * advantages
if teacher_logprobs is not None:
teacher_kl = teacher_logprobs - trainer_logprobs
advantages = advantages + loss_config.teacher_tau * teacher_kl.detach()
else:
teacher_kl = None
pg_loss = keep_mask * advantages * importance_ratio
kl_loss = loss_mask * log_importance_ratio**2
loss = (-pg_loss + loss_config.kl_tau * kl_loss).sum()
@@ -168,8 +161,59 @@ def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossO
"masked_advantage_positive": _safe_mean(positive_advantages, drop_mask),
"masked_advantage_negative": _safe_mean(negative_advantages, drop_mask),
}
if teacher_kl is not None:
metrics["teacher_kl"] = _safe_mean(teacher_kl, loss_mask)
return LossOutputs(loss=loss, metrics=metrics)
def opd_loss_fn(inputs: LossInputs) -> LossOutputs:
"""
On-policy distillation loss: the default DPPO+KL math with the tau knobs
hardcoded to drop the reward signal and use the teacher KL as the
per-token policy-gradient signal.
"""
trainer_logprobs = inputs.trainer_logprobs
inference_logprobs = inputs.inference_logprobs
teacher_logprobs = inputs.teacher_logprobs
advantages = inputs.advantages
loss_mask = inputs.loss_mask
if teacher_logprobs is None:
raise ValueError("opd_loss_fn requires teacher_logprobs - configure a teacher for opd mode.")
log_importance_ratio, importance_ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
trainer_logprobs, inference_logprobs
)
probs_diff = torch.exp(trainer_logprobs) - torch.exp(inference_logprobs)
dppo_invalid_mask_high = probs_diff > 0.2
dppo_invalid_mask_low = probs_diff < -0.2
positive_advantages = advantages > 0
negative_advantages = advantages < 0
dppo_invalid_mask = torch.where(positive_advantages, dppo_invalid_mask_high, dppo_invalid_mask_low)
is_masked = dppo_invalid_mask
is_masked_high = positive_advantages & dppo_invalid_mask_high
is_masked_low = negative_advantages & dppo_invalid_mask_low
drop_mask = loss_mask & is_masked
keep_mask = loss_mask & ~is_masked
teacher_kl = teacher_logprobs - trainer_logprobs
advantages = 0.0 * advantages + 1.0 * teacher_kl.detach()
pg_loss = keep_mask * advantages * importance_ratio
kl_loss = loss_mask * log_importance_ratio**2
loss = (-pg_loss + 1e-3 * kl_loss).sum()
metrics = {
"masked_mismatch_kl": _safe_mean(mismatch_kl, loss_mask & is_masked),
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask),
"is_masked": _safe_mean(is_masked, loss_mask),
"is_masked_low": _safe_mean(is_masked_low, loss_mask),
"is_masked_high": _safe_mean(is_masked_high, loss_mask),
"masked_advantage_positive": _safe_mean(positive_advantages, drop_mask),
"masked_advantage_negative": _safe_mean(negative_advantages, drop_mask),
"teacher_kl": _safe_mean(teacher_kl, loss_mask),
}
return LossOutputs(loss=loss, metrics=metrics)
@@ -186,24 +230,32 @@ def sft_loss_fn(inputs: LossInputs) -> LossOutputs:
return LossOutputs(loss=loss, metrics=metrics)
def setup_loss_fn(loss_config: LossConfig) -> LossFn:
"""Setup the loss function based on config."""
def setup_loss_fns(loss_config: LossConfig) -> dict[str, LossFn]:
"""Build the per-training-mode loss fn dispatch table.
Always returns all three modes - the trainer is mode-agnostic and routes
per batch from ``TrainingSample.training_mode``:
- ``"sft"`` → ``sft_loss_fn`` (masked NLL on teacher tokens)
- ``"opd"`` → ``opd_loss_fn`` (teacher KL as gradient signal, hardcoded
DPPO + KL knobs)
- ``"rl"`` → ``default_loss_fn(loss_config)`` for ``DefaultLossConfig``,
or the imported function for ``CustomLossConfig``.
``trainer.loss`` only affects the rl path - opd and sft are independent.
"""
if isinstance(loss_config, CustomLossConfig):
custom_fn = import_object(loss_config.import_path)
kwargs = loss_config.kwargs
def loss_fn(inputs: LossInputs) -> LossOutputs:
def rl_fn(inputs: LossInputs) -> LossOutputs:
return custom_fn(inputs, **kwargs)
else:
return loss_fn
def rl_fn(inputs: LossInputs) -> LossOutputs:
return default_loss_fn(inputs, loss_config)
if isinstance(loss_config, SFTLossConfig):
return sft_loss_fn
def loss_fn(inputs: LossInputs) -> LossOutputs:
return default_loss_fn(inputs, loss_config)
return loss_fn
return {"sft": sft_loss_fn, "opd": opd_loss_fn, "rl": rl_fn}
def compute_loss(
@@ -212,27 +264,37 @@ def compute_loss(
teacher_logprobs: list[Float[Tensor, " seq_i"]] | None,
advantages: list[Float[Tensor, " seq_i"]],
loss_mask: list[Bool[Tensor, " seq_i"]],
loss_fn: LossFn,
loss_fns: dict[str, LossFn],
loss_scale: int,
sft_loss: bool = False,
training_mode: str = "rl",
) -> tuple[Float[Tensor, ""], dict[str, Any]]:
"""
Compute loss for packed sequences (batch size = 1, multiple sequences packed along sequence dimension).
Loss dispatch is batch-driven: ``training_mode`` selects the loss fn from
``loss_fns`` (built by ``setup_loss_fns``). sft → sft_loss_fn, opd →
opd_loss_fn, rl → the configured default/custom loss.
Args:
trainer_logprobs: Log probabilities for each sequence
inference_logprobs: Reference log probabilities for each sequence
teacher_logprobs: Teacher log probabilities for each sequence, or None
advantages: Advantages for each sequence
loss_mask: Loss mask for each sequence
loss_fn: Per-sequence loss function
loss_fns: Per-mode loss fn dispatch table from setup_loss_fns()
loss_scale: Scale factor to normalize the loss
sft_loss: If True, use SFT loss instead of the configured loss_fn for this batch
training_mode: Selects which loss fn to apply
Returns:
Tuple of (scaled_loss, aggregated_metrics)
"""
effective_loss_fn = sft_loss_fn if sft_loss else loss_fn
try:
effective_loss_fn = loss_fns[training_mode]
except KeyError:
raise ValueError(
f"No loss fn available for training_mode={training_mode!r} "
f"(available: {sorted(loss_fns)}). Check trainer.loss.type."
)
total_loss = 0.0
all_metrics: dict[str, list[Tensor]] = {}
+6 -6
View File
@@ -31,7 +31,7 @@ from prime_rl.trainer.rl.loss import (
compute_loss,
compute_importance_ratio_and_mismatch_kl,
selective_log_softmax,
setup_loss_fn,
setup_loss_fns,
shift_tensor_left,
shift_tensor_right,
)
@@ -150,7 +150,7 @@ def train(config: TrainerConfig):
# Set up the loss function
logger.info(f"Setting up loss function ({config.loss})")
loss_fn = setup_loss_fn(config.loss)
loss_fns = setup_loss_fns(config.loss)
# Set up the optimizer
logger.info(f"Initializing optimizer ({config.optim})")
@@ -465,9 +465,9 @@ def train(config: TrainerConfig):
else None,
advantages=advantages.squeeze().split(response_lengths),
loss_mask=loss_mask.squeeze().split(response_lengths),
loss_fn=loss_fn,
loss_fns=loss_fns,
loss_scale=loss_scale,
sft_loss=micro_batch["sft_loss"],
training_mode=micro_batch["training_mode"],
)
# Backward pass
@@ -488,7 +488,7 @@ def train(config: TrainerConfig):
for env_name, indices in env_to_indices.items():
tensors[f"entropy/{env_name}"].append(entropy[indices])
if not micro_batch["sft_loss"]:
if micro_batch["training_mode"] != "sft":
with torch.no_grad():
_, _, mismatch_kl = compute_importance_ratio_and_mismatch_kl(out["logprobs"], inference_logprobs)
mismatch_kl = mismatch_kl[loss_mask].detach().to("cpu")
@@ -508,7 +508,7 @@ def train(config: TrainerConfig):
# Debug log with *local, micro step* stats
micro_step_message = f"Micro Step {micro_step}/{len(micro_batches)} | Loss: {tensors['loss'][-1].mean().item():.4f} | Entropy: {tensors['entropy/all'][-1].mean().item():.4f}"
if not micro_batch["sft_loss"]:
if micro_batch["training_mode"] != "sft":
micro_step_message += f" | Mismatch KL: {tensors['mismatch_kl/all'][-1].mean().item():.4f}"
if "max_vio" in tensors:
micro_step_message += f" | Max Vio: {tensors['max_vio'][-1].mean().item():.4f}"
+9 -7
View File
@@ -511,19 +511,21 @@ def setup_multi_run_manager(
def validate_lora_rank(orch_config: "OrchestratorConfig") -> tuple[bool, str]:
# Default to trainer's rank/alpha if not specified
if orch_config.model.lora.rank is None:
orch_config.model.lora.rank = trainer_lora.rank
if orch_config.model.lora.alpha is None:
orch_config.model.lora.alpha = trainer_lora.alpha
if orch_config.model.lora.rank > trainer_lora.rank:
if orch_config.student.model.lora.rank is None:
orch_config.student.model.lora.rank = trainer_lora.rank
if orch_config.student.model.lora.alpha is None:
orch_config.student.model.lora.alpha = trainer_lora.alpha
if orch_config.student.model.lora.rank > trainer_lora.rank:
return (
False,
f"model.lora.rank ({orch_config.model.lora.rank}) exceeds trainer max rank ({trainer_lora.rank})",
f"student.model.lora.rank ({orch_config.student.model.lora.rank}) exceeds trainer max rank ({trainer_lora.rank})",
)
return True, ""
def on_run_discovered(idx: int, run_id: str, orch_config: "OrchestratorConfig") -> None:
_MULTI_RUN_MANAGER.scaling_factors[idx] = orch_config.model.lora.alpha / orch_config.model.lora.rank
_MULTI_RUN_MANAGER.scaling_factors[idx] = (
orch_config.student.model.lora.alpha / orch_config.student.model.lora.rank
)
_MULTI_RUN_MANAGER.register_config_validation_hook(validate_lora_rank)
_MULTI_RUN_MANAGER.register_discovered_hook(on_run_discovered)
+10 -2
View File
@@ -1,5 +1,9 @@
from typing import Literal
import msgspec
TrainingMode = Literal["rl", "opd", "sft"]
# Orchestrator -> Packer
class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
@@ -27,7 +31,9 @@ class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=Tr
# mm_token_type_ids: token type ids per token [batch seq], int64 (0=text, 1=image, 2=video)
mm_token_type_ids: list[int] | None = None
sft_loss: bool = False # When True, trainer uses SFT loss instead of RL loss for this sample
# Loss dispatch is batch-driven: rl/opd use default_loss_fn (with mode-specific
# taus), sft uses sft_loss_fn. Stamped by the orchestrator from training_mode.
training_mode: TrainingMode = "rl"
class TrainingBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
@@ -61,4 +67,6 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
# mm_token_type_ids: token type ids per token [batch seq], int64 (0=text, 1=image, 2=video)
mm_token_type_ids: list[int] | None = None
sft_loss: bool = False # When True, trainer uses SFT loss instead of RL loss for this batch
# Loss dispatch is batch-driven (rl/opd → default loss with mode-specific taus,
# sft → sft loss). All samples packed into a micro batch share the same mode.
training_mode: TrainingMode = "rl"
+13 -9
View File
@@ -20,6 +20,11 @@ from prime_rl.utils.logger import get_logger
class InferencePool(Protocol):
"""Protocol for inference pools (static or elastic)."""
@property
def model_name(self) -> str:
"""Get current model name for inference requests."""
...
@property
def train_clients(self) -> list[vf.ClientConfig]:
"""Get inference clients."""
@@ -137,8 +142,6 @@ async def setup_inference_pool(
preserve_thinking_between_tool_calls: bool = False,
) -> InferencePool:
"""Create an inference pool from config (static or elastic)."""
logger = get_logger()
if client_config.is_elastic:
from prime_rl.utils.elastic import ElasticInferencePool
@@ -155,11 +158,6 @@ async def setup_inference_pool(
preserve_thinking_between_tool_calls=preserve_thinking_between_tool_calls,
)
logger.info(
f"Initializing static inference pool (base_url={', '.join(client_config.base_url)}, "
f"dp_rank_count={client_config.dp_rank_count}, "
f"api_key_var={client_config.api_key_var}, headers={client_config.headers})"
)
return StaticInferencePool(
client_config,
model_name=model_name,
@@ -196,9 +194,12 @@ def setup_clients(
"preserve_all_thinking": preserve_all_thinking,
"preserve_thinking_between_tool_calls": preserve_thinking_between_tool_calls,
}
env_headers = {
k: v for k, v in ((k, os.getenv(v)) for k, v in client_config.headers_from_env.items()) if v is not None
}
for base_url in client_config.base_url:
for dp_rank in range(client_config.dp_rank_count):
headers = client_config.headers.copy()
headers = {**client_config.headers, **env_headers}
if client_config.dp_rank_count > 1:
headers["X-data-parallel-rank"] = str(dp_rank)
clients.append(
@@ -236,7 +237,10 @@ def setup_admin_clients(client_config: ClientConfig) -> list[AsyncClient]:
urls = client_config.admin_base_url if client_config.admin_base_url else client_config.base_url
def _setup_admin_client(base_url: str) -> httpx.AsyncClient:
headers = client_config.headers.copy() # avoid mutating config
env_headers = {
k: v for k, v in ((k, os.getenv(v)) for k, v in client_config.headers_from_env.items()) if v is not None
}
headers = {**client_config.headers, **env_headers}
api_key = os.getenv(client_config.api_key_var, "EMPTY")
if api_key and api_key != "EMPTY":
headers["Authorization"] = f"Bearer {api_key}"
+2
View File
@@ -210,6 +210,7 @@ class ElasticInferencePool:
base_url=urls,
api_key_var=self.client_config.api_key_var,
headers=self.client_config.headers,
headers_from_env=self.client_config.headers_from_env,
dp_rank_count=self.client_config.dp_rank_count,
extra_headers_from_state=self.client_config.extra_headers_from_state,
)
@@ -267,6 +268,7 @@ class ElasticInferencePool:
base_url=[f"{url}/v1"],
api_key_var=self.client_config.api_key_var,
headers=self.client_config.headers,
headers_from_env=self.client_config.headers_from_env,
)
return setup_admin_clients(config)[0]
-1
View File
@@ -134,7 +134,6 @@ class PrimeMonitor(Monitor):
return
assert config is not None
self.logger.info(f"Initializing {self.__class__.__name__} ({config})")
api_key = os.getenv(config.api_key_var)
if api_key is None:
-1
View File
@@ -44,7 +44,6 @@ class WandbMonitor(Monitor):
return
assert config is not None
self.logger.info(f"Initializing {self.__class__.__name__} ({config})")
self._maybe_overwrite_wandb_command()
# WANDB_MODE=disabled/offline takes precedence over shared mode — shared mode
@@ -205,14 +205,14 @@ def start_orchestrator(
run_dir.as_posix(),
"--max-steps",
str(max_steps),
"--model.lora.name",
"--student.model.lora.name",
name,
"--wandb.project",
wandb_project,
"--wandb.name",
f"{wandb_name}-{proc_name}",
]
cmd.append("--client.base-url")
cmd.append("--student.client.base-url")
cmd.extend(INFERENCE_BASE_URLS)
with open(orch_log_dir / "orchestrator.log", "w") as f:
@@ -0,0 +1,118 @@
from types import SimpleNamespace
import torch
import prime_rl.inference.vllm.padded_input_scrub as padded_input_scrub
from prime_rl.inference.vllm.padded_input_scrub import (
_zero_padded_model_inputs,
monkey_patch_vllm_padded_input_scrub,
)
def test_monkey_patch_preprocess_matches_vllm_preprocess_signature(monkeypatch):
from vllm.v1.worker.gpu_model_runner import GPUModelRunner
calls = {}
def fake_preprocess(
self,
scheduler_output,
num_input_tokens,
intermediate_tensors=None,
):
calls["args"] = (
self,
scheduler_output,
num_input_tokens,
intermediate_tensors,
)
return (
torch.tensor([10, 11, 12, 991, 992]),
None,
torch.tensor([0, 1, 2, 991, 992]),
intermediate_tensors,
{},
None,
)
monkeypatch.setattr(padded_input_scrub, "_INSTALLED", False)
monkeypatch.setattr(GPUModelRunner, "_preprocess", fake_preprocess)
monkeypatch.setattr(
GPUModelRunner,
"_prime_rl_padded_input_scrub",
False,
raising=False,
)
monkey_patch_vllm_padded_input_scrub()
self = object()
scheduler_output = SimpleNamespace(total_num_scheduled_tokens=3)
intermediate_tensors = object()
result = GPUModelRunner._preprocess(self, scheduler_output, 5, intermediate_tensors)
assert calls["args"] == (
self,
scheduler_output,
5,
intermediate_tensors,
)
assert result[0].tolist() == [10, 11, 12, 0, 0]
assert result[2].tolist() == [0, 1, 2, 0, 0]
def test_zero_padded_model_inputs_leaves_scheduled_prefix_intact():
input_ids = torch.tensor([10, 11, 12, 991, 992])
positions = torch.tensor([0, 1, 2, 991, 992])
preprocess_result = (input_ids, None, positions, None, {}, None)
_zero_padded_model_inputs(
preprocess_result,
num_scheduled_tokens=3,
num_input_tokens=5,
)
assert input_ids.tolist() == [10, 11, 12, 0, 0]
assert positions.tolist() == [0, 1, 2, 0, 0]
def test_zero_padded_model_inputs_zeroes_embeddings_and_mrope_positions():
inputs_embeds = torch.ones((5, 4))
inputs_embeds[3:] = 7
positions = torch.tensor(
[
[0, 1, 2, 991, 992],
[0, 1, 2, 993, 994],
[0, 1, 2, 995, 996],
]
)
preprocess_result = (None, inputs_embeds, positions, None, {}, None)
_zero_padded_model_inputs(
preprocess_result,
num_scheduled_tokens=3,
num_input_tokens=5,
)
torch.testing.assert_close(inputs_embeds[:3], torch.ones((3, 4)))
torch.testing.assert_close(inputs_embeds[3:], torch.zeros((2, 4)))
assert positions.tolist() == [
[0, 1, 2, 0, 0],
[0, 1, 2, 0, 0],
[0, 1, 2, 0, 0],
]
def test_zero_padded_model_inputs_noops_without_padding():
input_ids = torch.tensor([10, 11, 12])
positions = torch.tensor([0, 1, 2])
preprocess_result = (input_ids, None, positions, None, {}, None)
_zero_padded_model_inputs(
preprocess_result,
num_scheduled_tokens=3,
num_input_tokens=3,
)
assert input_ids.tolist() == [10, 11, 12]
assert positions.tolist() == [0, 1, 2]
+9 -9
View File
@@ -8,7 +8,7 @@ from prime_rl.transport.types import TrainingSample
def make_training_example():
def _make_training_example(
temperature: float = 1.0,
sft_loss: bool = False,
training_mode: str = "rl",
env_name: str = "test-env",
) -> TrainingSample:
return TrainingSample(
@@ -21,7 +21,7 @@ def make_training_example():
teacher_logprobs=[0.0, 0.0, 0.0, 0.0],
advantage=1.0,
env_name=env_name,
sft_loss=sft_loss,
training_mode=training_mode,
)
return _make_training_example
@@ -99,17 +99,17 @@ def test_prepare_batch_packs_different_temperatures(make_training_example):
assert flat_batches[0].env_names == ["env-a"] * 4 + ["env-b"] * 4
def test_prepare_sample_propagates_sft_loss(make_training_example):
example = make_training_example(sft_loss=True)
def test_prepare_sample_propagates_training_mode(make_training_example):
example = make_training_example(training_mode="sft")
micro_batch = prepare_sample(example, seq_len=16)
assert micro_batch.sft_loss is True
assert micro_batch.training_mode == "sft"
def test_prepare_batch_does_not_pack_mixed_sft_loss(make_training_example):
rl_example = make_training_example(sft_loss=False)
sft_example = make_training_example(sft_loss=True)
def test_prepare_batch_does_not_pack_mixed_training_mode(make_training_example):
rl_example = make_training_example(training_mode="rl")
sft_example = make_training_example(training_mode="sft")
batches_per_gpu = prepare_batch(
rollouts=[rl_example, sft_example],
@@ -121,7 +121,7 @@ def test_prepare_batch_does_not_pack_mixed_sft_loss(make_training_example):
flat_batches = [batch for worker_batches in batches_per_gpu for batch in worker_batches]
assert len(flat_batches) == 2
assert {batch.sft_loss for batch in flat_batches} == {False, True}
assert {batch.training_mode for batch in flat_batches} == {"rl", "sft"}
def test_prepare_sample_with_routed_experts():
@@ -2,48 +2,19 @@ import asyncio
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
from prime_rl.orchestrator.orchestrator import setup_rollout_inference_pool
from prime_rl.orchestrator.orchestrator import setup_student_inference_pool
def test_setup_rollout_inference_pool_uses_plain_client_for_external_teacher_rollout():
def test_setup_student_inference_pool_uses_renderer_when_enabled():
async def run() -> None:
tokenizer = object()
config = SimpleNamespace(
teacher_rollout_model=SimpleNamespace(),
model=SimpleNamespace(renderer="auto", name="student-model"),
)
rollout_client_config = SimpleNamespace(base_url=["https://api.pinference.ai/api/v1"])
logger = MagicMock()
inference_pool = object()
with (
patch(
"prime_rl.orchestrator.orchestrator.setup_inference_pool", new=AsyncMock(return_value=inference_pool)
),
patch("prime_rl.orchestrator.orchestrator.create_renderer") as create_renderer_mock,
):
renderer, returned_pool = await setup_rollout_inference_pool(
config=config,
rollout_client_config=rollout_client_config,
rollout_model_name="teacher-model",
tokenizer=tokenizer,
logger=logger,
)
assert renderer is None
assert returned_pool is inference_pool
create_renderer_mock.assert_not_called()
asyncio.run(run())
def test_setup_rollout_inference_pool_uses_direct_renderer_client_for_local_vllm():
async def run() -> None:
tokenizer = object()
config = SimpleNamespace(
teacher_rollout_model=None,
training_mode="rl",
use_renderer=True,
model=SimpleNamespace(name="student-model"),
student=SimpleNamespace(
client=SimpleNamespace(base_url=["http://localhost:8000/v1"]),
model=SimpleNamespace(name="student-model"),
),
renderer=SimpleNamespace(
name="qwen3_vl",
tool_parser=None,
@@ -53,7 +24,6 @@ def test_setup_rollout_inference_pool_uses_direct_renderer_client_for_local_vllm
preserve_thinking_between_tool_calls=False,
),
)
rollout_client_config = SimpleNamespace(base_url=["http://localhost:8000/v1"])
logger = MagicMock()
renderer = object()
inference_pool = object()
@@ -65,10 +35,8 @@ def test_setup_rollout_inference_pool_uses_direct_renderer_client_for_local_vllm
new=AsyncMock(return_value=inference_pool),
) as setup_pool_mock,
):
returned_renderer, returned_pool = await setup_rollout_inference_pool(
returned_renderer, returned_pool = await setup_student_inference_pool(
config=config,
rollout_client_config=rollout_client_config,
rollout_model_name="student-model",
tokenizer=tokenizer,
logger=logger,
)
@@ -84,7 +52,7 @@ def test_setup_rollout_inference_pool_uses_direct_renderer_client_for_local_vllm
preserve_thinking_between_tool_calls=False,
)
setup_pool_mock.assert_awaited_once_with(
rollout_client_config,
config.student.client,
model_name="student-model",
train_client_type="renderer",
eval_client_type="openai_chat_completions",
@@ -97,3 +65,45 @@ def test_setup_rollout_inference_pool_uses_direct_renderer_client_for_local_vllm
)
asyncio.run(run())
def test_setup_student_inference_pool_defaults_to_mito():
"""No renderer -> plain MITO chat completions."""
async def run() -> None:
tokenizer = object()
config = SimpleNamespace(
training_mode="rl",
use_renderer=False,
student=SimpleNamespace(
client=SimpleNamespace(base_url=["http://localhost:8000/v1"]),
model=SimpleNamespace(name="student-model"),
),
)
logger = MagicMock()
inference_pool = object()
with (
patch("prime_rl.orchestrator.orchestrator.create_renderer") as create_renderer_mock,
patch(
"prime_rl.orchestrator.orchestrator.setup_inference_pool",
new=AsyncMock(return_value=inference_pool),
) as setup_pool_mock,
):
renderer, returned_pool = await setup_student_inference_pool(
config=config,
tokenizer=tokenizer,
logger=logger,
)
assert renderer is None
assert returned_pool is inference_pool
create_renderer_mock.assert_not_called()
setup_pool_mock.assert_awaited_once_with(
config.student.client,
model_name="student-model",
train_client_type="openai_chat_completions",
eval_client_type="openai_chat_completions",
)
asyncio.run(run())
+102 -4
View File
@@ -5,7 +5,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import verifiers as vf
from prime_rl.orchestrator.scheduler import InflightRequest, Scheduler
from prime_rl.orchestrator.scheduler import GroupState, InflightRequest, Scheduler
from prime_rl.utils.async_utils import safe_cancel
@@ -30,7 +30,7 @@ def make_scheduler() -> Scheduler:
scheduler.policy_update_lock = asyncio.Lock()
scheduler.inflight_policy_update_task = None
scheduler.update_policy_task = None
scheduler.enable_policy_updates = True
scheduler.rate_limiter = None
return scheduler
@@ -102,10 +102,11 @@ def test_maybe_update_policy_reuses_inflight_update_after_cancellation():
started.set()
await release.wait()
scheduler.inference_pool = SimpleNamespace(
scheduler.student_inference = SimpleNamespace(
update_weights=update_weights,
update_model_name=MagicMock(),
)
scheduler.rollout_inference = scheduler.student_inference
scheduler._update_off_policy = AsyncMock()
with (
@@ -142,10 +143,11 @@ def test_stop_cancels_inflight_policy_update_task():
finally:
cancelled.set()
scheduler.inference_pool = SimpleNamespace(
scheduler.student_inference = SimpleNamespace(
update_weights=update_weights,
update_model_name=MagicMock(),
)
scheduler.rollout_inference = scheduler.student_inference
scheduler._update_off_policy = AsyncMock()
with (
@@ -174,3 +176,99 @@ def test_client_identity_distinguishes_base_url_and_dp_rank():
)
assert Scheduler._client_identity(client_a) != Scheduler._client_identity(client_b)
def test_lora_policy_update_in_sft_keeps_teacher_model_name():
"""In sft mode, train_pool is the teacher. LoRA updates the student inference
pool but must not change scheduler.model_name (which is what gets sent to the
teacher endpoint on each rollout request)."""
async def run() -> None:
scheduler = make_scheduler()
scheduler.model_name = "teacher-model"
scheduler.lora_name = "student-lora"
student_inference = SimpleNamespace(
update_weights=AsyncMock(),
update_model_name=MagicMock(),
)
teacher_inference = SimpleNamespace()
scheduler.student_inference = student_inference
scheduler.rollout_inference = teacher_inference # sft: train_pool != student_inference
scheduler._update_off_policy = AsyncMock()
with (
patch("prime_rl.orchestrator.scheduler.get_latest_ckpt_step", return_value=8),
patch("prime_rl.orchestrator.scheduler.wait_for_path", new=AsyncMock()),
):
await scheduler.maybe_update_policy()
student_inference.update_weights.assert_awaited_once()
student_inference.update_model_name.assert_called_once_with("student-lora")
assert scheduler.model_name == "teacher-model"
asyncio.run(run())
def test_lora_policy_update_in_rl_updates_model_name():
"""In rl/opd mode, train_pool is the student. LoRA updates redirect rollout
requests to the new LoRA name."""
async def run() -> None:
scheduler = make_scheduler()
scheduler.model_name = "student-model"
scheduler.lora_name = "student-lora"
student_inference = SimpleNamespace(
update_weights=AsyncMock(),
update_model_name=MagicMock(),
)
scheduler.student_inference = student_inference
scheduler.rollout_inference = student_inference # rl/opd: same pool
scheduler._update_off_policy = AsyncMock()
with (
patch("prime_rl.orchestrator.scheduler.get_latest_ckpt_step", return_value=8),
patch("prime_rl.orchestrator.scheduler.wait_for_path", new=AsyncMock()),
):
await scheduler.maybe_update_policy()
student_inference.update_weights.assert_awaited_once()
student_inference.update_model_name.assert_called_once_with("student-lora")
assert scheduler.model_name == "student-lora"
asyncio.run(run())
def test_schedule_rollout_uses_train_pool():
"""schedule_rollout dispatches to train_pool's clients with train_pool's model name."""
async def run() -> None:
scheduler = make_scheduler()
scheduler.model_name = "teacher-model"
teacher_client = vf.ClientConfig(api_base_url="http://teacher.example/v1")
env = SimpleNamespace(
requires_group_scoring=False,
run_rollout=AsyncMock(return_value=[]),
)
scheduler.rollout_inference = SimpleNamespace(train_clients=[teacher_client])
scheduler.train_envs = SimpleNamespace(get=MagicMock(return_value=env))
scheduler.groups = {
0: GroupState(
example={"env_name": "math", "example_id": "ex-1"},
rollouts_to_schedule=1,
)
}
await scheduler.schedule_rollout(group_id=0)
await asyncio.gather(*scheduler.inflight_requests)
env.run_rollout.assert_awaited_once_with(
client=teacher_client,
example={"env_name": "math", "example_id": "ex-1"},
model_name="teacher-model",
cache_salt="7",
)
assert scheduler.groups[0].pinned_client is teacher_client
asyncio.run(run())
+12 -8
View File
@@ -161,10 +161,12 @@ def test_orchestrator_vlm_configs_must_disable_renderer():
with pytest.raises(ValidationError, match="orchestrator.use_renderer is not supported for VLMs"):
OrchestratorConfig.model_validate(
{
"model": {
"vlm": {
"vision_encoder_attr": "model.visual",
"language_model_attr": "model.language_model",
"student": {
"model": {
"vlm": {
"vision_encoder_attr": "model.visual",
"language_model_attr": "model.language_model",
}
}
}
}
@@ -172,10 +174,12 @@ def test_orchestrator_vlm_configs_must_disable_renderer():
config = OrchestratorConfig.model_validate(
{
"model": {
"vlm": {
"vision_encoder_attr": "model.visual",
"language_model_attr": "model.language_model",
"student": {
"model": {
"vlm": {
"vision_encoder_attr": "model.visual",
"language_model_attr": "model.language_model",
}
}
},
"use_renderer": False,
+16 -15
View File
@@ -1,8 +1,8 @@
import pytest
import torch
from prime_rl.configs.trainer import CustomLossConfig, DefaultLossConfig, SFTLossConfig
from prime_rl.trainer.rl.loss import LossInputs, LossOutputs, compute_entropy, compute_loss, setup_loss_fn
from prime_rl.configs.trainer import CustomLossConfig, DefaultLossConfig
from prime_rl.trainer.rl.loss import LossInputs, LossOutputs, compute_entropy, compute_loss, setup_loss_fns
pytestmark = [pytest.mark.gpu]
@@ -14,14 +14,14 @@ def test_grpo_loss():
advantages = [torch.randn(50).cuda(), torch.randn(30).cuda()]
loss_mask = [torch.ones(50, dtype=torch.bool).cuda(), torch.ones(30, dtype=torch.bool).cuda()]
loss_fn = setup_loss_fn(DefaultLossConfig(dppo_mask_high=10.0))
loss_fns = setup_loss_fns(DefaultLossConfig(dppo_mask_high=10.0))
loss, _ = compute_loss(
trainer_logprobs,
inference_logprobs,
teacher_logprobs,
advantages,
loss_mask=loss_mask,
loss_fn=loss_fn,
loss_fns=loss_fns,
loss_scale=1.0,
)
assert loss.shape == ()
@@ -34,14 +34,14 @@ def test_gspo_loss():
advantages = [torch.randn(40).cuda(), torch.randn(60).cuda()]
loss_mask = [torch.ones(40, dtype=torch.bool).cuda(), torch.ones(60, dtype=torch.bool).cuda()]
loss_fn = setup_loss_fn(DefaultLossConfig(dppo_mask_high=10.0))
loss_fns = setup_loss_fns(DefaultLossConfig(dppo_mask_high=10.0))
loss, _ = compute_loss(
trainer_logprobs,
inference_logprobs,
teacher_logprobs,
advantages,
loss_mask=loss_mask,
loss_fn=loss_fn,
loss_fns=loss_fns,
loss_scale=1.0,
)
assert loss.shape == ()
@@ -53,13 +53,13 @@ def test_entropy_loss():
assert entropy.shape == (10, 10)
def test_setup_loss_fn_with_custom_config():
"""Test setup_loss_fn with CustomLossConfig importing a custom loss."""
def test_setup_loss_fns_with_custom_config():
"""Test setup_loss_fns with CustomLossConfig importing a custom loss."""
loss_config = CustomLossConfig(
import_path="tests.unit.train.rl.test_loss._dummy_custom_loss",
kwargs={"multiplier": 2.0},
)
loss_fn = setup_loss_fn(loss_config)
loss_fns = setup_loss_fns(loss_config)
inputs = LossInputs(
trainer_logprobs=torch.randn(50, dtype=torch.float32).cuda(),
@@ -69,7 +69,7 @@ def test_setup_loss_fn_with_custom_config():
loss_mask=torch.ones(50, dtype=torch.bool).cuda(),
)
result = loss_fn(inputs)
result = loss_fns["rl"](inputs)
assert isinstance(result, LossOutputs)
assert result.loss.shape == ()
assert "custom_metric" in result.metrics
@@ -81,15 +81,16 @@ def test_sft_loss_matches_masked_nll():
advantages = [torch.zeros(3, dtype=torch.float32).cuda()]
loss_mask = [torch.tensor([True, False, True], dtype=torch.bool).cuda()]
loss_fn = setup_loss_fn(SFTLossConfig())
loss_fns = setup_loss_fns(DefaultLossConfig())
loss, metrics = compute_loss(
trainer_logprobs=trainer_logprobs,
inference_logprobs=inference_logprobs,
teacher_logprobs=None,
advantages=advantages,
loss_mask=loss_mask,
loss_fn=loss_fn,
loss_fns=loss_fns,
loss_scale=2,
training_mode="sft",
)
# loss = -sum(masked logprobs) / loss_scale = -(-0.1 - 0.2) / 2 = 0.15
@@ -103,16 +104,16 @@ def test_sft_loss_override_uses_masked_nll_with_default_loss_config():
advantages = [torch.ones(3, dtype=torch.float32).cuda()]
loss_mask = [torch.tensor([True, False, True], dtype=torch.bool).cuda()]
loss_fn = setup_loss_fn(DefaultLossConfig())
loss_fns = setup_loss_fns(DefaultLossConfig())
loss, metrics = compute_loss(
trainer_logprobs=trainer_logprobs,
inference_logprobs=inference_logprobs,
teacher_logprobs=None,
advantages=advantages,
loss_mask=loss_mask,
loss_fn=loss_fn,
loss_fns=loss_fns,
loss_scale=2,
sft_loss=True,
training_mode="sft",
)
assert torch.isclose(loss, torch.tensor(0.15, device=loss.device), atol=1e-6)
+1 -1
View File
@@ -217,7 +217,7 @@ def test_config_loading(tmp_path: Path) -> None:
# Access config as OrchestratorConfig object
config = multi_run_manager.config[run_idx]
assert config.model.name == "test-model"
assert config.student.model.name == "test-model"
assert config.batch_size == 32
assert config.max_steps == 1000
+1
View File
@@ -415,6 +415,7 @@ def test_elastic_clients_preserve_renderer_model_name_when_model_name_updates():
client_config.connect_timeout = 30.0
client_config.api_key_var = "PRIME_API_KEY"
client_config.headers = {}
client_config.headers_from_env = {}
client_config.extra_headers_from_state = {}
client_config.dp_rank_count = 1