Compare commits

...
15 Commits
Author SHA1 Message Date
carsten 6087c3addb Add LoRA adapter warm start and longer adapter reload timeouts
- model.lora.init_path on trainer and orchestrator initializes a fresh
  optimizer run from an attention-only PEFT adapter (strict shape, key,
  and finiteness checks).
- Adapter reload read timeout 30s -> 300s and retry budget 120s -> 600s;
  loaded TP2/DP3 servers can take minutes to apply an update.
2026-10-14 12:24:08 +00:00
carsten 99957ccd93 Point renderers submodule at dphn/renderers trinity branch
Pulls in the text-level Hermes tool-call parser Trinity needs.
2026-10-14 12:24:08 +00:00
JannikStandGitHub 31ff561df6 feat(ci): allow pinning prime-rl image_tag on nightly-fft dispatch (#3132)
* feat(ci): allow pinning prime-rl image_tag on nightly-fft dispatch

Adds an optional image_tag workflow_dispatch input. Empty (default)
keeps the existing auto-resolve behavior (newest v*.dev* with a
published manifest). Non-empty pins the tag directly, after verifying
the manifest is pullable.

* fix(ci): sanitize image_tag input to avoid shell injection

Move the workflow_dispatch input through a step env var so a
malicious value containing $(...) or embedded quotes cannot break
out of shell context during expression substitution. Validate the
result against the OCI/Docker tag charset before curl or GITHUB_OUTPUT
sees it.
2026-07-24 02:53:43 +02:00
JannikStandGitHub dea7707526 fix(nightly-fft): pin hendrycks attn to flash_attention_2 (#3131)
DeepSeek-R1-Distill-Qwen-1.5B is Qwen2 arch, not in prime-rl's
custom-impl support list, so impl='auto' resolves to 'hf'. The
platform default attn='flash_attention_3' requires impl='custom',
which raises ValueError and the trainer crash-loops. Pin attn to
fa2 (works with hf impl on H200).
2026-07-24 02:10:21 +02:00
fca9fb0975 fix(examples): set cp=4 for GLM-4.5-Air advanced examples (#3129)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 16:50:46 -07:00
JannikStandGitHub 1dcec737d9 ci(nightly-fft): add alphabet-sort, reverse-text, wiki-search, hendrycks-sanity (#3127)
* ci(nightly-fft): add alphabet-sort, reverse-text, wiki-search, hendrycks-sanity, multimodal configs

Broaden nightly-fft coverage beyond wordle. Each config mirrors wordle's
2 train + 6 infer shape and pulls model/taskset/renderer from the
corresponding configs/basic/*/rl.toml.

- multimodal-color-codeword moved from configs/ci/nightly/ (its pytest
  path updated); nightly/ is now empty
- hendrycks-sanity trimmed from 5000 -> 200 steps to fit the nightly
  budget
- wiki-search carries tool_call_parser = 'hermes' for tool use

* ci(nightly-fft): revert multimodal move; restore hendrycks max_steps=5000

* ci(nightly-fft): size deployments per env; add zero-advantage filter to wiki-search

- reverse-text: 1+1 GPUs, batch 128 (was 2+6/512 — overkill for a 0.6B toy loop)
- alphabet-sort: 4+4 GPUs (was 2+6 — 4B FFT needs more trainer memory)
- wiki-search: 4+4 GPUs; adds oversampling_factor=2.0 + zero_advantage
  pre-batch filter mirroring examples/basic/wiki-search — without them sparse
  tool rewards fill batches with all-zero groups and abort the run

* test(nightly): remove LoRA alphabet-sort and wiki-search — covered by FFT nightly workflow

* ci(nightly-fft): align hendrycks-sanity with examples/basic upstream

- drop max_completion_tokens=1024 cap so R1-Distill can produce full CoT
- group_size 16 -> 8, GPUs 2+6 -> 4+4 (upstream)
- add trainer.model.seq_len=16384 for long-context training
- add aime2024 eval block (interval=50, group_size=32)

* fix(nightly-fft): move seq_len under [orchestrator] in hendrycks-sanity

RLConfig rejects setting shared top-level seq_len alongside
trainer.model.seq_len. Mirror examples/basic/hendrycks-sanity/rl.toml:
seq_len=8192 under [orchestrator] for rollout context, seq_len=16384
under [trainer.model] for long-context training.

* revert(nightly): restore test_alphabet_sort and test_wiki_search — keep tests/nightly/ untouched
2026-07-24 01:18:33 +02:00
JannikStandGitHub 43c2905243 ci(nightly-fft): name RFTRun nightly-<config>-<date>-<run_id>; verify GHCR manifest exists before dispatch (#3121) 2026-07-24 00:32:29 +02:00
minh hoangandGitHub 54307fc301 fix(ci): build ghcr image on release via explicit dispatch (#3125)
Releases are published with GITHUB_TOKEN, whose events do not retrigger
workflows, so build_image.yaml's `on: release` trigger never fired and
release commits never received a GHCR image. Dispatch build_image.yaml
explicitly from tag-and-release.yaml after publishing (workflow_dispatch
is exempt from the no-retrigger rule), and drop the now-dead `on: release`
trigger plus its unreachable github.event.release.* references.
2026-07-23 14:27:49 -07:00
JannikStandGitHub 069e580c78 fix(trainer): skip identity HF↔PrimeRL conversion (fixes RO model-cache crash on dense Qwen3) (#3124)
* fix(trainer): skip identity HF↔PrimeRL conversion to avoid RO-cache write

* chore: ruff format

* refactor: drop inline explanation; gate branches on unambiguous snapshot format
2026-07-23 21:11:49 +02:00
samsjaandGitHub 45488ca048 fix(trainer): skip no-op weight conversion for dense models (#3069)
Dense models (Qwen3, Qwen3.5, Llama) use identical key names in both
HF and PrimeRL weight formats, so is_hf_state_dict and is_prime_state_dict
both returned True for the same state dict. The auto-conversion logic in
load_dcp_from_hf would fire anyway, performing a no-op convert and
attempting to save the unchanged weights into the snapshot directory —
which crashes with OSError [Errno 30] Read-only file system when the
model cache is mounted read-only.

Fix: make is_hf_state_dict / is_prime_state_dict mutually exclusive for
dense models by having is_prime_state_dict return False (following the
pattern already used by GPT-OSS). This makes the conversion branches
naturally skip when there is no format difference, without needing
extra guards in load_dcp_from_hf.

MoE models are unaffected: their is_hf_state_dict / is_prime_state_dict
checks are already mutually exclusive (expert.0.w1 vs experts.w1 key
patterns).
2026-07-23 19:08:58 +02:00
JannikStandGitHub 3b5d031028 feat(ci): nightly FFT workflow (#3118)
* feat(ci): add nightly FFT workflow dispatching hosted training runs

* ci(nightly-fft): pin --image-tag to the latest published dev tag

* ci(nightly-fft): rename to reverse-text and align with pytest nightly setup

* ci(nightly-fft): pin deployment shape (2 train + 6 infer)

* ci(nightly-fft): switch to wordle mirroring examples/basic/wordle/rl.toml

* ci(nightly-fft): update wordle config to match examples/basic/wordle

* ci(nightly-fft): add explicit least-privilege permissions block

* ci(nightly-fft): drop top-level type/name — [deployment] alone triggers FFT dispatch

* ci(nightly-fft): resolve image tag from GHCR to avoid unpublished tags

* ci(nightly-fft): forward WANDB_API_KEY and HF_TOKEN into hosted payload via -e
2026-07-23 09:46:44 +02:00
Matej SirovatkaandGitHub 783cff546d fix(nixl): replay strided views on inference (#3113) 2026-07-23 07:32:42 +02:00
acbabc6f0f fix(orchestrator): hold batch ship on the trainer's published version (#3050)
* fix(orchestrator): enforce target lag strictly at ship time

The dispatch gate only stops new rollouts; on tiny fast envs the sink
keeps forming batches from buffered rollouts, so the orchestrator ships
past TARGET_LAG, finishes, and tears down the watcher while the trainer
still has pending NCCL broadcasts. Those broadcasts then block forever
in the STABLE->NCCL_READY handshake (no watcher to trigger the inference
receive) and the launcher never exits.

hold_for_target_lag blocks shipping batch N until the trainer has
published v{N-1-TARGET_LAG}, bounding in-queue staleness and keeping the
orchestrator alive for every broadcast the trainer will make. Under NCCL
the last published version is max_steps-2, exactly what the final batch
requires, so the hold never waits on an unpublishable version.

Also logs a per-batch staleness decomposition (pre-queue = versions
elapsed during generation, in-queue = versions spent waiting in the
sink) under staleness/*.

Fixes RES-1077

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* remove staleness metrics from ship path

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(orchestrator): step-based staleness with demand-driven dispatch

Measure a rollout's off-policy lag against the batch that consumes it —
batch N trains on policy v{N-1}, so lag = (N-1) - generation version,
queue time included. The old off_policy_steps counter only counted
weight updates during generation, so a rollout that finished fast but
sat buffered across steps trained arbitrarily stale while reporting 0.

- max_off_policy_steps now bounds consumption lag: in-flight groups are
  cancelled pre-pause (cancel_stale_train_groups) and buffered sink
  survivors are swept whenever the cutoff moves (ship, weight update).
  Groups share one generation version, so stale groups drop whole.
- Dispatch is demand-driven: the orchestrator injects train_demand
  (batch shortfall minus buffered + partial-group + in-transit
  rollouts), re-evaluated per scheduled group, replacing the lead-based
  dispatch gate and the #2990 final-batch NCCL exemption it needed.
  out_q backlog counts as coverage so ship-holds don't over-provision.
- Max Off-Policy in logs is now the honest consumption lag, stamped at
  ship (reverse_text: steady-state max 3 vs a dishonest 0 before).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* review pass: bool dispatch contract, oversampling-aware demand, inline single-use helpers

- train_demand -> train_needed: the dispatcher only thresholds the value,
  and the magnitude isn't even unit-stable across batch modes, so the
  injected contract is a bool predicate.
- Demand target is max(batch_size, max_inflight_rollouts): explicit
  over-provisioning (oversampling_factor > 1 or a raised max_inflight)
  keeps racing batch stragglers instead of being silently capped at one
  batch; capacities below the batch keep a batch_size target so the
  batch can still complete.
- Reject max_off_policy_steps=0 with NCCL broadcast + max_steps: the
  final batch necessarily trains one version off-policy (the trainer
  never broadcasts the last versions), so a zero budget would hang the
  run collecting the final batch.
- Inline single-call helpers (hold_for_target_lag, stale_cutoff, the
  dispatcher lag gauges) into their call sites.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* require max_off_policy_steps >= 1 at the field

The last NCCL batch necessarily trains one version off-policy (the
trainer never broadcasts the final versions), so a zero budget can never
be met and would hang the run collecting the final batch. A field floor
covers this without a conditional validator.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix CI regressions: partial-group dispatch deadlock + serialized weight applies

Two regressions surfaced by the PR's GPU CI run:

- alphabet_sort/rl_opd deadlocked at 126/128 (+3 buffered, 0 inflight):
  demand hit zero mid-group, so an open group's remaining rollouts were
  never scheduled — its buffered members count as batch coverage but the
  group can never finalize. Already-open groups now keep scheduling
  regardless of demand (try_schedule allow_fresh); only fresh groups are
  demand-gated.
- reverse_text timed out (~26s/step vs ~19s on main): the ship hold
  waited on the applied version, serializing every inference weight
  reload into the ship path. Filesystem broadcast decouples publish from
  apply and the trainer never blocks on the watcher there, so the hold
  now releases on the published version (tracked in on_version_pending).
  NCCL keeps waiting for the apply — the trainer blocks in the receive
  handshake until then, so releasing on publish could strand its final
  handshake at teardown.

Verified: reverse_text e2e clean on both broadcast types (filesystem
6-7s steps, NCCL exits clean), 485 unit tests pass.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* raise multi-run integration timeout to 600s

Resumed orchestrators now pace to the shared trainer — a batch only
ships once the trainer has produced the required policy version — so
with three runs round-robining one trainer, beta_resume's tail (steps
21-25) can legitimately exceed the old 300s wait while its versions
queue behind the other runs. Matches the 600s budget of the other RL
integration tests.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* retract stale-dropped rollouts from the payload-size estimate

drop_stale now mirrors what entering pending_batch added to
_payload_total/_payload_count, keeping the token-mode demand estimate
consistent with the buffered set. Also expand the allow_fresh comment
with the group-finalization invariant it protects.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* upload integration run logs as artifacts on failure

The multi-run test's failures only surface a sampled tail of one
orchestrator's output; the copied per-run orchestrator/trainer/inference
logs are what's needed to debug them (currently: beta_resume wedging on
a policy version the shared trainer never publishes after resume).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* keep CI test outputs for the failure-artifact upload

The output_dir fixture rmtree'd the whole outputs dir at session
teardown, so the upload step found nothing. Skip the cleanup under CI
(the workspace is discarded with the job) and match log files directly
instead of a directory glob.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* dispatch lookahead: cover TARGET_LAG extra batches when freshness allows

Exact-one-batch demand synchronized dispatch into one 128-rollout wave
per batch: each ship opened demand 0->128 at once, the wave stampeded
the env server together (MCP timeouts + backoff retries in CI
alphabet_sort), and inference idled ~60s per cycle while the whole wave
sat in env round-trips — tripling the step cadence vs main (artifact
logs: vLLM alternating 30s busy / 60s '0 running, 0 waiting').

With up to TARGET_LAG batches of lookahead — allowed only while a
rollout landing that far ahead still fits max_off_policy_steps —
steady-state dispatch is continuous (each arrival frees demand for the
next start), keeping the engine fed through env-phase gaps. Costs one
version of staleness on the lookahead batch (reverse_text plateau 3->4,
within the default cap of 8).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* raise reverse_text mismatch-KL budget to 0.02

Mismatch KL compares generation-time inference logprobs against the
training weights, so it includes async training's policy-version gap on
top of trainer/inference numerics. With strict pacing + dispatch
lookahead the steady-state consumption lag is 2-3 versions (visible and
bounded, vs unmeasured before), which puts the last-steps average at
~0.011-0.012 against the old 0.01 budget calibrated for main's profile.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* raise alphabet_sort and multi-run integration budgets

Artifacts from the failed runs show no wedges — every process was
mid-progress at the deadline: alphabet_sort cycles at ~70s on slow vm
runners (33s on fast ones; trainer MFU varies 2-6% across the pool) and
the multi-run trainer was mid-micro-step serving three runs
round-robin. With strict pacing the orchestrators ride the trainer's
pace instead of finishing early on stale buffers, so wall time tracks
the slowest component.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* raise multi-run inner milestone waits to 600s

The wait_for_log/wait_for_file 300s defaults were calibrated for
orchestrators that sprint ahead of the shared trainer on buffered
batches; with strict pacing three orchestrators ride the trainer's
actual speed, so every internal milestone (alpha steps, checkpoint
STABLE markers, resume completion) lands slower and a different 300s
wait tripped on each CI round.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* count group-scored partial arrivals as batch coverage

buffered_count hides group-scoring envs' partial groups for the
pipeline log's honesty, but demand must count them — otherwise members
sitting between arrival and group completion invite bounded
over-dispatch. Also document why a held batch intentionally does not
count as coverage (dispatch-ahead keeps inference busy through
trainer-bound holds; staleness stays bounded by lookahead + cutoff).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* guard token-export STABLE markers against deleted run dirs

The multi-run trainer crashed with FileNotFoundError touching
run_gamma/token_exports/step_20/STABLE: the multi-run integration test
rmtree's a run's dir once its orchestrator finishes, while the trainer
is still flushing that run's tail steps. The broadcast paths already
skip deleted runs on FileNotFoundError; mark_stable now does the same.

This was the root cause of the recurring multi_run CI failure: the
crashed trainer never published the resumed run's next version, so
beta_resume's ship-hold waited forever ('failed with code None'). On
main the same crash risk exists but the orchestrator never waited on
the trainer, so nothing surfaced.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* recalibrate multi-run early-step reward floor for strict pacing

Batch N's data now comes from v{N-2}..v{N-4} instead of main's
effectively-fresher buffer profile, so reward-at-step-7 reads 1-2
policy versions staler (observed 0.14-0.20 across four CI rounds vs the
0.2 floor). The final-reward thresholds still enforce learning quality;
the early floor drops to 0.1 — comfortably above a broken run's flat
~0.05-0.08.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* raise rl_sft integration budget to 900s

Same class as the other RL integration budgets: the trainer was
SIGTERM'd at step 14 with the orchestrator already finished — killed by
the 600s deadline steps from completion on a slow runner.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* lower multi-run final reward floor to 0.6

With strict pacing the reward-vs-step-index curve sits 1-2 policy
versions lower throughout; gamma — the most trainer-contended of the
five runs — landed at 0.627 while its siblings cleared 0.69-0.75. A
broken run still reads ~0.1-0.3.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* bound dispatch freshness at DISPATCH_LAG instead of the drop cap

Root cause of the reward-at-step gap vs main: the old lead gate doubled
as the dispatch freshness bound (rollouts only started at version >=
step-2, landing lag <= 2). The demand rewrite left freshness gated only
by max_off_policy_steps (8) plus a deliberately-ahead lookahead batch,
so mean consumption lag ran 2-4 versions vs main's 1-2 — visible as
Max Off-Policy 3-4, mismatch KL ~2x main's, and reward-at-step lower by
1-2 versions of learning.

Dispatch now pauses when new rollouts would train more than
DISPATCH_LAG = TARGET_LAG+1 versions behind their generation policy,
with the lookahead scaled inside that budget — the tightest bound that
still keeps inference busy during ship-holds. Landing lag returns to
<= 2 (spill 3); local e2e: Max Off-Policy plateau 4 -> 3, mismatch KL
mean ~0.012 -> ~0.008. max_off_policy_steps returns to being purely the
drop safety net.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* ci: retrigger GPU tests

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* tolerate trainer tail-flush when deleting run dirs in multi-run test

The fixture's rmtree races the shared trainer's token-export writes,
which mkdir the run dir back mid-deletion (OSError: Directory not
empty). Retry until the flush for the finished run drains.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* restore NIXL ModelExpress handshake signals in the version hooks

The merge of #3060 kept this branch's on_version_pending/on_new_version
bodies and dropped main's ModelExpress status updates — the READY
signal the NIXL trainer waits on before each broadcast and the
INITIALIZING reset after it. Post-startup NIXL runs would hang in the
handshake. Both signals are back, ordered as on main (READY pre-update,
INITIALIZING post-update) around this branch's staleness/wake logic.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* reduce to the minimal ship-hold fix + staleness docs

Strip the demand-driven dispatch, consumption-lag drop rework, and test
recalibrations accumulated on this branch back to main's behavior, and
keep only what the spec (docs/staleness.md) strictly requires:

- ADVANCE rule: batch N ships only once the trainer has published
  v{N-1-TARGET_LAG}, so the orchestrator cannot finish and tear down the
  weight watcher while the trainer still has in-memory broadcast
  handshakes pending (RES-1077). Main's dispatch gate (START) and
  in-flight drop aging (DIE) are untouched, so generation freshness and
  throughput are unchanged in both pacing regimes — the hold only moves
  where a finished batch waits, never when the trainer consumes it.
- policy.version advances at publish confirmation (inference applies
  immediately and pauses during the update, so published and applied
  are indistinguishable to consumers), and WeightWatcher.stop() drains
  an in-flight apply before cancelling — teardown can never strand the
  trainer mid-handshake.
- Keep the trainer-side token-export guard, the multi-run test's
  deletion-race helper, and the CI failure-artifact pipeline from the
  earlier iterations; drop everything else.

Verified on the original repro (reverse_text, fast env, NCCL): 10/10
batches, clean trainer exit, 2 holds at the buffer-fed tail.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fold staleness spec into docs/training.md

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* drop the docs section for now, trim the hold comment

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* never delete the test output dir; clean at run start instead

The output_dir fixture deleted the whole workspace at session teardown,
racing the failure-artifact upload (and hiding logs from post-mortems
generally). Keep it unconditionally and make fresh starts responsible
for their own hygiene: alphabet_sort and reverse_text_moe now pass
--clean-output-dir like the other rl-launcher tests. Resume runs are
unaffected — validate_output_dir returns before cleaning when resuming.
The multi-run orchestrators manage per-run dirs the test creates (and
the standalone orchestrator entrypoint has no clean flag).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* stamp true consumption staleness on shipped rollouts

Batch N trains on policy v{N-1}, so a rollout generated from v{k} is
(N-1)-k versions off-policy — queue time included. The dispatcher's
in-flight counter only sees weight updates during generation, which
undercounts by the queue-wait aging and the dispatch-time baseline gap;
the ship-time stamp overwrites it so Max Off-Policy in logs and the
rollout records report the real number. The counter itself (and the
max_off_policy_steps drop rule it feeds) is unchanged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* use the deletion-retry helper for alpha's run dir too

Alpha is SIGTERM'd mid-run, so the trainer is actively flushing its
token-export tail when the dir is deleted — the recreate race is most
likely at exactly this site.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 06:43:48 +02:00
055f62ca32 chore(rl): add message to multimodal packing assert (#3117)
Follow-up to #3103 review feedback: make the mm_kwargs invariant assert self-describing when it fires.

Co-authored-by: eligotts <eligotts@users.noreply.github.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-23 06:11:09 +02:00
samsjaandGitHub 1b8c5ef01a fix: sync docs to public-docs on stable release only (#3116)
* fix: sync docs to public-docs on release tags only

Change the Sync Docs to Public Docs workflow to trigger on stable v*
tag pushes instead of every commit to main that touches docs/, so the
public docs only update on releases.

Exclude v*dev* tags so dev pre-release tags never trigger a sync.

Keep workflow_dispatch for manual syncs.

On a tag push github.sha resolves to the tagged commit, so the ref sent
to public-docs remains correct.

Mirrors PrimeIntellect-ai/verifiers#2108.

* fix: trigger docs sync on release published, not on main push

Change the Sync Docs to Public Docs workflow to trigger when a stable
GitHub release is published instead of every commit to main that touches
docs/, so the public docs only update on actual stable releases.

Dev tags (v*dev*) are created via GITHUB_TOKEN which doesn't retrigger
workflows, and they don't have GitHub Releases, so using the release
event with types: [published] naturally excludes them.

Keep workflow_dispatch for manual syncs.

On a release publish, github.sha resolves to the tagged commit, so the
ref sent to public-docs remains correct.
2026-07-23 05:42:45 +02:00
33 changed files with 601 additions and 46 deletions
+3 -5
View File
@@ -1,8 +1,6 @@
name: Build Image (ghcr)
on:
release:
types: [published]
workflow_dispatch:
inputs:
ref:
@@ -27,12 +25,12 @@ on:
env:
REGISTRY: ghcr.io
IMAGE_NAME: primeintellect-ai/prime-rl
BUILD_REF: ${{ github.event.release.tag_name || inputs.ref || github.ref_name }}
BUILD_TAG: ${{ github.event.release.tag_name || inputs.tag || '' }}
BUILD_REF: ${{ inputs.ref || github.ref_name }}
BUILD_TAG: ${{ inputs.tag || '' }}
BUILD_PLATFORMS: ${{ inputs.platforms || 'both' }}
concurrency:
group: build-image-${{ github.event.release.tag_name || inputs.tag || inputs.ref || github.ref_name }}
group: build-image-${{ inputs.tag || inputs.ref || github.ref_name }}
cancel-in-progress: false
jobs:
+8
View File
@@ -121,3 +121,11 @@ jobs:
PYTEST_OUTPUT_DIR: /tmp/outputs
VLLM_WORKER_MULTIPROC_METHOD: spawn
run: uv run pytest -vvs ${{ matrix.pytest_args }}
- name: Upload run logs on failure
if: failure()
uses: actions/upload-artifact@v4
with:
name: ${{ matrix.test }}-logs
path: /tmp/outputs/**/*.log
retention-days: 7
if-no-files-found: ignore
+189
View File
@@ -0,0 +1,189 @@
name: Nightly FFT
on:
# Allow to manually trigger the workflow
workflow_dispatch:
inputs:
config_file:
description: "Full-FT config to dispatch (e.g. configs/ci/nightly-fft/wordle.toml). Leave empty to run all."
required: false
default: ""
image_tag:
description: "prime-rl image tag to pin (e.g. v0.7.1.dev58). Leave empty to auto-resolve the newest v*.dev* with a published manifest."
required: false
default: ""
# Scheduled run at 3AM PST (11AM UTC) — disabled for now, enable once dry-run passes
# schedule:
# - cron: "0 11 * * *"
permissions:
contents: read
packages: read
jobs:
discover-configs:
name: Discover configs
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.build-matrix.outputs.matrix }}
steps:
- name: Checkout repository
uses: actions/checkout@v5
with:
submodules: false
- name: Build matrix from nightly FFT configs
id: build-matrix
run: |
# Find all nightly full-finetune configs
files=$(ls configs/ci/nightly-fft/*.toml)
# Filter to specific config if provided in workflow_dispatch
if [ "${{ github.event_name }}" = "workflow_dispatch" ] && [ -n "${{ github.event.inputs.config_file }}" ]; then
filtered=$(echo "$files" | grep -F "${{ github.event.inputs.config_file }}" || true)
if [ -z "$filtered" ]; then
echo "Error: Config file '${{ github.event.inputs.config_file }}' not found"
exit 1
fi
files="$filtered"
fi
echo "Discovered nightly FFT configs:"
echo "$files"
# Build JSON of the form: { "config_file": ["configs/ci/nightly-fft/foo.toml", ...] }
json=$(printf '%s\n' "$files" | jq -R . | jq -sc '{config_file: .}')
echo "matrix=$json" >> "$GITHUB_OUTPUT"
dispatch-run:
name: Dispatch hosted FFT run
needs: discover-configs
runs-on: ubuntu-latest
timeout-minutes: 30
strategy:
fail-fast: false
matrix: ${{ fromJSON(needs.discover-configs.outputs.matrix) }}
steps:
- name: Checkout repository
uses: actions/checkout@v5
with:
submodules: false
- name: Resolve prime-rl image tag
id: image
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Pass the dispatch input through env so a malicious value
# cannot break out of shell context via $(...) or embedded
# quotes — the GitHub expression is substituted before Bash
# parses the script.
REQUESTED_IMAGE_TAG: ${{ github.event.inputs.image_tag }}
run: |
# If workflow_dispatch passed an explicit image_tag, validate
# it as a Docker/OCI tag, verify its manifest is pullable,
# and use it as-is (skip resolution).
requested="$REQUESTED_IMAGE_TAG"
if [ -n "$requested" ]; then
# OCI/Docker tag charset: [A-Za-z0-9._-], max 128, no
# leading '.' or '-'. Reject anything else before it
# reaches curl or GITHUB_OUTPUT.
if ! printf '%s' "$requested" | grep -Eq '^[A-Za-z0-9_][A-Za-z0-9._-]{0,127}$'; then
echo "Invalid image_tag: only [A-Za-z0-9._-] allowed, max 128 chars, no leading '.' or '-'." >&2
exit 1
fi
registry_token=$(curl -fsSL \
"https://ghcr.io/token?scope=repository:primeintellect-ai/prime-rl:pull" \
| jq -r .token)
code=$(curl -sS -o /dev/null -w '%{http_code}' \
-H "Authorization: Bearer $registry_token" \
-H 'Accept: application/vnd.oci.image.index.v1+json' \
-H 'Accept: application/vnd.docker.distribution.manifest.list.v2+json' \
"https://ghcr.io/v2/primeintellect-ai/prime-rl/manifests/$requested")
if [ "$code" != "200" ]; then
echo "Requested image_tag '$requested' has no published manifest (HTTP $code)." >&2
exit 1
fi
echo "Using pinned prime-rl image tag: $requested"
echo "tag=$requested" >> "$GITHUB_OUTPUT"
exit 0
fi
# The GHCR versions API can list a tag before its manifest is
# actually pullable (build in-flight, or manifest step didn't
# finish). So: pull the top N candidate tags, then verify each
# with a manifest HEAD via the anonymous registry token flow;
# take the newest one that resolves.
candidates=$(gh api --paginate \
"/orgs/primeintellect-ai/packages/container/prime-rl/versions" \
--jq '.[].metadata.container.tags[]' \
| grep -E '^v[0-9]+\.[0-9]+\.[0-9]+\.dev[0-9]+$' \
| sort -Vru | head -n 10)
if [ -z "$candidates" ]; then
echo "No v*.dev* tag listed on GHCR." >&2
exit 1
fi
registry_token=$(curl -fsSL \
"https://ghcr.io/token?scope=repository:primeintellect-ai/prime-rl:pull" \
| jq -r .token)
tag=""
for cand in $candidates; do
code=$(curl -sS -o /dev/null -w '%{http_code}' \
-H "Authorization: Bearer $registry_token" \
-H 'Accept: application/vnd.oci.image.index.v1+json' \
-H 'Accept: application/vnd.docker.distribution.manifest.list.v2+json' \
"https://ghcr.io/v2/primeintellect-ai/prime-rl/manifests/$cand")
if [ "$code" = "200" ]; then
tag="$cand"
break
fi
echo "Skip $cand — manifest HEAD returned $code"
done
if [ -z "$tag" ]; then
echo "None of the top v*.dev* tags have a published manifest." >&2
exit 1
fi
echo "Latest published prime-rl image tag on GHCR: $tag"
echo "tag=$tag" >> "$GITHUB_OUTPUT"
- name: Install uv
uses: astral-sh/setup-uv@v7
- name: Install prime CLI (latest)
run: uv tool install prime
- name: Dispatch run
env:
PRIME_API_KEY: ${{ secrets.PRIME_FFT_API_KEY }}
PRIME_TEAM_ID: ${{ secrets.PRIME_FFT_TEAM_ID }}
PRIME_BASE_URL: ${{ secrets.PRIME_BASE_URL }}
WANDB_API_KEY: ${{ secrets.WANDB_API_KEY }}
HF_TOKEN: ${{ secrets.HF_TOKEN }}
run: |
echo "Dispatching config: ${{ matrix.config_file }}"
echo "Image tag: ${{ steps.image.outputs.tag }}"
# Tag the RFTRun so it's identifiable on the platform as
# coming from this workflow. Injected here rather than in
# the checked-in toml because a top-level `name` field
# breaks tests/unit/test_configs.py::test_load_configs
# (RLConfig has no top-level name).
config_base=$(basename "${{ matrix.config_file }}" .toml)
run_name="nightly-${config_base}-$(date -u +%Y-%m-%d)-${{ github.run_id }}"
dispatch_cfg=$(mktemp --suffix=.toml)
printf 'name = "%s"\n\n' "$run_name" > "$dispatch_cfg"
cat "${{ matrix.config_file }}" >> "$dispatch_cfg"
echo "Dispatched run name: $run_name"
# Forward WANDB_API_KEY / HF_TOKEN into the hosted payload:
# the full-FT dispatch path (`prime train`) only picks up
# secrets that were explicitly collected via `-e` / `--env-file`,
# not ambient env, so the workflow env: block alone is not
# enough to reach the hosted trainer/orchestrator pods.
prime train "$dispatch_cfg" \
--image-tag "${{ steps.image.outputs.tag }}" \
-e WANDB_API_KEY \
-e HF_TOKEN \
--yes --output json
+3 -5
View File
@@ -1,11 +1,9 @@
name: Sync Docs to Public Docs
on:
push:
branches:
- main
paths:
- 'docs/**'
release:
types:
- published
workflow_dispatch:
jobs:
+25
View File
@@ -119,6 +119,8 @@ jobs:
runs-on: ubuntu-latest
permissions:
contents: write
# Needed to dispatch build_image.yaml below (POST .../dispatches).
actions: write
steps:
- name: Publish draft release
env:
@@ -127,11 +129,22 @@ jobs:
run: |
gh release edit "$TAG" --repo "$GITHUB_REPOSITORY" --draft=false --latest
# Publishing runs as GITHUB_TOKEN, whose events don't retrigger
# workflows, so dispatch the image build explicitly.
- name: Trigger image build for the release
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ needs.auto-tag-on-main.outputs.tag }}
run: |
gh workflow run build_image.yaml --repo "$GITHUB_REPOSITORY" -f ref="$TAG"
tag-and-release:
if: github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
permissions:
contents: write
# Needed to dispatch build_image.yaml below (POST .../dispatches).
actions: write
steps:
- name: Checkout tagged release (dispatch)
if: github.event_name == 'workflow_dispatch'
@@ -195,6 +208,7 @@ jobs:
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
- name: Publish draft release
id: publish
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ steps.release.outputs.tag }}
@@ -207,6 +221,17 @@ jobs:
fi
if [ "$STATE" = "false" ]; then
echo "Release $TAG is already published; nothing to do."
echo "published=false" >> "$GITHUB_OUTPUT"
exit 0
fi
gh release edit "$TAG" --repo "$GITHUB_REPOSITORY" --draft=false --latest
echo "published=true" >> "$GITHUB_OUTPUT"
# Skipped when the release was already published (no rebuild needed).
- name: Trigger image build for the release
if: steps.publish.outputs.published == 'true'
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ steps.release.outputs.tag }}
run: |
gh workflow run build_image.yaml --repo "$GITHUB_REPOSITORY" -f ref="$TAG"
+2 -1
View File
@@ -3,7 +3,8 @@
url = git@github.com:PrimeIntellect-ai/verifiers.git
[submodule "renderers"]
path = deps/renderers
url = git@github.com:PrimeIntellect-ai/renderers.git
url = ../renderers.git
branch = trinity
[submodule "research-environments"]
path = deps/research-environments
url = git@github.com:PrimeIntellect-ai/research-environments.git
+32
View File
@@ -0,0 +1,32 @@
max_steps = 200
seq_len = 2048
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[wandb]
project = "alphabet-sort"
name = "alphabet-sort"
[ckpt]
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 512
group_size = 16
[[orchestrator.train.env]]
name = "alphabet-sort"
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.sampling]
max_completion_tokens = 768
[trainer]
[inference.parallel]
dp = 4
@@ -0,0 +1,49 @@
max_steps = 5000
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[wandb]
project = "hendrycks-sanity"
name = "hendrycks-sanity"
[ckpt]
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[orchestrator]
batch_size = 512
group_size = 8
seq_len = 8192
[[orchestrator.train.env]]
name = "hendrycks-math"
env.taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 50
[[orchestrator.eval.env]]
name = "aime2024"
env.taskset = { id = "aime24-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
group_size = 32
[trainer]
[trainer.model]
seq_len = 16384
attn = "flash_attention_2"
[inference.parallel]
dp = 4
[inference.model]
max_model_len = 8192
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+34
View File
@@ -0,0 +1,34 @@
max_steps = 20
seq_len = 2048
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
[wandb]
project = "reverse-text"
name = "reverse-text"
[ckpt]
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[orchestrator]
batch_size = 128
group_size = 16
[[orchestrator.train.env]]
name = "reverse-text"
env.taskset = { id = "reverse-text-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.sampling]
max_completion_tokens = 128
[trainer]
[inference]
[orchestrator.renderer]
name = "prime-qwen3"
+40
View File
@@ -0,0 +1,40 @@
max_steps = 200
seq_len = 4096
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[wandb]
project = "wiki-search"
name = "wiki-search"
[ckpt]
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 512
group_size = 16
oversampling_factor = 2.0
[[orchestrator.pre_batch_filters]]
type = "zero_advantage"
enforce = true
[[orchestrator.train.env]]
name = "wiki-search"
env.taskset = { id = "wiki-search-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.sampling]
max_completion_tokens = 512
[trainer]
[inference.parallel]
dp = 4
[inference.model]
tool_call_parser = "hermes"
+35
View File
@@ -0,0 +1,35 @@
max_steps = 200
seq_len = 8192
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[wandb]
project = "wordle"
name = "wordle"
[ckpt]
[model]
name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
[orchestrator]
batch_size = 512
group_size = 16
[[orchestrator.train.env]]
name = "wordle"
env.taskset = { id = "wordle-v1" }
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.train.sampling]
max_completion_tokens = 1024
[trainer]
[inference.parallel]
dp = 6
[orchestrator.renderer]
name = "prime-qwen3"
+1 -1
+1 -1
View File
@@ -46,7 +46,7 @@ enable_router_replay = true
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 8
cp = 4
cp_style = "ulysses"
fused_lm_head_token_chunk_size = 1024
optim_cpu_offload = true
+2 -2
View File
@@ -7,7 +7,7 @@
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
# subtraction.
#
# 2 train + 4 infer nodes. Trainer uses cp=8 (ulysses) plus
# 2 train + 4 infer nodes. Trainer uses cp=4 (ulysses) plus
# the memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), optimizer
# CPU offload, and skip-gather / skip-optimizer checkpointing.
@@ -57,7 +57,7 @@ enable_router_replay = true
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 8
cp = 4
cp_style = "ulysses"
fused_lm_head_token_chunk_size = 1024
optim_cpu_offload = true
+1 -1
View File
@@ -47,7 +47,7 @@ enable_router_replay = true
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 8
cp = 4
cp_style = "ulysses"
fused_lm_head_token_chunk_size = 1024
optim_cpu_offload = true
@@ -32,6 +32,9 @@ class OptimizerConfig(BaseConfig):
class LoRAConfig(BaseConfig):
init_path: Path | None = None
"""Initial adapter for a fresh optimizer run; full checkpoint resume takes precedence."""
name: str | None = None
"""LoRA adapter name. If None, auto-generated from rank and alpha."""
@@ -73,6 +73,9 @@ class IndexCacheConfig(BaseConfig):
class LoRAConfig(BaseConfig):
init_path: Path | None = None
"""Initialize adapter weights from a PEFT directory when not resuming a full checkpoint."""
rank: int = Field(16, ge=1)
"""Rank of the low-rank decomposition matrices."""
+44 -1
View File
@@ -176,6 +176,8 @@ class Orchestrator:
self.eval_triggered_at = {}
self.consecutive_empty_batches = 0
self.gate_closed_at = None
# Pulsed by the version hooks so a held ship can re-check ``policy.version``
self.version_advanced = asyncio.Event()
self.wait_for_policy_time = 0.0
self.component_tasks = []
@@ -378,6 +380,15 @@ class Orchestrator:
self.policy.model_name = self.lora_name
self.policy.version = sync_version
elif config.model.lora is not None and config.model.lora.init_path is not None:
await self.policy_inference.update_weights(
config.model.lora.init_path, lora_name=self.lora_name, step=0
)
self.policy_inference.update_model_name(self.lora_name)
self.policy.model_name = self.lora_name
self.policy.version = 0
get_logger().info(f"Initialized policy v0 from adapter {config.model.lora.init_path}")
self.train_source = TrainSource(self.train_envs, seed=42)
self.eval_source: EvalSource | None = (
EvalSource(
@@ -602,6 +613,35 @@ class Orchestrator:
f"({n_trainable / len(batch.rollouts):.1%}) — consider reviewing task difficulty / filter config"
)
# Ship batch ``step`` only once the trainer has published v{step-1-TARGET_LAG}.
# Without this, fast envs fill batches from buffered rollouts, the
# orchestrator finishes early, and its teardown strands the trainer inside
# an in-memory broadcast handshake that needs the live weight watcher.
# Always satisfiable: the trainer skips only the final TARGET_LAG+1
# in-memory broadcasts. Bench runs have no trainer, so they ship freely.
required_version = step - 1 - TARGET_LAG
if not config.bench and self.policy.version < required_version:
get_logger().info(
f"Holding batch {step} until the trainer publishes policy v{required_version} "
f"(currently v{self.policy.version})"
)
hold_start = time.perf_counter()
while True:
self.version_advanced.clear()
if self.policy.version >= required_version:
break
await self.version_advanced.wait()
self.wait_for_policy_time += time.perf_counter() - hold_start
# Stamp each rollout's true staleness: batch ``step`` trains on policy
# v{step-1}, so a rollout generated from v{k} is (step-1)-k versions
# off-policy — queue time included, unlike the dispatcher's in-flight
# counter, which only sees weight updates during generation. Frozen-
# sourced rollouts stay 0 (their sampler doesn't follow the policy).
for r in batch.rollouts:
if self.train_envs.get(r.env_name).sampler.samples_from_live_policy:
r.off_policy_steps = (step - 1) - r.policy_version
# The effective (clean, trained-on) subset lands in the per-step ``effective`` trace file
# at ship time; the full arrival window already streamed into ``all`` on arrival.
# to_record drops the per-node training tensors — they're for training, not the rollout
@@ -905,11 +945,14 @@ class Orchestrator:
gate.set()
async def on_version_pending(self, step: int) -> None:
"""``VersionObserver`` hook, fired at publish confirmation (pre-apply):
``policy.version`` already carries the new version, so wake a held ship."""
if self.model_express is not None:
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_READY)
self.version_advanced.set()
async def on_new_version(self, step: int) -> None:
"""``VersionObserver`` hook: the watcher just advanced ``policy.version``;
"""``VersionObserver`` hook: the weight update completed;
re-evaluate the dispatch gate (may resume if the trainer caught up)."""
if self.model_express is not None:
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
+13 -2
View File
@@ -64,6 +64,12 @@ class WeightWatcher:
async def stop(self) -> None:
self.stopped.set()
# Let an in-flight apply finish before dying: the trainer blocks inside
# its in-memory broadcast until the apply completes, so cancelling
# mid-apply would strand it. The orchestrator's global teardown budget
# bounds this wait.
async with self.update_lock:
pass
if self.task is not None:
await safe_cancel(self.task)
self.task = None
@@ -103,6 +109,13 @@ class WeightWatcher:
await wait_for_path(stable_marker)
self.last_wait_for_ckpt_time = time.perf_counter() - t0
# Publish confirmed: the policy version advances here, before the
# apply — inference pauses during the update, so nothing can generate
# under the new number from the old weights, and a ship held on this
# version releases without waiting out the inference weight reload.
self.ckpt_step = next_step
self.policy.version = next_step
# Drain off-policy rollouts BEFORE pausing the inference engines.
# Aborting a rollout triggers vLLM's KV-connector cleanup (NIXL's
# ``_reqs_not_processed``), which is only propagated to the workers
@@ -128,8 +141,6 @@ class WeightWatcher:
self.update_count += 1
get_logger().debug(f"Updated weights to step {next_step} in {format_time(self.last_update_weights_time)}")
self.ckpt_step = next_step
self.policy.version = next_step
if self.lora_name is not None:
self.inference.update_model_name(self.lora_name)
self.policy.model_name = self.lora_name
+1 -1
View File
@@ -270,7 +270,7 @@ class _MicroBatchBin:
if existing_mm_sample is not None and sample_is_mm:
dst = existing_mm_sample.mm_kwargs
src = sample.mm_kwargs
assert dst is not None and src is not None
assert dst is not None and src is not None, "multimodal samples must carry mm_kwargs"
return set(dst) == set(src) and all(
dst[key].dtype == src[key].dtype
and len(dst[key].shape) > 0
+53
View File
@@ -0,0 +1,53 @@
"""Strict attention-only PEFT initialization without optimizer restoration."""
import json
import torch
from safetensors.torch import load_file
from torch.distributed.tensor import DTensor, distribute_tensor
from prime_rl.utils.logger import get_logger
def load_attention_adapter(model, config):
adapter = config.lora
path = adapter.init_path
metadata = json.loads((path / "adapter_config.json").read_text())
allowed = {"q_proj", "k_proj", "v_proj", "o_proj"}
if set(adapter.target_modules) != allowed or adapter.modules_to_save:
raise ValueError("Adapter warm start supports only attention q/k/v/o with no modules_to_save")
if (metadata.get("r") != adapter.rank or metadata.get("lora_alpha") != adapter.alpha
or metadata.get("lora_dropout", 0.0) != adapter.dropout
or set(metadata.get("target_modules", [])) != allowed
or metadata.get("modules_to_save") or metadata.get("bias", "none") != "none"
or metadata.get("base_model_name_or_path") != config.name):
raise ValueError("Warm-start adapter metadata does not match trainer configuration")
saved = {k.removeprefix("base_model.model."): v for k, v in
load_file(str(path / "adapter_model.safetensors"), device="cpu").items()}
targets = {}
for name, param in model.named_parameters():
if ".lora_A." not in name and ".lora_B." not in name:
continue
name = name.replace("._orig_mod", "")
if not name.endswith(".0"):
raise ValueError("Adapter warm start supports one adapter slot only")
key = name[:-2] + ".weight"
if key in targets:
raise ValueError(f"Duplicate adapter destination: {key}")
targets[key] = param
if set(saved) != set(targets):
raise ValueError(f"Adapter key mismatch: missing={set(targets)-set(saved)}, extra={set(saved)-set(targets)}")
for key, param in targets.items():
if saved[key].shape != param.shape or not torch.isfinite(saved[key]).all():
raise ValueError(f"Invalid adapter tensor: {key}")
with torch.no_grad():
for key, param in targets.items():
value = saved[key].to(device=param.device, dtype=param.dtype)
if isinstance(param, DTensor):
value = distribute_tensor(value, param.device_mesh, param.placements)
param.copy_(value)
actual = param.to_local() if isinstance(param, DTensor) else param
expected = value.to_local() if isinstance(value, DTensor) else value
if not torch.equal(actual, expected):
raise ValueError(f"Adapter copy verification failed: {key}")
get_logger().success(f"Warm-started {len(targets)} adapter tensors from {path}; optimizer state is fresh")
+5 -2
View File
@@ -937,7 +937,10 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
snapshot_keys = dict.fromkeys(load_state_dict_keys(source_path))
model_keys = dict.fromkeys(model.state_dict().keys())
if model.is_hf_state_dict(snapshot_keys) and model.is_prime_state_dict(model_keys):
snapshot_is_hf = model.is_hf_state_dict(snapshot_keys)
snapshot_is_prime = model.is_prime_state_dict(snapshot_keys)
if snapshot_is_hf and not snapshot_is_prime and model.is_prime_state_dict(model_keys):
logger.warning(
"Found HF weight format in snapshot state dict and PrimeRL weight format in model state dict. Trying to auto-convert..."
)
@@ -951,7 +954,7 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
save_state_dict(snapshot_state_dict, snapshot_path)
del snapshot_state_dict
elif model.is_prime_state_dict(snapshot_keys) and model.is_hf_state_dict(model_keys):
elif snapshot_is_prime and not snapshot_is_hf and model.is_hf_state_dict(model_keys):
logger.warning(
"Found PrimeRL weight format in snapshot state dict and HF weight format in model state dict. Trying to auto-convert..."
)
@@ -124,8 +124,10 @@ class LlamaPreTrainedModel(PreTrainedModelPrimeRL):
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
"""Check if the state dict is in PrimeRL training format."""
return True
# Dense models use identical key names in HF and PrimeRL format, so we
# never claim to be in a separate PrimeRL format. This disables the
# auto-conversion path in load_dcp_from_hf and lets DCP load directly.
return False
@classmethod
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
@@ -107,7 +107,10 @@ class Qwen3PreTrainedModel(PreTrainedModelPrimeRL):
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return True
# Dense models use identical key names in HF and PrimeRL format, so we
# never claim to be in a separate PrimeRL format. This disables the
# auto-conversion path in load_dcp_from_hf and lets DCP load directly.
return False
@classmethod
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
@@ -160,7 +160,10 @@ class Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL, HFQwen3_5PreTrainedModel):
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return True
# Dense models use identical key names in HF and PrimeRL format, so we
# never claim to be in a separate PrimeRL format. This disables the
# auto-conversion path in load_dcp_from_hf and lets DCP load directly.
return False
@classmethod
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
@@ -92,9 +92,10 @@ def is_view_of(value: torch.Tensor, root: torch.Tensor) -> bool:
def plan_tensor_replay(shape: tuple[int, ...], dtype: torch.dtype, ops: OperationChain) -> TensorReplayPlan:
"""Resolve a directly transferable source view and local replay suffix.
The prefix must remain a same-dtype view of the trainer root and can
therefore be addressed by RDMA. The first materializing or dtype-changing
operation and everything after it is replayed on the receive arena.
The prefix must remain a contiguous, same-dtype view of the trainer root
and can therefore be transferred in large RDMA runs. The first strided,
materializing, or dtype-changing operation and everything after it is
replayed on the receive arena.
"""
root = torch.empty(shape, dtype=dtype, device="meta")
prefix_len = 0
@@ -105,7 +106,7 @@ def plan_tensor_replay(shape: tuple[int, ...], dtype: torch.dtype, ops: Operatio
if candidate_len < len(ops) and ops[candidate_len].name == "tuple_getitem":
continue
candidate = apply_chain(root, ops[:candidate_len])
if candidate.dtype != dtype or not is_view_of(candidate, root):
if candidate.dtype != dtype or not is_view_of(candidate, root) or not candidate.is_contiguous():
break
prefix_len = candidate_len
source_view = candidate
+7 -1
View File
@@ -10,6 +10,7 @@ from torch import Tensor
from prime_rl.configs.trainer import DefaultLossConfig, TrainerConfig
from prime_rl.trainer.rl.loss import compute_importance_ratio_and_mismatch_kl
from prime_rl.utils.logger import get_logger
SCHEMA_VERSION = 1
@@ -93,7 +94,12 @@ class TokenExporter:
ready_run_ids = ready_run_ids or set()
for run_id in [rid for rid in self._pending_stable_dirs if rid is None or rid in ready_run_ids]:
for stable_dir in self._pending_stable_dirs.pop(run_id):
(stable_dir / "STABLE").touch()
try:
(stable_dir / "STABLE").touch()
except FileNotFoundError:
# A multi-run run dir can be deleted while its tail steps are
# still flushing (mirrors the broadcast paths' guard)
get_logger().warning(f"Run dir for {run_id} is deleted, skipping token-export STABLE marker")
def _export_dir(self, export_step: int, run_id: str | None) -> Path:
if run_id is not None:
+7
View File
@@ -173,7 +173,14 @@ def train(config: TrainerConfig):
cpu_offload=config.model.optim_cpu_offload,
)
scheduler = setup_scheduler(optimizer, config.scheduler, config.max_steps, config.optim.lr)
# Run creation resets adapters; initialize only after that reset has finished.
if checkpoint_step is None and config.model.lora is not None and config.model.lora.init_path is not None:
from prime_rl.trainer.lora_init import load_attention_adapter
load_attention_adapter(model, config.model)
else:
if config.model.lora is not None and config.model.lora.init_path is not None:
raise ValueError("Adapter warm start requires max_concurrent_runs=1")
optimizer = setup_multi_optimizer(config.optim, parallel_dims)
scheduler = setup_multi_scheduler(optimizer, config.scheduler, config.max_steps)
+5 -9
View File
@@ -457,15 +457,11 @@ def _is_retryable_lora_error(exception: BaseException) -> bool:
return False
# Per-attempt and total bounds for `/load_lora_adapter`. A LoRA load is fast
# (small adapter file + KV cache reset, single-digit seconds in practice) but
# the global admin AsyncClient uses `timeout=None`, so a stuck server hangs
# the orchestrator forever inside `ElasticInferencePool._sync_server_adapter`.
# `_PER_ATTEMPT` converts a hang into a TimeoutException so tenacity retries;
# `_TOTAL` is the wall-clock budget across all retries — pick whichever
# stop condition fires first.
LORA_LOAD_READ_TIMEOUT_S = 30.0
LORA_LOAD_TOTAL_TIMEOUT_S = 120.0
# Loaded multi-DP servers can take minutes to finish an adapter update. Keep
# finite timeouts without retrying a healthy update after only a few seconds.
# The retry budget is checked between attempts, not as a hard outer deadline.
LORA_LOAD_READ_TIMEOUT_S = 300.0
LORA_LOAD_TOTAL_TIMEOUT_S = 600.0
async def load_lora_adapter(admin_clients: list[AsyncClient], lora_name: str, lora_path: Path) -> None:
+2 -3
View File
@@ -1,5 +1,4 @@
import os
import shutil
import signal
import socket
import subprocess
@@ -74,11 +73,11 @@ def branch_name() -> str:
@pytest.fixture(scope="session")
def output_dir(tmp_path_factory: pytest.TempPathFactory) -> Generator[Path, None, None]:
"""Fixture for temporary output directory for tests with automatic cleanup"""
"""Fixture for the tests' output directory. Never deleted — CI uploads run logs
from it on failure; runs start with ``--clean-output-dir`` for a fresh workspace."""
output_dir = Path(os.environ.get("PYTEST_OUTPUT_DIR", tmp_path_factory.mktemp("outputs")))
output_dir.mkdir(parents=True, exist_ok=True)
yield output_dir
shutil.rmtree(output_dir, ignore_errors=True)
@pytest.fixture(scope="session")
+1
View File
@@ -38,6 +38,7 @@ def rl_process(
"rl",
"@",
"configs/ci/integration/alphabet_sort.toml",
"--clean-output-dir",
"--wandb.project",
wandb_project,
"--wandb.name",
@@ -29,6 +29,7 @@ def rl_process(
"rl",
"@",
"configs/ci/integration/reverse-text-moe/start.toml",
"--clean-output-dir",
"--trainer.model.impl",
"custom",
"--wandb.project",
@@ -20,6 +20,17 @@ TIMEOUT = 600 # 10 minutes (was 300s — too tight when 3 concurrent orchestrat
ORCHESTRATOR_NAMES = ["alpha", "beta", "gamma"]
def remove_run_dir(run_dir: Path) -> None:
"""Delete a run dir, tolerating the shared trainer still flushing its tail
(token exports recreate directories mid-rmtree -> 'Directory not empty')."""
for _ in range(10):
shutil.rmtree(run_dir, ignore_errors=True)
if not run_dir.exists():
return
time.sleep(1)
shutil.rmtree(run_dir)
def wait_for_file(
file_path: Path,
timeout: int = 600,
@@ -274,7 +285,7 @@ def multi_run_result(
print(f"Copied alpha checkpoint to {tmp_path / 'alpha_ckpt_step_10'}")
# Remove alpha run directory
shutil.rmtree(output_dir / "run_alpha")
remove_run_dir(output_dir / "run_alpha")
# ===========================
# Queue alpha's resume proc
@@ -305,7 +316,7 @@ def multi_run_result(
shutil.copy(run_dir / "logs" / "orchestrator.log", log_dir / "beta_orchestrator.log")
shutil.copytree(beta_ckpt_dir, tmp_path / "beta_ckpt_step_20")
print(f"Copied {beta_ckpt_dir} to {tmp_path / 'beta_ckpt_step_20'}")
shutil.rmtree(run_dir)
remove_run_dir(run_dir)
# =====================
# Queue beta's resume
@@ -329,7 +340,7 @@ def multi_run_result(
timeout=TIMEOUT,
)
shutil.copy(output_dir / "run_gamma" / "logs" / "orchestrator.log", log_dir / "gamma_orchestrator.log")
shutil.rmtree(output_dir / "run_gamma")
remove_run_dir(output_dir / "run_gamma")
# ================================================
# Wait for alpha_resume and beta_resume to finish