* 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.
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).
* 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
* 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
* 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
* 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.
* 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.
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.
* 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>
* 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.
* 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
* 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>
* 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
* 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
* 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.
* 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
* 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
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.
* 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
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.
* 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.
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.
* 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)
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.
* 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
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().
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.
* 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
* 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
* 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>
* 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
* 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
* 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
* 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
* 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
* 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
* 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>
* 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>
* 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