76 Commits
Author SHA1 Message Date
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
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
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
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
JannikStandGitHub 31e81e5b18 feat: support PRIME_RL_REF for runtime source override (#2850)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: support PRIME_RL_REF for runtime source override

Mirrors the existing VERIFIERS_VERSION hook so researchers can dispatch
a run against an arbitrary prime-rl commit/branch/tag without rebuilding
the image. Clones into a per-ref dir under /tmp, seeds the venv from
/app/.venv so heavy wheels (flash-attn, mamba-ssm) survive, then
uv sync --inexact re-installs prime_rl from the override source.

* fix: address bugbot findings on PRIME_RL_REF entrypoint

- Slugify ref for cache dir name so branch names with slashes work.
- Always fetch + checkout on cache hit so mutable refs (branches/tags)
  pick up new commits between pod restarts.
- Move VERIFIERS_VERSION install after the PRIME_RL_REF swap so when
  both are set the install lands in the override venv.

* fix: init submodules and hash-key the override cache dir

- git clone --recurse-submodules so deps/* (verifiers, renderers,
  research-environments, pydantic-config) are populated on cold
  checkout, and refresh on every entrypoint via
  'git submodule update --init --recursive'.
- Rewrite git@github.com SSH URLs to https at runtime so the SSH
  submodule URLs work from pods that have no ssh keys.
- Append md5 hash of the ref to the cache dir name so distinct refs
  that slugify the same way ('feat/foo' vs 'feat-foo') get distinct
  cache dirs.

* fix: drop hardlink seed and key cache on repo+ref

- cp -al hardlinked /app/.venv into the override tree, so the
  subsequent uv sync wrote through to the baked venv on filesystems
  shared with /tmp. Plain cp -a always copies.
- Include PRIME_RL_REPO in the cache-dir hash so the same ref on
  different forks gets distinct cache dirs.

* fix: --all-extras on override sync

uv sync --inexact --no-dev only installed base deps, so env / gpt-oss /
modelexpress changes in the override branch were silently missed. With
--all-extras the override picks them up, and --inexact still keeps
flash-attn-3 / mamba-ssm from the seeded venv.

* fix: mirror image extras explicitly instead of --all-extras

--all-extras pulled in disagg/quack which the baked image does not
ship; their deps (deep-ep, deep-gemm, quack-kernels) would trigger
heavy source builds at pod startup. Mirror Dockerfile.cuda:82's set
exactly so the override venv lines up with the image.

* fix: submodule sync before update to pick up .gitmodules URL changes
2026-06-22 12:15:37 -07:00
JannikStandGitHub 146fcd0136 fix(inference): restore usage block on /inference/v1/generate (#2784)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(inference): restore usage block on /inference/v1/generate response

* fix(inference): apply ruff formatting

* fix(inference): drive _FinalOutputCapture through async-for, not __anext__

* fix(inference): always emit cached_tokens, drop enable_prompt_tokens_details gate

* chore: bump verifiers to fix/hatch-vcs-fallback-version

Pin to the fallback-version fix (PrimeIntellect-ai/verifiers#1650) so the
prime-rl Docker build resolves a version without VCS metadata. Temporary
pin to the PR branch; should move to verifiers main once #1650 lands.

* fix(inference): annotate _FinalOutputCapture source as AsyncIterable
2026-06-12 19:07:09 +02:00
JannikStandGitHub e6998a6f41 feat: json logging for inference (vLLM) (#2466)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: json logging for inference (vLLM)

Adds [log] config to InferenceConfig and routes vLLM's stdlib loggers
(plus uvicorn / fastapi / root) through a JSON formatter matching the
trainer/orchestrator shape. Driven via VLLM_LOGGING_CONFIG_PATH so the
config crosses the multiprocessing.spawn boundary into vLLM workers.

* chore: ruff format

* fix: force VLLM_CONFIGURE_LOGGING=1 when setting LOGGING_CONFIG_PATH

vLLM raises at import if VLLM_CONFIGURE_LOGGING=0 and
VLLM_LOGGING_CONFIG_PATH is set. Setting json_logging is an explicit
opt-in to configure vLLM's logger, so override the env var rather than
crash on jobs that have it preset to 0.

* fix: emit tz-aware UTC timestamps in JsonFormatter

Match loguru's tz-aware ISO output so the platform's JsonLogsViewer
parses inference timestamps correctly. Naive timestamps are interpreted
as the viewer's local time, off by the viewer-vs-pod offset.

* fix: propagate top-level [log] settings to inference subconfig

RLConfig.auto_setup_logs already mirrors [log] into trainer and
orchestrator subconfigs. Now that InferenceConfig has its own [log]
field, propagate there too — without this, an RL run with
[log] json_logging=true at the root still emits text vLLM logs because
inference.log defaults to non-JSON.

* fix: guard None inference in auto_setup_logs

RLConfig.inference is Optional and defaults to None for setups like
elastic-inference-pool runs. The previous commit propagated [log]
unconditionally, crashing the validator on any RLConfig without an
[inference] section (caught by the test_load_configs unit tests on
configs/elastic/rl.toml).

* fix: propagate top-level [log] settings to teacher_inference

Mirrors the auto_setup_logs propagation to inference, so teacher
inference servers also pick up shared level / json_logging when they
are configured separately or auto-created without a rollout inference
to deep-copy from.

* fix: map loguru-only levels (TRACE, SUCCESS) before dictConfig

Stdlib logging does not know TRACE/SUCCESS, so setting [log] level =
"trace" or PRIME_LOG_LEVEL=trace would crash setup_vllm_env when JSON
logging is enabled. Map TRACE→DEBUG and SUCCESS→INFO before building
the dictConfig payload.

* fix: route transformers logs through JSON handler

The docstring claimed transformers was covered but the named-loggers
tuple omitted it, so HF model-loading warnings/info were emitted as
plain text in otherwise-JSON inference logs (transformers sets
propagate=False on its own logger).

* fix: preserve per-component json_logging when shared [log] omits it

Codex P2: SharedLogConfig.json_logging defaulted to False, so auto_setup_logs would clobber any per-component (inference, teacher_inference) override back to text whenever the shared [log] section wasn't set. Mirrors the existing 'level' pattern: nullable on SharedLogConfig, gate propagation on the shared value being explicitly set.
2026-06-04 22:05:52 +02:00
JannikStandGitHub 63af82343d fix(trainer): guard against validation hook crash taking down trainer (#2698)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(trainer): don't crash trainer when validation hook fails

validate_lora_rank dereferenced student.model.lora without a None
check, so an orchestrator config with no LoRA section raised
AttributeError. The hook was called outside get_orchestrator_config's
try/except, so the exception propagated out of discover_runs through
the train loop, killed the master rank, and left worker ranks waiting
forever on rollouts that would never be written.

- Guard model.lora is None in validate_lora_rank so we reject cleanly
- Wrap hook calls in get_orchestrator_config in try/except so any
  future hook bug returns the run to the retry path instead of taking
  down the trainer

* fix(trainer): use safe fallback for hook name in error message

Validation hooks are typed as Callable, so hook.__name__ isn't
guaranteed (callable objects and functools.partial don't have it). If
such a hook raised, the exception handler itself would raise
AttributeError and defeat the try/except.

Per Codex review on #2698.
2026-06-04 18:41:03 +08:00
JannikStandGitHub 543e37eb3a Disable vLLM DeepGEMM by default (#2678)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-06-01 16:48:08 +02:00
JannikStandGitHub 4ecb92b534 Add ModelExpress to CUDA image (#2621)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* add ModelExpress to CUDA image

* add UCX runtime library to CUDA image

* build CUDA-enabled UCX for ModelExpress

* Keep protobuf 6 for ModelExpress image

* Scope ModelExpress protobuf metadata override

* Avoid empty UCX library path segment

* Cap ModelExpress protobuf metadata override
2026-05-27 01:59:26 +02:00
JannikStandGitHub f5e8113420 chore: drop environment gate on manifest job (#2624)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Each job referencing environment: ghcr-publish requires its own admin approval. manifest only combines arch-suffixed tags that build already pushed (and build was already approved), so a second approval doesn't add meaningful security but adds friction. Keep the gate on build.
2026-05-25 04:47:38 +02:00
ef773f1cee chore: add manual ghcr image build workflow (#2385)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore: also publish image to ghcr + add manual trigger

* chore: drop push/tag triggers, keep manual dispatch only

* chore: revert release.yaml, add manual ghcr build workflow

* fix: avoid script injection by passing inputs via env

* fix: trim trailing dash after tag truncation

* chore: dispatch build_image after creating dev tag

* multi platform builds (am64 and arm64)

* OCI metadata

* remove temporary push trigger

* trigger image builds when gh releases are published

* add step to init public submodules

* add pydantic-config to submodules

* should fail on failed image builds

* chore: gate ghcr publish on environment + ref/tag allowlist

- Require ghcr-publish environment for build and manifest jobs (admin approval)
- Reject refs other than main, v*, or *.dev*
- Disallow custom tag input unless ref=main, so a feature branch can't overwrite v1.2.3

* chore: allow tag input when it matches ref

Release events and the dev-tag auto-dispatch always pass ref==tag (e.g. v1.2.3/v1.2.3); the previous guard rejected those because tag was set and ref was not main. Only block when tag and ref diverge.

* chore: serialize same-tag builds and skip manifest job when single-arch

- Add concurrency group keyed on resolved tag so two runs for the same image queue rather than interleave (would otherwise mix arch digests in the unsuffixed manifest).
- Skip the manifest job when platforms != 'both' so a single-arch dispatch can't replace an existing multi-arch :tag with a single-arch index. The suffixed :tag-amd64 / :tag-arm64 are still pushed by build.

---------

Co-authored-by: eexwhyzee <13672394+eexwhyzee@users.noreply.github.com>
2026-05-25 03:15:55 +02:00
JannikStandGitHub 4df5b6229f fix: probe github ssh auth directly in install.sh (#2613)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix: probe github ssh auth directly in install.sh

The previous `has_ssh_access` probe ran `git ls-remote` against the
public prime-rl repo, which can return success under SSH connection
multiplexing, cached creds, or other states without the local key
actually being registered with a GitHub user. When that happens, the
HTTPS `insteadOf` rewrite is never applied and private-submodule
clones fail with "Permission denied (publickey)".

Use `ssh -T git@github.com` and grep for the canonical
"successfully authenticated" string instead. This is a direct check
of the precondition (your key is registered with a GitHub user) and
matches the pattern git itself recommends.

* fix: capture ssh output to var so pipefail doesn't mask success

`ssh -T git@github.com` always exits 1 (GitHub denies shell access
after authenticating), and install.sh has `set -o pipefail` at the
top, so the previous pipeline made has_ssh_access return failure even
for developers with valid keys. Capture stdout/stderr into a variable
first, then grep — keeps pipefail intact for the rest of the script.

* fix: use universal ssh options in github auth probe

`StrictHostKeyChecking=accept-new` requires OpenSSH 7.6+ (Sep 2017).
On older systems ssh errors with 'Bad configuration option' and the
probe wrongly reports no SSH auth, forcing HTTPS even when SSH would
have worked.

Use `StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null`
instead, which works on all OpenSSH versions. Safe for a probe-only
flow: no key material is exchanged, and a hostile MITM at worst
makes the probe wrongly report 'no SSH', causing HTTPS fallback for
public repos.

* fix: rely on ensure_known_hosts and default ssh host key checking

Previous commit disabled `StrictHostKeyChecking` and `UserKnownHostsFile`
to side-step OpenSSH version requirements, but that made the auth probe
trust any host that returns the "successfully authenticated" string —
a MITM could steer the script into using their SSH for submodule
clones.

`ensure_known_hosts` already runs (line 116) before any
`has_ssh_access` call and populates github.com via ssh-keyscan, so
default host key checking is both safe and sufficient. Drop the
options entirely; keep `BatchMode=yes` to suppress prompts.

* fix: propagate insteadOf to submodule clones via GIT_CONFIG_* env

`git submodule--helper clone` spawns fresh `git clone` processes
that read only ~/.gitconfig and env vars — not the parent repo's
local .git/config. So setting `url..insteadOf` locally never reached
the submodule clones, and they kept attempting SSH despite the probe
correctly reporting no auth.

Use `GIT_CONFIG_COUNT`/`GIT_CONFIG_KEY_0`/`GIT_CONFIG_VALUE_0` which
propagate the rewrite to every child git process for the duration of
this script, with no persistent state in ~/.gitconfig.
2026-05-24 04:58:21 +02:00
JannikStandGitHub 18e895651e accept fully-qualified expert names in lora check (#2301)
Release / Push CUDA image to Docker (push) Canceled after 0s
* accept fully-qualified expert names in lora check

* ruff format
2026-04-17 14:56:58 +02:00
JannikStandGitHub ba86b9ba88 Support runtime verifiers version override (#2274)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Support runtime verifiers version override via VERIFIERS_VERSION env var

When set, the entrypoint reinstalls verifiers from the specified git ref
(tag, branch, or commit) before starting the main process.

* Drop --no-deps so transitive deps are updated with verifiers override

* Use --reinstall-package to only reinstall verifiers, not the entire dep tree
2026-04-16 09:38:18 -07:00
JannikStandGitHub fa63a5a65a bump vllm-router to 0.1.20 (#2269)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-14 00:00:49 +02:00
f412e6d17e fix: prepend base_model.model. prefix to broadcast LoRA keys (#2242)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: prepend base_model.model. prefix to broadcast LoRA keys

* fix: normalize LoRA key prefix on both broadcast and loading sides

* simplify: rewrite safetensors file in-place instead of wrapping safe_open

* ruff format

* add file lock to prevent race condition between workers

* only acquire lock/write when keys actually need fixing

* revert base model patch in ckpts

* use upstream patch

---------

Co-authored-by: Jackmin801 <ongjackm@gmail.com>
2026-04-10 09:26:12 +02:00
JannikStandGitHub f07543e13c fix: unwrap list pad_token_id before huggingface_hub strict setter (#2240)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: unwrap list pad_token_id before strict setter assignment

* remove accidentally included test file
2026-04-09 21:42:28 +02:00
JannikStandGitHub 43ba157ba4 Bound admin client timeouts so a stuck inference server cannot wedge the orchestrator (#2230)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Bound admin client timeouts so a stuck inference server cannot wedge the orchestrator

setup_admin_clients used httpx.Timeout(None), so an unresponsive inference
server would hang the orchestrator forever inside update_weights /
load_lora_adapter (asyncio.gather across all admin clients makes one
stuck server stall the whole call). The existing tenacity retries only
fired on 404/500 status responses, never on a hung connection.

Replace the unbounded timeout with bounded per-phase timeouts (read=300s
covers legitimate LoRA load latency on large adapters), and widen the
retry predicate so transport-level failures (TimeoutException,
TransportError) actually retry instead of propagating as a hard error
on the first hiccup.

* Per-call NCCL timeouts on /init_broadcaster and /update_weights

The previous commit set the global admin-client read timeout to 300s,
which is shorter than the server-side NCCL store_timeout (default 1200s).
That would cause healthy NCCL init / weight broadcasts to abort with
ReadTimeout, and update_weights is not wrapped by tenacity so the abort
would propagate as a hard orchestrator failure.

Override the read timeout per call on the two endpoints whose server-side
work runs an NCCL collective:
- /init_broadcaster: derived from the actual NCCL timeout passed in
  (rendezvous timeout + 300s buffer).
- /update_weights: documented constant NCCL_OP_READ_TIMEOUT_S = 1500s,
  sized off the default NCCLWeightBroadcastConfig.timeout (1200s) plus
  headroom.

The global default stays at 300s so health checks, model checks and LoRA
loads still detect a stuck server quickly.

* Fix ruff format

* Narrow fix: bound only the LoRA load HTTP call

Previous commits on this branch tightened the global admin-client timeout
and added per-call timeouts on the NCCL paths to compensate. That was
overreach: the only call we have evidence of hanging is the
`/load_lora_adapter` POST inside ElasticInferencePool._sync_server_adapter.
NCCL collectives, weight broadcasts and health checks were never broken
by the unbounded global timeout, and touching them just dragged in
NCCL-timeout coupling concerns that shouldn't have been part of this fix.

Revert all the global / NCCL-path changes and apply the bound at the
exact call site that actually wedges:
- /load_lora_adapter POST gets a per-call read=300s timeout via
  httpx.Timeout, leaving the global admin-client timeout=None untouched.
- _is_retryable_lora_error keeps the TimeoutException / TransportError
  widening so tenacity bounds the total wall time across the 10 retries
  instead of letting the new timeout propagate as a hard failure.

* Tighten LoRA load timeouts and use tenacity stop_after_delay for the wall-clock cap

A LoRA load is single-digit seconds in practice; 300s read with 10
attempts and 30s backoff was effectively 'almost infinite'. Drop to a
30s per-attempt read timeout (still generous, just enough to convert a
hang into a TimeoutException that tenacity can see), and use tenacity's
own stop_after_delay(120s) as the wall-clock cap across all retries.
That keeps the bound in tenacity where it belongs — one number to tune,
no per-call wait_for or asyncio.wait reimplementation.

* Update tests for the new LoRA load timeout / retry behavior

- Existing assert_called_once_with broke because the call now passes a
  timeout= kwarg. Replace with explicit field-by-field assertions and
  also assert that timeout is set (the whole point of this PR).
- Add coverage for the widened _is_retryable_lora_error predicate
  (ReadTimeout, ConnectTimeout, ConnectError).
- Add a load_lora_adapter retry test that simulates a stuck server via
  ReadTimeout on the first attempt and succeeds on the second.

* Drop redundant predicate-level retry tests

The integration test test_load_lora_adapter_retries_on_timeout_then_succeeds
already exercises the retry-on-timeout path end-to-end, so the unit-level
predicate tests for TimeoutException / TransportError are redundant noise.

* Drop new lora-load retry test, keep minimal kwarg update
2026-04-08 19:53:17 +02:00
JannikStandGitHub 8b3faf4c2f Add training token usage reporting (#2210)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Add training token usage reporting for platform billing

Orchestrator reports training tokens per step to the platform API
for billing. Env-var driven (PI_USAGE_BASE_URL), not user-facing.

- New UsageReporter with background thread + async HTTP POSTs
- run_id captured after setup_monitor to fix timing bug
- Idempotent on (run_id, step, usage_type) for crash-resume safety
- Self-hosted users unaffected (no-op when env var unset)

* Add missing os import in orchestrator

* Simplify usage reporter env vars: PI_USAGE_BASE_URL + PI_USAGE_API_KEY

* Guard UsageReporter instantiation on env var

* Extract BackgroundAsync helper to reduce duplication

The async-client-on-background-thread pattern was duplicated between
PrimeMonitor and UsageReporter. Extract a small reusable helper
(BackgroundAsync) and use it via composition in UsageReporter.

UsageReporter drops from ~160 lines to ~70 lines. PrimeMonitor still
has its own copy and can be migrated to BackgroundAsync in a follow-up
to avoid touching unrelated monitor logic in this PR.

* usage_reporter: drop init log to debug, use f-string

The platform's JSON formatter prints record.msg raw rather than
calling getMessage(), so the printf-style %s placeholder showed up
literally in logs. Switch to an f-string. Also drop the init line
to debug since it fires every run and isn't actionable -- warnings
on actual reporting failures are still surfaced at WARNING level.

* usage_reporter: require API key, gate orchestrator on both env vars

Cursor bot caught a real issue: when PI_USAGE_BASE_URL was set but
PI_USAGE_API_KEY was not, self._api_key was None and httpx rejected
the {"x-api-key": None} header with an obscure .encode() error on
every retry. Reports silently failed three times then logged a
confusing warning.

Fix in two layers:
- Orchestrator only constructs UsageReporter when BOTH env vars are
  set, with a clear warning if one is set without the other.
- UsageReporter.__init__ validates both and raises ValueError so
  any future caller (or unit test) fails fast at construction time
  instead of inside httpx.

* Drop usage_reporter unit tests per review
2026-04-08 19:49:18 +02:00
JannikStandGitHub 0216d2cf5b Bound orchestrator post-training cleanup with hard timeout (#2229)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Bound orchestrator post-training cleanup with hard timeout

The orchestrator's post-training cleanup awaits scheduler/inference pool/
env teardown without any deadline. If any of those awaits wedges on a
remote peer (env-server ZMQ recv, inference admin httpx aclose, etc.) the
run pod sits in RUNNING forever even though training and the final
checkpoint upload have completed.

Wrap the cleanup sequence in an asyncio.wait with a 60s budget. If it
doesn't finish in time, log a warning and force-exit via os._exit so the
pod terminates and the run flips out of RUNNING. asyncio.wait_for is
deliberately not used because it would itself hang on an uncancellable
inner await — exactly the failure mode we're guarding against.

* Bump shutdown timeout to 5 minutes

* Re-raise cleanup exceptions on the non-timeout path

asyncio.wait does not propagate exceptions from the wrapped task. Without
this, a fast failure inside _graceful_shutdown would leave pending empty
and silently fall through to the success log. await the task once it is
done so cleanup errors surface the same way they did when each step was
awaited directly.
2026-04-08 16:03:03 +02:00
JannikStandGitHub 1b62360fbf Add qwen3_vl_moe to VLM registry (#2196)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-04-04 13:22:15 +02:00
JannikStandGitHub b1d37e9dd6 Point vllm-router at PrimeIntellect-ai/router v0.1.13 (#2167)
Release / Push CUDA image to Docker (push) Canceled after 0s
* improvement: point vllm-router at PrimeIntellect-ai/router v0.1.13

- Update pre-built wheel URL from samsja/flash-attn-builds (v0.1.11)
  to PrimeIntellect-ai/router releases (v0.1.13)
- Update install script from S1ro1 fork to PrimeIntellect-ai/router main

* fix: update router wheel URL to v0.1.14 with correct naming

* ci: retry after release assets available

* chore: update uv.lock for router v0.1.14

* chore: remove install_vllm_router.sh, wheels are now pre-built in CI
2026-04-01 14:43:55 +02:00
JannikStandGitHub 58fc060d31 Add watchdog to packer to detect silent hangs (#2142)
Release / Push CUDA image to Docker (push) Canceled after 0s
* add watchdog to packer to detect silent hangs

packer on rank 0 can silently hang on NFS I/O, leaving all other
ranks waiting forever for rank_N.bin files. adds a heartbeat +
watchdog thread that kills the process after 30min of no progress,
letting the StatefulSet restart recover automatically.

* scope watchdog to only be active during pack()

watchdog is now armed/disarmed around pack() in wait_for_batch()
so long training steps, checkpoints, or weight broadcasts don't
trigger false-positive restarts.

* wrap pack() in try/finally to always disarm watchdog
2026-03-31 14:08:26 -07:00
JannikStandGitHub dec92c1423 fix: add weights_only=False to torch.load for checkpoint resume (#2112)
Release / Push CUDA image to Docker (push) Canceled after 0s
PyTorch 2.9 defaults torch.load to weights_only=True, which blocks
deserialization of DTensor types like _StridedShard used in EP checkpoints.
This caused checkpoint resume to fail silently on 397B models with EP=8.
2026-03-26 18:14:04 -07:00
JannikStandGitHub 80a52899ea fix: exclude disagg extras from image build (requires CUDA 13) (#2108)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-26 06:10:23 +01:00
JannikStandGitHub 801995a341 fix: skip vllm-router on arm64 (x86_64-only wheel) (#2103)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-25 23:24:23 +01:00
JannikStandGitHub 381733e0cf fix: terminate process on fatal orchestrator error (#2092)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: use sys.exit(1) in clean_exit to terminate process on fatal error

raise alone doesn't terminate the process in async context - the event
loop swallows the exception and the process hangs indefinitely, leaving
runs stuck in RUNNING state with leaked pods.

* fix: remove unused exception variable for ruff
2026-03-25 03:54:52 +01:00
JannikStandGitHub 692dfc8a4b fix mamba-ssm build by using CUDA torch in build env (#2091)
Release / Push CUDA image to Docker (push) Canceled after 0s
mamba-ssm needs nvcc and CUDA torch to compile. uv was resolving
CPU-only torch for the build environment, causing bare_metal_version
to be undefined. Adding match-runtime = true ensures the CUDA torch
from pytorch-cu128 index is used during the build.
2026-03-24 17:33:11 -07:00
JannikStandGitHub 58f4b37d5b Add router_url support for elastic inference pool (#2049)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Add router_url support for elastic inference pool

When configured, inference requests route through a vllm-router
while admin operations (weight updates, LoRA loading) still go
directly to discovered pods via elastic DNS discovery.

* Gate router traffic on ready servers

Only expose the router client when there are actually ready backends,
preventing requests from being sent to a router with no healthy pods
during weight updates or scale-down.
2026-03-20 02:11:39 +01:00
JannikStandGitHub bd110a10e9 fix: cleanup env subprocesses on orchestrator crash (#2028)
Release / Push CUDA image to Docker (push) Canceled after 0s
atexit handler ensures spawned env server processes are terminated when
the orchestrator crashes, preventing orphaned subprocesses that keep the
container alive and leave the run stuck in RUNNING.
2026-03-18 05:13:42 +01:00
JannikStandGitHub 3639f0ab4f fix _tied_weights_keys for transformers v5 compat (#1998)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-09 16:07:05 -07:00
JannikStandGitHub deecddc4af fix crash when pad_token_id is a list in model config (#1991)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-09 17:08:57 +01:00
JannikStandGitHub 89a5343780 fix arm64 flash-attn-cute: revert to 2b5db43 for sm100 pipeline fix (#1982)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix arm64 flash-attn-cute: use 2b5db43 rev with sm100 pipeline fix

* also update fix-flash-attn-cute.sh to 2b5db43
2026-03-07 23:23:26 +01:00
JannikStandGitHub f0746566e9 fix arm64 flash-attn: run uv pip from /tmp to avoid pyproject.toml build vars (#1975)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-07 02:10:43 +01:00
JannikStandGitHub 99c02bba6c fix arm64 flash-attn build: override FLASH_ATTENTION_SKIP_CUDA_BUILD (#1974)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix arm64 flash-attn build: override FLASH_ATTENTION_SKIP_CUDA_BUILD

* also set FLASH_ATTENTION_FORCE_BUILD to bypass cached wheel download
2026-03-07 00:12:09 +01:00
JannikStandGitHub ebb5a1cac2 add --no-cache to force flash-attn source build on arm64 (#1973)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-06 21:43:45 +01:00
JannikStandGitHub d19ce7919f force flash-attn source build on arm64 with --no-binary (#1972)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-06 21:02:18 +01:00
JannikStandGitHub e2175c11ae add aarch64 vllm wheel and restrict uv environments to linux x86_64/aarch64 (#1970)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-06 10:53:20 +01:00
JannikStandGitHub d4bfa08977 Add arm64 support to Dockerfile and deps (#1933)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Add arm64 support to Dockerfile and deps

- Swap builder base to multi-arch nvidia/cuda:12.8.1 image
- Add platform_machine markers to x86_64-only wheel deps

* Fix tzdata interactive prompt in arm64 build

* Fix tzdata interactive prompt in Docker build

* add arm64 flash-attn source build and expose max_num_seqs on inference CLI

* only target sm_100 for arm64 flash-attn build

* remove max_num_seqs, belongs in a separate PR

* also build flash-attn-3 from source for arm64, supports sm_100

* use pip for flash-attn-3, uv cant resolve torch match-runtime from git

* use pip for flash-attn-3: uv rejects match-runtime without static metadata

* link uv issue in dockerfile comment

* use venv pip for flash-attn-3, pip not on PATH in builder

* use uv run pip for flash-attn-3

* install pip into venv before using it for flash-attn-3

* fix arm64 flash-attn build: export env vars, add ninja

* fix: install python ninja package, export all env vars properly

* remove flash-attn-3 from arm64 build, fa4 (flash-attn-cute) is used instead

* Fix missing cutlass.utils.ampere_helpers on arm64 (#1948)

* Fix missing cutlass.utils.ampere_helpers on arm64

flash-attn.cute imports cutlass.utils.ampere_helpers but
nvidia-cutlass-dsl 4.4.1 doesn't ship that module. Copy it
from flashinfer's vendored cutlass which has the file.

* Expand Dockerfile comment explaining cutlass ampere_helpers workaround

* Reinstall flash-attn-cute after flash-attn on arm64 to fix namespace conflict (#1949)

* Pin flash-attn-cute to locked commit, upstream renamed package to flash-attn-4 (#1950)

* Upgrade flash-attn-cute for cutlass-dsl 4.4.1 backward pass fix (#1952)

* Upgrade flash-attn-cute to 7ed0898 for cutlass-dsl 4.4.1 compatibility

* Pin fix-flash-attn-cute.sh to same commit as pyproject.toml

* Pin flash-attn-cute to 2b5db43 for cutlass-dsl 4.4.1 compat and sm100 backward fix

* refactor: extract arm64 post-install logic into script

* skip arm64 script entirely on x86, trim comments

* update uv.lock

* revert pydantic-config to branch=main

* pin flash-attn==2.8.3 in arm64 post-install

* pin flash-attn-cute to e2743ab5, regenerate uv.lock

* align flash-attn-cute rev in scripts with pyproject.toml (e2743ab5)
2026-03-06 09:56:16 +01:00
JannikStandGitHub 99058e9e37 bump nvidia-cutlass-dsl to 4.4.1 for flash-attn-cute ampere_helpers (#1945)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-03-04 05:54:10 +01:00
JannikStandGitHub df50bd2eb1 remove disown from orchestrator in multi-node sbatch template (#1907)
Release / Push CUDA image to Docker (push) Canceled after 0s
disown detaches the orchestrator from the shell job table, preventing
it from receiving SIGHUP on shell exit. This causes the orchestrator
and its env server subprocesses to survive as orphans after job
cancellation, leading to port conflicts on subsequent runs.
2026-02-26 20:29:43 -08:00
JannikStandGitHub 1ea7a8d3b5 fix: handle skipped eval intervals when ckpt_step jumps (#1903)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: handle skipped eval intervals when ckpt_step jumps + fix eval step reporting

When strict_async_level=False, ckpt_step can jump over eval interval
boundaries (e.g. 24->26 skipping 25), permanently missing scheduled evals.
Replace exact modulo check with range check that detects crossed intervals.

Also fix eval metrics being logged at progress.step instead of ckpt_step,
which caused eval results to appear at the wrong step in the metrics API.

* format ruff

* revert step=ckpt_step back to step=progress.step for eval logging

W&B requires monotonically increasing steps. Using ckpt_step (which lags
behind progress.step) causes W&B to silently drop eval metrics since
training already logged at a higher step. The ckpt_step is already
embedded in the metrics as progress/ckpt_step for platform-side lookup.

* fix stale comment about eval subprocess

* add unit tests for eval scheduling range check

* extract eval scheduling logic into compute_eval_ckpt_step function

Move range check logic from inline in orchestrator.py to a proper
function in eval_utils.py so tests import the real implementation.

* use plain functions instead of class in tests
2026-02-27 01:45:14 +01:00
JannikStandGitHub bc55a1c85a pass json_logging to env servers (#1823)
Release / Push CUDA image to Docker (push) Canceled after 0s
* pass json_logging to env servers

- pass json_logging to ZMQEnvServer in standalone env-server entrypoint
- add json_logging param to spawn_env_server()
- pass config.log.json_logging in orchestrator spawn calls

* bump verifiers to 013d4da (json_logging support)

* remove duplicate
2026-02-18 16:18:23 +01:00
JannikStandGitHub 26db10418e WIP fix: call evaluate with explicit keyword arguments (#1792)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: call evaluate with explicit keyword arguments

* chore: apply ruff format to vf utils

* fix: lazy client selection for elastic inference during evals

* refactor: make clients optional, remove redundant params from eval calls
2026-02-15 14:06:11 -08:00
JannikStandGitHub 8117c00ad6 Fix checkpoint step ordering bug (#1762)
Use bisect.insort to maintain sorted order when adding new checkpoint steps.
Previously, appending to the list could break sort order when saving a checkpoint
with a step number lower than existing ones, causing AssertionError in maybe_clean().
2026-02-11 17:24:17 +01:00
JannikStandGitHub 8695aa10f8 Strip @version suffix from env IDs before loading as Python modules (#1724)
Platform sends versioned env IDs (e.g. d42me/meow@0.1.5) for installation.
The version must be stripped before passing to vf.load_environment() since
importlib.import_module() cannot handle @ in module names.
2026-02-05 20:58:58 +01:00
JannikStandGitHub 0041a93a45 Fix int64 JSON serialization in Chinese character metrics (#1725) 2026-02-05 10:27:59 +01:00
9d40e5e6bf fix: use stable checkpoints for orchestrator resume (#1712)
* fix: use stable checkpoints for orchestrator resume

Only consider checkpoints with STABLE file when resuming, preventing
crash when orchestrator restarts before trainer finishes saving weights.

* fix: wait for checkpoint to become stable with timeout instead of skipping

* feat: make stability timeout configurable with 1000s default

* chore: log stability wait every 60s instead of 30s

* fix: add opt-in wait_for_stable_checkpoint config for orchestrator resume

* refactor: extract wait_for_stable_checkpoint helper, minimal orchestrator change

* fix: sort imports

* fix: import resolve_latest_ckpt_step from utils

* fix: formatting

* fix: add wait_for_weights_timeout option to wait for weight dir when resuming

* Update src/prime_rl/orchestrator/utils.py

Co-authored-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Signed-off-by: JannikSt <JannikSt@users.noreply.github.com>

* cleanup contd.

* format

* readd docstring

* remove unused import

* adjust path for stable file

* ensure weight dirs exist

---------

Co-authored-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
2026-02-04 03:08:40 +01:00
JannikStandGitHub d74bf06d27 Add podManagementPolicy: Parallel to inference and trainer StatefulSets (#1718) 2026-02-04 01:52:58 +01:00
JannikStandGitHub 64c214bf9c Add health probes for inference and trainer (#1719)
* Add health probes for inference and trainer components

* Disable health probes by default
2026-02-04 01:51:52 +01:00
JannikStandGitHub 3194b161a6 Add JSON structured logging for log aggregation (#1681)
* Add JSON structured logging option for log aggregation

* Add CHANGELOG entry and fix default value pattern

* Pass JSON logging config to env workers

* Wire JSON logging to all entrypoints (eval, synthesize, sft)

* Pass JSON logging to eval subprocesses

* Rename json to json_logging to avoid Pydantic shadowing warning

* Use flat JSON format for log aggregation instead of loguru serialize

* Fix exception handling in JSON logger sinks

* Remove [verifiers] prefix from intercepted logs

* Fix outdated docstring for intercept_verifiers_logging

* Refactor JSON logging: dedupe, non-blocking sinks, fix CHANGELOG

* Remove unused close method from _JsonFileSink

* Include worker tag in JSON log output

* Create parent directories for JSON file sink

* Restore [verifiers] prefix for intercepted logs

* Rename json parameter to json_logging in setup_logger for consistency

* Replace tqdm with ProgressTracker for JSON logging compatibility

When JSON logging is enabled, progress bars are replaced with periodic
log messages (every 10%) to avoid garbled output. When disabled, tqdm
works as before.

* Fix file handle leak and emit structured progress events

- Add atexit cleanup for _JsonFileSink file handle
- Progress events now emit structured JSON with type/current/total/percent fields
- Remove unused is_json_logging function
- Add proper type hints for postfix dict

* Add step context to progress events and fix 0% jump

- Add optional step parameter to ProgressTracker
- Include step in JSON output and tqdm desc
- Don't emit 0% on init (only on actual progress)

* Keep tqdm output unchanged, only add step to JSON mode

* Remove enqueue=True from non-JSON handlers to fix tqdm

enqueue=True causes loguru to use background thread which
interferes with tqdm's terminal output. Only needed for JSON mode.

* Remove unreachable else branch in _emit_progress

* Fix typo in get_logger docstring

* Add lock to prevent interleaved JSON output

Both _json_sink (loguru background thread) and _emit_progress write
to stdout - without synchronization they can corrupt JSON lines.

* Route progress through loguru for single output path

Instead of writing directly to stdout (which needed a lock),
progress events now go through loguru with _progress marker.
_build_log_entry detects and formats them specially.

* Add level field to progress events for consistency
2026-02-03 00:21:52 +01:00
JannikStandGitHub e5566f9819 Add HF Hub timeout defaults to Dockerfile (#1699)
Defaults are 10s which causes issues on slow networks or large model downloads.
2026-01-31 16:23:32 -08:00
JannikStandGitHub 667fb388fa bump prime to 0.5.24 (#1673)
* bump prime to >=0.5.24

* update uv.lock for prime 0.5.24
2026-01-26 23:41:41 -08:00
JannikStandGitHub 9d1581479c Revert "bump prime minimum version to 0.5.23 (#1664)" (#1669)
This reverts commit d6552d6d15.
2026-01-26 17:06:53 -08:00
JannikStandGitHub d6552d6d15 bump prime minimum version to 0.5.23 (#1664)
* bump prime minimum version to 0.5.23

* update uv.lock for prime 0.5.23
2026-01-26 20:35:46 +01:00
JannikStandGitHub beb8ef3c66 Add INFO log when orchestrator resumes after checkpoint wait (#1638) 2026-01-22 04:22:43 +01:00
JannikStandGitHub e1663ba065 Add elastic inference pool with DNS-based service discovery (#1617)
* Add elastic inference pool with DNS-based service discovery

- Add ElasticInferencePool for tracking pod readiness and adapter sync
- Main process discovers pods via K8s headless service DNS
- Only exposes pods with correct LoRA adapter as "ready" to workers
- Workers receive ready URLs via callback to prevent model-not-found errors
- Fully backwards compatible with static base_url configuration

* Fix tests: use asyncio.run() pattern instead of pytest-asyncio

* Fix: pass ready URLs to workers in elastic mode

* Generalize elastic inference pool to support any DNS-based discovery

- Rename headless_service to hostname (works with any DNS with multiple A records)
- Rename pod terminology to server throughout (not K8s-specific)
- Update docstrings to mention Kubernetes as one option among many

* Add changelog entry for elastic inference pool

* Fix min_pods -> min_servers parameter name

* Validate elastic inference requires LoRA training

* Add health and base model check before marking server as discovered

* Remove servers that fail health checks during sync

* Change elastic pool logs from info to debug

* fix: queue rollout requests when no inference servers available

- Clear clients when URLs become empty (instead of keeping stale clients)
- Queue incoming requests while waiting for servers to become ready
- Process queued requests once servers are available again
- Add NoServersAvailableError safety check in process_request

* fix: avoid false adapter match on default step=0

Only match by step when step > 0 to prevent false matches when
both loaded and desired adapters have default step=0 but different paths.

* test: fix elastic tests for health check changes

- Mock _check_server_health in _add_server and sync tests
- Add test for step=0 not causing false adapter matches
- Add test for health check failure in _add_server
- Add tests for _check_server_health method

* feat: support elastic inference for non-LoRA training

Elastic pool now works for base model inference too. Servers are
ready once they pass health check and have the base model loaded.

* fix: address cursor bot concerns

- Compare URLs as sets to avoid spurious callbacks from order changes
- Close old inference clients before creating new ones to prevent connection leaks

* refactor: use Literal type for server status

* docs: simplify elastic pool descriptions

* test: convert to pytest function style

* fix: address copilot review feedback

- Move time import to module level
- Use empty list instead of fallback to base_url in elastic mode
- Add comments to except:pass blocks

* docs: clarify sync_interval unit is seconds

* refactor: rename sync_interval to sync_interval_s for clarity

* rename update_weights to sync_adapter in elastic pool

* rename sync_adapter back to update_weights, remove test_elastic.py

* refactor: workers do own DNS discovery, remove callback pattern

- Workers discover servers via DNS and check /v1/models directly
- Majority vote: use all healthy servers if no adapter, only adapter servers otherwise
- Remove callback/URL push machinery from scheduler and elastic pool
- Simplify elastic.py to only handle admin operations (adapter sync)

* fix: pass model_name per-request for LoRA compatibility

* Simplify orchestrator: remove worker_client_config branching

* Restore comments in extract_result

* Encapsulate elastic mode behind InferencePool abstraction

* Move discovery functions to elastic.py to reduce duplication

* Restore comments in env_worker.py

* Fix type annotations - remove unnecessary string quotes

* Fix code review issues: rename sync_weights to public, add debug logging

* Add unit tests for elastic inference pool

* refactor: consolidate elastic config handling in WorkerServerDiscovery

- Remove redundant elastic params from env_worker (hostname, port, sync_interval)
- Extract elastic config from ClientConfig inside workers
- Add WorkerServerDiscovery class to encapsulate worker-side discovery
- Simplify worker loop logic, remove duplicate get_clients calls
- Convert tests to function-based format

🤖 Generated with [Claude Code](https://claude.com/claude-code)

* refactor: move client discovery logic to WorkerServerDiscovery class

* restore inline comment

* remove redundant update_model_name - model name is fixed at init

* restore update_model_name method

* move update_model_name to original location

* fix test: patch setup_clients function instead of non-existent method

* fix: dedupe servers, guard elastic requires LoRA, don't close clients mid-request

* fix: workers start with base model name, switch to LoRA after loading

* add logging for model switch and tests for update_model_name

* fix test: mock queue put to avoid multiprocessing timing issues

* make inference_pool required parameter in Scheduler

* cache inference clients in ElasticInferencePool to avoid recreating on each access

* update worker discovery model name when request model changes (LoRA switch)

* fix: multi-adapter detection, refactor InferencePool to Protocol

- fix _get_loaded_adapter to filter by adapter name when multiple adapters loaded
- unify LoadedAdapter and DesiredAdapterState into AdapterState
- refactor InferencePool to Protocol with StaticInferencePool and ElasticInferencePool implementations
- remove unused admin_clients param from Scheduler
- fix discover_ready_servers to only return servers with requested model (no fallback)
- add tests for multi-adapter case

* refactor: clean up elastic discovery with shared utility functions

- Add ServerDiscovery class for env workers (DNS discovery + client management)
- ElasticInferencePool uses same discovery functions
- Shared logic via utility functions: discover_server_ips, discover_ready_servers
- Remove mode flags and unnecessary abstractions

* remove early elastic+lora validation from orchestrator (handled in ElasticInferencePool.update_weights)

* add debug logging for adapter mismatch + parallelize sync_weights

* add more debug logging for adapter matching

* close inference clients on ElasticInferencePool shutdown
2026-01-22 02:26:01 +01:00
d7742b9569 Add AGENTS.md and CLAUDE.md (#1627)
* Add AGENTS.md and CLAUDE.md for AI coding agents

- AGENTS.md as source of truth for all AI agents
- CLAUDE.md imports AGENTS.md for Claude Code compatibility

* Update AGENTS.md

---------

Signed-off-by: JannikSt <JannikSt@users.noreply.github.com>
Co-authored-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
2026-01-21 02:02:09 +01:00
JannikStandGitHub c69c615cfb Add retry with exponential backoff for empty training batches (#1622)
* Add exponential backoff retry for empty training batches

When inference becomes temporarily unavailable, all rollouts may fail
resulting in an empty batch. Instead of crashing, retry the step with
exponential backoff (30s, 60s, 120s, 240s, 300s cap) up to 5 times.

* Cancel validation task before retry to avoid accumulation

* Fix off-by-one: use >= for retry count check
2026-01-20 18:55:32 +01:00
JannikStandGitHub a9b5aa5cdf Fix trainer crash when all rollouts in a batch fail (#1596)
* Fix trainer crash when all rollouts in a batch fail

When all rollouts fail (e.g., conversations exceed context limit), the tensor is empty and compute_stats() crashes on .min()/.max() calls. Skip stats computation for empty tensors.

* Emit NaN for empty tensor stats instead of skipping
2026-01-20 03:10:32 +01:00
JannikStandGitHub 571d48135c Auto-restart env workers on unexpected death (#1609)
* Auto-restart env workers on unexpected death

- Add restart() method to EnvWorker
- Modify collect_responses() to auto-restart with warning log
- Scheduler catches WorkerDiedError and continues instead of crashing
- Add unit tests for restart functionality

* Fix: join dead process to prevent zombies

* Add max restart limit (5) to prevent infinite restart loops

* Make max_worker_restarts configurable via orchestrator config

* Rename to max_env_worker_restarts for clarity

* Support -1 for unlimited restarts

* Fix AI review feedback on worker restart behavior

- Reset restart count after 10 successful responses (prevents
  isolated failures over time from accumulating)
- Store fatal error on worker so orchestrator can detect and crash
  when max restarts exceeded
- Fix misleading log message that claimed auto-restart unconditionally
- Add _check_for_fatal_worker_errors() to crash orchestrator properly

* Remove elastic utility file

* Remove k8s references from config and scheduler

* Make restart method private

* Fix test mock to use _restart
2026-01-20 02:58:09 +01:00
JannikStandGitHub bdfbfae982 Add health endpoint for worker nodes in multi-node training (#1601)
* Add health endpoint for worker nodes in multi-node training

- Add HealthServer base class with /health endpoint only
- MetricsServer now extends HealthServer
- Worker nodes start HealthServer, master gets full MetricsServer
- Add tests for HealthServer

* Fix port conflict: only start server on local_rank 0 per node

* Fix ruff formatting

* Format test file

* Fix ruff lint errors

* remove transient error testfile
2026-01-16 06:56:40 +01:00
JannikStandGitHub c330a6d4eb Add InfiniBand libraries for NCCL multi-node support (#1600)
* Add InfiniBand libraries for NCCL multi-node support

* Fix: remove comment breaking Dockerfile line continuation
2026-01-15 14:28:05 -08:00
88da7cb296 fix: detect dead worker process in collect_responses (#1546)
* fix: detect dead worker process in collect_responses

Previously if a worker subprocess crashed, collect_responses() would loop forever waiting for responses. Now it checks process.is_alive() and raises RuntimeError with exit code.

* fix: remove unused import

* fix: rewrite tests as sync to avoid pytest-asyncio dependency

* Add _stopping flag to skip dead worker error during shutdown

* Reset _stopping flag in start() to fix restart detection

* Remove unused tests for EnvWorker subprocess management

Co-authored-by: jannik <jannik@primeintellect.ai>

* Fix race condition and pending futures on worker death

* Prevent scheduler from routing to dead workers

* Drain response queue before checking dead worker

* Add WorkerDiedError to propagate through scheduler for K8s restart

* Fix exit code race condition in rl.py main loop

* Check subprocess return codes directly after loop
2026-01-12 12:58:52 +01:00
JannikStandGitHub 355e742a69 Add optional Prometheus metrics server for trainer (#1547)
* Add optional Prometheus metrics server for trainer observability

- Exposes /metrics endpoint with training metrics (step, loss, throughput, grad_norm, etc.)
- Disabled by default, enable via `metrics_server.port` config
- Uses isolated CollectorRegistry per instance
- prometheus_client is optional dependency (uv sync --extra metrics)

* Update lockfile for prometheus_client optional dep

* Add changelog entry for metrics_server

* Convert tests to function style

* Clean up Prometheus metrics naming and add mismatch_kl

- Remove rft_ prefix from all metrics (trainer_* instead of rft_trainer_*)
- Add trainer_mismatch_kl metric for tracking KL divergence

* Add per-run/LoRA metrics to Prometheus server

Aggregate metrics:
- trainer_runs_discovered: run folders found
- trainer_runs_active: runs with assigned slots
- trainer_runs_ready: runs ready for gradient updates
- trainer_runs_max: maximum run capacity

Per-run metrics (with labels):
- trainer_run_step{run="run_001"}: training step
- trainer_run_tokens{run="run_001"}: total tokens processed
- trainer_run_learning_rate{run="run_001"}: current LR
- trainer_run_ready{run="run_001"}: ready status (1/0)

* Add /health endpoint for K8s liveness probes

- Add HealthCheckConfig with max_step_age_seconds and startup_grace_seconds
- Add /health endpoint to MetricsServer for trainer liveness checks
- Fix socket leak in stop() by calling server_close() and joining thread

* Use heartbeat instead of step-age for health checks

- Rename max_step_age_seconds to timeout_seconds
- Add heartbeat() method called every loop iteration
- Detects hung main thread even when waiting for runs

* Add optional on_wait callback to sync_wait_for_path

* Revert unused on_wait callback

* Simplify /health to always return 200
2026-01-09 19:59:29 +01:00
d621e8889d Add retry logic to load_lora_adapter for NFS delays (#1520)
* Add retry logic to load_lora_adapter for NFS delays

Uses tenacity with exponential backoff (1-30s) for up to 10 attempts.
Retries on 404 (adapter not found) and 500 (server error) which can
occur due to NFS propagation delays between trainer broadcast and
inference server load.

* Add unit tests for load_lora_adapter retry logic

* Fix tests: use asyncio.run instead of pytest.mark.asyncio

* Refactor tests to pytest function style (no classes)

* Fix: Adjust reward check thresholds and step in lora integration test

Co-authored-by: ongjackm <ongjackm@gmail.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: ongjackm <ongjackm@gmail.com>
2026-01-01 01:09:32 -08:00
2a7a767ef5 improvement: avoid blocking orchestrator event loop with sync barrier (#1318)
* avoid blocking full orchestrator with sync waiting for stable file, add new async barrier

* make logging less verbose

* make level more understandable

* improve logging setup, only log waiting for trainer once, remove unecessary loggig in policy update. it essentially just waits for the checkpoint to arrive so its technically misleading

* update logs

---------

Co-authored-by: Mika Senghaas <mail@mikasenghaas.de>
2025-11-29 01:10:33 -08:00
JannikStandGitHub 6edca61a6e run ci in vm (#1319)
* run ci in vm

* adjust container setup

* remove unecessary setup step

* review

* bump timeouts
2025-11-20 06:56:44 +01:00
JannikStandGitHub 33ec40b36a K8s Support, Helm Chart and reverse text example on k8s (#1307)
* add basic helm chart based k8s support with reverse text example

* sleep once training completes instead of restarting

* cleanup k8s docs

* remove redundant logs

* nitpick on docs

* improve prime-rl example

* fix logic issue in examples

* additional readme perfectionism

* adjust get pods command

* removing nccl for now, will come back later with ib support for k8s

* apply valid k8s findings
2025-11-19 20:09:34 +01:00
JannikStandGitHub 2e5cf1d82f fix dockerfile uv not working, fix missing entrypoint, add ulimit (#1297)
* fix dockerfile uv not working, fix missing entrypoint, add ulimit

* adjust / cleanup dockerfile

* improve Dockerfile, move entrypoint script
2025-11-18 00:49:40 +01:00
JannikStandGitHub 46ad665231 improve docker experience for development (#1295) 2025-11-15 19:07:51 -08:00
JannikStandGitHub 61fe294cab imp: tmuxinator replacement (#564)
* replace tmuxinator with standard tmux config
2025-07-12 10:28:03 +02:00
JannikStandGitHub 5b11610591 Fix missing task ID in monitor.py (#328)
* fix missing taskid in monitor
2025-05-28 18:10:24 +10:00