Compare commits

...
Author SHA1 Message Date
halleriteandGitHub 51dc60a895 chore: dead-code sweep across trainer, orchestrator, utils, and configs (#2932)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-02 09:49:14 +02:00
halleriteandGitHub a8f090b444 chore: delete dead get_adapter_state_dict from trainer/weights.py (#2929)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-02 03:51:09 +02:00
halleriteandGitHub cdea189e3d chore(configs): remove dead max_retries knob from Env/Train/EvalConfig (#2930)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-02 03:50:54 +02:00
halleriteandGitHub d5f218f708 chore(configs): remove empty *ExperimentalConfig placeholders (#2931)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-02 03:14:56 +02:00
halleriteandGitHub a03c70f55b chore: delete dead utils/tensor_hashing.py (#2928)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-02 02:21:33 +02:00
e48a53853e fix: weight-sync hardening + dead-code / get_max_layer_num cleanup (#2922)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix: correct weight-broadcast validation + prefix-cache docs

- validate_shared_weight_broadcast: the chained comparison
  `trainer.type != orchestrator.type != inference.type` only compared
  adjacent pairs, so a mismatched inference weight_broadcast type
  (e.g. trainer/orchestrator=nccl, inference=filesystem) passed validation
  silently. Check trainer vs orchestrator, then inference vs both.
- update_weights / load_lora_adapter docstrings claimed the server resets
  the prefix cache on weight update; it doesn't — the orchestrator salts
  the prefix cache per weight version (cache_salt, see orchestrator/envs.py).
  Fix the docs and drop the dead reset_prefix_cache_after_update state flag
  (set but never read).
- heartbeat: docstring said "2s timeout"; the request uses timeout=1.

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

* chore: remove dead code in trainer/utils

Grep-verified as unused across src/:
- qwen3_moe: load_balancing_loss_func (aux-loss-free routing is used instead)
- rl/loss.py: shift_logits
- perf.py: _count_trainable_params
- kernels/fp8_utils.py: align()
- kernels/fp8_indexer.py: dead `_weight_scale = weight_scale` assignment
  (kernel intentionally ignores weight_scale, per its NOTE)
- layers/moe.py: leftover commented-out forward variant
- utils/utils.py: capitalize, to_row_format, mean_normalize
- broadcast/nccl.py: import NCCL_READY_MARKER from utils.client instead of
  redefining the same constant

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

* refactor: consolidate get_max_layer_num into trainer/weights

Seven converting_*.py modules each defined their own get_max_layer_num —
six as a fragile `int(key.split(".")[2])` one-liner and afmoe as a regex
variant that returned the max index (its callers compensated with
`range(max_layer + 1)`). Replace all seven with the canonical, robust
implementation in trainer/weights.py (handles an arbitrary layer_prefix,
guards non-digit segments, already used by the NCCL broadcaster).

- afmoe: the canonical returns a count (max+1), so its two callers switch
  from `range(max_layer + 1)` to `range(num_layers)` — behavior-identical.
- No import cycle: weights.py imports neither trainer.models nor the
  converting modules.

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

* refactor: centralize flash-attn varlen import guard

afmoe and qwen3_5_moe each re-declared the identical three-way
try/except import guard for flash_attn_varlen_func / _3_ / _4_ that
already exists in trainer/models/layers/attn.py. Import the (None-able)
module-level names from attn.py instead; each model's `_funcs` dispatch
table is unchanged.

Note: their attention classes are genuinely model-specific (gated output,
local/global split, MRoPE, GatedDeltaNet), so they legitimately do NOT
subclass the shared FlashAttention — only the optional-dependency import
guard was duplicated.

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

* fix: break circular import from get_max_layer_num consolidation

The consolidation made the converting_*.py modules import trainer/weights.py,
but weights.py imports trainer/lora.py, which (via trainer/models/__init__)
imports the model modules and their converting_*.py — closing a cycle:

  lora -> models/__init__ -> afmoe/modeling -> converting_afmoe
    -> weights -> lora (partially initialized) -> ImportError

Move get_max_layer_num into a dependency-free leaf module
trainer/conversion_utils.py (imports only torch) and point the seven
converting modules + the NCCL broadcaster at it. weights.py no longer
defines it (it never used it internally). Keeps the single-source dedup
without the cycle.

Caught by the reverse_text integration tests (trainer crashed at import).

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
2026-07-01 19:12:57 +01:00
f3c85a947a exp: update swe ablation (#2925)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* exp: add glm45air scaleswe length-penalty ablation config

Length-penalty variant of configs/debug/v1/glm45air_scaleswe.toml: enables the
GRPO linear length penalty with output-token, input-token, and turns coefficients
all set to 0.1, using the current [orchestrator.algo.length_penalty] schema on main.
Distinct -lp SLURM job name, wandb run name, and prime sandbox labels.

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

* exp: move scaleswe length-penalty config to configs/glm45air/swe.toml

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

* exp: move glm45air scaleswe config to configs/glm45air/swe.toml, use rlm harness

Promote configs/debug/v1/glm45air_scaleswe.toml to configs/glm45air/swe.toml as a
move + update: switch the train and eval harness from default to rlm, enable the
GRPO linear length penalty (all coefs 0.1), and drop the -lp suffix from the SLURM
job name and prime sandbox labels (labels can't reference $SLURM_JOB_NAME — that
field is passed verbatim to the sandbox API — so the literal must match the job name
that the pre-launch cleanup deletes by).

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

* exp: drop -lp from wandb run name

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 10:53:58 -07:00
f19ba721a9 chore(configs): bump dist_timeout_seconds default to 3600 (#2924)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The 600s default torch/NCCL distributed timeout was too tight for
large multi-node runs — startup collectives (step-0 evals, slow first
SWE batches) tripped the watchdog and SIGABRT'd the trainer. Bump the
default to 3600s for both RL and SFT trainer configs.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 10:23:35 -07:00
fd5db5df6a chore(deps): add longpdfs-v1 environment to pyproject.toml + uv.lock (#2920)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The longpdfs-v1 environment was added to research-environments main
(commit f1bdab50f, PR #542) but was missing from this PR's pyproject.toml.

- Add longpdfs-v1 to envs optional dependencies and [tool.uv.sources]
- Add longpdfs-v1 package entry to uv.lock

Co-authored-by: Sami Jaghouar <sami@primeintellect.ai>
2026-07-01 10:16:22 -07:00
halleriteandGitHub 7b7c7efdfa chore(configs): migrate v1 harness ids for the verifiers null/default rename (#2919)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-01 06:38:52 +02:00
2e2accb121 fix(deps): enable verifiers[harbor] extra so swebench-verified eval loads (#2917)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The `swebench-verified-v1` (and other Harbor) tasksets require the Harbor
CLI, shipped via the `harbor` extra of the `verifiers` package. The root
project depended on plain `verifiers`, and `uv sync --all-extras` only
enables the root project's own extras (not a dependency's), so `harbor`
was never installed — the eval env-pool worker crashed in `load_tasks()`
with `RuntimeError: Harbor tasksets require the Harbor CLI`.

Switch the root dep to `verifiers[harbor]` so `harbor==0.14.0` is pulled
in (and lands on SLURM compute nodes via the sbatch `uv sync --all-extras`).

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 12:34:51 -07:00
436873190d fix: schedule tail eval rollouts before draining at max_steps (#2913)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(dispatcher): wait for partly-scheduled eval groups before reporting idle

is_idle only checked the eval_source queue, but an eval example leaves the queue when its group
opens (next_fresh_group) while its group_size rollouts dispatch one at a time across fill_inflight
passes. In the window where the queue is empty, an eval group still has rollouts_to_schedule > 0,
and inflight/out_q are momentarily empty, is_idle wrongly reported drained — main_loop exits, the
tail eval rollouts are never scheduled, the eval batch never completes, and the eval point is
dropped. This hits hardest at max_steps, where the final eval triggers just as the train side is
cancelled.

Factor the eval-has-work predicate (queue OR any pending eval group) into a shared
RolloutDispatcher.eval_has_work property used by both is_idle and fill_inflight so they can't drift.

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

* test: drop dispatcher unit test — verify the tail-eval fix via e2e instead

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 11:06:17 -07:00
f0c339a234 [ENG-4306] fix(docker): repair CUDA image build broken by uv 0.11.25 centralized project envs (#2906)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(docker): pin uv project env to /app/.venv

uv's centralized/cached project environments (a preview feature as of uv
0.11.25, and a likely future default) make `uv sync` build the env in the
uv cache and leave `.venv` as a symlink into it. The runtime stage ships the
env via `COPY --from=builder /app /app`, which can't follow that symlink (the
cache store lives outside /app), so the venv goes missing and the build fails
at the `bin/python` relink.

Setting UV_PROJECT_ENVIRONMENT=/app/.venv forces uv to materialize a real
in-project venv directory regardless of that behavior, so the cross-stage copy
keeps working even if/when the feature graduates from preview to the default.

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

* fix(uv): drop vestigial `preview = true`

This flag was added in #1772 solely to silence a `uv run` warning on an
older uv (~Feb 2026). That warning no longer fires on uv >= 0.11.9 (verified
with and without preview on `uv run` and `uv lock`), so the opt-in is dead
weight.

It is not harmless dead weight: `preview = true` enables uv's *entire*
experimental feature surface, including features added in future releases.
uv 0.11.25 shipped the `centralized-project-envs` preview feature, which the
global opt-in silently activated — relocating the project env into the uv
cache and leaving `.venv` as a symlink into it. The Docker image build COPYs
only `/app`, so that symlink dangled in the runtime stage and the venv went
missing (`rm /app/.venv/bin/python` failed). Dropping the flag removes the
root enabler of that class of breakage.

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

* use system python intepreter and remove the re-linking steps

* clean up comments

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 10:32:15 -07:00
9f425fffcb feat(metrics): unify train/eval rollout metrics over the all/effective matrix (#2907)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(metrics): unify train/eval rollout metrics over the all/effective matrix

Closes #2903.

Replace the two divergent rollout-metric paths — the pandas-heavy MetricsBuilder
(train) and the hand-rolled EvalBatchMetrics.to_wandb_dict (eval) — with one shared,
pandas-free, unit-tested function `compute_rollout_metrics`, logged over the matrix:

    {train,eval} / {agg,<env>} / {all,effective} / <metric> / <stat>

- `all` = every rollout that came back (errored + filtered included); `effective` =
  its non-errored, non-filtered subset (~ what actually trained). The gap between them
  is the filtering/error cost, now directly comparable per metric.
- Train retains the full arrival window (TrainSink.arrivals_window → TrainBatch.all_rollouts)
  so an `all` set exists; eval already kept its full cohort.
- All metrics apply to both train and eval except pass@k / pass^k (eval-only; pass^k is
  new) and the filter-pipeline rates (train-only — eval has no filters).
- Drop pandas from this path; aggregation is plain Python (flat means/max/min/rates,
  group-by only for solve rates).

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

* refactor(metrics): rename token metrics to num_*_tokens, drop no_response, top-level is_filtered

- seq_len / prompt_len / completion_len -> num_total_tokens / num_input_tokens /
  num_output_tokens, matching the renamed vf.Trace properties
- remove the no_response metric
- log is_filtered as a top-level rollout metric (was filters/is_filtered); per-filter
  detection rates stay under filters/<name>

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

* feat(metrics): add full timing phases, reward components, is_completed

- timing: add setup + finalize spans; timing/total now sums all four phases
  (setup + generation + finalize + scoring) instead of just generation + scoring
- rewards/<name>: per-reward-component breakdown (mirrors metrics/<name>)
- is_completed/mean: a finished-on-its-own-terms rate alongside is_truncated

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

* refactor(metrics): rename effective_batch_size -> solved_some

Names the mixed-reward-group rate consistently with its solve_none / solve_all siblings.

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

* refactor(metrics): solve_none/solve_all -> solved_none/solved_all

Consistent solved_none / solved_some / solved_all trio.

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

* feat(metrics): log eval reward as avg@<k> instead of reward/mean

Eval reports the mean reward under the conventional avg@<group_size> key (a single value via
the new reward_label arg); train keeps the reward mean/max/min distribution. Same value,
eval-friendly name.

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

* refactor(metrics): split into compute_train_metrics / compute_eval_metrics over a shared core

Replace the single flag-driven compute_rollout_metrics with two functions sharing
_common_metrics: train adds the reward distribution + filter-pipeline rates; eval adds the
avg@<k> score + pass@k/pass^k. Drops the include_filters / include_pass_at_k / reward_label
flags and the train/eval branching from the call sites.

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

* refactor(metrics): rename error_rate -> has_error/mean

Consistent with the other per-rollout boolean rates (is_truncated/mean, is_completed/mean).

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

* refactor(metrics): move rollout_metrics.py back into metrics.py

Reclaim the conventional module name vacated by the old MetricsBuilder. Rename the source +
test (rollout_metrics.py -> metrics.py, test_rollout_metrics.py -> test_metrics.py) and fix
the stale compute_rollout_metrics doc references left from the train/eval split.

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

* feat(metrics): rename progress/{samples,problems} -> progress/{rollouts,tasks}

Also the cumulative keys: progress/total_samples -> progress/total_rollouts,
progress/total_problems -> progress/total_tasks. Metric-key renames only; the internal
Progress counter fields are unchanged (they're pickled in the orchestrator checkpoint).

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

* refactor(types): TrainBatch.rollouts = all rollouts + .effective view (symmetric with EvalBatch)

TrainBatch.rollouts now holds the full arrival window (errored + filtered included), matching
EvalBatch.rollouts. Both expose an `effective` property — the non-errored, non-filtered subset
as a view (references, not copies), so each expensive trace is retained once. Drops the separate
TrainBatch.all_rollouts field.

Consumers repointed: metrics over rollouts (all) + effective; sample/distribution logging and the
success-line quality metrics over effective; disk/progress/efficiency over rollouts (all).

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

* refactor(metrics): inline the dist spec list; make helpers public (dist_stats, rate, common_metrics)

Drop the _DIST_SPECS (name, getter) table — the five distributional metrics are emitted inline
in common_metrics. Rename the module helpers to clearer public names: _dist -> dist_stats,
_rate -> rate, _common_metrics -> common_metrics.

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

* refactor(metrics): drop redundant TrainBatchMetrics fields derivable from batch.rollouts

With TrainBatch.rollouts holding the full arrival window, several aggregates are redundant:
- arrivals_by_env / errors_by_env — per-env arrival/error counts = grouping batch.rollouts
  (and errored ones) by env; derive them in log_train_batch instead.
- samples_shipped — equalled len(batch.samples) and had no consumers.

The sink no longer tracks the per-env counters. Kept n_trainable (shipped non-filtered count,
feeds the empty-batch guard) and num_prefill/decode_tokens (cohort totals including filtered
rollouts, so not a sum over samples).

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

* refactor(metrics): rollout-container API (TrainRollouts/EvalRollouts with .metrics, .effective)

Replace the functional compute_train/eval_metrics with list-like rollout containers:
- TrainRollouts / EvalRollouts own the rollouts (append/__len__/__iter__), expose .effective
  (clean subset, same container type — a view), .by_env (train), and .metrics.
- TrainMetrics / EvalMetrics (over RolloutMetrics) expose each distributional/rate metric as a
  Stat (rollouts.metrics.num_input_tokens.mean()) and build the full {prefix}/{subset}/... dict
  via .to_wandb(); special metrics (solve rates, stop_condition, pass@k, custom/<name>) are methods.
- TrainBatch.rollouts / EvalBatch.rollouts are now these containers; TrainBatchMetrics is dropped
  (n_trainable + prefill/decode token totals are fields on TrainBatch).

solve_rates uses each group's actual size as the full-solve threshold (config-free metrics).

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

* refactor(metrics): derive trainable count + token totals, slim TrainBatch to {rollouts, samples}

- Add Rollout.is_trainable (a nonzero advantage on some token ⇒ carries gradient) and a
  train-only is_trainable/mean metric; the trainable count is now derived from the rollouts,
  not carried as TrainBatch.n_trainable.
- Drop TrainBatch.{n_trainable, num_prefill_tokens, num_decode_tokens}: prefill/decode totals
  derive from batch.samples (the shipped payload — excludes filtered rollouts, so the usage
  reporter no longer over-counts), and the empty-batch guard keys on `not batch.samples` (the
  precise "nothing shipped to the trainer" stall signal) instead of a zero count.
- Rename TrainSink.arrivals_window → pending_rollouts (matches pending_batch / pending_groups).
- Compute num_tokens / rollout / unique-example counts once in finalize_train_batch (were
  computed twice).

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

* refactor(metrics): nest timing as a sub-metric (metrics.timing.setup.mean())

Collapse the five flat timing_* Stat properties into a TimingMetrics sub-object reached via
metrics.timing, so per-phase durations read as metrics.timing.setup.mean() / .total.mean().
wandb keys (timing/<phase>/<stat>, timing/total/<stat>) are unchanged.

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

* fix(metrics): solved_all counts only reward==1.0 groups

Restore the binary "fully solved" semantics: a group is solved_all when every rollout scored
exactly 1.0 (was: every rollout had a nonzero reward, which over-reported solved_all for
continuous / partial-credit rewards). Config-free (no env group_size lookup); unspecified for
non-binary reward ranges.

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

* refactor(metrics): derive prefill/decode tokens from effective rollouts, not samples

progress/prefill_tokens, progress/decode_tokens, and the training usage report now sum the
effective rollouts' Trace.num_input_tokens / num_output_tokens (the shipped subset — its
branches are exactly what `samples` concatenates) instead of summing masks over batch.samples.
No metric is computed over `samples` anymore. progress/tokens stays over the full window.

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

* refactor(orchestrator): build the eval success line from the metrics API

Replace the hand-rolled reward/turns/truncation/error/branches sums in finalize_eval_batch with
effective.metrics / rollouts.metrics Stat accessors. Stat.mean() returns 0.0 for an empty set,
so this also drops the per-field empty guards (and fixes a latent ZeroDivisionError on the
branches mean for an empty cohort).

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

* refactor: move compute_pass_metrics into orchestrator/utils.py, drop eval_utils.py

compute_pass_metrics was the only thing in eval_utils.py; fold it into the existing
orchestrator/utils.py and delete the one-function module.

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

* refactor(orchestrator): name token totals input/output (vf v1 convention)

Rename the per-step token breakdown from prefill/decode to input/output to match the vf v1
Trace token naming used across the metric matrix: progress/input_tokens, progress/output_tokens,
and the usage report sum r.num_input_tokens / r.num_output_tokens over the effective subset
(the same props the matrix reports), rather than deriving a prefill/decode split.

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

* refactor(metrics): add p10/p90 stats, derive eval group size, inline timing phases

- Stat gains p10/p90 (linear-interpolated percentiles); to_dict now emits mean/max/min/p10/p90.
- EvalMetrics derives the avg@<k> group size from the rollouts (largest group) instead of
  carrying a passed int, so EvalRollouts no longer needs a group_size argument — everything is
  derived from the rollout list.
- Drop the TimingMetrics._phase helper; inline the per-phase Stat into each phase property.

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

* refactor(metrics): generic StatGroup for timing/metrics/rewards; drop quoted forward refs

- Extract a StatGroup base (named Stats → {prefix}/<name>/<stat> via to_dict, group[name] access);
  TimingMetrics (fixed phases) and a new CustomMetrics (dynamic per-rollout dict keys) both subclass
  it. metrics.metrics / metrics.rewards are now nested StatGroups (like metrics.timing), replacing
  the shared custom(attr) helper.
- Drop the string-quoted forward refs (list["Rollout"], Iterator["Rollout"], "TrainRollouts", …) —
  the module already has `from __future__ import annotations`, so the annotations resolve unquoted.

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

* refactor(orchestrator): build the train success line from the rollout container

Drop the hand-rolled arrivals_by_env / errors_by_env dicts and per-env quality sums in
log_train_batch; derive everything from batch.rollouts (.metrics for the aggregate error rate,
.effective.metrics for quality, .by_env() for the per-env lines). Same output, no manual aggregation.

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

* refactor(metrics): trim tests; drop dead EvalRollouts.append + batch_share manual dict

- Tests: fold the fluent-access test into the to_wandb test, merge the two boolean-rate tests and
  the two train-only-metric tests, add a train_wandb() helper, drop the unused has_response field
  from the rollout fake. Same coverage, 222→184 lines.
- Remove EvalRollouts.append (eval wraps a finished list, never appends — unlike TrainRollouts).
- finalize_train_batch: build the per-env batch/<env> shares from rollouts.by_env() instead of a
  hand-rolled env-count dict (same as the log_train_batch cleanup).

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

* feat(metrics): error-type breakdown by count; fix eval avg@k key split; small cleanups

- Add an error/<type> breakdown (counts of errored rollouts by Trace error type, e.g. Cancelled /
  ProviderError), emitted on the `all` subset alongside has_error/mean (mirrors stop_condition's
  per-key breakdown, but by count to match the old cancelled_count/errored_count).
- Fix eval avg@<k>: derive the group size once from the full epoch in EvalRollouts and carry it onto
  .effective, so `all` and `effective` share one stable avg@<k> key (was derived per-subset, so an
  eval error could split it into avg@4 vs avg@3).
- Drop the dead is_filtered clause from EvalRollouts.effective (eval never filters); bind effective
  once in log_train_batch.

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

* fix(train_sink): preserve the rollout window across empty (no-ship) batches

process_batch reset pending_rollouts unconditionally, but the orchestrator drops an empty batch
(no samples) without logging it — so that window's metrics/record were lost and any overflow left
in pending_batch shipped a later step unattributed. Reset the window only when the batch ships, so
a no-ship batch's arrivals (and overflow) carry into the next shipped batch's window.

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 22:15:11 -07:00
61 changed files with 1116 additions and 1019 deletions
+10 -5
View File
@@ -32,6 +32,10 @@ RUN apt-get update && apt-get install -y --no-install-recommends --force-yes \
libnl-route-3-dev \
libibverbs-dev \
librdmacm-dev \
python3.12 \
python3.12-venv \
python3.12-dev \
&& ln -sf /usr/bin/python3.12 /usr/local/bin/python \
&& apt-get clean autoclean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
ARG UCX_VERSION=1.19.1
@@ -60,8 +64,13 @@ ADD https://astral.sh/uv/install.sh /uv-installer.sh
# Set install dir to location accessible to non-root users
RUN INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR="/usr/local/bin" sh /uv-installer.sh && rm /uv-installer.sh
ENV PATH="/usr/local/bin:$PATH"
ENV UV_PYTHON_INSTALL_DIR="/usr/local/share/uv/python"
# Build .venv against the system CPython, so the venv's recorded interpreter
# matches the runtime interpreter and no bin/python relink is needed at runtime.
ENV UV_PYTHON_PREFERENCE=only-system
ENV UV_CACHE_DIR="/usr/local/share/uv/cache"
# Explicity set venv dir inside /app so to ensure it gets copied over during
# the runtime stage's `COPY /app`
ENV UV_PROJECT_ENVIRONMENT="/app/.venv"
# Install Python dependencies (The gradual copies help with caching)
WORKDIR /app
@@ -219,10 +228,6 @@ COPY --from=builder /opt/ucx /opt/ucx
COPY --chown=appuser:appuser scripts/docker-entrypoint.sh /app/docker-entrypoint.sh
RUN chmod +x /app/docker-entrypoint.sh
RUN rm /app/.venv/bin/python && ln -s /usr/local/bin/python /app/.venv/bin/python
RUN rm /app/.venv/bin/python3 && ln -s /usr/local/bin/python /app/.venv/bin/python3
RUN rm /app/.venv/bin/python3.12 && ln -s /usr/local/bin/python /app/.venv/bin/python3.12
# Place executables in the environment at the front of the path
ENV PATH="/app/.venv/bin:$PATH"
ENV UCX_HOME=/opt/ucx
@@ -23,7 +23,7 @@ max_completion_tokens = 64
[[orchestrator.train.env]]
name = "color-codeword"
taskset = { id = "color-codeword-v1", images_per_turn = 1, num_examples = 1000 }
harness = { id = "default", runtime = { type = "subprocess" } }
harness = { id = "null", runtime = { type = "subprocess" } }
[trainer]
+1 -1
View File
@@ -42,7 +42,7 @@ max_completion_tokens = 64
[[orchestrator.train.env]]
name = "color-codeword"
taskset = { id = "color-codeword-v1", images_per_turn = 1, num_examples = 1000 }
harness = { id = "default", runtime = { type = "subprocess" } }
harness = { id = "null", runtime = { type = "subprocess" } }
# Default renderer (AutoRendererConfig) resolves Qwen3-VL-4B-Instruct from
# MODEL_RENDERER_MAP to Qwen3VLRenderer at runtime; no explicit name needed.
+1 -1
View File
@@ -37,6 +37,6 @@ max_completion_tokens = 768
[[orchestrator.train.env]]
name = "alphabet-sort"
taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, power_per_turn = false }
harness = { id = "default", runtime = { type = "subprocess" } }
harness = { id = "null", runtime = { type = "subprocess" } }
[inference] # Default inference config
+1 -1
View File
@@ -42,7 +42,7 @@ name = "qwen3"
[[orchestrator.train.env]]
# v1 general-agent solver taskset; the tool server is colocated in the harness's modal sandbox.
taskset = { id = "general-agent-v1", tools = { colocated = true } }
harness = { id = "default", runtime = { type = "modal" } }
harness = { id = "null", runtime = { type = "modal" } }
[inference]
gpu_memory_utilization = 0.85
+2 -2
View File
@@ -23,7 +23,7 @@ max_completion_tokens = 2048
[[orchestrator.train.env]]
taskset = { id = "gsm8k-v1", split = "train" }
harness = { id = "default", runtime = { type = "subprocess" } }
harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 20
@@ -34,7 +34,7 @@ max_completion_tokens = 2048
[[orchestrator.eval.env]]
taskset = { id = "gsm8k-v1", split = "test" }
harness = { id = "default", runtime = { type = "subprocess" } }
harness = { id = "null", runtime = { type = "subprocess" } }
[trainer] # Default trainer config
+2 -2
View File
@@ -30,7 +30,7 @@ max_inflight_rollouts = 256
[[orchestrator.train.env]]
name = "hendrycks-math"
taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
harness = { id = "default", runtime = { type = "modal" } }
harness = { id = "null", runtime = { type = "modal" } }
timeout = { scoring = 300 }
[orchestrator.eval]
@@ -39,7 +39,7 @@ interval = 50
[[orchestrator.eval.env]]
name = "aime2024"
taskset = { id = "aime24-v1" }
harness = { id = "default", runtime = { type = "modal" } }
harness = { id = "null", runtime = { type = "modal" } }
timeout = { scoring = 300 }
group_size = 32
+1 -1
View File
@@ -27,7 +27,7 @@ max_completion_tokens = 128
taskset = { id = "reverse-text-v1" }
# reverse-text is a pure-text single-turn env: disable the bash tool (the model answers
# directly) and use the subprocess runtime (no docker).
harness = { id = "default", runtime = { type = "subprocess" } }
harness = { id = "null", runtime = { type = "subprocess" } }
# No eval block, mirroring examples/reverse_text/rl.toml — this is a train-only
# smoke. Add an [orchestrator.eval] block (with an interval) to exercise eval.
@@ -1,7 +1,11 @@
# v1 RL ablation: GLM-4.5-Air (100B MoE) on the v1 `scaleswe-v1` SWE taskset, bash_edit harness on
# a prime sandbox runtime; eval on SWE-Bench Verified. Router replay is enabled
# (trainer.enable_router_replay replays the routed-expert decisions returned by inference via
# enable_return_routed_experts) — GLM-4.5-Air is a glm4_moe model, which supports routed_experts.
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe-v1` SWE taskset, rlm harness on a prime sandbox
# runtime; eval on SWE-Bench Verified. Router replay is enabled (trainer.enable_router_replay replays
# the routed-expert decisions returned by inference via enable_return_routed_experts) — GLM-4.5-Air is
# a glm4_moe model, which supports routed_experts.
#
# GRPO uses the linear length penalty with the output-token, input-token, and turns coefficients all
# set to 0.1. Each term is pass_rate-scaled and normalized by the group's own max before the GRPO
# baseline subtraction.
#
# 2 train + 4 infer nodes. Trainer uses cp=8 (ulysses) plus
# the memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
@@ -82,6 +86,15 @@ group_size = 16
max_off_policy_steps = 32
max_inflight_rollouts = 512
[orchestrator.algo]
type = "grpo"
# Linear length penalty at coef 0.1 on all three terms (output tokens, input tokens, turns).
[orchestrator.algo.length_penalty]
num_output_tokens_weight = 0.1
num_input_tokens_weight = 0.1
num_turns_weight = 0.1
[orchestrator.renderer]
name = "glm-4.5"
thinking_retention = "all"
@@ -89,11 +102,11 @@ thinking_retention = "all"
[[orchestrator.train.env]]
name = "scaleswe"
taskset = { id = "scaleswe-v1" }
harness = { id = "bash_edit", runtime = { type = "prime", labels = ["glm45air-swe"] } }
harness = { id = "rlm", runtime = { type = "prime", labels = ["glm45air-swe"] } }
[orchestrator.prime_monitor]
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, bash_edit harness on prime ---
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, rlm harness on prime ---
[orchestrator.eval]
interval = 20
@@ -102,7 +115,7 @@ skip_first_step = false
[[orchestrator.eval.env]]
name = "swebench-verified"
taskset = { id = "swebench-verified-v1", use_prime_registry = true }
harness = { id = "bash_edit", runtime = { type = "prime", labels = ["glm45air-swe"] } }
harness = { id = "rlm", runtime = { type = "prime", labels = ["glm45air-swe"] } }
timeout = { rollout = 3600 }
# --- Inference ---
+1 -1
@@ -337,10 +337,6 @@ InferenceDeploymentConfig: TypeAlias = Annotated[
]
class InferenceExperimentalConfig(BaseConfig):
pass
class InferenceConfig(BaseConfig):
server: ServerConfig = ServerConfig()
@@ -436,8 +432,6 @@ class InferenceConfig(BaseConfig):
dry_run: bool = False
"""Only validate and dump resolved configs, then exit early."""
experimental: InferenceExperimentalConfig = InferenceExperimentalConfig()
@model_validator(mode="after")
def validate_multi_node_requires_slurm(self):
if self.deployment.type in ("multi_node", "disaggregated") and self.slurm is None:
@@ -160,9 +160,6 @@ class EnvConfig(vf.EnvServerConfig):
ratio: float | None = Field(None, gt=0)
"""Sampling weight for this environment in the buffer. When None for all envs, samples uniformly across all available problems. When set, must be set on all envs — values are relative weights normalized to probabilities (e.g. [1, 1] and [0.5, 0.5] are equivalent)."""
max_retries: int = Field(3, ge=0)
"""Times the env server retries a failed rollout before returning an error."""
@model_validator(mode="before")
@classmethod
def _migrate_num_workers(cls, data):
@@ -193,9 +190,9 @@ class EnvConfig(vf.EnvServerConfig):
def validate_env(self):
if not self.taskset.id and not self.id:
raise ValueError('no env configured — set taskset = { id = "<id>" } (v1) or id = "<id>" (v0/legacy)')
if self.resolved_name == "all":
if self.resolved_name == "agg":
raise ValueError(
'Environment name "all" is reserved for global metric aggregation. Use a different name or id.'
'Environment name "agg" is reserved for cross-env metric aggregation. Use a different name or id.'
)
return self
@@ -248,13 +245,10 @@ class TrainConfig(BaseConfig):
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Shared training sampling configuration."""
max_retries: int = Field(3, ge=0)
"""Default retries for failed rollouts. Can be overridden per env."""
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling and max_retries (the
worker ``pool`` is configured per env, defaulting to elastic)."""
"""Resolve per-env overrides: inherit group-level sampling (the worker ``pool``
is configured per env, defaulting to elastic)."""
group_sampling = self.sampling.model_dump()
for env in self.env:
if "sampling" not in env.model_fields_set:
@@ -262,8 +256,6 @@ class TrainConfig(BaseConfig):
else:
merged = group_sampling | env.sampling.model_dump(exclude_unset=True)
env.sampling = TrainSamplingConfig(**merged)
if "max_retries" not in env.model_fields_set:
env.max_retries = self.max_retries
return self
@model_validator(mode="after")
@@ -299,9 +291,6 @@ class EvalConfig(BaseConfig):
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
"""Default rollouts per example. Can be overridden per env."""
max_retries: int = Field(3, ge=0)
"""Default retries for failed rollouts. Can be overridden per env."""
interval: int = Field(100, ge=1)
"""Step interval at which to evaluate the model."""
@@ -311,7 +300,7 @@ class EvalConfig(BaseConfig):
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling, max_retries, num_examples,
"""Resolve per-env overrides: inherit group-level sampling, num_examples,
group_size, and interval (the worker ``pool`` is configured per env, default elastic)."""
group_sampling = self.sampling.model_dump()
for env in self.env:
@@ -326,8 +315,6 @@ class EvalConfig(BaseConfig):
env.group_size = self.group_size
if "interval" not in env.model_fields_set:
env.interval = self.interval
if "max_retries" not in env.model_fields_set:
env.max_retries = self.max_retries
return self
@model_validator(mode="after")
@@ -443,10 +430,6 @@ WeightBroadcastConfig: TypeAlias = Annotated[
]
class OrchestratorExperimentalConfig(BaseConfig):
pass
class OrchestratorConfig(BaseConfig):
algo: AlgoConfig = GRPOAlgoConfig()
"""Training algorithm: sampling plus the per-token training signal (credit
@@ -563,8 +546,6 @@ class OrchestratorConfig(BaseConfig):
heartbeat: HeartbeatConfig | None = None
"""BetterStack heartbeat configuration for monitoring training progress."""
experimental: OrchestratorExperimentalConfig = OrchestratorExperimentalConfig()
@model_validator(mode="before")
@classmethod
def _env_to_train(cls, data: Any) -> Any:
@@ -46,10 +46,6 @@ from prime_rl.utils.validation import (
)
class RLExperimentalConfig(BaseConfig):
pass
class SharedLogConfig(BaseConfig):
level: str | None = None
"""Log level for trainer, orchestrator, and inference. When unset, each sub-config's own log level applies (defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``)."""
@@ -234,8 +230,6 @@ class RLConfig(BaseConfig):
dry_run: bool = False
"""Only validate and dump resolved configs, then exit early."""
experimental: RLExperimentalConfig = RLExperimentalConfig()
### Validate configs (e.g. raise for unsupported (combinations of) configs)
@model_validator(mode="after")
@@ -167,10 +167,6 @@ SFTDeploymentConfig: TypeAlias = Annotated[
]
class SFTExperimentalConfig(BaseConfig):
pass
class SFTConfig(BaseConfig):
model: ModelConfig = ModelConfig()
@@ -226,7 +222,7 @@ class SFTConfig(BaseConfig):
trace_path: Path | None = None
"""Path to write the PyTorch profiler trace to."""
dist_timeout_seconds: int = 600
dist_timeout_seconds: int = 3600
"""Timeout in seconds for torch distributed ops."""
loss_impl: Literal["liger", "torch", "liger_fused", "quack_fused"] = "torch"
@@ -243,8 +239,6 @@ class SFTConfig(BaseConfig):
dry_run: bool = False
"""Only validate and dump resolved configs, then exit early."""
experimental: SFTExperimentalConfig = SFTExperimentalConfig()
### Pre-validation normalization
@model_validator(mode="before")
@@ -554,7 +554,7 @@ class TrainerConfig(BaseConfig):
trace_path: Path | None = None
"""Path to write the PyTorch profiler trace to."""
dist_timeout_seconds: int = 600
dist_timeout_seconds: int = 3600
"""Timeout in seconds for torch distributed ops."""
heartbeat: HeartbeatConfig | None = None
@@ -1,7 +1,6 @@
from pathlib import Path
from typing import Any
from pydantic import BaseModel
from pydantic_config import BaseConfig as BaseConfig # noqa: F401
from pydantic_config import cli # noqa: F401
@@ -38,19 +37,3 @@ def rsetattr(obj: Any, attr_path: str, value: Any) -> None:
return setattr(obj, attr_path, value)
parent_path, attr = attr_path.rsplit(".", 1)
setattr(rgetattr(obj, parent_path), attr, value)
def get_all_fields(model: BaseModel | type) -> list[str]:
if isinstance(model, BaseModel):
model_cls = model.__class__
else:
model_cls = model
fields = []
for name, field in model_cls.model_fields.items():
field_type = field.annotation
fields.append(name)
if field_type is not None and hasattr(field_type, "model_fields"):
sub_fields = get_all_fields(field_type)
fields.extend(f"{name}.{sub}" for sub in sub_fields)
return fields
@@ -317,14 +317,11 @@ def validate_shared_weight_broadcast(
orchestrator: OrchestratorConfig,
inference: Optional[InferenceConfig] = None,
) -> None:
if (
inference
and trainer.weight_broadcast.type != orchestrator.weight_broadcast.type != inference.weight_broadcast.type
):
raise ValueError(
f"Inference weight broadcast type ({inference.weight_broadcast.type}) and orchestrator weight broadcast type ({orchestrator.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for both."
)
elif trainer.weight_broadcast.type != orchestrator.weight_broadcast.type:
if trainer.weight_broadcast.type != orchestrator.weight_broadcast.type:
raise ValueError(
f"Trainer weight broadcast type ({trainer.weight_broadcast.type}) and orchestrator weight broadcast type ({orchestrator.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for both."
)
if inference is not None and inference.weight_broadcast.type != trainer.weight_broadcast.type:
raise ValueError(
f"Inference weight broadcast type ({inference.weight_broadcast.type}) and trainer/orchestrator weight broadcast type ({trainer.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for all components."
)
+3 -2
View File
@@ -33,7 +33,7 @@ dependencies = [
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"torchtitan",
"verifiers>=0.1.15.dev405",
"verifiers[harbor]>=0.1.15.dev411",
"renderers",
"dion",
"tilelang>=0.1.8",
@@ -93,6 +93,7 @@ envs = [
"logic-env",
"longcot-mini-v1",
"longcot-v1",
"longpdfs-v1",
"math-env",
"math-env-v1",
"math-python",
@@ -174,7 +175,6 @@ dev = [
# *without* the cooldown — bypassing this security policy.
required-version = ">=0.11.1"
exclude-newer = "7 days"
preview = true
no-build-isolation-package = ["flash-attn"]
environments = [
"sys_platform == 'linux' and platform_machine == 'x86_64'",
@@ -266,6 +266,7 @@ livecodebench-v1 = { path = "deps/research-environments/environments/livecodeben
logic-env = { path = "deps/research-environments/environments/logic_env", editable = true }
longcot-mini-v1 = { path = "deps/research-environments/environments/longcot_mini_v1", editable = true }
longcot-v1 = { path = "deps/research-environments/environments/longcot_v1", editable = true }
longpdfs-v1 = { path = "deps/research-environments/environments/longpdfs_v1", editable = true }
math-env = { path = "deps/research-environments/environments/math_env", editable = true }
math-env-v1 = { path = "deps/research-environments/environments/math_env_v1", editable = true }
math-python = { path = "deps/verifiers/environments/math_python", editable = true }
-15
View File
@@ -2,7 +2,6 @@ import logging.config
import os
from prime_rl.configs.inference import InferenceConfig
from prime_rl.utils.config import cli
def setup_vllm_env(config: InferenceConfig):
@@ -41,17 +40,3 @@ def setup_vllm_env(config: InferenceConfig):
os.environ["VLLM_CONFIGURE_LOGGING"] = "1"
os.environ["VLLM_LOGGING_CONFIG_PATH"] = str(config_path)
logging.config.dictConfig(build_dict_config(config.log.level))
def main():
config = cli(InferenceConfig)
setup_vllm_env(config)
# We import here to be able to set environment variables before importing vLLM
from prime_rl.inference.vllm.server import server # pyright: ignore
server(config, vllm_extra=config.vllm_extra)
if __name__ == "__main__":
main()
-1
View File
@@ -150,7 +150,6 @@ async def custom_init_app_state(
"""
await init_app_state(engine_client, state, args, supported_tasks)
state.reset_prefix_cache_after_update = getattr(args, "reset_prefix_cache_after_update", True)
state.liveness_timeout_seconds = args.liveness_timeout_seconds
# Swap in our ServingTokens subclass for /inference/v1/generate so the
+14 -8
View File
@@ -201,12 +201,21 @@ class RolloutDispatcher:
def queued_eval_examples(self) -> int:
return len(self.eval_source) if self.eval_source is not None else 0
@property
def eval_has_work(self) -> bool:
"""Eval has work while its source queue is non-empty OR any opened eval group still has
rollouts to schedule. An example leaves ``eval_source`` when its group opens
(``next_fresh_group``), but its ``group_size`` rollouts dispatch one at a time across
``fill_inflight`` passes — so the queue can be empty while a group is still mid-schedule."""
return bool(self.eval_source) or any(
g.kind == "eval" and g.rollouts_to_schedule > 0 for g in self.groups.values()
)
@property
def is_idle(self) -> bool:
"""True once nothing is in flight, no eval queued, and ``out_q`` is
empty — the pipeline has fully drained."""
eval_drained = self.eval_source is None or not self.eval_source
return not self.inflight and eval_drained and self.out_q.empty()
"""True once nothing is in flight, no eval work remains (queued *or* a partly-scheduled eval
group), and ``out_q`` is empty — the pipeline has fully drained."""
return not self.inflight and not self.eval_has_work and self.out_q.empty()
def disable_train_scheduling(self) -> None:
"""Stop scheduling new train rollouts; in-flight train + any
@@ -307,10 +316,7 @@ class RolloutDispatcher:
# PREFER_EVAL is only entered when the orchestrator triggers
# eval, which requires ``eval_source`` to be configured
assert self.eval_source is not None
eval_has_work = bool(self.eval_source) or any(
g.kind == "eval" and g.rollouts_to_schedule > 0 for g in self.groups.values()
)
if not eval_has_work:
if not self.eval_has_work:
# Eval source + all eval groups fully dispatched. Flip
# to PREFER_TRAIN so any remaining permits go to train
# while the in-flight eval tail completes naturally
+9 -49
View File
@@ -5,8 +5,8 @@ Same shape as ``TrainSink``, but no tokenization / advantages / filters:
1. ``process_rollout`` — no-op.
2. ``process_group`` — at ``group_size`` arrivals, move the rollouts
(errored ones included) into the ``(env, eval_step)`` bucket.
3. ``process_batch`` — at ``num_examples × group_size`` arrivals, build
the ``EvalBatchMetrics`` and return an ``EvalBatch``.
3. ``process_batch`` — at ``num_examples × group_size`` arrivals, return an
``EvalBatch`` with the full returned cohort (metrics are computed downstream).
``add()`` returns ``EvalBatch | None``.
"""
@@ -17,8 +17,8 @@ import uuid
from collections import defaultdict
from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.orchestrator.eval_utils import compute_pass_at_k
from prime_rl.orchestrator.types import EvalBatch, EvalBatchMetrics, Rollout
from prime_rl.orchestrator.metrics import EvalRollouts
from prime_rl.orchestrator.types import EvalBatch, Rollout
from prime_rl.utils.logger import get_logger
@@ -111,50 +111,10 @@ class EvalSink:
)
def process_batch(self, key: tuple[str, int]) -> EvalBatch:
"""Build ``EvalBatchMetrics`` and return the finalized ``EvalBatch``.
Errored rollouts (env failures, cancellations, task exceptions) are
excluded from reward / pass@k / seq_len aggregation (including them
at reward=0 would bias the score down) and surfaced separately as
``n_cancelled`` / ``n_errored``."""
"""Pop the finished ``(env, eval_step)`` epoch and return the ``EvalBatch`` with its full
returned cohort (errored rollouts included — the ``all`` set). Metrics are computed
downstream via ``EvalBatch.rollouts.metrics`` over the all/effective subsets, so the sink
does no aggregation."""
env_name, step = key
rollouts = self.pending_batches.pop(key, [])
n_total = len(rollouts)
n_cancelled = sum(1 for r in rollouts if r.has_error and r.error.type == "Cancelled")
n_errored = sum(1 for r in rollouts if r.has_error) - n_cancelled
valid = [r for r in rollouts if not r.has_error]
metrics = EvalBatchMetrics(
n_rollouts=n_total,
n_cancelled=n_cancelled,
n_errored=n_errored,
)
if valid:
rewards = [r.reward for r in valid]
lens = [sum(b.num_output_tokens for b in r.branches) for r in valid]
metrics.group_size = self.group_size_for(env_name)
metrics.reward_mean = float(sum(rewards) / len(rewards))
metrics.completion_len_mean = float(sum(lens) / len(lens))
metrics.completion_len_max = float(max(lens))
metrics.completion_len_min = float(min(lens))
metrics.truncation_rate = float(sum(1 for r in valid if r.is_truncated) / len(valid))
metrics.no_response_rate = float(sum(1 for r in valid if not r.has_response) / len(valid))
num_turns = [r.num_turns for r in valid]
metrics.num_turns_mean = float(sum(num_turns) / len(num_turns))
metrics.num_turns_min = float(min(num_turns))
metrics.num_turns_max = float(max(num_turns))
# pass@k: errored attempts don't count toward k tries
by_example: dict[int, list[float]] = {}
for r in valid:
by_example.setdefault(r.task.idx, []).append(r.reward)
metrics.n_examples = len(by_example)
unique_rewards = {float(r) for r in rewards}
if unique_rewards.issubset({0.0, 1.0}) and by_example:
pass_at_k_per_example = [compute_pass_at_k(rs) for rs in by_example.values()]
keys = set().union(*(d.keys() for d in pass_at_k_per_example))
for k in keys:
values = [d[k] for d in pass_at_k_per_example if k in d]
metrics.pass_at_k[k] = float(sum(values) / len(values))
return EvalBatch(env_name=env_name, step=step, rollouts=rollouts, metrics=metrics)
return EvalBatch(env_name=env_name, step=step, rollouts=EvalRollouts(rollouts))
-18
View File
@@ -1,18 +0,0 @@
import numpy as np
def _pass_at_k(n: int, c: int, k: int) -> float:
"""Unbiased estimator of pass@k (Chen et al., 2021).
Computes 1 - C(n-c, k) / C(n, k) in a numerically stable way.
"""
if n - c < k:
return 1.0
return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1))
def compute_pass_at_k(rewards: list[float]) -> dict[str, float]:
n = len(rewards)
c = sum(r == 1.0 for r in rewards)
ks = [2**i for i in range(n.bit_length())]
return {f"pass@{k}": _pass_at_k(n, c, k) for k in ks}
+368 -167
View File
@@ -1,185 +1,386 @@
"""MetricsBuilder: assembles the per-step W&B dict. No I/O, no side effects."""
"""Train and eval rollout metrics.
A rollout container (``TrainRollouts`` / ``EvalRollouts``) owns the rollout list and exposes
``.effective`` (the clean subset, as the same container type) and ``.metrics`` (``TrainMetrics`` /
``EvalMetrics``). The metrics object exposes each distributional / rate metric as a ``Stat`` — so
``rollouts.metrics.num_input_tokens.mean()`` works — and assembles the full
``{prefix}/{subset}/<metric>/<stat>`` wandb dict via ``.to_wandb(...)``.
No I/O, no pandas — plain Python over the ``vf.Trace`` properties each rollout exposes. Aggregation
is flat over the rollout list except the solve rates, which group by ``group_id``.
"""
from __future__ import annotations
from typing import Any
from typing import TYPE_CHECKING, Iterator, Literal
import pandas as pd
from prime_rl.orchestrator.utils import compute_pass_metrics
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.types import Progress, Rollout, TrainBatchMetrics
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
Subset = Literal["all", "effective"]
class MetricsBuilder:
def __init__(self, config: OrchestratorConfig) -> None:
self.config = config
class Stat:
"""A distribution of per-rollout values with mean/max/min and p10/p90 accessors."""
def build(
self,
*,
step: int,
rollouts: list[Rollout],
metrics: TrainBatchMetrics,
progress: Progress,
step_time: float,
save_ckpt_time: float,
pre_filter_seen: int,
pre_filter_dropped: int,
pre_filter_dropped_by_name: dict[str, int],
) -> dict[str, Any]:
"""Builds the per-step W&B dict. Stable metric names so
existing dashboards / alerts keep working."""
num_rollouts = len(rollouts)
num_unique_examples = len({r.group_id for r in rollouts})
num_tokens = sum(r.num_total_tokens for r in rollouts)
def __init__(self, values: list[float]) -> None:
self.values = values
results_df = pd.DataFrame(
{
"group_id": [r.group_id for r in rollouts],
"task_idx": [r.task.idx for r in rollouts],
"env_name": [r.env_name for r in rollouts],
"reward": [r.reward for r in rollouts],
"is_truncated": [r.is_truncated for r in rollouts],
"is_filtered": [r.is_filtered for r in rollouts],
"stop_condition": [r.stop_condition for r in rollouts],
"seq_len": [r.num_total_tokens for r in rollouts],
"prefill_len": metrics.rollout_prefill_lens,
"decode_len": metrics.rollout_decode_lens,
"samples_per_rollout": metrics.samples_per_rollout,
"num_turns": [r.num_turns for r in rollouts],
}
)
metrics_df = pd.DataFrame([r.metrics for r in rollouts])
filter_df = pd.DataFrame([r.filter_results for r in rollouts])
timing_df = self.timing_df(rollouts)
def mean(self) -> float:
return sum(self.values) / len(self.values) if self.values else 0.0
# Each group's full-solve threshold is its own env's group_size (envs
# can override the top-level group_size).
env_group_size = {env.resolved_name: env.group_size for env in self.config.train.env}
def max(self) -> float:
return float(max(self.values)) if self.values else 0.0
def compute_solve_rates(df):
grouped = df.groupby("group_id")
reward_per_problem = grouped.reward.sum()
solve_none = (reward_per_problem == 0).mean()
expected = grouped.env_name.first().map(env_group_size)
solve_all = (reward_per_problem == expected).mean()
return solve_none, solve_all, 1 - solve_none - solve_all
def min(self) -> float:
return float(min(self.values)) if self.values else 0.0
by_example = results_df.groupby("group_id")
solve_none, solve_all, effective_batch_size = compute_solve_rates(results_df)
def percentile(self, q: float) -> float:
"""Linear-interpolated ``q``-th percentile (numpy's default method); 0.0 if empty."""
if not self.values:
return 0.0
s = sorted(self.values)
rank = q / 100 * (len(s) - 1)
lo = int(rank)
hi = min(lo + 1, len(s) - 1)
return float(s[lo] + (s[hi] - s[lo]) * (rank - lo))
to_log: dict[str, Any] = {
"progress/tokens": num_tokens,
"progress/prefill_tokens": metrics.num_prefill_tokens,
"progress/decode_tokens": metrics.num_decode_tokens,
"progress/samples": num_rollouts,
"progress/problems": num_unique_examples,
"progress/total_tokens": progress.total_tokens,
"progress/total_samples": progress.total_samples,
"progress/total_problems": progress.total_problems,
"seq_len/all/mean": by_example.seq_len.mean().mean(),
"seq_len/all/max": by_example.seq_len.mean().max(),
"seq_len/all/min": by_example.seq_len.mean().min(),
"prefill_len/all/mean": by_example.prefill_len.mean().mean(),
"prefill_len/all/max": by_example.prefill_len.mean().max(),
"prefill_len/all/min": by_example.prefill_len.mean().min(),
"decode_len/all/mean": by_example.decode_len.mean().mean(),
"decode_len/all/max": by_example.decode_len.mean().max(),
"decode_len/all/min": by_example.decode_len.mean().min(),
"is_truncated/all/mean": by_example.is_truncated.mean().mean(),
"is_truncated/all/max": by_example.is_truncated.mean().max(),
"stop_condition/all/generation_truncated": (
results_df.is_truncated & (results_df.stop_condition != "prompt_too_long")
).mean(),
**{
f"stop_condition/all/{sc}": rate
for sc, rate in results_df.stop_condition.dropna().value_counts(normalize=True).items()
},
"samples_per_rollout/all/mean": by_example.samples_per_rollout.mean().mean(),
"samples_per_rollout/all/max": by_example.samples_per_rollout.mean().max(),
"samples_per_rollout/all/min": by_example.samples_per_rollout.mean().min(),
"num_turns/all/mean": by_example.num_turns.mean().mean(),
"num_turns/all/max": by_example.num_turns.mean().max(),
"num_turns/all/min": by_example.num_turns.mean().min(),
**{
f"timing/all/{key}/{stat}": getattr(
timing_df[key].groupby(results_df.group_id).mean(),
stat,
)()
for key in timing_df.columns
for stat in ("mean", "max", "min")
},
"reward/all/mean": by_example.reward.mean().mean(),
"reward/all/max": by_example.reward.mean().max(),
"reward/all/min": by_example.reward.mean().min(),
"solve_none/all": solve_none,
"solve_all/all": solve_all,
"effective_batch_size/all": effective_batch_size,
**{f"batch/{env}": r for env, r in results_df.env_name.value_counts(normalize=True).items()},
"time/step": step_time,
"time/save_ckpt": save_ckpt_time,
"filters/all/is_filtered": results_df.is_filtered.astype(float).mean(),
**{f"filters/all/{name}": filter_df[name].astype(float).mean() for name in filter_df.columns},
"step": step,
def p10(self) -> float:
return self.percentile(10)
def p90(self) -> float:
return self.percentile(90)
def to_dict(self, prefix: str) -> dict[str, float]:
"""``{prefix}/mean,max,min,p10,p90``; ``{}`` for an empty distribution."""
if not self.values:
return {}
return {
f"{prefix}/mean": self.mean(),
f"{prefix}/max": self.max(),
f"{prefix}/min": self.min(),
f"{prefix}/p10": self.p10(),
f"{prefix}/p90": self.p90(),
}
# Per-env metrics
per_env_columns = [
"seq_len",
"prefill_len",
"decode_len",
"is_truncated",
"samples_per_rollout",
"num_turns",
]
for env, env_df in results_df.groupby("env_name"):
env_by_example = env_df.groupby("group_id")
for col in per_env_columns:
to_log[f"{col}/{env}/mean"] = env_by_example[col].mean().mean()
to_log[f"{col}/{env}/max"] = env_by_example[col].mean().max()
if col != "is_truncated":
to_log[f"{col}/{env}/min"] = env_by_example[col].mean().min()
env_timing_df = timing_df.loc[env_df.index]
for key in timing_df.columns:
per_example = env_timing_df.groupby(env_df["group_id"])[key].mean()
to_log[f"timing/{env}/{key}/mean"] = per_example.mean()
to_log[f"timing/{env}/{key}/max"] = per_example.max()
to_log[f"timing/{env}/{key}/min"] = per_example.min()
to_log[f"reward/{env}/mean"] = env_by_example.reward.mean().mean()
to_log[f"reward/{env}/max"] = env_by_example.reward.mean().max()
to_log[f"reward/{env}/min"] = env_by_example.reward.mean().min()
sn, sa, eb = compute_solve_rates(env_df)
to_log[f"solve_none/{env}"] = sn
to_log[f"solve_all/{env}"] = sa
to_log[f"effective_batch_size/{env}"] = eb
to_log[f"stop_condition/{env}/generation_truncated"] = (
env_df.is_truncated & (env_df.stop_condition != "prompt_too_long")
).mean()
for sc, rate in env_df.stop_condition.dropna().value_counts(normalize=True).items():
to_log[f"stop_condition/{env}/{sc}"] = rate
env_metrics_df = metrics_df.loc[env_df.index] if not metrics_df.empty else metrics_df
for metric in metrics_df.columns:
to_log[f"metrics/{env}/{metric}"] = env_metrics_df.groupby(env_df["group_id"])[metric].mean().mean()
to_log[f"filters/{env}/is_filtered"] = env_df.is_filtered.astype(float).mean()
env_filter_df = filter_df.loc[env_df.index] if not filter_df.empty else filter_df
for name in filter_df.columns:
to_log[f"filters/{env}/{name}"] = env_filter_df[name].astype(float).mean()
# Dispatcher / watcher gauges live on the ``_timestamp`` axis via
# the periodic logger — keep this dict step-axis only
if pre_filter_seen > 0:
to_log["pre_filters/all/dropped_rate"] = pre_filter_dropped / pre_filter_seen
for name, count in pre_filter_dropped_by_name.items():
to_log[f"pre_filters/all/{name}/rate"] = count / pre_filter_seen
class StatGroup:
"""A nested group of named ``Stat``s. ``to_dict`` emits ``{prefix}/<name>/<stat>`` for each
distribution and ``group[name]`` returns one; subclasses supply the names via ``stats()``."""
return to_log
def __init__(self, rollouts: list[Rollout]) -> None:
self.rollouts = rollouts
@staticmethod
def timing_df(rollouts: list[Rollout]) -> pd.DataFrame:
"""Per-rollout timing from the v1 Trace (`generation`/`scoring` spans)."""
rows = []
for r in rollouts:
timing = r.timing
generation, scoring = timing.generation.duration, timing.scoring.duration
rows.append({"total": generation + scoring, "generation": generation, "scoring": scoring})
return pd.DataFrame(rows)
def stats(self) -> dict[str, Stat]:
raise NotImplementedError
def __getitem__(self, name: str) -> Stat:
return self.stats()[name]
def to_dict(self, prefix: str) -> dict[str, float]:
out: dict[str, float] = {}
for name, stat in self.stats().items():
out |= stat.to_dict(f"{prefix}/{name}")
return out
class TimingMetrics(StatGroup):
"""Per-phase rollout durations, nested so ``metrics.timing.setup.mean()`` reads naturally.
``total`` is the per-rollout sum across all phases."""
PHASES = ("setup", "generation", "finalize", "scoring")
@property
def setup(self) -> Stat:
return Stat([r.timing.setup.duration for r in self.rollouts])
@property
def generation(self) -> Stat:
return Stat([r.timing.generation.duration for r in self.rollouts])
@property
def finalize(self) -> Stat:
return Stat([r.timing.finalize.duration for r in self.rollouts])
@property
def scoring(self) -> Stat:
return Stat([r.timing.scoring.duration for r in self.rollouts])
@property
def total(self) -> Stat:
return Stat([sum(getattr(r.timing, p).duration for p in self.PHASES) for r in self.rollouts])
def stats(self) -> dict[str, Stat]:
return {**{phase: getattr(self, phase) for phase in self.PHASES}, "total": self.total}
class CustomMetrics(StatGroup):
"""Per-key ``Stat``s over a dynamic per-rollout dict attribute (env ``@metric``s or reward
components), each averaged over the rollouts that report the key."""
def __init__(self, rollouts: list[Rollout], attr: str) -> None:
super().__init__(rollouts)
self.attr = attr
def stats(self) -> dict[str, Stat]:
names = sorted({name for r in self.rollouts for name in getattr(r, self.attr)})
return {
name: Stat([getattr(r, self.attr)[name] for r in self.rollouts if name in getattr(r, self.attr)])
for name in names
}
class RolloutMetrics:
"""Metrics shared by train and eval over a rollout list. Distributional metrics are ``Stat``s
(mean/max/min); boolean metrics are ``Stat``s of 0/1 (use ``.mean()`` for the rate). ``to_wandb``
assembles the full ``{prefix}/{subset}/...`` dict; ``TrainMetrics`` / ``EvalMetrics`` extend it."""
def __init__(self, rollouts: list[Rollout]) -> None:
self.rollouts = rollouts
# Distributional metrics
@property
def num_total_tokens(self) -> Stat:
return Stat([float(r.num_total_tokens) for r in self.rollouts])
@property
def num_input_tokens(self) -> Stat:
return Stat([float(r.num_input_tokens) for r in self.rollouts])
@property
def num_output_tokens(self) -> Stat:
return Stat([float(r.num_output_tokens) for r in self.rollouts])
@property
def num_turns(self) -> Stat:
return Stat([float(r.num_turns) for r in self.rollouts])
@property
def num_branches(self) -> Stat:
return Stat([float(r.num_branches) for r in self.rollouts])
@property
def timing(self) -> TimingMetrics:
return TimingMetrics(self.rollouts)
@property
def metrics(self) -> CustomMetrics:
"""Env custom ``@metric`` outputs, keyed by name (``metrics.metrics["acc"].mean()``)."""
return CustomMetrics(self.rollouts, "metrics")
@property
def rewards(self) -> CustomMetrics:
"""Per-component reward breakdown, keyed by name (summed into the scalar ``reward``)."""
return CustomMetrics(self.rollouts, "rewards")
# Boolean rate metrics (0/1 distributions — ``.mean()`` is the rate)
@property
def is_truncated(self) -> Stat:
return Stat([float(r.is_truncated) for r in self.rollouts])
@property
def is_completed(self) -> Stat:
return Stat([float(r.is_completed) for r in self.rollouts])
@property
def has_error(self) -> Stat:
return Stat([float(r.has_error) for r in self.rollouts])
def stop_conditions(self) -> dict[str, float]:
"""``generation_truncated`` over all rollouts, then each recorded ``stop_condition``'s rate
over the rollouts that recorded one."""
out = {
"generation_truncated": sum(
1 for r in self.rollouts if r.is_truncated and r.stop_condition != "prompt_too_long"
)
/ len(self.rollouts)
}
conditions = [r.stop_condition for r in self.rollouts if r.stop_condition is not None]
for condition in sorted(set(conditions)):
out[condition] = conditions.count(condition) / len(conditions)
return out
def error_types(self) -> dict[str, int]:
"""Count of errored rollouts by error type (the rollout's last error — e.g. ``Cancelled``,
``ProviderError``)."""
types = [r.error.type for r in self.rollouts if r.has_error]
return {t: types.count(t) for t in sorted(set(types))}
def solve_rates(self) -> dict[str, float]:
"""Per-group solve rates, assuming binary 0/1 rewards (unspecified for other reward ranges):
``solved_none`` (the group earned no reward), ``solved_all`` (every rollout scored 1.0), and
``solved_some`` (the mixed remainder — the GRPO-signal groups)."""
groups: dict = {}
for r in self.rollouts:
groups.setdefault(r.group_id, []).append(r)
n_groups = len(groups)
solved_none = sum(1 for g in groups.values() if sum(r.reward for r in g) == 0)
solved_all = sum(1 for g in groups.values() if all(r.reward == 1.0 for r in g))
return {
"solved_none": solved_none / n_groups,
"solved_all": solved_all / n_groups,
"solved_some": 1 - (solved_none + solved_all) / n_groups,
}
def to_wandb(self, *, prefix: str, subset: Subset) -> dict[str, float]:
"""The common metric dict for one ``{prefix}/{subset}`` slice. Empty input → ``{}``."""
if not self.rollouts:
return {}
p = f"{prefix}/{subset}"
out: dict[str, float] = {}
out |= self.num_total_tokens.to_dict(f"{p}/num_total_tokens")
out |= self.num_input_tokens.to_dict(f"{p}/num_input_tokens")
out |= self.num_output_tokens.to_dict(f"{p}/num_output_tokens")
out |= self.num_turns.to_dict(f"{p}/num_turns")
out |= self.num_branches.to_dict(f"{p}/num_branches")
out |= self.timing.to_dict(f"{p}/timing")
out |= self.metrics.to_dict(f"{p}/metrics")
out |= self.rewards.to_dict(f"{p}/rewards")
out[f"{p}/is_truncated/mean"] = self.is_truncated.mean()
out[f"{p}/is_completed/mean"] = self.is_completed.mean()
# errors live only on the `all` subset (effective drops them), so emit the rate + the
# per-type counts there only
if subset == "all":
out[f"{p}/has_error/mean"] = self.has_error.mean()
out |= {f"{p}/error/{t}": float(count) for t, count in self.error_types().items()}
out |= {f"{p}/stop_condition/{k}": v for k, v in self.stop_conditions().items()}
out |= {f"{p}/{k}": v for k, v in self.solve_rates().items()}
return out
class TrainMetrics(RolloutMetrics):
"""Common metrics plus the reward distribution and filter-pipeline rates."""
@property
def reward(self) -> Stat:
return Stat([float(r.reward) for r in self.rollouts])
@property
def is_trainable(self) -> Stat:
return Stat([float(r.is_trainable) for r in self.rollouts])
@property
def is_filtered(self) -> Stat:
return Stat([float(r.is_filtered) for r in self.rollouts])
def filter_rates(self) -> dict[str, float]:
"""Per-filter detection rate over all rollouts."""
names = sorted({name for r in self.rollouts for name in r.filter_results})
return {
name: sum(1 for r in self.rollouts if r.filter_results.get(name)) / len(self.rollouts) for name in names
}
def to_wandb(self, *, prefix: str, subset: Subset) -> dict[str, float]:
out = super().to_wandb(prefix=prefix, subset=subset)
if not self.rollouts:
return out
p = f"{prefix}/{subset}"
out |= self.reward.to_dict(f"{p}/reward")
out[f"{p}/is_trainable/mean"] = self.is_trainable.mean()
out[f"{p}/is_filtered/mean"] = self.is_filtered.mean()
out |= {f"{p}/filters/{k}/mean": v for k, v in self.filter_rates().items()}
return out
class EvalMetrics(RolloutMetrics):
"""Common metrics plus the ``avg@<group_size>`` score and (on the effective subset, for
binary-reward tasks) pass@k / pass^k. ``group_size`` (the ``avg@k`` k) is supplied by the
container so the ``all`` and ``effective`` subsets share one stable key."""
def __init__(self, rollouts: list[Rollout], group_size: int) -> None:
super().__init__(rollouts)
self.group_size = group_size
@property
def reward(self) -> Stat:
return Stat([float(r.reward) for r in self.rollouts])
def pass_at_k(self) -> dict[str, float]:
"""pass@k / pass^k averaged over examples; ``{}`` for non-binary rewards."""
rewards = [r.reward for r in self.rollouts]
if not set(rewards).issubset({0.0, 1.0}):
return {}
by_example: dict = {}
for r in self.rollouts:
by_example.setdefault(r.group_id, []).append(r.reward)
per_example = [compute_pass_metrics(rs) for rs in by_example.values()]
keys = sorted({k for d in per_example for k in d})
return {k: sum(d[k] for d in per_example if k in d) / sum(1 for d in per_example if k in d) for k in keys}
def to_wandb(self, *, prefix: str, subset: Subset) -> dict[str, float]:
out = super().to_wandb(prefix=prefix, subset=subset)
if not self.rollouts:
return out
p = f"{prefix}/{subset}"
out[f"{p}/avg@{self.group_size}"] = self.reward.mean()
if subset == "effective":
out |= {f"{p}/{k}": v for k, v in self.pass_at_k().items()}
return out
class TrainRollouts:
"""A list of train rollouts (everything that came back, errored + filtered included). ``effective``
is the clean subset (a view of the same traces); ``metrics`` builds ``TrainMetrics`` over them."""
def __init__(self, rollouts: list[Rollout] | None = None) -> None:
self.rollouts = rollouts if rollouts is not None else []
def append(self, rollout: Rollout) -> None:
self.rollouts.append(rollout)
def __len__(self) -> int:
return len(self.rollouts)
def __iter__(self) -> Iterator[Rollout]:
return iter(self.rollouts)
@property
def effective(self) -> TrainRollouts:
return TrainRollouts([r for r in self.rollouts if not r.has_error and not r.is_filtered])
def by_env(self) -> dict[str, TrainRollouts]:
grouped: dict[str, list[Rollout]] = {}
for r in self.rollouts:
grouped.setdefault(r.env_name, []).append(r)
return {env: TrainRollouts(rs) for env, rs in grouped.items()}
@property
def metrics(self) -> TrainMetrics:
return TrainMetrics(self.rollouts)
class EvalRollouts:
"""A list of eval rollouts (errored included). ``effective`` is the non-errored subset (a view).
``group_size`` (rollouts per example, the ``avg@k`` k) is derived from the full epoch and carried
onto ``effective`` so both subsets share one stable key; ``metrics`` builds ``EvalMetrics``."""
def __init__(self, rollouts: list[Rollout] | None = None, group_size: int | None = None) -> None:
self.rollouts = rollouts if rollouts is not None else []
self._group_size = group_size
def __len__(self) -> int:
return len(self.rollouts)
def __iter__(self) -> Iterator[Rollout]:
return iter(self.rollouts)
@property
def group_size(self) -> int:
"""The largest group (equals the configured group size whenever one example kept all its
rollouts); a subview carries its parent's value so ``avg@k`` doesn't drift across subsets."""
if self._group_size is not None:
return self._group_size
counts: dict = {}
for r in self.rollouts:
counts[r.group_id] = counts.get(r.group_id, 0) + 1
return max(counts.values(), default=0)
@property
def effective(self) -> EvalRollouts:
return EvalRollouts([r for r in self.rollouts if not r.has_error], group_size=self.group_size)
@property
def metrics(self) -> EvalMetrics:
return EvalMetrics(self.rollouts, self.group_size)
+97 -74
View File
@@ -7,9 +7,10 @@ and drives the pipeline. Components are single-purpose:
discriminated by ``kind``) on its queue.
- ``TrainSink`` ingests train rollouts (tokenize → advantages → filters)
and returns a ``TrainBatch`` when the threshold is met.
- ``EvalSink`` ingests eval rollouts and returns an ``EvalBatch`` (with
per-env metrics) on epoch completion.
- ``MetricsBuilder`` builds the per-step train W&B dict.
- ``EvalSink`` ingests eval rollouts and returns an ``EvalBatch`` (the full
returned cohort) on epoch completion.
- ``TrainRollouts`` / ``EvalRollouts`` carry the rollouts and build the per-step W&B metrics
(``batch.rollouts.metrics`` / ``.effective.metrics``).
- ``WeightWatcher`` advances ``Policy`` and notifies observers.
- ``PeriodicLogger`` polls the components on a shared interval for the
``_timestamp``-axis pipeline log.
@@ -44,7 +45,6 @@ from prime_rl.orchestrator.eval_sink import EvalSink
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.filters import setup_filters
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
from prime_rl.orchestrator.metrics import MetricsBuilder
from prime_rl.orchestrator.patches import (
monkey_patch_chat_completion_logprobs,
monkey_patch_oai_iterable_types,
@@ -124,7 +124,6 @@ class Orchestrator:
train_sink: TrainSink
dispatcher: RolloutDispatcher
watcher: WeightWatcher
metrics: MetricsBuilder
lag_monitor: EventLoopLagMonitor
periodic_logger: PeriodicLogger
@@ -345,7 +344,6 @@ class Orchestrator:
tasks_per_minute=config.tasks_per_minute,
max_off_policy_steps=config.max_off_policy_steps,
)
self.metrics = MetricsBuilder(config)
self.train_sink = TrainSink(
config,
tokenizer=self.tokenizer,
@@ -495,23 +493,25 @@ class Orchestrator:
)
return
if batch.metrics.n_trainable == 0:
if not batch.samples:
self.consecutive_empty_batches += 1
get_logger().warning(
f"Step {step}: post-batch filters dropped all {len(batch.rollouts)} rollouts "
f"Step {step}: empty train batch (0 of {len(batch.rollouts)} generated rollouts shipped — "
f"all errored or filtered out) "
f"(consecutive empty batches: {self.consecutive_empty_batches}/{MAX_CONSECUTIVE_EMPTY_BATCHES})"
)
if self.consecutive_empty_batches >= MAX_CONSECUTIVE_EMPTY_BATCHES:
raise RuntimeError(
f"{self.consecutive_empty_batches} consecutive zero-trainable batches — "
f"{self.consecutive_empty_batches} consecutive empty train batches — "
"check filter config (pre_batch_filters / post_batch_filters) or task difficulty."
)
return
self.consecutive_empty_batches = 0
if batch.metrics.n_trainable / len(batch.rollouts) <= 0.1:
n_trainable = sum(1 for r in batch.rollouts if r.is_trainable)
if n_trainable / len(batch.rollouts) <= 0.1:
get_logger().warning(
f"Only {batch.metrics.n_trainable}/{len(batch.rollouts)} rollouts in the batch are trainable "
f"({batch.metrics.n_trainable / len(batch.rollouts):.1%}) — consider reviewing task difficulty / filter config"
f"Only {n_trainable}/{len(batch.rollouts)} generated rollouts are trainable "
f"({n_trainable / len(batch.rollouts):.1%}) — consider reviewing task difficulty / filter config"
)
# Serialize the typed Trace at the I/O boundary (disk + wandb sample tables); to_record
@@ -525,23 +525,51 @@ class Orchestrator:
self.update_dispatch_gate()
trim_process_memory()
metrics = self.metrics.build(
step=step,
rollouts=batch.rollouts,
metrics=batch.metrics,
progress=self.progress,
step_time=step_time,
save_ckpt_time=save_ckpt_time,
pre_filter_seen=self.train_sink.pre_filter_seen,
pre_filter_dropped=self.train_sink.pre_filter_dropped,
pre_filter_dropped_by_name=dict(self.train_sink.pre_filter_dropped_by_name),
)
# Rollout metrics over the {agg,<env>} × {all,effective} matrix. ``batch.rollouts`` is the
# full arrival window (errored + filtered included); ``.effective`` is the clean subset.
effective = batch.rollouts.effective
metrics: dict[str, float] = {}
for subset, pool in (("all", batch.rollouts), ("effective", effective)):
metrics |= pool.metrics.to_wandb(prefix="train/agg", subset=subset)
for env_name, env_pool in pool.by_env().items():
metrics |= env_pool.metrics.to_wandb(prefix=f"train/{env_name}", subset=subset)
# Progress / timing / env-share / pre-filter accounting (assembled here, not in the metrics
# objects). ``num_tokens`` is over the full arrival window; the input/output breakdown is over
# the effective (shipped) subset, summing the same ``vf.Trace`` token properties the metric
# matrix reports.
num_tokens = sum(r.num_total_tokens for r in batch.rollouts)
num_input = sum(r.num_input_tokens for r in effective)
num_output = sum(r.num_output_tokens for r in effective)
num_rollouts = len(batch.rollouts)
num_unique_examples = len({r.group_id for r in batch.rollouts})
metrics |= {
"progress/tokens": num_tokens,
"progress/input_tokens": num_input,
"progress/output_tokens": num_output,
"progress/rollouts": num_rollouts,
"progress/tasks": num_unique_examples,
"progress/total_tokens": self.progress.total_tokens,
"progress/total_rollouts": self.progress.total_samples,
"progress/total_tasks": self.progress.total_problems,
"time/step": step_time,
"time/save_ckpt": save_ckpt_time,
"step": step,
}
for env_name, env_pool in batch.rollouts.by_env().items():
metrics[f"batch/{env_name}"] = len(env_pool) / len(batch.rollouts)
if self.train_sink.pre_filter_seen > 0:
metrics["pre_filters/all/dropped_rate"] = (
self.train_sink.pre_filter_dropped / self.train_sink.pre_filter_seen
)
for name, count in self.train_sink.pre_filter_dropped_by_name.items():
metrics[f"pre_filters/all/{name}/rate"] = count / self.train_sink.pre_filter_seen
self.monitor.log(metrics, step=step)
self.monitor.log_samples(batch.rollouts, step=step)
self.monitor.log_samples(effective.rollouts, step=step)
self.monitor.log_distributions(
distributions={
"rewards": [r.reward for r in batch.rollouts],
"advantages": [a for r in batch.rollouts if (a := r.scalar_advantage()) is not None],
"rewards": [r.reward for r in effective],
"advantages": [a for r in effective if (a := r.scalar_advantage()) is not None],
},
step=step,
)
@@ -552,14 +580,11 @@ class Orchestrator:
self.usage_reporter.report_training_usage(
run_id=run_id,
step=step,
tokens=batch.metrics.num_prefill_tokens + batch.metrics.num_decode_tokens,
tokens=num_input + num_output,
)
if self.heart is not None:
self.heart.beat()
num_rollouts = len(batch.rollouts)
num_unique_examples = len({r.group_id for r in batch.rollouts})
num_tokens = sum(r.num_total_tokens for r in batch.rollouts)
self.progress.total_tokens += num_tokens
self.progress.total_samples += num_rollouts
self.progress.total_problems += num_unique_examples
@@ -655,50 +680,42 @@ class Orchestrator:
return body, payload
def log_train_batch(self, batch: TrainBatch, *, step: int, step_time: float) -> None:
"""Per-step ``Step …`` success line. Multi-env runs append an
indented ``╰─`` line per env. ``Error`` is relative to arrivals at
the sink (errored rollouts may have been group-dropped before
reaching ``batch.rollouts``)."""
n_arrivals_total = sum(batch.metrics.arrivals_by_env.values())
n_errors_total = sum(batch.metrics.errors_by_env.values())
n_survivors = len(batch.rollouts)
n_trainable = batch.metrics.n_trainable
error_rate = (n_errors_total / n_arrivals_total) if n_arrivals_total else 0.0
trainable_rate = (n_trainable / n_survivors) if n_survivors else 0.0
reward_mean = sum(r.reward for r in batch.rollouts) / max(n_survivors, 1)
max_off_policy = max((r.off_policy_steps for r in batch.rollouts), default=0)
turns_mean = sum(r.num_turns for r in batch.rollouts) / max(n_survivors, 1)
branches_mean = sum(r.num_branches for r in batch.rollouts) / max(n_survivors, 1)
truncation_rate = sum(1 for r in batch.rollouts if r.is_truncated) / max(n_survivors, 1)
"""Per-step ``Step …`` success line. Multi-env runs append an indented ``╰─`` line per env.
``Error`` is the sink-level rate (errored arrivals / total arrivals, over the full window);
the quality metrics are over the effective (clean, trained-on) subset; ``Trainable`` is
relative to all generated rollouts."""
rollouts = batch.rollouts
effective = rollouts.effective
eff = effective.metrics
n_generated = len(rollouts)
n_trainable = sum(1 for r in rollouts if r.is_trainable)
trainable_rate = (n_trainable / n_generated) if n_generated else 0.0
max_off_policy = max((r.off_policy_steps for r in effective), default=0)
head = (
f"Step {step} | {format_time(step_time):>7} | Reward {reward_mean:.4f} | "
f"Trainable {n_trainable}/{n_survivors} ({trainable_rate:.1%}) | "
f"Turns {turns_mean:.1f} | Branches {branches_mean:.1f} | Max Off-Policy {max_off_policy} | "
f"Error {error_rate:.1%} | Truncation {truncation_rate:.1%}"
f"Step {step} | {format_time(step_time):>7} | Reward {eff.reward.mean():.4f} | "
f"Trainable {n_trainable}/{n_generated} ({trainable_rate:.1%}) | "
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
f"Max Off-Policy {max_off_policy} | "
f"Error {rollouts.metrics.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
)
if len(self.train_envs) <= 1:
get_logger().success(head)
return
env_names = sorted(set(batch.metrics.arrivals_by_env) | {r.env_name for r in batch.rollouts})
name_width = max(len(n) for n in env_names) if env_names else 0
by_env = rollouts.by_env()
name_width = max((len(n) for n in by_env), default=0)
lines = [head]
for env_name in env_names:
env_rollouts = [r for r in batch.rollouts if r.env_name == env_name]
n_env_arrivals = batch.metrics.arrivals_by_env.get(env_name, 0)
n_env_errors = batch.metrics.errors_by_env.get(env_name, 0)
ratio = (n_env_arrivals / n_arrivals_total) if n_arrivals_total else 0.0
env_error_rate = (n_env_errors / n_env_arrivals) if n_env_arrivals else 0.0
env_reward = (sum(r.reward for r in env_rollouts) / len(env_rollouts)) if env_rollouts else 0.0
env_max_off_policy = max((r.off_policy_steps for r in env_rollouts), default=0)
env_turns = sum(r.num_turns for r in env_rollouts) / len(env_rollouts) if env_rollouts else 0.0
env_branches = sum(r.num_branches for r in env_rollouts) / len(env_rollouts) if env_rollouts else 0.0
env_truncation = sum(1 for r in env_rollouts if r.is_truncated) / len(env_rollouts) if env_rollouts else 0.0
for env_name in sorted(by_env):
pool = by_env[env_name]
env_eff_pool = pool.effective
env_eff = env_eff_pool.metrics
ratio = (len(pool) / n_generated) if n_generated else 0.0
lines.append(
f"╰─ {env_name:<{name_width}} | Ratio {ratio:.1%} | Reward {env_reward:.4f} | "
f"Turns {env_turns:.1f} | Branches {env_branches:.1f} | Max Off-Policy {env_max_off_policy} | "
f"Error {env_error_rate:.1%} | Truncation {env_truncation:.1%}"
f"╰─ {env_name:<{name_width}} | Ratio {ratio:.1%} | Reward {env_eff.reward.mean():.4f} | "
f"Turns {env_eff.num_turns.mean():.1f} | Branches {env_eff.num_branches.mean():.1f} | "
f"Max Off-Policy {max((r.off_policy_steps for r in env_eff_pool), default=0)} | "
f"Error {pool.metrics.has_error.mean():.1%} | Truncation {env_eff.is_truncated.mean():.1%}"
)
get_logger().success("\n\t\t ".join(lines))
@@ -706,7 +723,7 @@ class Orchestrator:
"""Persist + log one completed eval epoch (save_rollouts,
monitor.log_eval_samples, monitor.log)."""
if not batch.rollouts:
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no surviving rollouts, skipping log")
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no rollouts returned, skipping log")
return
rollout_dicts = [r.to_record() for r in batch.rollouts]
@@ -723,21 +740,27 @@ class Orchestrator:
get_logger().warning(
f"Eval {batch.env_name} step {batch.step} had mixed policy versions: {sorted(policy_versions)}"
)
metrics = batch.metrics.to_wandb_dict(env_name=batch.env_name, step=batch.step)
# Rollout metrics over {all,effective} (eval batches are per-env, so no `agg` axis).
# ``effective`` = non-errored; pass@k / pass^k only over the effective set.
rollouts = batch.rollouts
effective = rollouts.effective
metrics: dict[str, float] = {}
for subset, pool in (("all", rollouts), ("effective", effective)):
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
metrics[f"eval/{batch.env_name}/policy_version"] = float(policy_version)
metrics["step"] = float(batch.step)
self.monitor.log(metrics, step=batch.step)
n_total = batch.metrics.n_rollouts
error_rate = ((batch.metrics.n_cancelled + batch.metrics.n_errored) / n_total) if n_total else 0.0
# Success line — reward / turns / truncation over the effective set, error rate + branches
# over the full returned cohort. ``Stat.mean()`` is 0.0 for an empty set.
eff, full = effective.metrics, rollouts.metrics
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
branches_mean = sum(r.num_branches for r in batch.rollouts) / len(batch.rollouts)
get_logger().success(
f"Evaluated {batch.env_name} (Step {batch.step}) | "
f"Policy v{policy_version} | {format_time(elapsed):>7} | Reward {batch.metrics.reward_mean:.4f} | "
f"Turns {batch.metrics.num_turns_mean:.1f} | Branches {branches_mean:.1f} | "
f"Error {error_rate:.1%} | Truncation {batch.metrics.truncation_rate:.1%}"
f"Policy v{policy_version} | {format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
f"Turns {eff.num_turns.mean():.1f} | Branches {full.num_branches.mean():.1f} | "
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
)
async def maybe_save_ckpt(self, step: int) -> float:
+16 -48
View File
@@ -23,8 +23,9 @@ from collections import defaultdict
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.envs import TrainEnvs
from prime_rl.orchestrator.filters import RolloutFilter, apply_filters
from prime_rl.orchestrator.metrics import TrainRollouts
from prime_rl.orchestrator.trajectories import trace_to_samples
from prime_rl.orchestrator.types import Rollout, TrainBatch, TrainBatchMetrics
from prime_rl.orchestrator.types import Rollout, TrainBatch
from prime_rl.transport import TrainingSample
from prime_rl.utils.logger import get_logger
@@ -59,6 +60,7 @@ class TrainSink:
# Keyed by the dispatcher's group UUID. ``(env_name, task_idx)``
# isn't unique — the same task can be re-sampled while an
# earlier group is still in flight
self.pending_rollouts: TrainRollouts = TrainRollouts()
self.pending_groups: dict[uuid.UUID, list[Rollout]] = defaultdict(list)
self.pending_batch: list[Rollout] = []
# Running token total of ``pending_batch`` (token-batched runs), kept in
@@ -71,11 +73,6 @@ class TrainSink:
self.pre_filter_dropped = 0
self.pre_filter_dropped_by_name: dict[str, int] = {}
# Per-env arrival / error counters since the last ship; reset in
# ``process_batch``. Fuel for the per-env success log breakdown
self.arrivals_by_env: dict[str, int] = defaultdict(int)
self.errors_by_env: dict[str, int] = defaultdict(int)
def group_size_for(self, env_name: str) -> int:
return self.train_envs.get(env_name).config.group_size
@@ -123,9 +120,7 @@ class TrainSink:
arrival; return a ``TrainBatch`` if the batch threshold is met."""
await self.process_rollout(rollout)
env_name = rollout.env_name
self.arrivals_by_env[env_name] += 1
if rollout.has_error:
self.errors_by_env[env_name] += 1
self.pending_rollouts.append(rollout)
self.pending_groups[rollout.group_id].append(rollout)
if len(self.pending_groups[rollout.group_id]) >= self.group_size_for(env_name):
await self.process_group(rollout.group_id)
@@ -254,46 +249,19 @@ class TrainSink:
if self.post_filters:
apply_filters(self.post_filters, cohort)
# Samples are pre-built by ``process_rollout``; ``process_group``
# already stamped the advantage stream and loss routing on each sample
samples: list[TrainingSample] = []
prefill_lens: list[int] = []
decode_lens: list[int] = []
samples_per_rollout: list[int] = []
num_prefill = 0
num_decode = 0
for r in cohort:
samples_per_rollout.append(len(r.samples))
prefill = 0
decode = 0
for sample in r.samples:
sample_decode = sum(sample.mask)
sample_prefill = len(sample.token_ids) - sample_decode
decode += sample_decode
prefill += sample_prefill
if not r.is_filtered:
samples.append(sample)
prefill_lens.append(prefill)
decode_lens.append(decode)
num_prefill += prefill
num_decode += decode
# Samples are pre-built by ``process_rollout``; ``process_group`` already stamped the
# advantage stream and loss routing on each sample. Filtered rollouts don't ship.
samples: list[TrainingSample] = [sample for r in cohort if not r.is_filtered for sample in r.samples]
n_trainable = sum(1 for r in cohort if not r.is_filtered)
metrics = TrainBatchMetrics(
n_trainable=n_trainable,
num_prefill_tokens=num_prefill,
num_decode_tokens=num_decode,
rollout_prefill_lens=prefill_lens,
rollout_decode_lens=decode_lens,
samples_per_rollout=samples_per_rollout,
samples_shipped=len(samples),
arrivals_by_env=dict(self.arrivals_by_env),
errors_by_env=dict(self.errors_by_env),
)
self.arrivals_by_env.clear()
self.errors_by_env.clear()
return TrainBatch(rollouts=cohort, samples=samples, metrics=metrics)
# ``rollouts`` is the whole arrival window (errored + filtered + survivors); ``samples`` is
# the shipped cohort's trainable payload. ``rollouts.effective`` / ``rollouts.metrics`` derive
# the clean subset + metric views on demand. Reset the window only when the batch actually
# ships (non-empty samples) — an empty batch is dropped unlogged by the orchestrator, so keep
# accumulating its arrivals (and any overflow) into the next shipped batch's window.
rollouts = self.pending_rollouts
if samples:
self.pending_rollouts = TrainRollouts()
return TrainBatch(rollouts=rollouts, samples=samples)
def reset_pre_filter_stats(self) -> None:
self.pre_filter_seen = 0
+7 -7
View File
@@ -75,12 +75,12 @@ def trace_to_samples(
Each `trace.branches` entry is already a flat token sequence (`branch.token_ids` /
`branch.sampled_mask` / `branch.logprobs`), so a sample carries it directly: `mask` marks
the trainable (model-sampled) tokens, the context tokens between completions stay masked
out. On a rollout error the whole completion is masked out. A branch carrying images also
gets `mm_kwargs` (the concatenated pixel tensors) and `mm_token_type_ids` (the renderer's
`mm_token_type_id_map` applied to the branch tokens). Branches with no sampled tokens
(e.g. an openai client carrying none) yield nothing.
out. Errored rollouts are dropped upstream (`TrainSink.process_rollout`), so no error
handling happens here. A branch carrying images also gets `mm_kwargs` (the concatenated
pixel tensors) and `mm_token_type_ids` (the renderer's `mm_token_type_id_map` applied to
the branch tokens). Branches with no sampled tokens (e.g. an openai client carrying none)
yield nothing.
"""
has_error = trace.has_error
samples: list[TrainingSample] = []
for branch in trace.branches:
mask = branch.sampled_mask
@@ -97,7 +97,7 @@ def trace_to_samples(
samples.append(
TrainingSample(
token_ids=token_ids,
mask=[m and not has_error for m in mask],
mask=mask,
logprobs=branch.logprobs,
temperatures=[], # filled by TrainSink.process_group
env_name=env_name,
@@ -108,6 +108,6 @@ def trace_to_samples(
)
if not samples:
get_logger().warning(
f"No trainable samples (error={has_error}, stop={trace.stop_condition}, num_turns={trace.num_turns})."
f"No trainable samples (error={trace.has_error}, stop={trace.stop_condition}, num_turns={trace.num_turns})."
)
return samples
+19 -69
View File
@@ -3,8 +3,8 @@
from __future__ import annotations
import uuid
from dataclasses import dataclass, field
from typing import Generic, Literal, Protocol
from dataclasses import dataclass
from typing import TYPE_CHECKING, Generic, Literal, Protocol
import verifiers.v1 as vf
from pydantic import ConfigDict, Field
@@ -12,6 +12,9 @@ from verifiers.v1.task import TaskT
from prime_rl.transport import TrainingSample
if TYPE_CHECKING:
from prime_rl.orchestrator.metrics import EvalRollouts, TrainRollouts
@dataclass
class Policy:
@@ -122,86 +125,33 @@ class Rollout(vf.Trace[TaskT], Generic[TaskT]):
nonzero = [a for a in self.advantages if a != 0.0]
return sum(nonzero) / len(nonzero) if nonzero else 0.0
@dataclass
class TrainBatchMetrics:
"""Per-batch aggregates from ``TrainSink.process_batch``; consumed by
``MetricsBuilder.build``. ``arrivals_by_env`` / ``errors_by_env`` count
rollouts at the sink."""
n_trainable: int
num_prefill_tokens: int
num_decode_tokens: int
rollout_prefill_lens: list[int]
rollout_decode_lens: list[int]
samples_per_rollout: list[int]
samples_shipped: int
arrivals_by_env: dict[str, int] = field(default_factory=dict)
errors_by_env: dict[str, int] = field(default_factory=dict)
@property
def is_trainable(self) -> bool:
"""Whether the rollout carries a training signal — a nonzero advantage on some token. A
uniform-reward GRPO group (all-zero advantages) or an unscored rollout has no gradient."""
return bool(self.advantages) and any(a != 0.0 for a in self.advantages)
@dataclass
class TrainBatch:
"""``samples`` is the trainer-bound payload (post-filter survivors);
``rollouts`` is the full cohort kept for orchestrator-side I/O."""
"""``rollouts`` is the full arrival window since the last ship (errored + filtered included; its
``.effective`` / ``.metrics`` views drive logging). ``samples`` is the trainer-bound payload (the
shipped cohort's post-filter survivors) — an empty list means nothing ships, which would stall the
trainer. Trainable counts derive from ``rollouts`` (``r.is_trainable``) and token totals from
``samples``, so neither is carried as a field."""
rollouts: list[Rollout]
rollouts: TrainRollouts
samples: list[TrainingSample]
metrics: TrainBatchMetrics
@dataclass
class EvalBatchMetrics:
"""Typed per-batch metrics from ``EvalSink.process_batch``. Final wandb
dict derived via ``to_wandb_dict`` at log time."""
n_rollouts: int
n_cancelled: int
n_errored: int
n_examples: int = 0
group_size: int = 1
reward_mean: float = 0.0
completion_len_mean: float = 0.0
completion_len_max: float = 0.0
completion_len_min: float = 0.0
truncation_rate: float = 0.0
no_response_rate: float = 0.0
num_turns_mean: float = 0.0
num_turns_min: float = 0.0
num_turns_max: float = 0.0
pass_at_k: dict[str, float] = field(default_factory=dict)
def to_wandb_dict(self, *, env_name: str, step: int) -> dict[str, float]:
prefix = f"eval/{env_name}"
out: dict[str, float] = {
"step": float(step),
f"{prefix}/cancelled_count": float(self.n_cancelled),
f"{prefix}/errored_count": float(self.n_errored),
}
if self.n_examples > 0:
out[f"{prefix}/avg@{self.group_size}"] = self.reward_mean
out[f"{prefix}/completion_len/mean"] = self.completion_len_mean
out[f"{prefix}/completion_len/max"] = self.completion_len_max
out[f"{prefix}/completion_len/min"] = self.completion_len_min
out[f"{prefix}/is_truncated/mean"] = self.truncation_rate
out[f"{prefix}/no_response/mean"] = self.no_response_rate
out[f"{prefix}/num_turns/mean"] = self.num_turns_mean
out[f"{prefix}/num_turns/min"] = self.num_turns_min
out[f"{prefix}/num_turns/max"] = self.num_turns_max
for k, v in self.pass_at_k.items():
out[f"{prefix}/{k}"] = v
return out
@dataclass
class EvalBatch:
"""One env's eval epoch. ``metrics`` is the typed view from
``EvalSink.process_batch``."""
"""One env's eval epoch. ``rollouts`` is the full returned cohort (errored included); its
``.effective`` / ``.metrics`` views drive logging."""
env_name: str
step: int
rollouts: list[Rollout]
metrics: EvalBatchMetrics
rollouts: EvalRollouts
class VersionObserver(Protocol):
+25 -14
View File
@@ -2,12 +2,12 @@ import asyncio
import ctypes
import gc
import logging
import math
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import orjson
import verifiers.v1 as vf
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.utils.client import setup_inference_pool
@@ -50,14 +50,13 @@ async def setup_policy_inference_pool(*, config: OrchestratorConfig, tokenizer):
return renderer, inference_pool
def save_rollouts(rollouts: list[dict], path: Path, exclude_keys: set[str] | None = None) -> None:
def save_rollouts(rollouts: list[dict], path: Path) -> None:
"""Save rollouts (Trace dicts, already JSON-serializable) to a JSONL file."""
path.parent.mkdir(parents=True, exist_ok=True)
opts = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
with open(path, "wb") as f:
for rollout in rollouts:
row = {k: v for k, v in rollout.items() if k not in exclude_keys} if exclude_keys else rollout
f.write(orjson.dumps(row, default=str, option=opts))
f.write(orjson.dumps(rollout, default=str, option=opts))
def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix: str | None = None):
@@ -93,16 +92,6 @@ def trim_process_memory() -> None:
get_logger().debug(f"malloc_trim(0) failed: {exc!r}")
def get_tool_response_len(trace: vf.Trace) -> int:
"""Total tool-response tokens consumed across the whole rollout, read from a
harness-emitted metric (e.g. RLM's `rlm_total_tool_response_tokens`, deduped
across turns/branches/sub-RLMs). Returns 0 when no such metric is present."""
for key, value in (trace.metrics or {}).items():
if key.endswith("total_tool_response_tokens") and isinstance(value, (int, float)):
return int(value)
return 0
def get_weight_dir(output_dir: Path, step: int, check_exists: bool = True, wait_timeout: int | None = None) -> Path:
"""Get the weight directory for a given checkpoint step.
@@ -146,3 +135,25 @@ def get_weight_dir(output_dir: Path, step: int, check_exists: bool = True, wait_
return broadcast_weight_dir
raise FileNotFoundError(f"No weight directory found for checkpoint step {step}")
def compute_pass_metrics(rewards: list[float]) -> dict[str, float]:
"""Unbiased pass@k and pass^k for one example's binary (0/1) rewards.
pass@k = 1 - C(n-c, k) / C(n, k) (at least one of k samples correct)
pass^k = C(c, k) / C(n, k) (all k samples correct)
``n`` = number of rewards, ``c`` = number correct, ``k`` = powers of 2 in [1, n].
``math.comb`` returns 0 when ``k`` exceeds its first argument, so the edge cases
(``n - c < k`` → pass@k = 1; ``c < k`` → pass^k = 0) fall out without branching.
"""
n = len(rewards)
c = sum(1 for r in rewards if r == 1.0)
out: dict[str, float] = {}
k = 1
while k <= n:
n_choose_k = math.comb(n, k)
out[f"pass@{k}"] = 1.0 - math.comb(n - c, k) / n_choose_k
out[f"pass^{k}"] = math.comb(c, k) / n_choose_k
k *= 2
return out
+13
View File
@@ -0,0 +1,13 @@
from torch import Tensor
def get_max_layer_num(state_dict: dict[str, Tensor], layer_prefix: str = "model.layers.") -> int:
"""Get the maximum number of layers in the model."""
max_num = -1
for key in state_dict:
if not key.startswith(layer_prefix):
continue
layer_num_str = key[len(layer_prefix) :].split(".")[0]
if layer_num_str.isdigit():
max_num = max(max_num, int(layer_num_str))
return max_num + 1
@@ -3,6 +3,8 @@ import re
import torch
from torch import Tensor
from prime_rl.trainer.conversion_utils import get_max_layer_num
def get_num_experts_from_state_dict(state_dict: dict[str, Tensor], layer_idx: int) -> int:
"""Get the number of experts from the HF state dict for a given layer."""
@@ -122,26 +124,15 @@ def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_idx: int) -> Non
del state_dict[key]
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
"""Get the maximum layer number from the state dict."""
max_layer = -1
for key in state_dict.keys():
match = re.search(r"model\.layers\.(\d+)\.", key)
if match:
layer_idx = int(match.group(1))
max_layer = max(max_layer, layer_idx)
return max_layer
def convert_hf_to_tt_moe(state_dict: dict[str, Tensor]) -> None:
"""Convert all MoE layers from HF format to TT format in-place."""
max_layer = get_max_layer_num(state_dict)
for layer_idx in range(max_layer + 1):
num_layers = get_max_layer_num(state_dict)
for layer_idx in range(num_layers):
convert_hf_layer_to_tt(state_dict, layer_idx)
def convert_tt_to_hf_moe(state_dict: dict[str, Tensor]) -> None:
"""Convert all MoE layers from TT format to HF format in-place."""
max_layer = get_max_layer_num(state_dict)
for layer_idx in range(max_layer + 1):
num_layers = get_max_layer_num(state_dict)
for layer_idx in range(num_layers):
convert_tt_layer_to_hf(state_dict, layer_idx)
@@ -19,6 +19,11 @@ from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.attn import (
flash_attn_3_varlen_func,
flash_attn_4_varlen_func,
flash_attn_varlen_func,
)
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
@@ -30,21 +35,6 @@ from prime_rl.trainer.models.layers.rotary_emb import (
)
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
try:
from flash_attn import flash_attn_varlen_func
except ImportError:
flash_attn_varlen_func = None # type: ignore
try:
from flash_attn_interface import flash_attn_varlen_func as flash_attn_3_varlen_func
except ImportError:
flash_attn_3_varlen_func = None # type: ignore
try:
from flash_attn.cute import flash_attn_varlen_func as flash_attn_4_varlen_func
except ImportError:
flash_attn_4_varlen_func = None # type: ignore
from .configuration_afmoe import AfmoeConfig
from .converting_afmoe import (
convert_hf_layer_to_tt,
@@ -1,10 +1,7 @@
import torch
from torch import Tensor
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
"""Get the maximum number of layers in the model."""
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
from prime_rl.trainer.conversion_utils import get_max_layer_num
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
@@ -1,13 +1,10 @@
import torch
from torch import Tensor
from prime_rl.trainer.conversion_utils import get_max_layer_num
from prime_rl.trainer.models.fp8 import quantize_to_fp8_blockwise
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
def _is_moe_layer(state_dict: dict[str, Tensor], layer_idx: int) -> bool:
"""Check if a layer is an MoE layer by looking for the router gate weight."""
return f"model.layers.{layer_idx}.mlp.gate.weight" in state_dict
@@ -185,7 +185,6 @@ def fp8_indexer(q, k, w, ks, ke, topk, weight_scale=1.0):
"""
# NOTE: We don't use weight scale in this kernel as it produces higher KL mismatch for some reason
# This is not a problem result-wise, as it is a constant multiplier
_weight_scale = weight_scale
S_q, H, D = q.shape
S_k = k.shape[0]
device = q.device
@@ -15,10 +15,6 @@ def ceil_div(x: int, y: int) -> int:
return (x + y - 1) // y
def align(x: int, y: int) -> int:
return ceil_div(x, y) * y
# ---------------------------------------------------------------------------
# Layout building
# ---------------------------------------------------------------------------
@@ -1,9 +1,7 @@
import torch
from torch import Tensor
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
return max(int(key.split(".")[2]) for key in state_dict if key.startswith("model.layers.")) + 1
from prime_rl.trainer.conversion_utils import get_max_layer_num
def _pop_first(state_dict: dict[str, Tensor], keys: tuple[str, ...]) -> Tensor | None:
@@ -77,7 +77,6 @@ class BCFeedForward(nn.Module):
self.w3 = nn.Parameter(torch.empty(hidden_dim, dim))
def forward(self, x: torch.Tensor) -> torch.Tensor:
# return torch.matmul(self.w2, F.silu(torch.matmul(self.w1, x.T)) * torch.matmul(self.w3, x.T))
return torch.matmul(F.silu(torch.matmul(x, self.w1.T)) * torch.matmul(x, self.w3.T), self.w2.T)
def init_weights(self, init_std: float):
@@ -115,34 +115,3 @@ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
q_embed = torch.cat([q_embed, q_pass], dim=-1)
k_embed = torch.cat([k_embed, k_pass], dim=-1)
return q_embed, k_embed
def apply_rotary_pos_emb_interleave(q, k, cos, sin, unsqueeze_dim=1):
"""Interleaved RoPE: converts from [r0, i0, r1, i1, ...] layout before applying rotation.
Args:
q (`torch.Tensor`): The query tensor.
k (`torch.Tensor`): The key tensor.
cos (`torch.Tensor`): The cosine part of the rotary embedding.
sin (`torch.Tensor`): The sine part of the rotary embedding.
unsqueeze_dim (`int`, *optional*, defaults to 1):
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
Returns:
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
"""
cos = cos.unsqueeze(unsqueeze_dim)
sin = sin.unsqueeze(unsqueeze_dim)
b, h, s, d = q.shape
q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
b, h, s, d = k.shape
k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed
@@ -1,10 +1,7 @@
import torch
from torch import Tensor
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
"""Get the maximum number of layers in the model."""
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
from prime_rl.trainer.conversion_utils import get_max_layer_num
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
@@ -1,10 +1,7 @@
import torch
from torch import Tensor
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
"""Get the maximum number of layers in the model."""
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
from prime_rl.trainer.conversion_utils import get_max_layer_num
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
@@ -16,6 +16,11 @@ from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs, logging
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.attn import (
flash_attn_3_varlen_func,
flash_attn_4_varlen_func,
flash_attn_varlen_func,
)
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.moe import FeedForward, MoE, MoEArgs
from prime_rl.trainer.models.layers.rotary_emb import apply_rotary_pos_emb
@@ -30,22 +35,6 @@ from .converting_qwen3_5_moe import (
)
from .mrope import build_qwen3_5_mrope_position_ids
# Flash attention imports
try:
from flash_attn import flash_attn_varlen_func
except ImportError:
flash_attn_varlen_func = None # type: ignore
try:
from flash_attn_interface import flash_attn_varlen_func as flash_attn_3_varlen_func
except ImportError:
flash_attn_3_varlen_func = None # type: ignore
try:
from flash_attn.cute import flash_attn_varlen_func as flash_attn_4_varlen_func
except ImportError:
flash_attn_4_varlen_func = None # type: ignore
# Flash linear attention imports (for GatedDeltaNet fast path)
try:
from causal_conv1d import causal_conv1d_fn
@@ -1,10 +1,7 @@
import torch
from torch import Tensor
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
"""Get the maximum number of layers in the model."""
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
from prime_rl.trainer.conversion_utils import get_max_layer_num
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
@@ -242,88 +242,6 @@ class Qwen3MoeModel(Qwen3MoePreTrainedModel):
return MoeModelOutputWithPast(last_hidden_state=hidden_states)
def load_balancing_loss_func(
gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
num_experts: Optional[int] = None,
top_k=2,
attention_mask: Optional[torch.Tensor] = None,
) -> Union[torch.Tensor, int]:
r"""
Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
experts is too unbalanced.
Args:
gate_logits:
Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
shape [batch_size X sequence_length, num_experts].
num_experts:
Number of experts
top_k:
The number of experts to route per-token, can be also interpreted as the `top-k` routing
parameter.
attention_mask (`torch.Tensor`, *optional*):
The attention_mask used in forward function
shape [batch_size X sequence_length] if not None.
Returns:
The auxiliary loss.
"""
if gate_logits is None or not isinstance(gate_logits, tuple):
return 0
if isinstance(gate_logits, tuple):
compute_device = gate_logits[0].device
concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
_, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
if attention_mask is None:
# Compute the percentage of tokens routed to each experts
tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
# Compute the average probability of routing to these experts
router_prob_per_expert = torch.mean(routing_weights, dim=0)
else:
batch_size, sequence_length = attention_mask.shape
num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
# Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
expert_attention_mask = (
attention_mask[None, :, :, None, None]
.expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
.reshape(-1, top_k, num_experts)
.to(compute_device)
)
# Compute the percentage of tokens routed to each experts
tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
expert_attention_mask, dim=0
)
# Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
router_per_expert_attention_mask = (
attention_mask[None, :, :, None]
.expand((num_hidden_layers, batch_size, sequence_length, num_experts))
.reshape(-1, num_experts)
.to(compute_device)
)
# Compute the average probability of routing to these experts
router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
router_per_expert_attention_mask, dim=0
)
overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
return overall_loss * num_experts
@auto_docstring
class Qwen3MoeForCausalLM(Qwen3MoePreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
-20
View File
@@ -37,9 +37,6 @@ class PerfCounter:
self.gpu_peak_flops = self._get_peak_flops(torch.cuda.get_device_name(torch.device("cuda")))
else:
self.gpu_peak_flops = 0
# If not tie_word_embeddings, we exclude the embedding parameters from the total number of parameters
# If tie_word_embeddings, the embedding parameters are already excluded (shared with the LM head)
self.num_params = self._get_num_params(model, exclude_embedding=not model.config.tie_word_embeddings)
self.num_flop_per_token = self._get_num_flop_per_token(model.config, seq_len=seq_len)
def count_tokens(self, tokens: int) -> None:
@@ -209,23 +206,6 @@ class PerfCounter:
return flop_per_token
def _get_num_params(self, model: nn.Module, exclude_embedding: bool = False) -> int:
num_params = sum(p.numel() for p in model.parameters())
if exclude_embedding:
if hasattr(model.lm_head, "weight"):
num_params -= model.lm_head.weight.numel()
elif hasattr(model.lm_head, "base_layer"): # MultiLoRAModule
num_params -= model.lm_head.base_layer.weight.numel()
return num_params
def _count_trainable_params(self) -> int:
"""Count trainable parameters (LoRA adapters + modules_to_save)."""
trainable_params = 0
for param in self.model.parameters():
if param.requires_grad:
trainable_params += param.numel()
return trainable_params
def _count_lora_adapter_params(self) -> int:
"""Count LoRA adapter parameters (sum of lora_A and lora_B across all MultiLoRAModules)."""
params = 0
+2 -3
View File
@@ -11,19 +11,18 @@ from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
from vllm.distributed.utils import StatelessProcessGroup
from prime_rl.configs.trainer import NCCLWeightBroadcastConfig
from prime_rl.trainer.conversion_utils import get_max_layer_num
from prime_rl.trainer.models import PreTrainedModelPrimeRL
from prime_rl.trainer.rl.broadcast.base import WeightBroadcast
from prime_rl.trainer.runs import get_multi_run_manager
from prime_rl.trainer.utils import get_world
from prime_rl.trainer.weights import get_max_layer_num
from prime_rl.utils.client import NCCL_READY_MARKER
from prime_rl.utils.logger import get_logger
from prime_rl.utils.nccl import disable_nccl_p2p_if_unavailable
from prime_rl.utils.pathing import sync_wait_for_path
from prime_rl.utils.utils import get_broadcast_dir, get_step_path
from prime_rl.utils.vlm import get_layer_prefix
NCCL_READY_MARKER = "NCCL_READY"
def broadcast_integer(integer: int, communicator: PyNcclCommunicator) -> None:
"""Broadcast an integer to a process group using NCCL communicator."""
-3
View File
@@ -5,7 +5,6 @@ from typing import TypedDict
import torch
from jaxtyping import Bool, Float, Int
from torch import Tensor
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.configs.trainer import FakeDataLoaderConfig
from prime_rl.trainer.rl.packer import BasePacker, setup_packer
@@ -183,7 +182,6 @@ class DataLoader:
dp_world_size: int,
seq_len: int,
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
bin_cost: Callable[[Sequence[int]], int],
config: TransportConfig,
):
@@ -193,7 +191,6 @@ class DataLoader:
self.packer: BasePacker = setup_packer(
dp_world_size=dp_world_size,
seq_len=seq_len,
tokenizer=tokenizer,
transport_config=config,
pad_to_multiple_of=pad_to_multiple_of,
bin_cost=bin_cost,
-14
View File
@@ -63,20 +63,6 @@ def compute_entropy(shifted_logits: Float[Tensor, "batch seq vocab"]) -> Float[T
return entropy
@jaxtyped(typechecker=typechecker)
def shift_logits(
logits: Float[Tensor, "batch seq vocab"], left_pad_logit: Float[Tensor, "batch 1 vocab"] | None = None
) -> Float[Tensor, "batch seq vocab"]:
"""Removes final token logits and adds a left pad logit for the first token."""
# We drop the last logit because it corresponds to the next token that will be sampled but is not here yet
batch, seq, vocab = logits.shape
logits = logits[:, :-1, :] # (batch, seq-1, vocab)
if left_pad_logit is None:
left_pad_logit = torch.zeros(batch, 1, vocab, device=logits.device, dtype=logits.dtype) # (batch, 1, vocab)
logits = torch.cat([left_pad_logit, logits], dim=1) # (batch, seq, vocab)
return logits
def shift_tensor_left(t: Float[Tensor, "batch seq"]) -> Float[Tensor, "batch seq"]:
"""Shifts the tensor one token to the left.
+4 -15
View File
@@ -6,8 +6,6 @@ from abc import ABC, abstractmethod
from collections import deque
from collections.abc import Callable, Sequence
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.trainer.batch import prepare_batch
from prime_rl.trainer.runs import get_multi_run_manager
from prime_rl.transport import (
@@ -31,7 +29,6 @@ class BasePacker(ABC):
dp_world_size: int,
seq_len: int,
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
config: TransportConfig,
bin_cost: Callable[[Sequence[int]], int],
start_step: int = 0,
@@ -41,7 +38,6 @@ class BasePacker(ABC):
self.dp_world_size = dp_world_size
self.seq_len = seq_len
self.pad_to_multiple_of = pad_to_multiple_of
self.tokenizer = tokenizer
self.bin_cost = bin_cost
self.receiver = setup_training_batch_receiver(config)
shutil.rmtree(get_rollout_dir(self.multi_run_manager.output_dir), ignore_errors=True)
@@ -85,12 +81,11 @@ class SinglePacker(BasePacker):
dp_world_size: int,
seq_len: int,
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
config: TransportConfig,
bin_cost: Callable[[Sequence[int]], int],
start_step: int = 0,
):
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, bin_cost, start_step)
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, config, bin_cost, start_step)
assert self.multi_run_manager.max_runs == 1, "SinglePacker only supports one run"
def pack(self):
@@ -132,12 +127,11 @@ class MultiPacker(BasePacker):
dp_world_size: int,
seq_len: int,
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
config: TransportConfig,
bin_cost: Callable[[Sequence[int]], int],
start_step: int = 0,
):
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, bin_cost, start_step)
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, config, bin_cost, start_step)
# Per-run buffer: stores (TrainingSample, step) tuples
self.buffers: list[deque[tuple[TrainingSample, int]]] = [
deque() for _ in range(self.multi_run_manager.max_runs)
@@ -351,17 +345,12 @@ def setup_packer(
dp_world_size: int,
seq_len: int,
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
transport_config: TransportConfig,
bin_cost: Callable[[Sequence[int]], int],
start_step: int = 0,
) -> BasePacker:
multi_run_manager = get_multi_run_manager()
if multi_run_manager.max_runs == 1:
return SinglePacker(
dp_world_size, seq_len, pad_to_multiple_of, tokenizer, transport_config, bin_cost, start_step
)
return SinglePacker(dp_world_size, seq_len, pad_to_multiple_of, transport_config, bin_cost, start_step)
else:
return MultiPacker(
dp_world_size, seq_len, pad_to_multiple_of, tokenizer, transport_config, bin_cost, start_step
)
return MultiPacker(dp_world_size, seq_len, pad_to_multiple_of, transport_config, bin_cost, start_step)
-1
View File
@@ -239,7 +239,6 @@ def train(config: TrainerConfig):
parallel_dims.get_mesh("dp").size(),
config.model.seq_len,
config.model.cp,
tokenizer,
build_bin_cost(model.config),
config.rollout_transport,
)
-52
View File
@@ -24,26 +24,6 @@ from prime_rl.trainer.lora import (
)
from prime_rl.utils.logger import get_logger
PYTORCH_WRAPPER_PREFIXES = ["_fsdp_wrapped_module.", "_orig_module.", "_checkpoint_wrapped_module."]
def _strip_pytorch_wrapper_prefix(key: str) -> str:
for prefix in PYTORCH_WRAPPER_PREFIXES:
key = key.replace(prefix, "")
return key
def get_max_layer_num(state_dict: dict[str, Tensor], layer_prefix: str = "model.layers.") -> int:
"""Get the maximum number of layers in the model."""
max_num = -1
for key in state_dict:
if not key.startswith(layer_prefix):
continue
layer_num_str = key[len(layer_prefix) :].split(".")[0]
if layer_num_str.isdigit():
max_num = max(max_num, int(layer_num_str))
return max_num + 1
def load_state_dict_keys(save_dir: Path) -> list[str]:
"""Load only the key names from safetensor files without reading tensor data."""
@@ -152,35 +132,3 @@ def gather_weights_on_master(
cpu_state = clean_lora_state_dict(cpu_state)
return cpu_state
def get_adapter_state_dict(model: nn.Module, is_master: bool) -> dict[str, Tensor]:
"""Get adapter weights with clean keys for PEFT compatibility."""
lora_state = {}
named_params = {_strip_pytorch_wrapper_prefix(key): value for key, value in model.named_parameters()}
for key, value in model.state_dict().items():
param = named_params.get(key)
if param is None or not param.requires_grad:
continue
if isinstance(value, DTensor):
value = value.full_tensor()
if is_master:
clean_key = next(iter(get_fqns(model, key)))
clean_key = clean_key.replace(".base_layer.", ".")
# Add PEFT-expected prefix
peft_key = f"base_model.model.{clean_key}"
# Add .weight suffix for LoRA parameters if missing
if ("lora_A" in peft_key or "lora_B" in peft_key) and not peft_key.endswith(".weight"):
peft_key = f"{peft_key}.weight"
lora_state[peft_key] = value.to("cpu", non_blocking=False)
torch.distributed.barrier()
if is_master and len(lora_state) == 0:
raise ValueError("The LoRA state dict is empty. Something went wrong.")
return lora_state
-8
View File
@@ -10,14 +10,6 @@ class IncrementalTokenizationError(ValueError):
pass
def common_prefix_len(a: list[int], b: list[int]) -> int:
max_len = min(len(a), len(b))
for idx in range(max_len):
if a[idx] != b[idx]:
return idx
return max_len
def normalize_messages(messages: Any, default_role: str) -> list[dict[str, Any]]:
if messages is None:
return []
+6 -4
View File
@@ -407,8 +407,9 @@ async def update_weights(
weight update, then resumes. This ensures all DP workers are idle and can
participate in the collective weight transfer.
Note: The server-side /update_weights endpoint automatically resets the prefix cache
to invalidate any cached KV states computed with the old weights.
Note: the prefix cache is intentionally not reset on weight update. The orchestrator
salts the prefix cache per weight version (``cache_salt`` in the sampling request, see
``orchestrator/envs.py``), so KV computed under old weights is never reused.
"""
logger = get_logger()
@@ -470,8 +471,9 @@ LORA_LOAD_TOTAL_TIMEOUT_S = 120.0
async def load_lora_adapter(admin_clients: list[AsyncClient], lora_name: str, lora_path: Path) -> None:
"""Make a HTTP post request to the vLLM server to load a LoRA adapter.
Uses our wrapper endpoint that also resets the prefix cache to invalidate
KV states computed with old weights.
Uses our wrapper around vLLM's /v1/load_lora_adapter. The prefix cache is not reset
here; the orchestrator salts it per weight version (see ``orchestrator/envs.py``) so
KV computed under old weights is never reused.
Retries with exponential backoff if the adapter files are not found,
which can happen due to NFS propagation delays.
-28
View File
@@ -155,34 +155,6 @@ def gather_for_cp_wo_grad(t: torch.Tensor, cp_world_size: int, cp_group: dist.Pr
return torch.cat(empty_like_t, dim=1)
def get_padding_logit_from_prev_cp_rank(
logits: torch.Tensor, cp_rank: int, cp_world_size: int, cp_group: dist.ProcessGroup
) -> torch.Tensor | None:
"""
Get the padding logit from the previous context parallel rank.
Args:
logits: The logits tensor.
cp_rank: The rank of the current process.
cp_world_size: The number of processes in the context parallel group.
cp_group: The context parallel group.
Returns:
The padding logit from the previous context parallel rank.
"""
last_logit = logits[:, -1, :].unsqueeze(1)
all_rank_last_logits = [
torch.zeros(1, 1, logits.shape[2], dtype=logits.dtype, device=logits.device) for _ in range(cp_world_size)
]
dist.all_gather(all_rank_last_logits, last_logit, group=cp_group)
prev_cp_rank = cp_rank - 1
if prev_cp_rank >= 0:
return all_rank_last_logits[prev_cp_rank]
else:
return None
def setup_cp_params(
input_ids: torch.Tensor,
position_ids: torch.Tensor,
+1 -1
View File
@@ -43,7 +43,7 @@ class Heartbeat:
Non-blocking guarantee: This method never blocks the training loop. The HTTP
request runs in a daemon thread, so even if the server is slow/unresponsive
(up to the 2s timeout), training continues uninterrupted. The lock is held only
(up to the 1s timeout), training continues uninterrupted. The lock is held only
briefly (microseconds) to check/set flags atomically.
"""
with self._lock:
-57
View File
@@ -1,57 +0,0 @@
import hashlib
import torch
from torch.distributed.tensor import DTensor
from torch.optim.optimizer import Optimizer
TENSOR_SIG_SAMPLE_SIZE = 1000
def get_tensor_signature(a: torch.Tensor | torch.nn.Parameter) -> str:
while isinstance(a, torch.nn.Parameter):
a = a.data
if isinstance(a, DTensor):
a = a.to_local()
if a.device == torch.device("meta"):
return f"{a.dtype}{a.shape}<meta>"
if a.numel() < TENSOR_SIG_SAMPLE_SIZE:
b = a.as_strided(size=(a.numel(),), stride=(1,))
else:
step_size = a.numel() // TENSOR_SIG_SAMPLE_SIZE
b = a.as_strided(size=(TENSOR_SIG_SAMPLE_SIZE,), stride=(step_size,))
element_str = "".join([f"{x:.3e}" for x in b])
element_hash = hashlib.md5(element_str.encode("utf-8")).hexdigest()
return f"{a.dtype}{a.shape}{a.stride()}<{element_hash}>"
def get_signature(state_dict, compress: bool = True) -> str:
if compress:
return hashlib.md5(str(state_dict).encode("utf-8")).hexdigest()
else:
return "\n".join(f"{name}: {sig}" for name, sig in state_dict.items())
def get_optimizer_signature(optimizer: Optimizer, compress: bool = True) -> str:
def unwrap_tensor(state_dict: dict) -> dict:
new_dict = {}
for key, value in state_dict.items():
if isinstance(value, dict):
new_dict[key] = unwrap_tensor(value)
elif isinstance(value, torch.Tensor):
new_dict[key] = get_tensor_signature(value)
else:
new_dict[key] = str(value)
return new_dict
state_dict_sig = unwrap_tensor(optimizer.state_dict())
return get_signature(state_dict_sig, compress)
def get_module_signature(module: torch.nn.Module, compress: bool = True) -> str:
param_sig = {name: get_tensor_signature(param) for name, param in module.named_parameters()}
buffer_sig = {name: get_tensor_signature(buffer) for name, buffer in module.named_buffers()}
state_dict_sig = {**param_sig, **buffer_sig}
return get_signature(state_dict_sig, compress)
-45
View File
@@ -39,11 +39,6 @@ def import_object(dotted_path: str) -> Any:
return getattr(module, name)
def capitalize(s: str) -> str:
"""Capitalize the first letter of a string."""
return s[0].upper() + s[1:]
def clean_exit(func: Callable) -> Callable:
"""
A decorator that ensures the a torch.distributed process group is properly
@@ -113,26 +108,6 @@ def to_col_format(list_of_dicts: list[dict[str, Any]]) -> dict[str, list[Any]]:
return dict(dict_of_lists)
def to_row_format(dict_of_lists: dict[str, list[Any]]) -> list[dict[str, Any]]:
"""
Turns a dict of lists to a list of dicts.
Example:
```python
dict_of_lists = {"a": [1, 3], "b": [2, 4]} # Column format
to_row_format(dict_of_lists)
```
Returns:
```python
[{"a": 1, "b": 2}, {"a": 3, "b": 4}] # Row format
```
"""
return [dict(zip(dict_of_lists.keys(), values)) for values in zip(*dict_of_lists.values())]
def format_time(time_s: float) -> str:
"""
Format a time in seconds to a human-readable format:
@@ -188,15 +163,6 @@ def get_free_port() -> int:
return port
def get_cuda_visible_devices() -> list[int]:
"""Returns the list of availble CUDA devices, taking into account the CUDA_VISIBLE_DEVICES environment variable."""
cuda_visible = os.environ.get("CUDA_VISIBLE_DEVICES")
if cuda_visible is None:
# Default to all devices if the environment variable is not set
return list(range(torch.cuda.device_count()))
return list(sorted([int(device) for device in cuda_visible.split(",")]))
def get_latest_ckpt_step(weights_dir: Path) -> int | None:
step_dirs = list(weights_dir.glob("step_*"))
if len(step_dirs) == 0:
@@ -208,17 +174,6 @@ def get_latest_ckpt_step(weights_dir: Path) -> int | None:
return None
def mean(values: list[float] | list[int]) -> float:
"""Compute the mean of a list of values."""
return sum(values) / len(values) if values else 0.0
def mean_normalize(values: list[float] | list[int]) -> list[float]:
"""Mean-Normalize a list of values to 0-1."""
sum_values = sum(values)
return [value / sum_values if sum_values > 0 else 0.0 for value in values]
@contextmanager
def default_dtype(dtype):
prev = torch.get_default_dtype()
+186
View File
@@ -0,0 +1,186 @@
import math
from types import SimpleNamespace
import pytest
from prime_rl.orchestrator.metrics import EvalRollouts, Stat, TrainRollouts
from prime_rl.orchestrator.utils import compute_pass_metrics
def mk(
reward: float = 0.0,
*,
num_total_tokens: int = 10,
num_input_tokens: int = 4,
num_output_tokens: int = 6,
num_turns: int = 1,
num_branches: int = 1,
is_truncated: bool = False,
is_completed: bool = True,
has_error: bool = False,
error_type: str = "error",
stop_condition: str | None = None,
metrics: dict | None = None,
rewards: dict | None = None,
env_name: str = "env",
group_id: str = "g0",
is_trainable: bool = True,
is_filtered: bool = False,
filter_results: dict | None = None,
setup: float = 0.0,
generation: float = 0.0,
finalize: float = 0.0,
scoring: float = 0.0,
):
"""Duck-typed stand-in for ``Rollout``, exposing only the Trace properties the metrics read."""
return SimpleNamespace(
reward=reward,
rewards=rewards or {},
num_total_tokens=num_total_tokens,
num_input_tokens=num_input_tokens,
num_output_tokens=num_output_tokens,
num_turns=num_turns,
num_branches=num_branches,
is_truncated=is_truncated,
is_completed=is_completed,
has_error=has_error,
error=SimpleNamespace(type=error_type) if has_error else None,
stop_condition=stop_condition,
metrics=metrics or {},
env_name=env_name,
group_id=group_id,
is_trainable=is_trainable,
is_filtered=is_filtered,
filter_results=filter_results or {},
timing=SimpleNamespace(
setup=SimpleNamespace(duration=setup),
generation=SimpleNamespace(duration=generation),
finalize=SimpleNamespace(duration=finalize),
scoring=SimpleNamespace(duration=scoring),
),
)
def train_wandb(rollouts, subset: str = "all") -> dict:
return TrainRollouts(rollouts).metrics.to_wandb(prefix="train/agg", subset=subset)
def test_stat():
s = Stat([1.0, 2.0, 3.0])
assert (s.mean(), s.max(), s.min()) == (2.0, 3.0, 1.0)
assert (s.p10(), s.p90()) == pytest.approx((1.2, 2.8)) # linear-interpolated percentiles
assert s.to_dict("p") == pytest.approx({"p/mean": 2.0, "p/max": 3.0, "p/min": 1.0, "p/p10": 1.2, "p/p90": 2.8})
assert Stat([]).p90() == 0.0 and Stat([]).to_dict("p") == {}
def test_container_effective_by_env_and_listlike():
rc = TrainRollouts(
[mk(env_name="a"), mk(env_name="a", has_error=True), mk(env_name="b", is_filtered=True), mk(env_name="b")]
)
assert len(rc) == 4 and [r.env_name for r in rc] == ["a", "a", "b", "b"] # sized + iterable
eff = rc.effective
assert isinstance(eff, TrainRollouts) and len(eff) == 2 # same type, errored + filtered dropped
assert all(not r.has_error and not r.is_filtered and r in rc.rollouts for r in eff) # view of references
by_env = rc.by_env()
assert set(by_env) == {"a", "b"} and len(by_env["a"]) == 2 and isinstance(by_env["a"], TrainRollouts)
rc.append(mk())
assert len(rc) == 5
def test_to_wandb_distributions():
m = TrainRollouts(
[
mk(reward=1.0, num_total_tokens=10, num_input_tokens=4),
mk(reward=0.0, num_total_tokens=20, num_input_tokens=6),
]
).metrics
assert m.num_input_tokens.mean() == 5.0 # fluent Stat access
out = m.to_wandb(prefix="train/agg", subset="all")
assert out["train/agg/all/reward/mean"] == 0.5
assert out["train/agg/all/num_total_tokens/mean"] == 15.0
assert out["train/agg/all/num_total_tokens/max"] == 20.0 # flat over rollouts, not per-group
assert out["train/agg/all/num_input_tokens/mean"] == 5.0
assert out["train/agg/all/num_output_tokens/mean"] == 6.0
def test_boolean_rates_and_error_breakdown_all_only():
rc = TrainRollouts([mk(is_truncated=True), mk(has_error=True, error_type="ProviderError"), mk(is_filtered=True)])
out = rc.metrics.to_wandb(prefix="train/agg", subset="all")
assert out["train/agg/all/is_truncated/mean"] == 1 / 3
assert out["train/agg/all/is_completed/mean"] == 1.0
assert out["train/agg/all/has_error/mean"] == 1 / 3
assert out["train/agg/all/error/ProviderError"] == 1 # error-type breakdown by count
assert not any("no_response" in k for k in out) # removed metric
# has_error + the error-type counts are structurally empty on effective, so emitted on `all` only
eff = rc.effective.metrics.to_wandb(prefix="train/agg", subset="effective")
assert not any(k.endswith("/has_error/mean") or "/error/" in k for k in eff)
def test_solve_rates():
groups = {"A": [1.0, 1.0], "B": [0.0, 0.0], "C": [1.0, 0.0], "D": [1.0, 0.0]} # all / none / some / some
out = train_wandb([mk(reward=r, group_id=g) for g, rs in groups.items() for r in rs])
rates = (out["train/agg/all/solved_all"], out["train/agg/all/solved_none"], out["train/agg/all/solved_some"])
assert rates == (0.25, 0.25, 0.5)
def test_stop_condition_breakdown():
truncated = [mk(is_truncated=True, stop_condition=c) for c in ("length", "max_turns", "prompt_too_long")]
out = train_wandb(truncated + [mk(stop_condition=None)])
assert out["train/agg/all/stop_condition/generation_truncated"] == 0.5 # truncated & not prompt_too_long, over all
assert out["train/agg/all/stop_condition/length"] == 1 / 3 # over the 3 recorded conditions
assert out["train/agg/all/stop_condition/prompt_too_long"] == 1 / 3
def test_nested_metrics_and_rewards():
rollouts = [
mk(metrics={"acc": 1.0}, rewards={"correct": 1.0, "format": 0.0}),
mk(metrics={"acc": 3.0, "fmt": 5.0}, rewards={"correct": 0.0, "format": 1.0}),
]
m = TrainRollouts(rollouts).metrics
assert m.metrics["acc"].mean() == 2.0 and m.rewards["correct"].mean() == 0.5 # nested group access
out = m.to_wandb(prefix="train/agg", subset="all")
assert out["train/agg/all/metrics/acc/mean"] == 2.0 # averaged over reporters
assert out["train/agg/all/metrics/fmt/mean"] == 5.0 # single reporter
assert out["train/agg/all/rewards/format/mean"] == 0.5
def test_nested_timing():
m = TrainRollouts([mk(setup=1.0, generation=2.0, finalize=0.5, scoring=0.5)]).metrics
assert m.timing.setup.mean() == 1.0 and m.timing.total.mean() == 4.0 # total sums all four phases
out = m.to_wandb(prefix="train/agg", subset="all")
assert out["train/agg/all/timing/setup/mean"] == 1.0
assert out["train/agg/all/timing/total/mean"] == 4.0
def test_train_only_metrics_absent_from_eval():
rollouts = [
mk(is_trainable=True, is_filtered=True, filter_results={"gibberish": True}),
mk(is_trainable=False, filter_results={"gibberish": False}),
]
out = train_wandb(rollouts)
assert out["train/agg/all/is_trainable/mean"] == 0.5
assert out["train/agg/all/is_filtered/mean"] == 0.5
assert out["train/agg/all/filters/gibberish/mean"] == 0.5
eval_out = EvalRollouts(rollouts).metrics.to_wandb(prefix="eval/x", subset="all")
assert not any("is_trainable" in k or "is_filtered" in k or "/filters/" in k for k in eval_out)
def test_eval_avg_at_k_and_pass_k():
binary = EvalRollouts([mk(reward=1.0, group_id="g0"), mk(reward=0.0, group_id="g0")])
eff = binary.effective.metrics.to_wandb(prefix="eval/x", subset="effective")
assert eff["eval/x/effective/avg@2"] == 0.5 # mean reward under avg@<k> (k derived from the groups)
assert not any(k.startswith("eval/x/effective/reward") for k in eff)
assert eff["eval/x/effective/pass@1"] == 0.5 and eff["eval/x/effective/pass^2"] == 0.0
all_out = binary.metrics.to_wandb(prefix="eval/x", subset="all")
assert all_out["eval/x/all/avg@2"] == 0.5
assert not any("pass@" in k or "pass^" in k for k in all_out) # pass@k effective-only
non_binary = EvalRollouts([mk(reward=0.5, group_id="g0"), mk(reward=1.0, group_id="g0")])
assert not any("pass@" in k for k in non_binary.effective.metrics.to_wandb(prefix="eval/x", subset="effective"))
def test_compute_pass_metrics_matches_closed_form():
out = compute_pass_metrics([1.0, 1.0, 0.0, 0.0]) # n=4, c=2
assert out["pass@1"] == 1.0 - math.comb(2, 1) / math.comb(4, 1)
assert out["pass@2"] == 1.0 - math.comb(2, 2) / math.comb(4, 2)
assert out["pass^2"] == math.comb(2, 2) / math.comb(4, 2)
assert set(out) == {"pass@1", "pass@2", "pass@4", "pass^1", "pass^2", "pass^4"}
-1
View File
@@ -92,7 +92,6 @@ def test_packer_progress_updates_once_per_run(tmp_path: Path, monkeypatch: pytes
dp_world_size=1,
seq_len=4,
pad_to_multiple_of=1,
tokenizer=None,
config=FileSystemTransportConfig(),
bin_cost=build_bin_cost(None),
start_step=0,
Generated
+271 -15
View File
@@ -557,6 +557,21 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/e6/ec/0c42039e80b9acc534f67b73b7a42471948042859b3a64867b50a4a77fa3/chromadb-1.5.9-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cc09b3df76e5a5cb386aed2715a2eea152e3949f9e1ba93c7119505377749929", size = 23316203, upload-time = "2026-05-05T05:54:41.157Z" },
]
[[package]]
name = "claude-agent-sdk"
version = "0.2.107"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "anyio" },
{ name = "mcp" },
{ name = "sniffio" },
]
sdist = { url = "https://files.pythonhosted.org/packages/5a/f1/34820c3b12ec3d10d1cf4b72a877958134e4e2e7bd5af4dbc0cf4f55df33/claude_agent_sdk-0.2.107.tar.gz", hash = "sha256:e1310eef43b886c66ac157b9e80af0fb6ccedd83ad6acc9d4a6bb59cffdd2620", size = 255641, upload-time = "2026-06-22T20:51:00.429Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/fc/f1/ae6db2aa82f4d10ffa2c3c6953c2079d969f43e45bbf5f1ba3e5e6c66dad/claude_agent_sdk-0.2.107-py3-none-manylinux_2_17_aarch64.whl", hash = "sha256:abda89a41a4bcf2a9e1a3a94edf165ea5632174878874fcbfeeadbcc40e7f7d2", size = 73397534, upload-time = "2026-06-22T20:51:10.696Z" },
{ url = "https://files.pythonhosted.org/packages/9e/91/24808205b576842fb1ea8856d92da6ddca2903e1c3582e16d0ff0ed1b9d9/claude_agent_sdk-0.2.107-py3-none-manylinux_2_17_x86_64.whl", hash = "sha256:e3eabda428cbb1da71f1f0d3c742f81b1fe36c44d84e744fde39c4b9dbd3781b", size = 74371415, upload-time = "2026-06-22T20:51:14.154Z" },
]
[[package]]
name = "click"
version = "8.4.1"
@@ -913,6 +928,18 @@ dependencies = [
[package.metadata]
requires-dist = [{ name = "verifiers" }]
[[package]]
name = "deprecation"
version = "2.1.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "packaging" },
]
sdist = { url = "https://files.pythonhosted.org/packages/5a/d3/8ae2869247df154b64c1884d7346d412fed0c49df84db635aab2d1c40e62/deprecation-2.1.0.tar.gz", hash = "sha256:72b3bde64e5d778694b0cf68178aed03d15e15477116add3fb773e581f9518ff", size = 173788, upload-time = "2020-04-20T14:23:38.738Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/02/c3/253a89ee03fc9b9682f1541728eb66db7db22148cd94f89ab22528cd1e1b/deprecation-2.1.0-py2.py3-none-any.whl", hash = "sha256:a10811591210e1fb0e768a8c25517cabeabcba6f0bf96564f8ff45189f90b14a", size = 11178, upload-time = "2020-04-20T14:23:36.581Z" },
]
[[package]]
name = "depyf"
version = "0.20.0"
@@ -954,6 +981,18 @@ dependencies = [
{ name = "triton" },
]
[[package]]
name = "dirhash"
version = "0.5.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "scantree" },
]
sdist = { url = "https://files.pythonhosted.org/packages/1d/70/49f93897f3a4f7ab5f20a854ebc91aad47854e9fb2cd169e3a4452fa3f5e/dirhash-0.5.0.tar.gz", hash = "sha256:e60760f0ab2e935d8cb088923ea2c6492398dca42cec785df778985fd4cd5386", size = 21377, upload-time = "2024-08-03T22:14:13.322Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/5e/1f/c8bf92552b7f0a13b9f12b85e3de8df6d9814240e0f8ce8f37433df028b3/dirhash-0.5.0-py3-none-any.whl", hash = "sha256:523dfd6b058c64f45b31604376926c6e2bd2ea301d0df23095d4055674e38b09", size = 13119, upload-time = "2024-08-03T22:14:11.688Z" },
]
[[package]]
name = "diskcache"
version = "5.6.3"
@@ -1383,7 +1422,7 @@ dependencies = [
requires-dist = [
{ name = "filelock" },
{ name = "pydantic" },
{ name = "verifiers", specifier = ">=0.1.15.dev381" },
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
]
[[package]]
@@ -1593,6 +1632,50 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" },
]
[[package]]
name = "h2"
version = "4.3.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "hpack" },
{ name = "hyperframe" },
]
sdist = { url = "https://files.pythonhosted.org/packages/1d/17/afa56379f94ad0fe8defd37d6eb3f89a25404ffc71d4d848893d270325fc/h2-4.3.0.tar.gz", hash = "sha256:6c59efe4323fa18b47a632221a1888bd7fde6249819beda254aeca909f221bf1", size = 2152026, upload-time = "2025-08-23T18:12:19.778Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/69/b2/119f6e6dcbd96f9069ce9a2665e0146588dc9f88f29549711853645e736a/h2-4.3.0-py3-none-any.whl", hash = "sha256:c438f029a25f7945c69e0ccf0fb951dc3f73a5f6412981daee861431b70e2bdd", size = 61779, upload-time = "2025-08-23T18:12:17.779Z" },
]
[[package]]
name = "harbor"
version = "0.14.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "claude-agent-sdk" },
{ name = "datasets" },
{ name = "dirhash" },
{ name = "fastapi" },
{ name = "httpx" },
{ name = "jinja2" },
{ name = "litellm" },
{ name = "packaging" },
{ name = "pathspec" },
{ name = "pydantic" },
{ name = "python-dotenv" },
{ name = "pyyaml" },
{ name = "requests" },
{ name = "rich" },
{ name = "shortuuid" },
{ name = "supabase" },
{ name = "tenacity" },
{ name = "toml" },
{ name = "typer" },
{ name = "uvicorn" },
]
sdist = { url = "https://files.pythonhosted.org/packages/a9/f3/cba38a11b0cca01ecd471437869f1cd57d86a3b1e4091b8fd3d112cba8af/harbor-0.14.0.tar.gz", hash = "sha256:0ffffc25a618e4b7bf2b901a8c717c8bc28877f5aa8c37be47f1ec8c301cb0b6", size = 1241271, upload-time = "2026-06-17T16:43:23.495Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/f6/22/cb447121af474cfc7662b9f997be20316eadc692f19fa884608460589020/harbor-0.14.0-py3-none-any.whl", hash = "sha256:171971a008386ce633ef9f53fb4170e7d7807dba15349e930366581dd4c511e2", size = 1412739, upload-time = "2026-06-17T16:43:25.062Z" },
]
[[package]]
name = "hf-xet"
version = "1.5.0"
@@ -1605,6 +1688,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/aa/b2/703569fc881f3284487e68cda7b42179978480da3c438042a6bbbb4a671c/hf_xet-1.5.0-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:4b35549ce62601b84da4ff9b24d970032ace3d4430f52d91bcbb26c901d6c690", size = 4672414, upload-time = "2026-05-06T06:18:09.864Z" },
]
[[package]]
name = "hpack"
version = "4.2.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/26/5b/fcabf6028144a8723726318b07a32c2f3314acdff6265743cf08a344b18e/hpack-4.2.0.tar.gz", hash = "sha256:0895cfa3b5531fc65fe439c05eb65144f123bf7a394fcaa56aa423548d8e45c0", size = 51300, upload-time = "2026-06-23T18:34:46.667Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/71/b4/4a9fcfb2aef6ba44d9073ecd301443aa00b3dac95de5619f2a7de7ec8a91/hpack-4.2.0-py3-none-any.whl", hash = "sha256:858ac0b02280fa582b5080d68db0899c62a80375e0e5413a74970c5e518b6986", size = 34246, upload-time = "2026-06-23T18:34:45.472Z" },
]
[[package]]
name = "httpcore"
version = "1.0.9"
@@ -1645,6 +1737,11 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" },
]
[package.optional-dependencies]
http2 = [
{ name = "h2" },
]
[[package]]
name = "httpx-sse"
version = "0.4.3"
@@ -1703,6 +1800,15 @@ cu12 = [
{ name = "nvidia-cuda-runtime-cu12" },
]
[[package]]
name = "hyperframe"
version = "6.1.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/02/e7/94f8232d4a74cc99514c13a9f995811485a6903d48e5d952771ef6322e30/hyperframe-6.1.0.tar.gz", hash = "sha256:f630908a00854a7adeabd6382b43923a4c4cd4b821fcb527e6ab9e15382a3b08", size = 26566, upload-time = "2025-01-22T21:41:49.302Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/48/30/47d0bf6072f7252e6521f3447ccfa40b421b6824517f82854703d0f5a98b/hyperframe-6.1.0-py3-none-any.whl", hash = "sha256:b03380493a519fce58ea5af42e4a42317bf9bd425596f7a0835ffce80f1a42e5", size = 13007, upload-time = "2025-01-22T21:41:47.295Z" },
]
[[package]]
name = "i3-code-v1"
version = "0.1.0"
@@ -2194,7 +2300,7 @@ dependencies = [
[package.metadata]
requires-dist = [
{ name = "datasets", specifier = ">=2.0.0" },
{ name = "verifiers", specifier = ">=0.1.15.dev402" },
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
]
[[package]]
@@ -2373,6 +2479,21 @@ requires-dist = [
{ name = "verifiers", specifier = ">=0.1.15.dev381" },
]
[[package]]
name = "longpdfs-v1"
version = "0.0.1"
source = { editable = "deps/research-environments/environments/longpdfs_v1" }
dependencies = [
{ name = "datasets" },
{ name = "verifiers" },
]
[package.metadata]
requires-dist = [
{ name = "datasets", specifier = ">=3.0" },
{ name = "verifiers", specifier = ">=0.1.15.dev381" },
]
[[package]]
name = "mamba-ssm"
version = "2.3.1"
@@ -3347,7 +3468,7 @@ dependencies = [
[package.metadata]
requires-dist = [
{ name = "datasets" },
{ name = "verifiers", specifier = ">=0.1.15.dev397" },
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
]
[[package]]
@@ -3586,6 +3707,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/42/32/658973117bf0fd82a24abbfb94fe73a5e86216e49342985e10acce54775a/partial_json_parser-0.2.1.1.post7-py3-none-any.whl", hash = "sha256:145119e5eabcf80cbb13844a6b50a85c68bf99d376f8ed771e2a3c3b03e653ae", size = 10877, upload-time = "2025-11-17T07:27:40.457Z" },
]
[[package]]
name = "pathspec"
version = "1.1.1"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/5a/82/42f767fc1c1143d6fd36efb827202a2d997a375e160a71eb2888a925aac1/pathspec-1.1.1.tar.gz", hash = "sha256:17db5ecd524104a120e173814c90367a96a98d07c45b2e10c2f3919fff91bf5a", size = 135180, upload-time = "2026-04-27T01:46:08.907Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/f1/d9/7fb5aa316bc299258e68c73ba3bddbc499654a07f151cba08f6153988714/pathspec-1.1.1-py3-none-any.whl", hash = "sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189", size = 57328, upload-time = "2026-04-27T01:46:07.06Z" },
]
[[package]]
name = "patterned-needle-in-haystack-v1"
version = "0.1.0"
@@ -3667,6 +3797,21 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" },
]
[[package]]
name = "postgrest"
version = "2.31.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "deprecation" },
{ name = "httpx", extra = ["http2"] },
{ name = "pydantic" },
{ name = "yarl" },
]
sdist = { url = "https://files.pythonhosted.org/packages/e2/22/88c470d8838d2678a44e0172d061630b8837cba3fb7fb492e28f6578c309/postgrest-2.31.0.tar.gz", hash = "sha256:2f395d84b2ee34fc57622ff2f711df603e2ede625f98e5015240741888f7bd0c", size = 14419, upload-time = "2026-06-04T13:37:20.474Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/ea/3e/41909586cb148db0259e0208310067afda4cc097f4c7a779e829c1e68c46/postgrest-2.31.0-py3-none-any.whl", hash = "sha256:c2fd47c94e13ee8335111c4f03c9a24ea9766ce9d35fc3cd7330057c9e7ea0c3", size = 23098, upload-time = "2026-06-04T13:37:19.452Z" },
]
[[package]]
name = "pre-commit"
version = "4.6.0"
@@ -3810,7 +3955,7 @@ dependencies = [
{ name = "torchvision" },
{ name = "transformers" },
{ name = "uvloop" },
{ name = "verifiers" },
{ name = "verifiers", extra = ["harbor"] },
{ name = "vllm", version = "0.23.0+cu129", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.23.0/vllm-0.23.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl" }, marker = "platform_machine != 'x86_64'" },
{ name = "vllm", version = "0.23.0+cu129", source = { url = "https://github.com/vllm-project/vllm/releases/download/v0.23.0/vllm-0.23.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64'" },
{ name = "wandb" },
@@ -3863,6 +4008,7 @@ envs = [
{ name = "logic-env" },
{ name = "longcot-mini-v1" },
{ name = "longcot-v1" },
{ name = "longpdfs-v1" },
{ name = "math-env" },
{ name = "math-env-v1" },
{ name = "math-python" },
@@ -3975,6 +4121,7 @@ requires-dist = [
{ name = "loguru", specifier = ">=0.7.3" },
{ name = "longcot-mini-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/longcot_mini_v1" },
{ name = "longcot-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/longcot_v1" },
{ name = "longpdfs-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/longpdfs_v1" },
{ name = "math-env", marker = "extra == 'envs'", editable = "deps/research-environments/environments/math_env" },
{ name = "math-env-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/math_env_v1" },
{ name = "math-python", marker = "extra == 'envs'", editable = "deps/verifiers/environments/math_python" },
@@ -4041,7 +4188,7 @@ requires-dist = [
{ name = "uuid-ctf-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/uuid_ctf_v1" },
{ name = "uvloop", specifier = ">=0.21.0" },
{ name = "verbatim-copy-v1", marker = "extra == 'envs'", editable = "deps/research-environments/environments/verbatim_copy_v1" },
{ name = "verifiers", editable = "deps/verifiers" },
{ name = "verifiers", extras = ["harbor"], editable = "deps/verifiers" },
{ name = "vllm", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64'", specifier = ">=0.23.0" },
{ name = "vllm", marker = "platform_machine == 'aarch64'", url = "https://github.com/vllm-project/vllm/releases/download/v0.23.0/vllm-0.23.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl" },
{ name = "vllm", marker = "platform_machine == 'x86_64'", url = "https://github.com/vllm-project/vllm/releases/download/v0.23.0/vllm-0.23.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl" },
@@ -4130,7 +4277,7 @@ dependencies = [
]
[package.metadata]
requires-dist = [{ name = "verifiers", specifier = ">=0.1.15.dev402" }]
requires-dist = [{ name = "verifiers", specifier = ">=0.1.15.dev411" }]
[[package]]
name = "prometheus-client"
@@ -4604,6 +4751,20 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/6f/ec/550313f340b10501e72e69faf7a04223f99e4877c1cab7972eb3fbac3617/rdkit-2026.3.3-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:c69a40ad52a2489cf592d55b41f5f6fa482f028341c038f3ed7d6b46834d1d3d", size = 37188323, upload-time = "2026-06-05T18:42:47.48Z" },
]
[[package]]
name = "realtime"
version = "2.31.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "pydantic" },
{ name = "typing-extensions" },
{ name = "websockets" },
]
sdist = { url = "https://files.pythonhosted.org/packages/df/34/54a1eaaefa24db5cb12596fd74792e08efa53ed30dc5bce2c0a68ded6146/realtime-2.31.0.tar.gz", hash = "sha256:9e641cb4d77ca0fe768515f8cf9f83550c79f49ce1550a95afc2dc0e252be8c9", size = 18716, upload-time = "2026-06-04T13:37:22.089Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/13/60/164246615e8b059f6d53d34648a0784260421ec98a07eb1e45160f063221/realtime-2.31.0-py3-none-any.whl", hash = "sha256:f6e494b53d6a6e80b6efcee6711c8dd40413a52e766271de1bce8ced6c36cc1d", size = 22374, upload-time = "2026-06-04T13:37:21.162Z" },
]
[[package]]
name = "redis"
version = "8.0.0"
@@ -4625,7 +4786,7 @@ dependencies = [
[package.metadata]
requires-dist = [
{ name = "datasets" },
{ name = "verifiers", specifier = ">=0.1.15.dev397" },
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
]
[[package]]
@@ -4864,6 +5025,19 @@ requires-dist = [
{ name = "verifiers", specifier = ">=0.1.15.dev381" },
]
[[package]]
name = "scantree"
version = "0.0.4"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "attrs" },
{ name = "pathspec" },
]
sdist = { url = "https://files.pythonhosted.org/packages/b3/e4/40998faefc72ba1ddeb640a44fba92935353525dba110488806da8339c0b/scantree-0.0.4.tar.gz", hash = "sha256:15bd5cb24483b04db2c70653604e8ea3522e98087db7e38ab8482f053984c0ac", size = 24643, upload-time = "2024-08-03T20:08:59.413Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/93/ce/828467ddfa0d2fe473673026442d2032d552a168e42cfbf25fd0e5264e0c/scantree-0.0.4-py3-none-any.whl", hash = "sha256:7616ab65aa6b7f16fcf8e6fa1d9afaa99a27ab72bba05c61b691853b96763174", size = 20690, upload-time = "2024-08-03T20:08:58.137Z" },
]
[[package]]
name = "scikit-learn"
version = "1.9.0"
@@ -4963,6 +5137,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" },
]
[[package]]
name = "shortuuid"
version = "1.0.13"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/8c/e2/bcf761f3bff95856203f9559baf3741c416071dd200c0fc19fad7f078f86/shortuuid-1.0.13.tar.gz", hash = "sha256:3bb9cf07f606260584b1df46399c0b87dd84773e7b25912b7e391e30797c5e72", size = 9662, upload-time = "2024-03-11T20:11:06.879Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/c0/44/21d6bf170bf40b41396480d8d49ad640bca3f2b02139cd52aa1e272830a5/shortuuid-1.0.13-py3-none-any.whl", hash = "sha256:a482a497300b49b4953e15108a7913244e1bb0d41f9d332f5e9925dba33a3c5a", size = 10529, upload-time = "2024-03-11T20:11:04.807Z" },
]
[[package]]
name = "simpleqa-v1"
version = "0.1.0"
@@ -5141,6 +5324,76 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/81/0d/13d1d239a25cbfb19e740db83143e95c772a1fe10202dda4b76792b114dd/starlette-0.52.1-py3-none-any.whl", hash = "sha256:0029d43eb3d273bc4f83a08720b4912ea4b071087a3b48db01b7c839f7954d74", size = 74272, upload-time = "2026-01-18T13:34:09.188Z" },
]
[[package]]
name = "storage3"
version = "2.31.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "deprecation" },
{ name = "httpx", extra = ["http2"] },
{ name = "pydantic" },
{ name = "yarl" },
]
sdist = { url = "https://files.pythonhosted.org/packages/13/30/fee43d523d3f680a833a4aae5bf8094de0b9031b0c2bddb3e0bc6e829e1b/storage3-2.31.0.tar.gz", hash = "sha256:d2161e2ea650dc115a1787c30e09b118365589ac772f4dd8643e3a503ecfc667", size = 20348, upload-time = "2026-06-04T13:37:23.703Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/2f/b2/60d86a3a99ae743e8a00a6df912f85269b3bc882ba217b8ce1690881c669/storage3-2.31.0-py3-none-any.whl", hash = "sha256:4bf46e8bea320743179a6beafdc7531c5242495e00e0cc22af7c7a9d69d4ed84", size = 28492, upload-time = "2026-06-04T13:37:22.792Z" },
]
[[package]]
name = "strenum"
version = "0.4.15"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/85/ad/430fb60d90e1d112a62ff57bdd1f286ec73a2a0331272febfddd21f330e1/StrEnum-0.4.15.tar.gz", hash = "sha256:878fb5ab705442070e4dd1929bb5e2249511c0bcf2b0eeacf3bcd80875c82eff", size = 23384, upload-time = "2023-06-29T22:02:58.399Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/81/69/297302c5f5f59c862faa31e6cb9a4cd74721cd1e052b38e464c5b402df8b/StrEnum-0.4.15-py3-none-any.whl", hash = "sha256:a30cda4af7cc6b5bf52c8055bc4bf4b2b6b14a93b574626da33df53cf7740659", size = 8851, upload-time = "2023-06-29T22:02:56.947Z" },
]
[[package]]
name = "supabase"
version = "2.31.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "httpx" },
{ name = "postgrest" },
{ name = "realtime" },
{ name = "storage3" },
{ name = "supabase-auth" },
{ name = "supabase-functions" },
{ name = "yarl" },
]
sdist = { url = "https://files.pythonhosted.org/packages/fe/8e/54a2f950629689b1613434a61fc3bff5f92f84ba6b20213f5b2add05c1bb/supabase-2.31.0.tar.gz", hash = "sha256:3467b09d00482b9a0138235bdbde7a350426f93cf2a1342372eaddfc669f1206", size = 9805, upload-time = "2026-06-04T13:37:25.22Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/95/06/5e6f4bf89dedadf81f893832115c1866da1aa093142c9989c2818780dae3/supabase-2.31.0-py3-none-any.whl", hash = "sha256:25f2a99207a75f2d9377e2332783b4389cf56b02cbebdaf0c1743112dcbb704e", size = 16728, upload-time = "2026-06-04T13:37:24.278Z" },
]
[[package]]
name = "supabase-auth"
version = "2.31.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "httpx", extra = ["http2"] },
{ name = "pydantic" },
{ name = "pyjwt", extra = ["crypto"] },
]
sdist = { url = "https://files.pythonhosted.org/packages/61/8a/408689cf39820f0d46d2731d6747ff94dbefc87ae977b4b5c4066da5b070/supabase_auth-2.31.0.tar.gz", hash = "sha256:0945b33fa96239c76dc8eaf96d7d2c94991950d24b4cfe4a5c2da9aa5e909663", size = 39151, upload-time = "2026-06-04T13:37:27.375Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/ca/5e/22f3b0546bb1f0985f06fb1ebf5f6405a3b1bb7a5db01142c26cf148e988/supabase_auth-2.31.0-py3-none-any.whl", hash = "sha256:5e9c8b4ecdee6af04dbcb06455ce78cb15674806fcb6b425170455307d70b0ee", size = 48363, upload-time = "2026-06-04T13:37:26.26Z" },
]
[[package]]
name = "supabase-functions"
version = "2.31.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "httpx", extra = ["http2"] },
{ name = "strenum" },
{ name = "yarl" },
]
sdist = { url = "https://files.pythonhosted.org/packages/84/5d/61c2446ed26a57fa5543f9c270a731320911569202340d15341f72cdba7c/supabase_functions-2.31.0.tar.gz", hash = "sha256:4ad027b3ae3bd28b31233339f4db1da6965affd3546f655b421baf40cee2690f", size = 4683, upload-time = "2026-06-04T13:37:28.878Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/90/79/1a8162ce7d705381a4f2668c0da68e097b103c1aa701418a31da52905c7b/supabase_functions-2.31.0-py3-none-any.whl", hash = "sha256:3fdc4c4766152bfda63bdd0e286fc8a06f50e1280711fae4a1dfc9b7e9ebabc6", size = 8794, upload-time = "2026-06-04T13:37:28.022Z" },
]
[[package]]
name = "supervisor"
version = "4.3.0"
@@ -5263,7 +5516,7 @@ dependencies = [
requires-dist = [
{ name = "audioop-lts", marker = "python_full_version >= '3.13'" },
{ name = "tau2", git = "https://github.com/sierra-research/tau2-bench.git?rev=337326e" },
{ name = "verifiers", specifier = ">=0.1.15.dev381" },
{ name = "verifiers", specifier = ">=0.1.15.dev411" },
]
[[package]]
@@ -5876,6 +6129,9 @@ dependencies = [
]
[package.optional-dependencies]
harbor = [
{ name = "harbor" },
]
ta = [
{ name = "nltk" },
{ name = "textarena" },
@@ -6480,15 +6736,15 @@ wheels = [
[[package]]
name = "websockets"
version = "16.0"
version = "15.0.1"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/04/24/4b2031d72e840ce4c1ccb255f693b15c334757fc50023e4db9537080b8c4/websockets-16.0.tar.gz", hash = "sha256:5f6261a5e56e8d5c42a4497b364ea24d94d9563e8fbd44e78ac40879c60179b5", size = 179346, upload-time = "2026-01-10T09:23:47.181Z" }
sdist = { url = "https://files.pythonhosted.org/packages/21/e6/26d09fab466b7ca9c7737474c52be4f76a40301b08362eb2dbc19dcc16c1/websockets-15.0.1.tar.gz", hash = "sha256:82544de02076bafba038ce055ee6412d68da13ab47f0c60cab827346de828dee", size = 177016, upload-time = "2025-03-05T20:03:41.606Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/18/29/71729b4671f21e1eaa5d6573031ab810ad2936c8175f03f97f3ff164c802/websockets-16.0-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:9b5aca38b67492ef518a8ab76851862488a478602229112c4b0d58d63a7a4d5c", size = 184915, upload-time = "2026-01-10T09:22:51.071Z" },
{ url = "https://files.pythonhosted.org/packages/97/bb/21c36b7dbbafc85d2d480cd65df02a1dc93bf76d97147605a8e27ff9409d/websockets-16.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e0334872c0a37b606418ac52f6ab9cfd17317ac26365f7f65e203e2d0d0d359f", size = 186152, upload-time = "2026-01-10T09:22:52.224Z" },
{ url = "https://files.pythonhosted.org/packages/4a/34/9bf8df0c0cf88fa7bfe36678dc7b02970c9a7d5e065a3099292db87b1be2/websockets-16.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:a0b31e0b424cc6b5a04b8838bbaec1688834b2383256688cf47eb97412531da1", size = 185583, upload-time = "2026-01-10T09:22:53.443Z" },
{ url = "https://files.pythonhosted.org/packages/47/88/4dd516068e1a3d6ab3c7c183288404cd424a9a02d585efbac226cb61ff2d/websockets-16.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:485c49116d0af10ac698623c513c1cc01c9446c058a4e61e3bf6c19dff7335a2", size = 184880, upload-time = "2026-01-10T09:22:55.033Z" },
{ url = "https://files.pythonhosted.org/packages/6f/28/258ebab549c2bf3e64d2b0217b973467394a9cea8c42f70418ca2c5d0d2e/websockets-16.0-py3-none-any.whl", hash = "sha256:1637db62fad1dc833276dded54215f2c7fa46912301a24bd94d45d46a011ceec", size = 171598, upload-time = "2026-01-10T09:23:45.395Z" },
{ url = "https://files.pythonhosted.org/packages/a6/02/0073b3952f5bce97eafbb35757f8d0d54812b6174ed8dd952aa08429bcc3/websockets-15.0.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e8b56bdcdb4505c8078cb6c7157d9811a85790f2f2b3632c7d1462ab5783d215", size = 183152, upload-time = "2025-03-05T20:02:22.286Z" },
{ url = "https://files.pythonhosted.org/packages/14/8f/aa61f528fba38578ec553c145857a181384c72b98156f858ca5c8e82d9d3/websockets-15.0.1-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:64dee438fed052b52e4f98f76c5790513235efaa1ef7f3f2192c392cd7c91b65", size = 182523, upload-time = "2025-03-05T20:02:25.669Z" },
{ url = "https://files.pythonhosted.org/packages/ec/6d/0267396610add5bc0d0d3e77f546d4cd287200804fe02323797de77dbce9/websockets-15.0.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:d5f6b181bb38171a8ad1d6aa58a67a6aa9d4b38d0f8c5f496b9e42561dfc62fe", size = 182790, upload-time = "2025-03-05T20:02:26.99Z" },
{ url = "https://files.pythonhosted.org/packages/29/93/bb672df7b2f5faac89761cb5fa34f5cec45a4026c383a4b5761c6cea5c16/websockets-15.0.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3be571a8b5afed347da347bfcf27ba12b069d9d7f42cb8c7028b5e98bbb12597", size = 182160, upload-time = "2025-03-05T20:02:31.634Z" },
{ url = "https://files.pythonhosted.org/packages/fa/a8/5b41e0da817d64113292ab1f8247140aac61cbf6cfd085d6a0fa77f4984f/websockets-15.0.1-py3-none-any.whl", hash = "sha256:f7a866fbc1e97b5c617ee4116daaa09b722101d4a3c170c787450ba409f9736f", size = 169743, upload-time = "2025-03-05T20:03:39.41Z" },
]
[[package]]