Compare commits

...
53 Commits
Author SHA1 Message Date
32adbba802 Sami/fix logging env (#1602)
Release / Push CUDA image to Docker (push) Canceled after 0s
* make per worker env false by defaulot

* udpate changelogkl

---------

Co-authored-by: sami jaghouar <sami@primeintellect.ai>
2026-01-15 16:01:04 -08:00
JannikStandGitHub c330a6d4eb Add InfiniBand libraries for NCCL multi-node support (#1600)
* Add InfiniBand libraries for NCCL multi-node support

* Fix: remove comment breaking Dockerfile line continuation
2026-01-15 14:28:05 -08:00
11d87ee888 Incomplete evaluation results (#1589)
* Eval: record no-response rollouts instead of cancelling

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

* Eval: report no_response percentage metric

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

* Fix eval: don't clobber successful rollouts on save failure

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

* Annotate save failures without discarding state

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

* Revert "Annotate save failures without discarding state"

This reverts commit 85a0e3c441eb0b053964b0feb0eaab2863699e3b.

* Update src/prime_rl/eval/utils.py

Co-authored-by: rasdani <73563550+rasdani@users.noreply.github.com>
Signed-off-by: samsja <55492238+samsja@users.noreply.github.com>

* Eval: ignore failed rollouts in avg reward; simplify saving

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

* Simplify rollout_status parsing (assume dict)

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

* Update src/prime_rl/eval/utils.py

Co-authored-by: rasdani <73563550+rasdani@users.noreply.github.com>
Signed-off-by: samsja <55492238+samsja@users.noreply.github.com>

---------

Signed-off-by: samsja <55492238+samsja@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: sami <sami@primeintellect.ai>
Co-authored-by: rasdani <73563550+rasdani@users.noreply.github.com>
2026-01-15 13:05:27 -08:00
0e5940f82b refactor logging on environment in orch (#1594)
* remove logging

* add per env logging

* log to one file when having multiple worker

* intercept verifier log

* intercept verifier log

* intercept verifier log

* Add worker tag to env worker logger for identification

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

* Update changelog for logging config changes

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

* Rename env worker log config flag

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

---------

Signed-off-by: samsja <55492238+samsja@users.noreply.github.com>
Co-authored-by: sami jaghouar <sami@primeintellect.ai>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
2026-01-15 13:04:27 -08:00
969df59e54 fix eval order (#1598)
Co-authored-by: sami jaghouar <sami@primeintellect.ai>
2026-01-15 11:22:54 -08:00
ff620131e4 remove logging (#1592)
Co-authored-by: sami jaghouar <sami@primeintellect.ai>
2026-01-15 10:11:27 -08:00
Jackmin801andGitHub c95bd79d43 Make packer pack smaller granularity and round-robin (#1542)
* generated packer tests

* simplify packer tests

* packer doc

* support buffers and smaller orchestrator granularity

* fix duplicates in filesystem reader

* make small batch granularity toggleable to not break single run behavior

* add comment about temperature

* fix reset staleness

* fix: cc is way too defensive and didnt understand what we meant with needing full batches in small_batch_granularity=False case

* missing samples increment

* guard infinite loop in select samples

* remove the tests because the previous logic didnt make sense so theyre probably super stale and confusing

* fix: check every run in full batch case

* do popleft

* add create run data hook

* just prealloc state cuz life is easier

* set small granularity packing on the multi run test

* remove debug prints

* have very descriptive name for pack flag

* the doc isnt particularly helpful

* cover overfull case

* split out single run packer

* remove packer arg

* missing step arg

* pop out the oversized batch

* take out tokens collected if skip

* transport config

* move packing reset hook to deletion
2026-01-14 19:43:36 -08:00
baf62617aa Step check runtime context (#1587)
* refactor(eval): move checkpoint step validation to runtime

Keep the same stable-checkpoint step validation logic, but run it at eval startup instead of during config parsing.

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

* chore(eval): remove runtime step validation comment

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

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: sami <sami@primeintellect.ai>
2026-01-14 19:02:42 -08:00
bceb0ccebf Logging tmux script panes (#1590)
* docs: simplify tmux logging section

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

* docs: trim tmux logging usage snippet

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

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: sami <sami@primeintellect.ai>
2026-01-14 18:24:09 -08:00
rasdaniandGitHub 6d3af788ac fix skipped eval env log (#1591)
* fix: return values

* changelog
2026-01-15 01:06:47 +01:00
manveerandGitHub a03d81f14f Fix bug causing evals to not get uploaded for hosted RL (#1582)
* Fix bug causing evals to not get uploaded for hosted RL

* Simplify approach

* Add detailed comment
2026-01-14 15:46:39 -08:00
4ff009d2ec update docs for logging (#1588)
Co-authored-by: sami jaghouar <sami@primeintellect.ai>
2026-01-14 14:07:12 -08:00
0403f1271a bump verifier main (#1572)
Co-authored-by: sami jaghouar <sami@primeintellect.ai>
2026-01-14 13:54:23 -08:00
rasdaniandGitHub 33101f260c skip failed eval envs with warning (#1586) 2026-01-14 13:54:01 -08:00
eb8a154f11 Eval script checkpoint failures (#1585)
* fix: keep eval running on checkpoint failures

Adds `continue_on_ckpt_error` so a single bad checkpoint won't abort multi-checkpoint evals. In watcher mode, existing stable checkpoints are skipped (per docs) and failed new checkpoints remain pending for retry.

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

* chore: sort imports in eval checkpoint test

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

* chore: satisfy ruff import ordering in eval test

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

* chore: apply ruff import ordering fix

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

* fix: avoid global sys.modules stubs in eval test

Use anyio marker and local monkeypatching so this test doesn't break collection for other unit tests.

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

* refactor: always continue on checkpoint eval failures

Remove the config/test and make checkpoint eval best-effort by default: per-checkpoint exceptions are logged and evaluation continues. Watcher mode keeps failed checkpoints pending for retry.

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

* fix: keep watcher evaluating existing checkpoints

Restore prior watcher behavior: evaluate all stable checkpoints first, then watch for new ones. Checkpoint failures are logged and skipped without aborting the whole eval process.

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

* refactor: inline checkpoint try/except in eval

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

* Revert "refactor: inline checkpoint try/except in eval"

This reverts commit 4b6483786bd39889676c2226693229ae59a4e63a.

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: sami <sami@primeintellect.ai>
2026-01-14 13:09:14 -08:00
rasdaniandGitHub 518fa49811 fix: wait for checkpoint completion in eval watcher (#1584) 2026-01-14 15:58:03 +01:00
85a9dc0e71 add watcher (#1581)
* wip add watcher

* docs: add changelog entry for eval.watcher

Document the new eval.watcher config flag per config-change review rules.

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

---------

Co-authored-by: sami jaghouar <sami@primeintellect.ai>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
2026-01-13 18:20:49 -08:00
Jackmin801andGitHub dddc0ddfb7 add fa3 to deps (#1580)
* add fa3 to deps

* pin prebuilt wheel instead
2026-01-13 15:52:23 -08:00
faresobeidandGitHub 05456490a4 fix opd (#1577)
* fix opd

* oops
2026-01-13 20:02:29 +00:00
3436f42a4a add env worker logging (#1561)
* add env worker logging

* reset logger before env logger

* redirect verifiers logger to file

* Add CHANGELOG entry for orchestrator.env.log configuration

Documents the new EnvLogConfig class and log field added to EnvConfig,
which provides logging configuration for environment workers.

* Fix worker crash when logging disabled

When logging is disabled (default), reset_logger() sets _LOGGER to None
but setup_logger() was not called. This caused EventLoopLagMonitor to
crash with RuntimeError when calling get_logger().

Fix: Always set up a logger in worker processes. When logging is disabled,
use CRITICAL level which produces no output (critical logging is disabled
in setup_logger).

* fix

* Add formatter to verifiers logger FileHandler

The FileHandler added for the verifiers logger was missing a Formatter,
causing log messages to be written as raw text without timestamps, log
levels, or logger names. This makes the verifiers logs difficult to
correlate or debug effectively.

Added a Formatter with timestamp (HH:MM:SS) and log level formatting,
matching the format used by the prime-rl logger for consistency.

* Add missing reset_logger() in else branch

On Linux with fork start method, worker subprocesses inherit _LOGGER
from parent. Both branches need reset_logger() before setup_logger()
to avoid RuntimeError("Logger already set").

* Revert "Fix worker crash when logging disabled"

This reverts commit f37ab4be3ce4fe85e15391ecdc3164bfe5b59ee5.

* refactor

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
2026-01-13 11:29:44 -08:00
aab07534ea Trainer nccl broadcast log (#1575)
* Clarify NCCL weight broadcast logging for non-layer weights

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

* Refine debug logging for NCCL weight broadcast.

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

* Remove per-layer NCCL broadcast logging.

Keep only the aggregate broadcast count message to reduce trainer log noise.

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: sami <sami@primeintellect.ai>
2026-01-12 17:29:33 -08:00
samsjaandGitHub 5197c4027e Update README.md (#1573)
Signed-off-by: samsja <55492238+samsja@users.noreply.github.com>
2026-01-12 14:55:15 -08:00
rasdaniandGitHub 7fbf4a02cb Re-raise vf.SandboxError in eval to trigger rollout rescheduling (#1553)
* Re-raise `vf.SandboxError` in eval to trigger rollout rescheduling

* catch `vf.InfraError` instead
2026-01-12 23:18:43 +01:00
ddb9571ef4 Update LoRA layer default alpha from 16.0 to 32.0 (#1571)
Ensures consistency with the config default changed in #1567. The
MultiLoRALinear and MultiLoRAGroupedExperts classes had stale defaults
that should match the orchestrator and trainer configs.

Co-authored-by: Claude <noreply@anthropic.com>
2026-01-12 09:21:21 -08:00
c2f90c8a28 change LoRA alpha default to 32 (#1567)
* change LoRA alpha default to 32

* bugbot fixes

* LR fix

* use alpha=64 in alphabet_sort config

* adjust LR for CI configs

* Apply suggestion from @Jackmin801

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

* lr moved to optim

* check step 9 now that lr is lower

---------

Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Co-authored-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Co-authored-by: Jackmin801 <ongjackm@gmail.com>
2026-01-12 09:12:37 -08:00
Sebastian MüllerandGitHub 1455a8afbc Unique rollout request ids to avoid collisions (#1568)
* Fix rollout request matching by using unique request IDs

* Fix worker pending task tracking after request_id change

* simplify request_id access

* Revert "simplify request_id access"

This reverts commit eb456b87275120b2ba1ad5e000cee74f386d288f.

* Fix pending task typing
2026-01-12 05:51:52 -08:00
88da7cb296 fix: detect dead worker process in collect_responses (#1546)
* fix: detect dead worker process in collect_responses

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

* fix: remove unused import

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

* Add _stopping flag to skip dead worker error during shutdown

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

* Remove unused tests for EnvWorker subprocess management

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

* Fix race condition and pending futures on worker death

* Prevent scheduler from routing to dead workers

* Drain response queue before checking dead worker

* Add WorkerDiedError to propagate through scheduler for K8s restart

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

* Check subprocess return codes directly after loop
2026-01-12 12:58:52 +01:00
Jackmin801andGitHub d70a00f6e8 [fix] orchestrator shouldnt have null batch (#1563)
* orchestrator shouldnt have null batch

* change to zero check so partial is stil allowed
2026-01-09 19:01:39 -08:00
1fa70e83dd feat: set default fused_lm_head_chunk_size to 2048 for RL training (#1544)
* feat: set default fused_lm_head_chunk_size to 2048 for RL training

Auto-configures model.fused_lm_head_chunk_size to 2048 for RL training
when not explicitly set. SFT training continues to use None (no chunking)
as it doesn't support chunked loss yet.

* docs: update fused_lm_head_chunk_size description and changelog

Update the field description to mention RL training auto-sets to 2048.
Add changelog entry for the default behavior change.

* Fix: RL training auto-sets fused_lm_head_chunk_size except for liger_kernel

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

* Refactor check_number_in_range to improve step searching

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

---------

Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
2026-01-09 12:55:43 -08:00
JannikStandGitHub 355e742a69 Add optional Prometheus metrics server for trainer (#1547)
* Add optional Prometheus metrics server for trainer observability

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

* Update lockfile for prometheus_client optional dep

* Add changelog entry for metrics_server

* Convert tests to function style

* Clean up Prometheus metrics naming and add mismatch_kl

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

* Add per-run/LoRA metrics to Prometheus server

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

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

* Add /health endpoint for K8s liveness probes

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

* Use heartbeat instead of step-age for health checks

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

* Add optional on_wait callback to sync_wait_for_path

* Revert unused on_wait callback

* Simplify /health to always return 200
2026-01-09 19:59:29 +01:00
Jackmin801andGitHub 16e747c25e set multinear linear cumsum dtype to int32 (#1557) 2026-01-07 21:34:24 -08:00
Jackmin801andGitHub e75677fcbd [Feat] multi run optim args (#1555)
* orchestrator config is ok and component integrations look satisfactory

* rename lora_name to lora.name in orchestrator

* fix in rl.py

* multilora independent scaling factors

* train.py changes

* changes to runs

* update tomls for lora.name

* set the default lora rank to trainers

* set lora scaling dtype to bf16

* missed lora_name -> lora.name

* allow run to reset the lora globals

* damn these configs got hands

* i feel like i might have made my life hard for no reason. ah well, im lazy to think of somethin better rn

* set higher default lr on orch side

* fix configs for non-master ranks
2026-01-07 18:50:40 -08:00
a24ec986b3 Remove PR template (#1550)
With agents now drafting PRs and auto-generating descriptions, the
template with placeholder text is no longer needed.

Co-authored-by: Claude <noreply@anthropic.com>
2026-01-07 01:39:50 -08:00
kalomazeandGitHub ede6b62e69 feat: Add reward field to TrainingSample (#1551)
Store raw reward alongside advantage in rollouts for inspection.
Backward compatible with existing rollout files.
2026-01-06 21:07:12 -08:00
d564195cac [feat] Enable loss chunking for non-custom HuggingFace models (#1545)
* [feat] Enable loss chunking for non-custom HuggingFace models

Add support for chunked loss computation (via FusedOutputLinear) for any
HuggingFace CausalLM model, not just custom PrimeRL implementations.

Changes:
- Add wrap_lm_head_for_hf_model() function in model.py that:
  - Wraps the lm_head with FusedOutputLinear or VanillaOutputLinear
  - Overrides the model's forward method to accept labels and temperature
  - Returns PrimeLmOutput with logprobs/entropy for chunked mode
- Update setup_model() to call wrap_lm_head_for_hf_model for non-PrimeRL models
- Remove config validator restriction that limited fused_lm_head_chunk_size
  to custom/auto implementations
- Add tests for HF model wrapping with both vanilla and fused modes

* change PrimeLmOutput to TypedDict so that it is pytree node by default

Co-authored-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>

* change all references to output for dict

* guard against unconventional model being used

* dont be so defensive in tests with model output

* guard against lm heads with bias

* move lm head injection logic into lm_head.py and unify injection path for custom and hf impl

* update inject in tests

* fix forward signature for custom impls

* cover input embeds case

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
2026-01-06 18:56:06 -08:00
rasdaniandGitHub be0e3d1313 fix: resolve all checkpoints for proper cleanup on resume and cancelled rollout metric (#1537)
* fix: resolve all checkpoints for proper cleanup on resume

* delete dead code

* fix `resume_step`

* log cancelled rollouts to wandb
2026-01-06 02:21:55 +01:00
f870bc91df [feat] moe lora (#1526)
* plumbing to get it to be loaded

* first draft without tenant splitting

* correct fqns

* cleanup multilora moe impl

* fix: param counting

* fix excessive vram usage due to views

* fix perf lora adapter param counting

* make packer only pack global mbs rows with similar run_idx

* add comment because this packing is kinda weird

* fix: set offset correctly for multiloramoe

* idk if th vibe coding has more typos or me

* support lora dropout

* add experts to default lora targets

* remove outdated tests

* feat: Add LoRA dropout to MultiLoRAGroupedExperts

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

* cursor nits

* forgot the changelog lol

* Update CHANGELOG with recent changes and fixes

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

---------

Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Johannes Hagemann <johannes@primeintellect.ai>
2026-01-05 13:21:43 -08:00
Matej SirovatkaandGitHub 5ad6f62fc2 Fused LM Head implementation (#1525)
* Something

* poc

* Fix: proper logits in sft

* Feat: clean up the surface

* Fix: remove unused arg

* Fix: CP-safe label shift + unify custom forwards

* feat: cleanup

* Feat: more cleanup

* Feat: even more cleanup

* fix

* Feat: final

* cursor unscrew

* fix tests

* more fixes

* Shift labels instead of inputs

* Feat: fix logit shifting

* Fix: sft crash

* Tiny fix

* Shift entropy as well

* Some minor cleanup

* Add to afmoe

* Fix afmoe tests

* Final hopefully

* FINAL

---------

Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
2026-01-05 12:31:50 -08:00
2cc5c550b7 fix: enable grouped_mm on Blackwell cards (#1536)
* fix: enable grouped_mm on blackwell

* fix: disable grouped_mm in unit tests for MoE models other than AFMoE

* use_grouped_mm should default to True

---------

Co-authored-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
2026-01-04 18:45:22 -08:00
Johannes HagemannandGitHub 840cd87495 fix: add step param to Monitor.log() interface (#1538) 2026-01-03 07:47:39 +01:00
fba2185ed0 refactor online eval (#1518)
* refactor online eval

* fix eval

* fix eval

---------

Co-authored-by: sami jaghouar <sami@primeintellect.ai>
2026-01-02 12:17:10 +01:00
samsjaandGitHub 3fea505e9d Update README.md (#1533)
Signed-off-by: samsja <55492238+samsja@users.noreply.github.com>
2026-01-02 12:06:15 +01:00
4706ea0c27 Sami/fix nccl handshake (#1531)
* Revert "Revert "Inference readiness handshake (#1506)" (#1528)"

This reverts commit d85027f7f1.

* fix nccl ready

---------

Co-authored-by: sami jaghouar <sami@primeintellect.ai>
2026-01-02 11:16:13 +01:00
AutumnAureliumandGitHub f731eb9d07 feat: Add AFMoE support (#1515)
* basic slow afmoe setup

* add flex attention

* avoid compilation error on flex-attn

* super rough fix for swa and sequence packing

* massively simplify impl

* remove a bunch of dead/unused code and clean up

* un-correct unrelated bug for later fix

* remove debug config file accidentally left in

* remove redundant extra imports

* simplify attention impl

* revert comment

* remove flex_attn for now

* fix ruff lints

* do not put attn in separate file

* satisfy ruff
2026-01-02 10:21:55 +01:00
8b2ef0daa6 fix wandb (#1529)
Signed-off-by: samsja <55492238+samsja@users.noreply.github.com>
Co-authored-by: sami jaghouar <sami@primeintellect.ai>
2026-01-02 10:11:25 +01:00
b750db03c8 Revert "take out step in wandb monitor (#1516)" (#1530)
This reverts commit 895e7d6901.

Co-authored-by: sami jaghouar <sami@primeintellect.ai>
2026-01-01 10:19:21 +01:00
d621e8889d Add retry logic to load_lora_adapter for NFS delays (#1520)
* Add retry logic to load_lora_adapter for NFS delays

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

* Add unit tests for load_lora_adapter retry logic

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

* Refactor tests to pytest function style (no classes)

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

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

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: ongjackm <ongjackm@gmail.com>
2026-01-01 01:09:32 -08:00
d85027f7f1 Revert "Inference readiness handshake (#1506)" (#1528)
This reverts commit 76cc87ec59.

Co-authored-by: sami jaghouar <sami@primeintellect.ai>
2026-01-01 09:10:32 +01:00
e3dbf2ad86 feat: Add keep_interval to checkpointing config (#1521)
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: sami <sami@primeintellect.ai>
2025-12-31 16:00:46 +01:00
0bfb317c02 docs: add changelog entry for ckpt.keep_last and ckpt.keep_interval (#1522)
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
2025-12-31 15:51:17 +01:00
faresobeidandGitHub 1a5841b060 On policy distillation (#1458)
* on-policy-distill

* some more fixes

* some more fixes

* simplify loss

* fixes

* fix tests

* fix tests again

* fix changelog

* refactor

* use score rollouts

* fix ruff pls

* fix ruff and simplify temp

* fix ruff plssss

* Revert "fix ruff plssss"

This reverts commit ebe4fb1cfa33ab28643741cd4f904bf577728e9c.

* pls

* fixes

* fix kl loss

* fix tests

* fix

* fix

* remove reference model

* fix tests

* add logging and comments

* change logic

* setup teacher inference automatically

* fix

* cleanups and fixes

* fix

* fix changelog

* make so we can use an existing teacher inference server

* make teacher logprobs None when no teacher

* fixes

* fix

* fix

* fix

* add docs

---------

Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
2025-12-31 16:23:14 +02:00
Jackmin801andGitHub 895e7d6901 take out step in wandb monitor (#1516) 2025-12-31 10:22:18 +01:00
76cc87ec59 Inference readiness handshake (#1506)
* feat: Add NCCL broadcast support for weight updates

This commit introduces NCCL broadcast as a new method for updating weights. It includes modifications to the orchestrator, scheduler, and NCCL broadcast implementation to handle the synchronization required for NCCL communication. The `update_weights` utility function is updated to create a `NCCL_READY` marker file when NCCL broadcast is enabled, signaling to the trainer that inference workers are ready to receive weights.

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

* Refactor: Remove unused is_nccl_broadcast flag

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

* Remove NCCL ready marker cleanup from broadcast

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

* feat: Add timeout to sync_wait_for_path and wait_for_path

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

* Checkpoint before follow-up message

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

* remove to

* remove upus ty

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: sami <sami@primeintellect.ai>
2025-12-31 09:46:27 +01:00
91 changed files with 5696 additions and 607 deletions
-10
View File
@@ -1,10 +0,0 @@
<!-- Provide a brief description of the changes in this PR -->
I was too lazy to explain my changes, decreasing my chances of this ever getting merged.
---
<!-- Link the GitHub and Linear issue (if external, delete the Linear issue link) -->
**GitHub Issue**: [Issue ID]
**Linear Issue**: Resolves [Issue ID]
+17
View File
@@ -8,14 +8,31 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
- **`orchestrator.env_mix`**: Deprecated in favor of `orchestrator.buffer.env_ratios` (#1450, 2025-12-18)
- **`orchestrator.buffer.hash_keys`**: Added hash keys configuration for buffer checkpointing (#1450, 2025-12-18)
- **`orchestrator.buffer.env_ratios`**: Added environment ratio configuration for buffer sampling (#1450, 2025-12-18)
- **`orchestrator.buffer.skip_verification`**: Added configuration to skip verification of rollouts using the environment's rubric. If True, rewards are always set to 0. Cannot be used with `online_difficulty_filtering=True` or when `easy_threshold`/`hard_threshold` are set (default: False)
- **`orchestrator.ckpt.buffer_path`**: Deprecated (#1450, 2025-12-18)
- **`orchestrator.buffer.easy_fraction`** and **`orchestrator.buffer.hard_fraction`**: Easy and hard fraction now defines the fraction of easy and hard problems to convert to normal when resuming, whereas previously it was the ratio of easy/ hard samples to sample per step (#1450, 2025-12-18)
- **`orchestrator.teacher_model`**: Added teacher model configuration for computing teacher logprobs (e.g. for distillation). Supports `TeacherModelConfig` (custom model) or `None` (disabled). Renamed from `reference_model` (2025-12-20)
- **`seq_len`**: Added root-level `seq_len` config that sets both `trainer.model.seq_len` and `orchestrator.seq_len`. Added validation that `trainer.model.seq_len >= orchestrator.seq_len` (2025-12-18)
- **`trainer.loss.sequence_mask_ratio_low`** and **`trainer.loss.sequence_mask_ratio_high`**: Renamed to `trainer.loss.sequence_mask_low` and `trainer.loss.sequence_mask_high` (2025-12-19)
- **`trainer.loss.token_mask_high`** and **`trainer.loss.token_mask_low`**: Added token-level importance ratio masking thresholds (2025-12-19)
- **`trainer.loss.sequence_clip_high`**: Added sequence-level importance ratio clipping threshold (2025-12-19)
- **`trainer.loss.geo_mask_high`** and **`trainer.loss.geo_mask_low`**: Added geometric importance ratio masking thresholds (2025-12-19)
- **`trainer.loss.adv_tau`**: Added tau parameter for advantages (default: 1.0)
- **`trainer.loss.teacher_tau`**: Added tau parameter for teacher logprobs (default: 0.0). Renamed from `ref_tau`
- **`teacher_gpu_ids`**: Added GPU IDs for teacher inference server. When set, automatically starts a teacher inference server and configures `orchestrator.teacher_model`
- **`teacher_inference`**: Added optional teacher inference config. Defaults to copying from `inference` config with port 8001
- **`{orchestrator,trainer}.transport.zmq`**: Added ZMQ transport for training batches and micro batches (#1446, 2025-12-22)
- **`model.impl`**: Changed default from `hf` to `auto`. With `auto`, the implementation automatically selects `custom` if supported for the model, otherwise falls back to `hf` (#1488, 2025-12-27)
- **`orchestrator.eval.skip_eval_on_resume`**: Added flag (default `True`) to skip the first potentially redundant online eval immediately after resuming from a checkpoint (#1491, 2025-12-27)
- **`trainer.weight_broadcast.adapter_only`**: Removed. Adapter-only behavior is now automatically derived from the presence of LoRA configuration (2025-12-27)
- **`ckpt.keep`**: Renamed to `ckpt.keep_last`. Added `ckpt.keep_interval` to keep checkpoints at every N steps permanently (2025-12-31)
- **`MultiLoRAMoE`**: QwenMoE now supports training expert loras and this is enabled by default in the `target_modules`. (2026-01-01)
- **`model.fused_lm_head_chunk_size`**: Added chunk size configuration for fused LM head to enable memory-efficient chunked logprob computation. When set, splits vocabulary into chunks to avoid materializing full [N, V] logit tensor (default: None) (#1525, 2026-01-03)
- **`model.fused_lm_head_chunk_size`**: RL training now auto-sets this to 2048 if not specified (except when `impl='liger_kernel'`). SFT training continues to use None (2026-01-05)
- **`trainer.metrics_server`**: Added optional Prometheus metrics server for trainer observability. Exposes `/metrics` endpoint with step, loss, throughput, grad_norm, etc. Disabled by default (default: None) (#1547, 2026-01-06)
- **`model.lora.alpha`**: Changed default from 16.0 to 32.0 (2026-01-10)
- **`orchestrator.env.log`**: Added logging configuration for environment workers. If set, enables logging with `level` (str, default: "warn") and `vf_level` (str, default: "warn") fields. If None (default), logging is disabled (#1561, 2026-01-13)
- **`eval.watcher`**: Added flag (default `False`) to watch `weights_dir` for newly-created stable checkpoints and evaluate them as they appear (2026-01-14)
- **`orchestrator.log.env_worker_logs`**: Added flag (default `False`) to write env worker logs to `logs/env_workers/{env_name}.log` (2026-01-15)
- **`orchestrator.env.log`**: Removed. Use `orchestrator.log` for env worker logging instead (2026-01-15)
- **`orchestrator.eval.retry.reraise`**: Changed default from `True` to `False`. When `False`, raises `tenacity.RetryError` after retries are exhausted instead of the original exception, allowing failed eval environments to be skipped with a warning (#1586, 2026-01-14)
+2
View File
@@ -62,6 +62,8 @@ RUN apt-get update && apt-get install -y \
net-tools \
curl \
vim \
libibverbs1 \
ibverbs-providers \
&& apt-get clean autoclean \
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
+1 -1
View File
@@ -34,7 +34,7 @@ PRIME-RL is a framework for large-scale asynchronous reinforcement learning. It
1. Integrates natively with [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) environments via the [Environments Hub](https://app.primeintellect.ai/dashboard/environments?ex_sort=most_stars)
2. Supports end-to-end post-training, including SFT and RL training and evals
3. Multi-node deployment with [FSDP2](https://docs.pytorch.org/tutorials/intermediate/FSDP_tutorial.html) training and [vLLM](https://github.com/vllm-project/vllm) inference backend
4. Designed for asynchronous training in decentralized settings
4. Designed for asynchronous agentic RL training at scale
5. Hackable, modular and extensible by nature
## Setup
+6 -3
View File
@@ -11,7 +11,7 @@ resume_step = 20
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[trainer.optim]
lr = 1e-4
lr = 5e-5
[trainer.model.lora]
rank = 8
@@ -22,7 +22,9 @@ save_adapter_separately = true
[orchestrator]
batch_size = 128
rollouts_per_example = 16
lora_name = "r8-1e-4"
[orchestrator.model.lora]
name = "r8-1e-4"
[orchestrator.sampling]
max_tokens = 128
@@ -31,4 +33,5 @@ max_tokens = 128
id = "reverse-text"
[inference]
enable_lora = true
enable_lora = true
gpu_memory_utilization = 0.7
+6 -3
View File
@@ -10,7 +10,7 @@ seq_len = 2048
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[trainer.optim]
lr = 1e-4
lr = 5e-5
[trainer.model.lora]
rank = 8
@@ -21,7 +21,9 @@ save_adapter_separately = true
[orchestrator]
batch_size = 128
rollouts_per_example = 16
lora_name = "r8-1e-4"
[orchestrator.model.lora]
name = "r8-1e-4"
[orchestrator.sampling]
max_tokens = 128
@@ -30,4 +32,5 @@ max_tokens = 128
id = "reverse-text"
[inference]
enable_lora = true
enable_lora = true
gpu_memory_utilization = 0.7
@@ -1,5 +1,5 @@
# Orchestrator config for multi-run RL integration test
# lora_name and output_dir are set via CLI
# model.lora.name and output_dir are set via CLI
batch_size = 128
rollouts_per_example = 16
seq_len = 2048
@@ -8,6 +8,9 @@ max_steps = 20
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[optim]
lr = 2e-5
[sampling]
max_tokens = 128
@@ -1,5 +1,5 @@
# Trainer config for multi-run RL integration test
max_steps = 1000
max_steps = 100000
max_concurrent_runs = 2
max_async_level = 5
@@ -8,10 +8,3 @@ name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[model.lora]
rank = 8
[optim]
lr = 1e-4
[weight_broadcast]
adapter_only = true
-1
View File
@@ -17,7 +17,6 @@ weight_decay = 0.0
[trainer.model.lora]
rank = 8
alpha = 32
dropout = 0.0
target_modules = [
"q_proj",
+1 -1
View File
@@ -8,7 +8,7 @@ Checkpointing is non-standard due to trainer/orchestrator separation and natural
The default checkpoint directory is `checkpoints` and each checkpoint step will live in a step subdirectory, i.e. `checkpoints/step_{step}`.
Checkpointing is configured with the config key `--ckpt`. One can specify the interval (`--ckpt.interval`), whether to save checkpoints asynchronoously (`--ckpt.save-async`), and how many recent step checkpoints to keep on disk (`--ckpt.keep`). By default, we do not checkpoint to save disk space.
Checkpointing is configured with the config key `--ckpt`. One can specify the interval (`--ckpt.interval`), whether to save checkpoints asynchronoously (`--ckpt.save-async`), how many recent step checkpoints to keep on disk (`--ckpt.keep-last`), and keep checkpoints at every N steps permanently (`--ckpt.keep-interval`). By default, we do not checkpoint to save disk space.
## SFT
+81 -59
View File
@@ -1,14 +1,88 @@
# Logging
## Loguru
prime-rl uses [loguru](https://loguru.readthedocs.io/en/stable/) for logging with a global logger pattern. Logs are written to both console and files under `{output_dir}/logs/`. For RL training, we recommend streaming file logs into tmux panes (as set up by `tmux.sh`).
We log to console and files using `loguru` using a global logger instance. Each entrypoint should call `setup_logger` *exactly once* at the beginning of execution. Afterwards, all components can log using the global logger instance. For more details on loguru, see the [documentation](https://loguru.readthedocs.io/en/stable/). All logs are written into `{output_dir}/logs` and for RL training we recommend viewing logs by streaming the file logs into tmux panes, as set up by the `tmux.sh` script.
## tmux helper (`scripts/tmux.sh`)
`scripts/tmux.sh` sets up a tmux session for RL runs with **three panes (one per subprocess)**:
- **Trainer**: run `uv run rl ...` here
- **Orchestrator**: follows `{output_dir}/logs/orchestrator.stdout`
- **Inference**: follows `{output_dir}/logs/inference.stdout`
## Logger Architecture
### `setup_logger` and `get_logger`
We use a **singleton pattern** with a module-level global logger instance (`_LOGGER`).
```python
from prime_rl.utils.logger import setup_logger, get_logger
# At entrypoint - call ONCE
logger = setup_logger("info", log_file=Path("output/logs/my.log"))
# Anywhere else in codebase
logger = get_logger()
logger.info("Hello world")
```
**How it works:**
1. **`setup_logger(log_level, log_file)`** - Initializes the global logger exactly once:
- Creates an isolated loguru `Logger` instance (not the default `loguru.logger`) to prevent third-party code from hijacking our logs
- Adds a stdout handler with colorized output
- Optionally adds a file handler (deletes existing file first)
- Raises `RuntimeError` if called twice
2. **`get_logger()`** - Returns the global logger instance:
- Raises `RuntimeError` if `setup_logger` hasn't been called yet
- Safe to call from any module after initialization
3. **`reset_logger()`** - Resets the global logger to `None`:
- Used in subprocesses that inherit parent state (e.g., env workers)
- Used in tests between test cases
## RL Log File Structure
For RL training, logs are organized by component:
| Component | Log Path | Description |
|-----------|----------|-------------|
| **RL (parent)** | `logs/rl.log` | Main process that spawns subprocesses |
| **Inference** | `logs/inference.stdout` | vLLM inference server stdout/stderr |
| **Orchestrator** | `logs/orchestrator.log` | Rollout generation, buffer, scheduling |
| **Trainer** | `logs/trainer/rank_{N}.log` | Training process (one file per GPU rank) |
| **Env Workers** | `logs/env_workers/{env_name}/worker_{N}.log` | Per-environment worker logs (optional) |
## Per-Environment Worker Logging
Environment workers run in **separate subprocesses** to isolate event loop lag. Worker logging is controlled at the orchestrator level via `orchestrator.log`:
```toml
[orchestrator.log]
level = "debug" # Log level for prime-rl logger
vf_level = "info" # Log level for verifiers library
env_worker_logs = true # Enable file logging for env workers
```
When `env_worker_logs = true`, logs are written to:
```
output_dir/
└── logs/
└── env_workers/
├── {env_name_1}.log
├── {env_name_2}.log
└── ...
```
All workers for an environment share the same log file.
Set `env_worker_logs = false` to disable worker file logging (workers inherit parent process logging).
## Torchrun
For multi-node training, we use `torchrun` to set up distributed training. Because `torchrun` is SPMD, all ranks are logging to console and file at the same time. To only view the logs from the master rank, you can use the `--local-ranks-filter` flag.
For example, to only view the logs from the master rank when training on a full node
For multi-node training with `torchrun`, all ranks log simultaneously. To filter to master rank only:
```bash
uv run torchrun \
@@ -17,7 +91,7 @@ uv run torchrun \
...
```
In addition to the loguru file logs you can also use the `--log-dir` and `--redirects` and `--tee` flags to redirect the console logs to files.
You can also use torchrun's native log redirection:
```bash
uv run torchrun \
@@ -29,57 +103,5 @@ uv run torchrun \
...
```
This will redirect the console logs to `outputs/torchrun/{rdzv_id}/attempt_0/{rank}/{stdout,stderr}.log`.
This writes to `outputs/torchrun/{rdzv_id}/attempt_0/{rank}/{stdout,stderr}.log`.
## W&B
For most runs we recommend logging to [W&B](https://wandb.ai). Before enabling W&B, make sure that you have an account and are logged in.
```bash
uv run wandb login
# Or set `export WANDB_API_KEY=...`
```
### SFT
Logging to W&B is disabled by default. Enable the default configuration with `--wandb`
```bash
uv run sft ... --wandb
```
This will log to the `prime-rl` project with a random run name. You can specify which project and name to log to
```bash
uv run sft ... --wandb.project my-project --wandb.name my-run
```
The same settings also work for multi-node training with `torchrun`. Note, that we only log global metrics from the master rank (e.g. the all-reduced loss)
```bash
uv run torchrun --nproc-per-node 8 ... --wandb
```
### RL
For RL training, both the trainer and orchestrator log to W&B as separate runs. Again, logging to W&B is disabled by default. Enable the default configuration with `--wandb`
```bash
uv run rl ... --wandb
```
This will log to the `prime-rl` project with a random run name. The trainer run is suffixed with `-trainer` and the orchestrator run is suffixed with `-orchestrator`. You can specify which project and name to log to using the same flags as for SFT.
```bash
uv run rl ... --wandb.project my-project --wandb.name my-run
```
For the RL trainer, we support logging samples (e.g. prompt, completion, reward, advantage for selected rollouts) and distributions (e.g. reward, advantage, entropy distributions) as W&B tables using the `wandb.log-extras` subconfig. If W&B is setup, this is enabled by default and will log for the RL trainer and orchestrator every 10 steps.
You can configure this on the trainer and orchestrator separately. For example, to only log samples on the orchestrator every 50 steps, but not distribution on either
```bash
uv run rl ... \
--no-trainer.wandb.log-extras.distributions \
--orchestrator.wandb.log-extras.interval 50
```
+55
View File
@@ -0,0 +1,55 @@
# Metrics
## W&B
For most runs we recommend logging metrics to [W&B](https://wandb.ai). Before enabling W&B, make sure that you have an account and are logged in.
```bash
uv run wandb login
# Or set `export WANDB_API_KEY=...`
```
### SFT
Logging to W&B is disabled by default. Enable the default configuration with `--wandb`
```bash
uv run sft ... --wandb
```
This will log to the `prime-rl` project with a random run name. You can specify which project and name to log to
```bash
uv run sft ... --wandb.project my-project --wandb.name my-run
```
The same settings also work for multi-node training with `torchrun`. Note, that we only log global metrics from the master rank (e.g. the all-reduced loss)
```bash
uv run torchrun --nproc-per-node 8 ... --wandb
```
### RL
For RL training, both the trainer and orchestrator log to W&B as separate runs. Again, logging to W&B is disabled by default. Enable the default configuration with `--wandb`
```bash
uv run rl ... --wandb
```
This will log to the `prime-rl` project with a random run name. The trainer run is suffixed with `-trainer` and the orchestrator run is suffixed with `-orchestrator`. You can specify which project and name to log to using the same flags as for SFT.
```bash
uv run rl ... --wandb.project my-project --wandb.name my-run
```
For the RL trainer, we support logging samples (e.g. prompt, completion, reward, advantage for selected rollouts) and distributions (e.g. reward, advantage, entropy distributions) as W&B tables using the `wandb.log-extras` subconfig. If W&B is setup, this is enabled by default and will log for the RL trainer and orchestrator every 10 steps.
You can configure this on the trainer and orchestrator separately. For example, to only log samples on the orchestrator every 50 steps, but not distribution on either
```bash
uv run rl ... \
--no-trainer.wandb.log-extras.distributions \
--orchestrator.wandb.log-extras.interval 50
```
+73
View File
@@ -0,0 +1,73 @@
# On-Policy Distillation
On-policy distillation uses a teacher model to provide dense token-level feedback during RL training. The student generates rollouts, and the teacher's logprobs guide the student to stay close to stronger behavior while still learning from rewards.
For more details, see [On-Policy Distillation](https://thinkingmachines.ai/blog/on-policy-distillation/) by Thinking Machines.
## Quick Start
Add `teacher_gpu_ids` and set `teacher_tau > 0`:
```toml
teacher_gpu_ids = [2, 3]
[trainer.loss]
teacher_tau = 0.5
```
This automatically starts a teacher inference server using the same model as inference. To use a different teacher model:
```toml
teacher_gpu_ids = [2, 3]
[teacher_inference.model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
[trainer.loss]
teacher_tau = 0.5
```
## Using an External Teacher Server
If the teacher is already running elsewhere:
```toml
[trainer.loss]
teacher_tau = 0.5
[orchestrator.teacher_model.client]
base_url = ["http://teacher-server:8000/v1"]
[orchestrator.teacher_model.model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
```
## Pure Distillation (No Verification)
For agentic environments where verification is expensive (code execution, tool use, multi-turn interactions), you can skip verification entirely and use only the teacher signal:
```toml
teacher_gpu_ids = [2, 3]
[trainer.loss]
teacher_tau = 1.0
adv_tau = 0.0 # Disable reward-based learning
[orchestrator.buffer]
skip_verification = true # Skip expensive verification
```
This runs pure on-policy distillation: the student learns to match the teacher without needing any reward signal.
## Parameters
| Parameter | Default | Description |
|-----------|---------|-------------|
| `teacher_gpu_ids` | `None` | GPUs for teacher server. Auto-starts server when set. |
| `trainer.loss.teacher_tau` | `0.0` | Distillation strength. Set `> 0` to enable. |
| `trainer.loss.adv_tau` | `1.0` | Weight for RL advantage signal. Set `0` for pure distillation. |
| `orchestrator.buffer.skip_verification` | `false` | Skip verification. Use with `adv_tau = 0`. |
## Monitoring
The `teacher_kl` metric shows the KL divergence from teacher to student. Lower values mean the student is closer to the teacher.
+3 -2
View File
@@ -17,7 +17,6 @@ weight_decay = 0.0
[trainer.model.lora]
rank = 8
alpha = 32
dropout = 0.0
target_modules = [
"q_proj",
@@ -33,7 +32,9 @@ target_modules = [
batch_size = 512
rollouts_per_example = 16
oversampling_factor = 2.0
lora_name = "qwen3-4b-wiki-search"
[orchestrator.model.lora]
name = "qwen3-4b-wiki-search"
[orchestrator.sampling]
max_tokens = 512
+8 -1
View File
@@ -56,6 +56,12 @@ synthesize = "prime_rl.synthesize.synthesize:main"
flash-attn = [
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.6.8/flash_attn-2.8.3+cu128torch2.9-cp312-cp312-linux_x86_64.whl",
]
flash-attn-3 = [
"flash_attn_3 @ https://github.com/samsja/flash-attn-builds/releases/download/v0.1/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl",
]
metrics = [
"prometheus_client>=0.20.0",
]
[dependency-groups]
dev = [
@@ -74,12 +80,13 @@ prerelease = "allow"
[tool.uv.sources]
torch = { index = "pytorch-cu128" }
reverse-text = { index = "primeintellect" }
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "eb3bae36c93b2f574e13a39da2908609d4ec4b2f" }
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "209774a" }
dion = { git = "https://github.com/samsja/dion.git", rev = "main" }
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
[tool.uv.extra-build-dependencies]
flash-attn = [{ requirement = "torch", match-runtime = true }]
flash-attn-3 = [{ requirement = "torch", match-runtime = true }]
[tool.uv.extra-build-variables]
flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" }
+9 -8
View File
@@ -79,14 +79,15 @@ class OfflineEvalConfig(EvalConfig, BaseSettings):
),
] = None
@model_validator(mode="after")
def validate_steps(self):
if self.steps is not None and self.weights_dir is not None:
ckpt_steps = sorted([int(step_path.name.split("_")[-1]) for step_path in self.weights_dir.glob("step_*")])
for step in self.steps:
if step not in ckpt_steps:
raise ValueError(f"Step {step} not found in weights directory {self.weights_dir}")
return self
watcher: Annotated[
bool,
Field(
description=(
"If True, watch `weights_dir` for newly-created stable checkpoints (folders named `step_{x}` that contain a `STABLE` file) "
"and evaluate them as they appear, instead of immediately iterating over all existing checkpoints."
),
),
] = False
@model_validator(mode="after")
def validate_eval_base(self):
+64 -23
View File
@@ -1,7 +1,5 @@
import asyncio
import verifiers as vf
from prime_rl.eval.config import OfflineEvalConfig
from prime_rl.eval.utils import run_evals
from prime_rl.orchestrator.utils import set_semaphore
@@ -14,7 +12,7 @@ from prime_rl.utils.client import (
setup_evals_client,
update_weights,
)
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.logger import intercept_verifiers_logging, setup_logger
from prime_rl.utils.monitor import setup_monitor
from prime_rl.utils.pydantic_config import parse_argv
from prime_rl.utils.utils import clean_exit, get_env_ids_to_install, get_step_path, install_env
@@ -26,7 +24,7 @@ async def eval(config: OfflineEvalConfig):
logger = setup_logger(
config.log.level, log_file=config.output_dir / "logs" / "eval.log" if config.log.file else None
)
vf.setup_logging(level=config.log.vf_level.upper())
intercept_verifiers_logging(level=config.log.vf_level)
env_names = [env.name or env.id for env in config.env]
logger.info(f"Starting evals for {config.model.name} in environments {', '.join(env_names)}")
@@ -82,31 +80,74 @@ async def eval(config: OfflineEvalConfig):
# If specified, evaluate all checkpoints found in the weights directory
if config.weights_dir is not None:
logger.info(f"Evaluating weight checkpoints in {config.weights_dir}")
ckpt_steps = sorted([int(step_path.name.split("_")[-1]) for step_path in config.weights_dir.glob("step_*")])
logger.info(f"Found {len(ckpt_steps)} weight checkpoints (steps: {', '.join(map(str, ckpt_steps))})")
# Only include checkpoints that have a STABLE file (indicating save completed)
ckpt_steps = sorted(
[
int(step_path.name.split("_")[-1])
for step_path in config.weights_dir.glob("step_*")
if (step_path / "STABLE").exists()
]
)
logger.info(f"Found {len(ckpt_steps)} stable weight checkpoints (steps: {', '.join(map(str, ckpt_steps))})")
if config.steps is not None:
missing_steps = [step for step in config.steps if step not in ckpt_steps]
if missing_steps:
raise ValueError(
f"Step {missing_steps[0]} not found (or not stable) in weights directory {config.weights_dir}"
)
# Filter the steps to evaluate
if config.steps is not None:
ckpt_steps = [step for step in ckpt_steps if step in config.steps]
logger.info(f"Evaluating {len(ckpt_steps)} weight checkpoints (steps: {', '.join(map(str, ckpt_steps))})")
for ckpt_step in ckpt_steps[::-1]:
# Update the weights
logger.info(f"Evaluating model {config.model.name} at checkpoint {ckpt_step}")
await update_weights(admin_clients, get_step_path(config.weights_dir, ckpt_step))
async def _eval_ckpt(ckpt_step: int) -> bool:
try:
logger.info(f"Evaluating model {config.model.name} at checkpoint {ckpt_step}")
await update_weights(admin_clients, get_step_path(config.weights_dir, ckpt_step))
# Run evals on checkpoint
await run_evals(
clients=clients,
eval_config=config,
model_config=config.model,
sampling_config=config.sampling,
evals_client=evals_client,
reasoning_field=config.reasoning_field,
output_dir=config.output_dir,
ckpt_step=ckpt_step,
resume_path=config.resume_path,
)
await run_evals(
clients=clients,
eval_config=config,
model_config=config.model,
sampling_config=config.sampling,
evals_client=evals_client,
reasoning_field=config.reasoning_field,
output_dir=config.output_dir,
ckpt_step=ckpt_step,
resume_path=config.resume_path,
)
return True
except Exception:
logger.exception(f"Checkpoint eval failed (ckpt_step={ckpt_step})")
return False
logger.info(f"Evaluating {len(ckpt_steps)} weight checkpoints (steps: {', '.join(map(str, ckpt_steps))})")
for ckpt_step in ckpt_steps:
await _eval_ckpt(ckpt_step)
if config.watcher:
# Keep watcher behavior consistent with previous versions: after evaluating all currently-stable
# checkpoints, watch for new ones and evaluate them as they appear.
already_evaluated_ckpt_steps = list(ckpt_steps)
while True:
# Only include checkpoints that have a STABLE file (indicating save completed)
all_ckpt_steps = sorted(
[
int(step_path.name.split("_")[-1])
for step_path in config.weights_dir.glob("step_*")
if (step_path / "STABLE").exists()
]
)
new_ckpt_steps = [step for step in all_ckpt_steps if step not in already_evaluated_ckpt_steps]
if len(new_ckpt_steps) > 0:
logger.info(f"New checkpoints to evaluate: {', '.join(map(str, new_ckpt_steps))}")
for ckpt_step in new_ckpt_steps:
await _eval_ckpt(ckpt_step)
already_evaluated_ckpt_steps.append(ckpt_step)
else:
logger.info("No new checkpoints to evaluate, waiting for 10 seconds")
await asyncio.sleep(10)
logger.success("Eval finished!")
+265 -41
View File
@@ -4,6 +4,7 @@ import re
import time
from copy import deepcopy
from itertools import cycle
from multiprocessing import Process
from pathlib import Path
from typing import Any
@@ -13,7 +14,7 @@ import verifiers as vf
from huggingface_hub import whoami
from openai import AsyncOpenAI, BadRequestError
from prime_evals import AsyncEvalsClient
from tenacity import RetryCallState, retry, stop_after_attempt, wait_exponential
from tenacity import RetryCallState, RetryError, retry, stop_after_attempt, wait_exponential
from tqdm.asyncio import tqdm
from verifiers import load_environment
from verifiers.envs.environment import get_results_path
@@ -21,8 +22,11 @@ from verifiers.utils.eval_utils import get_hf_hub_dataset_name, make_dataset, sa
from prime_rl.eval.config import OfflineEvalConfig
from prime_rl.orchestrator.config import EvalConfig, EvalSamplingConfig, EvalSaveConfig, ModelConfig, RetryConfig
from prime_rl.orchestrator.utils import set_semaphore
from prime_rl.synthesize.utils import merge_reasoning_content, save_result
from prime_rl.utils.logger import get_logger
from prime_rl.utils.client import setup_clients, setup_evals_client
from prime_rl.utils.config import ClientConfig
from prime_rl.utils.logger import get_logger, intercept_verifiers_logging, reset_logger, setup_logger
from prime_rl.utils.monitor import get_monitor
from prime_rl.utils.utils import capitalize, get_eval_dir, get_step_path
from prime_rl.utils.vf import (
@@ -51,12 +55,16 @@ def read_existing_results(results_file: Path) -> pd.DataFrame:
with open(results_file, "r") as f:
for line in f:
result = json.loads(line)
info = result.get("info", {})
prime_info = info.get("prime_rl", {})
rollout_status = prime_info.get("rollout_status", "ok")
results.append(
{
"example_id": result["example_id"],
"reward": result["reward"],
"completion_len": result["completion_len"],
"is_truncated": result["is_truncated"],
"rollout_status": rollout_status,
}
)
@@ -191,12 +199,59 @@ def parse_and_calculate_max_tokens(error_message: str) -> int | None:
return None
def _make_no_response_state(
*,
example: dict,
rollout_idx: int,
env_name_or_id: str,
error: Exception,
) -> dict:
"""Create a vf.State-like dict for a rollout that never produced a model response."""
# NOTE: Keep completion/trajectory empty so merge_reasoning_content() doesn't assert.
return {
"example_id": example.get("example_id"),
"prompt": example.get("prompt"),
"completion": [],
"task": example.get("task"),
"reward": None,
"timing": {"generation_ms": 0.0, "scoring_ms": 0.0, "total_ms": 0.0},
"info": {
"prime_rl": {
"rollout_status": "no_response",
"env": env_name_or_id,
"rollout_idx": rollout_idx,
"error": repr(error),
}
},
"answer": example.get("answer", ""),
"metrics": {},
"trajectory": [],
"oai_tools": [],
}
def _is_valid_reward(reward: Any) -> bool:
if reward is None:
return False
if isinstance(reward, float) and np.isnan(reward):
return False
return isinstance(reward, (int, float))
def _format_avg_reward(rewards: list) -> str:
valid = [r for r in rewards if _is_valid_reward(r)]
if not valid:
return "N/A"
return f"{(sum(valid) / len(valid)):.4f}"
async def generate_and_save_rollout(
client: AsyncOpenAI,
env: vf.Environment,
model_name: str,
example: dict,
rollout_idx: int,
env_name_or_id: str,
sampling_args: dict,
save_file: Path | None,
reasoning_field: str,
@@ -227,7 +282,11 @@ async def generate_and_save_rollout(
"""Asynchronously generate and score a single rollout."""
logger = get_logger()
try:
return await generate_rollout(client, env, model_name, example, sampling_args)
state = await generate_rollout(client, env, model_name, example, sampling_args)
# Re-raise infrastructure errors to trigger retry
if state.get("error") and isinstance(state["error"], vf.InfraError):
raise state["error"]
return state
except BadRequestError as e:
# Check if this is a context length error and retry with adjusted max_tokens
error_message = str(e)
@@ -236,30 +295,49 @@ async def generate_and_save_rollout(
if new_max_tokens is not None:
logger.warning(f"Context length error: reducing max_tokens to {new_max_tokens}.")
sampling_args["max_tokens"] = new_max_tokens
return await generate_rollout(client, env, model_name, example, sampling_args)
state = await generate_rollout(client, env, model_name, example, sampling_args)
if state.get("error") and isinstance(state["error"], vf.InfraError):
raise state["error"]
return state
raise
try:
state = await _generate_rollout(client, env, model_name, example, _sampling_args)
except (RetryError, Exception) as e:
# IMPORTANT: do not raise here (asyncio.gather would cancel all other rollouts).
logger.exception(
f"Rollout generation failed after retries; recording no_response "
f"(env={env_name_or_id}, example_id={example.get('example_id')}, rollout_idx={rollout_idx}): {repr(e)}"
)
failed_state = _make_no_response_state(
example=example, rollout_idx=rollout_idx, env_name_or_id=env_name_or_id, error=e
)
# Save with rollout_idx if streaming saves enabled
# Save placeholder row if streaming saves enabled (supports resume + complete accounting).
if save_file is not None:
result_dict = await asyncio.to_thread(make_result, state, reasoning_field, rollout_idx)
result_dict = await asyncio.to_thread(make_result, failed_state, reasoning_field, rollout_idx)
await save_result(result_dict, save_file)
# Update running average immediately
# Update progress + running average without biasing downward.
async with rewards_lock:
rewards_accumulator.append(state["reward"])
avg_reward = sum(rewards_accumulator) / len(rewards_accumulator)
pbar.set_postfix({"Avg Reward": f"{avg_reward:.4f}"})
rewards_accumulator.append(None)
pbar.set_postfix({"Avg Reward": _format_avg_reward(rewards_accumulator)})
pbar.update(1)
return state
except Exception as e:
logger.exception(
f"Error evaluating rollout (example_id={example.get('example_id')}, rollout_idx={rollout_idx}): {repr(e)}"
)
raise
return failed_state # type: ignore[return-value]
# Save with rollout_idx if streaming saves enabled.
if save_file is not None:
result_dict = await asyncio.to_thread(make_result, state, reasoning_field, rollout_idx)
await save_result(result_dict, save_file)
# Update running average immediately.
async with rewards_lock:
rewards_accumulator.append(state["reward"])
pbar.set_postfix({"Avg Reward": _format_avg_reward(rewards_accumulator)})
pbar.update(1)
return state
async def generate_and_save_group(
@@ -268,6 +346,7 @@ async def generate_and_save_group(
model_name: str,
example: dict,
rollouts_per_example: int,
env_name_or_id: str,
sampling_args: dict,
save_file: Path | None,
reasoning_field: str,
@@ -299,7 +378,12 @@ async def generate_and_save_group(
"""Asynchronously generate and score a group of rollouts."""
logger = get_logger()
try:
return await generate_group(client, env, model_name, example, rollouts_per_example, sampling_args)
states = await generate_group(client, env, model_name, example, rollouts_per_example, sampling_args)
# Re-raise infrastructure errors to trigger retry (check all states in group)
for state in states:
if state.get("error") and isinstance(state["error"], vf.InfraError):
raise state["error"]
return states
except BadRequestError as e:
error_message = str(e)
new_max_tokens = parse_and_calculate_max_tokens(error_message)
@@ -307,31 +391,60 @@ async def generate_and_save_group(
if new_max_tokens is not None:
logger.warning(f"Context length error: reducing max_tokens to {new_max_tokens}.")
sampling_args["max_tokens"] = new_max_tokens
return await generate_group(client, env, model_name, example, rollouts_per_example, sampling_args)
states = await generate_group(client, env, model_name, example, rollouts_per_example, sampling_args)
for state in states:
if state.get("error") and isinstance(state["error"], vf.InfraError):
raise state["error"]
return states
raise
try:
states = await _generate_group(client, env, model_name, example, rollouts_per_example, _sampling_args)
except (RetryError, Exception) as e:
# IMPORTANT: do not raise here (asyncio.gather would cancel other groups).
logger.exception(
f"Group generation failed after retries; recording no_response rollouts "
f"(env={env_name_or_id}, example_id={example.get('example_id')}): {repr(e)}"
)
failed_states = [
_make_no_response_state(
example=example, rollout_idx=rollout_idx, env_name_or_id=env_name_or_id, error=e
)
for rollout_idx in range(rollouts_per_example)
]
if save_file is not None:
await asyncio.gather(
*[
make_and_save_result(state, save_file, reasoning_field, rollout_idx)
for rollout_idx, state in enumerate(states)
for rollout_idx, state in enumerate(failed_states)
]
)
# Update running average after group completes
async with rewards_lock:
for state in states:
rewards_accumulator.append(state["reward"])
avg_reward = sum(rewards_accumulator) / len(rewards_accumulator)
pbar.set_postfix({"Avg Reward": f"{avg_reward:.4f}"})
rewards_accumulator.extend([None] * rollouts_per_example)
pbar.set_postfix({"Avg Reward": _format_avg_reward(rewards_accumulator)})
pbar.update(rollouts_per_example)
return states
except Exception as e:
logger.exception(f"Error evaluating group (example_id={example.get('example_id')}): {repr(e)}")
raise
return failed_states # type: ignore[return-value]
# Save results for the generated group.
if save_file is not None:
await asyncio.gather(
*[
make_and_save_result(state, save_file, reasoning_field, rollout_idx)
for rollout_idx, state in enumerate(states)
]
)
# Update running average after group completes.
async with rewards_lock:
for state in states:
rewards_accumulator.append(state["reward"])
pbar.set_postfix({"Avg Reward": _format_avg_reward(rewards_accumulator)})
pbar.update(rollouts_per_example)
return states
async def run_eval(
@@ -410,8 +523,7 @@ async def run_eval(
pbar = tqdm(total=total_rollouts, desc="Evaluating")
if rewards_accumulator:
avg_reward = sum(rewards_accumulator) / len(rewards_accumulator)
pbar.set_postfix({"Avg Reward": f"{avg_reward:.4f}"})
pbar.set_postfix({"Avg Reward": _format_avg_reward(rewards_accumulator)})
all_states = await asyncio.gather(
*[
@@ -421,6 +533,7 @@ async def run_eval(
model_config.name,
example,
rollout_idx,
env_name_or_id,
sampling_args,
path_to_save if save_config.stream else None,
reasoning_field,
@@ -457,8 +570,7 @@ async def run_eval(
pbar = tqdm(total=total_rollouts, desc="Evaluating")
if rewards_accumulator:
avg_reward = sum(rewards_accumulator) / len(rewards_accumulator)
pbar.set_postfix({"Avg Reward": f"{avg_reward:.4f}"})
pbar.set_postfix({"Avg Reward": _format_avg_reward(rewards_accumulator)})
group_states_list = await asyncio.gather(
*[
@@ -468,6 +580,7 @@ async def run_eval(
model_config.name,
example,
rollouts_per_example,
env_name_or_id,
sampling_args,
path_to_save if save_config.stream else None,
reasoning_field,
@@ -488,6 +601,10 @@ async def run_eval(
"reward": [state["reward"] for state in all_states],
"completion_len": [get_completion_len(state) for state in all_states],
"is_truncated": [get_is_truncated(state) for state in all_states],
"rollout_status": [
(state.get("info", {}) or {}).get("prime_rl", {}).get("rollout_status", "ok")
for state in all_states
],
}
)
@@ -501,12 +618,12 @@ async def run_eval(
else:
results_df = new_results_df
unique_rewards = results_df.reward.unique()
unique_rewards = results_df.reward.dropna().unique()
could_be_binary = set(unique_rewards).issubset({0.0, 1.0})
if could_be_binary:
pass_at_k = (
results_df.groupby("example_id")
.apply(lambda x: compute_pass_at_k(x.reward), include_groups=False)
.apply(lambda x: compute_pass_at_k(x.reward.dropna()), include_groups=False)
.apply(pd.Series)
)
else:
@@ -515,17 +632,24 @@ async def run_eval(
# Log statistics to console
eval_time = time.perf_counter() - eval_start_time
no_response_rate = float((results_df.rollout_status == "no_response").mean()) if "rollout_status" in results_df else 0.0
message = f"Evaluated {env_name_or_id} in {eval_time:.2f}s (Avg@{k}={results_df.reward.mean():.4f}"
if could_be_binary:
assert pass_at_k is not None
for pass_rate, pass_rate_score in pd.Series(pass_at_k.mean()).items():
message += f", {capitalize(str(pass_rate))}: {pass_rate_score:.4f}"
message += f", Completion Length: {results_df.completion_len.mean():.2f} (±{results_df.completion_len.std():.2f}, ∈[{results_df.completion_len.min():.2f}, {results_df.completion_len.max():.2f}]), Truncated: {results_df.is_truncated.mean() * 100:.1f}%)"
message += (
f", No-response: {no_response_rate * 100:.1f}%"
f", Completion Length: {results_df.completion_len.mean():.2f} (±{results_df.completion_len.std():.2f}, ∈[{results_df.completion_len.min():.2f}, {results_df.completion_len.max():.2f}])"
f", Truncated: {results_df.is_truncated.mean() * 100:.1f}%)"
)
logger.success(message)
# Log statistics to monitor
eval_metrics = {
f"avg@{k}": results_df.reward.mean(),
"no_response/pct": no_response_rate * 100.0,
"no_response/count": int((results_df.rollout_status == "no_response").sum()) if "rollout_status" in results_df else 0,
"completion_len/avg": results_df.completion_len.mean().item(),
"completion_len/max": results_df.completion_len.max().item(),
"completion_len/min": results_df.completion_len.min().item(),
@@ -537,7 +661,7 @@ async def run_eval(
eval_metrics.update(pd.Series(pass_at_k.mean()).to_dict())
eval_metrics = {**{f"eval/{env_name_or_id}/{k}": v for k, v in eval_metrics.items()}}
eval_metrics.update({"progress/ckpt_step": ckpt_step, "step": step or ckpt_step})
monitor.log(eval_metrics)
monitor.log(eval_metrics, step=None)
# Save results
if save_config.disk is not None or save_config.hf is not None or save_config.env_hub:
@@ -614,9 +738,12 @@ async def run_evals(
step: int | None = None,
resume_path: Path | None = None,
):
await asyncio.gather(
*[
run_eval(
logger = get_logger()
async def run_eval_safe(env):
"""Wrapper to catch RetryError and skip env."""
try:
await run_eval(
clients=clients,
env_id=env.id,
env_name=env.name,
@@ -635,6 +762,103 @@ async def run_evals(
step=step,
resume_path=resume_path,
)
for env in eval_config.env
]
return True
except RetryError as e:
env_name = env.name or env.id
logger.warning(
f"Env '{env_name}' exhausted {eval_config.retry.max_attempts} retry attempts, skipping. "
f"Last error: {e.last_attempt.exception()}"
)
return None
results = await asyncio.gather(*[run_eval_safe(env) for env in eval_config.env])
skipped = sum(1 for r in results if r is None)
if skipped > 0:
logger.warning(f"Skipped {skipped}/{len(eval_config.env)} environments due to retry exhaustion")
def _run_evals_in_subprocess(
client_config: ClientConfig,
eval_config: EvalConfig,
model_config: ModelConfig,
sampling_config: EvalSamplingConfig,
reasoning_field: str,
output_dir: str,
ckpt_step: int,
step: int | None,
max_concurrent: int,
):
"""Entry point for eval subprocess. Creates its own event loop and clients."""
# Setup logger for subprocess (reset first since we inherit parent's global state when forked)
reset_logger()
logger = setup_logger("info")
intercept_verifiers_logging(level="info")
logger.info(f"Eval subprocess started for checkpoint step {ckpt_step}")
# Create fresh clients in subprocess
clients = setup_clients(client_config)
evals_client = setup_evals_client()
async def _run():
await set_semaphore(max_concurrent)
await run_evals(
clients=clients,
eval_config=eval_config,
model_config=model_config,
sampling_config=sampling_config,
evals_client=evals_client,
reasoning_field=reasoning_field,
output_dir=Path(output_dir),
ckpt_step=ckpt_step,
step=step,
)
asyncio.run(_run())
logger.info(f"Eval subprocess finished for checkpoint step {ckpt_step}")
async def run_evals_subprocess(
client_config: ClientConfig,
eval_config: EvalConfig | OfflineEvalConfig,
model_config: ModelConfig,
sampling_config: EvalSamplingConfig,
reasoning_field: str,
output_dir: Path,
ckpt_step: int,
step: int | None = None,
max_concurrent: int = -1,
):
"""Run evals in a separate subprocess to isolate the event loop.
This prevents eval's async work from causing event loop lag in the
orchestrator's main loop. The orchestrator blocks until eval completes.
"""
logger = get_logger()
logger.info(f"Spawning eval subprocess for checkpoint step {ckpt_step}")
process = Process(
target=_run_evals_in_subprocess,
args=(
client_config,
eval_config,
model_config,
sampling_config,
reasoning_field,
str(output_dir),
ckpt_step,
step,
max_concurrent,
),
daemon=True,
)
process.start()
# Wait for process to complete without blocking the event loop
while process.is_alive():
await asyncio.sleep(0.5)
if process.exitcode != 0:
logger.error(f"Eval subprocess failed with exit code {process.exitcode}")
else:
logger.success(f"Eval subprocess completed for checkpoint step {ckpt_step}")
+1 -2
View File
@@ -32,7 +32,6 @@ class CheckpointManager:
def _save_to_path(
self,
ckpt_path: Path,
ckpt_step: int,
progress: Progress,
buffer: Buffer,
):
@@ -88,7 +87,7 @@ class CheckpointManager:
"""Saves the full checkpoint state for a specified step."""
ckpt_path = self.get_ckpt_path(step)
ckpt_path.mkdir(parents=True, exist_ok=True)
self._save_to_path(ckpt_path, step, progress, buffer)
self._save_to_path(ckpt_path, progress, buffer)
def setup_ckpt_manager(output_dir: Path, config: CheckpointConfig | None) -> CheckpointManager | None:
+124 -12
View File
@@ -8,13 +8,65 @@ from prime_rl.utils.config import (
ClientConfig,
HeartbeatConfig,
LogConfig,
ModelConfig,
PrimeMonitorConfig,
WandbWithExtrasConfig,
)
from prime_rl.utils.config import (
ModelConfig as BaseModelConfig,
)
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings
class OptimizerConfig(BaseConfig):
"""Per-run optimizer configuration for multi-run training."""
lr: Annotated[
float,
Field(
ge=0,
description="Learning rate for this run.",
),
] = 1e-4
class LoRAConfig(BaseConfig):
"""Per-run LoRA configuration for multi-run training."""
name: Annotated[
str | None,
Field(
description="Name of the LoRA adapter. If None, auto-generated from rank and alpha.",
),
] = None
rank: Annotated[
int | None,
Field(
ge=1,
description="LoRA rank for this run. Must be <= trainer's max rank. If None, uses trainer's rank.",
),
] = None
alpha: Annotated[
float,
Field(
ge=0,
description="LoRA alpha for this run.",
),
] = 32.0
class ModelConfig(BaseModelConfig):
"""Extended model configuration with per-run LoRA settings."""
lora: Annotated[
LoRAConfig | None,
Field(
description="LoRA configuration. If None, LoRA is not used.",
),
] = None
class SamplingConfig(BaseConfig):
"""Configures how tokens are sampled from the model for training. Largely follows the vLLM sampling parameters."""
@@ -240,9 +292,9 @@ class RetryConfig(BaseConfig):
reraise: Annotated[
bool,
Field(
description="Whether to reraise the exception after all retries are exhausted.",
description="Whether to reraise the original exception after all retries are exhausted. If False, raises tenacity.RetryError instead.",
),
] = True
] = False
class EnvConfig(BaseConfig):
@@ -366,11 +418,19 @@ class CheckpointConfig(BaseConfig):
),
] = None
keep: Annotated[
keep_last: Annotated[
int | None,
Field(
ge=1,
description="Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints.",
description="Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency.",
),
] = None
keep_interval: Annotated[
int | None,
Field(
ge=1,
description="Keep checkpoints at every N steps permanently (e.g., keep_interval=100 keeps step 100, 200, ...). If None, no interval-based keeping.",
),
] = None
@@ -456,6 +516,17 @@ class BufferConfig(BaseConfig):
),
] = ["task", "prompt"]
skip_verification: Annotated[
bool,
Field(
description=(
"Whether to skip verification of rollouts using the environment's rubric. "
"If True, rewards are always set to 0, online_difficulty_filtering is disabled, "
"and easy/hard thresholds are not used."
),
),
] = False
@model_validator(mode="after")
def validate_thresholds(self):
if self.easy_threshold is not None and self.hard_threshold is not None:
@@ -468,6 +539,27 @@ class BufferConfig(BaseConfig):
assert all(ratio > 0 for ratio in self.env_ratios), "All env_ratios must be positive."
return self
@model_validator(mode="after")
def validate_skip_verification(self):
"""Validate that skip_verification is not used with reward-dependent features."""
if self.skip_verification:
if self.online_difficulty_filtering:
raise ValueError(
"skip_verification cannot be True when online_difficulty_filtering is True. "
"These features depend on rewards which are disabled when skip_verification=True."
)
if self.easy_threshold is not None:
raise ValueError(
"skip_verification cannot be True when easy_threshold is set. "
"Easy threshold depends on rewards which are disabled when skip_verification=True."
)
if self.hard_threshold is not None:
raise ValueError(
"skip_verification cannot be True when hard_threshold is set. "
"Hard threshold depends on rewards which are disabled when skip_verification=True."
)
return self
class AdvantageConfig(BaseConfig):
length_weighted_mean: bool = False
@@ -492,6 +584,20 @@ class NCCLWeightBroadcastConfig(BaseModel):
WeightBroadcastConfigType: TypeAlias = FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig
class TeacherModelConfig(BaseConfig):
"""Configures the teacher model for computing teacher logprobs (e.g. for distillation)."""
client: Annotated[
ClientConfig,
Field(description="The OAI client configuration for the teacher model."),
] = ClientConfig()
model: Annotated[
ModelConfig,
Field(description="The model configuration for the teacher model."),
] = ModelConfig()
class OrchestratorConfig(BaseSettings):
"""Configures the orchestrator for RL training."""
@@ -501,6 +607,19 @@ class OrchestratorConfig(BaseSettings):
# The model configuration
model: ModelConfig = ModelConfig()
# The optimizer configuration (per-run LR for multi-run training)
optim: OptimizerConfig = OptimizerConfig()
# The teacher model configuration (optional)
teacher_model: Annotated[
TeacherModelConfig | None,
Field(
description="The teacher model configuration for computing teacher logprobs (e.g. for distillation). "
"If provided, teacher logprobs will be computed using the specified model. "
"If None, no teacher model will be used."
),
] = None
# The sampling configuration
sampling: SamplingConfig = SamplingConfig()
@@ -643,13 +762,6 @@ class OrchestratorConfig(BaseSettings):
seed: Annotated[int | None, Field(description="Random seed for the orchestrator.")] = 42
lora_name: Annotated[
str | None,
Field(
description="Name of the LoRA to use for the orchestrator. If None, will not use any LoRA.",
),
] = None
heartbeat: Annotated[
HeartbeatConfig | None, Field(description="The heartbeat config for monitoring training progress.")
] = None
+74 -15
View File
@@ -6,22 +6,32 @@ Runs environment rollouts in a separate process to isolate event loop lag.
import asyncio
import queue
import uuid
from dataclasses import dataclass
from itertools import cycle
from multiprocessing import Process, Queue
from pathlib import Path
import verifiers as vf
from openai import AsyncOpenAI
from prime_rl.utils.client import setup_clients
from prime_rl.utils.config import ClientConfig
from prime_rl.utils.logger import intercept_verifiers_logging, reset_logger, setup_logger
class WorkerDiedError(Exception):
"""Raised when a worker subprocess dies unexpectedly."""
pass
@dataclass
class RolloutRequest:
"""Request to generate rollouts for an example."""
id: int # example_id
request_id: str
example_id: int
rollouts_per_example: int
model_name: str # Model name to use for this request (may change for LoRA)
@@ -30,7 +40,7 @@ class RolloutRequest:
class RolloutResponse:
"""Response containing rollout results."""
id: str
request_id: str
results: list[dict] # Simplified state dicts
lag_metrics: dict | None = None # Event loop lag metrics from worker
@@ -82,7 +92,7 @@ async def process_request(
) -> RolloutResponse:
"""Process a single rollout request."""
client = next(client_cycle)
example = example_lookup[request.id]
example = example_lookup[request.example_id]
group_inputs = [vf.RolloutInput(**example) for _ in range(request.rollouts_per_example)]
states = await env.run_group(
@@ -95,7 +105,7 @@ async def process_request(
)
results = [extract_result(state) for state in states]
return RolloutResponse(id=str(request.id), results=results)
return RolloutResponse(request_id=request.request_id, results=results)
async def worker_loop(
@@ -119,7 +129,7 @@ async def worker_loop(
lag_monitor_task = asyncio.create_task(lag_monitor.run())
# Track in-flight tasks
pending_tasks: dict[asyncio.Task, int] = {}
pending_tasks: dict[asyncio.Task, str] = {}
def check_for_requests():
"""Non-blocking check for new requests."""
@@ -133,7 +143,7 @@ async def worker_loop(
task = asyncio.create_task(
process_request(request, env, client_cycle, semaphore, example_lookup, sampling_args)
)
pending_tasks[task] = request.id
pending_tasks[task] = request.request_id
return True
try:
@@ -174,8 +184,18 @@ def worker_main(
max_concurrent: int,
example_lookup: dict[int, dict],
sampling_args: dict,
log_level: str,
vf_log_level: str,
log_file: str | None,
worker_name: str | None = None,
):
"""Main entry point for worker process."""
# Reset logger inherited from parent process, then setup fresh logger for this worker
if log_file:
reset_logger()
setup_logger(log_level, log_file=Path(log_file), append=True, tag=worker_name)
intercept_verifiers_logging(level=vf_log_level)
# Load environment
env = vf.load_environment(env_id, **env_args)
env.set_max_seq_len(seq_len)
@@ -215,6 +235,9 @@ class EnvWorker:
example_lookup: dict[int, dict],
sampling_args: dict,
worker_name: str | None = None,
log_level: str = "warn",
vf_log_level: str = "warn",
log_file: str | None = None,
):
self.env_id = env_id
self.env_args = env_args
@@ -227,6 +250,10 @@ class EnvWorker:
self.sampling_args = sampling_args
self.worker_name = worker_name or env_id
self.log_level = log_level
self.vf_log_level = vf_log_level
self.log_file = log_file
self.request_queue: Queue = Queue()
self.response_queue: Queue = Queue()
self.process: Process | None = None
@@ -237,6 +264,11 @@ class EnvWorker:
# Track latest lag metrics from this worker
self.latest_lag_metrics: dict = {}
# Track intentional shutdown to avoid false error on clean stop
self._stopping = False
# Track if worker died unexpectedly (prevents scheduler from routing to dead worker)
self._dead = False
def start(self):
"""Start the worker process."""
self.process = Process(
@@ -252,13 +284,20 @@ class EnvWorker:
self.max_concurrent,
self.example_lookup,
self.sampling_args,
self.log_level,
self.vf_log_level,
self.log_file,
self.worker_name,
),
daemon=True,
)
self.process.start()
self._stopping = False # Reset after process is alive to avoid race condition
self._dead = False # Reset in case of restart
def stop(self):
"""Stop the worker process."""
self._stopping = True
if self.process and self.process.is_alive():
self.request_queue.put(None) # Shutdown signal
self.process.join(timeout=5)
@@ -269,25 +308,27 @@ class EnvWorker:
self,
example_id: int,
rollouts_per_example: int,
) -> asyncio.Future:
"""Submit a rollout request and return a future for the response."""
) -> tuple[asyncio.Future, str]:
"""Submit a rollout request and return a (future, request_id) tuple."""
request_id = uuid.uuid4().hex
request = RolloutRequest(
id=example_id,
request_id=request_id,
example_id=example_id,
rollouts_per_example=rollouts_per_example,
model_name=self.model_name,
)
loop = asyncio.get_event_loop()
future = loop.create_future()
self.pending_futures[str(example_id)] = future
self.pending_futures[request_id] = future
self.request_queue.put(request)
return future
return future, request_id
async def collect_responses(self):
"""Background task to collect responses and resolve futures."""
while True:
# Non-blocking check for responses
# Drain queue first to salvage any responses before checking for dead worker
while True:
try:
response: RolloutResponse = self.response_queue.get_nowait()
@@ -296,12 +337,25 @@ class EnvWorker:
# Store latest lag metrics from worker
if response.lag_metrics:
self.latest_lag_metrics = response.lag_metrics
if response.id in self.pending_futures:
future = self.pending_futures.pop(response.id)
if response.request_id in self.pending_futures:
future = self.pending_futures.pop(response.request_id)
# Check if future was cancelled (e.g., by update_policy)
if not future.done():
future.set_result(response.results)
# Check if worker process died unexpectedly (but not during intentional shutdown)
if self.process and not self.process.is_alive() and not self._stopping:
exit_code = self.process.exitcode
error = WorkerDiedError(f"Worker '{self.worker_name}' died unexpectedly (exit code: {exit_code})")
# Mark worker as dead so scheduler won't route new requests here
self._dead = True
# Fail remaining pending futures so callers don't hang indefinitely
for future in self.pending_futures.values():
if not future.done():
future.set_exception(error)
self.pending_futures.clear()
raise error
await asyncio.sleep(0.01)
def update_model_name(self, model_name: str):
@@ -310,5 +364,10 @@ class EnvWorker:
@property
def pending_count(self) -> int:
"""Number of pending requests for this worker."""
"""Number of pending requests for this worker.
Returns a large number if the worker is dead to prevent scheduler from selecting it.
"""
if self._dead:
return 999999 # Effectively infinite - scheduler will pick other workers
return len(self.pending_futures)
@@ -71,10 +71,6 @@ class EventLoopLagMonitor:
self.logger.warning(
f"Detected busy event loop. Measured {mean_lag:.1f}s (min={min_lag:.1f}s, med={med_lag:.1f}s, p90={p90_lag:.1f}s, max={max_lag:.1f}s) event loop lag over the last {len(last_lags)} measurement(s)"
)
else:
self.logger.debug(
f"Event loop is running smoothly. Measured {mean_lag:.1f}s (min={min_lag:.1f}s, med={med_lag:.1f}s, p90={p90_lag:.1f}s, max={max_lag:.1f}s) event loop lag over the last {len(last_lags)} measurement(s)"
)
return {
"event_loop_lag/min": min_lag,
+86 -44
View File
@@ -23,12 +23,13 @@ import verifiers as vf
from loguru import logger
from transformers import AutoTokenizer
from prime_rl.eval.utils import run_evals
from prime_rl.eval.utils import run_evals_subprocess
from prime_rl.orchestrator.buffer import Buffer
from prime_rl.orchestrator.ckpt import Progress, setup_ckpt_manager
from prime_rl.orchestrator.config import BufferConfig, OrchestratorConfig
from prime_rl.orchestrator.scheduler import Scheduler
from prime_rl.orchestrator.utils import (
compute_teacher_logprobs,
get_sampling_args,
print_benchmark,
set_semaphore,
@@ -40,11 +41,10 @@ from prime_rl.utils.client import (
reload_weights,
setup_admin_clients,
setup_clients,
setup_evals_client,
update_weights,
)
from prime_rl.utils.heartbeat import Heartbeat
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.logger import intercept_verifiers_logging, setup_logger
from prime_rl.utils.monitor import setup_monitor
from prime_rl.utils.pydantic_config import parse_argv
from prime_rl.utils.utils import (
@@ -66,7 +66,7 @@ async def orchestrate(config: OrchestratorConfig):
logger = setup_logger(
config.log.level, log_file=config.output_dir / "logs" / "orchestrator.log" if config.log.file else None
)
vf.setup_logging(level=config.log.vf_level.upper())
intercept_verifiers_logging(level=config.log.vf_level)
logger.info("Starting orchestrator")
event_loop_lag_monitor = EventLoopLagMonitor()
@@ -97,7 +97,19 @@ async def orchestrate(config: OrchestratorConfig):
)
clients = setup_clients(config.client)
admin_clients = setup_admin_clients(config.client)
evals_client = setup_evals_client()
# Setup teacher model client if configured
teacher_clients = None
teacher_admin_clients = None
teacher_model_name = None
if config.teacher_model:
logger.info(
f"Initializing teacher OpenAI client (base_url={', '.join(config.teacher_model.client.base_url)}, "
f"model={config.teacher_model.model.name})"
)
teacher_clients = setup_clients(config.teacher_model.client)
teacher_admin_clients = setup_admin_clients(config.teacher_model.client)
teacher_model_name = config.teacher_model.model.name
# Load tokenizer
logger.info(f"Initializing tokenizer for {config.model.name}")
@@ -132,6 +144,9 @@ async def orchestrate(config: OrchestratorConfig):
if config.trajectory_strategy == "interleaved":
logger.info("Using token prompts in environment to avoid retokenization discrepancies in multi-turn rollouts")
env.set_interleaved_rollouts(True)
if config.buffer.skip_verification:
logger.info("Skipping verification (rewards will be set to 0)")
env.set_score_rollouts(False)
# Setup buffer
logger.info(f"Setting up buffer ({config.buffer})")
@@ -166,14 +181,15 @@ async def orchestrate(config: OrchestratorConfig):
max_async_level=config.max_async_level,
max_off_policy_steps=config.max_off_policy_steps,
strict_async_level=config.strict_async_level,
lora_name=config.lora_name,
lora_name=config.model.lora.name if config.model.lora else None,
output_dir=config.output_dir,
)
if checkpoint_step is not None and config.lora_name is not None:
scheduler.model_name = config.lora_name
if checkpoint_step is not None and config.model.lora is not None:
scheduler.model_name = config.model.lora.name
for workers in scheduler.workers.values():
for worker in workers:
worker.model_name = config.lora_name
worker.model_name = config.model.lora.name
await scheduler.start()
@@ -183,6 +199,13 @@ async def orchestrate(config: OrchestratorConfig):
await check_has_model(clients, config.model.name)
logger.success("Inference pool ready")
# Check health of teacher inference server if configured
if teacher_admin_clients is not None:
logger.info("Waiting for teacher inference pool to be ready")
await check_health(teacher_admin_clients)
await check_has_model(teacher_clients, teacher_model_name)
logger.success("Teacher inference pool ready")
# Set up weight broadcast backend
logger.info(f"Initializing weight broadcast ({config.weight_broadcast})")
if config.weight_broadcast.type == "nccl":
@@ -210,11 +233,11 @@ async def orchestrate(config: OrchestratorConfig):
await update_weights(
admin_clients,
get_step_path(get_broadcast_dir(config.output_dir), scheduler.ckpt_step),
lora_name=config.lora_name,
lora_name=config.model.lora.name if config.model.lora else None,
)
else:
logger.info("Training from scratch. Resetting weights to base model")
if config.lora_name is None:
if config.model.lora is None:
await reload_weights(admin_clients)
# Iterate over dataset in batches
@@ -257,11 +280,40 @@ async def orchestrate(config: OrchestratorConfig):
logger.info(f"Starting orchestrator step {progress.step}")
step_start_time = time.perf_counter()
# Run evals BEFORE training (blocking, in subprocess to isolate event loop)
# This ensures weights don't change during eval and eval doesn't cause event loop lag
if (
config.eval
and ckpt_step % config.eval.interval == 0
and ckpt_step > last_eval_step
and ((ckpt_step == 0 and config.eval.eval_base_model) or ckpt_step > 0)
):
last_eval_step = ckpt_step
logger.info(f"Running evals for checkpoint step {ckpt_step} (blocking, subprocess)")
# Pause weight updates during eval
scheduler.checkpoint_ready.clear()
await run_evals_subprocess(
client_config=config.client,
eval_config=config.eval,
model_config=config.model,
sampling_config=config.eval.sampling,
reasoning_field=config.eval.reasoning_field,
output_dir=config.output_dir,
ckpt_step=ckpt_step,
step=progress.step,
max_concurrent=config.max_concurrent or -1,
)
# Resume weight updates
scheduler.checkpoint_ready.set()
# Schedule generating the training batch
generate_completions_start_time = time.perf_counter()
train_task = asyncio.create_task(scheduler.generate_batch(step=progress.step))
# Schedule running evals at the specified interval
# Schedule running validation at the specified interval
if val_buffer and config.val and progress.step % config.val.interval == 0:
logger.info(f"Running validation for step {progress.step}")
val_examples = val_buffer.sample_examples(config.val.num_examples)
@@ -279,31 +331,6 @@ async def orchestrate(config: OrchestratorConfig):
else:
val_task = asyncio.create_task(asyncio.sleep(0)) # Dummy task
# Schedule running evals at the specified interval
if (
config.eval
and ckpt_step % config.eval.interval == 0
and ckpt_step > last_eval_step
and ((ckpt_step == 0 and config.eval.eval_base_model) or ckpt_step > 0)
):
last_eval_step = ckpt_step
logger.info(f"Running evals for checkpoint step {ckpt_step}")
eval_task = asyncio.create_task(
run_evals(
clients=clients,
eval_config=config.eval,
model_config=config.model,
sampling_config=config.eval.sampling,
evals_client=evals_client,
reasoning_field=config.eval.reasoning_field,
output_dir=config.output_dir,
ckpt_step=ckpt_step,
step=progress.step,
)
)
else:
eval_task = asyncio.create_task(asyncio.sleep(0)) # Dummy task
# Await train rollouts, process results and write batch to disk to consume by trainer
await train_task
generate_completions_time = time.perf_counter() - generate_completions_start_time
@@ -327,25 +354,39 @@ async def orchestrate(config: OrchestratorConfig):
if train_example is not None:
for te in train_example:
te.advantage = advantage
te.reward = train_rollout["reward"]
train_examples.extend(train_example)
logger.debug(
f"Converted {len(train_rollouts)} training rollouts to {len(train_examples)} training examples using {config.trajectory_strategy} strategy"
)
# Compute teacher logprobs if teacher model is configured
teacher_logprobs_time = 0
if config.teacher_model is not None:
logger.info(f"Computing teacher logprobs for {len(train_examples)} training examples")
teacher_logprobs_start_time = time.perf_counter()
teacher_logprobs_list = await compute_teacher_logprobs(
clients=teacher_clients,
model_name=teacher_model_name,
samples=train_examples,
)
for train_example, teacher_logprobs in zip(train_examples, teacher_logprobs_list):
train_example.teacher_logprobs = teacher_logprobs
teacher_logprobs_time = time.perf_counter() - teacher_logprobs_start_time
logger.debug(f"Computed teacher logprobs in {teacher_logprobs_time:.2f}s")
training_batch = TrainingBatch(
examples=train_examples,
temperature=config.sampling.temperature,
step=progress.step,
)
assert len(training_batch.examples) != 0, "Step with no samples is not allowed"
training_batch_sender.send(training_batch)
# Await and process val results
await val_task
val_outputs = val_task.result()
# Await eval results
await eval_task
# Gather metrics in dataframes
results_df = pd.DataFrame(
{
@@ -447,6 +488,7 @@ async def orchestrate(config: OrchestratorConfig):
# Time metrics
"time/step": step_time,
"time/generate_completions": generate_completions_time,
"time/teacher_logprobs": teacher_logprobs_time,
"time/save_ckpt": save_ckpt_time,
# Scheduler metrics
**scheduler.get_metrics(),
@@ -507,17 +549,17 @@ async def orchestrate(config: OrchestratorConfig):
heart.beat()
if config.eval:
logger.info("Running final evals")
await run_evals(
clients=clients,
logger.info("Running final evals (subprocess)")
await run_evals_subprocess(
client_config=config.client,
eval_config=config.eval,
model_config=config.model,
sampling_config=config.eval.sampling,
evals_client=evals_client,
reasoning_field=config.eval.reasoning_field,
output_dir=config.output_dir,
ckpt_step=scheduler.ckpt_step,
step=progress.step,
max_concurrent=config.max_concurrent or -1,
)
# Log final (immutable) samples and distributions to monitor(s)
+21 -5
View File
@@ -6,6 +6,7 @@ Isolates event loop lag from environment execution.
import asyncio
import time
from pathlib import Path
from typing import NamedTuple
from httpx import AsyncClient
@@ -13,11 +14,12 @@ from tqdm import tqdm
from prime_rl.orchestrator.buffer import Buffer
from prime_rl.orchestrator.config import EnvConfig, OrchestratorConfig
from prime_rl.orchestrator.env_worker import EnvWorker
from prime_rl.orchestrator.env_worker import EnvWorker, WorkerDiedError
from prime_rl.orchestrator.utils import get_sampling_args
from prime_rl.utils.client import update_weights
from prime_rl.utils.config import ClientConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.pathing import get_env_worker_log_file
from prime_rl.utils.utils import (
get_broadcast_dir,
get_latest_ckpt_step,
@@ -57,6 +59,7 @@ class Scheduler:
max_off_policy_steps: int,
strict_async_level: bool,
lora_name: str | None = None,
output_dir: Path | None = None,
):
self.logger = get_logger()
self.admin_clients = admin_clients
@@ -88,6 +91,13 @@ class Scheduler:
env_name = env_config.name or env_config.id
self.env_names.append(env_name)
self.workers[env_name] = []
# Setup log file if env worker file logging is enabled (all workers share one file)
env_log_file = None
if config.log.env_worker_logs and output_dir is not None:
env_log_file = get_env_worker_log_file(output_dir, env_name)
env_log_file.parent.mkdir(parents=True, exist_ok=True)
for worker_idx in range(self.workers_per_env):
worker = EnvWorker(
env_id=env_config.id,
@@ -100,6 +110,9 @@ class Scheduler:
example_lookup=self.example_lookups[env_name],
sampling_args=self.sampling_args,
worker_name=f"{env_name}_{worker_idx}",
log_level=config.log.level,
vf_log_level=config.log.vf_level,
log_file=str(env_log_file) if env_log_file else None,
)
self.workers[env_name].append(worker)
@@ -110,6 +123,7 @@ class Scheduler:
self.checkpoint_ready = asyncio.Event()
self.checkpoint_ready.set()
self.update_weights_time, self.wait_for_ckpt_time = 0, 0
self.cancelled_rollouts_count = 0
# Background tasks
self._response_collectors: list[asyncio.Task] = []
@@ -142,14 +156,11 @@ class Scheduler:
workers = self.workers[task]
worker = min(workers, key=lambda w: w.pending_count)
future = await worker.submit_request(
future, request_id = await worker.submit_request(
example_id=example["example_id"],
rollouts_per_example=self.config.rollouts_per_example,
)
# Extract request_id from the future's pending tracking
request_id = [k for k, v in worker.pending_futures.items() if v is future][0]
self.inflight_group_rollouts[future] = InflightRolloutInfo(
off_policy_steps=0,
worker=worker,
@@ -220,6 +231,7 @@ class Scheduler:
# Remove cancelled
for future, worker in futures_to_remove:
self.inflight_group_rollouts.pop(future, None)
self.cancelled_rollouts_count += len(futures_to_remove)
# Update off-policy steps for remaining
for future, off_policy_steps, worker, request_id in futures_to_update:
@@ -282,6 +294,8 @@ class Scheduler:
except asyncio.CancelledError:
pass # Request was cancelled, will be rescheduled
except WorkerDiedError:
raise # Re-raise to exit process for K8s restart
except Exception as e:
self.logger.warning(f"Rollout failed: {e}")
@@ -321,7 +335,9 @@ class Scheduler:
"batch/off_policy_level/max": self.max_off_policy_level,
"batch/off_policy_level/mean": self.mean_off_policy_level,
"batch/off_policy_level/min": self.min_off_policy_level,
"batch/cancelled_rollouts": self.cancelled_rollouts_count,
}
self.cancelled_rollouts_count = 0
# Add per-worker lag metrics and pending counts
for workers in self.workers.values():
@@ -35,6 +35,7 @@ def interleave_rollout(state: vf.State) -> list[TrainingSample] | None:
completion_ids=deepcopy(first_step["tokens"]["completion_ids"]),
completion_mask=completion_mask,
completion_logprobs=deepcopy(first_step["tokens"]["completion_logprobs"]),
teacher_logprobs=None, # Populated at the end after full sequence length is known if teacher model is configured
advantage=None,
)
@@ -70,6 +71,7 @@ def interleave_rollout(state: vf.State) -> list[TrainingSample] | None:
# New prefix is the current prompt and completion ids concatenated
prefix_tokens = tokens["prompt_ids"] + tokens["completion_ids"]
return [interleaved_rollout]
@@ -98,6 +100,7 @@ def branch_rollout(state: vf.State) -> list[TrainingSample] | None:
completion_mask=completion_mask,
completion_logprobs=deepcopy(tokens["completion_logprobs"]),
advantage=None,
teacher_logprobs=None,
)
rollouts.append(rollout)
return rollouts
+32
View File
@@ -1,6 +1,9 @@
import asyncio
from itertools import cycle
from typing import Any, AsyncContextManager
import pandas as pd
from openai import AsyncOpenAI
from openai.types.chat.chat_completion import ChatCompletion, Choice
from openai.types.completion_usage import CompletionUsage
from rich.console import Console
@@ -8,6 +11,7 @@ from rich.table import Table
from verifiers.utils.async_utils import maybe_semaphore
from prime_rl.orchestrator.config import SamplingConfig
from prime_rl.transport import TrainingSample
from prime_rl.utils.utils import (
format_num,
format_time,
@@ -129,3 +133,31 @@ def print_benchmark(history: dict[str, list[Any]]) -> None:
# Display table
console.print(table)
async def compute_teacher_logprobs(
clients: list[AsyncOpenAI],
model_name: str,
samples: list[TrainingSample],
) -> list[list[float]]:
"""Compute teacher model logprobs for a batch of training samples via prefill."""
async def _compute_single(client: AsyncOpenAI, sample: TrainingSample) -> list[float]:
async with await get_semaphore():
response = await client.post(
"/chat/completions/tokens",
body={
"model": model_name,
"messages": [{"role": "user", "content": ""}],
"tokens": sample.prompt_ids + sample.completion_ids,
"max_tokens": 1,
"temperature": 1.0,
"top_p": 1.0,
"skip_special_tokens": False,
"prompt_logprobs": True,
},
cast_to=ChatCompletion,
)
return [0.0 if lp is None else float(next(iter(lp.values()))["logprob"]) for lp in response.prompt_logprobs]
return await asyncio.gather(*[_compute_single(client, sample) for client, sample in zip(cycle(clients), samples)])
+145 -8
View File
@@ -72,11 +72,19 @@ class SharedCheckpointConfig(BaseSettings):
int | None, Field(description="The step to resume from. If None, will not resume from a checkpoint.")
] = None
keep: Annotated[
keep_last: Annotated[
int | None,
Field(
ge=1,
description="Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints.",
description="Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency.",
),
] = None
keep_interval: Annotated[
int | None,
Field(
ge=1,
description="Keep checkpoints at every N steps permanently (e.g., keep_interval=100 keeps step 100, 200, ...). If None, no interval-based keeping.",
),
] = None
@@ -130,6 +138,19 @@ class RLConfig(BaseSettings):
inference_gpu_ids: Annotated[list[int], Field(description="The GPU IDs to use for inference.")] = [0]
trainer_gpu_ids: Annotated[list[int], Field(description="The GPU IDs to use for trainer.")] = [1]
teacher_gpu_ids: Annotated[
list[int] | None,
Field(
description="The GPU IDs to use for teacher inference. If None, teacher inference server will not be started."
),
] = None
teacher_inference: Annotated[
InferenceConfig | None,
Field(
description="The teacher inference config. If None, will use the same config as inference (if available) or a default config. Only used when teacher_gpu_ids is set."
),
] = None
### Shared configurations
@@ -252,9 +273,13 @@ class RLConfig(BaseSettings):
self.orchestrator.ckpt.resume_step = self.ckpt.resume_step
# If specified, propagate keep policy
if self.ckpt.keep is not None:
self.trainer.ckpt.keep = self.ckpt.keep
self.orchestrator.ckpt.keep = self.ckpt.keep
if self.ckpt.keep_last is not None:
self.trainer.ckpt.keep_last = self.ckpt.keep_last
self.orchestrator.ckpt.keep_last = self.ckpt.keep_last
if self.ckpt.keep_interval is not None:
self.trainer.ckpt.keep_interval = self.ckpt.keep_interval
self.orchestrator.ckpt.keep_interval = self.ckpt.keep_interval
validate_shared_ckpt_config(self.trainer, self.orchestrator)
@@ -393,9 +418,17 @@ class RLConfig(BaseSettings):
if self.trainer.model.lora is not None:
if self.trainer.weight_broadcast.type == "nccl":
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
if self.orchestrator.lora_name is None:
lora_name = f"r{self.trainer.model.lora.rank}-a{self.trainer.model.lora.alpha}"
self.orchestrator.lora_name = lora_name
# Ensure orchestrator has LoRA config
if self.orchestrator.model.lora is None:
from prime_rl.orchestrator.config import LoRAConfig
self.orchestrator.model.lora = LoRAConfig()
# Auto-generate name if not provided
if self.orchestrator.model.lora.name is None:
self.orchestrator.model.lora.name = f"r{self.trainer.model.lora.rank}-a{self.trainer.model.lora.alpha}"
if self.inference is not None:
self.inference.enable_lora = True
self.inference.max_lora_rank = self.trainer.model.lora.rank
@@ -428,6 +461,57 @@ class RLConfig(BaseSettings):
raise ValueError("NCCL weight broadcast requires at least 2 GPUs to build the broadcast process group.")
return self
@model_validator(mode="after")
def auto_setup_teacher_inference(self):
"""Auto-configure teacher inference server and orchestrator teacher_model client."""
if self.teacher_gpu_ids is None or len(self.teacher_gpu_ids) == 0:
return self
import copy
from prime_rl.orchestrator.config import TeacherModelConfig
# Create or complete teacher_inference config
if self.teacher_inference is None:
self.teacher_inference = copy.deepcopy(self.inference) if self.inference else InferenceConfig()
# Avoid port conflict with main inference by using next port
if self.inference is not None:
self.teacher_inference.server.port = self.inference.server.port + 1
elif self.inference is not None and self.teacher_inference.server.port == self.inference.server.port:
raise ValueError(
f"teacher_inference.server.port ({self.teacher_inference.server.port}) conflicts with "
f"inference.server.port ({self.inference.server.port}). "
"Either use different ports or let teacher_inference be auto-configured."
)
# Auto-configure DP based on GPU count
tp = self.teacher_inference.parallel.tp
if len(self.teacher_gpu_ids) != self.teacher_inference.parallel.dp * tp:
assert len(self.teacher_gpu_ids) % tp == 0, (
"Number of teacher GPUs must be divisible by tensor parallel size"
)
assert len(self.teacher_gpu_ids) > 0, "teacher_gpu_ids cannot be empty"
self.teacher_inference.parallel.dp = len(self.teacher_gpu_ids) // tp
# Auto-configure orchestrator's teacher_model client
if self.orchestrator.teacher_model is None:
self.orchestrator.teacher_model = TeacherModelConfig()
host = self.teacher_inference.server.host or "localhost"
port = self.teacher_inference.server.port
self.orchestrator.teacher_model.client.base_url = [f"http://{host}:{port}/v1"]
self.orchestrator.teacher_model.model.name = self.teacher_inference.model.name
return self
@model_validator(mode="after")
def validate_teacher_model(self):
if self.trainer.loss.teacher_tau > 0 and not self.orchestrator.teacher_model:
raise ValueError(
"teacher_model must be configured when teacher_tau > 0. "
"Either set teacher_tau = 0, set teacher_gpu_ids, or configure teacher_model manually."
)
return self
def cleanup_threads(threads: list[Thread]):
for thread in threads:
@@ -544,6 +628,46 @@ def rl(config: RLConfig):
"No inference config specified, skipping starting inference server. Is your inference server running?"
)
# Optionally, start teacher inference process
if config.teacher_inference:
if config.teacher_gpu_ids is None or len(config.teacher_gpu_ids) == 0:
raise ValueError(
"teacher_inference is configured but teacher_gpu_ids is not set or is empty. "
"Either set teacher_gpu_ids to start a teacher inference server, "
"or omit teacher_inference and configure orchestrator.teacher_model to use an existing server."
)
teacher_inference_file = get_temp_toml_file()
with open(teacher_inference_file, "wb") as f:
tomli_w.dump(config.teacher_inference.model_dump(exclude_none=True, mode="json"), f)
teacher_inference_cmd = ["uv", "run", "inference", "@", teacher_inference_file.as_posix()]
logger.info(f"Starting teacher inference process on GPU(s) {' '.join(map(str, config.teacher_gpu_ids))}")
logger.debug(f"Teacher inference start command: {' '.join(teacher_inference_cmd)}")
with open(log_dir / "teacher_inference.stdout", "w") as log_file:
teacher_inference_process = Popen(
teacher_inference_cmd,
env={**os.environ, "CUDA_VISIBLE_DEVICES": ",".join(map(str, config.teacher_gpu_ids))},
stdout=log_file,
stderr=log_file,
)
processes.append(teacher_inference_process)
# Start monitoring thread
stop_event = Event()
stop_events["teacher_inference"] = stop_event
monitor_thread = Thread(
target=monitor_process,
args=(teacher_inference_process, stop_event, error_queue, "teacher_inference"),
daemon=True,
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
elif config.trainer.loss.teacher_tau > 0 or config.orchestrator.teacher_model:
logger.warning(
"No teacher_inference config specified, skipping starting teacher inference server. "
"Is your teacher inference server running? Make sure orchestrator.teacher_model is configured."
)
# Start orchestrator process
orchestrator_file = get_temp_toml_file()
with open(orchestrator_file, "wb") as f:
@@ -654,6 +778,19 @@ def rl(config: RLConfig):
# Small delay to avoid busy waiting
time.sleep(1)
# Check if any critical process failed
if orchestrator_process.returncode != 0:
logger.error(f"Orchestrator failed with exit code {orchestrator_process.returncode}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
if trainer_process.returncode != 0:
logger.error(f"Trainer failed with exit code {trainer_process.returncode}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
logger.success("RL training finished!")
# Cleanup threads and processes
+2 -4
View File
@@ -1,7 +1,5 @@
import asyncio
import verifiers as vf
from prime_rl.orchestrator.utils import (
set_semaphore,
)
@@ -13,7 +11,7 @@ from prime_rl.utils.client import (
setup_admin_clients,
setup_clients,
)
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.logger import intercept_verifiers_logging, setup_logger
from prime_rl.utils.pydantic_config import parse_argv
from prime_rl.utils.utils import clean_exit, get_env_ids_to_install, install_env
@@ -24,7 +22,7 @@ async def synthesize(config: SynthesizeConfig):
logger = setup_logger(
config.log.level, log_file=config.output_dir / "logs" / "synthesize.log" if config.log.file else None
)
vf.setup_logging(level=config.log.vf_level.upper())
intercept_verifiers_logging(level=config.log.vf_level)
env_names = [env.name or env.id for env in config.env]
logger.info(f"Starting synthetic data generation for {config.model.name} in environments {', '.join(env_names)}")
+30 -9
View File
@@ -6,6 +6,7 @@ from prime_rl.transport.types import MicroBatch, TrainingSample
def prepare_sample(
training_example: TrainingSample,
seq_len: int,
temperature: float,
) -> MicroBatch:
"""
Prepare a problem for sequence packing training.
@@ -14,26 +15,43 @@ def prepare_sample(
# Prepare input_ids, loss_mask, position_ids, inference_logprobs, and advantages
input_ids = training_example.prompt_ids + training_example.completion_ids
loss_mask = training_example.prompt_mask + training_example.completion_mask
# Inference logprobs only cover completion tokens, so prepend zeros for prompt tokens
inference_logprobs = [0.0] * len(training_example.prompt_ids) + training_example.completion_logprobs
advantages = [training_example.advantage] * len(input_ids)
position_ids = list(range(len(input_ids)))
# Teacher logprobs already cover the full sequence (prompt + completion),
# computed via prefill in the orchestrator when a teacher model is configured
teacher_logprobs = training_example.teacher_logprobs
if len(input_ids) > seq_len:
input_ids = input_ids[:seq_len]
loss_mask = loss_mask[:seq_len]
inference_logprobs = inference_logprobs[:seq_len]
position_ids = position_ids[:seq_len]
advantages = advantages[:seq_len]
if teacher_logprobs is not None:
teacher_logprobs = teacher_logprobs[:seq_len]
assert len(input_ids) == len(advantages) == len(loss_mask) == len(position_ids) == len(inference_logprobs), (
assert (
len(input_ids)
== len(advantages)
== len(loss_mask)
== len(position_ids)
== len(inference_logprobs)
), (
f"input_ids: {len(input_ids)}, advantages: {len(advantages)}, loss_mask: {len(loss_mask)}, position_ids: {len(position_ids)}, inference_logprobs: {len(inference_logprobs)}"
)
if teacher_logprobs is not None:
assert len(teacher_logprobs) == len(input_ids), f"teacher_logprobs: {len(teacher_logprobs)}"
return MicroBatch(
input_ids=input_ids,
advantages=advantages,
loss_mask=loss_mask,
position_ids=position_ids,
inference_logprobs=inference_logprobs,
teacher_logprobs=teacher_logprobs,
temperature=temperature,
)
@@ -58,6 +76,10 @@ def packed_samples_into_micro_bs(
bin_content.loss_mask.extend(sample.loss_mask)
bin_content.advantages.extend(sample.advantages)
bin_content.inference_logprobs.extend(sample.inference_logprobs)
if sample.teacher_logprobs is not None:
if bin_content.teacher_logprobs is None:
bin_content.teacher_logprobs = []
bin_content.teacher_logprobs.extend(sample.teacher_logprobs)
bin_content.position_ids.extend(sample.position_ids)
bin_content.lora_num_tokens[idx] += len(sample.input_ids)
break
@@ -85,11 +107,13 @@ def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBa
if not (pad_to_multiple_of > 1 and padding_size > 0):
return micro_batch
micro_batch.input_ids.extend([1 for _ in range(padding_size)])
micro_batch.advantages.extend([0.0 for _ in range(padding_size)])
micro_batch.loss_mask.extend([False for _ in range(padding_size)])
micro_batch.input_ids.extend([1] * padding_size)
micro_batch.advantages.extend([0.0] * padding_size)
micro_batch.loss_mask.extend([False] * padding_size)
micro_batch.position_ids.extend(list(range(padding_size)))
micro_batch.inference_logprobs.extend([0.0 for _ in range(padding_size)])
micro_batch.inference_logprobs.extend([0.0] * padding_size)
if micro_batch.teacher_logprobs is not None:
micro_batch.teacher_logprobs.extend([0.0] * padding_size)
micro_batch.lora_num_tokens[-1] += (
padding_size # We send padding to the last lora so that tokens have ascending lora idx
)
@@ -112,14 +136,11 @@ def prepare_batch(
"""
max_seq_len = seq_len
all_samples = [(idx, prepare_sample(rollout, max_seq_len)) for idx, rollout in zip(idxs, rollouts)]
all_samples = [(idx, prepare_sample(rollout, max_seq_len, temperature)) for idx, rollout in zip(idxs, rollouts)]
micro_batches = packed_samples_into_micro_bs(all_samples, max_seq_len, num_loras)
micro_batches = [pad_micro_batch(micro_batch, pad_to_multiple_of) for micro_batch in micro_batches]
for micro_batch in micro_batches:
micro_batch.temperature = temperature
num_padding_batch = -len(micro_batches) % num_train_workers
# because of fsdp we need to make sure that each data ran has the same number of micro batches otherwise training will hang.
+65 -14
View File
@@ -29,7 +29,7 @@ from prime_rl.trainer.weights import (
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
from prime_rl.utils.tensor_hashing import get_module_signature, get_optimizer_signature
from prime_rl.utils.utils import get_ckpt_dir, get_step_path, get_weights_dir
from prime_rl.utils.utils import get_all_ckpt_steps, get_ckpt_dir, get_step_path, get_weights_dir
class AppState(Stateful):
@@ -87,7 +87,14 @@ class CheckpointManager:
self.ckpt_dir = get_ckpt_dir(output_dir)
self.logger = get_logger()
self.world = get_world()
self.ckpt_steps: list[int] = [] # Sorted list of steps that have been checkpointed, only used on master rank
if self.world.is_master:
all_steps = get_all_ckpt_steps(self.ckpt_dir)
if config.resume_step is not None and config.resume_step >= 0:
self.ckpt_steps = [s for s in all_steps if s <= config.resume_step]
else:
self.ckpt_steps = all_steps
else:
self.ckpt_steps = []
def get_ckpt_path(self, step: int) -> Path:
"""Get the path to write the trainer checkpoint for a given step."""
@@ -193,13 +200,28 @@ class CheckpointManager:
self.ckpt_steps.append(step)
def maybe_clean(self) -> None:
"""Deletes past checkpoints beyond the most recent config.keep steps. No-op if config.keep is None."""
if self.config.keep is None:
"""Deletes past checkpoints based on keep_last and keep_interval policies. No-op if both are None."""
if self.config.keep_last is None and self.config.keep_interval is None:
return
# Get all the checkpoint steps to delete
assert list(self.ckpt_steps) == sorted(self.ckpt_steps)
ckpt_steps_to_delete = self.ckpt_steps[: -self.config.keep]
# Determine which steps to keep
steps_to_keep = set()
# Keep the most recent keep_last steps
if self.config.keep_last is not None:
steps_to_keep.update(self.ckpt_steps[-self.config.keep_last :])
# Keep steps at keep_interval intervals
if self.config.keep_interval is not None:
for step in self.ckpt_steps:
if step % self.config.keep_interval == 0:
steps_to_keep.add(step)
# Delete steps not in steps_to_keep
ckpt_steps_to_delete = [step for step in self.ckpt_steps if step not in steps_to_keep]
for ckpt_step in ckpt_steps_to_delete:
trainer_ckpt_path = self.get_ckpt_path(ckpt_step)
ckpt_path = trainer_ckpt_path.parent
@@ -208,7 +230,7 @@ class CheckpointManager:
shutil.rmtree(ckpt_path)
# Update checkpoint steps
self.ckpt_steps = self.ckpt_steps[-self.config.keep :]
self.ckpt_steps = [step for step in self.ckpt_steps if step in steps_to_keep]
class WeightCheckpointManager:
@@ -220,15 +242,25 @@ class WeightCheckpointManager:
config: WeightCheckpointConfig,
lora_config: LoRAConfig | None = None,
save_async: bool = False,
keep: int | None = None,
keep_last: int | None = None,
keep_interval: int | None = None,
resume_step: int | None = None,
):
self.weights_dir = get_weights_dir(output_dir)
self.config = config
self.lora_config = lora_config
self.logger = get_logger()
self.world = get_world()
self.ckpt_steps: list[int] = [] # Sorted list of steps that have been checkpointed, only used on master rank
self.keep = keep
if self.world.is_master:
all_steps = get_all_ckpt_steps(self.weights_dir)
if resume_step is not None and resume_step >= 0:
self.ckpt_steps = [s for s in all_steps if s <= resume_step]
else:
self.ckpt_steps = all_steps
else:
self.ckpt_steps = []
self.keep_last = keep_last
self.keep_interval = keep_interval
def get_step_path(self, step: int) -> Path:
"""Get the path to write the weight checkpoint for a given step."""
@@ -305,16 +337,33 @@ class WeightCheckpointManager:
# Save weight checkpoint on master rank
if self.world.is_master:
self.save_to_path(step_path, state_dict, lora_state_dict, model, tokenizer)
# Write STABLE file to indicate checkpoint is complete (for eval to safely read)
(step_path / "STABLE").touch()
self.ckpt_steps.append(step)
def maybe_clean(self) -> None:
"""Deletes past checkpoints beyond the most recent config.keep steps. No-op if config.keep is None."""
if self.keep is None:
"""Deletes past checkpoints based on keep_last and keep_interval policies. No-op if both are None."""
if self.keep_last is None and self.keep_interval is None:
return
# Get all the checkpoint steps to delete
assert list(self.ckpt_steps) == sorted(self.ckpt_steps)
ckpt_steps_to_delete = self.ckpt_steps[: -self.keep]
# Determine which steps to keep
steps_to_keep = set()
# Keep the most recent keep_last steps
if self.keep_last is not None:
steps_to_keep.update(self.ckpt_steps[-self.keep_last :])
# Keep steps at keep_interval intervals
if self.keep_interval is not None:
for step in self.ckpt_steps:
if step % self.keep_interval == 0:
steps_to_keep.add(step)
# Delete steps not in steps_to_keep
ckpt_steps_to_delete = [step for step in self.ckpt_steps if step not in steps_to_keep]
for ckpt_step in ckpt_steps_to_delete:
ckpt_path = self.get_step_path(ckpt_step)
if ckpt_path.exists():
@@ -322,7 +371,7 @@ class WeightCheckpointManager:
shutil.rmtree(ckpt_path)
# Update checkpoint steps
self.ckpt_steps = self.ckpt_steps[-self.keep :]
self.ckpt_steps = [step for step in self.ckpt_steps if step in steps_to_keep]
def setup_ckpt_managers(
@@ -336,7 +385,9 @@ def setup_ckpt_managers(
output_dir,
ckpt_config.weights,
lora_config=lora_config,
keep=ckpt_config.keep,
keep_last=ckpt_config.keep_last,
keep_interval=ckpt_config.keep_interval,
resume_step=ckpt_config.resume_step,
)
else:
weight_ckpt_manager = None
+28 -3
View File
@@ -80,7 +80,7 @@ class LoRAConfig(BaseConfig):
ge=0,
description="LoRA scaling parameter.",
),
] = 16.0
] = 32.0
dropout: Annotated[
float,
@@ -104,6 +104,7 @@ class LoRAConfig(BaseConfig):
"gate_proj",
"up_proj",
"down_proj",
"experts",
]
modules_to_save: Annotated[
@@ -237,6 +238,13 @@ class ModelConfig(BaseConfig):
),
] = DebugModelConfig()
fused_lm_head_chunk_size: Annotated[
int | None,
Field(
description="The chunk size to use for the fused LM head. If None, will not use chunking. RL training auto-sets this to 2048 if not specified (except when impl='liger_kernel').",
),
] = None
@model_validator(mode="after")
def _map_model_name_for_moe(self):
"""Map model name if it exists in MOE_MODEL_MAPS."""
@@ -265,6 +273,15 @@ class ModelConfig(BaseConfig):
self.ac = ActivationCheckpointConfig()
return self
@model_validator(mode="after")
def fused_lm_head_chunk_size_is_valid(self):
if self.fused_lm_head_chunk_size is not None:
low = 512
if self.fused_lm_head_chunk_size < low:
raise ValueError(f"Fused LM head chunk size must be greater than {low}")
return self
class TokenizerConfig(BaseConfig):
"""Configuration for the tokenizer."""
@@ -405,11 +422,19 @@ class CheckpointConfig(BaseConfig):
),
] = None
keep: Annotated[
keep_last: Annotated[
int | None,
Field(
ge=1,
description="Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints.",
description="Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency.",
),
] = None
keep_interval: Annotated[
int | None,
Field(
ge=1,
description="Keep checkpoints at every N steps permanently (e.g., keep_interval=100 keeps step 100, 200, ...). If None, no interval-based keeping.",
),
] = None
+32 -13
View File
@@ -6,6 +6,8 @@ import torch.nn as nn
from prime_rl.trainer.config import LoRAConfig
from prime_rl.trainer.models.layers.lora import MultiLoRALinear, MultiLoRAModule
from prime_rl.trainer.models.layers.lora.multi_moe import MultiLoRAGroupedExperts
from prime_rl.trainer.models.layers.moe import GroupedExperts
from prime_rl.trainer.runs import get_runs
from prime_rl.utils.logger import get_logger
@@ -66,11 +68,14 @@ def _find_target_modules(model: nn.Module, target_patterns: List[str]) -> List[s
Patterns can be simple module names (e.g., "q_proj") or regex patterns
(e.g., r".*\\.q_proj$"). Simple names match any component in the module path.
Supports both nn.Linear layers and GroupedExperts (MoE) modules.
"""
target_modules = []
for name, module in model.named_modules():
if not isinstance(module, nn.Linear):
# Check if module is Linear or GroupedExperts
if not (isinstance(module, nn.Linear) or isinstance(module, GroupedExperts)):
continue
for pattern in target_patterns:
@@ -155,19 +160,32 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
for module_name in target_modules:
base_module = _get_module_by_name(model, module_name)
if not isinstance(base_module, nn.Linear):
logger.warning(f"Module {module_name} is not nn.Linear, skipping")
# Handle Linear layers
if isinstance(base_module, nn.Linear):
lora_module = MultiLoRALinear(
base_layer=base_module,
rank=config.rank,
n_adapters=n_loras,
alpha=config.alpha,
dropout=config.dropout,
)
# Handle GroupedExperts (MoE)
elif isinstance(base_module, GroupedExperts):
lora_module = MultiLoRAGroupedExperts(
base_layer=base_module,
rank=config.rank,
n_adapters=n_loras,
alpha=config.alpha,
dropout=config.dropout,
)
else:
logger.warning(
f"Module {module_name} is type {type(base_module).__name__}, "
f"expected nn.Linear or GroupedExperts. Skipping."
)
continue
lora_module = MultiLoRALinear(
base_layer=base_module,
rank=config.rank,
n_adapters=n_loras,
alpha=config.alpha,
dropout=config.dropout,
)
lora_module.register_with_runs(get_runs(), module_name)
_set_module_by_name(model, module_name, lora_module)
freeze_all_except_lora_and_specified(model, config)
@@ -179,8 +197,9 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
lora_adapted_params = 0
for name, module in model.named_modules():
if isinstance(module, MultiLoRAModule):
lora_adapter_params += module.lora_A[0].numel() + module.lora_B[0].numel()
lora_adapted_params += module.base_layer.weight.numel()
adapter_params, adapted_params = module.get_lora_param_counts()
lora_adapter_params += adapter_params
lora_adapted_params += adapted_params
fully_trainable = trainable_params - lora_adapter_params
adapted_or_trainable = lora_adapted_params + fully_trainable
+25 -5
View File
@@ -7,7 +7,7 @@ import torch
import torch.nn as nn
from beartype import beartype as typechecker
from huggingface_hub import snapshot_download
from jaxtyping import Float, Int, jaxtyped
from jaxtyping import Int, jaxtyped
from liger_kernel.transformers import AutoLigerKernelForCausalLM
from torch import Tensor
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_wrapper
@@ -20,7 +20,14 @@ from transformers.utils.import_utils import is_flash_attn_3_available
from prime_rl.trainer.config import ActivationCheckpointConfig, CompileConfig, ModelConfig, TokenizerConfig
from prime_rl.trainer.lora import apply_lora_to_model, strip_lora_from_state_dict
from prime_rl.trainer.models import AutoModelForCausalLMPrimeRL, PreTrainedModelPrimeRL, supports_custom_impl
from prime_rl.trainer.models import (
AutoModelForCausalLMPrimeRL,
PreTrainedModelPrimeRL,
PrimeLmOutput,
cast_float_and_contiguous,
supports_custom_impl,
)
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.parallel_dims import ParallelDims
from prime_rl.trainer.weights import (
load_state_dict,
@@ -341,6 +348,7 @@ def setup_model(
# 1. We load to meta device by default
model = get_model(config, device=torch.device("meta"), dtype=DTYPE_MAP[config.optimization_dtype])
possible_to_load_to_meta = can_reinit_empty_buffers(model)
if config.debug.random_init and not possible_to_load_to_meta:
@@ -353,6 +361,8 @@ def setup_model(
logger.warning("Cannot load model to meta device only, loading to CPU instead.")
model = get_model(config, device=torch.device("cpu"), dtype=DTYPE_MAP[config.optimization_dtype])
inject_prime_lm_head(model, chunk_size=config.fused_lm_head_chunk_size)
# Apply LoRA before FSDP setup
if config.lora is not None:
apply_lora_to_model(model, config.lora)
@@ -388,6 +398,16 @@ def setup_model(
@jaxtyped(typechecker=typechecker)
def forward(
model: nn.Module, input_ids: Int[Tensor, "batch seq"], position_ids: Int[Tensor, "batch seq"]
) -> Float[Tensor, "batch seq vocab"]:
return model(input_ids=input_ids, position_ids=position_ids).logits
model: nn.Module,
input_ids: Int[Tensor, "batch seq"],
position_ids: Int[Tensor, "batch seq"],
labels: Int[Tensor, "batch seq"] | None = None,
temperature: float | None = None,
) -> PrimeLmOutput:
out = model(input_ids=input_ids, position_ids=position_ids, labels=labels, temperature=temperature)
# PrimeLmOutput is a TypedDict (dict at runtime), HF outputs are dataclass-like objects
if isinstance(out, dict):
return cast_float_and_contiguous(out)
return cast_float_and_contiguous(PrimeLmOutput(logits=out.logits))
+5 -1
View File
@@ -8,17 +8,21 @@ from transformers.models.auto.auto_factory import _BaseAutoModelClass, _LazyAuto
from transformers.models.auto.configuration_auto import CONFIG_MAPPING_NAMES
from transformers.models.llama.configuration_llama import LlamaConfig
from prime_rl.trainer.models.afmoe import AfmoeConfig, AfmoeForCausalLM
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.glm4_moe import Glm4MoeConfig, Glm4MoeForCausalLM
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput, cast_float_and_contiguous
from prime_rl.trainer.models.llama import LlamaForCausalLM
from prime_rl.trainer.models.qwen3_moe import Qwen3MoeConfig, Qwen3MoeForCausalLM
# Make custom config discoverable by AutoConfig
AutoConfig.register("afmoe", AfmoeConfig, exist_ok=True)
AutoConfig.register("glm4_moe", Glm4MoeConfig, exist_ok=True)
AutoConfig.register("qwen3_moe", Qwen3MoeConfig, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING = _LazyAutoMapping(CONFIG_MAPPING_NAMES, OrderedDict())
_CUSTOM_CAUSAL_LM_MAPPING.register(LlamaConfig, LlamaForCausalLM, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING.register(AfmoeConfig, AfmoeForCausalLM, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING.register(Glm4MoeConfig, Glm4MoeForCausalLM, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3MoeConfig, Qwen3MoeForCausalLM, exist_ok=True)
@@ -42,4 +46,4 @@ def supports_custom_impl(model_config: PretrainedConfig) -> bool:
return type(model_config) in _CUSTOM_CAUSAL_LM_MAPPING
__all__ = ["AutoModelForCausalLMPrimeRL", "PreTrainedModelPrimeRL", "supports_custom_impl"]
__all__ = ["AutoModelForCausalLMPrimeRL", "PreTrainedModelPrimeRL", "supports_custom_impl", "PrimeLmOutput", "cast_float_and_contiguous"]
@@ -0,0 +1,14 @@
from prime_rl.trainer.models.afmoe.configuration_afmoe import AfmoeConfig
from prime_rl.trainer.models.afmoe.modeling_afmoe import (
AfmoeForCausalLM,
AfmoeModel,
AfmoePreTrainedModel,
)
__all__ = [
"AfmoeConfig",
"AfmoeForCausalLM",
"AfmoeModel",
"AfmoePreTrainedModel",
]
@@ -0,0 +1,113 @@
from transformers.configuration_utils import PretrainedConfig, layer_type_validation
from transformers.modeling_rope_utils import rope_config_validation
from transformers.utils import logging
logger = logging.get_logger(__name__)
class AfmoeConfig(PretrainedConfig):
"""Configuration for AFMoE."""
model_type = "afmoe"
base_model_pp_plan = {
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
"norm": (["hidden_states"], ["hidden_states"]),
}
def __init__(
self,
num_hidden_layers: int = 32,
vocab_size: int = 200192,
hidden_size: int = 2048,
intermediate_size: int = 6144,
moe_intermediate_size=1408,
num_dense_layers=1,
num_attention_heads=16,
num_key_value_heads=None,
head_dim=128,
hidden_act="silu",
max_position_embeddings=16384,
initializer_range=0.02,
rms_norm_eps=1e-5,
use_cache=True,
tie_word_embeddings=False,
rope_theta=10000.0,
rope_scaling=None,
num_experts=64,
num_experts_per_tok=6,
num_shared_experts=2,
num_expert_groups=1,
num_limited_groups=1,
score_func="sigmoid",
route_norm=True,
route_scale=1.0,
score_before_experts: bool = False,
load_balance_coeff: float | None = None,
use_grouped_mm: bool = True,
global_attn_every_n_layers=4,
sliding_window=1024,
mup_enabled=False,
layer_types=None,
attention_dropout: float = 0.0,
n_group: int = 1,
topk_group: int = 1,
**kwargs,
):
self.vocab_size = vocab_size
self.max_position_embeddings = max_position_embeddings
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.num_hidden_layers = num_hidden_layers
self.num_dense_layers = num_dense_layers
self.num_attention_heads = num_attention_heads
self.head_dim = head_dim
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.rms_norm_eps = rms_norm_eps
self.use_cache = use_cache
self.rope_theta = rope_theta
self.rope_scaling = rope_scaling
# MoE specific
self.moe_intermediate_size = moe_intermediate_size
self.num_experts_per_tok = num_experts_per_tok
self.n_group = n_group
self.topk_group = topk_group
self.num_experts = num_experts
self.num_shared_experts = num_shared_experts
self.num_expert_groups = num_expert_groups
self.num_limited_groups = num_limited_groups
self.score_func = score_func
self.route_norm = route_norm
self.route_scale = route_scale
self.score_before_experts = score_before_experts
self.load_balance_coeff = load_balance_coeff
self.use_grouped_mm = use_grouped_mm
# Attention specific
self.attention_dropout = attention_dropout
self.global_attn_every_n_layers = global_attn_every_n_layers
self.sliding_window = sliding_window
self.layer_types = layer_types
if self.layer_types is None:
self.layer_types = [
"sliding_attention" if bool((i + 1) % global_attn_every_n_layers) else "full_attention" for i in range(self.num_hidden_layers)
]
layer_type_validation(self.layer_types)
# muP specific
self.mup_enabled = mup_enabled
if num_key_value_heads is None:
num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
# Validate rope configs
if self.rope_scaling is not None and "type" in self.rope_scaling:
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
rope_config_validation(self)
super().__init__(
tie_word_embeddings=tie_word_embeddings,
**kwargs,
)
__all__ = ["AfmoeConfig"]
@@ -0,0 +1,147 @@
import re
import torch
from torch import Tensor
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."""
pattern = re.compile(rf"model\.layers\.{layer_idx}\.mlp\.experts\.(\d+)\.")
expert_indices = set()
for key in state_dict.keys():
match = pattern.search(key)
if match:
expert_indices.add(int(match.group(1)))
return len(expert_indices)
def is_moe_layer_hf(state_dict: dict[str, Tensor], layer_idx: int) -> bool:
"""Check if a layer is a MoE layer in HF format."""
return any(f"model.layers.{layer_idx}.mlp.experts." in k for k in state_dict.keys())
def is_moe_layer_tt(state_dict: dict[str, Tensor], layer_idx: int) -> bool:
"""Check if a layer is a MoE layer in TT format."""
return f"model.layers.{layer_idx}.mlp.experts.w1" in state_dict
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int) -> None:
"""Convert a single MoE layer from HF format to TT format in-place.
Args:
state_dict: The state dict to modify in-place.
layer_idx: The layer index to convert.
"""
prefix = f"model.layers.{layer_idx}.mlp"
# Check if this is a MoE layer (has individual experts)
is_moe_layer = is_moe_layer_hf(state_dict, layer_idx)
if not is_moe_layer:
return # Dense layer, no conversion needed
num_experts = get_num_experts_from_state_dict(state_dict, layer_idx)
if num_experts == 0:
return
# Convert shared experts: shared_experts -> shared_expert, gate_proj/up_proj/down_proj -> w1/w3/w2
shared_mappings = [
(f"{prefix}.shared_experts.gate_proj.weight", f"{prefix}.shared_expert.w1"),
(f"{prefix}.shared_experts.down_proj.weight", f"{prefix}.shared_expert.w2"),
(f"{prefix}.shared_experts.up_proj.weight", f"{prefix}.shared_expert.w3"),
]
for hf_key, tt_key in shared_mappings:
if hf_key in state_dict:
state_dict[tt_key] = state_dict.pop(hf_key)
# Stack individual expert weights into grouped format
# HF: experts.{i}.gate_proj.weight [hidden_dim, hidden_size]
# TT: experts.w1 [num_experts, hidden_dim, hidden_size]
expert_mappings = [
("gate_proj", "w1"),
("down_proj", "w2"),
("up_proj", "w3"),
]
for hf_name, tt_name in expert_mappings:
expert_weights = []
for i in range(num_experts):
hf_key = f"{prefix}.experts.{i}.{hf_name}.weight"
if hf_key in state_dict:
expert_weights.append(state_dict.pop(hf_key))
if expert_weights:
# Stack along first dimension: [num_experts, out_dim, in_dim]
stacked = torch.stack(expert_weights, dim=0)
state_dict[f"{prefix}.experts.{tt_name}"] = stacked
def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_idx: int) -> None:
"""Convert a single MoE layer from TT format to HF format in-place.
Args:
state_dict: The state dict to modify in-place.
layer_idx: The layer index to convert.
"""
prefix = f"model.layers.{layer_idx}.mlp"
# Check if this is a MoE layer in TT format
if not is_moe_layer_tt(state_dict, layer_idx):
return # Dense layer, no conversion needed
# Convert shared expert: shared_expert -> shared_experts, w1/w2/w3 -> gate_proj/down_proj/up_proj
shared_mappings = [
(f"{prefix}.shared_expert.w1", f"{prefix}.shared_experts.gate_proj.weight"),
(f"{prefix}.shared_expert.w2", f"{prefix}.shared_experts.down_proj.weight"),
(f"{prefix}.shared_expert.w3", f"{prefix}.shared_experts.up_proj.weight"),
]
for tt_key, hf_key in shared_mappings:
if tt_key in state_dict:
state_dict[hf_key] = state_dict.pop(tt_key)
# Unstack grouped expert weights into individual experts
expert_mappings = [
("w1", "gate_proj"),
("w2", "down_proj"),
("w3", "up_proj"),
]
for tt_name, hf_name in expert_mappings:
tt_key = f"{prefix}.experts.{tt_name}"
if tt_key in state_dict:
stacked = state_dict.pop(tt_key)
num_experts = stacked.shape[0]
for i in range(num_experts):
hf_key = f"{prefix}.experts.{i}.{hf_name}.weight"
state_dict[hf_key] = stacked[i]
# Remove TT-specific buffers that don't exist in HF
for key in list(state_dict.keys()):
if f"{prefix}.tokens_per_expert" in key:
del state_dict[key]
if f"{prefix}.reorderer" in key:
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):
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):
convert_tt_layer_to_hf(state_dict, layer_idx)
@@ -0,0 +1,484 @@
from dataclasses import dataclass
from typing import Optional, Union
import torch
import torch.nn.functional as F
from torch import nn
from transformers.cache_utils import Cache
from transformers.generation import GenerationMixin
from transformers.masking_utils import (
create_causal_mask,
create_sliding_window_causal_mask,
)
from transformers.modeling_layers import GradientCheckpointingLayer
from transformers.modeling_outputs import (
MoeModelOutputWithPast,
)
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.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
from prime_rl.trainer.models.layers.rotary_emb import (
RotaryEmbedding,
RotaryEmbeddingConfig,
apply_rotary_pos_emb,
)
from .configuration_afmoe import AfmoeConfig
from .converting_afmoe import (
convert_hf_layer_to_tt,
convert_hf_to_tt_moe,
convert_tt_layer_to_hf,
convert_tt_to_hf_moe,
)
@dataclass
class AfmoeAttentionConfig:
"""Configuration for AFMoE attention layers."""
hidden_size: int
head_dim: int
num_attention_heads: int
num_key_value_heads: int
rms_norm_eps: float
is_local_attention: bool
sliding_window: int | None = None
attention_dropout: float = 0.0
def _repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
"""Repeat KV heads to match query heads for GQA."""
if n_rep == 1:
return hidden_states
batch, num_kv_heads, slen, head_dim = hidden_states.shape
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_kv_heads, n_rep, slen, head_dim)
return hidden_states.reshape(batch, num_kv_heads * n_rep, slen, head_dim)
class AfmoeAttentionBase(nn.Module):
def __init__(self, config: AfmoeAttentionConfig):
super().__init__()
self.head_dim = config.head_dim
self.num_heads = config.num_attention_heads
self.num_key_value_heads = config.num_key_value_heads
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
self.scaling = self.head_dim**-0.5
self.is_local_attention = config.is_local_attention
self.sliding_window = config.sliding_window if config.is_local_attention else None
self.attention_dropout = config.attention_dropout
# Projections
self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=False)
self.k_proj = nn.Linear(config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
self.v_proj = nn.Linear(config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
self.o_proj = nn.Linear(self.num_heads * self.head_dim, config.hidden_size, bias=False)
# Output gating
self.gate_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=False)
# QK normalization
self.q_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
self.k_norm = RMSNorm(RMSNormConfig(hidden_size=self.head_dim, eps=config.rms_norm_eps))
def _project_states(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, tuple[int, ...]]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states = self.q_proj(hidden_states).view(hidden_shape)
key_states = self.k_proj(hidden_states).view(hidden_shape)
value_states = self.v_proj(hidden_states).view(hidden_shape)
gate_states = self.gate_proj(hidden_states)
query_states = self.q_norm(query_states)
key_states = self.k_norm(key_states)
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
value_states = value_states.transpose(1, 2)
if self.is_local_attention:
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
key_states = _repeat_kv(key_states, self.num_key_value_groups)
value_states = _repeat_kv(value_states, self.num_key_value_groups)
return query_states, key_states, value_states, gate_states, input_shape
def _finalize_output(
self,
attn_output: torch.Tensor,
gate_states: torch.Tensor,
input_shape: tuple[int, ...],
) -> tuple[torch.Tensor, None]:
attn_output = attn_output.transpose(1, 2).contiguous()
attn_output = attn_output.view(*input_shape, -1)
attn_output = attn_output * torch.sigmoid(gate_states)
attn_output = self.o_proj(attn_output)
return attn_output, None
class AfmoeSDPAAttention(AfmoeAttentionBase):
"""AFMoE attention using PyTorch's scaled_dot_product_attention."""
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
attention_mask: torch.Tensor | None = None,
) -> tuple[torch.Tensor, None]:
query_states, key_states, value_states, gate_states, input_shape = self._project_states(
hidden_states, position_embeddings
)
dropout_p = self.attention_dropout if self.training else 0.0
attn_output = F.scaled_dot_product_attention(
query_states,
key_states,
value_states,
attn_mask=attention_mask,
dropout_p=dropout_p,
is_causal=attention_mask is None, # Use causal if no explicit mask
scale=self.scaling,
)
return self._finalize_output(attn_output, gate_states, input_shape)
AFMOE_ATTN_IMPL2CLASS = {
"sdpa": AfmoeSDPAAttention,
}
def _create_rotary_emb(config: AfmoeConfig) -> RotaryEmbedding:
if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type", "default"))
else:
rope_type = "default"
rotary_config = RotaryEmbeddingConfig(
max_position_embeddings=config.max_position_embeddings,
rope_type=rope_type,
model_config=config,
)
return RotaryEmbedding(rotary_config)
def _get_afmoe_attention(config: AfmoeConfig, layer_idx: int) -> nn.Module:
is_local = config.layer_types[layer_idx] == "sliding_attention"
attn_config = AfmoeAttentionConfig(
hidden_size=config.hidden_size,
head_dim=getattr(config, "head_dim", config.hidden_size // config.num_attention_heads),
num_attention_heads=config.num_attention_heads,
num_key_value_heads=config.num_key_value_heads,
rms_norm_eps=config.rms_norm_eps,
is_local_attention=is_local,
sliding_window=config.sliding_window if is_local else None,
attention_dropout=config.attention_dropout,
)
attn_impl = config._attn_implementation
if attn_impl == "eager":
attn_impl = "sdpa"
if attn_impl not in AFMOE_ATTN_IMPL2CLASS:
supported = list(AFMOE_ATTN_IMPL2CLASS.keys())
raise ValueError(
f"AFMoE attention does not support '{config._attn_implementation}'. "
f"Supported implementations: {supported}. "
f"Note: flash_attention is not supported for AFMoE due to sliding window + RoPE constraints."
)
return AFMOE_ATTN_IMPL2CLASS[attn_impl](attn_config)
class AfmoeDecoderLayer(GradientCheckpointingLayer):
def __init__(self, config: AfmoeConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.layer_idx = layer_idx
self.self_attn = _get_afmoe_attention(config, layer_idx)
self.attention_type = config.layer_types[layer_idx]
self.input_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
self.post_attention_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
self.pre_mlp_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
self.post_mlp_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
self.moe_enabled = layer_idx >= config.num_dense_layers
mlp_config = MLPConfig(
hidden_size=config.hidden_size,
intermediate_size=config.intermediate_size,
gate_act=config.hidden_act,
bias=False,
)
moe_args = MoEArgs(
num_experts=config.num_experts,
num_shared_experts=config.num_shared_experts,
score_func=config.score_func,
route_norm=config.route_norm,
route_scale=config.route_scale,
score_before_experts=getattr(config, "score_before_experts", False),
top_k=config.num_experts_per_tok,
use_grouped_mm=getattr(config, "use_grouped_mm", True),
load_balance_coeff=getattr(config, "load_balance_coeff", None),
)
if self.moe_enabled:
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
else:
self.mlp = MLP(mlp_config)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
) -> torch.FloatTensor:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
hidden_states, _ = self.self_attn(
hidden_states=hidden_states,
position_embeddings=position_embeddings,
attention_mask=attention_mask,
)
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = residual + hidden_states
residual = hidden_states
hidden_states = self.pre_mlp_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = self.post_mlp_layernorm(hidden_states)
hidden_states = residual + hidden_states
return hidden_states
class AfmoePreTrainedModel(PreTrainedModelPrimeRL):
config_class = AfmoeConfig
base_model_prefix = "model"
_no_split_modules = ["AfmoeDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_keep_in_fp32_modules = [
"input_layernorm",
"post_attention_layernorm",
"pre_mlp_layernorm",
"post_mlp_layernorm",
"q_norm",
"k_norm",
"norm",
]
_supports_sdpa = True
_supports_flash_attn = False
_supports_flex_attn = False
_supports_attention_backend = True
_can_compile_fullgraph = False
_can_record_outputs = {
"hidden_states": AfmoeDecoderLayer,
}
supports_gradient_checkpointing = True
@classmethod
def is_hf_state_dict(cls, state_dict: dict[str, torch.Tensor]) -> bool:
return any("mlp.experts.1.up_proj" in module_name for module_name in state_dict.keys())
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, torch.Tensor]) -> bool:
return any("mlp.experts.w1" in module_name for module_name in state_dict.keys())
@classmethod
def convert_to_hf(cls, state_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
convert_tt_to_hf_moe(state_dict)
return state_dict
@classmethod
def convert_to_prime(cls, state_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
convert_hf_to_tt_moe(state_dict)
return state_dict
@classmethod
def convert_layer_to_hf(cls, state_dict: dict[str, torch.Tensor], layer_idx: int) -> dict[str, torch.Tensor]:
convert_tt_layer_to_hf(state_dict, layer_idx)
return state_dict
@classmethod
def convert_layer_to_prime(cls, state_dict: dict[str, torch.Tensor], layer_idx: int) -> dict[str, torch.Tensor]:
convert_hf_layer_to_tt(state_dict, layer_idx)
return state_dict
class AfmoeModel(AfmoePreTrainedModel):
_no_split_modules = ["AfmoeDecoderLayer"]
def __init__(self, config: AfmoeConfig):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
self.layers = nn.ModuleList(
[AfmoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
)
self.norm = RMSNorm(RMSNormConfig(hidden_size=config.hidden_size, eps=config.rms_norm_eps))
self.rotary_emb = _create_rotary_emb(config)
self.gradient_checkpointing = False
self.post_init()
def get_input_embeddings(self):
return self.embed_tokens
def set_input_embeddings(self, value):
self.embed_tokens = value
def forward(
self,
input_ids: torch.LongTensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
) -> MoeModelOutputWithPast:
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
if position_ids is None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
cache_position = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device)
if not isinstance(causal_mask_mapping := attention_mask, dict):
mask_kwargs = {
"config": self.config,
"input_embeds": inputs_embeds,
"attention_mask": attention_mask,
"cache_position": cache_position,
"past_key_values": None,
"position_ids": position_ids,
}
causal_mask_mapping = {
"full_attention": create_causal_mask(**mask_kwargs),
"sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
}
hidden_states = inputs_embeds
if self.config.mup_enabled:
hidden_states = hidden_states * (self.config.hidden_size**0.5)
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for decoder_layer in self.layers:
mask = causal_mask_mapping[decoder_layer.attention_type]
hidden_states = decoder_layer(
hidden_states,
attention_mask=mask,
position_embeddings=position_embeddings,
)
hidden_states = self.norm(hidden_states)
return MoeModelOutputWithPast(
last_hidden_state=hidden_states,
)
class AfmoeForCausalLM(AfmoePreTrainedModel, GenerationMixin):
_tied_weights_keys = ["lm_head.weight"]
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config):
super().__init__(config)
self.model = AfmoeModel(config)
self.vocab_size = config.vocab_size
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self):
return self.model.embed_tokens
def set_input_embeddings(self, value):
self.model.embed_tokens = value
def get_output_embeddings(self):
return self.lm_head
def set_output_embeddings(self, new_embeddings):
self.lm_head = new_embeddings
def set_decoder(self, decoder):
self.model = decoder
def get_decoder(self):
return self.model
def forward(
self,
input_ids: torch.LongTensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
token_type_ids: Optional[torch.Tensor] = None, # will be ignored
temperature: Optional[float] = 1.0,
**kwargs: Unpack[TransformersKwargs],
) -> PrimeLmOutput:
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels used by PrimeRL's wrapped LM head to optionally compute per-token logprobs/entropy.
If not provided, the wrapped LM head returns logits only.
temperature (`float`, *optional*, defaults to 1.0):
Temperature used for the logprobs/entropy computation when `labels` are provided.
"""
assert use_cache is None, "use_cache is not supported for custom afmoe for now"
assert past_key_values is None, "past_key_values is not supported for custom afmoe for now"
outputs: MoeModelOutputWithPast = self.model(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
)
hidden_states = outputs.last_hidden_state
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
return self.lm_head(
hidden_states[:, slice_indices, :],
labels[:, slice_indices] if labels is not None else None,
temperature=temperature,
)
def init_buffers_post_meta(self):
buffer_names = [name for name, _ in self.named_buffers()]
if "model.rotary_emb.inv_freq" in buffer_names:
rotary_emb = self.model.rotary_emb
inv_freq, rotary_emb.attention_scaling = rotary_emb.rope_init_fn(
rotary_emb.config, rotary_emb.inv_freq.device
)
rotary_emb.inv_freq.copy_(inv_freq)
__all__ = [
"AfmoeForCausalLM",
"AfmoeModel",
"AfmoePreTrainedModel",
]
@@ -20,7 +20,7 @@ from torch import Tensor, nn
from transformers.cache_utils import Cache
from transformers.generation import GenerationMixin
from transformers.modeling_layers import GradientCheckpointingLayer
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
from transformers.modeling_outputs import BaseModelOutputWithPast
from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs, auto_docstring
from transformers.utils.deprecation import deprecate_kwarg
@@ -34,6 +34,7 @@ from prime_rl.trainer.models.glm4_moe.converting_glm4_moe import (
convert_tt_to_hf_moe,
)
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
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
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
@@ -263,9 +264,16 @@ class Glm4MoeForCausalLM(Glm4MoePreTrainedModel, GenerationMixin):
use_cache: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
temperature: Optional[float] = 1.0,
**kwargs: Unpack[TransformersKwargs],
) -> CausalLMOutputWithPast:
) -> PrimeLmOutput:
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels used by PrimeRL's wrapped LM head to optionally compute per-token logprobs/entropy.
If not provided, the wrapped LM head returns logits only.
temperature (`float`, *optional*, defaults to 1.0):
Temperature used for the logprobs/entropy computation when `labels` are provided.
Example:
```python
@@ -300,18 +308,10 @@ class Glm4MoeForCausalLM(Glm4MoePreTrainedModel, GenerationMixin):
hidden_states = outputs.last_hidden_state
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
logits = self.lm_head(hidden_states[:, slice_indices, :])
loss = None
if labels is not None:
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
return CausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
return self.lm_head(
hidden_states[:, slice_indices, :],
labels[:, slice_indices] if labels is not None else None,
temperature=temperature,
)
def init_buffers_post_meta(self):
@@ -0,0 +1,265 @@
from __future__ import annotations
import types
from typing import TypedDict
import torch
import torch.nn as nn
from torch import Tensor
from prime_rl.utils.logger import get_logger
class PrimeLmOutput(TypedDict, total=False):
"""Output from LM head - a TypedDict so pytree can find tensors for FSDP2 hooks."""
logits: Tensor | None
logprobs: Tensor | None
entropy: Tensor | None
def cast_float_and_contiguous(output: PrimeLmOutput) -> PrimeLmOutput:
"""Convert tensors in PrimeLmOutput to float and make contiguous."""
def _float_and_contiguous(tensor: Tensor | None) -> Tensor | None:
return tensor.float().contiguous() if tensor is not None else None
return PrimeLmOutput(
logits=_float_and_contiguous(output.get("logits")),
logprobs=_float_and_contiguous(output.get("logprobs")),
entropy=_float_and_contiguous(output.get("entropy")),
)
class FusedOutputLinear(torch.nn.Linear):
def __init__(self, in_features: int, out_features: int, chunk_size: int):
super().__init__(in_features, out_features, bias=False)
self.chunk_size = chunk_size
def forward(
self,
hidden_states: torch.Tensor,
labels: torch.Tensor | None = None,
temperature: float = 1.0,
) -> PrimeLmOutput:
assert labels is not None, "FusedOutputLinear requires labels for chunked logprob computation"
inv_t = 1.0 / float(temperature)
b, s, h = hidden_states.shape
hidden_states = hidden_states.reshape(b * s, h).contiguous()
labels = labels.reshape(b * s).contiguous()
logprobs, entropy = _ChunkedLogProbEntropyFn.apply(hidden_states, self.weight, labels, inv_t, self.chunk_size)
logprobs = logprobs.reshape(b, s)
entropy = entropy.reshape(b, s)
return PrimeLmOutput(logprobs=logprobs, entropy=entropy)
class VanillaOutputLinear(torch.nn.Linear):
def __init__(self, in_features: int, out_features: int):
super().__init__(in_features, out_features, bias=False)
def forward(
self, hidden_states: torch.Tensor, labels: torch.Tensor | None = None, temperature: float = 1.0
) -> PrimeLmOutput:
return PrimeLmOutput(logits=super().forward(hidden_states))
class _ChunkedLogProbEntropyFn(torch.autograd.Function):
@staticmethod
def forward( # type: ignore[override]
ctx,
hidden: torch.Tensor, # [N, H]
weight: torch.Tensor, # [V, H]
labels: torch.Tensor, # [N]
inv_temperature: float,
chunk_size: int,
) -> tuple[torch.Tensor, torch.Tensor]:
"""
Returns (per-token logprobs, per-token entropy) without materializing [N, V].
Important: entropy is computed from the *same* per-chunk logits used for the softmax
normalization (no extra W @ hidden matmul).
"""
assert hidden.dim() == 2, f"expected hidden [N,H], got {tuple(hidden.shape)}"
assert weight.dim() == 2, f"expected weight [V,H], got {tuple(weight.shape)}"
assert labels.dim() == 1, f"expected labels [N], got {tuple(labels.shape)}"
assert hidden.shape[0] == labels.shape[0], "hidden/labels N mismatch"
assert hidden.shape[1] == weight.shape[1], "hidden/weight H mismatch"
assert chunk_size > 0
device = hidden.device
n = hidden.shape[0]
vocab = weight.shape[0]
# Running stats in fp32.
m = torch.full((n,), float("-inf"), device=device, dtype=torch.float32)
s = torch.zeros((n,), device=device, dtype=torch.float32)
t = torch.zeros((n,), device=device, dtype=torch.float32)
target_logits = torch.zeros((n,), device=device, dtype=torch.float32)
for start in range(0, vocab, chunk_size):
end = min(start + chunk_size, vocab)
w_chunk = weight[start:end] # [C, H]
logits = hidden @ w_chunk.t() # [N, C] (model dtype)
logits_f = logits.to(torch.float32).mul_(inv_temperature) # [N, C] fp32
# Shared intermediates for logZ and entropy stats.
m, s, t = _online_logsumexp_and_weighted_update(m, s, t, logits_f)
# Fill target logits for labels that fall in this chunk.
mask = (labels >= start) & (labels < end)
if torch.any(mask):
idx = (labels[mask] - start).to(torch.long)
target_logits[mask] = logits_f[mask, idx]
logz = m + torch.log(s)
logprobs = target_logits - logz
entropy = logz - (t / s)
# Save for backward (recompute logits per chunk for grad)
ctx.save_for_backward(hidden, weight, labels, logz)
ctx.inv_temperature = inv_temperature
ctx.chunk_size = chunk_size
# Return fp32 for numerical stability (matching baseline behavior).
return logprobs, entropy
@staticmethod
def backward(ctx, grad_logprobs: torch.Tensor, grad_entropy: torch.Tensor | None):
assert grad_entropy is None or torch.all(grad_entropy == 0.0), (
"Backward through entropy is not implemented in FusedOutputLinear"
)
hidden, weight, labels, logz = ctx.saved_tensors
inv_temperature: float = ctx.inv_temperature
chunk_size: int = ctx.chunk_size
n, h = hidden.shape
vocab = weight.shape[0]
grad_hidden = torch.zeros_like(hidden)
grad_weight = torch.zeros_like(weight)
g = grad_logprobs.to(torch.float32) # [N] fp32 for stable scaling
for start in range(0, vocab, chunk_size):
end = min(start + chunk_size, vocab)
w_chunk = weight[start:end] # [C, H]
logits = hidden @ w_chunk.t() # [N, C] (model dtype)
logits_f = logits.to(torch.float32).mul_(inv_temperature) # [N, C] fp32
# p = softmax(logits_f) chunk = exp(logits_f - logz)
p = torch.exp(logits_f - logz.unsqueeze(-1)) # [N, C] fp32
# dL/dlogits = g * (1_{label} - p)
grad_logits = (-g).unsqueeze(-1) * p # [N, C] fp32
mask = (labels >= start) & (labels < end)
if torch.any(mask):
idx = (labels[mask] - start).to(torch.long)
grad_logits[mask, idx] += g[mask]
# Chain through temperature scaling: logits_f = logits * inv_temperature
grad_logits.mul_(inv_temperature)
grad_hidden.add_(grad_logits.to(hidden.dtype) @ w_chunk)
grad_w_chunk = grad_logits.to(weight.dtype).t() @ hidden # [C, H]
grad_weight[start:end].add_(grad_w_chunk)
return grad_hidden, grad_weight, None, None, None
def _online_logsumexp_and_weighted_update(
m: torch.Tensor, s: torch.Tensor, t: torch.Tensor, chunk_logits: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""
Online logsumexp + weighted-sum accumulator for entropy.
Maintains:
m: running max
s: running sum(exp(x - m))
t: running sum(exp(x - m) * x)
"""
chunk_m = torch.amax(chunk_logits, dim=-1) # [N]
m_new = torch.maximum(m, chunk_m) # [N]
exp_old = torch.exp(m - m_new)
chunk_exp = torch.exp(chunk_logits - m_new.unsqueeze(-1)) # [N, C]
s_new = s * exp_old + chunk_exp.sum(dim=-1)
t_new = t * exp_old + (chunk_exp * chunk_logits).sum(dim=-1)
return m_new, s_new, t_new
def inject_prime_lm_head(model: nn.Module, chunk_size: int | None = None) -> None:
"""
Inject a PrimeRL LM head (FusedOutputLinear or VanillaOutputLinear) into a model.
This replaces the model's lm_head and overrides the forward method to use labels
and temperature for chunked loss computation.
Args:
model: The model to wrap.
chunk_size: If provided, use FusedOutputLinear with chunked logprob/entropy computation.
If None, use VanillaOutputLinear which just returns logits.
"""
# Guards so we have nicer error messages when a non-standard model is used
assert hasattr(model, "model"), f"model doesnt have backbone in model.model:\n{model}"
assert isinstance(model.model, nn.Module), f"model.model is not a nn.Module: {type(model.model)}\n{model}"
assert hasattr(model, "lm_head"), f"model doesnt have lm_head in model.lm_head:\n{model}"
assert isinstance(model.lm_head, nn.Linear), f"model.lm_head is not a nn.Linear: {type(model.lm_head)}\n{model}"
assert not hasattr(model.lm_head, "bias") or model.lm_head.bias is None, (
f"model.lm_head.bias is not supported: {model.lm_head}\n{model}"
)
logger = get_logger()
logger.info(f"Injecting Prime LM head with chunk size {chunk_size}")
# Replace the lm_head with the appropriate wrapper
old_lm_head = model.lm_head
if chunk_size is not None:
model.lm_head = FusedOutputLinear(
in_features=old_lm_head.in_features, out_features=old_lm_head.out_features, chunk_size=chunk_size
)
else:
model.lm_head = VanillaOutputLinear(in_features=old_lm_head.in_features, out_features=old_lm_head.out_features)
model.lm_head.weight = old_lm_head.weight
del old_lm_head
# Patch the forward method to use the new lm_head with labels and temperature
def new_forward(
self: nn.Module,
input_ids: torch.Tensor | None = None,
position_ids: torch.Tensor | None = None,
inputs_embeds: torch.Tensor | None = None,
labels: torch.Tensor | None = None,
logits_to_keep: int = 0,
temperature: float = 1.0,
**kwargs: object,
) -> PrimeLmOutput:
if position_ids is None:
reference_tensor = input_ids if input_ids is not None else inputs_embeds
position_ids = torch.arange(1, reference_tensor.shape[1] + 1, device=reference_tensor.device).unsqueeze(0)
outputs = self.model(
input_ids=input_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
**kwargs,
)
hidden_states = outputs.last_hidden_state
# Slice hidden states for logits_to_keep
slice_indices = (
slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) and logits_to_keep > 0 else slice(None)
)
# Pass through the wrapped lm_head
return self.lm_head(
hidden_states[:, slice_indices, :],
labels[:, slice_indices] if labels is not None else None,
temperature=temperature,
)
# Bind the new forward to the model
model.forward = types.MethodType(new_forward, model)
@@ -1,8 +1,19 @@
from prime_rl.trainer.models.layers.lora.base import MultiLoRAModule, set_multilora_offsets
from prime_rl.trainer.models.layers.lora.base import (
MultiLoRAModule,
get_lora_num_tokens,
get_multilora_scaling,
set_lora_num_tokens,
set_multilora_scaling,
)
from prime_rl.trainer.models.layers.lora.multi_linear import MultiLoRALinear
from prime_rl.trainer.models.layers.lora.multi_moe import MultiLoRAGroupedExperts
__all__ = [
"MultiLoRAModule",
"MultiLoRALinear",
"set_multilora_offsets",
"MultiLoRAGroupedExperts",
"set_lora_num_tokens",
"get_lora_num_tokens",
"set_multilora_scaling",
"get_multilora_scaling",
]
@@ -9,12 +9,65 @@ if TYPE_CHECKING:
_LORA_PREFIX = "base_layer."
# Global state for multilora - initialized once in train.py, referenced by modules
LORA_NUM_TOKENS: torch.Tensor | None = None # [n_adapters] token counts per adapter
SCALING_FACTORS: torch.Tensor | None = None # [max_runs] scaling factors per run
def set_multilora_offsets(offsets: torch.Tensor, reset_reference: bool = False) -> None:
"""Set offsets for all LoRA modules."""
from prime_rl.trainer.models.layers.lora.multi_linear import set_multilora_offsets as set_multilora_offsets_linear
set_multilora_offsets_linear(offsets, reset_reference)
def set_lora_num_tokens(num_tokens: torch.Tensor, reset_reference: bool = False) -> None:
"""Set the number of tokens per adapter.
Args:
num_tokens: Tensor of shape [n_adapters] with token counts per adapter.
reset_reference: If True, replace the tensor reference. If False, copy values in-place.
"""
global LORA_NUM_TOKENS
if LORA_NUM_TOKENS is None or reset_reference:
if SCALING_FACTORS is not None and num_tokens is not None:
assert num_tokens.shape == SCALING_FACTORS.shape, (
f"lora_num_tokens shape {num_tokens.shape} != scaling_factors shape {SCALING_FACTORS.shape}"
)
LORA_NUM_TOKENS = num_tokens
else:
LORA_NUM_TOKENS.copy_(num_tokens)
def get_lora_num_tokens() -> torch.Tensor:
"""Get the current lora_num_tokens tensor.
Raises:
AssertionError: If called before set_lora_num_tokens() has been called.
"""
assert LORA_NUM_TOKENS is not None, "LORA_NUM_TOKENS not initialized. Call set_lora_num_tokens() first."
return LORA_NUM_TOKENS
def set_multilora_scaling(scaling_factors: torch.Tensor, reset_reference: bool = False) -> None:
"""Set per-run scaling factors (alpha / rank).
Args:
scaling_factors: Tensor of shape [max_runs] with scaling factors per run.
reset_reference: If True, replace the tensor reference. If False, copy values in-place.
"""
global SCALING_FACTORS
if SCALING_FACTORS is None or reset_reference:
if LORA_NUM_TOKENS is not None and scaling_factors is not None:
assert scaling_factors.shape == LORA_NUM_TOKENS.shape, (
f"scaling_factors shape {scaling_factors.shape} != lora_num_tokens shape {LORA_NUM_TOKENS.shape}"
)
SCALING_FACTORS = scaling_factors
else:
SCALING_FACTORS.copy_(scaling_factors)
def get_multilora_scaling() -> torch.Tensor:
"""Get the current scaling factors tensor.
Raises:
AssertionError: If called before set_multilora_scaling() has been called.
"""
assert SCALING_FACTORS is not None, "SCALING_FACTORS not initialized. Call set_multilora_scaling() first."
return SCALING_FACTORS
class MultiLoRAModule(nn.Module):
@@ -23,8 +76,6 @@ class MultiLoRAModule(nn.Module):
"""
base_layer: nn.Module
lora_A: nn.ParameterList
lora_B: nn.ParameterList
def __init__(self, base_layer: nn.Module) -> None:
super().__init__()
@@ -61,6 +112,17 @@ class MultiLoRAModule(nn.Module):
"""
...
@abstractmethod
def get_lora_param_counts(self) -> tuple[int, int]:
"""Get the number of LoRA adapter parameters and adapted base parameters.
Returns:
A tuple of (adapter_params, adapted_params) where:
- adapter_params: Number of parameters in ONE LoRA adapter (lora_A + lora_B)
- adapted_params: Number of base layer parameters being adapted by LoRA
"""
...
def register_with_runs(self, runs: "Runs", prefix: str) -> None:
"""Register this module with the Runs system.
@@ -3,17 +3,7 @@ import math
import torch
from torch import nn
from prime_rl.trainer.models.layers.lora.base import MultiLoRAModule
OFFSETS: torch.Tensor | None = None
def set_multilora_offsets(offsets: torch.Tensor, reset_reference: bool = False) -> None:
global OFFSETS
if OFFSETS is None or reset_reference:
OFFSETS = offsets
else:
OFFSETS.copy_(offsets)
from prime_rl.trainer.models.layers.lora.base import MultiLoRAModule, get_lora_num_tokens, get_multilora_scaling
def _run_lora_grouped_mm(
@@ -55,7 +45,7 @@ class MultiLoRALinear(MultiLoRAModule):
base_layer: nn.Linear,
rank: int,
n_adapters: int,
alpha: float = 16.0,
alpha: float = 32.0,
dropout: float = 0.0,
use_grouped_mm: bool = True,
):
@@ -77,11 +67,13 @@ class MultiLoRALinear(MultiLoRAModule):
self.n_adapters = n_adapters
self.alpha = alpha
self.lora_dropout = nn.Dropout(dropout) if dropout > 0.0 else nn.Identity()
self.scaling = alpha / rank
self.use_grouped_mm = use_grouped_mm
self.in_features = base_layer.in_features
self.out_features = base_layer.out_features
self._lora_num_tokens = get_lora_num_tokens()
self._scaling_factors = get_multilora_scaling()
# LoRA weights: one low-rank pair per adapter
# [n_adapters, in, r]
self.lora_A = nn.ParameterList(
@@ -136,16 +128,26 @@ class MultiLoRALinear(MultiLoRAModule):
("lora_B", self.lora_B[idx]),
]
def get_lora_param_counts(self) -> tuple[int, int]:
"""Get the number of LoRA adapter parameters and adapted base parameters.
Returns:
A tuple of (adapter_params, adapted_params) where:
- adapter_params: Number of parameters in ONE LoRA adapter (lora_A + lora_B)
- adapted_params: Number of base layer parameters being adapted by LoRA
"""
adapter_params = self.lora_A[0].numel() + self.lora_B[0].numel()
adapted_params = self.base_layer.weight.numel()
return adapter_params, adapted_params
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
x: [..., in_features]
offsets: [n_adapters]
"""
global OFFSETS
offsets = OFFSETS
ori_shape = x.shape
new_shape = ori_shape[:-1] + (self.out_features,)
x = x.view(-1, x.shape[-1])
offsets = self._lora_num_tokens.cumsum(dim=0, dtype=torch.int32)
assert offsets[-1] == x.shape[0], f"offsets: {offsets}, x.shape: {x.shape}"
base_out = self.base_layer(x)
@@ -157,7 +159,10 @@ class MultiLoRALinear(MultiLoRAModule):
lora_out = _run_lora_grouped_mm(lora_x, combined_lora_A, combined_lora_B, offsets)
else:
lora_out = _run_lora_for_loop(lora_x, combined_lora_A, combined_lora_B, offsets)
return (base_out + self.scaling * lora_out).view(new_shape)
# Apply per-token scaling
per_token_scaling = torch.repeat_interleave(self._scaling_factors, self._lora_num_tokens).unsqueeze(-1)
return (base_out + per_token_scaling * lora_out).view(new_shape)
def __repr__(self) -> str:
return (
@@ -0,0 +1,433 @@
import math
import torch
import torch.nn.functional as F
from torch import nn
from prime_rl.trainer.models.layers.lora.base import MultiLoRAModule, get_lora_num_tokens, get_multilora_scaling
from prime_rl.trainer.models.layers.moe import GroupedExperts
def _run_lora_grouped_mm(
x: torch.Tensor,
lora_A: torch.Tensor,
lora_B: torch.Tensor,
offsets: torch.Tensor,
) -> torch.Tensor:
"""Apply LoRA via grouped matrix multiplication.
Args:
x: Input tensor [total_tokens, in_features]
lora_A: Low-rank A matrices [num_experts, rank, in_features]
lora_B: Low-rank B matrices [num_experts, out_features, rank]
offsets: Cumulative token counts per expert [num_experts]
Returns:
LoRA output [total_tokens, out_features]
"""
_a_out = torch._grouped_mm(x.bfloat16(), lora_A.bfloat16().transpose(-2, -1), offs=offsets)
lora_out = torch._grouped_mm(_a_out, lora_B.bfloat16().transpose(-2, -1), offs=offsets)
return lora_out
def _run_lora_for_loop(
x: torch.Tensor,
lora_A: torch.Tensor,
lora_B: torch.Tensor,
num_tokens_per_expert: torch.Tensor,
) -> torch.Tensor:
"""Apply LoRA via for-loop over experts (fallback for non-Hopper GPUs).
Args:
x: Input tensor [total_tokens, in_features]
lora_A: Low-rank A matrices [num_experts, rank, in_features]
lora_B: Low-rank B matrices [num_experts, out_features, rank]
num_tokens_per_expert: Token counts per expert [num_experts]
Returns:
LoRA output [total_tokens, out_features]
"""
num_tokens_per_expert_list = num_tokens_per_expert.tolist()
lora_out_splits = []
start = 0
for expert_idx, num_tokens in enumerate(num_tokens_per_expert_list):
if num_tokens == 0:
continue
end = start + num_tokens
# Apply LoRA for this expert: B @ A @ x
_a_out = torch.matmul(x[start:end], lora_A[expert_idx].transpose(-2, -1))
lora_out = torch.matmul(_a_out, lora_B[expert_idx].transpose(-2, -1))
lora_out_splits.append(lora_out)
start = end
return torch.cat(lora_out_splits, dim=0)
class MultiLoRAGroupedExperts(MultiLoRAModule):
"""
GroupedExperts + multi-LoRA with grouped GEMM.
Applies LoRA to all three expert projections (w1, w2, w3) for multi-tenant MoE training.
Compatible with vLLM's MoE LoRA format when broadcasting weights.
"""
def __init__(
self,
base_layer: GroupedExperts,
rank: int,
n_adapters: int,
alpha: float = 32.0,
dropout: float = 0.0,
):
super().__init__(base_layer)
if rank <= 0 or n_adapters <= 0:
raise ValueError("rank and n_adapters must be > 0")
self.num_experts = base_layer.num_experts
self.dim = base_layer.w1.shape[2]
self.hidden_dim = base_layer.w1.shape[1]
use_grouped_mm = False
if torch.cuda.is_available():
cc_major, _ = torch.cuda.get_device_capability()
if cc_major == 9: # Hopper GPUs (H100, H200)
use_grouped_mm = True
# grouped_mm requires 8-byte alignment
if rank % 8 != 0 or self.dim % 8 != 0 or self.hidden_dim % 8 != 0:
use_grouped_mm = False
self.rank = rank
self.n_adapters = n_adapters
self.alpha = alpha
self.lora_dropout = nn.Dropout(dropout) if dropout > 0.0 else nn.Identity()
self.use_grouped_mm = use_grouped_mm
self._lora_num_tokens = get_lora_num_tokens()
self._scaling_factors = get_multilora_scaling()
# Initialize LoRA parameters for w1 (gate_proj: dim -> moe_dim)
self.w1_lora_A = nn.ParameterList(
[
nn.Parameter(
torch.empty(
self.num_experts,
rank,
self.dim,
device=base_layer.w1.device,
dtype=base_layer.w1.dtype,
)
)
for _ in range(n_adapters)
]
)
self.w1_lora_B = nn.ParameterList(
[
nn.Parameter(
torch.empty(
self.num_experts,
self.hidden_dim,
rank,
device=base_layer.w1.device,
dtype=base_layer.w1.dtype,
)
)
for _ in range(n_adapters)
]
)
# Initialize LoRA parameters for w2 (down_proj: moe_dim -> dim)
self.w2_lora_A = nn.ParameterList(
[
nn.Parameter(
torch.empty(
self.num_experts,
rank,
self.hidden_dim,
device=base_layer.w2.device,
dtype=base_layer.w2.dtype,
)
)
for _ in range(n_adapters)
]
)
self.w2_lora_B = nn.ParameterList(
[
nn.Parameter(
torch.empty(
self.num_experts,
self.dim,
rank,
device=base_layer.w2.device,
dtype=base_layer.w2.dtype,
)
)
for _ in range(n_adapters)
]
)
# Initialize LoRA parameters for w3 (up_proj: moe_dim -> dim)
self.w3_lora_A = nn.ParameterList(
[
nn.Parameter(
torch.empty(
self.num_experts,
rank,
self.dim,
device=base_layer.w3.device,
dtype=base_layer.w3.dtype,
)
)
for _ in range(n_adapters)
]
)
self.w3_lora_B = nn.ParameterList(
[
nn.Parameter(
torch.empty(
self.num_experts,
self.hidden_dim,
rank,
device=base_layer.w3.device,
dtype=base_layer.w3.dtype,
)
)
for _ in range(n_adapters)
]
)
self.reset_parameters()
def reset_parameters(self, index: int | None = None) -> None:
"""Reset LoRA parameters using Kaiming uniform for A, zeros for B.
Args:
index: If provided, reset only the parameters for that adapter index.
If None, reset all adapter parameters.
"""
if index is None:
for i in range(self.n_adapters):
self.reset_parameters(i)
else:
# Reset w1 LoRA
nn.init.kaiming_uniform_(self.w1_lora_A[index], a=math.sqrt(5))
nn.init.zeros_(self.w1_lora_B[index])
# Reset w2 LoRA
nn.init.kaiming_uniform_(self.w2_lora_A[index], a=math.sqrt(5))
nn.init.zeros_(self.w2_lora_B[index])
# Reset w3 LoRA
nn.init.kaiming_uniform_(self.w3_lora_A[index], a=math.sqrt(5))
nn.init.zeros_(self.w3_lora_B[index])
def named_parameters_for_adapter(self, idx: int) -> list[tuple[str, nn.Parameter]]:
"""Get named parameters for a specific adapter index.
Returns the full stacked parameters (leaf tensors) for optimizer use.
Each parameter has shape [num_experts, ...] with all experts stacked.
Args:
idx: The adapter index to get parameters for
Returns:
List of (name, parameter) tuples for the specified adapter
"""
return [
("w1_lora_A", self.w1_lora_A[idx]), # Shape: [num_experts, rank, dim]
("w1_lora_B", self.w1_lora_B[idx]), # Shape: [num_experts, moe_dim, rank]
("w2_lora_A", self.w2_lora_A[idx]), # Shape: [num_experts, rank, moe_dim]
("w2_lora_B", self.w2_lora_B[idx]), # Shape: [num_experts, dim, rank]
("w3_lora_A", self.w3_lora_A[idx]), # Shape: [num_experts, rank, dim]
("w3_lora_B", self.w3_lora_B[idx]), # Shape: [num_experts, moe_dim, rank]
]
def get_lora_param_counts(self) -> tuple[int, int]:
"""Get the number of LoRA adapter parameters and adapted base parameters.
Returns:
A tuple of (adapter_params, adapted_params) where:
- adapter_params: Number of parameters in ONE LoRA adapter (all w1/w2/w3 lora_A + lora_B)
- adapted_params: Number of base layer parameters being adapted by LoRA (w1, w2, w3)
"""
adapter_params = (
self.w1_lora_A[0].numel()
+ self.w1_lora_B[0].numel()
+ self.w2_lora_A[0].numel()
+ self.w2_lora_B[0].numel()
+ self.w3_lora_A[0].numel()
+ self.w3_lora_B[0].numel()
)
adapted_params = self.base_layer.w1.numel() + self.base_layer.w2.numel() + self.base_layer.w3.numel()
return adapter_params, adapted_params
def state_dict_for_adapter(self, idx: int) -> dict[str, torch.Tensor]:
"""Get state dict for a specific adapter index in vLLM-compatible format.
Returns per-expert parameter slices for vLLM compatibility.
For 8 experts, returns 48 tensors (8 experts × 3 projections × 2 matrices):
- {expert_id}.gate_proj.lora_A.weight
- {expert_id}.gate_proj.lora_B.weight
- {expert_id}.down_proj.lora_A.weight
- {expert_id}.down_proj.lora_B.weight
- {expert_id}.up_proj.lora_A.weight
- {expert_id}.up_proj.lora_B.weight
Args:
idx: The adapter index to get state dict for
Returns:
Dict mapping vLLM-compatible names to parameter tensors
"""
state_dict = {}
detached_w1_lora_a = self.w1_lora_A[idx].detach()
detached_w1_lora_b = self.w1_lora_B[idx].detach()
detached_w2_lora_a = self.w2_lora_A[idx].detach()
detached_w2_lora_b = self.w2_lora_B[idx].detach()
detached_w3_lora_a = self.w3_lora_A[idx].detach()
detached_w3_lora_b = self.w3_lora_B[idx].detach()
# The clone is necessary to avoid views that cause giant memory spikes
# TODO: There's probably a better way to do this
for expert_id in range(self.num_experts):
state_dict[f"{expert_id}.gate_proj.lora_A.weight"] = detached_w1_lora_a[expert_id].clone()
state_dict[f"{expert_id}.gate_proj.lora_B.weight"] = detached_w1_lora_b[expert_id].clone()
state_dict[f"{expert_id}.down_proj.lora_A.weight"] = detached_w2_lora_a[expert_id].clone()
state_dict[f"{expert_id}.down_proj.lora_B.weight"] = detached_w2_lora_b[expert_id].clone()
state_dict[f"{expert_id}.up_proj.lora_A.weight"] = detached_w3_lora_a[expert_id].clone()
state_dict[f"{expert_id}.up_proj.lora_B.weight"] = detached_w3_lora_b[expert_id].clone()
return state_dict
def forward(self, x: torch.Tensor, num_tokens_per_expert: torch.Tensor) -> torch.Tensor:
# TODO: We assume theres only one adapter active in a sequence for now
# Being able to route multi-adapter sequences efficiently requires two things that are tricky
# 1. We need the tensor to be interleaved [(e0, a0), (e0, a1), (e1, a0), (e1, a1), ...]
# This causes issues when we want to create a stacked param for the optimizer
# 2. The topkrouter needs to set the offsets by binning its hist for each adapter
# The sort currently occurs there, so it needs to be done there too
adapter_idx = self._lora_num_tokens.argmax().item()
w1_lora_a = self.w1_lora_A[adapter_idx] # [num_experts, rank, dim]
w1_lora_b = self.w1_lora_B[adapter_idx] # [num_experts, hidden_dim, rank]
w2_lora_a = self.w2_lora_A[adapter_idx] # [num_experts, rank, hidden_dim]
w2_lora_b = self.w2_lora_B[adapter_idx] # [num_experts, dim, rank]
w3_lora_a = self.w3_lora_A[adapter_idx] # [num_experts, rank, dim]
w3_lora_b = self.w3_lora_B[adapter_idx] # [num_experts, hidden_dim, rank]
# Get per-adapter scaling factor
scaling = self._scaling_factors[adapter_idx].item()
# Access base weights directly
base_w1 = self.base_layer.w1 # [num_experts, hidden_dim, dim]
base_w2 = self.base_layer.w2 # [num_experts, dim, hidden_dim]
base_w3 = self.base_layer.w3 # [num_experts, hidden_dim, dim]
# Compute offsets for grouped_mm
offsets = torch.cumsum(num_tokens_per_expert, dim=0, dtype=torch.int32)
lora_x = self.lora_dropout(x)
if self.use_grouped_mm:
# Gate
h1_base = torch._grouped_mm(x.bfloat16(), base_w1.bfloat16().transpose(-2, -1), offs=offsets)
w1_lora_out = _run_lora_grouped_mm(lora_x, w1_lora_a, w1_lora_b, offsets)
h1 = h1_base + scaling * w1_lora_out.bfloat16()
# Up
h3_base = torch._grouped_mm(x.bfloat16(), base_w3.bfloat16().transpose(-2, -1), offs=offsets)
w3_lora_out = _run_lora_grouped_mm(lora_x, w3_lora_a, w3_lora_b, offsets)
h3 = h3_base + scaling * w3_lora_out.bfloat16()
# SwiGLU activation
h = F.silu(h1) * h3
# Down
lora_h = self.lora_dropout(h)
h2_base = torch._grouped_mm(h, base_w2.bfloat16().transpose(-2, -1), offs=offsets)
w2_lora_out = _run_lora_grouped_mm(lora_h, w2_lora_a, w2_lora_b, offsets)
out = h2_base + scaling * w2_lora_out.bfloat16()
return out.type_as(x)
else:
# For-loop fallback for older GPUs
return self._forward_for_loop(
x,
num_tokens_per_expert,
w1_lora_a,
w1_lora_b,
w2_lora_a,
w2_lora_b,
w3_lora_a,
w3_lora_b,
base_w1,
base_w2,
base_w3,
scaling,
)
def _forward_for_loop(
self,
x: torch.Tensor,
num_tokens_per_expert: torch.Tensor,
w1_lora_a: torch.Tensor,
w1_lora_b: torch.Tensor,
w2_lora_a: torch.Tensor,
w2_lora_b: torch.Tensor,
w3_lora_a: torch.Tensor,
w3_lora_b: torch.Tensor,
base_w1: torch.Tensor,
base_w2: torch.Tensor,
base_w3: torch.Tensor,
scaling: float,
) -> torch.Tensor:
"""For-loop implementation of forward pass (fallback for non-Hopper GPUs)."""
num_tokens_per_expert_list = num_tokens_per_expert.tolist()
out_splits = []
start = 0
for expert_idx, num_tokens in enumerate(num_tokens_per_expert_list):
if num_tokens == 0:
continue
end = start + num_tokens
x_expert = x[start:end]
# Apply dropout for LoRA path (consistent with grouped_mm path)
x_expert_lora = self.lora_dropout(x_expert)
# Compute w1 + w1_lora for this expert
h1_base = torch.matmul(x_expert, base_w1[expert_idx].transpose(-2, -1))
w1_lora_tmp = torch.matmul(x_expert_lora, w1_lora_a[expert_idx].transpose(-2, -1))
w1_lora_out = torch.matmul(w1_lora_tmp, w1_lora_b[expert_idx].transpose(-2, -1))
h1 = h1_base + scaling * w1_lora_out
# Compute w3 + w3_lora for this expert
h3_base = torch.matmul(x_expert, base_w3[expert_idx].transpose(-2, -1))
w3_lora_tmp = torch.matmul(x_expert_lora, w3_lora_a[expert_idx].transpose(-2, -1))
w3_lora_out = torch.matmul(w3_lora_tmp, w3_lora_b[expert_idx].transpose(-2, -1))
h3 = h3_base + scaling * w3_lora_out
# SwiGLU activation
h = F.silu(h1) * h3
# Compute w2 + w2_lora for this expert
# Apply dropout for LoRA path (consistent with grouped_mm path)
h_lora = self.lora_dropout(h)
h2_base = torch.matmul(h, base_w2[expert_idx].transpose(-2, -1))
w2_lora_tmp = torch.matmul(h_lora, w2_lora_a[expert_idx].transpose(-2, -1))
w2_lora_out = torch.matmul(w2_lora_tmp, w2_lora_b[expert_idx].transpose(-2, -1))
out = h2_base + scaling * w2_lora_out
out_splits.append(out)
start = end
return torch.cat(out_splits, dim=0)
def __repr__(self) -> str:
return (
f"{self.__class__.__name__}(base={self.base_layer}, rank={self.rank}, "
f"n_adapters={self.n_adapters}, num_experts={self.num_experts}, "
f"alpha={self.alpha}, dropout={self.lora_dropout}, "
f"use_grouped_mm={self.use_grouped_mm})"
)
+2 -1
View File
@@ -324,7 +324,8 @@ class MoE(nn.Module):
num_experts = moe_args.num_experts
if torch.cuda.is_available():
cc_major, _ = torch.cuda.get_device_capability()
if cc_major != 9:
# As of PyTorch 2.9, grouped_mm is supported on Hopper and Blackwell.
if cc_major < 9:
moe_args.use_grouped_mm = False
self.experts = GroupedExperts(
dim=dim,
@@ -28,7 +28,6 @@ from transformers.modeling_layers import (
)
from transformers.modeling_outputs import (
BaseModelOutputWithPast,
CausalLMOutputWithPast,
)
from transformers.models.llama.configuration_llama import LlamaConfig
from transformers.processing_utils import Unpack
@@ -37,6 +36,7 @@ from transformers.utils.deprecation import deprecate_kwarg
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
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.rms_norm import RMSNorm, RMSNormConfig
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
@@ -248,9 +248,16 @@ class LlamaForCausalLM(LlamaPreTrainedModel, GenerationMixin):
use_cache: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
temperature: Optional[float] = 1.0,
**kwargs: Unpack[TransformersKwargs],
) -> CausalLMOutputWithPast:
) -> PrimeLmOutput:
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels used by PrimeRL's wrapped LM head to optionally compute per-token logprobs/entropy.
If not provided, the wrapped LM head returns logits only.
temperature (`float`, *optional*, defaults to 1.0):
Temperature used for the logprobs/entropy computation when `labels` are provided.
Example:
```python
@@ -285,18 +292,10 @@ class LlamaForCausalLM(LlamaPreTrainedModel, GenerationMixin):
hidden_states = outputs.last_hidden_state
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
logits = self.lm_head(hidden_states[:, slice_indices, :])
loss = None
if labels is not None:
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
return CausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
return self.lm_head(
hidden_states[:, slice_indices, :],
labels[:, slice_indices] if labels is not None else None,
temperature=temperature,
)
def init_buffers_post_meta(self):
@@ -168,6 +168,7 @@ class Qwen3MoeConfig(PretrainedConfig):
router_aux_loss_coef=0.001,
mlp_only_layers=None,
load_balance_coeff=None,
use_grouped_mm=True,
**kwargs,
):
self.vocab_size = vocab_size
@@ -204,7 +205,8 @@ class Qwen3MoeConfig(PretrainedConfig):
self.router_aux_loss_coef = router_aux_loss_coef
self.mlp_only_layers = [] if mlp_only_layers is None else mlp_only_layers
self.load_balance_coeff = load_balance_coeff
self.use_grouped_mm = use_grouped_mm
super().__init__(
tie_word_embeddings=tie_word_embeddings,
**kwargs,
@@ -22,12 +22,13 @@ from transformers.generation import GenerationMixin
from transformers.modeling_layers import (
GradientCheckpointingLayer,
)
from transformers.modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
from transformers.modeling_outputs import MoeModelOutputWithPast
from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.attn import ATTN_IMPL2CLASS, AttentionConfig
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
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
@@ -69,7 +70,7 @@ class Qwen3MoeDecoderLayer(GradientCheckpointingLayer):
route_scale=1.0,
score_before_experts=False,
top_k=config.num_experts_per_tok,
use_grouped_mm=True,
use_grouped_mm=config.use_grouped_mm,
load_balance_coeff=config.load_balance_coeff,
)
mlp_config = MLPConfig(
@@ -359,13 +360,16 @@ class Qwen3MoeForCausalLM(Qwen3MoePreTrainedModel, GenerationMixin):
output_router_logits: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
temperature: Optional[float] = 1.0,
**kwargs: Unpack[TransformersKwargs],
) -> MoeCausalLMOutputWithPast:
) -> PrimeLmOutput:
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
temperature (`float`, *optional*, defaults to 1.0):
The temperature to use for the logprobs/entropy.
Example:
@@ -405,31 +409,10 @@ class Qwen3MoeForCausalLM(Qwen3MoePreTrainedModel, GenerationMixin):
hidden_states = outputs.last_hidden_state
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
logits = self.lm_head(hidden_states[:, slice_indices, :])
loss = None
if labels is not None:
loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
aux_loss = None
if output_router_logits:
aux_loss = load_balancing_loss_func(
outputs.router_logits,
self.num_experts,
self.num_experts_per_tok,
attention_mask,
)
if labels is not None:
loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
return MoeCausalLMOutputWithPast(
loss=loss,
aux_loss=aux_loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
router_logits=outputs.router_logits,
return self.lm_head(
hidden_states[:, slice_indices, :],
labels[:, slice_indices] if labels is not None else None,
temperature=temperature,
)
def init_buffers_post_meta(self):
+15 -7
View File
@@ -36,13 +36,19 @@ def setup_optimizer(
def _create_optimizer(
config: OptimizerConfigType, named_params: list[tuple[str, nn.Parameter]], device_mesh: DeviceMesh
config: OptimizerConfigType,
named_params: list[tuple[str, nn.Parameter]],
device_mesh: DeviceMesh,
lr: float | None = None,
) -> Optimizer:
"""Create optimizer. If lr is None, uses config.lr."""
if lr is None:
lr = config.lr
match config.type:
case "sgd":
return SGD(
params=[p for _, p in named_params],
lr=config.lr,
lr=lr,
weight_decay=config.weight_decay,
momentum=config.momentum,
nesterov=config.nesterov,
@@ -50,7 +56,7 @@ def _create_optimizer(
case "adamw":
return AdamW(
params=[p for _, p in named_params],
lr=config.lr,
lr=lr,
weight_decay=config.weight_decay,
betas=(config.betas1, config.betas2),
)
@@ -73,13 +79,13 @@ def _create_optimizer(
dict(
params=muon_params,
algorithm="muon",
lr=config.lr,
lr=lr,
weight_decay=config.weight_decay,
adjust_lr="rms_norm",
),
dict(params=adamw_params, algorithm="adamw", lr=config.lr, weight_decay=config.weight_decay),
dict(params=adamw_params, algorithm="adamw", lr=lr, weight_decay=config.weight_decay),
],
lr=config.lr,
lr=lr,
weight_decay=config.weight_decay,
adjust_lr="rms_norm",
distributed_mesh=device_mesh,
@@ -113,7 +119,9 @@ class MultiLoRAOptimizer:
def optimizer_creation_hook(self, idx: int, run_id: str) -> None:
# Get named parameters for this run from the Runs system
named_params = self.runs.get_named_parameters_for_run(idx)
self.optimizers[idx] = _create_optimizer(self.config, named_params, self.device_mesh)
lr = self.runs.config[idx].optim.lr
self.optimizers[idx] = _create_optimizer(self.config, named_params, self.device_mesh, lr)
# Call post-creation callbacks (e.g., for scheduler creation)
for callback in self._post_creation_callbacks:
+2 -1
View File
@@ -197,7 +197,8 @@ class PerfCounter:
params = 0
for module in self.model.modules():
if isinstance(module, MultiLoRAModule):
params += module.lora_A[0].numel() + module.lora_B[0].numel()
adapter_params, _ = module.get_lora_param_counts()
params += adapter_params
return params
def _count_fully_trainable_params_excluding_lora(self) -> int:
+25 -5
View File
@@ -17,8 +17,11 @@ from prime_rl.trainer.runs import get_runs
from prime_rl.trainer.utils import get_world
from prime_rl.trainer.weights import get_max_layer_num
from prime_rl.utils.logger import get_logger
from prime_rl.utils.pathing import sync_wait_for_path
from prime_rl.utils.utils import get_broadcast_dir, get_step_path
NCCL_READY_MARKER = "NCCL_READY"
def broadcast_integer(integer: int, communicator: PyNcclCommunicator) -> None:
"""Broadcast an integer to a process group using NCCL communicator."""
@@ -118,7 +121,6 @@ class NCCLWeightBroadcastSender:
self.logger.debug(f"Broadcasting {num_state_dict_to_send} layer state dicts")
for layer_id, state_dict in filter_state_dict_by_layers(state_dict, num_layers):
self.logger.debug(f"Sending layer {layer_id + 1}/{num_state_dict_to_send} state dict")
for key, value in list(state_dict.items()):
if isinstance(value, DTensor):
value = cast(DTensor, value.to(self.dtype)).full_tensor()
@@ -147,7 +149,7 @@ class NCCLWeightBroadcast(WeightBroadcast):
self.world = get_world()
self.runs = get_runs()
self.nccl_broadcast_sender = NCCLWeightBroadcastSender(
config.host, config.port, 0, config.inference_world_size + 1, device, config.timeout
config.host, config.port, 0, config.inference_world_size + 1, device, config.timeout, dtype
)
@torch.no_grad()
@@ -155,13 +157,21 @@ class NCCLWeightBroadcast(WeightBroadcast):
"""Broadcast the state dict of a model into the inference pool using NCCL and notifies the orchestrator."""
self.logger.debug("Starting broadcasting weights to inference engine via NCCL")
start_time = time.perf_counter()
notified_runs: list[tuple[int, Path]] = []
if self.world.is_master:
self._notify_orchestrator()
notified_runs = self._notify_orchestrator()
# Wait for inference workers to signal readiness before starting NCCL broadcast
self._wait_for_nccl_ready(notified_runs)
self.nccl_broadcast_sender.broadcast_weights(model, step)
self.logger.debug(f"Weights broadcasted in {time.perf_counter() - start_time:.2f}s")
def _notify_orchestrator(self):
"""Notify the orchestrator to initiate weight broadcast."""
def _notify_orchestrator(self) -> list[tuple[int, Path]]:
"""Notify the orchestrator to initiate weight broadcast.
Returns:
List of (run_idx, save_dir) tuples for runs that were notified.
"""
notified_runs: list[tuple[int, Path]] = []
if self.world.is_master:
for idx in self.runs.used_idxs:
if not self.runs.ready_to_update[idx]:
@@ -175,9 +185,19 @@ class NCCLWeightBroadcast(WeightBroadcast):
stable_file = save_dir / "STABLE"
stable_file.touch()
notified_runs.append((idx, save_dir))
except FileNotFoundError:
self.logger.warning(f"Run {idx} is deleted, skipping")
except Exception as e:
self.logger.error(f"Error broadcasting weights for run {idx}: {e}")
finally:
self.runs.ready_to_update[idx] = False
return notified_runs
def _wait_for_nccl_ready(self, notified_runs: list[tuple[int, Path]]):
"""Wait for inference workers to signal they are ready to receive NCCL broadcast."""
for idx, save_dir in notified_runs:
nccl_ready_file = save_dir / NCCL_READY_MARKER
self.logger.debug(f"Waiting for NCCL_READY marker at {nccl_ready_file}")
sync_wait_for_path(nccl_ready_file, interval=0.1, log_interval=10)
self.logger.debug(f"Inference workers ready for NCCL broadcast (run {idx})")
+16 -2
View File
@@ -13,7 +13,7 @@ from prime_rl.trainer.config import (
TokenizerConfig,
)
from prime_rl.transport.config import FileSystemTransportConfig, TransportConfigType
from prime_rl.utils.config import HeartbeatConfig, LogConfig, WandbConfig
from prime_rl.utils.config import HeartbeatConfig, LogConfig, MetricsServerConfig, WandbConfig
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings
@@ -35,7 +35,6 @@ class LossConfig(BaseConfig):
10.0
)
geo_mask_low: Annotated[float, Field(ge=0, description="The low threshold for geo importance ratio to mask.")] = 0.1
kl_tau: Annotated[float, Field(ge=0, description="The tau for KL divergence.")] = 0.0
sequence_mask_low: Annotated[
float,
Field(
@@ -51,6 +50,10 @@ class LossConfig(BaseConfig):
),
] = 100.0
adv_tau: Annotated[float, Field(ge=0, description="The tau for advantages.")] = 1.0
teacher_tau: Annotated[float, Field(ge=0, description="The tau for teacher logprobs.")] = 0.0
kl_tau: Annotated[float, Field(ge=0, description="The tau for KL divergence.")] = 0.0
@model_validator(mode="after")
def validate_mask_bounds(self):
if self.token_mask_low >= self.token_mask_high:
@@ -193,6 +196,11 @@ class RLTrainerConfig(BaseSettings):
HeartbeatConfig | None, Field(description="The heartbeat config for monitoring training progress.")
] = None
metrics_server: Annotated[
MetricsServerConfig | None,
Field(description="Prometheus metrics server config. If set, exposes /metrics endpoint for scraping."),
] = None
max_concurrent_runs: Annotated[
int,
Field(
@@ -259,3 +267,9 @@ class RLTrainerConfig(BaseSettings):
if self.tokenizer.trust_remote_code is None:
self.tokenizer.trust_remote_code = self.model.trust_remote_code
return self
@model_validator(mode="after")
def auto_setup_fused_lm_head_chunk_size(self):
if self.model.fused_lm_head_chunk_size is None and self.model.impl != "liger_kernel":
self.model.fused_lm_head_chunk_size = 2048
return self
+10 -4
View File
@@ -7,7 +7,7 @@ from torch import Tensor
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.trainer.rl.config import FakeDataLoaderConfig
from prime_rl.trainer.rl.packer import Packer
from prime_rl.trainer.rl.packer import BasePacker, setup_packer
from prime_rl.trainer.runs import get_runs
from prime_rl.trainer.world import get_world
from prime_rl.transport import MicroBatch, MicroBatchReceiver, TransportConfigType, setup_micro_batch_receiver
@@ -21,6 +21,7 @@ class TensorMicroBatch(TypedDict):
position_ids: Int[Tensor, "batch seq"]
advantages: Float[Tensor, "batch seq"]
inference_logprobs: Float[Tensor, "batch seq"]
teacher_logprobs: Float[Tensor, "batch seq"] | None
loss_mask: Bool[Tensor, "batch seq"]
# Batch level
@@ -91,6 +92,7 @@ class FakeDataLoader:
"position_ids": position_ids.unsqueeze(0),
"advantages": advantages.unsqueeze(0),
"inference_logprobs": inference_logprobs.unsqueeze(0),
"teacher_logprobs": None,
"temperature": 1.0,
"loss_mask": loss_mask.unsqueeze(0),
"lora_num_tokens": lora_num_tokens,
@@ -112,6 +114,7 @@ class FakeDataLoader:
"position_ids": torch.cat([torch.arange(self.seq_len)]).unsqueeze(0),
"advantages": torch.randn(self.seq_len, generator=generator).unsqueeze(0),
"inference_logprobs": torch.randn(self.seq_len, generator=generator).unsqueeze(0),
"teacher_logprobs": None,
"temperature": 1.0,
"loss_mask": torch.ones(self.seq_len, dtype=torch.bool).unsqueeze(0),
"lora_num_tokens": lora_num_tokens,
@@ -134,11 +137,11 @@ class DataLoader:
self.world = get_world()
if self.world.is_master:
self.packer = Packer(
self.packer: BasePacker = setup_packer(
dp_world_size=dp_world_size,
seq_len=seq_len,
tokenizer=tokenizer,
config=config,
transport_config=config,
pad_to_multiple_of=pad_to_multiple_of,
start_step=start_step,
)
@@ -169,7 +172,10 @@ class DataLoader:
position_ids=torch.tensor(micro_batch.position_ids, dtype=torch.long).unsqueeze(0),
advantages=torch.tensor(micro_batch.advantages, dtype=torch.float).unsqueeze(0),
inference_logprobs=torch.tensor(micro_batch.inference_logprobs, dtype=torch.float).unsqueeze(0),
teacher_logprobs=torch.tensor(micro_batch.teacher_logprobs, dtype=torch.float).unsqueeze(0)
if micro_batch.teacher_logprobs is not None
else None,
loss_mask=torch.tensor(micro_batch.loss_mask, dtype=torch.bool).unsqueeze(0),
temperature=micro_batch.temperature if micro_batch.temperature is not None else 1.0,
temperature=micro_batch.temperature,
lora_num_tokens=torch.tensor(micro_batch.lora_num_tokens, dtype=torch.int32),
)
+47 -5
View File
@@ -40,6 +40,34 @@ def shift_logits(
return logits
def shift_tensor_left(t: Float[Tensor, "batch seq"]) -> Float[Tensor, "batch seq"]:
"""Shifts the tensor one token to the left.
Used to create labels from input_ids: labels[i] = input_ids[i+1].
The last position is padded with 0 (a valid token index) since this value
will be shifted off by shift_tensor_right and never used.
"""
return torch.cat([t[:, 1:], torch.full((t.shape[0], 1), 0, device=t.device, dtype=t.dtype)], dim=1)
def shift_tensor_right(t: Float[Tensor, "batch seq"], pad_value: float | None = None) -> Float[Tensor, "batch seq"]:
"""Shifts the tensor one token to the right, prepending a padding value.
Used to realign logprobs/entropy after computing with shifted labels.
After shift: result[i] = t[i-1], result[0] = pad_value.
This converts from "predict next token" convention to "probability of current token" convention.
Args:
t: Tensor to shift right
pad_value: Value to use for position 0. If None, uses 0.0 for backward compatibility.
For logprobs, should be log(1/vocab_size) to represent uniform distribution.
For entropy, should be log(vocab_size) to represent maximum entropy.
"""
if pad_value is None:
pad_value = 0.0
return torch.cat([torch.full((t.shape[0], 1), pad_value, device=t.device, dtype=t.dtype), t[:, :-1]], dim=1)
def _safe_mean(values: Tensor, mask: Tensor) -> Tensor:
"""Mean of values over a boolean mask; returns 0 when mask is empty."""
denom = torch.clamp_min(mask.sum(), 1)
@@ -49,6 +77,7 @@ def _safe_mean(values: Tensor, mask: Tensor) -> Tensor:
def compute_loss(
trainer_logprobs: Any, # list of Float[Tensor, "seq_i"] with potentially different seq_i lengths
inference_logprobs: Any, # list of Float[Tensor, "seq_i"] with potentially different seq_i lengths
teacher_logprobs: Any | None, # list of Float[Tensor, "seq_i"] with potentially different seq_i lengths, or None
advantages: Any, # list of Float[Tensor, "seq_i"] with potentially different seq_i lengths
loss_mask: Any, # list of Bool[Tensor, "seq_i"] with potentially different seq_i lengths
loss_config: LossConfig,
@@ -60,6 +89,7 @@ def compute_loss(
Args:
trainer_logprobs: Log probabilities tensor for packed sequences
inference_logprobs: Old log probabilities tensor for packed sequences
teacher_logprobs: Teacher log probabilities tensor for packed sequences, or None if not configured
advantages: Advantages tensor for packed sequences
loss_mask: Loss mask tensor for packed sequences
loss_config: Loss configuration object
@@ -81,19 +111,23 @@ def compute_loss(
total_geo_masked_low = []
total_geo_masked_high = []
total_geo_seq_ratio = []
total_teacher_kl = []
for trainer_logprobs, inference_logprobs, advantages, loss_mask in zip(
trainer_logprobs, inference_logprobs, advantages, loss_mask
if teacher_logprobs is None:
teacher_logprobs = [None] * len(trainer_logprobs)
for trainer_logprobs, inference_logprobs, teacher_logprobs, advantages, loss_mask in zip(
trainer_logprobs, inference_logprobs, teacher_logprobs, advantages, loss_mask
):
log_importance_ratio = trainer_logprobs - inference_logprobs
teacher_kl = teacher_logprobs - trainer_logprobs if teacher_logprobs is not None else None
# Trainer-inference mismatch KL per token
token_importance_ratio = torch.exp(log_importance_ratio)
geo_seq_ratio = torch.exp(_safe_mean(log_importance_ratio, loss_mask))
token_mismatch_kl = token_importance_ratio - log_importance_ratio - 1
seq_log_importance_ratio = log_importance_ratio[loss_mask].sum().detach()
seq_log_importance_ratio = torch.clamp(trainer_logprobs - trainer_logprobs.detach() + seq_log_importance_ratio, max=10.0)
seq_log_importance_ratio = torch.clamp(log_importance_ratio[loss_mask].sum().detach(), max=10.0)
seq_importance_ratio = torch.clamp(torch.exp(seq_log_importance_ratio), max=loss_config.sequence_clip_high)
seq_min_ratio = torch.where(loss_mask, token_importance_ratio, torch.inf).min()
@@ -112,6 +146,9 @@ def compute_loss(
importance_ratio = seq_importance_ratio if loss_config.ratio_type == "sequence" else token_importance_ratio
advantages = loss_config.adv_tau * advantages
if teacher_logprobs is not None:
advantages = advantages + loss_config.teacher_tau * teacher_kl.detach()
coeff = importance_ratio * (advantages - loss_config.kl_tau * log_importance_ratio)
loss = -(coeff.detach() * trainer_logprobs)[keep_mask].sum()
@@ -132,11 +169,13 @@ def compute_loss(
total_geo_masked_low.append(geo_mask_low.float())
total_geo_masked_high.append(geo_mask_high.float())
total_geo_seq_ratio.append(geo_seq_ratio)
if teacher_logprobs is not None:
total_teacher_kl.append(_safe_mean(teacher_kl, loss_mask))
# Apply loss scaling
scaled_loss = total_loss / loss_scale
return scaled_loss, {
result = {
"mismatch_kl": torch.stack(total_mismatch_kl),
"masked_mismatch_kl": torch.stack(total_masked_mismatch_kl),
"unmasked_mismatch_kl": torch.stack(total_unmasked_mismatch_kl),
@@ -149,3 +188,6 @@ def compute_loss(
"geo_masked_high": torch.stack(total_geo_masked_high),
"geo_seq_ratio": torch.stack(total_geo_seq_ratio),
}
if total_teacher_kl:
result["teacher_kl"] = torch.stack(total_teacher_kl)
return scaled_loss, result
+205 -44
View File
@@ -1,5 +1,7 @@
import shutil
import time
from abc import ABC, abstractmethod
from collections import deque
from transformers.tokenization_utils import PreTrainedTokenizer
@@ -7,7 +9,6 @@ from prime_rl.trainer.batch import prepare_batch
from prime_rl.trainer.runs import get_runs
from prime_rl.transport import (
MicroBatchSender,
TrainingBatch,
TrainingSample,
TransportConfigType,
setup_micro_batch_sender,
@@ -19,7 +20,7 @@ from prime_rl.utils.pathing import get_rollout_dir
TIMEOUT_SECONDS = 10
class Packer:
class BasePacker(ABC):
def __init__(
self,
dp_world_size: int,
@@ -41,58 +42,218 @@ class Packer:
self.runs.output_dir, dp_world_size, start_step, config
)
def get_batch(self) -> dict[int, TrainingBatch]:
self.runs.check_for_changes()
batches = self.receiver.receive()
return {batch.run_idx: batch for batch in batches if batch.run_idx is not None}
@abstractmethod
def pack(self) -> None:
"""Pack samples for the next step."""
pass
def has_enough_tokens(self, rollouts: dict[int, TrainingBatch]) -> bool:
tokens = 0
batches = 1e-5 # Avoid division by zero
threshold = self.seq_len * self.dp_world_size
for _rollouts in rollouts.values():
for rollout in _rollouts.examples:
tokens += len(rollout.prompt_ids) + len(rollout.completion_ids)
batches += 1
estimated_next_batch_tokens = tokens + tokens / batches
if estimated_next_batch_tokens >= threshold:
return True
else:
return False
class SinglePacker(BasePacker):
def __init__(
self,
dp_world_size: int,
seq_len: int,
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
config: TransportConfigType,
start_step: int = 0,
):
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, start_step)
assert self.runs.max_runs == 1, "SinglePacker only supports one run"
def pack(self):
assert all(not i for i in self.runs.ready_to_update), "No runs should be ready to update at start of pack."
training_batches: dict[int, TrainingBatch] = self.get_batch()
start_time = time.time()
while not self.has_enough_tokens(training_batches):
if time.time() - start_time > TIMEOUT_SECONDS and training_batches:
self.logger.warning("Timeout waiting for enough tokens to pack")
break
time.sleep(1)
training_batches = self.get_batch()
# Wait for batch to be available
batches = []
while len(batches) == 0:
self.runs.check_for_changes()
batches = self.receiver.receive()
time.sleep(0.2)
train_examples: list[TrainingSample] = []
train_idxs = []
for idx, training_batch in training_batches.items():
self.runs.progress[idx].step += 1
self.runs.progress[idx].total_tokens += sum(
len(rollout.prompt_ids) + len(rollout.completion_ids) for rollout in training_batch.examples
)
self.runs.progress[idx].total_samples += len(training_batch.examples)
train_examples.extend(training_batch.examples)
train_idxs.extend([idx] * len(training_batch.examples))
self.runs.ready_to_update[idx] = True
assert len(batches) == 1, "SinglePacker only supports one batch per step"
batch = batches[0]
# TODO: Handle different temperatures for each run
some_temperature = next(iter(training_batches.values())).temperature
self.runs.ready_to_update[0] = True
self.runs.progress[0].step += 1
micro_batch_grid = prepare_batch(
rollouts=train_examples,
temperature=some_temperature,
rollouts=batch.examples,
temperature=batch.temperature,
seq_len=self.seq_len,
pad_to_multiple_of=self.pad_to_multiple_of,
num_train_workers=self.dp_world_size,
idxs=train_idxs,
idxs=[0] * len(batch.examples),
num_loras=self.runs.max_runs,
)
self.sender.send(micro_batch_grid)
class MultiPacker(BasePacker):
def __init__(
self,
dp_world_size: int,
seq_len: int,
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
config: TransportConfigType,
start_step: int = 0,
):
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, start_step)
# Per-run buffer: stores (TrainingSample, temperature) tuples
self.buffers: list[deque[tuple[TrainingSample, float]]] = [deque() for _ in range(self.runs.max_runs)]
# Per-run sample count consumed in current step
self.samples_consumed_this_step: list[int] = [0] * self.runs.max_runs
# Round-robin position (persists across pack() calls)
self._round_robin_position: int = 0
# Register delete_run_data hook for receiver reset (master only, runs during check_for_changes)
# This must happen when a run is deleted to prevent stale data from remaining
self.runs.register_delete_run_data_hook(self._on_run_data_deleted)
def _on_run_data_deleted(self, idx: int, run_id: str) -> None:
"""Reset run state when run data is deleted (master only)."""
self.logger.debug(f"Packing is resetting run state for deleted run {idx}")
self.receiver.reset_run(idx)
# Reset run state
self.buffers[idx].clear()
self.samples_consumed_this_step[idx] = 0
def _get_batch(self) -> None:
"""Receive batches from orchestrator and buffer samples per run."""
self.runs.check_for_changes()
batches = self.receiver.receive()
for batch in batches:
if batch.run_idx is None:
self.logger.warning("Received batch with no run index")
continue
for sample in batch.examples:
self.buffers[batch.run_idx].append((sample, batch.temperature))
def _has_enough_tokens(self) -> bool:
"""Check if we have enough samples in buffer to pack a step"""
# When not using small batch granularity, require at least one full batch
threshold = self.seq_len * self.dp_world_size
tokens = 0
for buffer in self.buffers:
for sample, _ in buffer:
tokens += len(sample.prompt_ids) + len(sample.completion_ids)
if tokens >= threshold:
return True
return False
def _select_samples_round_robin(self, token_budget: int) -> list[tuple[int, TrainingSample, float]]:
"""Select samples using round-robin from runs with buffered work."""
selected: list[tuple[int, TrainingSample, float]] = []
tokens_collected = 0
while tokens_collected < token_budget:
# Round-robin until we find a run with work
for _ in range(len(self.buffers)):
if len(self.buffers[self._round_robin_position]) != 0:
break
self._round_robin_position = (self._round_robin_position + 1) % len(self.buffers)
else:
# TODO: We could probably make the logic safer. This is basically counting on _has_enough_tokens() to be correct.
# We also need to cover the timeout case here.
break
run_idx = self._round_robin_position
self._round_robin_position = (self._round_robin_position + 1) % len(self.buffers)
while len(self.buffers[run_idx]) > 0:
sample, temperature = self.buffers[run_idx][0]
tokens_collected += len(sample.prompt_ids) + len(sample.completion_ids)
if tokens_collected > token_budget:
if tokens_collected == (len(sample.prompt_ids) + len(sample.completion_ids)):
tokens_collected -= len(sample.prompt_ids) + len(sample.completion_ids)
# This means we have a sample that has more tokens than max seqlen
self.buffers[run_idx].popleft()
continue
return selected
selected.append((run_idx, sample, temperature))
self.buffers[run_idx].popleft()
return selected
def _update_run_progress(self, run_idx: int, num_samples: int, num_tokens: int) -> None:
"""Update progress, increment step only when batch_size reached."""
self.samples_consumed_this_step[run_idx] += num_samples
batch_size = self.runs.config[run_idx].batch_size
# May complete multiple steps if we consumed more than batch_size worth
while self.samples_consumed_this_step[run_idx] >= batch_size:
self.runs.progress[run_idx].step += 1
self.runs.ready_to_update[run_idx] = True
self.samples_consumed_this_step[run_idx] -= batch_size
self.runs.progress[run_idx].total_tokens += num_tokens
self.runs.progress[run_idx].total_samples += num_samples
def pack(self):
"""Pack samples from buffers using round-robin fair scheduling."""
self._get_batch()
start_time = time.time()
while not self._has_enough_tokens():
if time.time() - start_time > TIMEOUT_SECONDS and any(len(i) > 0 for i in self.buffers):
self.logger.warning("Timeout waiting for enough tokens to pack")
break
time.sleep(1)
self._get_batch()
token_budget = self.seq_len * self.dp_world_size
selected_samples = self._select_samples_round_robin(token_budget)
assert selected_samples, "No samples selected"
# Group by run for prepare_batch (MultiLoRAMoE requires same run_idx in microbatch)
samples_by_run: dict[int, list[tuple[TrainingSample, float]]] = {}
for run_idx, sample, temperature in selected_samples:
if run_idx not in samples_by_run:
samples_by_run[run_idx] = []
samples_by_run[run_idx].append((sample, temperature))
micro_batch_grid = [[] for _ in range(self.dp_world_size)]
for run_idx, sample_temp_pairs in samples_by_run.items():
samples = [s for s, _ in sample_temp_pairs]
# We don't support dynamic temperatures in orchestrator yet
# So this works for now
temperature = sample_temp_pairs[0][1]
num_samples = len(samples)
num_tokens = sum(len(s.prompt_ids) + len(s.completion_ids) for s in samples)
self._update_run_progress(run_idx, num_samples, num_tokens)
_micro_batch_grid = prepare_batch(
rollouts=samples,
temperature=temperature,
seq_len=self.seq_len,
pad_to_multiple_of=self.pad_to_multiple_of,
num_train_workers=self.dp_world_size,
idxs=[run_idx] * num_samples,
num_loras=self.runs.max_runs,
)
for i, micro_batch in enumerate(_micro_batch_grid):
micro_batch_grid[i].extend(micro_batch)
self.sender.send(micro_batch_grid)
def setup_packer(
dp_world_size: int,
seq_len: int,
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
transport_config: TransportConfigType,
start_step: int = 0,
) -> BasePacker:
runs = get_runs()
if runs.max_runs == 1:
return SinglePacker(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, transport_config, start_step)
else:
return MultiPacker(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, transport_config, start_step)
+125 -42
View File
@@ -19,15 +19,16 @@ from prime_rl.trainer.scheduler import setup_scheduler, setup_multi_scheduler
from prime_rl.trainer.rl.config import RLTrainerConfig
from prime_rl.trainer.rl.data import DataLoader, FakeDataLoader
from prime_rl.utils.cp import (
get_padding_logit_from_prev_cp_rank,
setup_cp_params,
shard_for_cp,
)
from prime_rl.utils.logger import setup_logger
from prime_rl.trainer.rl.loss import (
shift_logits,
selective_log_softmax,
compute_entropy,
compute_loss,
selective_log_softmax,
shift_tensor_left,
shift_tensor_right,
)
from prime_rl.trainer.model import (
forward,
@@ -48,8 +49,9 @@ from prime_rl.trainer.utils import (
)
from prime_rl.trainer.world import get_world
from prime_rl.trainer.runs import setup_runs, Progress, get_runs
from prime_rl.trainer.models.layers.lora import set_multilora_offsets
from prime_rl.trainer.models.layers.lora import set_lora_num_tokens
from prime_rl.utils.heartbeat import Heartbeat
from prime_rl.utils.metrics_server import MetricsServer, RunStats
from prime_rl.utils.monitor import setup_monitor
from prime_rl.utils.pydantic_config import parse_argv
from prime_rl.utils.utils import clean_exit, resolve_latest_ckpt_step, to_col_format
@@ -83,6 +85,13 @@ def train(config: RLTrainerConfig):
logger.info("Initializing heartbeat")
heart = Heartbeat(config.heartbeat.url)
# Setup metrics server (only on rank 0)
metrics_server = None
if config.metrics_server is not None and world.is_master:
logger.info(f"Initializing metrics server on port {config.metrics_server.port}")
metrics_server = MetricsServer(config.metrics_server)
metrics_server.start()
# Set precision
setup_torch_distributed(
timeout=timedelta(seconds=config.dist_timeout_seconds), enable_gloo=config.model.fsdp_cpu_offload
@@ -90,11 +99,30 @@ def train(config: RLTrainerConfig):
torch.set_float32_matmul_precision("high")
# Setup runs and offsets
setup_runs(config.output_dir, config.max_concurrent_runs)
setup_runs(config.output_dir, config.max_concurrent_runs, torch.device("cuda", world.local_rank))
runs = get_runs()
set_multilora_offsets(
torch.tensor([0] * config.max_concurrent_runs, dtype=torch.int32, device=torch.device("cuda", world.local_rank))
)
# Register validation and scaling hooks for LoRA
if config.model.lora:
trainer_lora = config.model.lora
def validate_lora_rank(orch_config) -> tuple[bool, str]:
# Default to trainer's rank if not specified
if orch_config.model.lora.rank is None:
orch_config.model.lora.rank = trainer_lora.rank
if orch_config.model.lora.rank > trainer_lora.rank:
return (
False,
f"model.lora.rank ({orch_config.model.lora.rank}) exceeds trainer max rank ({trainer_lora.rank})",
)
return True, ""
def compute_scaling(orch_config) -> float:
return orch_config.model.lora.alpha / orch_config.model.lora.rank
runs.register_config_validation_hook(validate_lora_rank)
runs.register_scaling_hook(compute_scaling)
# Initialize parallel dimensions
parallel_dims = get_parallel_dims(config.model)
@@ -132,7 +160,7 @@ def train(config: RLTrainerConfig):
scheduler = setup_scheduler(optimizer, config.scheduler, config.max_steps, config.optim.lr)
else:
optimizer = setup_multi_optimizer(config.optim, parallel_dims.world_mesh["dp_shard_cp"])
scheduler = setup_multi_scheduler(optimizer, config.scheduler, config.max_steps, config.optim.lr)
scheduler = setup_multi_scheduler(optimizer, config.scheduler, config.max_steps)
logger.info(f"Using `{config.scheduler.type}` scheduler ({config.scheduler})")
@@ -273,70 +301,82 @@ def train(config: RLTrainerConfig):
advantages = micro_batch["advantages"].to("cuda")
loss_mask = micro_batch["loss_mask"].to("cuda")
inference_logprobs = micro_batch["inference_logprobs"].to("cuda")
teacher_logprobs = (
micro_batch["teacher_logprobs"].to("cuda") if micro_batch["teacher_logprobs"] is not None else None
)
labels = shift_tensor_left(input_ids)
if cp_enabled:
input_ids, forward_position_ids = setup_cp_params(input_ids, position_ids, cp_rank, cp_size, cp_group)
labels = shard_for_cp(labels, cp_rank=cp_rank, cp_world_size=cp_size)
else:
forward_position_ids = position_ids
if config.model.lora:
lora_num_tokens = micro_batch["lora_num_tokens"].to("cuda")
lora_cu_offsets = lora_num_tokens.cumsum(dim=0, dtype=torch.int32)
if cp_enabled:
chunk_size = input_ids.shape[1] # We pad to multiple of cp so this should be fine
logger.debug(f"[Rank {world.rank}] {cp_rank=} {cp_size=} {cp_group=} {chunk_size=}")
# Shift down by seq idx and clip to edges of chunk
lora_cu_offsets = torch.clip(lora_cu_offsets - chunk_size * cp_rank, min=0, max=chunk_size)
set_multilora_offsets(lora_cu_offsets)
# Convert to cumsum, adjust for CP chunk, convert back to num_tokens
cu_offsets = lora_num_tokens.cumsum(dim=0, dtype=torch.int32)
adjusted_cu = torch.clip(cu_offsets - chunk_size * cp_rank, min=0, max=chunk_size)
lora_num_tokens = torch.diff(
adjusted_cu, prepend=torch.tensor([0], device=adjusted_cu.device, dtype=adjusted_cu.dtype)
)
set_lora_num_tokens(lora_num_tokens)
temperature = micro_batch["temperature"]
# Forward pass
with maybe_record_function("forward"), maybe_activation_offloading(config.model.ac_offloading):
logits = forward(model, input_ids, forward_position_ids).float().contiguous()
out = forward(model, input_ids, forward_position_ids, labels=labels, temperature=temperature)
if out.get("logprobs") is None:
assert out.get("logits") is not None, "Logits must be provided to compute logprobs"
logits = out["logits"] / float(temperature)
out["logprobs"] = selective_log_softmax(logits, labels)
out["entropy"] = compute_entropy(logits)
if cp_enabled:
left_pad_logit = get_padding_logit_from_prev_cp_rank(logits, cp_rank, cp_size, cp_group)
else:
left_pad_logit = None
logprobs = dist_nn.all_gather(out["logprobs"], group=cp_group)
out["logprobs"] = torch.cat(logprobs, dim=1)
shifted_logits = shift_logits(logits, left_pad_logit=left_pad_logit)
shifted_logits = shifted_logits / temperature
trainer_logprobs = selective_log_softmax(shifted_logits, input_ids)
entropies = [torch.zeros_like(out["entropy"]) for _ in range(cp_size)]
dist.all_gather(entropies, out["entropy"], group=cp_group)
out["entropy"] = torch.cat(entropies, dim=1)
if cp_enabled:
trainer_logprobs = dist_nn.all_gather(trainer_logprobs, group=cp_group)
trainer_logprobs = torch.cat(trainer_logprobs, dim=1)
vocab_size = model.config.vocab_size
# This is not really necessary as the first token should be masked out, but we do it anyway to be sure
out["logprobs"] = shift_tensor_right(
out["logprobs"], pad_value=torch.log(torch.tensor(1.0 / vocab_size)).item()
)
out["entropy"] = shift_tensor_right(
out["entropy"], pad_value=torch.log(torch.tensor(float(vocab_size))).item()
)
# Compute loss
response_lengths = get_response_lengths(position_ids)
loss, loss_tensors = compute_loss(
trainer_logprobs=trainer_logprobs.squeeze().split(response_lengths),
trainer_logprobs=out["logprobs"].squeeze().split(response_lengths),
inference_logprobs=inference_logprobs.squeeze().split(response_lengths),
teacher_logprobs=teacher_logprobs.squeeze().split(response_lengths)
if teacher_logprobs is not None
else None,
advantages=advantages.squeeze().split(response_lengths),
loss_mask=loss_mask.squeeze().split(response_lengths),
loss_config=config.loss,
loss_scale=loss_scale,
)
# Compute entropy
entropy = compute_entropy(shifted_logits)
if cp_enabled:
entropies = [torch.zeros_like(entropy) for _ in range(cp_size)]
dist.all_gather(entropies, entropy, group=cp_group)
entropy = torch.cat(entropies, dim=1)
# Delete logits and shifted_logits before backward pass to avoid memory spike
del logits, shifted_logits
# Backward pass
with maybe_record_function("backward"):
loss.backward()
# Add relevant tensors to tensor dict for logging purposes
tensors["trainer_probs"].append(torch.exp(trainer_logprobs)[loss_mask].detach().to("cpu"))
tensors["trainer_probs"].append(torch.exp(out["logprobs"])[loss_mask].detach().to("cpu"))
tensors["inference_probs"].append(torch.exp(inference_logprobs)[loss_mask].detach().to("cpu"))
tensors["entropy"].append(entropy[loss_mask].detach().to("cpu"))
tensors["entropy"].append(out["entropy"][loss_mask].detach().to("cpu"))
tensors["loss"].append(loss.detach().to("cpu").unsqueeze(0))
if is_tt_moe_model(model):
@@ -409,7 +449,7 @@ def train(config: RLTrainerConfig):
"perf/peak_memory": peak_memory,
"step": progress.step,
}
monitor.log(perf_metrics)
monitor.log(perf_metrics, step=progress.step)
# Log optimizer metrics
optim_metrics = {
@@ -417,11 +457,11 @@ def train(config: RLTrainerConfig):
"optim/grad_norm": grad_norm.item(),
"step": progress.step,
}
monitor.log(optim_metrics)
monitor.log(optim_metrics, step=progress.step)
# Log tensor stats
tensor_stats["step"] = progress.step
monitor.log(tensor_stats)
monitor.log(tensor_stats, step=progress.step)
# Log time metrics
time_metrics = {
@@ -433,12 +473,51 @@ def train(config: RLTrainerConfig):
"time/forward_backward": forward_backward_time,
"step": progress.step,
}
monitor.log(time_metrics)
monitor.log(time_metrics, step=progress.step)
# Log disk metrics
disk_metrics = get_ckpt_disk_metrics(config.output_dir)
disk_metrics["step"] = progress.step
monitor.log(disk_metrics)
monitor.log(disk_metrics, step=progress.step)
# Update Prometheus metrics if configured
if metrics_server is not None:
metrics_server.update(
step=progress.step,
loss=tensor_stats["loss/mean"],
throughput=throughput,
grad_norm=grad_norm.item(),
peak_memory_gib=peak_memory,
learning_rate=current_lr,
mfu=mfu,
entropy=tensor_stats.get("entropy/mean", 0.0),
mismatch_kl=tensor_stats.get("mismatch_kl/mean", 0.0),
)
# Update run/LoRA metrics
runs = get_runs()
runs_discovered = len(list(config.output_dir.glob("run_*")))
run_stats = []
for idx in runs.used_idxs:
run_id = runs.idx_2_id[idx]
run_progress = runs.progress[idx]
if config.max_concurrent_runs == 1:
lr = optimizer.param_groups[0]["lr"]
else:
lr = optimizer.get_current_lr(idx) if optimizer.optimizers[idx] else 0.0
run_stats.append(
RunStats(
run_id=run_id,
step=run_progress.step,
total_tokens=run_progress.total_tokens,
learning_rate=lr,
ready=runs.ready_to_update[idx],
)
)
metrics_server.update_runs(
runs_discovered=runs_discovered,
runs_max=runs.max_runs,
run_stats=run_stats,
)
progress.step += 1
is_first_step = False
@@ -470,6 +549,10 @@ def train(config: RLTrainerConfig):
logger.info(f"Peak memory: {max(to_col_format(monitor.history)['perf/peak_memory']):.1f} GiB")
logger.success("RL trainer finished!")
# Stop metrics server if configured
if metrics_server is not None:
metrics_server.stop()
# Optionally, print benchmark table
if config.bench and world.is_master:
print_benchmark(to_col_format(monitor.history))
+121 -21
View File
@@ -26,7 +26,7 @@ class Progress:
class Runs:
"""This class stores information about the runs in the system."""
def __init__(self, output_dir: Path, max_runs: int):
def __init__(self, output_dir: Path, max_runs: int, device: torch.device = torch.device("cpu")):
self.output_dir = output_dir
self.max_runs = max_runs
self.logger = get_logger()
@@ -40,6 +40,10 @@ class Runs:
self.ready_to_update = [False] * max_runs
self._creation_hooks: list[Callable[[int, str], None]] = []
self._create_run_data_hooks: list[Callable[[int, str, "OrchestratorConfig"], None]] = []
self._delete_run_data_hooks: list[Callable[[int, str], None]] = []
self._config_validation_hooks: list[Callable[["OrchestratorConfig"], tuple[bool, str]]] = []
self._scaling_hook: Callable[["OrchestratorConfig"], float] | None = None
# We use the store to keep other ranks in sync with master
self.store = c10d._get_default_store()
@@ -50,52 +54,123 @@ class Runs:
# Store modules with their FQN prefixes for parameter management
self._modules: list[tuple[str, "MultiLoRALinear"]] = []
# Initialize lora globals on device so runs.* ARE the global tensors
from prime_rl.trainer.models.layers.lora import (
get_lora_num_tokens,
get_multilora_scaling,
set_lora_num_tokens,
set_multilora_scaling,
)
# We first set to None so we dont check the shape
# Might be better to not have the check at all but this will do for now
set_lora_num_tokens(None, reset_reference=True)
set_multilora_scaling(None, reset_reference=True)
set_lora_num_tokens(torch.zeros(max_runs, dtype=torch.int32, device=device), reset_reference=True)
self.lora_num_tokens = get_lora_num_tokens()
set_multilora_scaling(
torch.ones(max_runs, dtype=torch.bfloat16, device=device) * 1000_000.0, reset_reference=True
)
self.scaling_factors = get_multilora_scaling()
def register_config_validation_hook(self, hook: Callable[["OrchestratorConfig"], tuple[bool, str]]) -> None:
"""Register a hook to validate orchestrator config when a run is created.
Args:
hook: A callable that takes (config: OrchestratorConfig) and returns
(is_valid: bool, error_message: str). Error message is used when invalid.
"""
self._config_validation_hooks.append(hook)
def register_scaling_hook(self, hook: Callable[["OrchestratorConfig"], float]) -> None:
"""Register a hook to compute LoRA scaling factor for a run.
Args:
hook: A callable that takes (config: OrchestratorConfig) and returns the scaling factor.
"""
self._scaling_hook = hook
def register_create_run_data_hook(self, hook: Callable[[int, str, "OrchestratorConfig"], None]) -> None:
"""Register a hook to be called when run data is created (master only).
Args:
hook: A callable that takes (idx: int, run_id: str, config: OrchestratorConfig).
Called only on master rank when a new run's data structures are initialized.
"""
self._create_run_data_hooks.append(hook)
def register_delete_run_data_hook(self, hook: Callable[[int, str], None]) -> None:
"""Register a hook to be called when run data is deleted (master only).
Args:
hook: A callable that takes (idx: int, run_id: str).
Called only on master rank when a run's data structures are being deleted.
"""
self._delete_run_data_hooks.append(hook)
def get_orchestrator_config(self, run_id: str) -> Optional["OrchestratorConfig"]:
# Load orchestrator config first to validate it
"""Load and validate orchestrator config for a run.
Returns None if config doesn't exist, fails to parse, or fails validation.
Writes error to config dir for orchestrator to consume.
"""
config_path = self.output_dir / run_id / "configs" / "orch.toml"
config_dir = config_path.parent
error_path = config_dir / "error.txt"
if not config_path.exists():
# Skip run if no config exists
if not error_path.exists():
config_dir.mkdir(parents=True, exist_ok=True)
with open(error_path, "w") as f:
f.write(f"Error: No orchestrator config found at {config_path}\n")
self.logger.error(f"Error: No orchestrator config found at {config_path}")
f.write(f"No orchestrator config found at {config_path}\n")
self.logger.error(f"Run {run_id}: No orchestrator config found at {config_path}")
return None
try:
# Import here to avoid circular dependency
with open(config_path, "rb") as f:
config_dict = tomli.load(f)
# Parse config with Pydantic validation
from prime_rl.orchestrator.config import OrchestratorConfig
config = OrchestratorConfig(**config_dict)
# Remove error file if it exists (config is now valid)
if error_path.exists():
error_path.unlink()
except Exception as e:
# Write error to file and skip this run
config_dir.mkdir(parents=True, exist_ok=True)
with open(error_path, "w") as f:
f.write(f"Error parsing orchestrator config:\n{str(e)}\n")
self.logger.error(f"Error parsing orchestrator config for run {run_id}: {e}")
self.logger.error(f"Run {run_id}: Error parsing orchestrator config: {e}")
return None
# Run registered validation hooks
for hook in self._config_validation_hooks:
is_valid, error_message = hook(config)
if not is_valid:
self.logger.error(f"Run {run_id}: {error_message}")
config_dir.mkdir(parents=True, exist_ok=True)
with open(error_path, "w") as f:
f.write(f"{error_message}\n")
return None
# Config is valid, remove any stale error file
if error_path.exists():
error_path.unlink()
return config
def _delete_run_data(self, deleted_run: str, deleted_idx: int) -> None:
"""Update data structures for a deleted run"""
# Call delete hooks before removing data
for hook in self._delete_run_data_hooks:
hook(deleted_idx, deleted_run)
del self.progress[deleted_idx]
if deleted_idx in self.config:
del self.config[deleted_idx]
# A big value might help make it error loudly
self.scaling_factors[deleted_idx] = 1000_000.0
# Process mappings
self.unused_idxs.add(deleted_idx)
del self.idx_2_id[deleted_idx]
@@ -140,7 +215,6 @@ class Runs:
for new_run in new_runs:
try:
# Process mappings
new_id = next(iter(self.unused_idxs))
config = self.get_orchestrator_config(new_run)
@@ -148,6 +222,8 @@ class Runs:
continue
self._create_run_data(new_run, new_id, config)
for hook in self._create_run_data_hooks:
hook(new_id, new_run, config)
except StopIteration:
continue
@@ -160,9 +236,21 @@ class Runs:
"""
if self.world.is_master:
# Compute scaling factors for new runs before sync
new_runs = self.id_2_idx.keys() - self._last_synced_id_2_idx.keys()
for new_run in new_runs:
new_id = self.id_2_idx[new_run]
if self._scaling_hook is not None:
self.scaling_factors[new_id] = self._scaling_hook(self.config[new_id])
# Include configs for new runs so non-master ranks have them
new_configs = {new_run: self.config[self.id_2_idx[new_run]] for new_run in new_runs}
sync_data = {
"id_2_idx": self.id_2_idx,
"ready_to_update": self.ready_to_update,
"scaling_factors": self.scaling_factors.cpu(),
"new_configs": new_configs,
}
self.store.set("runs", pickle.dumps(sync_data))
dist.barrier()
@@ -175,6 +263,8 @@ class Runs:
sync_data: dict = pickle.loads(self.store.get("runs"))
new_id_2_idx: dict[str, int] = sync_data["id_2_idx"]
self.ready_to_update = sync_data["ready_to_update"]
self.scaling_factors.copy_(sync_data["scaling_factors"])
new_configs: dict[str, "OrchestratorConfig"] = sync_data["new_configs"]
new_runs = new_id_2_idx.keys() - self.id_2_idx.keys()
deleted_runs = self.id_2_idx.keys() - new_id_2_idx.keys()
@@ -186,8 +276,7 @@ class Runs:
for new_run in new_runs:
new_id = new_id_2_idx[new_run]
config = {} # The other ranks dont need them for now
self._create_run_data(new_run, new_id, config) # type: ignore[arg-type]
self._create_run_data(new_run, new_id, new_configs[new_run])
for new_run in new_runs:
new_id = self.id_2_idx[new_run]
@@ -257,7 +346,18 @@ class Runs:
Returns:
State dict for the specified run index
"""
return {name: param.detach() for name, param in self.get_named_parameters_for_run(idx)}
state_dict = {}
for prefix, module in self._modules:
# Check if module has a custom state_dict_for_adapter method (e.g., MoE modules)
# which returns vLLM-compatible per-expert format
if hasattr(module, "state_dict_for_adapter"):
for name, tensor in module.state_dict_for_adapter(idx).items():
state_dict[f"{prefix}.{name}"] = tensor.detach()
else:
# Default: use named_parameters_for_adapter
for name, param in module.named_parameters_for_adapter(idx):
state_dict[f"{prefix}.{name}.weight"] = param.detach()
return state_dict
def reset_run_parameters(self, idx: int) -> None:
"""Reset parameters for a specific run index.
@@ -286,6 +386,6 @@ def get_runs() -> Runs:
return _RUNS
def setup_runs(output_dir: Path, max_runs: int):
def setup_runs(output_dir: Path, max_runs: int, device: torch.device):
global _RUNS
_RUNS = Runs(output_dir, max_runs)
_RUNS = Runs(output_dir, max_runs, device)
+3 -5
View File
@@ -123,11 +123,9 @@ class MultiLoRAScheduler:
self,
scheduler_config: SchedulerConfigType,
max_steps: int | None,
lr: float,
):
self.scheduler_config = scheduler_config
self.max_steps = max_steps
self.lr = lr
self.runs = get_runs()
self.logger = get_logger()
@@ -138,11 +136,12 @@ class MultiLoRAScheduler:
This should be called after an optimizer is created for a run.
"""
lr = self.runs.config[idx].optim.lr
self.schedulers[idx] = setup_scheduler(
optimizer,
self.scheduler_config,
self.max_steps,
self.lr,
lr,
)
def step(self) -> None:
@@ -171,10 +170,9 @@ def setup_multi_scheduler(
optimizer: "MultiLoRAOptimizer",
scheduler_config: SchedulerConfigType,
max_steps: int | None,
lr: float,
) -> MultiLoRAScheduler:
"""Create a MultiLoRAScheduler for managing per-run schedulers."""
scheduler = MultiLoRAScheduler(scheduler_config, max_steps, lr)
scheduler = MultiLoRAScheduler(scheduler_config, max_steps)
# Register callback so schedulers are created when optimizers are created
optimizer.register_post_creation_callback(scheduler.scheduler_creation_hook)
return scheduler
+8
View File
@@ -236,3 +236,11 @@ class SFTTrainerConfig(BaseSettings):
if self.tokenizer.trust_remote_code is None:
self.tokenizer.trust_remote_code = self.model.trust_remote_code
return self
@model_validator(mode="after")
def validate_no_chunked_loss(self):
if self.model.fused_lm_head_chunk_size is not None:
raise ValueError(
"Chunked loss is not supported for SFT training yet, please set `model.fused_lm_head_chunk_size` to None"
)
return self
+10 -8
View File
@@ -240,7 +240,9 @@ def train(config: SFTTrainerConfig):
# Forward pass
logger.debug("Starting forward pass")
with maybe_record_function("forward"), maybe_activation_offloading(config.model.ac_offloading):
logits = forward(model, input_ids, position_ids)
out = forward(model, input_ids, position_ids)
logits = out["logits"]
B, L, V = logits.shape
# Compute loss
@@ -342,7 +344,7 @@ def train(config: SFTTrainerConfig):
for subset_or_split, num_tokens in dataset.num_tokens.items()
},
)
monitor.log(progress_metrics)
monitor.log(progress_metrics, step=progress.step)
# Log performance metrics
perf_metrics = {
@@ -352,7 +354,7 @@ def train(config: SFTTrainerConfig):
"perf/mfu": mfu,
"step": progress.step,
}
monitor.log(perf_metrics)
monitor.log(perf_metrics, step=progress.step)
# Log optimizer metrics
optim_metrics = {
@@ -360,7 +362,7 @@ def train(config: SFTTrainerConfig):
"optim/grad_norm": grad_norm.item(),
"step": progress.step,
}
monitor.log(optim_metrics)
monitor.log(optim_metrics, step=progress.step)
loss_log_metrics = {
"loss/mean": batch_loss.item(),
@@ -368,7 +370,7 @@ def train(config: SFTTrainerConfig):
"step": progress.step,
}
# Log tensor stats
monitor.log(loss_log_metrics)
monitor.log(loss_log_metrics, step=progress.step)
# Log time metrics
time_metrics = {
@@ -377,19 +379,19 @@ def train(config: SFTTrainerConfig):
"time/forward_backward": forward_backward_time,
"step": progress.step,
}
monitor.log(time_metrics)
monitor.log(time_metrics, step=progress.step)
# Log disk metrics
disk_metrics = get_ckpt_disk_metrics(config.output_dir)
disk_metrics["step"] = progress.step
monitor.log(disk_metrics)
monitor.log(disk_metrics, step=progress.step)
if is_tt_moe_model(model):
max_vio_log_metrics = {
"max_vio/mean": batch_max_vio.item(),
"step": progress.step,
}
monitor.log(max_vio_log_metrics)
monitor.log(max_vio_log_metrics, step=progress.step)
is_first_step = False
progress.step += 1
+7
View File
@@ -50,6 +50,13 @@ class TrainingBatchReceiver(ABC):
"""
pass
def reset_run(self, idx: int) -> None:
"""Reset state for a run index. Called when a run is deleted and replaced.
Override in subclasses that maintain per-run state.
"""
pass
def close(self) -> None:
"""Clean up any resources. Override if needed."""
pass
+23 -2
View File
@@ -39,12 +39,22 @@ class FileSystemTrainingBatchReceiver(TrainingBatchReceiver):
self._last_logged_paths: list[Path] | None = None
self._last_logged_time = time()
self._waiting_since: float | None = None
# Track received steps per run independently of runs.progress[idx].step
# This prevents duplicate reads when trainer step != orchestrator step
self._received_steps: dict[int, int] = {}
def _get_received_step(self, idx: int) -> int:
"""Get the next step to receive for a run, initializing from progress if needed."""
if idx not in self._received_steps:
# Initialize from runs.progress on first access (for checkpoint resume)
self._received_steps[idx] = self.runs.progress[idx].step
return self._received_steps[idx]
def _get_batch_path(self, idx: int) -> Path:
"""Get the batch file path for a specific run at its current step."""
"""Get the batch file path for a specific run at its next step to receive."""
run_dir = self.runs.get_run_dir(idx)
rollout_dir = get_rollout_dir(run_dir)
step = self.runs.progress[idx].step
step = self._get_received_step(idx)
return get_step_path(rollout_dir, step) / BATCH_FILE_NAME
def can_receive(self) -> bool:
@@ -87,10 +97,21 @@ class FileSystemTrainingBatchReceiver(TrainingBatchReceiver):
batch: TrainingBatch = self.decoder.decode(f.read())
batch.run_idx = idx
batches.append(batch)
# Increment received step to avoid reading the same file again
self._received_steps[idx] = self._get_received_step(idx) + 1
except Exception as e:
self.logger.error(f"Error loading rollouts for run {idx}: {e}")
return batches
def reset_run(self, idx: int) -> None:
"""Reset received step tracking for a run index.
Called when a run is deleted and a new run takes its place.
The next access to _get_received_step will re-initialize from runs.progress.
"""
if idx in self._received_steps:
del self._received_steps[idx]
class FileSystemMicroBatchSender(MicroBatchSender):
"""Filesystem-based micro batch sender that writes micro batches to disk."""
+4 -1
View File
@@ -10,7 +10,9 @@ class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=Tr
completion_ids: list[int]
completion_mask: list[bool]
completion_logprobs: list[float]
teacher_logprobs: list[float] | None = None
advantage: float | None = None
reward: float | None = None
class TrainingBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
@@ -31,5 +33,6 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
advantages: list[float]
inference_logprobs: list[float]
position_ids: list[int]
temperature: float
teacher_logprobs: list[float] | None = None
lora_num_tokens: list[int] | None = None
temperature: float | None = None
+41 -9
View File
@@ -6,6 +6,7 @@ import httpx
from httpx import AsyncClient
from openai import AsyncOpenAI, NotFoundError
from prime_evals import AsyncEvalsClient
from tenacity import retry, retry_if_exception, stop_after_attempt, wait_exponential
from prime_rl.utils.config import ClientConfig
from prime_rl.utils.logger import get_logger
@@ -101,10 +102,20 @@ async def check_health(
await asyncio.gather(*[_check_health(admin_client) for admin_client in admin_clients])
NCCL_READY_MARKER = "NCCL_READY"
async def update_weights(
admin_clients: list[AsyncClient], weight_dir: Path | None, lora_name: str | None = None
admin_clients: list[AsyncClient],
weight_dir: Path | None,
lora_name: str | None = None,
) -> None:
"""Make a HTTP post request to the vLLM server to update the weights."""
"""Make a HTTP post request to the vLLM server to update the weights.
Creates a NCCL_READY marker file before calling the update endpoint to signal
to the trainer that inference workers are about to enter the receive path.
This marker is only used in NCCL broadcast mode but is harmless in filesystem mode.
"""
logger = get_logger()
weight_dir_posix = weight_dir.as_posix() if weight_dir is not None else None
@@ -123,6 +134,13 @@ async def update_weights(
return
raise
# Create ready marker before servers enter receive path (used by NCCL broadcast)
if weight_dir is not None:
nccl_ready_file = weight_dir / NCCL_READY_MARKER
nccl_ready_file.parent.mkdir(parents=True, exist_ok=True)
nccl_ready_file.touch()
logger.debug(f"Created NCCL_READY marker at {nccl_ready_file}")
await asyncio.gather(*[_update_weights(admin_client, weight_dir_posix) for admin_client in admin_clients])
@@ -144,20 +162,34 @@ async def reload_weights(admin_clients: list[AsyncClient]) -> None:
await asyncio.gather(*[_reload_weights(admin_client) for admin_client in admin_clients])
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."""
logger = get_logger()
def _is_retryable_lora_error(exception: BaseException) -> bool:
"""Check if an exception should trigger a retry for LoRA loading."""
if isinstance(exception, httpx.HTTPStatusError):
# Retry on 404 (adapter not found) or 500 (server error during loading)
return exception.response.status_code in (404, 500)
return False
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.
Retries with exponential backoff if the adapter files are not found,
which can happen due to NFS propagation delays.
"""
logger = get_logger()
lora_path_posix = lora_path.as_posix()
@retry(
retry=retry_if_exception(_is_retryable_lora_error),
stop=stop_after_attempt(10),
wait=wait_exponential(multiplier=1, min=1, max=30),
reraise=True,
)
async def _load_lora_adapter(admin_client: AsyncClient) -> None:
logger.debug(f"Sending request to load LoRA adapter {lora_name} from {lora_path}")
response = await admin_client.post(
"/v1/load_lora_adapter",
json={
"lora_name": lora_name,
"lora_path": lora_path_posix,
},
json={"lora_name": lora_name, "lora_path": lora_path_posix},
)
response.raise_for_status()
+27
View File
@@ -73,6 +73,13 @@ class LogConfig(BaseConfig):
),
] = True
env_worker_logs: Annotated[
bool,
Field(
description="Whether env workers log to files. If True, workers write to logs/env_workers/{env_name}.log.",
),
] = False
log_data: Annotated[
bool,
Field(
@@ -171,3 +178,23 @@ class HeartbeatConfig(BaseConfig):
"""Configures the heartbeat for BetterStack."""
url: Annotated[str, Field(description="The URL to send the heartbeat to.")]
class MetricsServerConfig(BaseConfig):
"""Configures the Prometheus metrics server for trainer observability."""
port: Annotated[
int,
Field(
ge=1,
le=65535,
description="Port to expose metrics and health endpoints. Defaults to 8000.",
),
] = 8000
host: Annotated[
str,
Field(
description="Host to bind the server to. Defaults to 0.0.0.0.",
),
] = "0.0.0.0"
+1 -2
View File
@@ -77,9 +77,8 @@ def setup_cp_params(
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.
*extra_tensors: Extra tensors to prepare for context parallelism.
Returns:
The prepared input for context parallelism.
The sharded input_ids and position_ids for context parallelism.
"""
input_ids = shard_for_cp(input_ids, cp_rank=cp_rank, cp_world_size=cp_world_size)
+33 -4
View File
@@ -1,3 +1,4 @@
import logging
import sys
from pathlib import Path
@@ -8,17 +9,36 @@ NO_BOLD = "\033[22m"
RESET = "\033[0m"
def setup_logger(log_level: str, log_file: Path | None = None):
class _VerifiersInterceptHandler(logging.Handler):
"""Intercept stdlib logging from verifiers and route to loguru with [verifiers] tag."""
def emit(self, record: logging.LogRecord) -> None:
logger = get_logger()
try:
level = logger.level(record.levelname).name
except ValueError:
level = record.levelno
frame, depth = logging.currentframe(), 2
while frame and frame.f_code.co_filename == logging.__file__:
frame = frame.f_back
depth += 1
logger.opt(depth=depth, exception=record.exc_info).log(level, f"[verifiers] {record.getMessage()}")
def setup_logger(log_level: str, log_file: Path | None = None, append: bool = False, tag: str | None = None):
global _LOGGER
if _LOGGER is not None:
raise RuntimeError("Logger already set. Please call `setup_logger` only once.")
# Format message
# Format message with optional tag prefix
tag_prefix = f"[{tag}] " if tag else ""
message = "".join(
[
" <level>{level: >7}</level>",
f" <level>{NO_BOLD}",
"{message}",
f"{tag_prefix}{{message}}",
f"{RESET}</level>",
]
)
@@ -52,7 +72,7 @@ def setup_logger(log_level: str, log_file: Path | None = None):
# If specified, install file handler
if log_file is not None:
if log_file.exists():
if not append and log_file.exists():
log_file.unlink()
logger.add(log_file, format=format, level=log_level.upper(), colorize=True)
@@ -84,3 +104,12 @@ def reset_logger():
"""Reset the global logger. Useful mainly in test to clear loggers between tests."""
global _LOGGER
_LOGGER = None
def intercept_verifiers_logging(level: str = "DEBUG"):
"""Intercept all verifiers stdlib logging and route through prime-rl loguru with [verifiers] tag."""
vf_logger = logging.getLogger("verifiers")
vf_logger.handlers.clear()
vf_logger.addHandler(_VerifiersInterceptHandler())
vf_logger.setLevel(level.upper())
vf_logger.propagate = False
+230
View File
@@ -0,0 +1,230 @@
"""Prometheus metrics server for trainer observability.
Exposes training metrics at /metrics in Prometheus format.
Also exposes /health endpoint for Kubernetes liveness probes.
Runs in a background thread to avoid blocking the training loop.
"""
import threading
import time
from dataclasses import dataclass
from http.server import BaseHTTPRequestHandler, HTTPServer
from typing import TYPE_CHECKING
from loguru import logger
if TYPE_CHECKING:
from prime_rl.utils.config import MetricsServerConfig
try:
from prometheus_client import CONTENT_TYPE_LATEST, CollectorRegistry, Gauge, generate_latest
PROMETHEUS_AVAILABLE = True
except ImportError:
PROMETHEUS_AVAILABLE = False
@dataclass
class RunStats:
"""Statistics for a single run/LoRA adapter."""
run_id: str
step: int
total_tokens: int
learning_rate: float
ready: bool
class MetricsServer:
"""Prometheus metrics server for trainer observability.
Uses an isolated CollectorRegistry to avoid global state pollution.
Disabled by default - enable by setting `metrics_server` in trainer config.
"""
def __init__(self, config: "MetricsServerConfig"):
self.config = config
self._server: HTTPServer | None = None
self._thread: threading.Thread | None = None
self._started = False
if PROMETHEUS_AVAILABLE:
self._registry = CollectorRegistry()
self._step = Gauge("trainer_step", "Current training step", registry=self._registry)
self._loss = Gauge("trainer_loss", "Current training loss", registry=self._registry)
self._throughput = Gauge(
"trainer_throughput_tokens_per_sec", "Training throughput in tokens/sec", registry=self._registry
)
self._last_step_ts = Gauge(
"trainer_last_step_timestamp_seconds", "Unix timestamp of last step", registry=self._registry
)
self._grad_norm = Gauge("trainer_grad_norm", "Gradient norm", registry=self._registry)
self._peak_mem = Gauge("trainer_peak_memory_gib", "Peak GPU memory in GiB", registry=self._registry)
self._lr = Gauge("trainer_learning_rate", "Current learning rate", registry=self._registry)
self._mfu = Gauge("trainer_mfu_percent", "Model FLOPS utilization %", registry=self._registry)
self._entropy = Gauge("trainer_entropy", "Mean entropy", registry=self._registry)
self._mismatch_kl = Gauge(
"trainer_mismatch_kl", "KL divergence between trainer and inference model", registry=self._registry
)
# Aggregate run metrics
self._runs_discovered = Gauge(
"trainer_runs_discovered", "Number of run folders discovered", registry=self._registry
)
self._runs_active = Gauge(
"trainer_runs_active", "Number of runs with assigned slots", registry=self._registry
)
self._runs_ready = Gauge(
"trainer_runs_ready", "Number of runs ready for gradient updates", registry=self._registry
)
self._runs_max = Gauge("trainer_runs_max", "Maximum run capacity", registry=self._registry)
# Per-run metrics with labels
self._run_step = Gauge(
"trainer_run_step", "Training step for run", ["run"], registry=self._registry
)
self._run_tokens = Gauge(
"trainer_run_tokens", "Total tokens processed by run", ["run"], registry=self._registry
)
self._run_learning_rate = Gauge(
"trainer_run_learning_rate", "Current learning rate for run", ["run"], registry=self._registry
)
self._run_ready = Gauge(
"trainer_run_ready", "Whether run is ready for updates (1=ready, 0=not ready)", ["run"], registry=self._registry
)
# Track known run labels for cleanup
self._known_runs: set[str] = set()
else:
self._registry = None
def _make_handler(self):
"""Create handler class with access to our registry."""
registry = self._registry
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/metrics":
self._handle_metrics()
elif self.path == "/health":
self._handle_health()
else:
self.send_response(404)
self.end_headers()
def _handle_metrics(self):
self.send_response(200)
if registry is not None:
self.send_header("Content-Type", CONTENT_TYPE_LATEST)
self.end_headers()
self.wfile.write(generate_latest(registry))
else:
self.send_header("Content-Type", "text/plain")
self.end_headers()
self.wfile.write(b"# prometheus_client not installed\n")
def _handle_health(self):
"""Simple liveness probe - returns 200 if server is running."""
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.end_headers()
self.wfile.write(b"ok\n")
def log_message(self, format, *args):
pass
return Handler
def start(self) -> None:
"""Start the metrics server in a background thread."""
if self._started:
logger.warning("Metrics server already started")
return
if not PROMETHEUS_AVAILABLE:
logger.warning("prometheus_client not installed. Install with: uv sync --extra metrics")
self._server = HTTPServer((self.config.host, self.config.port), self._make_handler())
self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
self._thread.start()
self._started = True
logger.info(f"Metrics server started at http://{self.config.host}:{self.config.port}/metrics")
logger.info(f"Health endpoint available at http://{self.config.host}:{self.config.port}/health")
def stop(self) -> None:
"""Stop the metrics server and release the port."""
if self._server is not None:
self._server.shutdown()
self._server.server_close() # Close socket to release port
if self._thread is not None:
self._thread.join(timeout=5.0) # Wait for thread to finish
self._server = None
self._thread = None
self._started = False
logger.info("Metrics server stopped")
def update(
self,
step: int,
loss: float,
throughput: float,
grad_norm: float,
peak_memory_gib: float,
learning_rate: float,
mfu: float = 0.0,
entropy: float = 0.0,
mismatch_kl: float = 0.0,
) -> None:
"""Update metrics after a training step."""
if not PROMETHEUS_AVAILABLE:
return
self._step.set(step)
self._loss.set(loss)
self._throughput.set(throughput)
self._grad_norm.set(grad_norm)
self._peak_mem.set(peak_memory_gib)
self._lr.set(learning_rate)
self._mfu.set(mfu)
self._entropy.set(entropy)
self._mismatch_kl.set(mismatch_kl)
self._last_step_ts.set(time.time())
def update_runs(
self,
runs_discovered: int,
runs_max: int,
run_stats: list[RunStats],
) -> None:
"""Update run/LoRA metrics.
Args:
runs_discovered: Number of run_* folders found in output directory
runs_max: Maximum run capacity
run_stats: List of per-run statistics
"""
if not PROMETHEUS_AVAILABLE:
return
# Update aggregate metrics
self._runs_discovered.set(runs_discovered)
self._runs_active.set(len(run_stats))
self._runs_ready.set(sum(1 for r in run_stats if r.ready))
self._runs_max.set(runs_max)
# Track current runs for cleanup
current_runs = {r.run_id for r in run_stats}
# Remove metrics for runs that no longer exist
removed_runs = self._known_runs - current_runs
for run_id in removed_runs:
self._run_step.remove(run_id)
self._run_tokens.remove(run_id)
self._run_learning_rate.remove(run_id)
self._run_ready.remove(run_id)
# Update per-run metrics
for run in run_stats:
self._run_step.labels(run=run.run_id).set(run.step)
self._run_tokens.labels(run=run.run_id).set(run.total_tokens)
self._run_learning_rate.labels(run=run.run_id).set(run.learning_rate)
self._run_ready.labels(run=run.run_id).set(1 if run.ready else 0)
self._known_runs = current_runs
+2 -2
View File
@@ -12,7 +12,7 @@ class Monitor(ABC):
"""
@abstractmethod
def log(self, metrics: dict[str, Any]) -> None:
def log(self, metrics: dict[str, Any], step: int | None = None) -> None:
pass
@abstractmethod
@@ -42,7 +42,7 @@ class NoOpMonitor(Monitor):
def __init__(self):
self.history: list[dict[str, Any]] = []
def log(self, metrics: dict[str, Any]) -> None:
def log(self, metrics: dict[str, Any], step: int | None = None) -> None:
self.history.append(metrics)
def log_samples(self, rollouts: list[vf.State], step: int) -> None:
+2 -2
View File
@@ -19,10 +19,10 @@ class MultiMonitor(Monitor):
return []
return self.monitors[0].history
def log(self, metrics: dict[str, Any]) -> None:
def log(self, metrics: dict[str, Any], step: int | None = None) -> None:
for monitor in self.monitors:
try:
monitor.log(metrics)
monitor.log(metrics, step=step)
except Exception as e:
self.logger.warning(f"Failed to log metrics to {monitor.__class__.__name__}: {e}")
+20 -6
View File
@@ -61,11 +61,14 @@ class PrimeMonitor(Monitor):
return
self.run_id = run_id
# Set up async HTTP client with background event loop
self._loop: asyncio.AbstractEventLoop = asyncio.new_event_loop()
self._thread = Thread(target=self._run_event_loop, daemon=True)
self._thread.start()
self._client = httpx.AsyncClient(timeout=30)
# Set up async HTTP client with background event loop.
# Evals can run in a forked subprocess (see run_evals_subprocess in eval/utils.py). When a
# process forks, only the calling thread survives - our background thread running the
# event loop is not copied. The Thread object still exists but the OS thread is gone,
# so asyncio.run_coroutine_threadsafe() silently fails. We use register_at_fork to
# recreate the thread, event loop, and HTTP client in the child process.
self._init_async_client()
os.register_at_fork(after_in_child=self._reinit_after_fork)
# Optionally, initialize sample logging attributes
if config is not None and config.log_extras:
@@ -75,7 +78,7 @@ class PrimeMonitor(Monitor):
if config.log_extras.distributions:
self.last_log_distributions_step = -1
def log(self, metrics: dict[str, Any]) -> None:
def log(self, metrics: dict[str, Any], step: int | None = None) -> None:
self.history.append(metrics)
if not self.is_master:
return
@@ -251,6 +254,17 @@ class PrimeMonitor(Monitor):
"""Destructor to ensure cleanup."""
self.close()
def _init_async_client(self) -> None:
"""Initialize the event loop, background thread, and HTTP client."""
self._loop: asyncio.AbstractEventLoop = asyncio.new_event_loop()
self._thread = Thread(target=self._run_event_loop, daemon=True)
self._thread.start()
self._client = httpx.AsyncClient(timeout=30)
def _reinit_after_fork(self) -> None:
"""Reinitialize thread and event loop after fork."""
self._init_async_client()
def _run_event_loop(self) -> None:
"""Run the async event loop in a background thread."""
asyncio.set_event_loop(self._loop)
+2 -2
View File
@@ -71,13 +71,13 @@ class WandbMonitor(Monitor):
self.logger.debug(f"Found WANDB_ARGS in environment variables {wandb_args}")
sys.argv = json.loads(wandb_args)
def log(self, metrics: dict[str, Any]) -> None:
def log(self, metrics: dict[str, Any], step: int | None = None) -> None:
self.history.append(metrics)
if not self.is_master:
return
if not self.enabled:
return
wandb.log(metrics, step=metrics.get("step", None))
wandb.log(metrics, step=step)
def log_samples(self, rollouts: list[vf.State], step: int) -> None:
"""Logs rollouts to W&B table."""
+12 -3
View File
@@ -29,18 +29,27 @@ def get_broadcast_dir(output_dir: Path) -> Path:
return output_dir / "broadcasts"
def get_env_worker_log_file(output_dir: Path, env_name: str) -> Path:
return output_dir / "logs" / "env_workers" / f"{env_name}.log"
def get_step_path(path: Path, step: int) -> Path:
return path / f"step_{step}"
def get_all_ckpt_steps(ckpt_dir: Path) -> list[int]:
"""Gets all checkpoint steps from the checkpoint directory, sorted in ascending order."""
step_dirs = list(ckpt_dir.glob("step_*"))
return sorted([int(step_dir.name.split("_")[-1]) for step_dir in step_dirs])
def resolve_latest_ckpt_step(ckpt_dir: Path) -> int | None:
"""Gets the latest checkpoint step from the checkpoint directory. Returns None if no checkpoints are found."""
step_dirs = list(ckpt_dir.glob("step_*"))
if len(step_dirs) == 0:
steps = get_all_ckpt_steps(ckpt_dir)
if len(steps) == 0:
logger = get_logger()
logger.warning(f"No checkpoints found in {ckpt_dir}. Starting from scratch.")
return None
steps = sorted([int(step_dir.name.split("_")[-1]) for step_dir in step_dirs])
latest_step = steps[-1]
logger = get_logger()
logger.info(f"Found latest checkpoint in {ckpt_dir}: {latest_step}")
+1
View File
@@ -17,6 +17,7 @@ from prime_rl.utils.logger import get_logger
# TODO: Change all imports to use utils.pathing
# ruff: noqa: F401
from prime_rl.utils.pathing import (
get_all_ckpt_steps,
get_broadcast_dir,
get_ckpt_dir,
get_eval_dir,
+2 -2
View File
@@ -129,7 +129,7 @@ def multi_run_result(
"configs/ci/integration/rl_multi_run/orchestrator.toml",
"--output-dir",
run_dir.as_posix(),
"--lora-name",
"--model.lora.name",
name,
"--wandb.project",
wandb_project,
@@ -227,5 +227,5 @@ def test_reward_in_range(multi_run_result: tuple[dict[str, ProcessResult], str],
log_file = output_dir / f"run_{name}" / "logs" / "orchestrator.stdout"
with open(log_file, "r") as f:
lines = strip_escape_codes(f.read()).splitlines()
check_number_in_range(lines, step=4, min_threshold=0.2, max_threshold=0.5, pattern=r"Reward:\s*(\d+\.\d{4})")
check_number_in_range(lines, step=9, min_threshold=0.2, max_threshold=0.6, pattern=r"Reward:\s*(\d+\.\d{4})")
check_number_in_range(lines, min_threshold=0.65, pattern=r"Reward:\s*(\d+\.\d{4})")
+1
View File
@@ -13,6 +13,7 @@ def make_training_example():
completion_ids=[3, 4],
completion_mask=[True, True],
completion_logprobs=[-0.1, -0.2],
teacher_logprobs=[0.0, 0.0, 0.0, 0.0],
advantage=1.0,
)
@@ -0,0 +1,136 @@
# coding=utf-8
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from transformers.configuration_utils import PretrainedConfig, layer_type_validation
from transformers.modeling_rope_utils import rope_config_validation
from transformers.utils import logging
logger = logging.get_logger(__name__)
class AfmoeConfig(PretrainedConfig):
"""
n_group (`int`, *optional*, defaults to 1):
Number of groups for routed experts.
topk_group (`int`, *optional*, defaults to 1):
Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
"""
model_type = "afmoe"
base_model_pp_plan = {
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
"norm": (["hidden_states"], ["hidden_states"]),
}
def __init__(
self,
num_hidden_layers: int = 32,
vocab_size: int = 200192,
hidden_size: int = 2048,
intermediate_size: int = 6144,
moe_intermediate_size=1408,
num_dense_layers=1,
num_attention_heads=16,
num_key_value_heads=None,
head_dim=128,
hidden_act="silu",
max_position_embeddings=16384,
initializer_range=0.02,
rms_norm_eps=1e-5,
use_cache=True,
tie_word_embeddings=False,
rope_theta=10000.0,
rope_scaling=None,
num_experts=64,
num_experts_per_tok=6,
num_shared_experts=2,
num_expert_groups=1,
num_limited_groups=1,
score_func="sigmoid",
route_norm=True,
route_scale=1.0,
load_balance_coeff: float | None = None,
use_grouped_mm: bool = True,
global_attn_every_n_layers=4,
sliding_window=1024,
mup_enabled=False,
layer_types=None,
attention_dropout: float = 0.0,
n_group: int = 1,
topk_group: int = 1,
**kwargs,
):
self.vocab_size = vocab_size
self.max_position_embeddings = max_position_embeddings
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.num_hidden_layers = num_hidden_layers
self.num_dense_layers = num_dense_layers
self.num_attention_heads = num_attention_heads
self.head_dim = head_dim
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.rms_norm_eps = rms_norm_eps
self.use_cache = use_cache
self.rope_theta = rope_theta
self.rope_scaling = rope_scaling
# MoE specific
self.moe_intermediate_size = moe_intermediate_size
self.num_experts_per_tok = num_experts_per_tok
self.n_group = n_group
self.topk_group = topk_group
self.num_experts = num_experts
self.num_shared_experts = num_shared_experts
self.num_expert_groups = num_expert_groups
self.num_limited_groups = num_limited_groups
self.score_func = score_func
self.route_norm = route_norm
self.route_scale = route_scale
self.load_balance_coeff = load_balance_coeff
self.use_grouped_mm = use_grouped_mm
# Attention specific
self.attention_dropout = attention_dropout
self.global_attn_every_n_layers = global_attn_every_n_layers
self.sliding_window = sliding_window
self.layer_types = layer_types
if self.layer_types is None:
self.layer_types = [
"sliding_attention" if bool((i + 1) % global_attn_every_n_layers) else "full_attention" for i in range(self.num_hidden_layers)
]
layer_type_validation(self.layer_types)
# muP specific
self.mup_enabled = mup_enabled
if num_key_value_heads is None:
num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
# Validate rope configs
if self.rope_scaling is not None and "type" in self.rope_scaling:
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
rope_config_validation(self)
super().__init__(
tie_word_embeddings=tie_word_embeddings,
**kwargs,
)
__all__ = ["AfmoeConfig"]
@@ -0,0 +1,677 @@
from typing import Callable, Optional, Tuple, Union
import torch
import torch.nn.functional as F
from torch import nn
from transformers.activations import ACT2FN
from transformers.cache_utils import Cache, DynamicCache
from transformers.generation import GenerationMixin
from transformers.integrations import use_kernel_forward_from_hub
from transformers.masking_utils import (
create_causal_mask,
create_sliding_window_causal_mask,
)
from transformers.modeling_layers import GradientCheckpointingLayer
from transformers.modeling_outputs import (
MoeCausalLMOutputWithPast,
MoeModelOutputWithPast,
)
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs
try:
from .configuration_afmoe import AfmoeConfig
except:
from configuration_afmoe import AfmoeConfig
class AfmoeRotaryEmbedding(nn.Module):
def __init__(self, config: AfmoeConfig, device=None):
super().__init__()
# BC: "rope_type" was originally "type"
if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
else:
self.rope_type = "default"
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
self.config = config
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
self.register_buffer("inv_freq", inv_freq, persistent=False)
self.original_inv_freq = self.inv_freq
def _dynamic_frequency_update(self, position_ids, device):
"""
dynamic RoPE layers should recompute `inv_freq` in the following situations:
1 - growing beyond the cached sequence length (allow scaling)
2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
"""
seq_len = torch.max(position_ids) + 1
if seq_len > self.max_seq_len_cached: # growth
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
self.register_buffer("inv_freq", inv_freq, persistent=False)
self.max_seq_len_cached = seq_len
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
# This .to() is needed if the model has been moved to a device after being initialized (because
# the buffer is automatically moved, but not the original copy)
self.original_inv_freq = self.original_inv_freq.to(device)
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
self.max_seq_len_cached = self.original_max_seq_len
@torch.no_grad()
def forward(self, x, position_ids):
if "dynamic" in self.rope_type:
self._dynamic_frequency_update(position_ids, device=x.device)
# Core RoPE block
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
position_ids_expanded = position_ids[:, None, :].float()
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
device_type = x.device.type
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
with torch.autocast(device_type=device_type, enabled=False):
freqs = (inv_freq_expanded.float().to(x.device) @ position_ids_expanded.float()).transpose(1, 2)
emb = torch.cat((freqs, freqs), dim=-1)
cos = emb.cos()
sin = emb.sin()
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
cos = cos * self.attention_scaling
sin = sin * self.attention_scaling
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
def rotate_half(x):
"""Rotates half the hidden dims of the input."""
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=-1)
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
"""Applies Rotary Position Embedding to the query and key tensors.
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.
position_ids (`torch.Tensor`, *optional*):
Deprecated and unused.
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)
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
"""
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
"""
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
if n_rep == 1:
return hidden_states
hidden_states = hidden_states[:, :, None, :, :].expand(
batch, num_key_value_heads, n_rep, slen, head_dim
)
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
@use_kernel_forward_from_hub("RMSNorm")
class AfmoeRMSNorm(nn.Module):
def __init__(self, hidden_size: int, eps: float):
"""
AfmoeRMSNorm is equivalent to T5LayerNorm
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self, hidden_states):
input_dtype = hidden_states.dtype
hidden_states = hidden_states.to(torch.float32)
variance = hidden_states.pow(2).mean(-1, keepdim=True)
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
return self.weight * hidden_states.to(input_dtype)
def extra_repr(self):
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
def eager_attention_forward(
module: nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_mask: Optional[torch.Tensor],
scaling: float,
dropout: float = 0.0,
**kwargs,
):
key_states = repeat_kv(key, module.num_key_value_groups)
value_states = repeat_kv(value, module.num_key_value_groups)
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
if attention_mask is not None:
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
attn_weights = attn_weights + causal_mask
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(
query.dtype
)
attn_weights = nn.functional.dropout(
attn_weights, p=dropout, training=module.training
)
attn_output = torch.matmul(attn_weights, value_states)
attn_output = attn_output.transpose(1, 2).contiguous()
return attn_output, attn_weights
class AfmoeMLP(nn.Module):
def __init__(self, config, intermediate_size=None):
super().__init__()
self.config = config
self.hidden_size = config.hidden_size
self.intermediate_size = intermediate_size or config.intermediate_size
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
self.act_fn = ACT2FN[config.hidden_act]
def forward(self, x):
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
class AfmoeTokenChoiceRouter(nn.Module):
"""Token-choice top-K router for MoE routing."""
def __init__(self, config):
super().__init__()
self.config = config
self.top_k = config.num_experts_per_tok
self.num_experts = config.num_experts
self.score_func = config.score_func
self.route_norm = config.route_norm
self.route_scale = config.route_scale
self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False)
def forward(self, hidden_states, expert_bias: torch.Tensor | None):
_, _, hidden_dim = hidden_states.shape
hidden_states = hidden_states.view(-1, hidden_dim)
scores = self.gate(hidden_states)
# Apply scoring function in float32 for stability
if self.score_func == "sigmoid":
scores = torch.sigmoid(scores.to(torch.float32))
else:
scores = F.softmax(scores.to(torch.float32), dim=-1)
if expert_bias is not None:
_, selected_experts = torch.topk(scores + expert_bias, k=self.top_k, dim=1)
top_scores = scores.gather(dim=1, index=selected_experts)
else:
top_scores, selected_experts = torch.topk(scores, k=self.top_k, dim=1)
# Normalize weights if using sigmoid
if self.score_func == "sigmoid" and self.route_norm:
denominator = top_scores.sum(dim=-1, keepdim=True) + 1e-20
top_scores = top_scores / denominator
top_scores = top_scores * self.route_scale
return top_scores, selected_experts
class AfmoeMoE(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.router = AfmoeTokenChoiceRouter(config)
self.shared_experts = None
if config.num_shared_experts > 0:
self.shared_experts = AfmoeMLP(
config, config.moe_intermediate_size * config.num_shared_experts
)
self.experts = nn.ModuleList(
[AfmoeMLP(
config, intermediate_size=config.moe_intermediate_size
) for _ in range(config.num_experts)]
)
self.expert_bias = nn.Parameter(torch.zeros(config.num_experts, dtype=torch.float32), requires_grad=False)
def forward(self, hidden_states):
batch_size, seq_len, hidden_dim = hidden_states.shape
hidden_states_flat = hidden_states.view(-1, hidden_dim)
# Get routing decisions
top_scores, selected_experts = self.router(hidden_states, self.expert_bias)
# Process through shared experts
if self.shared_experts is not None:
shared_output = self.shared_experts(hidden_states_flat)
else:
shared_output = torch.zeros_like(hidden_states_flat)
# Reorder tokens by expert for efficient processing
token_indices_sorted = torch.argsort(selected_experts.view(-1), stable=True)
top_scores_sorted = top_scores.view(-1)[token_indices_sorted]
token_to_expert = selected_experts.view(-1)[token_indices_sorted]
token_indices_sorted = token_indices_sorted // self.config.num_experts_per_tok
# Gather input tokens
token_indices_expanded = token_indices_sorted.unsqueeze(-1).expand(
-1, hidden_dim
)
routed_input = torch.gather(
hidden_states_flat, dim=0, index=token_indices_expanded
)
routed_output = torch.zeros_like(routed_input)
for expert_id in range(self.config.num_experts):
mask = token_to_expert == expert_id
if mask.any():
expert_input = routed_input[mask]
expert_out = self.experts[expert_id](expert_input)
routed_output[mask] = expert_out
routed_output = (
routed_output.to(torch.float32) * top_scores_sorted.unsqueeze(-1)
).to(hidden_states.dtype)
# Scatter back to original positions
output = shared_output.scatter_add(
dim=0, index=token_indices_expanded, src=routed_output
)
return output.view(batch_size, seq_len, hidden_dim)
class AfmoeAttention(nn.Module):
"""Multi-headed attention with local/global pattern and gating."""
def __init__(self, config: AfmoeConfig, layer_idx: int):
super().__init__()
self.config = config
self.layer_idx = layer_idx
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
self.num_heads = config.num_attention_heads
self.num_key_value_heads = config.num_key_value_heads
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
self.scaling = self.head_dim**-0.5
self.attention_dropout = config.attention_dropout
self.is_local_attention = config.layer_types[layer_idx] == "sliding_attention"
self.sliding_window = config.sliding_window if self.is_local_attention else None
self.q_proj = nn.Linear(
config.hidden_size, self.num_heads * self.head_dim, bias=False
)
self.k_proj = nn.Linear(
config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
)
self.v_proj = nn.Linear(
config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
)
self.o_proj = nn.Linear(
self.num_heads * self.head_dim, config.hidden_size, bias=False
)
self.q_norm = AfmoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
self.k_norm = AfmoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
self.gate_proj = nn.Linear(
config.hidden_size, self.num_heads * self.head_dim, bias=False
)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
attention_mask: Optional[torch.Tensor],
past_key_value: Optional[Cache] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> torch.Tensor:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states = self.q_proj(hidden_states).view(hidden_shape)
key_states = self.k_proj(hidden_states).view(hidden_shape)
value_states = self.v_proj(hidden_states).view(hidden_shape)
gate_states = self.gate_proj(hidden_states)
query_states = self.q_norm(query_states)
key_states = self.k_norm(key_states)
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
value_states = value_states.transpose(1, 2)
if self.is_local_attention:
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
if past_key_value is not None:
cache_kwargs = {"cache_position": cache_position}
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
attention_interface = ALL_ATTENTION_FUNCTIONS[
self.config._attn_implementation
]
output, _ = attention_interface(
self,
query_states,
key_states,
value_states,
attention_mask=attention_mask,
dropout=0.0 if not self.training else self.attention_dropout,
scaling=self.scaling,
sliding_window=self.sliding_window,
**kwargs,
)
output = output.view(*input_shape, -1).contiguous()
output = output * F.sigmoid(gate_states)
return self.o_proj(output)
class AfmoeDecoderLayer(GradientCheckpointingLayer):
def __init__(self, config: AfmoeConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.layer_idx = layer_idx
self.self_attn = AfmoeAttention(config=config, layer_idx=layer_idx)
self.attention_type = config.layer_types[layer_idx]
# Dual normalization for attention
self.input_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
# Dual normalization for FFN
self.pre_mlp_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_mlp_layernorm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
# MoE or dense FFN
self.moe_enabled = layer_idx >= config.num_dense_layers
if self.moe_enabled:
self.mlp = AfmoeMoE(config)
else:
self.mlp = AfmoeMLP(config)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_value: Optional[Cache] = None,
use_cache: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
**kwargs: Unpack[TransformersKwargs],
) -> torch.FloatTensor:
residual = hidden_states
# Self Attention with dual normalization
hidden_states = self.input_layernorm(hidden_states)
hidden_states = self.self_attn(
hidden_states=hidden_states,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_value=past_key_value,
use_cache=use_cache,
cache_position=cache_position,
position_embeddings=position_embeddings,
**kwargs,
)
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = residual + hidden_states
# FFN with dual normalization
residual = hidden_states
hidden_states = self.pre_mlp_layernorm(hidden_states)
if self.moe_enabled:
hidden_states = self.mlp(hidden_states)
else:
hidden_states = self.mlp(hidden_states)
hidden_states = self.post_mlp_layernorm(hidden_states)
hidden_states = residual + hidden_states
return hidden_states
class AfmoePreTrainedModel(PreTrainedModel):
config_class = AfmoeConfig
base_model_prefix = "model"
_no_split_modules = ["AfmoeDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_keep_in_fp32_modules = [
"input_layernorm",
"post_attention_layernorm",
"pre_mlp_layernorm",
"post_mlp_layernorm",
"q_norm",
"k_norm",
"norm",
]
_supports_sdpa = True
_supports_attention_backend = True
supports_gradient_checkpointing = True
class AfmoeModel(AfmoePreTrainedModel):
_no_split_modules = ["AfmoeDecoderLayer"]
def __init__(self, config: AfmoeConfig):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(
config.vocab_size, config.hidden_size, self.padding_idx
)
self.layers = nn.ModuleList(
[
AfmoeDecoderLayer(config, layer_idx)
for layer_idx in range(config.num_hidden_layers)
]
)
self.norm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.rotary_emb = AfmoeRotaryEmbedding(config=config)
self.gradient_checkpointing = False
self.post_init()
def get_input_embeddings(self):
return self.embed_tokens
def set_input_embeddings(self, value):
self.embed_tokens = value
def forward(
self,
input_ids: torch.LongTensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[list[torch.FloatTensor]] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
use_cache: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> MoeModelOutputWithPast:
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError(
"You must specify exactly one of input_ids or inputs_embeds"
)
if use_cache and past_key_values is None:
past_key_values = DynamicCache()
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
if cache_position is None:
past_seen_tokens = (
past_key_values.get_seq_length() if past_key_values is not None else 0
)
cache_position = torch.arange(
past_seen_tokens,
past_seen_tokens + inputs_embeds.shape[1],
device=inputs_embeds.device,
)
if position_ids is None:
position_ids = cache_position.unsqueeze(0)
# It may already have been prepared by e.g. `generate`
if not isinstance(causal_mask_mapping := attention_mask, dict):
mask_kwargs = {
"config": self.config,
"input_embeds": inputs_embeds,
"attention_mask": attention_mask,
"cache_position": cache_position,
"past_key_values": past_key_values,
}
causal_mask_mapping = {
"full_attention": create_causal_mask(**mask_kwargs),
"sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
}
hidden_states = inputs_embeds
# Apply muP input scaling if enabled
if self.config.mup_enabled:
hidden_states = hidden_states * (self.config.hidden_size**0.5)
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for decoder_layer in self.layers:
hidden_states = decoder_layer(
hidden_states,
attention_mask=causal_mask_mapping[decoder_layer.attention_type],
position_ids=position_ids,
past_key_value=past_key_values,
use_cache=use_cache,
cache_position=cache_position,
position_embeddings=position_embeddings,
**kwargs,
)
hidden_states = self.norm(hidden_states)
return MoeModelOutputWithPast(
last_hidden_state=hidden_states,
past_key_values=past_key_values,
)
class AfmoeForCausalLM(AfmoePreTrainedModel, GenerationMixin):
_tied_weights_keys = ["lm_head.weight"]
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config):
super().__init__(config)
self.model = AfmoeModel(config)
self.vocab_size = config.vocab_size
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self):
return self.model.embed_tokens
def set_input_embeddings(self, value):
self.model.embed_tokens = value
def get_output_embeddings(self):
return self.lm_head
def set_output_embeddings(self, new_embeddings):
self.lm_head = new_embeddings
def set_decoder(self, decoder):
self.model = decoder
def get_decoder(self):
return self.model
def forward(
self,
input_ids: torch.LongTensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
token_type_ids: Optional[torch.Tensor] = None, # will be ignored
**kwargs: Unpack[TransformersKwargs],
) -> Union[Tuple, MoeCausalLMOutputWithPast]:
outputs: MoeModelOutputWithPast = self.model(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
cache_position=cache_position,
**kwargs,
)
hidden_states = outputs.last_hidden_state
# Only compute necessary logits
slice_indices = (
slice(-logits_to_keep, None)
if isinstance(logits_to_keep, int)
else logits_to_keep
)
logits = self.lm_head(hidden_states[:, slice_indices, :])
loss = None
if labels is not None:
loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
return MoeCausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
router_logits=outputs.router_logits,
)
__all__ = [
"AfmoeForCausalLM",
"AfmoeModel",
"AfmoePreTrainedModel",
]
+166
View File
@@ -0,0 +1,166 @@
import pytest
import torch
from torch import nn
from prime_rl.trainer.models.afmoe import AfmoeForCausalLM as PrimeRLAfmoeForCausalLM
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.utils.utils import default_dtype
from tests.unit.train.models.afmoe_hf_modeling.configuration_afmoe import AfmoeConfig
from tests.unit.train.models.afmoe_hf_modeling.modeling_afmoe import (
AfmoeForCausalLM as HFAfmoeForCausalLM,
)
pytestmark = [pytest.mark.gpu]
def get_model_pairs():
hf_config = AfmoeConfig(
architectures=["AfmoeForCausalLM"],
attention_dropout=0.0,
global_attn_every_n_layers=2,
head_dim=64,
hidden_act="silu",
hidden_size=256,
initializer_range=0.02,
intermediate_size=512,
layer_types=[
"sliding_attention",
"full_attention",
"sliding_attention",
"full_attention",
],
load_balance_coeff=0.001,
max_position_embeddings=512,
moe_intermediate_size=128,
mup_enabled=True,
n_group=1,
num_attention_heads=4,
num_dense_layers=2,
num_expert_groups=1,
num_experts=4,
num_experts_per_tok=2,
num_hidden_layers=4,
num_key_value_heads=2,
num_limited_groups=1,
num_shared_experts=1,
rms_norm_eps=1e-5,
rope_scaling=None,
rope_theta=10000.0,
route_norm=True,
route_scale=2.826,
score_func="sigmoid",
sliding_window=128,
tie_word_embeddings=False,
topk_group=1,
use_cache=True,
use_grouped_mm=False,
vocab_size=256,
)
hf_config._attn_implementation = "sdpa"
with torch.device("cuda"), default_dtype(torch.float32):
hf_model = HFAfmoeForCausalLM._from_config(hf_config)
prime_model = PrimeRLAfmoeForCausalLM._from_config(hf_config)
with torch.no_grad():
state_dict = hf_model.state_dict()
prime_state_keys = prime_model.state_dict().keys()
prime_model.convert_to_prime(state_dict)
prime_model.load_state_dict(state_dict)
inject_prime_lm_head(prime_model, chunk_size=None)
assert set(prime_state_keys) - set(state_dict.keys()) == set()
return hf_model, prime_model
def test_afmoe_attn_only() -> None:
hf_model, prime_model = get_model_pairs()
for layer in hf_model.model.layers:
layer.mlp = nn.Identity()
for layer in prime_model.model.layers:
layer.mlp = nn.Identity()
with torch.device("cuda"), default_dtype(torch.float32):
input_ids = torch.randint(0, hf_model.config.vocab_size, (1, 100))
position_ids = torch.arange(1, 101).unsqueeze(0)
hf_output = hf_model(input_ids, position_ids=position_ids)
prime_output = prime_model(input_ids, position_ids=position_ids)
hf_output.logits.sum().backward()
prime_output["logits"].sum().backward()
logits_diff = prime_output["logits"] - hf_output.logits
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
f"Max logits diff: {logits_diff.abs().max()}"
)
grad_diff = hf_model.model.embed_tokens.weight.grad - prime_model.model.embed_tokens.weight.grad
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
def test_afmoe_mlp_only() -> None:
hf_model, prime_model = get_model_pairs()
# HF AfmoeAttention.forward() returns a single tensor
def identity_attn_hf(hidden_states: torch.Tensor, *args, **kwargs) -> torch.Tensor:
return hidden_states
# PrimeRL attention returns a tuple (output, attn_weights)
def identity_attn_prime(hidden_states: torch.Tensor, *args, **kwargs) -> tuple[torch.Tensor, None]:
return hidden_states, None
for layer in hf_model.model.layers:
layer.self_attn.forward = identity_attn_hf
for layer in prime_model.model.layers:
layer.self_attn.forward = identity_attn_prime
with torch.device("cuda"), default_dtype(torch.float32):
input_ids = torch.randint(0, hf_model.config.vocab_size, (1, 100))
position_ids = torch.arange(1, 101).unsqueeze(0)
hf_output = hf_model(input_ids, position_ids=position_ids)
prime_output = prime_model(input_ids, position_ids=position_ids)
hf_output.logits.sum().backward()
prime_output["logits"].sum().backward()
logits_diff = prime_output["logits"] - hf_output.logits
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
f"Max logits diff: {logits_diff.abs().max()}"
)
grad_diff = hf_model.model.embed_tokens.weight.grad - prime_model.model.embed_tokens.weight.grad
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
def test_afmoe() -> None:
hf_model, prime_model = get_model_pairs()
with torch.device("cuda"), default_dtype(torch.float32):
input_ids = torch.randint(0, hf_model.config.vocab_size, (1, 100))
position_ids = torch.arange(1, 101).unsqueeze(0)
hf_output = hf_model(input_ids, position_ids=position_ids)
prime_output = prime_model(input_ids, position_ids=position_ids)
hf_output.logits.sum().backward()
prime_output["logits"].sum().backward()
logits_diff = prime_output["logits"] - hf_output.logits
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
f"Max logits diff: {logits_diff.abs().max()}"
)
grad_diff = hf_model.model.embed_tokens.weight.grad - prime_model.model.embed_tokens.weight.grad
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
with torch.device("cuda"), default_dtype(torch.float32):
hf_from_prime_model = HFAfmoeForCausalLM._from_config(hf_model.config)
converted_state_dict = prime_model.convert_to_hf(prime_model.state_dict())
hf_from_prime_model.load_state_dict(converted_state_dict)
hf_from_prime_output = hf_from_prime_model(input_ids, position_ids=position_ids)
hf_from_prime_output.logits.sum().backward()
logits_diff = hf_from_prime_output.logits - hf_output.logits
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
f"Max logits diff: {logits_diff.abs().max()}"
)
grad_diff = hf_from_prime_model.model.embed_tokens.weight.grad - hf_model.model.embed_tokens.weight.grad
assert torch.allclose(grad_diff, torch.zeros_like(grad_diff), atol=2), f"Max grad diff: {grad_diff.abs().max()}"
if __name__ == "__main__":
test_afmoe()
+10 -6
View File
@@ -5,6 +5,7 @@ from transformers import Glm4MoeForCausalLM as HFGlm4MoeForCausalLM
from prime_rl.trainer.models.glm4_moe import Glm4MoeConfig
from prime_rl.trainer.models.glm4_moe import Glm4MoeForCausalLM as PrimeRLGlm4MoeForCausalLM
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.utils.utils import default_dtype
pytestmark = [pytest.mark.gpu]
@@ -26,6 +27,7 @@ def get_model_pairs() -> tuple[HFGlm4MoeForCausalLM, PrimeRLGlm4MoeForCausalLM]:
rope_theta=1000000.0,
first_k_dense_replace=1,
partial_rotary_factor=0.5,
use_grouped_mm=False,
)
# TODO: We should test this path because it's the most performant
# But the grad seems to be off in attn because of precision
@@ -39,6 +41,8 @@ def get_model_pairs() -> tuple[HFGlm4MoeForCausalLM, PrimeRLGlm4MoeForCausalLM]:
prime_state_keys = prime_model.state_dict().keys()
prime_model.convert_to_prime(state_dict)
prime_model.load_state_dict(state_dict)
# Training code wraps the LM head; tests should mirror that (so forward can accept labels/temperature).
inject_prime_lm_head(prime_model, chunk_size=None)
assert set(prime_state_keys) - set(state_dict.keys()) == set()
return hf_model, prime_model
@@ -57,9 +61,9 @@ def test_glm4_moe_attn_only() -> None:
hf_output = hf_model(input_ids, position_ids)
prime_output = prime_model(input_ids, position_ids)
hf_output.logits.sum().backward()
prime_output.logits.sum().backward()
prime_output["logits"].sum().backward()
logits_diff = prime_output.logits - hf_output.logits
logits_diff = prime_output["logits"] - hf_output.logits
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
f"Max logits diff: {logits_diff.abs().max()}"
)
@@ -85,9 +89,9 @@ def test_glm4_moe_mlp_only() -> None:
hf_output = hf_model(input_ids, position_ids)
prime_output = prime_model(input_ids, position_ids)
hf_output.logits.sum().backward()
prime_output.logits.sum().backward()
prime_output["logits"].sum().backward()
logits_diff = prime_output.logits - hf_output.logits
logits_diff = prime_output["logits"] - hf_output.logits
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
f"Max logits diff: {logits_diff.abs().max()}"
)
@@ -105,9 +109,9 @@ def test_glm4_moe() -> None:
hf_output = hf_model(input_ids, position_ids)
prime_output = prime_model(input_ids, position_ids)
hf_output.logits.sum().backward()
prime_output.logits.sum().backward()
prime_output["logits"].sum().backward()
logits_diff = prime_output.logits - hf_output.logits
logits_diff = prime_output["logits"] - hf_output.logits
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
f"Max logits diff: {logits_diff.abs().max()}"
)
+9 -6
View File
@@ -4,6 +4,7 @@ from torch import nn
from transformers import LlamaForCausalLM as HFLlamaForCausalLM
from transformers.models.llama.configuration_llama import LlamaConfig
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.models.llama import LlamaForCausalLM as PrimeRLLlamaForCausalLM
from prime_rl.utils.utils import default_dtype
@@ -33,6 +34,8 @@ def get_model_pairs():
prime_state_keys = prime_model.state_dict().keys()
prime_model.convert_to_prime(state_dict)
prime_model.load_state_dict(state_dict)
# Training code wraps the LM head; tests should mirror that (so forward can accept labels/temperature).
inject_prime_lm_head(prime_model, chunk_size=None)
assert set(prime_state_keys) - set(state_dict.keys()) == set()
return hf_model, prime_model
@@ -51,9 +54,9 @@ def test_llama_attn_only():
hf_output = hf_model(input_ids, position_ids)
prime_output = prime_model(input_ids, position_ids)
hf_output.logits.sum().backward()
prime_output.logits.sum().backward()
prime_output["logits"].sum().backward()
logits_diff = prime_output.logits - hf_output.logits
logits_diff = prime_output["logits"] - hf_output.logits
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
f"Max logits diff: {logits_diff.abs().max()}"
)
@@ -79,9 +82,9 @@ def test_llama_mlp_only():
hf_output = hf_model(input_ids, position_ids)
prime_output = prime_model(input_ids, position_ids)
hf_output.logits.sum().backward()
prime_output.logits.sum().backward()
prime_output["logits"].sum().backward()
logits_diff = prime_output.logits - hf_output.logits
logits_diff = prime_output["logits"] - hf_output.logits
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
f"Max logits diff: {logits_diff.abs().max()}"
)
@@ -99,9 +102,9 @@ def test_llama():
hf_output = hf_model(input_ids, position_ids)
prime_output = prime_model(input_ids, position_ids)
hf_output.logits.sum().backward()
prime_output.logits.sum().backward()
prime_output["logits"].sum().backward()
logits_diff = prime_output.logits - hf_output.logits
logits_diff = prime_output["logits"] - hf_output.logits
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
f"Max logits diff: {logits_diff.abs().max()}"
)
+10 -6
View File
@@ -3,6 +3,7 @@ import torch
from torch import nn
from transformers import Qwen3MoeForCausalLM as HFQwen3MoeForCausalLM
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.models.qwen3_moe import Qwen3MoeConfig
from prime_rl.trainer.models.qwen3_moe import Qwen3MoeForCausalLM as PrimeRLQwen3MoeForCausalLM
from prime_rl.utils.utils import default_dtype
@@ -25,6 +26,7 @@ def get_model_pairs():
rope_theta=1000000.0,
use_qk_norm=True,
mlp_only_layers=[1],
use_grouped_mm=False,
)
# TODO: We should test this path because it's the most performant
# But the grad seems to be off in attn because of precision
@@ -38,6 +40,8 @@ def get_model_pairs():
prime_state_keys = prime_model.state_dict().keys()
prime_model.convert_to_prime(state_dict)
prime_model.load_state_dict(state_dict)
# Training code wraps the LM head; tests should mirror that (so forward can accept labels/temperature).
inject_prime_lm_head(prime_model, chunk_size=None)
assert set(prime_state_keys) - set(state_dict.keys()) == set()
return hf_model, prime_model
@@ -56,9 +60,9 @@ def test_qwen3_moe_attn_only():
hf_output = hf_model(input_ids, position_ids)
prime_output = prime_model(input_ids, position_ids)
hf_output.logits.sum().backward()
prime_output.logits.sum().backward()
prime_output["logits"].sum().backward()
logits_diff = prime_output.logits - hf_output.logits
logits_diff = prime_output["logits"] - hf_output.logits
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
f"Max logits diff: {logits_diff.abs().max()}"
)
@@ -84,9 +88,9 @@ def test_qwen3_moe_mlp_only():
hf_output = hf_model(input_ids, position_ids)
prime_output = prime_model(input_ids, position_ids)
hf_output.logits.sum().backward()
prime_output.logits.sum().backward()
prime_output["logits"].sum().backward()
logits_diff = prime_output.logits - hf_output.logits
logits_diff = prime_output["logits"] - hf_output.logits
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
f"Max logits diff: {logits_diff.abs().max()}"
)
@@ -104,9 +108,9 @@ def test_qwen3_moe():
hf_output = hf_model(input_ids, position_ids)
prime_output = prime_model(input_ids, position_ids)
hf_output.logits.sum().backward()
prime_output.logits.sum().backward()
prime_output["logits"].sum().backward()
logits_diff = prime_output.logits - hf_output.logits
logits_diff = prime_output["logits"] - hf_output.logits
assert torch.allclose(logits_diff, torch.zeros_like(logits_diff), atol=2e-2), (
f"Max logits diff: {logits_diff.abs().max()}"
)
+417
View File
@@ -0,0 +1,417 @@
import pytest
import torch
from transformers import AutoModelForCausalLM
from transformers.models.llama.configuration_llama import LlamaConfig
from prime_rl.trainer.models import cast_float_and_contiguous
from prime_rl.trainer.models.layers.lm_head import FusedOutputLinear, VanillaOutputLinear, inject_prime_lm_head
from prime_rl.trainer.models.llama import LlamaForCausalLM as PrimeRLLlamaForCausalLM
from prime_rl.trainer.rl.loss import compute_entropy, selective_log_softmax, shift_tensor_left, shift_tensor_right
from prime_rl.utils.utils import default_dtype
def _baseline_logprobs_and_entropy(
hidden: torch.Tensor, weight: torch.Tensor, labels: torch.Tensor, *, temperature: float
) -> tuple[torch.Tensor, torch.Tensor]:
logits = hidden @ weight.t()
logits = logits / float(temperature)
logp = torch.log_softmax(logits, dim=-1).gather(dim=-1, index=labels.unsqueeze(-1)).squeeze(-1)
ent = compute_entropy(logits)
return logp, ent
def test_fused_lm_head_matches_full_logits_forward_and_backward_cpu():
torch.manual_seed(0)
b, s, h, v = 2, 4, 8, 37
temperature = 1.7
chunk_size = 11
hidden0 = torch.randn(b, s, h, dtype=torch.float32, requires_grad=True)
labels = torch.randint(0, v, (b, s), dtype=torch.long)
weight0 = torch.randn(v, h, dtype=torch.float32, requires_grad=True)
# Baseline
logp0, ent0 = _baseline_logprobs_and_entropy(hidden0, weight0, labels, temperature=temperature)
loss0 = logp0.sum()
loss0.backward()
grad_hidden0 = hidden0.grad.detach().clone()
grad_weight0 = weight0.grad.detach().clone()
# Fused
hidden1 = hidden0.detach().clone().requires_grad_(True)
weight1 = weight0.detach().clone().requires_grad_(True)
lm = FusedOutputLinear(in_features=h, out_features=v, chunk_size=chunk_size)
lm.weight = torch.nn.Parameter(weight1)
out = lm(hidden1, labels, temperature=temperature)
assert out.get("logits") is None
assert out.get("logprobs") is not None
assert out.get("entropy") is not None
loss1 = out["logprobs"].sum()
loss1.backward()
grad_hidden1 = hidden1.grad.detach().clone()
grad_weight1 = lm.weight.grad.detach().clone()
torch.testing.assert_close(out["logprobs"], logp0, rtol=0, atol=1e-5)
torch.testing.assert_close(out["entropy"], ent0, rtol=0, atol=1e-5)
torch.testing.assert_close(grad_hidden1, grad_hidden0, rtol=0, atol=1e-5)
torch.testing.assert_close(grad_weight1, grad_weight0, rtol=0, atol=1e-5)
def test_fused_lm_head_requires_labels():
"""Test that FusedOutputLinear raises assertion error when labels is None."""
torch.manual_seed(0)
b, s, h, v = 2, 3, 4, 9
hidden = torch.randn(b, s, h, dtype=torch.float32)
weight = torch.randn(v, h, dtype=torch.float32)
lm = FusedOutputLinear(in_features=h, out_features=v, chunk_size=5)
lm.weight = torch.nn.Parameter(weight)
with pytest.raises(AssertionError, match="FusedOutputLinear requires labels"):
lm(hidden, labels=None, temperature=1.0)
def test_vanilla_lm_head_returns_logits():
"""Test that VanillaOutputLinear returns logits."""
torch.manual_seed(0)
b, s, h, v = 2, 3, 4, 9
hidden = torch.randn(b, s, h, dtype=torch.float32)
weight = torch.randn(v, h, dtype=torch.float32)
lm = VanillaOutputLinear(in_features=h, out_features=v)
lm.weight = torch.nn.Parameter(weight)
out = lm(hidden, labels=None, temperature=1.0)
assert out.get("logits") is not None
assert out.get("logprobs") is None
assert out.get("entropy") is None
logits_ref = hidden @ weight.t()
torch.testing.assert_close(out["logits"], logits_ref, rtol=0, atol=1e-6)
def test_fused_vs_vanilla_integration():
"""Integration test comparing fused and vanilla outputs after postprocessing."""
torch.manual_seed(42)
b, s, h, v = 2, 4, 8, 37
temperature = 1.7
chunk_size = 11
hidden = torch.randn(b, s, h, dtype=torch.float16)
labels = torch.randint(0, v, (b, s), dtype=torch.long)
weight = torch.randn(v, h, dtype=torch.float16)
# Vanilla path: get logits, compute logprobs manually
vanilla_lm = VanillaOutputLinear(in_features=h, out_features=v)
vanilla_lm.weight = torch.nn.Parameter(weight.clone())
vanilla_out = cast_float_and_contiguous(vanilla_lm(hidden, labels=None, temperature=temperature))
assert vanilla_out.get("logits") is not None
logits = vanilla_out["logits"] / float(temperature)
vanilla_logprobs = torch.log_softmax(logits, dim=-1).gather(dim=-1, index=labels.unsqueeze(-1)).squeeze(-1)
vanilla_entropy = compute_entropy(logits)
# Fused path: get logprobs and entropy directly
fused_lm = FusedOutputLinear(in_features=h, out_features=v, chunk_size=chunk_size)
fused_lm.weight = torch.nn.Parameter(weight.clone())
fused_out = cast_float_and_contiguous(fused_lm(hidden, labels=labels, temperature=temperature))
assert fused_out.get("logprobs") is not None
assert fused_out.get("entropy") is not None
# Compare: fused should match vanilla within tolerance
torch.testing.assert_close(fused_out["logprobs"], vanilla_logprobs, rtol=1e-3, atol=1e-4)
torch.testing.assert_close(fused_out["entropy"], vanilla_entropy, rtol=1e-3, atol=1e-4)
@pytest.mark.gpu
def test_full_model_fused_vs_vanilla():
"""Full model integration test comparing fused vs vanilla LM head across multiple training steps."""
torch.manual_seed(123)
# Create tiny Llama model for fast testing
config = LlamaConfig(
hidden_size=128,
intermediate_size=256,
max_position_embeddings=512,
num_attention_heads=4,
num_key_value_heads=2,
num_hidden_layers=2,
vocab_size=1000,
rms_norm_eps=1e-5,
rope_theta=10000.0,
attention_bias=False,
mlp_bias=False,
)
with torch.device("cuda"), default_dtype(torch.float32):
# Create two identical models
model_vanilla = PrimeRLLlamaForCausalLM._from_config(config)
model_fused = PrimeRLLlamaForCausalLM._from_config(config)
# Share weights between models
model_fused.load_state_dict(model_vanilla.state_dict())
# Wrap with different LM heads
inject_prime_lm_head(model_vanilla, chunk_size=None) # Vanilla
inject_prime_lm_head(model_fused, chunk_size=256) # Fused with chunking
# Setup optimizers
optimizer_vanilla = torch.optim.AdamW(model_vanilla.parameters(), lr=1e-4)
optimizer_fused = torch.optim.AdamW(model_fused.parameters(), lr=1e-4)
# Run a few training steps
num_steps = 3
batch_size, seq_len = 2, 64
temperature = 1.5
for step in range(num_steps):
# Generate random batch
with torch.device("cuda"):
labels = torch.randint(0, config.vocab_size, (batch_size, seq_len))
position_ids = torch.arange(seq_len).unsqueeze(0).expand(batch_size, -1)
# Vanilla forward (returns logits, compute logprobs/entropy using RL train functions)
optimizer_vanilla.zero_grad()
out_vanilla = cast_float_and_contiguous(
model_vanilla(labels, position_ids, labels=labels, temperature=temperature)
)
if out_vanilla.get("logprobs") is None:
assert out_vanilla.get("logits") is not None
logits = out_vanilla["logits"] / float(temperature)
out_vanilla["logprobs"] = selective_log_softmax(logits, labels)
out_vanilla["entropy"] = compute_entropy(logits)
loss_vanilla = -out_vanilla["logprobs"].mean()
loss_vanilla.backward()
optimizer_vanilla.step()
# Fused forward (returns logprobs and entropy directly)
optimizer_fused.zero_grad()
out_fused = cast_float_and_contiguous(model_fused(labels, position_ids, labels=labels, temperature=temperature))
if out_fused.get("logprobs") is None:
assert out_fused.get("logits") is not None
logits = out_fused["logits"] / float(temperature)
out_fused["logprobs"] = selective_log_softmax(logits, labels)
out_fused["entropy"] = compute_entropy(logits)
loss_fused = -out_fused["logprobs"].mean()
loss_fused.backward()
optimizer_fused.step()
# Compare outputs (should be very close since models started identical)
torch.testing.assert_close(out_fused["logprobs"], out_vanilla["logprobs"], rtol=1e-4, atol=1e-5)
torch.testing.assert_close(out_fused["entropy"], out_vanilla["entropy"], rtol=1e-4, atol=1e-5)
torch.testing.assert_close(loss_fused, loss_vanilla, rtol=1e-4, atol=1e-5)
# After training, weights should still be close (optimizer steps should be similar)
for (name_v, param_v), (name_f, param_f) in zip(model_vanilla.named_parameters(), model_fused.named_parameters()):
if "lm_head" not in name_v: # Compare non-lm_head params
torch.testing.assert_close(param_f, param_v, rtol=1e-3, atol=1e-4)
def test_fused_lm_head_correct_shift():
"""
End-to-end test that the fused LM head with shifted labels, after shift_tensor_right,
produces logprobs aligned with the inference convention.
This simulates the full training loop behavior and verifies the importance ratio
(trainer_logprobs - inference_logprobs) is ~0 for positions that matter in training.
"""
torch.manual_seed(999)
b, s, h, v = 2, 16, 32, 50
temperature = 1.5
chunk_size = 13
hidden = torch.randn(b, s, h, dtype=torch.float32)
weight = torch.randn(v, h, dtype=torch.float32)
input_ids = torch.randint(0, v, (b, s), dtype=torch.long)
# Create shifted labels as done in training
labels = shift_tensor_left(input_ids)
# === Fused path (as in training) ===
fused_lm = FusedOutputLinear(in_features=h, out_features=v, chunk_size=chunk_size)
fused_lm.weight = torch.nn.Parameter(weight.clone())
fused_out = fused_lm(hidden, labels=labels, temperature=temperature)
trainer_logprobs = shift_tensor_right(fused_out["logprobs"])
# === Inference convention (baseline) ===
logits = hidden @ weight.t()
logits = logits / temperature
# Shift logits right (prepend zeros, drop last) to get inference convention
shifted_logits = torch.cat([torch.zeros(b, 1, v, dtype=logits.dtype), logits[:, :-1, :]], dim=1)
inference_logprobs = (
torch.log_softmax(shifted_logits, dim=-1).gather(dim=-1, index=input_ids.unsqueeze(-1)).squeeze(-1)
)
assert torch.all(trainer_logprobs[:, 0] == 0), "Position 0 should be 0 after shift_tensor_right"
importance_ratio = trainer_logprobs[:, 1:] - inference_logprobs[:, 1:]
torch.testing.assert_close(
importance_ratio,
torch.zeros(b, s - 1),
rtol=0,
atol=1e-4,
msg="Importance ratio at positions 1 to s-1 should be ~0 (same token probs)",
)
@pytest.mark.gpu
def test_inject_prime_lm_head_vanilla():
"""Test that inject_prime_lm_head correctly wraps HF model with VanillaOutputLinear."""
torch.manual_seed(123)
# Create tiny Llama model using HuggingFace AutoModelForCausalLM
config = LlamaConfig(
hidden_size=128,
intermediate_size=256,
max_position_embeddings=512,
num_attention_heads=4,
num_key_value_heads=2,
num_hidden_layers=2,
vocab_size=1000,
rms_norm_eps=1e-5,
rope_theta=10000.0,
attention_bias=False,
mlp_bias=False,
)
with torch.device("cuda"), default_dtype(torch.float32):
model = AutoModelForCausalLM.from_config(config)
# Wrap with VanillaOutputLinear (chunk_size=None)
inject_prime_lm_head(model, chunk_size=None)
assert isinstance(model.lm_head, VanillaOutputLinear), "lm_head should be VanillaOutputLinear"
# Test forward with labels and temperature
batch_size, seq_len = 2, 64
temperature = 1.5
with torch.device("cuda"):
input_ids = torch.randint(0, config.vocab_size, (batch_size, seq_len))
position_ids = torch.arange(seq_len).unsqueeze(0).expand(batch_size, -1)
labels = torch.randint(0, config.vocab_size, (batch_size, seq_len))
with torch.autocast("cuda", dtype=torch.bfloat16):
out = model(input_ids=input_ids, position_ids=position_ids, labels=labels, temperature=temperature)
# VanillaOutputLinear returns logits
assert isinstance(out, dict), "Output should be PrimeLmOutput (dict)"
assert out.get("logits") is not None, "Vanilla path should return logits"
assert out.get("logprobs") is None, "Vanilla path should not return logprobs"
assert out["logits"].shape == (batch_size, seq_len, config.vocab_size), "Logits shape mismatch"
@pytest.mark.gpu
def test_inject_prime_lm_head_fused():
"""Test that inject_prime_lm_head correctly wraps HF model with FusedOutputLinear."""
torch.manual_seed(123)
# Create tiny Llama model using HuggingFace AutoModelForCausalLM
config = LlamaConfig(
hidden_size=128,
intermediate_size=256,
max_position_embeddings=512,
num_attention_heads=4,
num_key_value_heads=2,
num_hidden_layers=2,
vocab_size=1000,
rms_norm_eps=1e-5,
rope_theta=10000.0,
attention_bias=False,
mlp_bias=False,
)
with torch.device("cuda"), default_dtype(torch.float32):
model = AutoModelForCausalLM.from_config(config)
# Wrap with FusedOutputLinear (chunk_size=512)
inject_prime_lm_head(model, chunk_size=512)
assert isinstance(model.lm_head, FusedOutputLinear), "lm_head should be FusedOutputLinear"
# Test forward with labels and temperature
batch_size, seq_len = 2, 64
temperature = 1.5
with torch.device("cuda"):
input_ids = torch.randint(0, config.vocab_size, (batch_size, seq_len))
position_ids = torch.arange(seq_len).unsqueeze(0).expand(batch_size, -1)
labels = torch.randint(0, config.vocab_size, (batch_size, seq_len))
with torch.autocast("cuda", dtype=torch.bfloat16):
out = model(input_ids=input_ids, position_ids=position_ids, labels=labels, temperature=temperature)
# FusedOutputLinear returns logprobs and entropy
assert isinstance(out, dict), "Output should be PrimeLmOutput (dict)"
assert out.get("logprobs") is not None, "Fused path should return logprobs"
assert out.get("entropy") is not None, "Fused path should return entropy"
assert out.get("logits") is None, "Fused path should not return logits"
assert out["logprobs"].shape == (batch_size, seq_len), "Logprobs shape mismatch"
assert out["entropy"].shape == (batch_size, seq_len), "Entropy shape mismatch"
@pytest.mark.gpu
def test_hf_model_fused_vs_vanilla_matches():
"""Test that fused and vanilla paths produce equivalent results for HF models."""
torch.manual_seed(42)
# Create tiny Llama model using HuggingFace AutoModelForCausalLM
config = LlamaConfig(
hidden_size=128,
intermediate_size=256,
max_position_embeddings=512,
num_attention_heads=4,
num_key_value_heads=2,
num_hidden_layers=2,
vocab_size=1000,
rms_norm_eps=1e-5,
rope_theta=10000.0,
attention_bias=False,
mlp_bias=False,
)
with torch.device("cuda"), default_dtype(torch.float32):
model_vanilla = AutoModelForCausalLM.from_config(config)
model_fused = AutoModelForCausalLM.from_config(config)
# Share weights
model_fused.load_state_dict(model_vanilla.state_dict())
# Wrap models
inject_prime_lm_head(model_vanilla, chunk_size=None)
inject_prime_lm_head(model_fused, chunk_size=512)
# Test data
batch_size, seq_len = 2, 64
temperature = 1.5
with torch.device("cuda"):
input_ids = torch.randint(0, config.vocab_size, (batch_size, seq_len))
position_ids = torch.arange(seq_len).unsqueeze(0).expand(batch_size, -1)
labels = torch.randint(0, config.vocab_size, (batch_size, seq_len))
# Run vanilla model
with torch.autocast("cuda", dtype=torch.bfloat16):
out_vanilla = model_vanilla(
input_ids=input_ids, position_ids=position_ids, labels=labels, temperature=temperature
)
# Compute logprobs and entropy from vanilla logits
logits = out_vanilla["logits"].float() / float(temperature)
vanilla_logprobs = selective_log_softmax(logits, labels)
vanilla_entropy = compute_entropy(logits)
# Run fused model
with torch.autocast("cuda", dtype=torch.bfloat16):
out_fused = model_fused(input_ids=input_ids, position_ids=position_ids, labels=labels, temperature=temperature)
fused_logprobs = out_fused["logprobs"].float()
fused_entropy = out_fused["entropy"].float()
# Compare results
torch.testing.assert_close(fused_logprobs, vanilla_logprobs, rtol=1e-3, atol=1e-4)
torch.testing.assert_close(fused_entropy, vanilla_entropy, rtol=1e-3, atol=1e-4)
+4
View File
@@ -10,12 +10,14 @@ pytestmark = [pytest.mark.gpu]
def test_grpo_loss():
trainer_logprobs = [torch.randn(50, dtype=torch.float32).cuda(), torch.randn(30, dtype=torch.float32).cuda()]
inference_logprobs = [torch.randn(50, dtype=torch.float32).cuda(), torch.randn(30, dtype=torch.float32).cuda()]
teacher_logprobs = [torch.randn(50, dtype=torch.float32).cuda(), torch.randn(30, dtype=torch.float32).cuda()]
advantages = [torch.randn(50).cuda(), torch.randn(30).cuda()]
loss_mask = [torch.ones(50, dtype=torch.bool).cuda(), torch.ones(30, dtype=torch.bool).cuda()]
loss, _ = compute_loss(
trainer_logprobs,
inference_logprobs,
teacher_logprobs,
advantages,
loss_mask=loss_mask,
loss_config=LossConfig(ratio_type="token", token_mask_high=10.0),
@@ -28,12 +30,14 @@ def test_gspo_loss():
# Create list of tensors as expected by compute_loss (simulating split sequences)
trainer_logprobs = [torch.randn(40, dtype=torch.float32).cuda(), torch.randn(60, dtype=torch.float32).cuda()]
inference_logprobs = [torch.randn(40, dtype=torch.float32).cuda(), torch.randn(60, dtype=torch.float32).cuda()]
teacher_logprobs = [torch.randn(40, dtype=torch.float32).cuda(), torch.randn(60, dtype=torch.float32).cuda()]
advantages = [torch.randn(40).cuda(), torch.randn(60).cuda()]
loss_mask = [torch.ones(40, dtype=torch.bool).cuda(), torch.ones(60, dtype=torch.bool).cuda()]
loss, _ = compute_loss(
trainer_logprobs,
inference_logprobs,
teacher_logprobs,
advantages,
loss_mask=loss_mask,
loss_config=LossConfig(ratio_type="sequence", token_mask_high=10.0),
+21 -10
View File
@@ -3,6 +3,7 @@ import torch
from prime_rl.trainer.config import AttnImplementation, ModelConfig
from prime_rl.trainer.model import get_model
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
BS = 1
SEQ_LEN = 8
@@ -40,9 +41,10 @@ def test_model_forward(model):
model = model.to("cuda")
with torch.autocast("cuda", dtype=torch.bfloat16):
inputs_ids = torch.randint(0, 100, (BS, SEQ_LEN)).to("cuda")
outputs = model(input_ids=inputs_ids).logits
outputs = model(input_ids=inputs_ids)
logits = outputs["logits"]
assert outputs.shape == (BS, SEQ_LEN, model.config.vocab_size)
assert logits.shape == (BS, SEQ_LEN, model.config.vocab_size)
def test_model_with_position_ids(model):
@@ -51,9 +53,10 @@ def test_model_with_position_ids(model):
inputs_ids = torch.randint(0, 100, (BS, SEQ_LEN)).to("cuda")
position_ids = torch.arange(SEQ_LEN).unsqueeze(0).repeat(BS, 1).to("cuda")
outputs = model(input_ids=inputs_ids, position_ids=position_ids).logits
outputs = model(input_ids=inputs_ids, position_ids=position_ids)
logits = outputs["logits"]
assert outputs.shape == (BS, SEQ_LEN, model.config.vocab_size)
assert logits.shape == (BS, SEQ_LEN, model.config.vocab_size)
@pytest.mark.skip(reason="Sequence packing for Qwen not working.")
@@ -75,7 +78,8 @@ def test_model_with_sequence_packing(model, correct_position_ids):
with torch.autocast("cuda", dtype=torch.bfloat16):
inputs_ids = torch.Tensor(inputs).repeat(1, 1).int().to("cuda")
output_base = model(input_ids=inputs_ids).logits
outputs = model(input_ids=inputs_ids)
output_base = outputs["logits"]
assert output_base.shape == (1, len(inputs), model.config.vocab_size)
@@ -87,7 +91,8 @@ def test_model_with_sequence_packing(model, correct_position_ids):
else:
position_ids = torch.Tensor([0, 1, 2, 3, 4, 5, 6, 7]).repeat(1, 1).int().to("cuda")
# should fail
outputs_packed = model(input_ids=inputs_ids, position_ids=position_ids).logits
outputs = model(input_ids=inputs_ids, position_ids=position_ids)
outputs_packed = outputs["logits"]
assert outputs_packed.shape == (1, 2 * len(inputs), model.config.vocab_size)
@@ -109,11 +114,14 @@ def test_moe_custom_impl():
config = ModelConfig(name="PrimeIntellect/GLM-0.5B", attn="sdpa", impl="custom", moe_use_grouped_mm=False)
model = get_model(config)
model = model.to("cuda")
# we need to wrap the lm head as custom forward only works with it, this is done in setup_model
inject_prime_lm_head(model, chunk_size=None)
with torch.autocast("cuda", dtype=torch.bfloat16):
inputs_ids = torch.randint(0, 100, (BS, SEQ_LEN)).to("cuda")
outputs = model(input_ids=inputs_ids).logits
outputs = model(input_ids=inputs_ids)
logits = outputs["logits"]
assert outputs.shape == (BS, SEQ_LEN, model.config.vocab_size)
assert logits.shape == (BS, SEQ_LEN, model.config.vocab_size)
@pytest.mark.skip(reason="need special token for meta stuff in ci")
@@ -121,9 +129,12 @@ def test_moe_custom_impl():
def test_model_forward_custom_impl(model_name):
config = ModelConfig(name=model_name, impl="custom", attn="sdpa")
model = get_model(config)
# we need to wrap the lm head as custom forward only works with it, this is done in setup_model
inject_prime_lm_head(model, chunk_size=None)
model = model.to("cuda")
with torch.autocast("cuda", dtype=torch.bfloat16):
inputs_ids = torch.randint(0, 100, (BS, SEQ_LEN)).to("cuda")
outputs = model(input_ids=inputs_ids).logits
outputs = model(input_ids=inputs_ids)
logits = outputs["logits"]
assert outputs.shape == (BS, SEQ_LEN, model.config.vocab_size)
assert logits.shape == (BS, SEQ_LEN, model.config.vocab_size)
View File
+85
View File
@@ -0,0 +1,85 @@
import asyncio
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock
import httpx
import pytest
from prime_rl.utils.client import _is_retryable_lora_error, load_lora_adapter
def test_is_retryable_lora_error_returns_true_for_404():
response = MagicMock()
response.status_code = 404
error = httpx.HTTPStatusError("Not found", request=MagicMock(), response=response)
assert _is_retryable_lora_error(error) is True
def test_is_retryable_lora_error_returns_true_for_500():
response = MagicMock()
response.status_code = 500
error = httpx.HTTPStatusError("Server error", request=MagicMock(), response=response)
assert _is_retryable_lora_error(error) is True
def test_is_retryable_lora_error_returns_false_for_400():
response = MagicMock()
response.status_code = 400
error = httpx.HTTPStatusError("Bad request", request=MagicMock(), response=response)
assert _is_retryable_lora_error(error) is False
def test_is_retryable_lora_error_returns_false_for_non_http_error():
assert _is_retryable_lora_error(ValueError("some error")) is False
def test_load_lora_adapter_succeeds_on_first_attempt():
mock_client = AsyncMock()
mock_response = MagicMock()
mock_response.raise_for_status = MagicMock()
mock_client.post.return_value = mock_response
asyncio.run(load_lora_adapter([mock_client], "test-lora", Path("/test/path")))
mock_client.post.assert_called_once_with(
"/v1/load_lora_adapter",
json={"lora_name": "test-lora", "lora_path": "/test/path"},
)
def test_load_lora_adapter_retries_on_404_then_succeeds():
mock_client = AsyncMock()
error_response = MagicMock()
error_response.status_code = 404
success_response = MagicMock()
success_response.raise_for_status = MagicMock()
call_count = 0
async def mock_post(*args, **kwargs):
nonlocal call_count
call_count += 1
if call_count == 1:
raise httpx.HTTPStatusError("Not found", request=MagicMock(), response=error_response)
return success_response
mock_client.post = mock_post
asyncio.run(load_lora_adapter([mock_client], "test-lora", Path("/test/path")))
assert call_count == 2
def test_load_lora_adapter_raises_non_retryable_error_immediately():
mock_client = AsyncMock()
error_response = MagicMock()
error_response.status_code = 400
mock_client.post.side_effect = httpx.HTTPStatusError("Bad request", request=MagicMock(), response=error_response)
with pytest.raises(httpx.HTTPStatusError) as exc_info:
asyncio.run(load_lora_adapter([mock_client], "test-lora", Path("/test/path")))
assert exc_info.value.response.status_code == 400
assert mock_client.post.call_count == 1
+226
View File
@@ -0,0 +1,226 @@
"""Tests for the Prometheus metrics server."""
import socket
import time
import urllib.request
from contextlib import closing
import pytest
from prime_rl.utils.config import MetricsServerConfig
from prime_rl.utils.metrics_server import PROMETHEUS_AVAILABLE, MetricsServer, RunStats
def find_free_port() -> int:
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
s.bind(("", 0))
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
return s.getsockname()[1]
def test_config_default_values():
config = MetricsServerConfig()
assert config.port == 8000
assert config.host == "0.0.0.0"
def test_config_custom_port():
config = MetricsServerConfig(port=9090)
assert config.port == 9090
def test_config_invalid_port_low():
with pytest.raises(ValueError):
MetricsServerConfig(port=0)
def test_config_invalid_port_high():
with pytest.raises(ValueError):
MetricsServerConfig(port=65536)
def test_server_start_stop():
port = find_free_port()
server = MetricsServer(MetricsServerConfig(port=port))
server.start()
assert server._started
time.sleep(0.1)
response = urllib.request.urlopen(f"http://localhost:{port}/metrics", timeout=2)
assert response.status == 200
server.stop()
assert not server._started
def test_server_returns_404_on_unknown_path():
port = find_free_port()
server = MetricsServer(MetricsServerConfig(port=port))
server.start()
time.sleep(0.1)
try:
urllib.request.urlopen(f"http://localhost:{port}/unknown", timeout=2)
pytest.fail("Expected 404")
except urllib.error.HTTPError as e:
assert e.code == 404
finally:
server.stop()
def test_server_double_start_is_safe():
port = find_free_port()
server = MetricsServer(MetricsServerConfig(port=port))
server.start()
server.start() # Should not raise
server.stop()
def test_server_update_metrics():
port = find_free_port()
server = MetricsServer(MetricsServerConfig(port=port))
server.start()
time.sleep(0.1)
server.update(step=42, loss=0.5, throughput=1000.0, grad_norm=1.5, peak_memory_gib=10.0, learning_rate=1e-4)
response = urllib.request.urlopen(f"http://localhost:{port}/metrics", timeout=2)
content = response.read().decode()
if PROMETHEUS_AVAILABLE:
assert "trainer_step" in content
assert "trainer_loss" in content
assert "trainer_last_step_timestamp_seconds" in content
assert "trainer_mismatch_kl" in content
server.stop()
@pytest.mark.skipif(not PROMETHEUS_AVAILABLE, reason="prometheus_client not installed")
def test_server_metrics_values_are_correct():
port = find_free_port()
server = MetricsServer(MetricsServerConfig(port=port))
server.start()
time.sleep(0.1)
server.update(
step=100,
loss=0.123,
throughput=5000.0,
grad_norm=2.5,
peak_memory_gib=16.0,
learning_rate=3e-5,
mismatch_kl=0.045,
)
response = urllib.request.urlopen(f"http://localhost:{port}/metrics", timeout=2)
content = response.read().decode()
assert "trainer_step 100.0" in content
assert "trainer_loss 0.123" in content
assert "trainer_mismatch_kl 0.045" in content
server.stop()
def test_server_isolated_registry():
"""Each MetricsServer instance should have its own registry."""
port1 = find_free_port()
port2 = find_free_port()
server1 = MetricsServer(MetricsServerConfig(port=port1))
server2 = MetricsServer(MetricsServerConfig(port=port2))
server1.start()
server2.start()
time.sleep(0.1)
server1.update(step=999, loss=0.1, throughput=100, grad_norm=1, peak_memory_gib=1, learning_rate=1e-3)
if PROMETHEUS_AVAILABLE:
resp1 = urllib.request.urlopen(f"http://localhost:{port1}/metrics", timeout=2).read().decode()
resp2 = urllib.request.urlopen(f"http://localhost:{port2}/metrics", timeout=2).read().decode()
assert "999.0" in resp1
assert "999.0" not in resp2
server1.stop()
server2.stop()
def test_server_port_conflict_raises():
port = find_free_port()
server1 = MetricsServer(MetricsServerConfig(port=port))
server1.start()
time.sleep(0.1)
server2 = MetricsServer(MetricsServerConfig(port=port))
with pytest.raises(OSError):
server2.start()
server1.stop()
@pytest.mark.skipif(not PROMETHEUS_AVAILABLE, reason="prometheus_client not installed")
def test_server_update_runs():
port = find_free_port()
server = MetricsServer(MetricsServerConfig(port=port))
server.start()
time.sleep(0.1)
run_stats = [
RunStats(run_id="run_001", step=50, total_tokens=100000, learning_rate=1e-4, ready=True),
RunStats(run_id="run_002", step=25, total_tokens=50000, learning_rate=1e-5, ready=False),
]
server.update_runs(runs_discovered=5, runs_max=8, run_stats=run_stats)
response = urllib.request.urlopen(f"http://localhost:{port}/metrics", timeout=2)
content = response.read().decode()
# Check aggregate metrics
assert "trainer_runs_discovered 5.0" in content
assert "trainer_runs_active 2.0" in content
assert "trainer_runs_ready 1.0" in content
assert "trainer_runs_max 8.0" in content
# Check per-run metrics with labels
assert 'trainer_run_step{run="run_001"} 50.0' in content
assert 'trainer_run_step{run="run_002"} 25.0' in content
assert 'trainer_run_tokens{run="run_001"} 100000.0' in content
assert 'trainer_run_learning_rate{run="run_001"}' in content
assert 'trainer_run_ready{run="run_001"} 1.0' in content
assert 'trainer_run_ready{run="run_002"} 0.0' in content
server.stop()
@pytest.mark.skipif(not PROMETHEUS_AVAILABLE, reason="prometheus_client not installed")
def test_server_update_runs_cleanup():
"""Test that removed runs are cleaned up from metrics."""
port = find_free_port()
server = MetricsServer(MetricsServerConfig(port=port))
server.start()
time.sleep(0.1)
# First update with two runs
run_stats = [
RunStats(run_id="run_001", step=50, total_tokens=100000, learning_rate=1e-4, ready=True),
RunStats(run_id="run_002", step=25, total_tokens=50000, learning_rate=1e-5, ready=False),
]
server.update_runs(runs_discovered=2, runs_max=8, run_stats=run_stats)
# Second update with only one run (run_002 removed)
run_stats = [
RunStats(run_id="run_001", step=60, total_tokens=120000, learning_rate=1e-4, ready=True),
]
server.update_runs(runs_discovered=1, runs_max=8, run_stats=run_stats)
response = urllib.request.urlopen(f"http://localhost:{port}/metrics", timeout=2)
content = response.read().decode()
# run_001 should be updated
assert 'trainer_run_step{run="run_001"} 60.0' in content
# run_002 should be removed
assert 'run_002' not in content
server.stop()
+10 -5
View File
@@ -73,11 +73,16 @@ def check_number_in_range(
"""Helper to assert that a number in step logs is within a threshold"""
step_lines = [line for line in lines if "Step" in line]
assert len(step_lines) > 0, f"No step lines found in output ({lines})"
try:
step_line = step_lines[step]
except IndexError:
step_line = ""
assert step_line, f"Could not find step {step} in output ({lines})"
# Search for the specific step number in the lines
if step == -1:
step_line = step_lines[-1]
else:
step_pattern = rf"Step {step}\b"
matching_lines = [line for line in step_lines if re.search(step_pattern, line)]
assert len(matching_lines) > 0, f"Could not find step {step} in output ({step_lines})"
step_line = matching_lines[0]
step_reward = re.search(pattern, step_line)
assert step_reward is not None, f"Could not find reward for step {step}. Line: {step_line} ({lines})"
step_reward = float(step_reward.group(1))
Generated
+59 -11
View File
@@ -828,6 +828,28 @@ requires-dist = [
{ name = "torch" },
]
[[package]]
name = "flash-attn-3"
version = "3.0.0b1"
source = { url = "https://github.com/samsja/flash-attn-builds/releases/download/v0.1/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl" }
dependencies = [
{ name = "einops" },
{ name = "ninja" },
{ name = "packaging" },
{ name = "torch" },
]
wheels = [
{ url = "https://github.com/samsja/flash-attn-builds/releases/download/v0.1/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl", hash = "sha256:4878b0e81704972109479f0667b2ace65f62e62a1161c9dbc23fa746889c79e4" },
]
[package.metadata]
requires-dist = [
{ name = "einops" },
{ name = "ninja" },
{ name = "packaging" },
{ name = "torch" },
]
[[package]]
name = "flashinfer-python"
version = "0.5.3"
@@ -1612,7 +1634,7 @@ wheels = [
[[package]]
name = "mcp"
version = "1.13.1"
version = "1.25.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "anyio" },
@@ -1621,15 +1643,18 @@ dependencies = [
{ name = "jsonschema" },
{ name = "pydantic" },
{ name = "pydantic-settings" },
{ name = "pyjwt", extra = ["crypto"] },
{ name = "python-multipart" },
{ name = "pywin32", marker = "sys_platform == 'win32'" },
{ name = "sse-starlette" },
{ name = "starlette" },
{ name = "typing-extensions" },
{ name = "typing-inspection" },
{ name = "uvicorn", marker = "sys_platform != 'emscripten'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/66/3c/82c400c2d50afdac4fbefb5b4031fd327e2ad1f23ccef8eee13c5909aa48/mcp-1.13.1.tar.gz", hash = "sha256:165306a8fd7991dc80334edd2de07798175a56461043b7ae907b279794a834c5", size = 438198, upload-time = "2025-08-22T09:22:16.061Z" }
sdist = { url = "https://files.pythonhosted.org/packages/d5/2d/649d80a0ecf6a1f82632ca44bec21c0461a9d9fc8934d38cb5b319f2db5e/mcp-1.25.0.tar.gz", hash = "sha256:56310361ebf0364e2d438e5b45f7668cbb124e158bb358333cd06e49e83a6802", size = 605387, upload-time = "2025-12-19T10:19:56.985Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/19/3f/d085c7f49ade6d273b185d61ec9405e672b6433f710ea64a90135a8dd445/mcp-1.13.1-py3-none-any.whl", hash = "sha256:c314e7c8bd477a23ba3ef472ee5a32880316c42d03e06dcfa31a1cc7a73b65df", size = 161494, upload-time = "2025-08-22T09:22:14.705Z" },
{ url = "https://files.pythonhosted.org/packages/e2/fc/6dc7659c2ae5ddf280477011f4213a74f806862856b796ef08f028e664bf/mcp-1.25.0-py3-none-any.whl", hash = "sha256:b37c38144a666add0862614cc79ec276e97d72aa8ca26d622818d4e278b9721a", size = 233076, upload-time = "2025-12-19T10:19:55.416Z" },
]
[[package]]
@@ -2432,6 +2457,12 @@ dependencies = [
flash-attn = [
{ name = "flash-attn" },
]
flash-attn-3 = [
{ name = "flash-attn-3" },
]
metrics = [
{ name = "prometheus-client" },
]
[package.dev-dependencies]
dev = [
@@ -2451,6 +2482,7 @@ requires-dist = [
{ name = "datasets", specifier = ">=4.0.0" },
{ name = "dion", git = "https://github.com/samsja/dion.git?rev=main" },
{ name = "flash-attn", marker = "extra == 'flash-attn'", url = "https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.6.8/flash_attn-2.8.3+cu128torch2.9-cp312-cp312-linux_x86_64.whl" },
{ name = "flash-attn-3", marker = "extra == 'flash-attn-3'", url = "https://github.com/samsja/flash-attn-builds/releases/download/v0.1/flash_attn_3-3.0.0b1-cp39-abi3-linux_x86_64.whl" },
{ name = "jaxtyping", specifier = ">=0.3.2" },
{ name = "liger-kernel", specifier = ">=0.5.10" },
{ name = "loguru", specifier = ">=0.7.3" },
@@ -2461,6 +2493,7 @@ requires-dist = [
{ name = "openai", specifier = ">=1.106.1" },
{ name = "prime", specifier = ">=0.5.0" },
{ name = "prime-evals", specifier = ">=0.1.5" },
{ name = "prometheus-client", marker = "extra == 'metrics'", specifier = ">=0.20.0" },
{ name = "pydantic", specifier = ">=1.10.13" },
{ name = "pydantic-settings", specifier = ">=2.10.1" },
{ name = "pylatexenc", specifier = ">=2.10" },
@@ -2478,11 +2511,11 @@ requires-dist = [
{ name = "torchtitan", git = "https://github.com/pytorch/torchtitan?rev=a1fdd7e" },
{ name = "transformers", specifier = ">=4.56.0" },
{ name = "uvloop", specifier = ">=0.21.0" },
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=eb3bae36c93b2f574e13a39da2908609d4ec4b2f" },
{ name = "verifiers", git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=209774a" },
{ name = "vllm", specifier = "==0.12.0" },
{ name = "wandb", specifier = ">=0.20.1" },
]
provides-extras = ["flash-attn"]
provides-extras = ["flash-attn", "flash-attn-3", "metrics"]
[package.metadata.requires-dev]
dev = [
@@ -2495,7 +2528,7 @@ dev = [
[[package]]
name = "prime-sandboxes"
version = "0.2.7"
version = "0.2.9"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "aiofiles" },
@@ -2503,9 +2536,9 @@ dependencies = [
{ name = "pydantic" },
{ name = "tenacity" },
]
sdist = { url = "https://files.pythonhosted.org/packages/08/b6/5acc211831acd3670f2d8d02bb8f75c2ff47999958393b1005bf250821d8/prime_sandboxes-0.2.7.tar.gz", hash = "sha256:1bd6f70a5be14ac1366ee96d0c3bb2a80521fdeeee7bca8453a95140bcac0e25", size = 45095, upload-time = "2025-12-19T11:53:10.539Z" }
sdist = { url = "https://files.pythonhosted.org/packages/59/55/e6c855074af9ef027f3601396d4e5e0b464f26f724c074253dd0dd2f47b7/prime_sandboxes-0.2.9.tar.gz", hash = "sha256:af4ad06d205a95f4c54778ecac8492f3f382c850528072df79252e7fd0f3fa08", size = 45538, upload-time = "2026-01-07T20:24:15.352Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/f0/11/bf9f7732a0ed6ef9665cbd5d6ff4f074ee0032e2ba0e4574ee8a65a97efa/prime_sandboxes-0.2.7-py3-none-any.whl", hash = "sha256:ac32e0d78d9655378548b627f9cdffd68d8116c36f596297ad7224d920f219b2", size = 18310, upload-time = "2025-12-19T11:53:09.627Z" },
{ url = "https://files.pythonhosted.org/packages/88/ae/5d38212ff0cbad2c468e9b5cf1e3235af04d123b55c4adaa8812abdeabbb/prime_sandboxes-0.2.9-py3-none-any.whl", hash = "sha256:dab4dd9c1f4f633386593cfb08f7a3dacb2de4eb6e75f4a2ec7f5f1c6ea2207b", size = 18824, upload-time = "2026-01-07T20:24:14.133Z" },
]
[[package]]
@@ -2792,6 +2825,20 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/c7/21/705964c7812476f378728bdf590ca4b771ec72385c533964653c68e86bdc/pygments-2.19.2-py3-none-any.whl", hash = "sha256:86540386c03d588bb81d44bc3928634ff26449851e99741617ecb9037ee5ec0b", size = 1225217, upload-time = "2025-06-21T13:39:07.939Z" },
]
[[package]]
name = "pyjwt"
version = "2.10.1"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/e7/46/bd74733ff231675599650d3e47f361794b22ef3e3770998dda30d3b63726/pyjwt-2.10.1.tar.gz", hash = "sha256:3cc5772eb20009233caf06e9d8a0577824723b44e6648ee0a2aedb6cf9381953", size = 87785, upload-time = "2024-11-28T03:43:29.933Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/61/ad/689f02752eeec26aed679477e80e632ef1b682313be70793d798c1d5fc8f/PyJWT-2.10.1-py3-none-any.whl", hash = "sha256:dcdd193e30abefd5debf142f9adfcdd2b58004e644f25406ffaebd50bd98dacb", size = 22997, upload-time = "2024-11-28T03:43:27.893Z" },
]
[package.optional-dependencies]
crypto = [
{ name = "cryptography" },
]
[[package]]
name = "pylatexenc"
version = "3.0a33"
@@ -3018,7 +3065,7 @@ dependencies = [
{ name = "verifiers" },
]
wheels = [
{ url = "https://hub.primeintellect.ai/primeintellect/reverse-text/@f5644269/reverse_text-0.1.4-py2.py3-none-any.whl", hash = "sha256:0adc3abcb6ceba3fa82709258c732e95c90400bc899230dce47a2e0f31a74aec" },
{ url = "https://hub.primeintellect.ai/primeintellect/reverse-text/@efe79870/reverse_text-0.1.4-py2.py3-none-any.whl", hash = "sha256:0adc3abcb6ceba3fa82709258c732e95c90400bc899230dce47a2e0f31a74aec" },
]
[[package]]
@@ -3814,12 +3861,13 @@ wheels = [
[[package]]
name = "verifiers"
version = "0.1.8.post2"
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=eb3bae36c93b2f574e13a39da2908609d4ec4b2f#eb3bae36c93b2f574e13a39da2908609d4ec4b2f" }
version = "0.1.9.post3"
source = { git = "https://github.com/PrimeIntellect-ai/verifiers.git?rev=209774a#209774a22b6915eeff2091a1ce2782ecbe580ae7" }
dependencies = [
{ name = "datasets" },
{ name = "jinja2" },
{ name = "math-verify" },
{ name = "mcp" },
{ name = "nest-asyncio" },
{ name = "openai" },
{ name = "openai-agents" },