Compare commits

...
Author SHA1 Message Date
8136f13c55 log reward statistics (#1866)
Release / Push CUDA image to Docker (push) Canceled after 0s
* log reward statistics

* ruff

---------

Co-authored-by: hallerite <git@hallerite.com>
2026-02-24 11:36:03 -08:00
cc59d7bedf cleaner naming for discriminated unions in config (#1879)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Drop Type suffix from config union TypeAliases

Rename all *ConfigType aliases to drop the redundant suffix:
- OptimizerConfigType → OptimizerConfig
- SchedulerConfigType → SchedulerConfig
- DeploymentConfigType → DeploymentConfig
- SFTDeploymentConfigType → SFTDeploymentConfig
- DataConfigType → DataConfig
- TransportConfigType → TransportConfig
- FilterConfigType → FilterConfig
- WeightBroadcastConfigType → WeightBroadcastConfig
- LossConfigType → LossConfig (class renamed to DefaultLossConfig)
- AdvantageConfigType → AdvantageConfig (class renamed to DefaultAdvantageConfig)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Move Field(discriminator) into TypeAliases, simplify field sites

Embed Field(discriminator="type") in each union TypeAlias so field
declarations can use the alias directly without wrapping in
Annotated[..., Field(discriminator="type")].

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 11:28:16 -08:00
cfed378624 replace callable discriminator with field values (#1878)
Release / Push CUDA image to Docker (push) Canceled after 0s
LossConfigType and AdvantageConfigType used callable discriminators with
Tag annotations to provide a default fallback when the "type" key was
missing. This is unnecessary since _default_discriminator_types on
BaseSettings already injects the type tag from defaults. Switch to the
simpler Field(discriminator="type") pattern used by all other unions.

LossConfig and AdvantageConfig are changed from BaseConfig to BaseModel
because BaseConfig's field_validator("*", mode="before") conflicts with
pydantic's string-based discriminator. Neither model has Optional fields
that benefit from the empty_str_to_none validator.

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 11:15:16 -08:00
f9b7856eec fix: per-component seq_len overrides shared seq_len (#1875)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fix: per-component seq_len overrides shared seq_len

Remove `nested_model_default_partial_update=True` from BaseSettings so that
`model_fields_set` correctly tracks which nested fields were explicitly set
in the config. This lets `auto_setup_seq_len` propagate the shared `seq_len`
only to components that didn't receive an explicit value.

- Bump pydantic-settings >=2.12.0
- Replace the `normalize_deployment` workaround with a generic
  `_default_discriminator_types` before-validator that injects the `type`
  tag from a field's default instance when missing
- Guard `auto_setup_seq_len` with `model_fields_set` checks

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* add hendrycks sanity check exp (#1873)

* Flesh out hendrycks sanity example README

Add explanation of the sanity check methodology (perfectible dataset
filtering), setup instructions, and training commands for local/SLURM.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* update examples

* Add hendrycks sanity to training examples list in README

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* update readme

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>

* add output_dir safety check to prevent accidental overwrites (#1872)

* Add output_dir safety check to prevent accidental overwrites

Training now raises FileExistsError when output_dir already contains
files from a previous run, unless explicitly resuming (ckpt.resume_step)
or opting in to clean (clean_output_dir=true). This encourages using
unique per-experiment output directories and prevents silent data loss.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Move output_dir validation to entrypoints (before SLURM submission)

Validate in sft()/rl() dispatch functions instead of pydantic validators
or train() functions. This ensures the check runs before sbatch submit
while keeping config parsing side-effect-free.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Remove old clean flag from RLConfig local path

The old `clean` field (default True) silently deleted logs, rollouts,
and broadcasts on every local RL run. This is now superseded by the
explicit `clean_output_dir` flag on the trainer configs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Move clean_output_dir to RLConfig and use shared ckpt for resume check

clean_output_dir belongs on the top-level RLConfig (next to output_dir),
not on the trainer sub-config. The resume check now uses config.ckpt
(the shared checkpoint config) instead of config.trainer.ckpt.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* update err message

* Fix stray paren in error message, ensure dirs exist after clean, add changelog

- Fix stray ) in FileExistsError message text
- Create output_dir after validate_output_dir in both entrypoints so it
  exists even after a clean
- Add log_dir.mkdir in RL local path (was previously done by maybe_clean)
- Add CHANGELOG entries for clean_output_dir and clean removal

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* only raise if checkpoints exists

* Make RLConfig.output_dir non-optional and fix docs to match actual behavior

output_dir is always a Path after validation, so type it as Path with
default Path("outputs"). Fix docs/changelog that incorrectly said the
safety check triggers on "non-empty" dirs — it only triggers on dirs
containing checkpoints.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Add changelog entry for output_dir type change and SLURM validation removal

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* add env var to never clean output dir safeguard

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>

* add some more tests

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 10:29:23 -08:00
82652c7393 add output_dir safety check to prevent accidental overwrites (#1872)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Add output_dir safety check to prevent accidental overwrites

Training now raises FileExistsError when output_dir already contains
files from a previous run, unless explicitly resuming (ckpt.resume_step)
or opting in to clean (clean_output_dir=true). This encourages using
unique per-experiment output directories and prevents silent data loss.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Move output_dir validation to entrypoints (before SLURM submission)

Validate in sft()/rl() dispatch functions instead of pydantic validators
or train() functions. This ensures the check runs before sbatch submit
while keeping config parsing side-effect-free.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Remove old clean flag from RLConfig local path

The old `clean` field (default True) silently deleted logs, rollouts,
and broadcasts on every local RL run. This is now superseded by the
explicit `clean_output_dir` flag on the trainer configs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Move clean_output_dir to RLConfig and use shared ckpt for resume check

clean_output_dir belongs on the top-level RLConfig (next to output_dir),
not on the trainer sub-config. The resume check now uses config.ckpt
(the shared checkpoint config) instead of config.trainer.ckpt.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* update err message

* Fix stray paren in error message, ensure dirs exist after clean, add changelog

- Fix stray ) in FileExistsError message text
- Create output_dir after validate_output_dir in both entrypoints so it
  exists even after a clean
- Add log_dir.mkdir in RL local path (was previously done by maybe_clean)
- Add CHANGELOG entries for clean_output_dir and clean removal

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* only raise if checkpoints exists

* Make RLConfig.output_dir non-optional and fix docs to match actual behavior

output_dir is always a Path after validation, so type it as Path with
default Path("outputs"). Fix docs/changelog that incorrectly said the
safety check triggers on "non-empty" dirs — it only triggers on dirs
containing checkpoints.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Add changelog entry for output_dir type change and SLURM validation removal

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* add env var to never clean output dir safeguard

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 09:52:11 -08:00
4b0ecdb223 add hendrycks sanity check exp (#1873)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Flesh out hendrycks sanity example README

Add explanation of the sanity check methodology (perfectible dataset
filtering), setup instructions, and training commands for local/SLURM.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* update examples

* Add hendrycks sanity to training examples list in README

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* update readme

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 09:13:47 -08:00
1826b18927 unify rl and sft slurm entrypoints to enable single-node slurm deployments (#1859)
Release / Push CUDA image to Docker (push) Canceled after 0s
* fuse rl-slurm and rl

* also migrate sft slurm

* Move SLURM templates to templates/ and rename to multi_node_*

- rl_slurm.sh.j2 → templates/multi_node_rl.sh.j2
- sft_slurm.sh.j2 → templates/multi_node_sft.sh.j2
- Remove src/prime_rl/slurm/ directory entirely
- Update template path references in rl.py and sft/train.py

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* update

* add single node template

* allow setting env vars everywhere

* fixes

* fix

* rename to .sbatch

* update scripts

* update configs

* adopt deployment and slurm config for sft

* rename slurm.template -> slurm.template_path

* style

* make inference optional again and some misc bug fixes

* update examples

* fix configs

* rewrite slurm docs for unified entrypoints and fix slurm_sft.toml

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix config

* deprecate hf hub offline in sft slurm

* only HF_HUB_OFFLINE in multi_node

* tail with -F

* exclude deployment

* update changelog

* move templates

* update branch

* fix output dir

* do not allow None partition

* fix

* revert env_vars

* remove env_vars entries from changelog

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* address bugbot

* extract sft entrypoint

* move entrypoints

* cleanup logic in sft local

* fix single node sft slurm

* fix

* fix: resolve SLURM template path relative to package for editable installs

Co-authored-by: Cursor <cursoragent@cursor.com>

* add changelog line

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-24 03:11:21 -08:00
db5092914d afmoe ring attention support. (#1848)
Release / Push CUDA image to Docker (push) Canceled after 0s
* initial test for ring attn

* tmp

---------

Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
Signed-off-by: samsja <55492238+samsja@users.noreply.github.com>
Co-authored-by: S1ro1 <matej.sirovatka@gmail.com>
Co-authored-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
2026-02-23 23:23:54 -08:00
faresobeidandGitHub 5bd9809399 fix effective_batch_size metric (#1862)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-24 04:04:26 +00:00
448f8c09ad ep inference support (#1860)
Release / Push CUDA image to Docker (push) Canceled after 0s
* ep inference support

* some fixes

* docs: add inference EP config changelog entry

Co-authored-by: faresobeid <faresobeid@users.noreply.github.com>

* revert docs

* oops

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: faresobeid <faresobeid@users.noreply.github.com>
2026-02-24 01:59:57 +00:00
4076a0e457 Fix tool_call_parser not resolved when model name is propagated (#1854)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Move tool_call_parser log from validator to server startup

Validators shouldn't have logging side effects - they run during
config construction which causes spurious log messages on import.
Also use default_factory for ModelConfig to avoid eager instantiation.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* Fix tool_call_parser not resolved when model name is propagated

auto_setup_model() changes inference.model.name after the ModelConfig
validator has already run, leaving tool_call_parser stale from the
default model. Re-resolve after propagating the name, but only when
the current parser was auto-detected (preserves explicit overrides).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-23 14:12:48 -08:00
Mika SenghaasandGitHub ad8d775fc3 bump vf 3f555af (#1858)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-23 09:04:33 -08:00
c2027a79d0 Feat: GLM5 (#1827)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: add GLM-5 (glm_moe_dsa) custom model with MLA attention

Implement GLM-5 as a custom model following the 4-file convention:
- configuration, modeling, converting, and __init__
- MLA (Multi-head Latent Attention) with LoRA-compressed Q/KV
- Interleaved RoPE support via apply_rotary_pos_emb_interleave()
- Dense attention only (sparse Lightning Indexer is future work)
- Reuses existing MoE, MLP, RMSNorm, and RotaryEmbedding layers
- Weight conversion roundtrip (HF <-> PrimeRL) for MoE experts
- Indexer weights declared but unused for state dict compatibility
- mini_moe.py preset for test model creation
- Unit tests (attn-only, mlp-only, full model + roundtrip)

* feat: add sparse MLA attention with tilelang kernels for GLM-5

Add Dynamic Sparse Attention (DSA) to the glm_moe_dsa model using
vendored tilelang kernels for training fwd+bwd. Includes a bf16
PyTorch indexer (varlen-aware via cu_seqlens) and the absorption
trick to operate in compressed KV latent space (d_qk=576, d_v=512).

* Progress we run against vllm

* Feat: works but slow

* works now i think

* Cleanup

* deps

* Minor changes

* fix minimoe

* To be verified

* Feat: glm5

* Fix: scaling

* Fix more scaling

* FP8 quant

* Scale

* Cleanup: remove banner comments, verbose docstrings, dead code, and broken tests

- Remove license banner, section separators, and shape annotation comments
- Remove unused _weight_scale variable and commented-out code in fp8_indexer
- Trim verbose vendor attribution comments
- Consolidate duplicate warnings in GlmMoeDsaForCausalLM
- Remove broken test file (tests passed wrong kwargs to attention forward)
- Remove sloppy init comment in models/__init__.py

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

* final

* nit

* Fix GlmMoeDsaConfig pad_token_id forwarding

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

---------

Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Matej Sirovatka <S1ro1@users.noreply.github.com>
2026-02-22 19:14:56 -08:00
will brownandGitHub 944163ac68 track seqs per rollout (#1852)
Release / Push CUDA image to Docker (push) Canceled after 0s
* track seqs per rollout

* rename
2026-02-22 17:37:49 -08:00
samsjaandGitHub 1e7561668d make tito default (#1851)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-22 15:54:02 -08:00
fd78f21f79 make tito client opt-in (#1847)
Release / Push CUDA image to Docker (push) Canceled after 0s
* make tito client opt-in

* Add CHANGELOG entry for orchestrator.use_token_client config field

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-22 01:15:30 -08:00
7eade4f7e1 Add SFT SLURM entrypoint (#1832)
Release / Push CUDA image to Docker (push) Canceled after 0s
* add SFT SLURM entrypoint (`sft_slurm`)

Adds a `sft_slurm` CLI that mirrors `rl_slurm` but for SFT training.
The config extends `SFTTrainerConfig` directly (no `[trainer]` nesting)
with slurm-specific fields (num_nodes, gpus_per_node, etc.). Includes a
simplified Jinja2 SLURM template with no inference/orchestrator nodes.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* add sft example

* add SFT MoE SLURM example and slim down SFT docs

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* add sft slur config to tests

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 18:31:36 -08:00
bf0f903b86 Feature/auto detect tool call parser (#1844)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat(inference): auto-detect tool_call_parser from model name

Previously tool_call_parser defaulted to "hermes" regardless of model,
causing silent failures when the wrong parser was used. Now the parser
is automatically inferred from the model name via a hardcoded mapping.
Users can still override explicitly.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: simplify MODEL_TOOL_CALL_PARSER to dict, address PR review

- Use get_logger instead of std logging
- Replace ordered list-of-tuples with a simple dict (no aliases/ordering concerns)
- Don't raise on unknown model, leave tool_call_parser as None
- Scope supported models to GLM, MiniMax, INTELLECT-3, Qwen3

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: use exact model names in MODEL_TOOL_CALL_PARSER dict

Replace substring pattern matching with exact 1:1 model name lookup.
All supported models are listed explicitly by their HuggingFace ID.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* remove extra inference stuff

* feat: default enable_auto_tool_choice to True

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: auto-enable enable_auto_tool_choice when tool_call_parser is set

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: remove hermes default, leave tool_call_parser as None for unknown models

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 17:57:15 -08:00
Mika SenghaasandGitHub 8ffa00c648 remove model map (#1842)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-20 15:58:47 -08:00
samsjaandGitHub bc740de6dc bump vf (#1843)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-02-20 14:39:05 -08:00
105 changed files with 4039 additions and 1401 deletions
+18 -1
View File
@@ -59,5 +59,22 @@ Documenting changes which affect configuration usage patterns (added/moved/remov
- **`dump_config`**: Added `--dump-config <path>` flag to the `rl` command. When set, writes the resolved subconfigs (trainer, orchestrator, inference, teacher_inference) to the given directory and exits without starting any processes (2026-02-12)
- **`client.api_key_var`**: Changed default from "OPENAI_API_KEY" to "VLLM_API_KEY" (2026-02-12)
- **`orchestrator.filters`**: Added orchestrator-side rollout filters for detecting degenerate generations. Supports `[[filters]] type = "gibberish"` (rare tokens at high entropy) and `[[filters]] type = "repetition"` (high-confidence token streaks). Detected rollouts get reward zeroed and completion mask cleared (2026-02-13)
- **`inference.model.tool_call_parser`**: Changed default from `"hermes"` to auto-detection from model name. Uses `MODEL_TOOL_CALL_PARSER` dict to infer the correct vLLM tool call parser (e.g. Qwen3→`hermes`, GLM-4.5→`glm45`, GLM-4.7→`glm47`, MiniMax-M2→`minimax_m2`, INTELLECT-3→`hermes`). Unknown models default to `None`. Explicit values still take priority. (#1795, 2026-02-16)
- **`orchestrator.eval.cancel_inflight_rollouts_on_eval`**: Added flag to optionally cancel in-flight training rollouts before starting online evals. When enabled, avoids congestion by preventing training and eval rollouts from running simultaneously, but slows training as the rollout pipeline must refill after each eval (default: False) (2026-02-16)
- **`orchestrator.use_token_client`**: Added flag to use the token-in-token-out (TITO) client for training across all environments. When enabled, uses `openai_chat_completions_token` client type instead of `openai_chat_completions`. Only use when environments have linear history and the chat template has the extension property (default: False) (2026-02-21)
- **`model.cp` + AFMoE**: Context parallelism now works with AFMoE models via unified `substitute_ring_attn` which patches `_compute_attention` on both `FlashAttention` and `AfmoeFlashAttention` to use ring attention. Sliding window layers automatically get per-layer `window_size`; full attention layers default to `(-1, -1)`. Also plumbed `window_size` through the FA3 ring attention wrapper (`ring_fa3_varlen_func`). (2026-02-21)
- **`inference.enable_expert_parallel`**, **`inference.all2all_backend`**, and **`inference.enable_eplb`**: Added expert-parallel inference controls passed to vLLM as `--enable-expert-parallel`, `--all2all-backend`, and `--enable-eplb` (defaults: `False`, `"allgather_reducescatter"`, `False`) (2026-0
- **`rl_slurm` / `sft_slurm` entrypoints**: Removed. SLURM submission is now handled by the unified `rl` and `sft` entrypoints. Add a `[slurm]` section to your config to submit via SLURM instead of running locally (2026-02-23)
- **`inference_gpu_ids` / `trainer_gpu_ids` / `teacher_gpu_ids`**: Removed from `RLConfig`. Replaced by `[deployment]` section with `type = "single_node"` (fields: `num_train_gpus`, `num_infer_gpus`, `num_teacher_gpus`) or `type = "multi_node"` (fields: `num_train_nodes`, `num_infer_nodes`, `num_teacher_nodes`, `nodes_per_fsdp_group`). Default is `single_node` with 1 train GPU and 1 infer GPU (2026-02-23)
- **`RLSLURMConfig`**: Removed. Fields `job_name`, `num_train_nodes`, `num_infer_nodes`, `gpus_per_node`, `nodes_per_fsdp_group`, `project_dir`, `slurm_template`, `dry_run` are now under `[slurm]` and `[deployment]` in the unified `RLConfig` (2026-02-23)
- **`SFTSLURMConfig`**: Removed. Fields `job_name`, `num_nodes`, `gpus_per_node`, `nodes_per_fsdp_group`, `project_dir`, `slurm_template`, `dry_run` are now under `[slurm]` and `[deployment]` in `SFTTrainerConfig` (2026-02-23)
- **`[deployment]` (RL)**: Added deployment configuration. `type = "single_node"` auto-derives contiguous GPU assignments from `num_infer_gpus`, `num_train_gpus`, `num_teacher_gpus`. `type = "multi_node"` requires `[slurm]` and uses `num_train_nodes`, `num_infer_nodes` (2026-02-23)
- **`[deployment]` (SFT)**: Added deployment configuration. `type = "single_node"` with `num_gpus` (default: 1). `type = "multi_node"` with `num_nodes`, `nodes_per_fsdp_group`, `hf_hub_offline` (2026-02-23)
- **`[slurm]` (RL)**: Added SLURM configuration with `job_name`, `project_dir`, `template_path`, `partition`, `dry_run`. When present, `uv run rl` generates and submits an sbatch script instead of running locally. Template is auto-selected based on deployment type (2026-02-23)
- **`[slurm]` (SFT)**: Added SLURM configuration with `job_name`, `project_dir`, `template_path`, `partition`, `dry_run`. When present, `uv run sft` generates and submits an sbatch script instead of running locally (2026-02-23)
- **`hf_hub_offline` (RL/SFT SLURM)**: Removed. `HF_HUB_OFFLINE=1` is now hardcoded in the multi-node SLURM templates (2026-02-23)
- **SLURM templates**: Moved from `src/prime_rl/slurm/` to `src/prime_rl/templates/` and renamed to `single_node_rl.sbatch.j2`, `multi_node_rl.sbatch.j2`, `single_node_sft.sbatch.j2`, `multi_node_sft.sbatch.j2` (2026-02-23)
- **Entrypoints**: Moved `rl` and `sft` entrypoints from `prime_rl.rl` / `prime_rl.sft` to `prime_rl.entrypoints.rl` / `prime_rl.entrypoints.sft`. No change to CLI usage (`uv run rl`, `uv run sft`) (2026-02-24)
- **`output_dir` (RL)**: Changed from `Path | None` (default `None`) to `Path` (default `Path("outputs")`). The SLURM-specific validation that rejected the default has been removed — `output_dir` now works the same for local and SLURM runs (2026-02-24)
- **`clean_output_dir`**: Added to `RLConfig` and `SFTTrainerConfig` (default: `False`). Training now raises `FileExistsError` when `output_dir` contains checkpoints from a previous run and not resuming. Set `clean_output_dir=true` to delete and start fresh, or set `ckpt.resume_step` to resume (2026-02-24)
- **`clean`**: Removed from `RLConfig`. The old `clean` flag (default: `True`) silently deleted logs, rollouts, and broadcasts on every local RL run. Superseded by the explicit `clean_output_dir` flag (2026-02-24)
+2 -1
View File
@@ -164,8 +164,9 @@ We provide end-to-end training examples in the [`examples`](examples) directory
2. [**Wordle**](examples/wordle/README.md): Train `Qwen3-1.7B` to play Wordle. A fun example of multi-turn SFT and RL training. Can be trained on a 2-4 H100 GPUs in a few hours. Ideal for exploring the multi-turn training capabilities of the framework.
3. [**Alphabet Sort**](examples/alphabet_sort/README.md): Train `Qwen3-4B-Instruct-2507` to sort names alphabetically. Demonstrates multi-turn RL training via LoRA without SFT warmup. Can be trained on a single H100 GPU in just over an hour. Ideal for exploring LoRA-based training.
4. [**Wiki Search**](examples/wiki_search/README.md): Train `Qwen3-4B-Instruct-2507` to answer trivia questions by searching through a Wikipedia. Demonstrates multi-turn with web search tool use.
5. [**Hendrycks Sanity**](examples/hendrycks_sanity/README.md): Run a sanity check experiment on `DeepSeek-R1-Distill-Qwen-1.5B` using a filtered subset of MATH where the model already partially solves 20-80% of problems. Useful for algorithm ablations.
4. *More to come...*
*More to come...*
## Docs
+4 -3
View File
@@ -1,9 +1,10 @@
inference_gpu_ids = [0,1,2,3,4,5]
trainer_gpu_ids = [6,7]
max_steps = 500
seq_len = 8192
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
+4 -3
View File
@@ -1,9 +1,10 @@
inference_gpu_ids = [0,1,2,3,4,5]
trainer_gpu_ids = [6,7]
max_steps = 1000
seq_len = 16384
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 10
seq_len = 2048
-3
View File
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 25
seq_len = 2048
-3
View File
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 20
seq_len = 2048
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 25
seq_len = 2048
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 20
seq_len = 2048
-3
View File
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 20
seq_len = 2048
+4 -3
View File
@@ -3,12 +3,13 @@
# - 300 instead of 500 steps
# - No checkpointing
# - No evals
inference_gpu_ids = [0,1,2,3]
trainer_gpu_ids = [4,5,6,7]
max_steps = 300
seq_len = 8192
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
+4 -3
View File
@@ -1,9 +1,10 @@
inference_gpu_ids = [0,1,2,3]
trainer_gpu_ids = [4,5,6,7]
max_steps = 300
seq_len = 2048
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
@@ -1,10 +1,11 @@
# Based on configs/multimodal/rl_color_codeword.toml but tuned for CI
inference_gpu_ids = [0,1,2,3]
trainer_gpu_ids = [4,5,6,7]
max_steps = 25
seq_len = 4096
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[model]
name = "Qwen/Qwen3-VL-4B-Instruct"
+4 -3
View File
@@ -1,9 +1,10 @@
inference_gpu_ids = [0,1,2,3,4,5]
trainer_gpu_ids = [6,7]
max_steps = 500
seq_len = 8192
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
+4 -3
View File
@@ -1,9 +1,10 @@
inference_gpu_ids = [0,1,2,3,4,5]
trainer_gpu_ids = [6,7]
max_steps = 1000
seq_len = 16384
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
+4 -3
View File
@@ -1,9 +1,10 @@
inference_gpu_ids = [0,1,2,3,4,5]
trainer_gpu_ids = [6,7]
max_steps = 1500
seq_len = 24576
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
+1 -1
View File
@@ -43,4 +43,4 @@ sync_interval = 5.0
[[orchestrator.env]]
id = "primeintellect/alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
+4 -3
View File
@@ -1,9 +1,10 @@
trainer_gpu_ids = [0,1,2,3]
inference_gpu_ids = [4,5,6,7]
max_steps = 300
seq_len = 8192
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[wandb]
project = "env-mix-debug"
name = "env-mix"
-3
View File
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 100
seq_len = 2048
-3
View File
@@ -1,6 +1,3 @@
trainer_gpu_ids = [0]
inference_gpu_ids = [1]
max_steps = 500
seq_len = 2048
-3
View File
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 3000
seq_len = 8192
-3
View File
@@ -1,6 +1,3 @@
trainer_gpu_ids = [0]
inference_gpu_ids = [1]
max_steps = 500
[wandb]
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 15
seq_len = 4096
-3
View File
@@ -1,6 +1,3 @@
inference_gpu_ids = [0]
trainer_gpu_ids = [1]
max_steps = 500
seq_len = 4096
+151 -79
View File
@@ -1,89 +1,113 @@
# SLURM
For SLURM clusters, use the `rl_slurm` entrypoint. It resolves the full config (trainer, orchestrator, inference), dumps sub-configs as TOML files, renders a SLURM batch script from a Jinja2 template, and submits it with `sbatch`.
Both `rl` and `sft` have built-in SLURM support. Adding a `[slurm]` section to your config switches from local execution to SLURM job submission — no separate entrypoint needed.
## Quick Start
```bash
uv run rl_slurm @ examples/slurm/hendrycks_math.toml
# Local run
uv run rl @ examples/reverse_text/rl.toml
# SLURM run (same entrypoint, just add [slurm] to the config)
uv run rl @ examples/reverse_text/slurm_rl.toml
```
This will:
The SLURM config is a thin overlay that inherits from a base config and adds `[slurm]` + `[deployment]` sections:
1. Write resolved sub-configs to `{output_dir}/configs/` (trainer.toml, orchestrator.toml, inference.toml)
2. Render the SLURM script to `{output_dir}/rl.sh`
3. Submit the job via `sbatch`
```toml
# examples/reverse_text/slurm_rl.toml
toml_files = ["rl.toml"]
To only generate the script without submitting, use `--dry-run`:
output_dir = "outputs/reverse-text-rl"
```bash
uv run rl_slurm @ examples/slurm/hendrycks_math.toml --dry-run
[slurm]
job_name = "reverse-text-rl"
```
## How it works
When `[slurm]` is present, the entrypoint:
1. Resolves the full config
2. Renders a SLURM batch script from a Jinja2 template
3. Writes the script and resolved config to `{output_dir}/`
4. Submits via `sbatch` (or prints the script with `--slurm.dry-run`)
For **single-node** jobs, the entire config is dumped to a TOML file and the template simply runs `uv run rl @` or `uv run sft @` on the allocated node.
For **multi-node** jobs, sub-configs are written separately and `srun` dispatches processes across nodes.
## Configuration
The SLURM config extends the standard RL config with the following fields:
### `[slurm]` — Job submission (shared between RL and SFT)
| Field | Description |
|---|---|
| `job_name` | SLURM job name |
| `output_dir` | Directory for outputs, sub-configs, and logs |
| `project_dir` | Path to the project root on the cluster (defaults to cwd) |
| `num_train_nodes` | Number of nodes for training |
| `num_infer_nodes` | Number of nodes for inference |
| `gpus_per_node` | Number of GPUs per node (default: 8) |
| `nodes_per_fsdp_group` | Number of train nodes per FSDP island (optional, auto-sets `trainer.dp_replicate`) |
| `slurm_template` | Path to a custom Jinja2 template (optional) |
| `dry_run` | Only generate the script without submitting (default: false) |
| Field | Description | Default |
|---|---|---|
| `job_name` | SLURM job name | `"prime-rl"` |
| `project_dir` | Path to the project root on the cluster | `"."` |
| `template_path` | Path to a custom Jinja2 template | auto-selected |
| `partition` | SLURM partition | `"cluster"` |
| `dry_run` | Generate script without submitting | `false` |
All standard RL config fields (model, trainer, orchestrator, inference, wandb, ckpt, etc.) are available and will be resolved into the sub-configs.
### `[deployment]` — Node and GPU allocation
### Dense model (Hendrycks Math)
**RL** uses a discriminated union with `type = "single_node"` (default) or `type = "multi_node"`:
| Field | single_node | multi_node |
|---|---|---|
| `gpus_per_node` | Number of GPUs per node (default: 8) | Same |
| `num_train_gpus` | Training GPUs | — |
| `num_infer_gpus` | Inference GPUs | — |
| `num_train_nodes` | — | Training nodes |
| `num_infer_nodes` | — | Inference nodes |
| `nodes_per_fsdp_group` | — | Nodes per FSDP island (optional) |
**SFT** follows the same pattern but only has training nodes:
| Field | single_node | multi_node |
|---|---|---|
| `gpus_per_node` | Number of GPUs per node (default: 8) | Same |
| `num_gpus` | Number of GPUs (default: 1) | — |
| `num_nodes` | — | Training nodes (default: 2) |
| `nodes_per_fsdp_group` | — | Nodes per FSDP island (optional) |
The SLURM template is auto-selected based on `deployment.type`. You can override it with `slurm.template_path`.
### Constraints
- `output_dir` should be explicitly set when using SLURM (defaults to `"outputs"`)
- Multi-node deployment requires `[slurm]` to be set
---
## RL Examples
### Single-node SLURM
The simplest case: run on a single allocated node. No `[deployment]` needed — defaults to `single_node`.
```toml
job_name = "hendrycks-math"
output_dir = "/shared/outputs/my-rl-run"
num_train_nodes = 1
num_infer_nodes = 1
max_steps = 500
seq_len = 2048
[wandb]
project = "hendrycks-math"
name = "hendrycks-math"
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 128
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 2048
[[orchestrator.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
[inference.parallel]
tp = 1
dp = 8
[slurm]
job_name = "my-rl-run"
```
### MoE model (Hendrycks Math)
For MoE models like `Qwen3-30B-A3B`, the config is designed to minimize memory usage on a single training node. It enables activation checkpointing with offloading, optimizer CPU offload, and NCCL weight broadcast:
### Multi-node SLURM (Hendrycks Math)
```toml
job_name = "hendrycks-math-moe"
num_train_nodes = 1
num_infer_nodes = 1
output_dir = "outputs/rl-math-moe"
max_steps = 500
seq_len = 2048
[slurm]
job_name = "hendrycks-math-rl-moe"
[deployment]
type = "multi_node"
num_train_nodes = 1
num_infer_nodes = 1
[weight_broadcast]
type = "nccl"
@@ -118,37 +142,85 @@ tp = 4
dp = 2
```
## Custom SLURM Templates
See [`examples/hendrycks_math/rl.toml`](../examples/hendrycks_math/rl.toml) for the full example.
The default template handles a standard multi-node setup with NCCL weight broadcast, InfiniBand detection, and `srun`-based process dispatch. For more advanced use cases (custom partitions, account settings, module loads, different networking setups, etc.), provide your own Jinja2 template:
---
```bash
uv run rl_slurm \
@ my_config.toml \
--slurm-template path/to/my_template.sh.j2
## SFT Examples
### Single-node SLURM
```toml
output_dir = "/shared/outputs/my-sft-run"
[slurm]
job_name = "my-sft-run"
```
The template receives the following variables: `job_name`, `project_dir`, `output_dir`, `config_dir`, `num_train_nodes`, `num_infer_nodes`, `gpus_per_node`, `hf_hub_offline`. See `src/prime_rl/slurm/rl_slurm.sh.j2` for the default template as a starting point.
### Multi-node SLURM (MoE SFT)
```toml
output_dir = "outputs/sft-moe-math"
max_steps = 500
[slurm]
job_name = "sft-moe-math"
[deployment]
type = "multi_node"
num_nodes = 2
[model]
name = "Qwen/Qwen3-30B-A3B-Thinking-2507"
impl = "custom"
attn = "flash_attention_3"
optim_cpu_offload = true
[model.ac_offloading]
max_inflight_activations = 5
[model.ac]
freq = 1
[data]
type = "sft"
name = "PrimeIntellect/INTELLECT-3-SFT-10K"
subsets = ["default"]
splits = ["math"]
batch_size = 128
seq_len = 8192
```
See [`examples/hendrycks_math/sft.toml`](../examples/hendrycks_math/sft.toml) for the full example.
---
## Custom SLURM Templates
The default templates handle standard setups with InfiniBand detection, environment setup, and `srun`-based process dispatch. For advanced use cases (custom partitions, account settings, module loads, etc.), provide your own Jinja2 template:
```bash
uv run rl @ my_config.toml --slurm.template-path path/to/my_template.sbatch.j2
```
See [`src/prime_rl/templates/`](../src/prime_rl/templates/) for the default templates as a starting point.
## Monitoring
After submission, the logs are available at:
After submission, logs are available at:
```bash
tail -f {output_dir}/slurm/latest_train_node_rank_0.log
tail -f {output_dir}/slurm/latest_infer_node_rank_0.log
tail -f {output_dir}/slurm/latest_orchestrator.log
# Single-node
tail -F {output_dir}/logs/trainer/rank_0.log
# Multi-node RL
tail -F {output_dir}/slurm/latest_train_node_rank_0.log
tail -F {output_dir}/slurm/latest_infer_node_rank_0.log
tail -F {output_dir}/slurm/latest_orchestrator.log
```
For convenience, a tmux launcher is provided that sets up a session with all three log streams:
For convenience, a tmux launcher sets up a session with all log streams:
```bash
bash scripts/slurm_tmux.sh my-rl-job /shared/outputs/my-rl-job
```
This creates a tmux session `slurm-my-rl-job` with two windows:
- **Window 0 (Terminal)**: a plain shell for running commands
- **Window 1 (Logs)**: three vertical panes tailing trainer, orchestrator, and inference logs
The trainer and inference panes use glob patterns (`latest_train_node_rank_*.log`, `latest_infer_node_rank_*.log`) to follow logs from all node ranks. Re-running the same command attaches to the existing session.
+2 -1
View File
@@ -90,7 +90,8 @@ The correct alphabetical order by last name should be: Akman, Cakir, Durgun. The
We train with LoRA (rank 32, alpha 64) for 100 steps.
![RL](rl/wandb.png)
![RL](rl.png)
*Check out the logs on [W&B](https://wandb.ai/primeintellect/alphabet-sort-4b-lora/workspace?nw=nwuserandrewpi).*
```bash
# In the `Trainer` pane

Before

Width:  |  Height:  |  Size: 141 KiB

After

Width:  |  Height:  |  Size: 141 KiB

+6
View File
@@ -0,0 +1,6 @@
toml_files = ["rl.toml"]
output_dir = "outputs/alphabet-sort"
[slurm]
job_name = "alphabet-sort"
+25
View File
@@ -0,0 +1,25 @@
# Hendrycks Sanity
This example runs the Hendrycks Sanity Check experiment proposed in [Defeating the Training-Inference Mismatch](https://arxiv.org/abs/2510.26788). The sanity check tests whether an RL algorithm can reliably improve a model on problems it can *already partially solve*. The dataset is filtered from MATH to only include problems where the base model (`DeepSeek-R1-Distill-Qwen-1.5B`) solves 20-80% of the time across 40 rollouts. A reliable algorithm should push training accuracy on this "perfectible" subset above 95%.
Because our trainer is asynchronous, we perform only one gradient step per batch (the inference engine generates the next batch while the trainer processes the current one).
> This example runs on 8 GPUs (4 for inference, 4 for training).
## Training
Schedule training locally on a node with 8 GPUs
```bash
uv run rl @ examples/hendrycks_sanity/rl.toml \
--wandb.project your-project \
--wandb.name your-run
```
Or schedule the same training via SLURM
```bash
uv run rl @ examples/hendrycks_sanity/slurm_rl.toml \
--wandb.project your-project \
--wandb.name your-run
```
+38
View File
@@ -0,0 +1,38 @@
max_steps = 5000
seq_len = 8192
[wandb]
project = "hendrycks-sanity"
name = "hendrycks-sanity"
[deployment]
num_train_gpus = 4
num_infer_gpus = 4
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[orchestrator]
batch_size = 512
rollouts_per_example = 8
oversampling_factor = 2.0
[[orchestrator.env]]
id = "math-env" # included in lock file
args = { dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
name = "hendrycks-math"
[orchestrator.eval]
interval = 50
[[orchestrator.eval.env]]
id = "primeintellect/aime2024"
name = "aime2024"
rollouts_per_example = 32
[trainer.model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
seq_len = 16384
[inference.model]
max_model_len = 8192
+6
View File
@@ -0,0 +1,6 @@
toml_files = ["rl.toml"]
output_dir = "outputs/hendrycks-sanity"
[slurm]
job_name = "hendrycks-sanity"
@@ -1,12 +1,15 @@
job_name = "hendrycks-math-moe"
output_dir = "outputs/hendrycks-math-moe"
num_train_nodes = 1
num_infer_nodes = 1
output_dir = "outputs/rl-math-moe"
max_steps = 500
seq_len = 2048
[slurm]
job_name = "hendrycks-math-rl-moe"
[deployment]
type = "multi_node"
num_train_nodes = 1
num_infer_nodes = 1
[log]
level = "debug"
@@ -25,7 +28,6 @@ impl = "custom"
attn = "flash_attention_3"
optim_cpu_offload = true
[trainer.model.ac_offloading]
max_inflight_activations = 5
+35
View File
@@ -0,0 +1,35 @@
output_dir = "outputs/sft-moe-math"
max_steps = 500
[slurm]
job_name = "sft-moe-math"
[deployment]
type = "multi_node"
num_nodes = 2
[wandb]
project = "sft-moe-intellect"
name = "sft-moe-math"
[model]
name = "Qwen/Qwen3-30B-A3B-Thinking-2507"
impl = "custom"
attn = "flash_attention_3"
optim_cpu_offload = true
[model.compile]
[model.ac_offloading]
max_inflight_activations = 5
[model.ac]
freq = 1
[data]
type = "sft"
name = "PrimeIntellect/INTELLECT-3-SFT-10K"
subsets = ["default"]
splits = ["math"]
batch_size = 128
seq_len = 8192
+2 -2
View File
@@ -36,7 +36,7 @@ This is of course just a quick vibe check and no full-fledged evaluation, but we
We will fine-tune `PrimeIntellect/Qwen3-0.6B` ([HF](https://huggingface.co/PrimeIntellect/Qwen3-0.6B)), which is a clone of `Qwen/Qwen3-0.6B` ([HF](https://huggingface.co/Qwen/Qwen3-0.6B)) with a chat template suitable for multi-turn RL, on `willcb/R1-reverse-wikipedia-paragraphs-v1-1000` ([HF](https://huggingface.co/datasets/willcb/R1-reverse-wikipedia-paragraphs-v1-1000)) which contains 1K examples of reversals of small paragraphs.
![SFT](sft/wandb.png)
![SFT](sft.png)
*Check out the logs of the SFT run on [W&B](https://wandb.ai/primeintellect/examples?nw=s3p14m48jod).*
To train on a single GPU, run
@@ -72,7 +72,7 @@ We have uploaded the final model as [`PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT
For the RL we will only do 20 steps at 8x16 rollouts, for a total batch size of 128 and sequence length 128. Because of the small context, training should be extremely quick.
![RL](rl/wandb.png)
![RL](rl.png)
*Check out the logs of the RL run on [W&B](https://wandb.ai/primeintellect/examples?nw=yxjwjc556do).*
```bash

Before

Width:  |  Height:  |  Size: 129 KiB

After

Width:  |  Height:  |  Size: 129 KiB

-2
View File
@@ -1,2 +0,0 @@
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
-15
View File
@@ -1,15 +0,0 @@
batch_size = 128
rollouts_per_example = 16
seq_len = 2048
max_steps = 20
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[sampling]
max_tokens = 128
[[env]]
id = "reverse-text"
[ckpt]
-9
View File
@@ -1,9 +0,0 @@
max_steps = 20
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[optim]
lr = 3e-6
[ckpt]

Before

Width:  |  Height:  |  Size: 77 KiB

After

Width:  |  Height:  |  Size: 77 KiB

-14
View File
@@ -1,14 +0,0 @@
max_steps = 100
[model]
name = "PrimeIntellect/Qwen3-0.6B"
[data]
name = "willcb/R1-reverse-wikipedia-paragraphs-v1-1000"
seq_len = 4096
batch_size = 32
[optim]
lr = 2e-5
[ckpt] # Checkpoint at the end of training
+6
View File
@@ -0,0 +1,6 @@
toml_files = ["rl.toml"]
output_dir = "outputs/reverse-text-rl"
[slurm]
job_name = "reverse-text-rl"
+6
View File
@@ -0,0 +1,6 @@
toml_files = ["sft.toml"]
output_dir = "outputs/reverse-text-sft"
[slurm]
job_name = "reverse-text-sft"
-41
View File
@@ -1,41 +0,0 @@
job_name = "hendrycks-math"
output_dir = "outputs/hendrycks-math"
num_train_nodes = 1
num_infer_nodes = 1
max_steps = 500
seq_len = 2048
[log]
level = "debug"
[wandb]
project = "hendrycks-math-debug"
name = "hendrycks-math"
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 128
rollouts_per_example = 16
[orchestrator.sampling]
max_tokens = 2048
[[orchestrator.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
[orchestrator.buffer]
easy_threshold = 1.0
hard_threshold = 0.0
[trainer]
[inference.parallel]
tp = 1
dp = 8
+4 -3
View File
@@ -1,9 +1,10 @@
inference_gpu_ids = [0,1,2,3,4,5]
trainer_gpu_ids = [6,7]
max_steps = 200
seq_len = 4096
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
+6
View File
@@ -0,0 +1,6 @@
toml_files = ["rl.toml"]
output_dir = "outputs/wiki-search"
[slurm]
job_name = "wiki-search"
+4 -3
View File
@@ -1,9 +1,10 @@
inference_gpu_ids = [0,1,2,3,4,5]
trainer_gpu_ids = [6,7]
max_steps = 200
seq_len = 8192
[deployment]
num_train_gpus = 2
num_infer_gpus = 6
[wandb]
project = "wordle"
name = "wordle"
+6
View File
@@ -0,0 +1,6 @@
toml_files = ["rl.toml"]
output_dir = "outputs/wordle-rl"
[slurm]
job_name = "wordle-rl"
+6
View File
@@ -0,0 +1,6 @@
toml_files = ["sft.toml"]
output_dir = "outputs/wordle-sft"
[slurm]
job_name = "wordle-sft"
+5 -5
View File
@@ -12,7 +12,7 @@ dependencies = [
"loguru>=0.7.3",
"pyarrow>=21.0.0",
"pydantic>=1.10.13",
"pydantic-settings>=2.10.1",
"pydantic-settings>=2.12.0",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"numpy>=2.2.6",
@@ -34,16 +34,16 @@ dependencies = [
"verifiers",
"dion",
"reverse-text",
"tilelang>=0.1.8",
]
[project.scripts]
rl = "prime_rl.rl:main"
rl_slurm = "prime_rl.slurm.rl:main"
rl = "prime_rl.entrypoints.rl:main"
sft = "prime_rl.entrypoints.sft:main"
trainer = "prime_rl.trainer.rl.train:main"
orchestrator = "prime_rl.orchestrator.orchestrator:main"
inference = "prime_rl.inference.server:main"
env-server = "prime_rl.orchestrator.env_server.env_server:main"
sft = "prime_rl.trainer.sft.train:main"
[project.entry-points."vllm.general_plugins"]
prime_rl = "prime_rl.inference.patches:transformers_v5_compat"
@@ -83,7 +83,7 @@ override-dependencies = [
[tool.uv.sources]
torch = { index = "pytorch-cu128" }
math-env = { index = "primeintellect" }
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "0317556" }
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "3f555af" }
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "609e3d5" }
+3 -2
View File
@@ -87,6 +87,7 @@ ARCH_PRESETS = {
"prime_model_class": PrimeRLMiniMaxM2ForCausalLM,
"tokenizer_source": "MiniMaxAI/MiniMax-M2.1",
},
# glm_moe_dsa: HF implementation is incorrect, not supported here
}
@@ -159,7 +160,7 @@ def verify(arch: str, model_dir: Path) -> None:
input_ids = torch.randint(0, config.vocab_size, (1, 64))
position_ids = torch.arange(1, 65).unsqueeze(0)
hf_output = hf_model(input_ids, position_ids)
hf_output = hf_model(input_ids=input_ids, position_ids=position_ids)
prime_output = prime_model(input_ids, position_ids)
logits_diff = prime_output["logits"] - hf_output.logits
@@ -173,7 +174,7 @@ def verify(arch: str, model_dir: Path) -> None:
hf_roundtrip = _create_hf_model_from_config(preset, config)
hf_roundtrip.load_state_dict(roundtrip_state_dict)
hf_roundtrip_output = hf_roundtrip(input_ids, position_ids)
hf_roundtrip_output = hf_roundtrip(input_ids=input_ids, position_ids=position_ids)
roundtrip_diff = hf_roundtrip_output.logits - hf_output.logits
max_roundtrip_diff = roundtrip_diff.abs().max().item()
print(f" HF -> PrimeRL -> HF roundtrip max logits diff: {max_roundtrip_diff:.6f}")
+57 -2
View File
@@ -67,20 +67,75 @@ Use the string `"None"` in TOML to set a field to None:
max_model_len = "None"
```
## SLURM mode
Both `rl` and `sft` commands support SLURM execution via an optional `[slurm]` section. When present, the run is submitted as a SLURM job instead of running locally.
### RL SLURM
```toml
output_dir = "/shared/experiments/my-run"
[deployment]
type = "multi_node"
num_train_nodes = 2
num_infer_nodes = 1
gpus_per_node = 8
# nodes_per_fsdp_group = 1
[slurm]
job_name = "my-rl-job"
# dry_run = true # generate script without submitting
# template_path = "path/to/custom.sh.j2"
# project_dir = "/path/to/project"
```
When `[slurm]` is set for RL:
- `output_dir` must be explicitly set (the default `outputs` is rejected)
- Teacher inference is not supported in multi-node deployment
### SFT SLURM
```toml
output_dir = "/shared/experiments/my-sft-run"
[deployment]
type = "multi_node"
num_nodes = 2
gpus_per_node = 8
# nodes_per_fsdp_group = 1
[slurm]
job_name = "my-sft-job"
# dry_run = true
# template_path = "path/to/custom.sh.j2"
# project_dir = "/path/to/project"
```
SFT deployment follows the same pattern as RL:
- `[deployment]` configures node/GPU allocation (`single_node` default or `multi_node`)
- `[slurm]` configures SLURM submission (job name, partition, template)
- `output_dir` must be explicitly set when using SLURM
- Multi-node deployment requires `[slurm]` to be set
## Available commands
All accept `@ config.toml` and CLI overrides:
| Command | Config class | Description |
|---------|-------------|-------------|
| `uv run rl` | full RL pipeline | Orchestrator + inference + trainer |
| `uv run rl` | full RL pipeline | Orchestrator + inference + trainer (local or SLURM) |
| `uv run inference` | `InferenceConfig` | vLLM inference server |
| `uv run trainer` | trainer config | RL trainer |
| `uv run orchestrator` | orchestrator config | Rollout orchestrator |
| `uv run env-server` | env server config | Environment server |
| `uv run sft` | SFT config | Supervised fine-tuning |
| `uv run sft` | SFT config | Supervised fine-tuning (local or SLURM) |
## Key files
- `src/prime_rl/utils/pydantic_config.py` — `parse_argv`, `BaseSettings`, `@` syntax parsing
- `src/prime_rl/rl.py` — unified RL entrypoint (local + SLURM)
- `src/prime_rl/rl_config.py` — `RLConfig`, `SlurmConfig, DeploymentConfig`, `write_subconfigs`
- `src/prime_rl/trainer/sft/train.py` — unified SFT entrypoint (local + SLURM)
- `src/prime_rl/trainer/sft/config.py` — `SFTTrainerConfig`, `SFTSlurmConfig`
- `configs/` — all config files, organized by task
+453
View File
@@ -0,0 +1,453 @@
import json
import os
import subprocess
import sys
import time
import uuid
from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
import pynvml
import tomli_w
from prime_rl.rl_config import RLConfig
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import validate_output_dir
from prime_rl.utils.process import cleanup_processes, cleanup_threads, monitor_process
from prime_rl.utils.pydantic_config import parse_argv
from prime_rl.utils.utils import (
get_free_port,
get_log_dir,
)
def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
"""Write resolved subconfigs to disk as TOML files."""
output_dir.mkdir(parents=True, exist_ok=True)
with open(output_dir / "trainer.toml", "wb") as f:
tomli_w.dump(config.trainer.model_dump(exclude_none=True, mode="json"), f)
with open(output_dir / "orchestrator.toml", "wb") as f:
tomli_w.dump(config.orchestrator.model_dump(exclude_none=True, mode="json"), f)
if config.inference is not None:
with open(output_dir / "inference.toml", "wb") as f:
tomli_w.dump(config.inference.model_dump(exclude_none=True, mode="json"), f)
teacher_inference = getattr(config, "teacher_inference", None)
if teacher_inference is not None:
with open(output_dir / "teacher_inference.toml", "wb") as f:
tomli_w.dump(teacher_inference.model_dump(exclude_none=True, mode="json"), f)
def check_gpus_available(gpu_ids: list[int]) -> None:
"""Raise error if there are existing processes on the specified GPUs."""
pynvml.nvmlInit()
occupied = []
for gpu_id in gpu_ids:
handle = pynvml.nvmlDeviceGetHandleByIndex(gpu_id)
processes = pynvml.nvmlDeviceGetComputeRunningProcesses(handle)
if processes:
pids = [p.pid for p in processes]
occupied.append((gpu_id, pids))
if occupied:
msg = "Existing processes found on GPUs:\n"
for gpu_id, pids in occupied:
msg += f" GPU {gpu_id}: PIDs {pids}\n"
msg += "Kill these processes or use different GPUs."
raise RuntimeError(msg)
def rl_local(config: RLConfig):
# Setup logger
logger = setup_logger(
config.log.level or "info",
log_file=config.output_dir / "logs" / "rl.log" if config.log.file else None,
json_logging=config.log.json_logging,
)
# If dump_config is set, write resolved subconfigs and exit early
if config.dump_config is not None:
logger.warning(
"--dump-config is set. No RL training will be started. Only writing resolved subconfigs to disk."
)
write_subconfigs(config, config.dump_config)
logger.info(f"Dumping resolved subconfigs to {config.dump_config}")
logger.info(f" Wrote trainer config to {config.dump_config / 'trainer.toml'}")
logger.info(f" Wrote orchestrator config to {config.dump_config / 'orchestrator.toml'}")
if config.inference is not None:
logger.info(f" Wrote inference config to {config.dump_config / 'inference.toml'}")
if config.teacher_inference is not None:
logger.info(f" Wrote teacher inference config to {config.dump_config / 'teacher_inference.toml'}")
logger.success(f"Config dump complete. Files written to {config.dump_config}")
logger.warning("To start an RL run, remove --dump-config from your command.")
return
# Derive GPU IDs from deployment config
assert config.deployment.type == "single_node"
gpu_offset = 0
num_infer_gpus = config.deployment.num_infer_gpus if config.inference is not None else 0
infer_gpu_ids = list(range(gpu_offset, gpu_offset + num_infer_gpus))
gpu_offset += num_infer_gpus
trainer_gpu_ids = list(range(gpu_offset, gpu_offset + config.deployment.num_train_gpus))
gpu_offset += config.deployment.num_train_gpus
num_teacher_gpus = config.deployment.num_teacher_gpus or 0
teacher_gpu_ids = list(range(gpu_offset, gpu_offset + num_teacher_gpus)) if num_teacher_gpus > 0 else []
start_command = sys.argv
logger.info("Starting RL run")
logger.debug(f"RL start command: {' '.join(start_command)}")
# Check for existing processes on GPUs
all_gpu_ids = list(set(infer_gpu_ids + trainer_gpu_ids + teacher_gpu_ids))
check_gpus_available(all_gpu_ids)
# Validate client port matches inference server port
if config.inference is not None and not config.orchestrator.client.is_elastic:
from urllib.parse import urlparse
base_url = config.orchestrator.client.base_url[0]
parsed = urlparse(base_url)
client_port = parsed.port
expected_port = config.inference.server.port
if client_port != expected_port:
raise ValueError(
f"orchestrator.client.base_url port ({client_port}) does not match "
f"inference.server.port ({expected_port}). "
f"Update the base_url to use port {expected_port} to match the inference server."
)
# Prepare paths to communicate with the trainer
log_dir = get_log_dir(config.output_dir)
log_dir.mkdir(parents=True, exist_ok=True)
# Write all resolved subconfigs to disk
config_dir = Path(".pydantic_config") / uuid.uuid4().hex
write_subconfigs(config, config_dir)
# Start processes
processes: list[Popen] = []
monitor_threads: list[Thread] = []
error_queue: list[Exception] = []
stop_events: dict[str, Event] = {}
try:
# Optionally, start inference process
if config.inference:
inference_cmd = ["uv", "run", "inference", "@", (config_dir / "inference.toml").as_posix()]
logger.info(f"Starting inference process on GPU(s) {' '.join(map(str, infer_gpu_ids))}")
logger.debug(f"Inference start command: {' '.join(inference_cmd)}")
# If we don't log stdout, the server hangs
with open(log_dir / "inference.stdout", "w") as log_file:
inference_process = Popen(
inference_cmd,
env={
**os.environ,
"CUDA_VISIBLE_DEVICES": ",".join(map(str, infer_gpu_ids)),
},
stdout=log_file,
stderr=log_file,
)
processes.append(inference_process)
# Start monitoring thread
stop_event = Event()
stop_events["inference"] = stop_event
monitor_thread = Thread(
target=monitor_process,
args=(inference_process, stop_event, error_queue, "inference"),
daemon=True,
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
else:
logger.warning(
"No inference config specified, skipping starting inference server. Make sure your inference server is running."
)
# Optionally, start teacher inference process
if config.teacher_inference:
if not teacher_gpu_ids:
raise ValueError(
"teacher_inference is configured but deployment.num_teacher_gpus is not set. "
"Either set deployment.num_teacher_gpus to start a teacher inference server, "
"or omit teacher_inference and configure orchestrator.teacher_model to use an existing server."
)
teacher_inference_cmd = ["uv", "run", "inference", "@", (config_dir / "teacher_inference.toml").as_posix()]
logger.info(f"Starting teacher inference process on GPU(s) {' '.join(map(str, 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, 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.type == "default" and 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_cmd = [
"uv",
"run",
"orchestrator",
"@",
(config_dir / "orchestrator.toml").as_posix(),
]
logger.info("Starting orchestrator process")
logger.debug(f"Orchestrator start command: {' '.join(orchestrator_cmd)}")
with open(log_dir / "orchestrator.stdout", "w") as log_file:
orchestrator_process = Popen(
orchestrator_cmd,
stdout=log_file,
stderr=log_file,
env={
**os.environ,
"LOGURU_FORCE_COLORS": "1",
"WANDB_PROGRAM": "uv run rl",
"WANDB_ARGS": json.dumps(start_command),
},
)
processes.append(orchestrator_process)
# Start monitoring thread
stop_event = Event()
stop_events["orchestrator"] = stop_event
monitor_thread = Thread(
target=monitor_process,
args=(orchestrator_process, stop_event, error_queue, "orchestrator"),
daemon=True,
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
# Start training process
trainer_cmd = [
"uv",
"run",
"env",
"PYTHONUNBUFFERED=1",
"PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True",
"torchrun",
f"--rdzv-endpoint=localhost:{get_free_port()}",
f"--rdzv-id={uuid.uuid4().hex}",
# Pipe all logs to file, and only master rank logs to stdout
f"--log-dir={config.output_dir / 'torchrun'}",
"--local-ranks-filter=0",
"--redirect=3",
"--tee=3",
f"--nproc-per-node={len(trainer_gpu_ids)}",
"-m",
"prime_rl.trainer.rl.train",
"@",
(config_dir / "trainer.toml").as_posix(),
]
logger.info(f"Starting trainer process on GPU(s) {' '.join(map(str, trainer_gpu_ids))}")
logger.debug(f"Training start command: {' '.join(trainer_cmd)}")
with open(log_dir / "trainer.stdout", "w") as log_file:
trainer_process = Popen(
trainer_cmd,
env={
**os.environ,
"CUDA_VISIBLE_DEVICES": ",".join(map(str, trainer_gpu_ids)),
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
"LOGURU_FORCE_COLORS": "1",
"WANDB_PROGRAM": "uv run rl",
"WANDB_ARGS": json.dumps(start_command),
},
stdout=log_file,
stderr=log_file,
)
processes.append(trainer_process)
# Start monitoring thread
stop_event = Event()
stop_events["trainer"] = stop_event
monitor_thread = Thread(
target=monitor_process, args=(trainer_process, stop_event, error_queue, "trainer"), daemon=True
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
# Monitor all processes for failures
logger.success("Startup complete. Showing trainer logs...")
tail_process = Popen(["tail", "-F", log_dir / "trainer.stdout"])
processes.append(tail_process)
# Check for errors from monitor threads
while not (stop_events["orchestrator"].is_set() and stop_events["trainer"].is_set()):
if error_queue:
error = error_queue[0]
logger.error(f"Error: {error}")
logger.error("Terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
# 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
cleanup_threads(monitor_threads)
cleanup_processes(processes)
except KeyboardInterrupt:
logger.warning("Received interrupt signal, terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
except Exception as e:
logger.error(f"Error occurred: {e}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
raise
def render_slurm_script(config: RLConfig, config_dir: Path) -> tuple[str, str]:
"""Render the SLURM script template. Returns (script, log_message)."""
from jinja2 import Environment, FileSystemLoader
assert config.slurm is not None
assert config.slurm.template_path is not None
env = Environment(loader=FileSystemLoader(config.slurm.template_path.parent), keep_trailing_newline=True)
template = env.get_template(config.slurm.template_path.name)
log_dir = config.output_dir / "logs"
if config.deployment.type == "single_node":
import tomli_w
config_path = config_dir / "rl.toml"
config_dict = config.model_dump(exclude={"slurm"}, exclude_none=True, mode="json")
config_dir.mkdir(parents=True, exist_ok=True)
with open(config_path, "wb") as f:
tomli_w.dump(config_dict, f)
script = template.render(
config_path=config_path,
job_name=config.slurm.job_name,
project_dir=config.slurm.project_dir,
partition=config.slurm.partition,
output_dir=config.output_dir,
gpus_per_node=config.deployment.gpus_per_node,
)
log_message = (
f"Logs:\n"
f" Trainer: tail -F {log_dir}/trainer.stdout\n"
f" Orchestrator: tail -F {log_dir}/orchestrator.stdout\n"
f" Inference: tail -F {log_dir}/inference.stdout"
)
else:
script = template.render(
config_dir=config_dir,
job_name=config.slurm.job_name,
project_dir=config.slurm.project_dir,
partition=config.slurm.partition,
output_dir=config.output_dir,
orchestrator_output_dir=config.orchestrator.output_dir,
num_train_nodes=config.deployment.num_train_nodes,
num_infer_nodes=config.deployment.num_infer_nodes,
num_teacher_nodes=config.deployment.num_teacher_nodes,
gpus_per_node=config.deployment.gpus_per_node,
)
slurm_log_dir = config.output_dir / "slurm"
log_message = (
f"Logs:\n"
f" Trainer: tail -F {slurm_log_dir}/latest_train_node_rank_0.log\n"
f" Orchestrator: tail -F {slurm_log_dir}/latest_orchestrator.log\n"
f" Inference: tail -F {slurm_log_dir}/latest_infer_node_rank_0.log"
)
return script, log_message
def rl_slurm(config: RLConfig):
assert config.slurm is not None
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
config_dir = config.output_dir / "configs"
if config.deployment.type == "multi_node":
write_subconfigs(config, config_dir)
logger.info(f"Wrote subconfigs to {config_dir}")
script, log_message = render_slurm_script(config, config_dir)
script_path = config.output_dir / "rl.sbatch"
script_path.parent.mkdir(parents=True, exist_ok=True)
script_path.write_text(script)
logger.info(f"Wrote SLURM script to {script_path}")
if config.slurm.dry_run:
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
return
logger.info(f"Submitting: sbatch {script_path}")
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
if result.returncode != 0:
logger.error(f"sbatch failed: {result.stderr.strip()}")
sys.exit(1)
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
def rl(config: RLConfig):
resuming = config.ckpt is not None and config.ckpt.resume_step is not None
clean = config.clean_output_dir and not os.environ.get("NEVER_CLEAN_OUTPUT_DIR")
validate_output_dir(config.output_dir, resuming=resuming, clean=clean)
config.output_dir.mkdir(parents=True, exist_ok=True)
if config.slurm is not None:
rl_slurm(config)
else:
rl_local(config)
def main():
rl(parse_argv(RLConfig))
if __name__ == "__main__":
main()
+208
View File
@@ -0,0 +1,208 @@
import os
import subprocess
import sys
import uuid
from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
import tomli_w
from prime_rl.trainer.sft.config import SFTTrainerConfig
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import validate_output_dir
from prime_rl.utils.process import cleanup_processes, cleanup_threads, monitor_process
from prime_rl.utils.pydantic_config import parse_argv
from prime_rl.utils.utils import get_free_port
def write_trainer_config(config: SFTTrainerConfig, output_dir: Path) -> None:
"""Write resolved trainer config to disk, excluding launcher-only fields."""
output_dir.mkdir(parents=True, exist_ok=True)
trainer_data = config.model_dump(exclude={"deployment"}, exclude_none=True, mode="json")
with open(output_dir / "trainer.toml", "wb") as f:
tomli_w.dump(trainer_data, f)
def render_slurm_script(config: SFTTrainerConfig, config_dir: Path) -> tuple[str, str]:
"""Render the SLURM script template. Returns (script, log_message)."""
from jinja2 import Environment, FileSystemLoader
assert config.slurm is not None
assert config.slurm.template_path is not None
env = Environment(loader=FileSystemLoader(config.slurm.template_path.parent), keep_trailing_newline=True)
template = env.get_template(config.slurm.template_path.name)
if config.deployment.type == "single_node":
config_path = config_dir / "sft.toml"
config_dir.mkdir(parents=True, exist_ok=True)
with open(config_path, "wb") as f:
tomli_w.dump(config.model_dump(exclude={"slurm"}, exclude_none=True, mode="json"), f)
script = template.render(
config_path=config_path,
output_dir=config.output_dir,
job_name=config.slurm.job_name,
project_dir=config.slurm.project_dir,
gpus_per_node=config.deployment.gpus_per_node,
partition=config.slurm.partition,
)
log_dir = config.output_dir / "logs"
log_message = f"Logs:\n Trainer: tail -F {log_dir}/trainer/rank_0.log"
else:
script = template.render(
config_dir=config_dir,
output_dir=config.output_dir,
job_name=config.slurm.job_name,
project_dir=config.slurm.project_dir,
num_nodes=config.deployment.num_nodes,
gpus_per_node=config.deployment.gpus_per_node,
partition=config.slurm.partition,
)
log_message = f"Logs:\n Trainer: tail -F {config.output_dir}/slurm/latest_train_node_rank_0.log"
return script, log_message
def sft_slurm(config: SFTTrainerConfig):
"""Run SFT training via SLURM."""
assert config.slurm is not None
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
config_dir = config.output_dir / "configs"
if config.deployment.type == "multi_node":
write_trainer_config(config, config_dir)
logger.info(f"Wrote trainer config to {config_dir}")
script, log_message = render_slurm_script(config, config_dir)
script_path = config.output_dir / "sft.sbatch"
script_path.parent.mkdir(parents=True, exist_ok=True)
script_path.write_text(script)
logger.info(f"Wrote SLURM script to {script_path}")
if config.slurm.dry_run:
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
return
logger.info(f"Submitting: sbatch {script_path}")
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
if result.returncode != 0:
logger.error(f"sbatch failed: {result.stderr.strip()}")
sys.exit(1)
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
def sft_local(config: SFTTrainerConfig):
"""Run SFT training locally with process monitoring and cleanup."""
assert config.deployment.type == "single_node"
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
config_dir = Path(".pydantic_config") / uuid.uuid4().hex
config_dir.mkdir(parents=True, exist_ok=True)
config_path = config_dir / "trainer.toml"
with open(config_path, "wb") as f:
tomli_w.dump(config.model_dump(exclude={"deployment"}, exclude_none=True, mode="json"), f)
log_dir = config.output_dir / "logs"
log_dir.mkdir(parents=True, exist_ok=True)
trainer_cmd = [
"uv",
"run",
"env",
"PYTHONUNBUFFERED=1",
"PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True",
"torchrun",
f"--rdzv-endpoint=localhost:{get_free_port()}",
f"--rdzv-id={uuid.uuid4().hex}",
f"--log-dir={config.output_dir / 'torchrun'}",
"--local-ranks-filter=0",
"--redirect=3",
"--tee=3",
f"--nproc-per-node={config.deployment.num_gpus}",
"-m",
"prime_rl.trainer.sft.train",
"@",
config_path.as_posix(),
]
logger.info(f"Starting SFT trainer with {config.deployment.num_gpus} GPU(s)")
logger.debug(f"Trainer command: {' '.join(trainer_cmd)}")
processes: list[Popen] = []
monitor_threads: list[Thread] = []
error_queue: list[Exception] = []
try:
with open(log_dir / "trainer.stdout", "w") as log_file:
trainer_process = Popen(
trainer_cmd,
env={
**os.environ,
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
},
stdout=log_file,
stderr=log_file,
)
processes.append(trainer_process)
stop_event = Event()
monitor_thread = Thread(
target=monitor_process,
args=(trainer_process, stop_event, error_queue, "trainer"),
daemon=True,
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
logger.success("Startup complete. Showing trainer logs...")
tail_process = Popen(["tail", "-F", str(log_dir / "trainer.stdout")])
processes.append(tail_process)
stop_event.wait()
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("SFT training finished!")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
except KeyboardInterrupt:
logger.warning("Received interrupt signal, terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
except Exception as e:
logger.error(f"Error occurred: {e}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
raise
def sft(config: SFTTrainerConfig):
resuming = config.ckpt is not None and config.ckpt.resume_step is not None
clean = config.clean_output_dir and not os.environ.get("NEVER_CLEAN_OUTPUT_DIR")
validate_output_dir(config.output_dir, resuming=resuming, clean=clean)
config.output_dir.mkdir(parents=True, exist_ok=True)
if config.slurm is not None:
sft_slurm(config)
else:
sft_local(config)
def main():
sft(parse_argv(SFTTrainerConfig))
if __name__ == "__main__":
main()
+131 -5
View File
@@ -6,6 +6,84 @@ from pydantic import Field, model_validator
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings, get_all_fields
from prime_rl.utils.utils import rgetattr, rsetattr
MODEL_TOOL_CALL_PARSER: dict[str, str] = {
# GLM-4.5
"zai-org/GLM-4.5": "glm45",
"zai-org/GLM-4.5-FP8": "glm45",
"zai-org/GLM-4.5-Base": "glm45",
"zai-org/GLM-4.5-Air": "glm45",
"zai-org/GLM-4.5-Air-FP8": "glm45",
"zai-org/GLM-4.5-Air-Base": "glm45",
"zai-org/GLM-4.5V": "glm45",
"zai-org/GLM-4.5V-FP8": "glm45",
# GLM-4.7
"zai-org/GLM-4.7": "glm47",
"zai-org/GLM-4.7-FP8": "glm47",
"zai-org/GLM-4.7-Flash": "glm47",
# MiniMax M2
"MiniMaxAI/MiniMax-M2": "minimax_m2",
"MiniMaxAI/MiniMax-M2.1": "minimax_m2",
"MiniMaxAI/MiniMax-M2.5": "minimax_m2",
# INTELLECT-3
"PrimeIntellect/INTELLECT-3": "hermes",
"PrimeIntellect/INTELLECT-3-FP8": "hermes",
"PrimeIntellect/INTELLECT-3.1": "hermes",
# Qwen3 dense
"Qwen/Qwen3-0.6B": "hermes",
"Qwen/Qwen3-0.6B-Base": "hermes",
"Qwen/Qwen3-0.6B-FP8": "hermes",
"Qwen/Qwen3-1.7B": "hermes",
"Qwen/Qwen3-1.7B-Base": "hermes",
"Qwen/Qwen3-1.7B-FP8": "hermes",
"Qwen/Qwen3-4B": "hermes",
"Qwen/Qwen3-4B-Base": "hermes",
"Qwen/Qwen3-4B-FP8": "hermes",
"Qwen/Qwen3-8B": "hermes",
"Qwen/Qwen3-8B-Base": "hermes",
"Qwen/Qwen3-8B-FP8": "hermes",
"Qwen/Qwen3-14B": "hermes",
"Qwen/Qwen3-14B-Base": "hermes",
"Qwen/Qwen3-14B-FP8": "hermes",
"Qwen/Qwen3-32B": "hermes",
"Qwen/Qwen3-32B-FP8": "hermes",
# Qwen3 MoE
"Qwen/Qwen3-30B-A3B": "hermes",
"Qwen/Qwen3-30B-A3B-Base": "hermes",
"Qwen/Qwen3-30B-A3B-FP8": "hermes",
"Qwen/Qwen3-235B-A22B": "hermes",
"Qwen/Qwen3-235B-A22B-FP8": "hermes",
# Qwen3 2507
"Qwen/Qwen3-4B-Instruct-2507": "hermes",
"Qwen/Qwen3-4B-Thinking-2507": "hermes",
"Qwen/Qwen3-4B-Instruct-2507-FP8": "hermes",
"Qwen/Qwen3-4B-Thinking-2507-FP8": "hermes",
"Qwen/Qwen3-30B-A3B-Instruct-2507": "hermes",
"Qwen/Qwen3-30B-A3B-Thinking-2507": "hermes",
"Qwen/Qwen3-30B-A3B-Instruct-2507-FP8": "hermes",
"Qwen/Qwen3-30B-A3B-Thinking-2507-FP8": "hermes",
"Qwen/Qwen3-235B-A22B-Instruct-2507": "hermes",
"Qwen/Qwen3-235B-A22B-Thinking-2507": "hermes",
"Qwen/Qwen3-235B-A22B-Instruct-2507-FP8": "hermes",
"Qwen/Qwen3-235B-A22B-Thinking-2507-FP8": "hermes",
# Qwen3-Next
"Qwen/Qwen3-Next-80B-A3B-Instruct": "hermes",
"Qwen/Qwen3-Next-80B-A3B-Thinking": "hermes",
"Qwen/Qwen3-Next-80B-A3B-Instruct-FP8": "hermes",
"Qwen/Qwen3-Next-80B-A3B-Thinking-FP8": "hermes",
# Qwen3-Coder
"Qwen/Qwen3-Coder-480B-A35B-Instruct": "hermes",
"Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8": "hermes",
"Qwen/Qwen3-Coder-30B-A3B-Instruct": "hermes",
"Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8": "hermes",
# Qwen3-Coder-Next
"Qwen/Qwen3-Coder-Next": "hermes",
"Qwen/Qwen3-Coder-Next-Base": "hermes",
"Qwen/Qwen3-Coder-Next-FP8": "hermes",
# Qwen3.5
"Qwen/Qwen3.5-397B-A17B": "hermes",
"Qwen/Qwen3.5-397B-A17B-FP8": "hermes",
}
# TODO: Set thinking/ solution budget
@@ -79,16 +157,18 @@ class ModelConfig(BaseConfig):
enable_auto_tool_choice: Annotated[
bool,
Field(
description="Whether to enable auto tool choice. Passed to vLLM as `--enable-auto-tool-choice`",
description="Whether to enable auto tool choice. Passed to vLLM as `--enable-auto-tool-choice`. "
"Automatically set to True when tool_call_parser is configured.",
),
] = False
tool_call_parser: Annotated[
str,
str | None,
Field(
description="The tool call parser to use. Passed to vLLM as `--tool-call-parser`",
description="The tool call parser to use. Passed to vLLM as `--tool-call-parser`. "
"If not set, automatically inferred from the model name.",
),
] = "hermes"
] = None
reasoning_parser: Annotated[
str | None,
@@ -104,6 +184,18 @@ class ModelConfig(BaseConfig):
),
] = None
@model_validator(mode="after")
def resolve_tool_call_parser(self):
if self.tool_call_parser is None:
parser = MODEL_TOOL_CALL_PARSER.get(self.name)
if parser is not None:
self.tool_call_parser = parser
if self.tool_call_parser is not None:
self.enable_auto_tool_choice = True
return self
class WeightBroadcastConfig(BaseSettings):
"""Configures weight broadcast settings."""
@@ -117,6 +209,16 @@ class WeightBroadcastConfig(BaseSettings):
# TODO: on newer vLLM, can import via `get_args(vllm.config.lora.MaxLoRARanks)`
VALID_VLLM_LORA_RANKS = (8, 16, 32, 64, 128, 256, 320, 512)
# vLLM all2all backend options for expert-parallel deployments.
All2AllBackend = Literal[
"allgather_reducescatter",
"deepep_high_throughput",
"deepep_low_latency",
"flashinfer_all2allv",
"naive",
"pplx",
]
class InferenceConfig(BaseSettings):
"""Configures inference."""
@@ -125,7 +227,7 @@ class InferenceConfig(BaseSettings):
server: ServerConfig = ServerConfig()
# The model configuration
model: ModelConfig = ModelConfig()
model: ModelConfig = Field(default_factory=ModelConfig)
# The parallel configuration
parallel: ParallelConfig = ParallelConfig()
@@ -190,6 +292,27 @@ class InferenceConfig(BaseSettings):
),
] = 0
enable_expert_parallel: Annotated[
bool,
Field(
description="Enable expert parallelism for MoE models. Passed to vLLM as `--enable-expert-parallel`.",
),
] = False
all2all_backend: Annotated[
All2AllBackend,
Field(
description="All-to-all backend for expert parallel communication. Passed to vLLM as `--all2all-backend`.",
),
] = "allgather_reducescatter"
enable_eplb: Annotated[
bool,
Field(
description="Enable expert parallel load balancer (EPLB). Passed to vLLM as `--enable-eplb`.",
),
] = False
weight_broadcast: Annotated[WeightBroadcastConfig, Field(description="The weight broadcast config.")] = (
WeightBroadcastConfig()
)
@@ -250,6 +373,9 @@ class InferenceConfig(BaseSettings):
"max_lora_rank": "max_lora_rank",
"gpu_memory_utilization": "gpu_memory_utilization",
"api_server_count": "api_server_count",
"enable_expert_parallel": "enable_expert_parallel",
"all2all_backend": "all2all_backend",
"enable_eplb": "enable_eplb",
}
for key in get_all_fields(self):
+6
View File
@@ -22,6 +22,9 @@ from vllm.logger import init_logger
from vllm.utils.argparse_utils import FlexibleArgumentParser
from prime_rl.inference.config import InferenceConfig
from prime_rl.utils.logger import get_logger
logger = get_logger()
from prime_rl.inference.patches import (
monkey_patch_hermes_tool_parser_thread_safety,
monkey_patch_load_lora_adapter,
@@ -230,6 +233,9 @@ def server(config: InferenceConfig, vllm_args: list[str]):
from vllm.entrypoints.cli.serve import run_headless, run_multi_api_server
from vllm.entrypoints.openai.api_server import run_server
if config.model.tool_call_parser is not None:
logger.info(f"Using tool_call_parser='{config.model.tool_call_parser}' for model '{config.model.name}'")
parser = FlexibleArgumentParser(description="vLLM OpenAI-Compatible RESTful API server.")
parser = make_arg_parser(parser)
args = parser.parse_args(args=vllm_args, namespace=config.to_vllm())
+4 -4
View File
@@ -5,7 +5,7 @@ import torch
from jaxtyping import Float, Int
from torch import Tensor
from prime_rl.orchestrator.config import AdvantageConfigType, CustomAdvantageConfig
from prime_rl.orchestrator.config import AdvantageConfig, CustomAdvantageConfig
from prime_rl.utils.utils import import_object
@@ -45,7 +45,7 @@ def default_advantage_fn(inputs: AdvantageInputs, length_weighted_mean: bool = F
return AdvantageOutputs(advantages=inputs.rewards - baseline)
def setup_advantage_fn(config: AdvantageConfigType) -> AdvantageFn:
def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
"""Setup advantage function from config."""
if isinstance(config, CustomAdvantageConfig):
custom_fn = import_object(config.import_path)
@@ -66,7 +66,7 @@ def compute_advantages(
rewards: list[float],
completion_lengths: list[int],
samples_per_problem: int,
advantage_config: AdvantageConfigType | None,
advantage_config: AdvantageConfig | None,
) -> list[float]:
"""
Computes advantages from a flattened list of rewards, grouped by problem.
@@ -75,7 +75,7 @@ def compute_advantages(
rewards: Flattened list of rewards where first `samples_per_problem` rewards are for the first problem
completion_lengths: List of completion lengths for each reward
samples_per_problem: Number of samples (and thus, rewards) per problem
advantage_config: Configuration for advantage computation (AdvantageConfig or CustomAdvantageConfig)
advantage_config: Configuration for advantage computation (DefaultAdvantageConfig or CustomAdvantageConfig)
"""
if not advantage_config:
return rewards
+23 -20
View File
@@ -1,9 +1,9 @@
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
from pydantic import AliasChoices, BaseModel, ConfigDict, Discriminator, Field, Tag, model_validator
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, model_validator
from prime_rl.transport.config import FileSystemTransportConfig, TransportConfigType
from prime_rl.transport.config import FileSystemTransportConfig, TransportConfig
from prime_rl.utils.config import (
ClientConfig,
HeartbeatConfig,
@@ -548,9 +548,11 @@ class BufferConfig(BaseConfig):
return self
class AdvantageConfig(BaseConfig):
class DefaultAdvantageConfig(BaseModel):
"""Config for the default advantage."""
model_config = ConfigDict(extra="forbid")
type: Literal["default"] = "default"
length_weighted_mean: bool = False
@@ -567,15 +569,9 @@ class CustomAdvantageConfig(BaseModel):
]
def _advantage_config_discriminator(v: Any) -> str:
if isinstance(v, dict):
return v.get("type", "default")
return getattr(v, "type", "default")
AdvantageConfigType: TypeAlias = Annotated[
Annotated[AdvantageConfig, Tag("default")] | Annotated[CustomAdvantageConfig, Tag("custom")],
Discriminator(_advantage_config_discriminator),
AdvantageConfig: TypeAlias = Annotated[
DefaultAdvantageConfig | CustomAdvantageConfig,
Field(discriminator="type"),
]
@@ -629,7 +625,7 @@ class RepetitionFilterConfig(BaseModel):
] = 0.99
FilterConfigType: TypeAlias = Annotated[
FilterConfig: TypeAlias = Annotated[
GibberishFilterConfig | RepetitionFilterConfig,
Field(discriminator="type"),
]
@@ -651,7 +647,9 @@ class NCCLWeightBroadcastConfig(BaseModel):
timeout: Annotated[int, Field(description="The timeout in seconds to use for the NCCL broadcast.")] = 1200
WeightBroadcastConfigType: TypeAlias = FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig
WeightBroadcastConfig: TypeAlias = Annotated[
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig, Field(discriminator="type")
]
class TeacherModelConfig(BaseConfig):
@@ -703,10 +701,10 @@ class OrchestratorConfig(BaseSettings):
buffer: BufferConfig = BufferConfig()
# The advantage configuration
advantage: AdvantageConfigType | None = AdvantageConfig()
advantage: AdvantageConfig | None = DefaultAdvantageConfig()
# Rollout filters (monitor by default, enforce optionally)
filters: list[FilterConfigType] = [GibberishFilterConfig(), RepetitionFilterConfig()]
filters: list[FilterConfig] = [GibberishFilterConfig(), RepetitionFilterConfig()]
# The logging configuration
log: LogConfig = LogConfig()
@@ -723,11 +721,9 @@ class OrchestratorConfig(BaseSettings):
# The validation configuration
val: ValConfig | None = None
weight_broadcast: Annotated[WeightBroadcastConfigType, Field(discriminator="type")] = (
FileSystemWeightBroadcastConfig()
)
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
rollout_transport: Annotated[TransportConfigType, Field(discriminator="type")] = FileSystemTransportConfig()
rollout_transport: TransportConfig = FileSystemTransportConfig()
output_dir: Annotated[
Path,
@@ -825,6 +821,13 @@ class OrchestratorConfig(BaseSettings):
HeartbeatConfig | None, Field(description="The heartbeat config for monitoring training progress.")
] = None
use_token_client: Annotated[
bool,
Field(
description="Whether to use the token-in-token-out (TITO) client for training across all environments. WARNING: Only use this if your environment has a linear history and the chat template has the extension property (i.e. no tokens are ever removed or inserted by the chat template)"
),
] = True
@model_validator(mode="after")
def validate_unique_filter_types(self):
types = [f.type for f in self.filters]
+3 -3
View File
@@ -14,7 +14,7 @@ from typing import Protocol
import verifiers as vf
from loguru import logger
from prime_rl.orchestrator.config import FilterConfigType
from prime_rl.orchestrator.config import FilterConfig
@dataclass
@@ -95,7 +95,7 @@ class RepetitionFilter:
return FilterResult(detected=False)
def setup_filter(config: FilterConfigType, vocab_size: int) -> RolloutFilter:
def setup_filter(config: FilterConfig, vocab_size: int) -> RolloutFilter:
"""Create a RolloutFilter from a filter config."""
if config.type == "gibberish":
return GibberishFilter(
@@ -114,7 +114,7 @@ def setup_filter(config: FilterConfigType, vocab_size: int) -> RolloutFilter:
raise ValueError(f"Unknown filter type: {config.type}")
def setup_filters(configs: list[FilterConfigType], vocab_size: int) -> list[RolloutFilter]:
def setup_filters(configs: list[FilterConfig], vocab_size: int) -> list[RolloutFilter]:
"""Create RolloutFilters from a list of filter configs."""
return [setup_filter(config, vocab_size) for config in configs]
+33 -8
View File
@@ -103,7 +103,13 @@ async def orchestrate(config: OrchestratorConfig):
install_env(env_id)
# Setup inference pool (handles both static and elastic modes)
inference_pool = await setup_inference_pool(config.client, model_name=config.model.name)
client_type = "openai_chat_completions_token" if config.use_token_client else "openai_chat_completions"
if config.use_token_client:
logger.warning(
"Token-in-token-out (TITO) client is enabled. Only use this if your environment has a linear "
"history and the chat template has the extension property."
)
inference_pool = await setup_inference_pool(config.client, model_name=config.model.name, client_type=client_type)
# Setup teacher inference pool if configured
if config.teacher_model:
@@ -491,12 +497,14 @@ async def orchestrate(config: OrchestratorConfig):
train_examples: list[TrainingSample] = []
rollout_prefill_lens: list[int] = []
rollout_decode_lens: list[int] = []
rollout_samples_per_rollout: list[int] = []
num_prefill_tokens = 0
num_decode_tokens = 0
for rollout, advantage, samples in zip(train_rollouts, advantages, results):
rollout_prefill_tokens = 0
rollout_decode_tokens = 0
if samples is not None:
rollout_samples_per_rollout.append(len(samples))
for sample in samples:
sample.advantage = advantage
sample.reward = rollout["reward"]
@@ -505,6 +513,8 @@ async def orchestrate(config: OrchestratorConfig):
rollout_decode_tokens += sample_decode_tokens
rollout_prefill_tokens += sample_prefill_tokens
train_examples.append(sample)
else:
rollout_samples_per_rollout.append(0)
rollout_prefill_lens.append(rollout_prefill_tokens)
rollout_decode_lens.append(rollout_decode_tokens)
num_prefill_tokens += rollout_prefill_tokens
@@ -572,6 +582,7 @@ async def orchestrate(config: OrchestratorConfig):
"seq_len": [get_seq_len(rollout) for rollout in train_rollouts],
"prefill_len": rollout_prefill_lens,
"decode_len": rollout_decode_lens,
"samples_per_rollout": rollout_samples_per_rollout,
"num_turns": [len(rollout["trajectory"]) for rollout in train_rollouts],
"generation_ms": [rollout["timing"]["generation_ms"] for rollout in train_rollouts],
"scoring_ms": [rollout["timing"]["scoring_ms"] for rollout in train_rollouts],
@@ -601,12 +612,10 @@ async def orchestrate(config: OrchestratorConfig):
throughput = num_tokens / generate_completions_time
# Compute solve all and none tensors
solve_all = (
results_df.groupby("example_id")
.apply(lambda x: x.reward.sum() == config.rollouts_per_example, include_groups=False)
.mean()
)
solve_none = results_df.groupby("example_id").apply(lambda x: x.reward.sum() == 0, include_groups=False).mean()
problem_indices = results_df.index // config.rollouts_per_example
reward_sum_per_problem = results_df.groupby(problem_indices).reward.sum()
solve_all = (reward_sum_per_problem == config.rollouts_per_example).mean()
solve_none = (reward_sum_per_problem == 0).mean()
effective_batch_size = 1 - solve_none - solve_all
step_time = time.perf_counter() - step_start_time
@@ -634,6 +643,10 @@ async def orchestrate(config: OrchestratorConfig):
"is_truncated/mean": results_df.groupby("example_id").is_truncated.mean().mean(),
"is_truncated/max": results_df.groupby("example_id").is_truncated.mean().max(),
"is_truncated/min": results_df.groupby("example_id").is_truncated.mean().min(),
# Seqs per rollout metrics
"samples_per_rollout/mean": results_df.groupby("example_id").samples_per_rollout.mean().mean(),
"samples_per_rollout/max": results_df.groupby("example_id").samples_per_rollout.mean().max(),
"samples_per_rollout/min": results_df.groupby("example_id").samples_per_rollout.mean().min(),
# Turn metrics
"num_turns/mean": results_df.groupby("example_id").num_turns.mean().mean(),
"num_turns/max": results_df.groupby("example_id").num_turns.mean().max(),
@@ -649,6 +662,10 @@ async def orchestrate(config: OrchestratorConfig):
"perf/throughput": throughput,
# Train reward
"reward/mean": results_df.reward.mean(),
"reward/std": results_df.reward.std(),
"reward/min": results_df.reward.min(),
"reward/max": results_df.reward.max(),
"reward/median": results_df.reward.median(),
"sampling/temperature": temperature,
# Batch metrics
"batch/solve_none": solve_none,
@@ -693,7 +710,15 @@ async def orchestrate(config: OrchestratorConfig):
# Optionally, add val metrics
if val_results_df is not None:
to_log.update({"val_reward/mean": val_results_df.reward.mean()})
to_log.update(
{
"val_reward/mean": val_results_df.reward.mean(),
"val_reward/std": val_results_df.reward.std(),
"val_reward/min": val_results_df.reward.min(),
"val_reward/max": val_results_df.reward.max(),
"val_reward/median": val_results_df.reward.median(),
}
)
if val_results_df.task.nunique() > 1:
per_env_reward = val_results_df.groupby("task").reward.mean().to_dict()
-666
View File
@@ -1,666 +0,0 @@
import json
import os
import shutil
import subprocess
import sys
import time
import uuid
import warnings
from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
from typing import Annotated, Literal
import pynvml
import tomli_w
from pydantic import Field, model_validator
from prime_rl.inference.config import InferenceConfig
from prime_rl.rl_config import BaseRLConfig
from prime_rl.trainer.rl.config import FakeDataLoaderConfig
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pydantic_config import BaseSettings, parse_argv
from prime_rl.utils.utils import (
get_broadcast_dir,
get_free_port,
get_log_dir,
get_rollout_dir,
)
class SharedLogConfig(BaseSettings):
"""Configures shared logging."""
level: Annotated[str | None, Field(description="The log level to use.")] = "info"
file: Annotated[bool | None, Field(description="Whether to log to a file.")] = True
json_logging: Annotated[
bool,
Field(description="Emit JSON logs (newline-delimited) for log aggregation (Loki, Grafana, etc.)."),
] = False
class SharedWandbConfig(BaseSettings):
"""Configures shared W&B configs."""
project: Annotated[str | None, Field(description="The W&B project to use.")] = "prime-rl"
name: Annotated[str | None, Field(description="The W&B run name to use.")] = None
offline: Annotated[bool | None, Field(description="Whether to run W&B in offline mode.")] = False
class SharedCheckpointConfig(BaseSettings):
"""Configures shared checkpoint configs."""
interval: Annotated[int | None, Field(description="The interval at which to save checkpoints.")] = None
resume_step: Annotated[
int | None, Field(description="The step to resume from. If None, will not resume from a checkpoint.")
] = None
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 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
class SharedModelConfig(BaseSettings):
"""Configures shared model settings."""
name: Annotated[
str,
Field(description="The name of the model to use."),
] = "Qwen/Qwen3-0.6B"
class SharedWeightBroadcastConfig(BaseSettings):
"""Configures shared weight broadcast settings."""
type: Annotated[Literal["nccl", "filesystem"], Field(description="The type of weight broadcast to use.")] = (
"filesystem"
)
class RLConfig(BaseRLConfig):
"""Configures an RL training run."""
clean: Annotated[
bool,
Field(
description="Whether to clean the rollouts, checkpoint, checkpoint weights and logs directories at the beginning of the run. If True, will forceably, and irreversibly, delete all directories.",
),
] = True
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
output_dir: Annotated[
Path,
Field(description="The directory to store the outputs. Should typically be set to an experiment identifier."),
] = Path("outputs") # NOTE: Must match `OUTPUT_DIR` in `tmux.sh` to see logs
bench: Annotated[
bool,
Field(
description="Whether to run in benchmark mode. It will automatically set the trainer and orchestrator to benchmark mode and, if present, configure the W&B project by suffixing the project with `-bench`.",
),
] = False
dump_config: Annotated[
Path | None,
Field(
description="If set, dump resolved subconfigs (trainer, orchestrator, inference) to this directory and exit without starting any processes."
),
] = None
@model_validator(mode="after")
def auto_setup_dp(self):
if self.inference and len(self.inference_gpu_ids) != self.inference.parallel.dp * self.inference.parallel.tp:
assert len(self.inference_gpu_ids) % self.inference.parallel.tp == 0, (
"Number of inference GPUs must be divisible by the tensor parallel size"
)
self.inference.parallel.dp = len(self.inference_gpu_ids) // self.inference.parallel.tp
return self
@model_validator(mode="after")
def auto_setup_num_train_workers(self):
non_data_parallel_size = self.trainer.model.cp * self.trainer.model.tp
if len(self.trainer_gpu_ids) > 1:
self.orchestrator.num_train_workers = len(self.trainer_gpu_ids) // non_data_parallel_size
return self
@model_validator(mode="after")
def auto_setup_bench(self):
if self.bench:
# Set trainer and orchestrator to benchmark mode
self.trainer.bench = True
self.orchestrator.bench = True
# Configure the trainer fake data to match the orchestrator config
self.trainer.data.fake = FakeDataLoaderConfig(
batch_size=self.orchestrator.batch_size,
)
trainer_bench_enabled = self.trainer.bench is not None
if trainer_bench_enabled != self.orchestrator.bench:
raise ValueError(
f"Trainer benchmark mode ({self.trainer.bench}) and orchestrator benchmark mode ({self.orchestrator.bench}) are not the same. Please specify the same benchmark mode for both."
)
return self
@model_validator(mode="after")
def auto_setup_lora(self):
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.")
# Ensure orchestrator has LoRA config
if self.orchestrator.model.lora is None:
from prime_rl.orchestrator.config import LoRAConfig
self.orchestrator.model.lora = LoRAConfig()
# Validate orchestrator LoRA rank/alpha don't conflict with trainer
if (
self.orchestrator.model.lora.rank is not None
and self.orchestrator.model.lora.rank != self.trainer.model.lora.rank
):
raise ValueError(
f"orchestrator.model.lora.rank ({self.orchestrator.model.lora.rank}) conflicts with "
f"trainer.model.lora.rank ({self.trainer.model.lora.rank}). "
f"Remove orchestrator.model.lora.rank to inherit from trainer, or update trainer.model.lora.rank to match."
)
if (
self.orchestrator.model.lora.alpha is not None
and self.orchestrator.model.lora.alpha != self.trainer.model.lora.alpha
):
raise ValueError(
f"orchestrator.model.lora.alpha ({self.orchestrator.model.lora.alpha}) conflicts with "
f"trainer.model.lora.alpha ({self.trainer.model.lora.alpha}). "
f"Remove orchestrator.model.lora.alpha to inherit from trainer, or update trainer.model.lora.alpha to match."
)
# Propagate rank/alpha from trainer when not explicitly set
if self.orchestrator.model.lora.rank is None:
self.orchestrator.model.lora.rank = self.trainer.model.lora.rank
if self.orchestrator.model.lora.alpha is None:
self.orchestrator.model.lora.alpha = self.trainer.model.lora.alpha
# Auto-generate name if not provided
if self.orchestrator.model.lora.name is None:
self.orchestrator.model.lora.name = (
f"r{self.orchestrator.model.lora.rank}-a{self.orchestrator.model.lora.alpha}"
)
if self.inference is not None:
self.inference.enable_lora = True
self.inference.max_lora_rank = self.trainer.model.lora.rank
else:
warnings.warn(
"LoRA is enabled, but inference is not configured. When manually starting the inference server, make sure to set `--enable_lora` and `--max-lora-rank`."
)
return self
@model_validator(mode="after")
def validate_enough_devices_for_nccl(self):
if self.trainer.weight_broadcast.type == "nccl":
num_gpus = len(set(self.trainer_gpu_ids + self.inference_gpu_ids))
if num_gpus < 2:
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:
thread.join(timeout=5)
def cleanup_processes(processes: list[Popen]):
for process in processes:
if process.poll() is None: # Process is still running
process.terminate()
try:
process.wait(timeout=60) # 60 seconds to terminate gracefully
except subprocess.TimeoutExpired:
process.kill()
def monitor_process(process: Popen, stop_event: Event, error_queue: list, process_name: str):
"""Monitor a subprocess and signal errors via shared queue"""
try:
# Wait for process to complete
process.wait()
if process.returncode != 0:
err_msg = f"{process_name.capitalize()} failed with exit code {process.returncode}"
if process.stderr:
err_msg += f"\n{process.stderr.read().decode('utf-8')}"
error_queue.append(RuntimeError(err_msg))
stop_event.set()
except Exception as e:
error_queue.append(RuntimeError(f"Error monitoring {process_name}: {e}"))
stop_event.set()
def check_gpus_available(gpu_ids: list[int]) -> None:
"""Raise error if there are existing processes on the specified GPUs."""
pynvml.nvmlInit()
occupied = []
for gpu_id in gpu_ids:
handle = pynvml.nvmlDeviceGetHandleByIndex(gpu_id)
processes = pynvml.nvmlDeviceGetComputeRunningProcesses(handle)
if processes:
pids = [p.pid for p in processes]
occupied.append((gpu_id, pids))
if occupied:
msg = "Existing processes found on GPUs:\n"
for gpu_id, pids in occupied:
msg += f" GPU {gpu_id}: PIDs {pids}\n"
msg += "Kill these processes or use different GPUs."
raise RuntimeError(msg)
def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
"""Write resolved subconfigs to disk as TOML files."""
output_dir.mkdir(parents=True, exist_ok=True)
with open(output_dir / "trainer.toml", "wb") as f:
tomli_w.dump(config.trainer.model_dump(exclude_none=True, mode="json"), f)
with open(output_dir / "orchestrator.toml", "wb") as f:
tomli_w.dump(config.orchestrator.model_dump(exclude_none=True, mode="json"), f)
if config.inference is not None:
with open(output_dir / "inference.toml", "wb") as f:
tomli_w.dump(config.inference.model_dump(exclude_none=True, mode="json"), f)
if config.teacher_inference is not None:
with open(output_dir / "teacher_inference.toml", "wb") as f:
tomli_w.dump(config.teacher_inference.model_dump(exclude_none=True, mode="json"), f)
def rl(config: RLConfig):
# Setup logger
logger = setup_logger(
config.log.level or "info",
log_file=config.output_dir / "logs" / "rl.log" if config.log.file else None,
json_logging=config.log.json_logging,
)
# If dump_config is set, write resolved subconfigs and exit early
if config.dump_config is not None:
logger.warning(
"--dump-config is set. No RL training will be started. Only writing resolved subconfigs to disk."
)
write_subconfigs(config, config.dump_config)
logger.info(f"Dumping resolved subconfigs to {config.dump_config}")
logger.info(f" Wrote trainer config to {config.dump_config / 'trainer.toml'}")
logger.info(f" Wrote orchestrator config to {config.dump_config / 'orchestrator.toml'}")
if config.inference is not None:
logger.info(f" Wrote inference config to {config.dump_config / 'inference.toml'}")
if config.teacher_inference is not None:
logger.info(f" Wrote teacher inference config to {config.dump_config / 'teacher_inference.toml'}")
logger.success(f"Config dump complete. Files written to {config.dump_config}")
logger.warning("To start an RL run, remove --dump-config from your command.")
return
start_command = sys.argv
logger.info("Starting RL run")
logger.debug(f"RL start command: {' '.join(start_command)}")
# Check for existing processes on GPUs
all_gpu_ids = list(set(config.inference_gpu_ids + config.trainer_gpu_ids + (config.teacher_gpu_ids or [])))
check_gpus_available(all_gpu_ids)
# Validate client port matches inference server port
if config.inference is not None and not config.orchestrator.client.is_elastic:
from urllib.parse import urlparse
base_url = config.orchestrator.client.base_url[0]
parsed = urlparse(base_url)
client_port = parsed.port
expected_port = config.inference.server.port
if client_port != expected_port:
raise ValueError(
f"orchestrator.client.base_url port ({client_port}) does not match "
f"inference.server.port ({expected_port}). "
f"Update the base_url to use port {expected_port} to match the inference server."
)
# Prepare paths to communicate with the trainer
log_dir = get_log_dir(config.output_dir)
orch_log_dir = get_log_dir(config.orchestrator.output_dir)
rollout_dir = get_rollout_dir(config.orchestrator.output_dir)
broadcast_dir = get_broadcast_dir(config.orchestrator.output_dir)
# Clean up directories if specified
if config.clean:
logger.info("Cleaning checkpoint, logs, weights, broadcast and rollout directories")
# Cleaning logs (so that streaming logs to terminal works)
logger.info(f"Cleaning log dir ({log_dir})")
shutil.rmtree(log_dir, ignore_errors=True)
log_dir.mkdir(parents=True, exist_ok=True)
logger.info(f"Cleaning orchestrator log dir ({orch_log_dir})")
shutil.rmtree(orch_log_dir, ignore_errors=True)
orch_log_dir.mkdir(parents=True, exist_ok=True)
# Cleaning broadcast dir (so that orchestrator does not pre-maturely update weights)
if not (
config.ckpt
and config.ckpt.resume_step
and config.trainer.weight_broadcast
and config.trainer.weight_broadcast.type == "filesystem"
):
logger.info(f"Cleaning broadcast directory ({broadcast_dir})")
shutil.rmtree(broadcast_dir, ignore_errors=True)
# Cleaning rollouts (so that trainer does not train on old rollouts)
logger.info(f"Cleaning rollout dir ({rollout_dir})")
shutil.rmtree(rollout_dir, ignore_errors=True)
# Write all resolved subconfigs to disk
config_dir = Path(".pydantic_config") / uuid.uuid4().hex
write_subconfigs(config, config_dir)
# Start processes
processes: list[Popen] = []
monitor_threads: list[Thread] = []
error_queue: list[Exception] = []
stop_events: dict[str, Event] = {}
try:
# Optionally, start inference process
if config.inference:
inference_cmd = ["uv", "run", "inference", "@", (config_dir / "inference.toml").as_posix()]
logger.info(f"Starting inference process on GPU(s) {' '.join(map(str, config.inference_gpu_ids))}")
logger.debug(f"Inference start command: {' '.join(inference_cmd)}")
# If we don't log stdout, the server hangs
with open(log_dir / "inference.stdout", "w") as log_file:
inference_process = Popen(
inference_cmd,
env={**os.environ, "CUDA_VISIBLE_DEVICES": ",".join(map(str, config.inference_gpu_ids))},
stdout=log_file,
stderr=log_file,
)
processes.append(inference_process)
# Start monitoring thread
stop_event = Event()
stop_events["inference"] = stop_event
monitor_thread = Thread(
target=monitor_process,
args=(inference_process, stop_event, error_queue, "inference"),
daemon=True,
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
else:
logger.warning(
"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_cmd = ["uv", "run", "inference", "@", (config_dir / "teacher_inference.toml").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_cmd = [
"uv",
"run",
"orchestrator",
"@",
(config_dir / "orchestrator.toml").as_posix(),
]
logger.info("Starting orchestrator process")
logger.debug(f"Orchestrator start command: {' '.join(orchestrator_cmd)}")
with open(log_dir / "orchestrator.stdout", "w") as log_file:
orchestrator_process = Popen(
orchestrator_cmd,
stdout=log_file,
stderr=log_file,
env={
**os.environ,
"LOGURU_FORCE_COLORS": "1",
"WANDB_PROGRAM": "uv run rl",
"WANDB_ARGS": json.dumps(start_command),
},
)
processes.append(orchestrator_process)
# Start monitoring thread
stop_event = Event()
stop_events["orchestrator"] = stop_event
monitor_thread = Thread(
target=monitor_process,
args=(orchestrator_process, stop_event, error_queue, "orchestrator"),
daemon=True,
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
# Start training process
trainer_cmd = [
"uv",
"run",
"env",
"PYTHONUNBUFFERED=1",
"PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True",
"torchrun",
f"--rdzv-endpoint=localhost:{get_free_port()}",
f"--rdzv-id={uuid.uuid4().hex}",
# Pipe all logs to file, and only master rank logs to stdout
f"--log-dir={config.output_dir / 'torchrun'}",
"--local-ranks-filter=0",
"--redirect=3",
"--tee=3",
f"--nproc-per-node={len(config.trainer_gpu_ids)}",
"-m",
"prime_rl.trainer.rl.train",
"@",
(config_dir / "trainer.toml").as_posix(),
]
logger.info(f"Starting trainer process on GPU(s) {' '.join(map(str, config.trainer_gpu_ids))}")
logger.debug(f"Training start command: {' '.join(trainer_cmd)}")
with open(log_dir / "trainer.stdout", "w") as log_file:
trainer_process = Popen(
trainer_cmd,
env={
**os.environ,
"CUDA_VISIBLE_DEVICES": ",".join(map(str, config.trainer_gpu_ids)),
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
"LOGURU_FORCE_COLORS": "1",
"WANDB_PROGRAM": "uv run rl",
"WANDB_ARGS": json.dumps(start_command),
},
stdout=log_file,
stderr=log_file,
)
processes.append(trainer_process)
# Start monitoring thread
stop_event = Event()
stop_events["trainer"] = stop_event
monitor_thread = Thread(
target=monitor_process, args=(trainer_process, stop_event, error_queue, "trainer"), daemon=True
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
# Monitor all processes for failures
logger.success("Startup complete. Showing trainer logs...")
tail_process = Popen(["tail", "-F", log_dir / "trainer.stdout"])
processes.append(tail_process)
# Check for errors from monitor threads
while not (stop_events["orchestrator"].is_set() and stop_events["trainer"].is_set()):
if error_queue:
error = error_queue[0]
logger.error(f"Error: {error}")
logger.error("Terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
# 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
cleanup_threads(monitor_threads)
cleanup_processes(processes)
except KeyboardInterrupt:
logger.warning("Received interrupt signal, terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
except Exception as e:
logger.error(f"Error occurred: {e}")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
raise
def main():
rl(parse_argv(RLConfig))
if __name__ == "__main__":
main()
+349 -34
View File
@@ -1,8 +1,10 @@
import warnings
from pathlib import Path
from typing import Annotated, Literal
from typing import Annotated, Literal, TypeAlias
from pydantic import Field, model_validator
from pydantic.config import ConfigDict
from pydantic.main import BaseModel
from prime_rl.inference.config import InferenceConfig
from prime_rl.inference.config import WeightBroadcastConfig as InferenceWeightBroadcastConfig
@@ -10,7 +12,9 @@ from prime_rl.orchestrator.config import CheckpointConfig as OrchestratorCheckpo
from prime_rl.orchestrator.config import FileSystemWeightBroadcastConfig as OrchestratorFileSystemWeightBroadcastConfig
from prime_rl.orchestrator.config import NCCLWeightBroadcastConfig as OrchestratorNCCLWeightBroadcastConfig
from prime_rl.orchestrator.config import OrchestratorConfig
from prime_rl.trainer.config import BenchConfig, SlurmConfig
from prime_rl.trainer.config import CheckpointConfig as TrainerCheckpointConfig
from prime_rl.trainer.rl.config import FakeDataLoaderConfig
from prime_rl.trainer.rl.config import FileSystemWeightBroadcastConfig as TrainerFileSystemWeightBroadcastConfig
from prime_rl.trainer.rl.config import NCCLWeightBroadcastConfig as TrainerNCCLWeightBroadcastConfig
from prime_rl.trainer.rl.config import RLTrainerConfig as TrainerConfig
@@ -96,26 +100,100 @@ class SharedWeightBroadcastConfig(BaseSettings):
timeout: Annotated[int, Field(description="The timeout in seconds for NCCL weight broadcast.")] = 1200
class BaseRLConfig(BaseSettings):
"""Configures an RL training run."""
class BaseDeploymentConfig(BaseModel):
"""Configures a base deployment."""
### Submodule configurations
model_config = ConfigDict(extra="forbid")
trainer: TrainerConfig
orchestrator: OrchestratorConfig
gpus_per_node: Annotated[int, Field(description="Number of GPUs per node.")] = 8
output_dir: Annotated[
Path | None,
Field(description="The directory to store the outputs. Should typically be set to an experiment identifier."),
] = None
inference: Annotated[
InferenceConfig | None,
class SingleNodeDeploymentConfig(BaseDeploymentConfig):
"""Configures a single node deployment."""
type: Literal["single_node"] = "single_node"
num_train_gpus: Annotated[int, Field(description="Number of training GPUs")] = 1
num_infer_gpus: Annotated[int, Field(description="Number of inference GPUs")] = 1
num_teacher_gpus: Annotated[int | None, Field(description="Number of teacher inference GPUs")] = None
@model_validator(mode="after")
def validate_gpu_count(self):
total = self.num_train_gpus + self.num_infer_gpus + (self.num_teacher_gpus or 0)
if total > self.gpus_per_node:
raise ValueError(
f"Total GPU count ({total} = {self.num_train_gpus} train + {self.num_infer_gpus} infer"
f" + {self.num_teacher_gpus or 0} teacher) exceeds gpus_per_node ({self.gpus_per_node})."
)
return self
class MultiNodeDeploymentConfig(BaseDeploymentConfig):
"""Configures a multi node deployment."""
type: Literal["multi_node"] = "multi_node"
num_train_nodes: Annotated[int, Field(description="Number of training nodes.")]
num_infer_nodes: Annotated[int, Field(description="Number of inference nodes.")]
num_teacher_nodes: Annotated[int | None, Field(description="Number of teacher inference nodes.")] = None
nodes_per_fsdp_group: Annotated[
int | None,
Field(
description="The inference config. If None, will not start an inference process. Only viable, if an inference server was started manually."
description="Number of training nodes per FSDP island. Auto-sets trainer.dp_replicate = num_train_nodes / nodes_per_fsdp_group."
),
] = None
### Top-level configurations
@model_validator(mode="after")
def teacher_inference_not_supported(self):
if self.num_teacher_nodes is not None:
raise ValueError("Teacher inference is not yet supported in multi node deployment.")
return self
DeploymentConfig: TypeAlias = Annotated[
SingleNodeDeploymentConfig | MultiNodeDeploymentConfig, Field(discriminator="type")
]
class RLConfig(BaseSettings):
"""Configures an RL training run."""
trainer: TrainerConfig
orchestrator: OrchestratorConfig
inference: Annotated[
InferenceConfig | None,
Field(
description="The inference config. If None, the rl entrypoint will not start an inference server (useful for elastic inference pools or manually started servers)."
),
] = None
teacher_inference: Annotated[
InferenceConfig | None,
Field(
description="Teacher inference config. If None, will use the same config as inference or a default config. Only used when teacher GPUs or nodes are set."
),
] = None
output_dir: Annotated[
Path,
Field(
description="The directory to store the outputs. Should be set to a unique directory identifying the experiment."
),
] = Path("outputs")
clean_output_dir: Annotated[
bool,
Field(
description="If true, delete the output directory before starting training. Required to overwrite an output directory that contains checkpoints from a previous run when not resuming.",
),
] = False
deployment: DeploymentConfig = SingleNodeDeploymentConfig()
slurm: Annotated[SlurmConfig | None, Field(description="SLURM configuration. If None, will run locally.")] = None
### Shared configurations
log: Annotated[
SharedLogConfig,
@@ -162,7 +240,9 @@ class BaseRLConfig(BaseSettings):
seq_len: Annotated[
int | None,
Field(
description="The sequence length to use. If set, will configure both trainer.model.seq_len and orchestrator.seq_len to this value. If None, each can be set independently."
description="Shared sequence length. Propagates to trainer.model.seq_len and orchestrator.seq_len, "
"but only for those not explicitly set in the config. "
"Explicitly set per-component values always take precedence."
),
] = None
@@ -177,10 +257,79 @@ class BaseRLConfig(BaseSettings):
SharedWeightBroadcastConfig | None, Field(description="The weight broadcast config.")
] = None
### Setup and validate shared configs
### Local-only fields
bench: Annotated[
bool,
Field(
description="Whether to run in benchmark mode. Automatically sets the trainer and orchestrator to benchmark mode and, if present, suffixes the W&B project with `-bench`.",
),
] = False
dump_config: Annotated[
Path | None,
Field(
description="If set, dump resolved subconfigs (trainer, orchestrator, inference) to this directory and exit without starting any processes."
),
] = None
### Validate configs (e.g. raise for unsupported (combinations of) configs)
@model_validator(mode="after")
def validate_deployment(self):
if self.deployment.type == "multi_node":
if self.slurm is None:
raise ValueError("Must use SLURM for multi-node deployment.")
if not self.inference:
raise ValueError("Must configure inference when using multi-node deployment.")
return self
# TODO: fix this
@model_validator(mode="after")
def validate_no_teacher_in_multinode(self):
if self.deployment.type == "multi_node" and self.teacher_inference is not None:
raise ValueError(
"Teacher inference is not supported in multi-node deployment. "
"The SLURM template only handles inference and training nodes."
)
return self
@model_validator(mode="after")
def validate_enough_devices_for_nccl(self):
if self.deployment.type == "single_node":
if self.trainer.weight_broadcast.type == "nccl":
if self.deployment.num_train_gpus + self.deployment.num_infer_gpus < 2:
raise ValueError(
"NCCL weight broadcast requires at least 2 GPUs to build the broadcast process group."
)
return self
@model_validator(mode="after")
def validate_teacher_model(self):
if (
self.trainer.loss.type == "default" and 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 deployment.num_teacher_gpus, or configure teacher_model manually."
)
return self
### Auto-setup and validate shared configs
@model_validator(mode="after")
def auto_setup_output_dir(self):
"""Auto-setup shared output directory for trainer and orchestrator."""
self.trainer.output_dir = self.output_dir
self.orchestrator.output_dir = self.output_dir / "run_default"
validate_shared_output_dir(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_logs(self):
"""Auto-setup shared log config for trainer and orchestrator."""
if self.log is not None:
if self.log.level is not None:
self.trainer.log.level = self.log.level
@@ -195,7 +344,7 @@ class BaseRLConfig(BaseSettings):
@model_validator(mode="after")
def auto_setup_ckpt(self):
# If specified, automatically setup checkpoint configs for trainer and orchestrator
"""Auto-setup shared checkpoint config for trainer and orchestrator."""
if self.ckpt is not None:
# Create checkpoint configs if not specified
if self.trainer.ckpt is None:
@@ -228,7 +377,7 @@ class BaseRLConfig(BaseSettings):
@model_validator(mode="after")
def auto_setup_wandb(self):
# If specified, automatically use shared W&B project for orchestrator and trainer
"""Auto-setup shared W&B config for trainer and orchestrator."""
if self.wandb is not None:
if not self.trainer.wandb:
self.trainer.wandb = WandbConfig()
@@ -255,12 +404,15 @@ class BaseRLConfig(BaseSettings):
@model_validator(mode="after")
def auto_setup_model(self):
# Use the same model for trainer, orchestrator and inference
"""Auto-setup shared model config for trainer, orchestrator, and inference."""
if self.model is not None:
self.trainer.model.name = self.model.name
self.orchestrator.model.name = self.model.name
if self.inference is not None:
self.inference.model.name = self.model.name
self.inference.model.tool_call_parser = None
self.inference.model.enable_auto_tool_choice = False
self.inference.model.resolve_tool_call_parser()
validate_shared_model_name(self.trainer, self.orchestrator, self.inference)
@@ -268,7 +420,7 @@ class BaseRLConfig(BaseSettings):
@model_validator(mode="after")
def auto_setup_max_steps(self):
# If specified, use the same max steps for trainer and orchestrator
"""Auto-setup shared max steps for trainer and orchestrator."""
if self.max_steps is not None:
self.trainer.max_steps = self.max_steps
self.orchestrator.max_steps = self.max_steps
@@ -279,7 +431,7 @@ class BaseRLConfig(BaseSettings):
@model_validator(mode="after")
def auto_setup_async_level(self):
# If specified, use the same async level for trainer and orchestrator
"""Auto-setup shared async level for trainer and orchestrator."""
if self.max_async_level is not None:
self.trainer.max_async_level = self.max_async_level
self.orchestrator.max_async_level = self.max_async_level
@@ -290,10 +442,16 @@ class BaseRLConfig(BaseSettings):
@model_validator(mode="after")
def auto_setup_seq_len(self):
# If specified, use the same seq_len for trainer and orchestrator
"""Auto-setup shared seq_len for trainer and orchestrator.
Only propagates to components that weren't explicitly set in the config.
Uses model_fields_set to detect explicit assignment.
"""
if self.seq_len is not None:
self.trainer.model.seq_len = self.seq_len
self.orchestrator.seq_len = self.seq_len
if "seq_len" not in self.trainer.model.model_fields_set:
self.trainer.model.seq_len = self.seq_len
if "seq_len" not in self.orchestrator.model_fields_set:
self.orchestrator.seq_len = self.seq_len
if self.trainer.model.seq_len < self.orchestrator.seq_len:
raise ValueError(
@@ -305,6 +463,7 @@ class BaseRLConfig(BaseSettings):
@model_validator(mode="after")
def auto_setup_weight_broadcast(self):
"""Auto-setup shared weight broadcast config for trainer, orchestrator, and inference."""
if self.weight_broadcast is not None:
if self.weight_broadcast.type == "nccl":
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp if self.inference else 1
@@ -329,6 +488,172 @@ class BaseRLConfig(BaseSettings):
return self
@model_validator(mode="after")
def auto_setup_bench(self):
if self.bench:
self.trainer.bench = BenchConfig()
self.orchestrator.bench = True
self.trainer.data.fake = FakeDataLoaderConfig(
batch_size=self.orchestrator.batch_size,
)
trainer_bench_enabled = self.trainer.bench is not None
if trainer_bench_enabled != self.orchestrator.bench:
raise ValueError(
f"Trainer benchmark mode ({self.trainer.bench}) and orchestrator benchmark mode "
f"({self.orchestrator.bench}) must match. Use the top-level bench = true to set both."
)
return self
@model_validator(mode="after")
def auto_setup_lora(self):
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.model.lora is None:
from prime_rl.orchestrator.config import LoRAConfig
self.orchestrator.model.lora = LoRAConfig()
if (
self.orchestrator.model.lora.rank is not None
and self.orchestrator.model.lora.rank != self.trainer.model.lora.rank
):
raise ValueError(
f"orchestrator.model.lora.rank ({self.orchestrator.model.lora.rank}) conflicts with "
f"trainer.model.lora.rank ({self.trainer.model.lora.rank}). "
f"Remove orchestrator.model.lora.rank to inherit from trainer, or update trainer.model.lora.rank to match."
)
if (
self.orchestrator.model.lora.alpha is not None
and self.orchestrator.model.lora.alpha != self.trainer.model.lora.alpha
):
raise ValueError(
f"orchestrator.model.lora.alpha ({self.orchestrator.model.lora.alpha}) conflicts with "
f"trainer.model.lora.alpha ({self.trainer.model.lora.alpha}). "
f"Remove orchestrator.model.lora.alpha to inherit from trainer, or update trainer.model.lora.alpha to match."
)
if self.orchestrator.model.lora.rank is None:
self.orchestrator.model.lora.rank = self.trainer.model.lora.rank
if self.orchestrator.model.lora.alpha is None:
self.orchestrator.model.lora.alpha = self.trainer.model.lora.alpha
if self.orchestrator.model.lora.name is None:
self.orchestrator.model.lora.name = (
f"r{self.orchestrator.model.lora.rank}-a{self.orchestrator.model.lora.alpha}"
)
if self.inference is not None:
self.inference.enable_lora = True
self.inference.max_lora_rank = self.trainer.model.lora.rank
else:
warnings.warn(
"LoRA is enabled, but inference is not configured. When manually starting the inference server, "
"make sure to set --enable_lora and --max-lora-rank."
)
return self
@model_validator(mode="after")
def auto_setup_deployment(self):
if self.deployment.type == "single_node": # single-node
# set num_train_workers to the number of data replicas
non_data_parallel_size = self.trainer.model.cp * self.trainer.model.tp
if self.deployment.num_train_gpus > 1:
self.orchestrator.num_train_workers = self.deployment.num_train_gpus // non_data_parallel_size
# fill up inference capacity with dp ranks
if self.inference is not None:
num_infer_gpus = self.deployment.num_infer_gpus
if num_infer_gpus != self.inference.parallel.dp * self.inference.parallel.tp:
assert num_infer_gpus % self.inference.parallel.tp == 0, (
"Number of inference GPUs must be divisible by the tensor parallel size"
)
self.inference.parallel.dp = num_infer_gpus // self.inference.parallel.tp
elif self.deployment.type == "multi_node": # multi-node
self.orchestrator.num_train_workers = self.deployment.num_train_nodes * self.deployment.gpus_per_node
if self.deployment.nodes_per_fsdp_group is not None:
if self.deployment.num_train_nodes % self.deployment.nodes_per_fsdp_group != 0:
raise ValueError(
f"deployment.num_train_nodes ({self.deployment.num_train_nodes}) must be divisible by "
f"deployment.nodes_per_fsdp_group ({self.deployment.nodes_per_fsdp_group})"
)
self.trainer.model.dp_replicate = (
self.deployment.num_train_nodes // self.deployment.nodes_per_fsdp_group
)
if self.weight_broadcast is not None and self.weight_broadcast.type == "nccl":
assert self.trainer.weight_broadcast.type == "nccl"
self.trainer.weight_broadcast.host = "0.0.0.0"
self.trainer.weight_broadcast.inference_world_size = (
self.deployment.gpus_per_node * self.deployment.num_infer_nodes
)
return self
@model_validator(mode="after")
def auto_setup_teacher_inference(self):
"""Auto-configure teacher inference server and orchestrator teacher_model client."""
if self.deployment.type != "single_node":
return self
if self.deployment.num_teacher_gpus is None or self.deployment.num_teacher_gpus == 0:
return self
import copy
from prime_rl.orchestrator.config import TeacherModelConfig
if self.teacher_inference is None:
if self.inference is None:
self.teacher_inference = InferenceConfig()
else:
self.teacher_inference = copy.deepcopy(self.inference)
self.teacher_inference.server.port = (self.inference.server.port if self.inference else 8000) + 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."
)
tp = self.teacher_inference.parallel.tp
num_teacher_gpus = self.deployment.num_teacher_gpus
if num_teacher_gpus != self.teacher_inference.parallel.dp * tp:
assert num_teacher_gpus % tp == 0, "Number of teacher GPUs must be divisible by tensor parallel size"
assert num_teacher_gpus > 0, "num_teacher_gpus cannot be zero"
self.teacher_inference.parallel.dp = num_teacher_gpus // tp
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 auto_setup_slurm_template(self):
"""Auto-setup the default single-node/multi-node SLURM template if no custom template is provided."""
if self.slurm is not None and self.slurm.template_path is None:
import prime_rl
templates_dir = Path(prime_rl.__file__).parent / "templates"
if self.deployment.type == "single_node":
self.slurm.template_path = templates_dir / "single_node_rl.sbatch.j2"
else:
self.slurm.template_path = templates_dir / "multi_node_rl.sbatch.j2"
return self
### Warnings
@model_validator(mode="after")
def warn_wandb_resume_id_missing(self):
if self.trainer.ckpt is not None and self.trainer.ckpt.resume_step is not None:
@@ -342,13 +667,3 @@ class BaseRLConfig(BaseSettings):
"W&B run ID is not set for orchestrator even though resuming training. The current run will be created as a new run."
)
return self
@model_validator(mode="after")
def auto_setup_output_dir(self):
if self.output_dir is not None:
self.trainer.output_dir = self.output_dir
self.orchestrator.output_dir = self.output_dir / "run_default"
validate_shared_output_dir(self.trainer, self.orchestrator)
return self
-155
View File
@@ -1,155 +0,0 @@
import subprocess
import sys
from pathlib import Path
import tomli_w
from jinja2 import Environment, FileSystemLoader
from pydantic import Field, model_validator
from prime_rl.rl_config import BaseRLConfig
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pydantic_config import parse_argv
TEMPLATE_DIR = Path(__file__).parent
TEMPLATE_NAME = "rl_slurm.sh.j2"
class RLSLURMConfig(BaseRLConfig):
output_dir: Path
job_name: str
num_train_nodes: int
num_infer_nodes: int
gpus_per_node: int = Field(default=8, description="Number of GPUs per node.")
nodes_per_fsdp_group: int | None = Field(
default=None,
description="Number of train nodes per FSDP island. Auto-sets trainer.dp_replicate = num_train_nodes / nodes_per_fsdp_group.",
)
project_dir: Path = Field(
default_factory=lambda: Path.cwd(),
description="Path to the project root. Used to source .env, activate .venv, and run uv sync.",
)
hf_hub_offline: bool = Field(
default=False, description="Set HF_HUB_OFFLINE=1 on training nodes to prevent downloading models at runtime."
)
slurm_template: Path | None = Field(
default=None, description="The path to the SLURM template file. If none, will use the default template."
)
dry_run: bool = Field(default=False, description="Only generate the SLURM script and configs without submitting.")
@model_validator(mode="after")
def auto_setup_dp_replicate(self):
if self.nodes_per_fsdp_group is not None:
if self.num_train_nodes % self.nodes_per_fsdp_group != 0:
raise ValueError(
f"num_train_nodes ({self.num_train_nodes}) must be divisible by nodes_per_fsdp_group ({self.nodes_per_fsdp_group})"
)
self.trainer.dp_replicate = self.num_train_nodes // self.nodes_per_fsdp_group
return self
@model_validator(mode="after")
def auto_setup_slurm_nccl(self):
"""Set SLURM-specific values for NCCL weight broadcast and num_train_workers."""
# Set num_train_workers based on SLURM topology
self.orchestrator.num_train_workers = self.num_train_nodes * self.gpus_per_node
# Set NCCL-specific values if using NCCL weight broadcast
if self.weight_broadcast is not None and self.weight_broadcast.type == "nccl":
# Trainer listens on all interfaces
self.trainer.weight_broadcast.host = "0.0.0.0"
# Compute inference world size from SLURM topology
self.trainer.weight_broadcast.inference_world_size = self.gpus_per_node * self.num_infer_nodes
return self
@model_validator(mode="after")
def validate_inference_config(self):
"""Validate that inference config is provided when num_infer_nodes > 0."""
if self.num_infer_nodes > 0 and self.inference is None:
raise ValueError(
f"inference config is required when num_infer_nodes > 0 (got {self.num_infer_nodes}). "
"The SLURM template will launch inference servers on these nodes."
)
return self
def write_subconfigs(config: RLSLURMConfig, output_dir: Path) -> None:
"""Write resolved subconfigs to disk as TOML files."""
output_dir.mkdir(parents=True, exist_ok=True)
with open(output_dir / "trainer.toml", "wb") as f:
tomli_w.dump(config.trainer.model_dump(exclude_none=True, mode="json"), f)
with open(output_dir / "orchestrator.toml", "wb") as f:
tomli_w.dump(config.orchestrator.model_dump(exclude_none=True, mode="json"), f)
if config.inference is not None:
with open(output_dir / "inference.toml", "wb") as f:
tomli_w.dump(config.inference.model_dump(exclude_none=True, mode="json"), f)
def render_slurm_script(config: RLSLURMConfig, config_dir: Path) -> str:
"""Render the SLURM script template with config values."""
if config.slurm_template is not None:
template_dir = config.slurm_template.parent
template_name = config.slurm_template.name
else:
template_dir = TEMPLATE_DIR
template_name = TEMPLATE_NAME
env = Environment(loader=FileSystemLoader(template_dir), keep_trailing_newline=True)
template = env.get_template(template_name)
return template.render(
job_name=config.job_name,
output_dir=config.output_dir,
orchestrator_output_dir=config.orchestrator.output_dir,
config_dir=config_dir,
num_train_nodes=config.num_train_nodes,
num_infer_nodes=config.num_infer_nodes,
project_dir=config.project_dir,
gpus_per_node=config.gpus_per_node,
hf_hub_offline=config.hf_hub_offline,
)
def rl_slurm(config: RLSLURMConfig):
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
config_dir = config.output_dir / "configs"
write_subconfigs(config, config_dir)
logger.info(f"Wrote subconfigs to {config_dir}")
script = render_slurm_script(config, config_dir)
script_path = config.output_dir / "rl.sh"
script_path.parent.mkdir(parents=True, exist_ok=True)
script_path.write_text(script)
logger.info(f"Wrote SLURM script to {script_path}")
slurm_log_dir = config.output_dir / "slurm"
log_message = (
f"Logs:\n"
f" Trainer: tail -f {slurm_log_dir}/latest_train_node_rank_0.log\n"
f" Inference: tail -f {slurm_log_dir}/latest_infer_node_rank_0.log\n"
f" Orchestrator: tail -f {slurm_log_dir}/latest_orchestrator.log"
)
if config.dry_run:
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
return
logger.info(f"Submitting: sbatch {script_path}")
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
if result.returncode != 0:
logger.error(f"sbatch failed: {result.stderr.strip()}")
sys.exit(1)
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
def main():
rl_slurm(parse_argv(RLSLURMConfig))
if __name__ == "__main__":
main()
@@ -4,10 +4,10 @@
#SBATCH --nodes={{ num_train_nodes + num_infer_nodes }}
#SBATCH --ntasks-per-node=1
#SBATCH --gres=gpu:{{ gpus_per_node }}
#SBATCH --partition=cluster
#SBATCH --exclusive # Get the ENTIRE node exclusively
#SBATCH --output=/shared/logs/job_%j.log
#SBATCH --error=/shared/logs/job_%j.log
#SBATCH --partition={{ partition }}
#SBATCH --exclusive
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
# Configs
export NUM_TRAIN_NODES={{ num_train_nodes }}
@@ -28,7 +28,6 @@ rm -rf $OUTPUT_DIR/run_*/rollouts
rm -rf $OUTPUT_DIR/run_*/broadcasts
rm -rf $OUTPUT_DIR/rollouts
# General
export CUDA_DEVICE_ORDER=PCI_BUS_ID
export PYTHONUNBUFFERED=1
@@ -58,22 +57,19 @@ export MASTER_PORT=29500
echo "MASTER_ADDR=${MASTER_ADDR}"
echo "MASTER_PORT=${MASTER_PORT}"
# Install environment
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
source $PROJECT_DIR/.venv/bin/activate
# Install environment as local package
cd $PROJECT_DIR && uv sync --all-extras
# Setup environment
cd $PROJECT_DIR
[ -f .env ] && source .env
source .venv/bin/activate
uv sync --all-extras
# Run RL
srun bash -c '
# Setup environment
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
source $PROJECT_DIR/.venv/bin/activate
# Disable sync to avoid conflicts with lockfile
# Source environment
cd $PROJECT_DIR
[ -f .env ] && source .env
source .venv/bin/activate
# Do not sync to avoid conflicts with lockfile
# Higher ulimit
ulimit -n 65536
@@ -84,17 +80,14 @@ srun bash -c '
export NCCL_IB_HCA=$IB_HCA
if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
# This is required for vLLM graph compile to work
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:False"
INFER_NODE_RANK=$SLURM_PROCID
export VLLM_WORKER_MULTIPROC_METHOD=spawn
uv run inference \
@ $CONFIG_DIR/inference.toml \
--enable-auto-tool-choice \
--enable-log-requests \
--no-disable-log-requests \
2>&1 | tee $OUTPUT_DIR/slurm/latest_infer_node_rank_${INFER_NODE_RANK}.log $OUTPUT_DIR/slurm/job_${INFER_NODE_RANK}_infer_node_rank_${INFER_NODE_RANK}.log
2>&1 | tee $OUTPUT_DIR/slurm/latest_infer_node_rank_${INFER_NODE_RANK}.log $OUTPUT_DIR/slurm/job_${SLURM_JOB_ID}_infer_node_rank_${INFER_NODE_RANK}.log
else
TRAIN_NODE_RANK=$((SLURM_PROCID - NUM_INFER_NODES))
@@ -106,13 +99,13 @@ else
2>&1 | tee $OUTPUT_DIR/slurm/latest_orchestrator.log $OUTPUT_DIR/slurm/job_${SLURM_JOB_ID}_orchestrator.log & disown
fi
export HF_HUB_OFFLINE={{ 1 if hf_hub_offline else 0 }}
export HF_HUB_OFFLINE=1
# This is required for compilation to work correctly
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True"
echo $HOSTNAMES | tee $OUTPUT_DIR/slurm/latest_train_node_rank_${TRAIN_NODE_RANK}.log
echo $HOSTNAMES | tee $OUTPUT_DIR/slurm/latest_train_node_rank_${TRAIN_NODE_RANK}.log
uv run torchrun \
--nnodes=$NUM_TRAIN_NODES \
--nproc-per-node=$GPUS_PER_NODE \
@@ -0,0 +1,79 @@
#!/bin/bash
#SBATCH --job-name={{ job_name }}
#SBATCH --nodes={{ num_nodes }}
#SBATCH --ntasks-per-node=1
#SBATCH --gres=gpu:{{ gpus_per_node }}
#SBATCH --partition={{ partition }}
#SBATCH --exclusive # Get the ENTIRE node exclusively
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
# Configs
export NUM_NODES={{ num_nodes }}
export GPUS_PER_NODE={{ gpus_per_node }}
# Paths
export PROJECT_DIR={{ project_dir }}
export CONFIG_DIR={{ config_dir }}
export OUTPUT_DIR={{ output_dir }}
mkdir -p $OUTPUT_DIR/slurm
# General
export CUDA_DEVICE_ORDER=PCI_BUS_ID
export PYTHONUNBUFFERED=1
export OMP_NUM_THREADS=1
# Networking
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
echo "HOSTNAMES=${HOSTNAMES[@]}"
export MASTER_ADDR="${HOSTNAMES[0]}"
export MASTER_PORT=29500
echo "MASTER_ADDR=${MASTER_ADDR}"
echo "MASTER_PORT=${MASTER_PORT}"
# Install environment
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
source $PROJECT_DIR/.venv/bin/activate
# Install environment as local package
cd $PROJECT_DIR && uv sync --all-extras
# Run SFT
srun bash -c '
# Setup environment
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
source $PROJECT_DIR/.venv/bin/activate
# Higher ulimit
ulimit -n 65536
export GIT_LFS_SKIP_SMUDGE=1
# Infiniband setup
IB_HCA=$(ibv_devinfo | sed -n -e "/hca_id/p" -e "/link_layer:/p" | grep -B1 InfiniBand | grep hca_id | sed -e "s/^hca_id://g" | tr -d "[[:blank:]]" |paste -sd,)
export NCCL_IB_HCA=$IB_HCA
TRAIN_NODE_RANK=$SLURM_PROCID
export HF_HUB_OFFLINE=1
# This is required for compilation to work correctly
export PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True"
echo $HOSTNAMES | tee $OUTPUT_DIR/slurm/latest_train_node_rank_${TRAIN_NODE_RANK}.log
uv run torchrun \
--nnodes=$NUM_NODES \
--nproc-per-node=$GPUS_PER_NODE \
--node-rank=$TRAIN_NODE_RANK \
--rdzv-endpoint=$MASTER_ADDR:$MASTER_PORT \
--rdzv-id=job_$SLURM_JOB_ID \
--log-dir=$OUTPUT_DIR/torchrun \
--tee=3 \
--redirects=3 \
--local-ranks-filter=$(seq -s, 0 $((GPUS_PER_NODE - 1))) \
-m prime_rl.trainer.sft.train \
@ $CONFIG_DIR/trainer.toml \
2>&1 | tee -a $OUTPUT_DIR/slurm/latest_train_node_rank_${TRAIN_NODE_RANK}.log $OUTPUT_DIR/slurm/job_${SLURM_JOB_ID}_train_node_rank_${TRAIN_NODE_RANK}.log
'
@@ -0,0 +1,20 @@
#!/bin/bash
#SBATCH --job-name={{ job_name }}
#SBATCH --nodes=1
#SBATCH --ntasks-per-node=1
#SBATCH --gres=gpu:{{ gpus_per_node }}
#SBATCH --exclusive
#SBATCH --partition={{ partition }}
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
export PROJECT_DIR={{ project_dir }}
# Setup environment
cd $PROJECT_DIR
[ -f .env ] && source .env
source .venv/bin/activate
uv sync --all-extras
uv run rl @ {{ config_path }}
@@ -0,0 +1,20 @@
#!/bin/bash
#SBATCH --job-name={{ job_name }}
#SBATCH --nodes=1
#SBATCH --ntasks-per-node=1
#SBATCH --gres=gpu:{{ gpus_per_node }}
#SBATCH --exclusive
#SBATCH --partition={{ partition }}
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
export PROJECT_DIR={{ project_dir }}
# Setup environment
cd $PROJECT_DIR
[ -f .env ] && source .env
source .venv/bin/activate
uv sync --all-extras
uv run sft @ {{ config_path }}
+30 -14
View File
@@ -13,11 +13,6 @@ AttnImplementation: TypeAlias = Literal["sdpa", "flash_attention_2", "flash_atte
# to attempt installing a kernel from hub.
_ATTN_ALIASES = {"flash_attention_4": "fa4"}
MOE_MODEL_MAPS = {
"Qwen/Qwen3-30B-A3B": "Jackmin108/Qwen3-30B-A3B-Fast",
"moonshotai/Moonlight-16B-A3B-Instruct": "Jackmin108/Moonlight-16B-A3B-Instruct-Fast",
}
class ActivationCheckpointConfig(BaseConfig):
"""Configures activation checkpointing."""
@@ -298,13 +293,6 @@ class ModelConfig(BaseConfig):
data["attn"] = _ATTN_ALIASES[data["attn"]]
return data
@model_validator(mode="after")
def _map_model_name_for_moe(self):
"""Map model name if it exists in MOE_MODEL_MAPS."""
if self.name in MOE_MODEL_MAPS:
self.name = MOE_MODEL_MAPS[self.name]
return self
@model_validator(mode="after")
def trust_remote_code_only_with_hf(self):
"""Trust remote code only if the model is from HF."""
@@ -415,7 +403,9 @@ class CosineSchedulerConfig(BaseModel):
min_lr: Annotated[float, Field(ge=0, description="Minimum learning rate to converge to.")] = 0.0
SchedulerConfigType: TypeAlias = ConstantSchedulerConfig | LinearSchedulerConfig | CosineSchedulerConfig
SchedulerConfig: TypeAlias = Annotated[
ConstantSchedulerConfig | LinearSchedulerConfig | CosineSchedulerConfig, Field(discriminator="type")
]
class BaseOptimizerConfig(BaseModel):
@@ -449,7 +439,7 @@ class MuonConfig(BaseOptimizerConfig):
] = 0.95
OptimizerConfigType: TypeAlias = SGDConfig | AdamWConfig | MuonConfig
OptimizerConfig: TypeAlias = Annotated[SGDConfig | AdamWConfig | MuonConfig, Field(discriminator="type")]
class WeightCheckpointConfig(BaseConfig):
@@ -477,6 +467,32 @@ class WeightCheckpointConfig(BaseConfig):
] = False
class SlurmConfig(BaseConfig):
"""SLURM-specific configuration shared between RL and SFT."""
job_name: Annotated[str, Field(description="The SLURM job name.")] = "prime-rl"
project_dir: Annotated[
Path,
Field(description="Path to the project root. Used to source .env, activate .venv, and run uv sync."),
] = Path(".")
template_path: Annotated[
Path | None,
Field(
description="The path to the SLURM template file. If None, will use the default single-node/multi-node template."
),
] = None
partition: Annotated[
str, Field(description="The SLURM partition to use. Will be passed as #SBATCH --partition.")
] = "cluster"
dry_run: Annotated[bool, Field(description="Only generate the SLURM script and configs without submitting.")] = (
False
)
class CheckpointConfig(BaseConfig):
"""Configures checkpointing the full model, optimizer and training state for resuming training."""
+3
View File
@@ -11,6 +11,7 @@ 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.glm_moe_dsa import GlmMoeDsaConfig, GlmMoeDsaForCausalLM
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.minimax_m2 import MiniMaxM2Config, MiniMaxM2ForCausalLM
@@ -19,6 +20,7 @@ from prime_rl.trainer.models.qwen3_moe import Qwen3MoeConfig, Qwen3MoeForCausalL
# Make custom config discoverable by AutoConfig
AutoConfig.register("afmoe", AfmoeConfig, exist_ok=True)
AutoConfig.register("glm4_moe", Glm4MoeConfig, exist_ok=True)
AutoConfig.register("glm_moe_dsa", GlmMoeDsaConfig, exist_ok=True)
AutoConfig.register("minimax_m2", MiniMaxM2Config, exist_ok=True)
AutoConfig.register("qwen3_moe", Qwen3MoeConfig, exist_ok=True)
@@ -26,6 +28,7 @@ _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(GlmMoeDsaConfig, GlmMoeDsaForCausalLM, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING.register(MiniMaxM2Config, MiniMaxM2ForCausalLM, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3MoeConfig, Qwen3MoeForCausalLM, exist_ok=True)
@@ -189,6 +189,19 @@ class AfmoeFlashAttention(AfmoeAttentionBase):
if self._flash_attn_version == 4:
self._flash_attn_call = torch._dynamo.disable(self.func)
def _compute_attention(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, cu_seqlens, max_seqlen):
"""Run the flash attention kernel. q/k/v are [total_tokens, heads, dim]."""
args = [q, k, v, cu_seqlens, cu_seqlens]
if self._flash_attn_version != 4:
args.extend([max_seqlen, max_seqlen])
kwargs: dict = {"causal": True}
if self.sliding_window is not None:
kwargs["window_size"] = (self.sliding_window - 1, 0)
out = self._flash_attn_call(*args, **kwargs)
if isinstance(out, tuple):
out = out[0]
return out
def forward(
self,
hidden_states: torch.Tensor,
@@ -209,7 +222,6 @@ class AfmoeFlashAttention(AfmoeAttentionBase):
key_states = self.k_norm(key_states)
if self.is_local_attention:
# apply_rotary_pos_emb expects [batch, heads, seq, dim]
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
cos, sin = position_embeddings
@@ -217,18 +229,7 @@ class AfmoeFlashAttention(AfmoeAttentionBase):
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
# Flash attention varlen expects [total_tokens, heads, dim]
args = [query_states[0], key_states[0], value_states[0], cu_seqlens, cu_seqlens]
if self._flash_attn_version != 4:
args.extend([max_seqlen, max_seqlen])
kwargs: dict = {"causal": True}
if self.sliding_window is not None:
kwargs["window_size"] = (self.sliding_window - 1, 0)
out = self._flash_attn_call(*args, **kwargs)
if isinstance(out, tuple):
out = out[0]
out = self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
attn_output = out.contiguous().view(*input_shape, -1)
attn_output = attn_output * torch.sigmoid(gate_states)
@@ -0,0 +1,13 @@
from prime_rl.trainer.models.glm_moe_dsa.configuration_glm_moe_dsa import GlmMoeDsaConfig
from prime_rl.trainer.models.glm_moe_dsa.modeling_glm_moe_dsa import (
GlmMoeDsaForCausalLM,
GlmMoeDsaModel,
GlmMoeDsaPreTrainedModel,
)
__all__ = [
"GlmMoeDsaConfig",
"GlmMoeDsaForCausalLM",
"GlmMoeDsaModel",
"GlmMoeDsaPreTrainedModel",
]
@@ -0,0 +1,209 @@
import warnings
from transformers.configuration_utils import PretrainedConfig
class GlmMoeDsaConfig(PretrainedConfig):
r"""
Configuration class for the GLM-5 (GlmMoeDsa) model.
GLM-5 uses DeepSeek V3.2-style Multi-head Latent Attention (MLA) with LoRA-compressed
KV projections, combined with Mixture-of-Experts feed-forward layers.
Args:
vocab_size (`int`, defaults to 154880):
Vocabulary size.
hidden_size (`int`, defaults to 6144):
Dimension of the hidden representations.
intermediate_size (`int`, defaults to 12288):
Dimension of the dense MLP representations.
moe_intermediate_size (`int`, defaults to 2048):
Dimension of the MoE expert representations.
num_hidden_layers (`int`, defaults to 78):
Number of hidden layers in the Transformer decoder.
num_attention_heads (`int`, defaults to 64):
Number of attention heads.
num_key_value_heads (`int`, defaults to 64):
Number of key-value heads (after kv_b_proj up-projection).
n_shared_experts (`int`, defaults to 1):
Number of shared experts.
n_routed_experts (`int`, defaults to 256):
Number of routed experts.
routed_scaling_factor (`float`, defaults to 2.5):
Scaling factor for routed experts.
kv_lora_rank (`int`, defaults to 512):
Rank of the LoRA compression for key-value projections.
q_lora_rank (`int`, defaults to 2048):
Rank of the LoRA compression for query projections.
qk_rope_head_dim (`int`, defaults to 64):
Dimension of query/key heads that use rotary position embeddings.
v_head_dim (`int`, defaults to 256):
Dimension of value heads.
qk_nope_head_dim (`int`, defaults to 192):
Dimension of query/key heads that don't use rotary position embeddings.
n_group (`int`, defaults to 1):
Number of groups for routed experts.
topk_group (`int`, defaults to 1):
Number of selected groups per token.
num_experts_per_tok (`int`, defaults to 8):
Number of active experts per token.
first_k_dense_replace (`int`, defaults to 3):
Number of initial layers that use dense MLP instead of MoE.
norm_topk_prob (`bool`, defaults to `True`):
Whether to normalize the top-k routing probabilities.
hidden_act (`str`, defaults to `"silu"`):
Activation function in the feed-forward layers.
max_position_embeddings (`int`, defaults to 202752):
Maximum sequence length.
initializer_range (`float`, defaults to 0.02):
Standard deviation for weight initialization.
rms_norm_eps (`float`, defaults to 1e-5):
Epsilon for RMS normalization.
rope_interleave (`bool`, defaults to `True`):
Whether to use interleaved (non-neox) RoPE style.
attention_bias (`bool`, defaults to `False`):
Whether to use bias in attention projections.
attention_dropout (`float`, defaults to 0.0):
Dropout for attention probabilities.
index_n_heads (`int`, defaults to 32):
Number of heads used by the sparse indexer.
index_head_dim (`int`, defaults to 128):
Head dimension used by the sparse indexer.
indexer_rope_interleave (`bool`, defaults to `True`):
Whether to use interleaved RoPE style in the sparse indexer.
index_topk (`int`, defaults to 2048):
Number of top tokens selected by the sparse indexer.
scoring_func (`str`, defaults to `"sigmoid"`):
Scoring function for MoE router. Must match the vLLM inference
server's expectation (vLLM defaults to ``"softmax"`` when this
field is absent from the config).
topk_method (`str`, defaults to `"noaux_tc"`):
MoE routing top-k method used by GLM-5 checkpoints.
use_grouped_mm (`bool`, defaults to `True`):
Whether to use grouped matrix multiplication for MoE.
"""
model_type = "glm_moe_dsa"
keys_to_ignore_at_inference = ["past_key_values"]
attribute_map = {"num_local_experts": "n_routed_experts"}
base_model_tp_plan = {
"layers.*.self_attn.o_proj": "rowwise",
"layers.*.mlp.experts.*.gate_proj": "colwise",
"layers.*.mlp.experts.*.up_proj": "colwise",
"layers.*.mlp.experts.*.down_proj": "rowwise",
"layers.*.mlp.gate_proj": "colwise",
"layers.*.mlp.up_proj": "colwise",
"layers.*.mlp.down_proj": "rowwise",
}
base_model_pp_plan = {
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
"layers": (["hidden_states"], ["hidden_states"]),
"norm": (["hidden_states"], ["hidden_states"]),
}
def __init__(
self,
vocab_size=154880,
hidden_size=6144,
intermediate_size=12288,
moe_intermediate_size=2048,
num_hidden_layers=78,
num_attention_heads=64,
num_key_value_heads=64,
n_shared_experts=1,
n_routed_experts=256,
routed_scaling_factor=2.5,
kv_lora_rank=512,
q_lora_rank=2048,
qk_rope_head_dim=64,
v_head_dim=256,
qk_nope_head_dim=192,
n_group=1,
topk_group=1,
num_experts_per_tok=8,
first_k_dense_replace=3,
norm_topk_prob=True,
hidden_act="silu",
max_position_embeddings=202752,
initializer_range=0.02,
rms_norm_eps=1e-5,
use_cache=True,
tie_word_embeddings=False,
rope_interleave=True,
rope_parameters=None,
rope_theta=10000.0,
mlp_layer_types=None,
attention_bias=False,
attention_dropout=0.0,
index_n_heads=32,
index_head_dim=128,
indexer_rope_interleave=True,
pad_token_id=154820,
index_topk=2048,
scoring_func="sigmoid",
topk_method="noaux_tc",
use_grouped_mm=True,
**kwargs,
):
self.vocab_size = vocab_size
self.max_position_embeddings = max_position_embeddings
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.moe_intermediate_size = moe_intermediate_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
# MLA dimensions
self.kv_lora_rank = kv_lora_rank
self.q_lora_rank = q_lora_rank
self.qk_rope_head_dim = qk_rope_head_dim
self.v_head_dim = v_head_dim
self.qk_nope_head_dim = qk_nope_head_dim
self.qk_head_dim = qk_nope_head_dim + qk_rope_head_dim
self.head_dim = qk_rope_head_dim
# MoE
self.n_shared_experts = n_shared_experts
self.n_routed_experts = n_routed_experts
self.routed_scaling_factor = routed_scaling_factor
self.n_group = n_group
self.topk_group = topk_group
self.num_experts_per_tok = num_experts_per_tok
self.first_k_dense_replace = first_k_dense_replace
self.norm_topk_prob = norm_topk_prob
# MLP layer types: per-layer dense/sparse dispatch
if mlp_layer_types is None:
mlp_layer_types = ["dense"] * min(first_k_dense_replace, num_hidden_layers) + ["sparse"] * max(
0, num_hidden_layers - first_k_dense_replace
)
self.mlp_layer_types = mlp_layer_types
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.rms_norm_eps = rms_norm_eps
self.use_cache = use_cache
self.rope_interleave = rope_interleave
self.rope_parameters = rope_parameters
self.rope_theta = rope_theta
self.attention_bias = attention_bias
self.attention_dropout = attention_dropout
self.index_n_heads = index_n_heads
self.index_head_dim = index_head_dim
self.indexer_rope_interleave = indexer_rope_interleave
self.index_topk = index_topk
self.scoring_func = scoring_func
self.topk_method = topk_method
self.use_grouped_mm = use_grouped_mm
self.pad_token_id = pad_token_id
if not self.use_grouped_mm:
warnings.warn("not using grouped mm for moe is very slow, should only be used for debugging")
super().__init__(
pad_token_id=pad_token_id,
tie_word_embeddings=tie_word_embeddings,
**kwargs,
)
@@ -0,0 +1,144 @@
import torch
from torch import Tensor
def get_max_layer_num(state_dict: dict[str, Tensor]) -> int:
return max(int(i.split(".")[2]) for i in state_dict.keys() if "model.layers." in i) + 1
def _is_moe_layer(state_dict: dict[str, Tensor], layer_idx: int) -> bool:
"""Check if a layer is an MoE layer by looking for the router gate weight."""
return f"model.layers.{layer_idx}.mlp.gate.weight" in state_dict
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int):
i = layer_idx
if not _is_moe_layer(state_dict, i):
return
# Router: gate.weight -> router.gate.weight
state_dict[f"model.layers.{i}.mlp.router.gate.weight"] = state_dict[f"model.layers.{i}.mlp.gate.weight"]
del state_dict[f"model.layers.{i}.mlp.gate.weight"]
# Routed experts: fused or per-expert format -> stacked w1/w2/w3
if f"model.layers.{i}.mlp.experts.gate_up_proj" in state_dict:
gate_up_proj = state_dict[f"model.layers.{i}.mlp.experts.gate_up_proj"]
down_proj = state_dict[f"model.layers.{i}.mlp.experts.down_proj"]
num_experts, fused_dim, dim = gate_up_proj.shape
moe_dim = fused_dim // 2
w1 = gate_up_proj[:, :moe_dim, :]
w3 = gate_up_proj[:, moe_dim:, :]
w2 = down_proj
del state_dict[f"model.layers.{i}.mlp.experts.gate_up_proj"]
del state_dict[f"model.layers.{i}.mlp.experts.down_proj"]
else:
num_experts = len([j for j in state_dict.keys() if f"model.layers.{i}.mlp.experts" in j]) // 3
if num_experts == 0:
return
dim, moe_dim = state_dict[f"model.layers.{i}.mlp.experts.0.down_proj.weight"].shape
dtype = state_dict[f"model.layers.{i}.mlp.experts.0.down_proj.weight"].dtype
w1 = torch.empty((num_experts, moe_dim, dim), dtype=dtype)
w2 = torch.empty((num_experts, dim, moe_dim), dtype=dtype)
w3 = torch.empty((num_experts, moe_dim, dim), dtype=dtype)
for j in range(num_experts):
w1[j].copy_(state_dict[f"model.layers.{i}.mlp.experts.{j}.gate_proj.weight"])
w2[j].copy_(state_dict[f"model.layers.{i}.mlp.experts.{j}.down_proj.weight"])
w3[j].copy_(state_dict[f"model.layers.{i}.mlp.experts.{j}.up_proj.weight"])
del state_dict[f"model.layers.{i}.mlp.experts.{j}.gate_proj.weight"]
del state_dict[f"model.layers.{i}.mlp.experts.{j}.down_proj.weight"]
del state_dict[f"model.layers.{i}.mlp.experts.{j}.up_proj.weight"]
state_dict[f"model.layers.{i}.mlp.experts.w1"] = w1
state_dict[f"model.layers.{i}.mlp.experts.w2"] = w2
state_dict[f"model.layers.{i}.mlp.experts.w3"] = w3
# Shared experts
state_dict[f"model.layers.{i}.mlp.shared_expert.w1"] = state_dict[
f"model.layers.{i}.mlp.shared_experts.gate_proj.weight"
]
state_dict[f"model.layers.{i}.mlp.shared_expert.w2"] = state_dict[
f"model.layers.{i}.mlp.shared_experts.down_proj.weight"
]
state_dict[f"model.layers.{i}.mlp.shared_expert.w3"] = state_dict[
f"model.layers.{i}.mlp.shared_experts.up_proj.weight"
]
del state_dict[f"model.layers.{i}.mlp.shared_experts.gate_proj.weight"]
del state_dict[f"model.layers.{i}.mlp.shared_experts.down_proj.weight"]
del state_dict[f"model.layers.{i}.mlp.shared_experts.up_proj.weight"]
# Expert bias for load balancing
state_dict[f"model.layers.{i}.mlp.expert_bias"] = state_dict[f"model.layers.{i}.mlp.gate.e_score_correction_bias"]
del state_dict[f"model.layers.{i}.mlp.gate.e_score_correction_bias"]
def convert_hf_to_tt_moe(state_dict: dict[str, Tensor]):
num_layers = get_max_layer_num(state_dict)
for i in range(num_layers):
convert_hf_layer_to_tt(state_dict, i)
def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_index: int):
i = layer_index
# Expert bias
if f"model.layers.{i}.mlp.expert_bias" in state_dict:
state_dict[f"model.layers.{i}.mlp.gate.e_score_correction_bias"] = state_dict[
f"model.layers.{i}.mlp.expert_bias"
]
del state_dict[f"model.layers.{i}.mlp.expert_bias"]
if f"model.layers.{i}.mlp.tokens_per_expert" in state_dict:
del state_dict[f"model.layers.{i}.mlp.tokens_per_expert"]
# Shared experts
if f"model.layers.{i}.mlp.shared_expert.w1" in state_dict:
state_dict[f"model.layers.{i}.mlp.shared_experts.gate_proj.weight"] = state_dict[
f"model.layers.{i}.mlp.shared_expert.w1"
]
state_dict[f"model.layers.{i}.mlp.shared_experts.down_proj.weight"] = state_dict[
f"model.layers.{i}.mlp.shared_expert.w2"
]
state_dict[f"model.layers.{i}.mlp.shared_experts.up_proj.weight"] = state_dict[
f"model.layers.{i}.mlp.shared_expert.w3"
]
if state_dict[f"model.layers.{i}.mlp.shared_experts.up_proj.weight"].shape[0] == 1:
state_dict[f"model.layers.{i}.mlp.shared_experts.up_proj.weight"] = state_dict[
f"model.layers.{i}.mlp.shared_experts.up_proj.weight"
][0]
state_dict[f"model.layers.{i}.mlp.shared_experts.down_proj.weight"] = state_dict[
f"model.layers.{i}.mlp.shared_experts.down_proj.weight"
][0]
state_dict[f"model.layers.{i}.mlp.shared_experts.gate_proj.weight"] = state_dict[
f"model.layers.{i}.mlp.shared_experts.gate_proj.weight"
][0]
del state_dict[f"model.layers.{i}.mlp.shared_expert.w1"]
del state_dict[f"model.layers.{i}.mlp.shared_expert.w2"]
del state_dict[f"model.layers.{i}.mlp.shared_expert.w3"]
# Router
if f"model.layers.{i}.mlp.router.gate.weight" in state_dict:
state_dict[f"model.layers.{i}.mlp.gate.weight"] = state_dict[f"model.layers.{i}.mlp.router.gate.weight"]
del state_dict[f"model.layers.{i}.mlp.router.gate.weight"]
# Routed experts - convert to per-expert format (compatible with vLLM and transformers)
w1 = state_dict.pop(f"model.layers.{i}.mlp.experts.w1") # (num_experts, moe_dim, dim)
w2 = state_dict.pop(f"model.layers.{i}.mlp.experts.w2") # (num_experts, dim, moe_dim)
w3 = state_dict.pop(f"model.layers.{i}.mlp.experts.w3") # (num_experts, moe_dim, dim)
num_experts = w1.shape[0]
for j in range(num_experts):
state_dict[f"model.layers.{i}.mlp.experts.{j}.gate_proj.weight"] = w1[j]
state_dict[f"model.layers.{i}.mlp.experts.{j}.down_proj.weight"] = w2[j]
state_dict[f"model.layers.{i}.mlp.experts.{j}.up_proj.weight"] = w3[j]
def convert_tt_to_hf_moe(state_dict: dict[str, Tensor]):
num_layers = get_max_layer_num(state_dict)
for i in range(num_layers):
convert_tt_layer_to_hf(state_dict, i)
@@ -0,0 +1,439 @@
import warnings
from typing import Optional, Union
import torch
import torch.nn.functional as F
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
from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs, auto_docstring
from transformers.utils.deprecation import deprecate_kwarg
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.glm_moe_dsa.configuration_glm_moe_dsa import GlmMoeDsaConfig
from prime_rl.trainer.models.glm_moe_dsa.converting_glm_moe_dsa import (
convert_hf_layer_to_tt,
convert_hf_to_tt_moe,
convert_tt_layer_to_hf,
convert_tt_to_hf_moe,
)
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_interleave,
)
try:
from prime_rl.trainer.models.kernels.sparse_mla_bwd import sparse_mla_bwd
from prime_rl.trainer.models.kernels.sparse_mla_fwd import sparse_mla_fwd_interface
except ImportError:
sparse_mla_fwd_interface = None # type: ignore
sparse_mla_bwd = None # type: ignore
from prime_rl.trainer.models.kernels.fp8_indexer import fp8_indexer
class _SparseMLA(torch.autograd.Function):
"""Autograd wrapper for tilelang sparse MLA forward/backward kernels."""
@staticmethod
def forward(ctx, q, kv, indices, sm_scale):
out, lse = sparse_mla_fwd_interface(q, kv, indices, sm_scale=sm_scale)
ctx.save_for_backward(q, kv, out, indices, lse)
ctx.sm_scale = sm_scale
return out
@staticmethod
def backward(ctx, do):
q, kv, out, indices, lse = ctx.saved_tensors
dq, dkv = sparse_mla_bwd(q, kv, out, do.contiguous(), indices, lse, sm_scale=ctx.sm_scale)
return dq, dkv, None, None
class LayerNorm(nn.Module):
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__()
self.dim = dim
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim, dtype=torch.float32))
self.bias = nn.Parameter(torch.zeros(dim, dtype=torch.float32))
def forward(self, x: torch.Tensor):
return F.layer_norm(x.float(), (self.dim,), self.weight.float(), self.bias.float(), self.eps).type_as(x)
class Indexer(nn.Module):
def __init__(self, config: GlmMoeDsaConfig):
super().__init__()
if config.q_lora_rank is None:
raise ValueError("Sparse indexer requires q_lora_rank to be set")
self.n_head = config.index_n_heads
self.head_dim = config.index_head_dim
self.rope_dim = config.qk_rope_head_dim
self.wq_b = nn.Linear(config.q_lora_rank, self.n_head * self.head_dim, bias=False)
self.wk = nn.Linear(config.hidden_size, self.head_dim, bias=config.attention_bias)
self.k_norm = LayerNorm(dim=self.head_dim, eps=1e-6)
self.weights_proj = nn.Linear(config.hidden_size, self.n_head, bias=False)
self.weight_scale = (self.head_dim**-0.5) * (self.n_head**-0.5)
@torch.no_grad()
def compute_sparse_indices(
self,
hidden_states: torch.Tensor,
q_latent: torch.Tensor,
ks: torch.Tensor,
ke: torch.Tensor,
index_topk: int,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
) -> torch.Tensor:
total_tokens = hidden_states.shape[1]
assert index_topk % 64 == 0, f"index_topk must be divisible by 64 (block_I), got {index_topk}"
q_idx = self.wq_b(q_latent[0]).view(total_tokens, self.n_head, self.head_dim)
k_idx = self.k_norm(self.wk(hidden_states[0]))
w = self.weights_proj(hidden_states[0])
q_pe = q_idx[..., : self.rope_dim]
q_nope = q_idx[..., self.rope_dim :]
k_pe = k_idx[..., : self.rope_dim]
k_nope = k_idx[..., self.rope_dim :]
cos, sin = position_embeddings
q_pe = q_pe.unsqueeze(0).transpose(1, 2)
k_pe = k_pe.unsqueeze(0).unsqueeze(1)
q_pe, k_pe = apply_rotary_pos_emb_interleave(q_pe, k_pe, cos, sin)
q_pe = q_pe.transpose(1, 2).squeeze(0)
k_pe = k_pe.squeeze(1).squeeze(0)
q_idx = torch.cat([q_pe, q_nope], dim=-1)
k_idx = torch.cat([k_pe, k_nope], dim=-1)
indices = fp8_indexer(q_idx, k_idx, w, ks, ke, index_topk, self.weight_scale)
return indices.view(1, total_tokens, 1, index_topk)
class GlmMoeDsaAttention(nn.Module):
def __init__(self, config: GlmMoeDsaConfig):
super().__init__()
self.config = config
self.num_heads = config.num_attention_heads
self.kv_lora_rank = config.kv_lora_rank
self.qk_rope_head_dim = config.qk_rope_head_dim
self.qk_nope_head_dim = config.qk_nope_head_dim
self.qk_head_dim = config.qk_head_dim
self.v_head_dim = config.v_head_dim
self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=config.attention_bias)
self.q_a_layernorm = RMSNorm(RMSNormConfig(hidden_size=config.q_lora_rank, eps=config.rms_norm_eps))
self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.qk_head_dim, bias=False)
self.kv_a_proj_with_mqa = nn.Linear(
config.hidden_size,
self.kv_lora_rank + self.qk_rope_head_dim,
bias=config.attention_bias,
)
self.kv_a_layernorm = RMSNorm(RMSNormConfig(hidden_size=self.kv_lora_rank, eps=config.rms_norm_eps))
self.kv_b_proj = nn.Linear(
self.kv_lora_rank,
self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
bias=False,
)
self.o_proj = nn.Linear(self.num_heads * self.v_head_dim, config.hidden_size, bias=config.attention_bias)
self.indexer = Indexer(config)
self.scaling = self.qk_head_dim ** (-0.5)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
ks: torch.Tensor | None = None,
ke: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor | None]:
batch_size, total_tokens, _ = hidden_states.shape
q_latent = self.q_a_layernorm(self.q_a_proj(hidden_states))
q_full = self.q_b_proj(q_latent).view(batch_size, total_tokens, self.num_heads, self.qk_head_dim)
q_nope, q_rope = q_full.split([self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
k_compressed, k_rope = compressed_kv.split([self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
k_compressed_normed = self.kv_a_layernorm(k_compressed)
q_rope_r = q_rope.transpose(1, 2)
k_rope_r = k_rope.unsqueeze(1)
cos, sin = position_embeddings
q_rope_r, k_rope_r = apply_rotary_pos_emb_interleave(q_rope_r, k_rope_r, cos, sin)
q_rope = q_rope_r.transpose(1, 2)
k_rope = k_rope_r.squeeze(1)
indices = self.indexer.compute_sparse_indices(
hidden_states, q_latent, ks, ke, self.config.index_topk, position_embeddings
)
# KV absorption
kv_b_w = self.kv_b_proj.weight.view(self.num_heads, self.qk_nope_head_dim + self.v_head_dim, self.kv_lora_rank)
w_k_nope = kv_b_w[:, : self.qk_nope_head_dim, :]
w_v = kv_b_w[:, self.qk_nope_head_dim :, :]
q_absorbed = torch.einsum("bshd,hdk->bshk", q_nope, w_k_nope)
sparse_q = torch.cat([q_absorbed, q_rope], dim=-1)
sparse_kv = torch.cat([k_compressed_normed, k_rope], dim=-1).unsqueeze(2)
# Sentinel zero-token so padded indices (= total_tokens) are in-bounds
sentinel = torch.zeros(batch_size, 1, 1, sparse_kv.shape[-1], dtype=sparse_kv.dtype, device=sparse_kv.device)
sparse_kv = torch.cat([sparse_kv, sentinel], dim=1)
out = _SparseMLA.apply(sparse_q, sparse_kv, indices, self.scaling)
# Un-absorb
out = torch.einsum("bshk,hdk->bshd", out, w_v)
out = out.reshape(batch_size, total_tokens, -1)
return self.o_proj(out), None
class GlmMoeDsaDecoderLayer(GradientCheckpointingLayer):
def __init__(self, config: GlmMoeDsaConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = GlmMoeDsaAttention(config)
moe_args = MoEArgs(
num_experts=config.n_routed_experts,
num_shared_experts=config.n_shared_experts,
score_func="sigmoid",
route_norm=config.norm_topk_prob,
route_scale=config.routed_scaling_factor,
score_before_experts=False,
top_k=config.num_experts_per_tok,
load_balance_coeff=1e-3,
use_grouped_mm=config.use_grouped_mm,
)
mlp_config = MLPConfig(
hidden_size=config.hidden_size,
intermediate_size=config.intermediate_size,
gate_act=config.hidden_act,
bias=False,
)
if layer_idx >= config.first_k_dense_replace:
self.mlp = MoE(moe_args, dim=config.hidden_size, hidden_dim=config.moe_intermediate_size)
else:
self.mlp = MLP(mlp_config)
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))
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
ks: Optional[torch.Tensor] = None,
ke: Optional[torch.Tensor] = None,
) -> torch.Tensor:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
hidden_states, _ = self.self_attn(
hidden_states=hidden_states,
position_embeddings=position_embeddings,
ks=ks,
ke=ke,
)
hidden_states = residual + hidden_states
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = residual + hidden_states
return hidden_states
@auto_docstring
class GlmMoeDsaPreTrainedModel(PreTrainedModelPrimeRL):
config: GlmMoeDsaConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["GlmMoeDsaDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
_can_compile_fullgraph = False
_supports_attention_backend = True
_can_record_outputs = {
"hidden_states": GlmMoeDsaDecoderLayer,
}
def _init_weights(self, module):
super()._init_weights(module)
@classmethod
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return any("mlp.experts.1.up_proj" in name or "mlp.experts.gate_up_proj" in name for name in state_dict.keys())
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, 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, Tensor]) -> dict[str, Tensor]:
convert_tt_to_hf_moe(state_dict)
return state_dict
@classmethod
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
convert_hf_to_tt_moe(state_dict)
return state_dict
@classmethod
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
convert_tt_layer_to_hf(state_dict, layer_idx)
return state_dict
@classmethod
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
convert_hf_layer_to_tt(state_dict, layer_idx)
return state_dict
@auto_docstring
class GlmMoeDsaModel(GlmMoeDsaPreTrainedModel):
def __init__(self, config: GlmMoeDsaConfig):
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(
[GlmMoeDsaDecoderLayer(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))
rope_parameters = getattr(config, "rope_parameters", None) or {}
rope_type = rope_parameters.get("rope_type", "default") if isinstance(rope_parameters, dict) else "default"
rotary_config = RotaryEmbeddingConfig(
max_position_embeddings=config.max_position_embeddings,
rope_type=rope_type,
model_config=config,
)
self.rotary_emb = RotaryEmbedding(rotary_config)
self.gradient_checkpointing = False
self.post_init()
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
) -> BaseModelOutputWithPast:
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: torch.Tensor = self.embed_tokens(input_ids)
flat_position_ids = position_ids.view(-1)
S = flat_position_ids.shape[0]
ks = torch.arange(S, dtype=torch.int32, device=flat_position_ids.device) - flat_position_ids.to(torch.int32)
ke = torch.arange(1, S + 1, dtype=torch.int32, device=flat_position_ids.device)
hidden_states = inputs_embeds
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
hidden_states = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
ks=ks,
ke=ke,
)
hidden_states = self.norm(hidden_states)
return BaseModelOutputWithPast(last_hidden_state=hidden_states)
@auto_docstring
class GlmMoeDsaForCausalLM(GlmMoeDsaPreTrainedModel, 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 = GlmMoeDsaModel(config)
self.vocab_size = config.vocab_size
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
warnings.warn("GlmMoeDsaForCausalLM is experimental, higher trainer<->inference KL mismatch may be observed.")
warnings.warn("`model.attn` is ignored, GlmMoeDsa uses only sparse attention.")
self.post_init()
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = 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,
temperature: Optional[torch.Tensor] = None,
**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.
temperature (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Per-token temperatures for logprobs/entropy computation when `labels` are provided.
"""
assert use_cache is None, "use_cache is not supported for custom glm_moe_dsa for now"
assert past_key_values is None, "past_key_values is not supported for custom glm_moe_dsa for now"
if position_ids is None:
if inputs_embeds is not None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
else:
position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).unsqueeze(0)
outputs: BaseModelOutputWithPast = self.model(
input_ids=input_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
)
hidden_states = outputs.last_hidden_state
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__ = ["GlmMoeDsaConfig", "GlmMoeDsaPreTrainedModel", "GlmMoeDsaModel", "GlmMoeDsaForCausalLM"]
@@ -0,0 +1,236 @@
"""Triton FP8 indexer kernel for DSA sparse token selection.
Scoring formula: I_{t,s} = Σ_j w_{t,j} · ReLU(q_{t,j} · k_s)
FP8 quantization vendored from vLLM (Apache 2.0).
"""
import torch
import triton
import triton.language as tl
FP8_MAX = 448.0
FP8_MIN = -448.0
FP8_EPS = 1e-10
@triton.jit
def _per_token_group_quant_fp8(
y_ptr,
y_q_ptr,
y_s_ptr,
group_size,
y_num_columns,
y_row_stride,
eps,
fp8_min,
fp8_max,
use_ue8m0: tl.constexpr,
BLOCK: tl.constexpr,
):
groups_per_row = y_num_columns // group_size
g_id = tl.program_id(0)
row = g_id // groups_per_row
row_g_id = g_id % groups_per_row
y_ptr_offset = (row.to(tl.int64) * y_row_stride) + (row_g_id.to(tl.int64) * group_size)
y_ptr += y_ptr_offset
y_q_ptr_offset = g_id.to(tl.int64) * group_size
y_q_ptr += y_q_ptr_offset
y_s_ptr += g_id
cols = tl.arange(0, BLOCK)
mask = cols < group_size
y = tl.load(y_ptr + cols, mask=mask, other=0.0).to(tl.float32)
_absmax = tl.maximum(tl.max(tl.abs(y)), eps)
scale_raw = _absmax / fp8_max
y_s = tl.math.exp2(tl.ceil(tl.log2(scale_raw))) if use_ue8m0 else scale_raw
y_q = tl.clamp(y / y_s, fp8_min, fp8_max).to(y_q_ptr.dtype.element_ty)
tl.store(y_q_ptr + cols, y_q, mask=mask)
tl.store(y_s_ptr, y_s)
def per_token_group_quant_fp8(
x: torch.Tensor, group_size: int, use_ue8m0: bool = True
) -> tuple[torch.Tensor, torch.Tensor]:
assert x.shape[-1] % group_size == 0
assert x.stride(-1) == 1
x_q = torch.empty(x.shape, device=x.device, dtype=torch.float8_e4m3fn)
shape = x.shape[:-1] + (x.shape[-1] // group_size,)
x_s = torch.empty(shape, device=x.device, dtype=torch.float32)
M = x.numel() // group_size
N = group_size
BLOCK = triton.next_power_of_2(N)
num_warps = min(max(BLOCK // 256, 1), 8)
_per_token_group_quant_fp8[(M,)](
x,
x_q,
x_s,
group_size,
x.shape[-1],
x.stride(-2),
FP8_EPS,
FP8_MIN,
FP8_MAX,
use_ue8m0=use_ue8m0,
BLOCK=BLOCK,
num_warps=num_warps,
num_stages=1,
)
return x_q, x_s
@triton.autotune(
configs=[
triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=4, num_stages=2),
triton.Config({"BLOCK_M": 64, "BLOCK_N": 128}, num_warps=4, num_stages=2),
triton.Config({"BLOCK_M": 128, "BLOCK_N": 64}, num_warps=8, num_stages=2),
triton.Config({"BLOCK_M": 128, "BLOCK_N": 128}, num_warps=8, num_stages=2),
triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=8, num_stages=3),
triton.Config({"BLOCK_M": 64, "BLOCK_N": 128}, num_warps=8, num_stages=3),
],
key=["S"],
)
@triton.jit
def _triton_fp8_indexer_kernel(
Q_fp8,
K_fp8,
K_scales,
W,
Out,
KS,
KE,
S,
stride_qh,
stride_qs,
stride_ks,
stride_ws,
H: tl.constexpr,
D: tl.constexpr,
BLOCK_M: tl.constexpr,
BLOCK_N: tl.constexpr,
):
pid_m = tl.program_id(0)
pid_n = tl.program_id(1)
offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
offs_d = tl.arange(0, D)
mask_m = offs_m < S
mask_n = offs_n < S
ks_vals = tl.load(KS + offs_m, mask=mask_m, other=S)
ke_vals = tl.load(KE + offs_m, mask=mask_m, other=0)
offs_m_64 = offs_m.to(tl.int64)
offs_n_64 = offs_n.to(tl.int64)
out_ptrs = Out + offs_m_64[:, None] * S + offs_n_64[None, :]
out_mask = mask_m[:, None] & mask_n[None, :]
ks_min = tl.min(ks_vals)
ke_max = tl.max(ke_vals)
n_lo = pid_n * BLOCK_N
if n_lo >= ke_max or n_lo + BLOCK_N <= ks_min:
tl.store(out_ptrs, tl.full([BLOCK_M, BLOCK_N], float("-inf"), tl.float32), mask=out_mask)
return
# Clamp indices for FP8 loads (can't use mask+other with fp8 dtype)
offs_n_safe = tl.minimum(offs_n, S - 1)
offs_m_safe = tl.minimum(offs_m, S - 1)
k_block = tl.load(K_fp8 + offs_n_safe[:, None] * stride_ks + offs_d[None, :])
k_sc = tl.load(K_scales + offs_n_safe, mask=mask_n, other=0.0).to(tl.float32)
acc = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)
for h in range(H):
q_h = tl.load(Q_fp8 + h * stride_qh + offs_m_safe[:, None] * stride_qs + offs_d[None, :])
w_h = tl.load(W + offs_m * stride_ws + h, mask=mask_m, other=0.0).to(tl.float32)
scores = tl.dot(q_h, tl.trans(k_block)).to(tl.float32)
scores = tl.maximum(scores, 0.0) * k_sc[None, :]
acc += scores * w_h[:, None]
valid = (offs_n[None, :] >= ks_vals[:, None]) & (offs_n[None, :] < ke_vals[:, None])
acc = tl.where(valid, acc, float("-inf"))
tl.store(out_ptrs, acc, mask=out_mask)
def fp8_indexer(q, k, w, ks, ke, topk, weight_scale=1.0):
"""Triton FP8 indexer: UE8M0 quantization + fused scoring kernel + topk.
Args:
q: [S, H, D] bf16 query vectors per head
k: [S, D] bf16 key vectors (shared across heads)
w: [S, H] bf16 per-head weights
ks: [S] int32 sequence start per token
ke: [S] int32 causal end per token (= position + 1)
topk: number of top indices to return
weight_scale: constant scaling factor for weights
Returns:
[S, topk] int32 selected token indices per query
"""
# NOTE: We don't use weight scale in this kernel as it produces higher KL mismatch for some reason
# This is not a problem result-wise, as it is a constant multiplier
_weight_scale = weight_scale
S, H, D = q.shape
device = q.device
q_flat = q.reshape(S * H, D).contiguous()
q_fp8, q_scales = per_token_group_quant_fp8(q_flat, group_size=D, use_ue8m0=True)
k_fp8, k_scales = per_token_group_quant_fp8(k.contiguous(), group_size=D, use_ue8m0=True)
q_fp8 = q_fp8.view(S, H, D).permute(1, 0, 2).contiguous()
# Fold q_scale into weights
q_scales = q_scales.view(S, H)
w = w * q_scales
logits = torch.empty(S, S, dtype=torch.float32, device=device)
grid = lambda meta: (
triton.cdiv(S, meta["BLOCK_M"]),
triton.cdiv(S, meta["BLOCK_N"]),
)
_triton_fp8_indexer_kernel[grid](
q_fp8,
k_fp8,
k_scales,
w,
logits,
ks,
ke,
S,
q_fp8.stride(0),
q_fp8.stride(1),
k_fp8.stride(0),
w.stride(0),
H=H,
D=D,
)
actual_topk = min(topk, S)
_, indices = torch.topk(logits, actual_topk, dim=-1)
if actual_topk < topk:
padding = torch.full((S, topk - actual_topk), S, dtype=indices.dtype, device=device)
indices = torch.cat([indices, padding], dim=-1)
# Replace cross-sequence indices with sentinel S (maps to zero-valued KV)
ks_exp = ks.unsqueeze(1).expand_as(indices)
ke_exp = ke.unsqueeze(1).expand_as(indices)
out_of_range = (indices < ks_exp) | (indices >= ke_exp)
indices = indices.masked_fill(out_of_range, S)
return indices.to(torch.int32)
@@ -0,0 +1,286 @@
# Vendored from tile-ai/tilelang (Apache 2.0), modified for dynamic shapes.
import tilelang
import torch
from tilelang import language as T
@tilelang.jit(out_idx=[-1])
def preprocess(
H,
D,
block_ND=32,
num_stages=5,
dtype=T.bfloat16,
accum_dtype=T.float32,
):
assert dtype == T.bfloat16
assert accum_dtype == T.float32
B = T.dynamic("B")
S = T.dynamic("S")
shape = [B, S, H, D]
@T.prim_func
def preprocess_kernel(
O: T.Tensor(shape, dtype),
dO: T.Tensor(shape, dtype),
Delta: T.Tensor([B, S, H], accum_dtype),
):
with T.Kernel(H, T.ceildiv(S, block_ND), B) as (bx, by, bz):
o = T.alloc_fragment([block_ND, block_ND], accum_dtype)
do = T.alloc_fragment([block_ND, block_ND], accum_dtype)
delta = T.alloc_fragment([block_ND], accum_dtype)
acc = T.alloc_fragment([block_ND, block_ND], accum_dtype)
T.clear(acc)
for k in T.Pipelined(T.ceildiv(D, block_ND), num_stages=num_stages):
T.copy(O[bz, by * block_ND : (by + 1) * block_ND, bx, k * block_ND : (k + 1) * block_ND], o)
T.copy(dO[bz, by * block_ND : (by + 1) * block_ND, bx, k * block_ND : (k + 1) * block_ND], do)
for i, j in T.Parallel(block_ND, block_ND):
acc[i, j] += o[i, j] * do[i, j]
T.reduce_sum(acc, delta, 1)
T.copy(delta, Delta[bz, by * block_ND : (by + 1) * block_ND, bx])
return preprocess_kernel
@tilelang.jit(out_idx=[-1])
def postprocess(
D,
D_tail,
kv_group=1,
block_N=64,
threads=128,
dtype=T.bfloat16,
accum_dtype=T.float32,
):
assert dtype == T.bfloat16
assert accum_dtype == T.float32
B = T.dynamic("B")
S_kv = T.dynamic("S_kv")
dkv_shape = [B, S_kv, kv_group, D + D_tail]
@T.prim_func
def postprocess_kernel(
dKV: T.Tensor(dkv_shape, accum_dtype),
dKV_out: T.Tensor(dkv_shape, dtype),
):
with T.Kernel(T.ceildiv(S_kv, block_N), kv_group, B, threads=threads) as (bx, by, bz):
T.copy(
dKV[bz, bx * block_N : (bx + 1) * block_N, by, :],
dKV_out[bz, bx * block_N : (bx + 1) * block_N, by, :],
)
return postprocess_kernel
@tilelang.jit(
out_idx=[-2],
pass_configs={
tilelang.PassConfigKey.TL_DISABLE_TMA_LOWER: True,
tilelang.PassConfigKey.TL_DISABLE_WARP_SPECIALIZED: True,
tilelang.PassConfigKey.TL_ENABLE_AGGRESSIVE_SHARED_MEMORY_MERGE: True,
},
)
def bwd(
H,
D,
D_tail,
topk,
kv_group=1,
sm_scale=None,
is_causal=True,
block_size=32,
num_stages=0,
threads=256,
indices_dtype=T.int32,
dtype=T.bfloat16,
accum_dtype=T.float32,
):
assert is_causal is True, "non-casual is not supported now"
assert topk % block_size == 0, "otherwise will load some index=0 thus causing wrong kv to be loaded"
assert dtype == T.bfloat16
assert accum_dtype == T.float32
assert indices_dtype == T.int32
if sm_scale is None:
sm_scale = (D + D_tail) ** (-0.5)
sm_scale_mul_reciprocal_log2 = sm_scale * 1.44269504 # log2(e)
B = T.dynamic("B")
S = T.dynamic("S")
S_kv = T.dynamic("S_kv")
H_kv = H // kv_group
q_shape = [B, S, H, D + D_tail]
k_shape = [B, S_kv, kv_group, D + D_tail]
o_shape = [B, S, H, D]
indices_shape = [B, S, kv_group, topk]
delta_shape = [B, S, H]
lse_shape = [B, S, H]
H = H_kv
padded_H = max(tilelang.math.next_power_of_2(H_kv), 16)
block_H = min(64, padded_H)
assert padded_H % block_H == 0
NH = padded_H // block_H
BS = block_size
NS = tilelang.cdiv(topk, block_size)
split_store = 2
@T.prim_func
def sparse_mla_bwd_kernel(
Q: T.Tensor(q_shape, dtype),
KV: T.Tensor(k_shape, dtype),
dO: T.Tensor(o_shape, dtype),
Indices: T.Tensor(indices_shape, indices_dtype),
Lse: T.Tensor(lse_shape, accum_dtype),
Delta: T.Tensor(delta_shape, accum_dtype),
dQ: T.Tensor(q_shape, dtype),
dKV: T.Tensor(k_shape, accum_dtype),
):
with T.Kernel(S, B, kv_group * NH, threads=threads) as (s_i, by, bz):
Q_shared = T.alloc_shared([block_H, D], dtype)
Q_tail_shared = T.alloc_shared([block_H, D_tail], dtype)
KV_shared = T.alloc_shared([BS, D], dtype)
KV_tail_shared = T.alloc_shared([BS, D_tail], dtype)
dO_shared = T.alloc_shared([block_H, D], dtype)
mask = T.alloc_fragment([BS], "bool")
P_shared_cast = T.alloc_shared([block_H, BS], dtype)
dP_shared_cast = T.alloc_shared([block_H, BS], dtype)
dQ_shared = T.alloc_shared([block_H, D], dtype)
dQ_tail_shared = T.alloc_shared([block_H, D_tail], dtype)
acc_p = T.alloc_fragment([block_H, BS], accum_dtype)
acc_dp = T.alloc_fragment([block_H, BS], accum_dtype)
acc_dq = T.alloc_fragment([block_H, D], accum_dtype)
acc_dq_tail = T.alloc_fragment([block_H, D_tail], accum_dtype)
acc_dkv = T.alloc_fragment([BS, D], accum_dtype)
acc_dkv_tail = T.alloc_fragment([BS, D_tail], accum_dtype)
acc_dkv_shared = T.alloc_shared([BS // split_store, D], accum_dtype)
acc_dkv_tail_shared = T.alloc_shared([BS // split_store, D_tail], accum_dtype)
max_kv_i = s_i
T.copy(Q[by, s_i, bz * block_H : (bz + 1) * block_H, :D], Q_shared)
T.copy(Q[by, s_i, bz * block_H : (bz + 1) * block_H, D:], Q_tail_shared)
T.copy(dO[by, s_i, bz * block_H : (bz + 1) * block_H, :D], dO_shared)
T.clear(acc_dq)
T.clear(acc_dq_tail)
for i_i in T.Pipelined(NS, num_stages=num_stages):
for bi_i in T.Parallel(BS):
mask[bi_i] = Indices[by, s_i, bz // NH, i_i * BS + bi_i] <= max_kv_i
for h_i, bi_i in T.Parallel(block_H, BS):
acc_p[h_i, bi_i] = T.if_then_else(mask[bi_i], 0, -T.infinity(acc_p.dtype))
for bi_i, d_i in T.Parallel(BS, D):
KV_shared[bi_i, d_i] = KV[by, Indices[by, s_i, bz // NH, i_i * BS + bi_i], bz // NH, d_i]
T.gemm(Q_shared, KV_shared, acc_p, transpose_B=True, policy=T.GemmWarpPolicy.FullCol)
for bi_i, d_i in T.Parallel(BS, D_tail):
KV_tail_shared[bi_i, d_i] = KV[by, Indices[by, s_i, bz // NH, i_i * BS + bi_i], bz // NH, D + d_i]
T.gemm(Q_tail_shared, KV_tail_shared, acc_p, transpose_B=True, policy=T.GemmWarpPolicy.FullCol)
for h_i, bi_i in T.Parallel(block_H, BS):
acc_p[h_i, bi_i] = T.exp2(
acc_p[h_i, bi_i] * sm_scale_mul_reciprocal_log2 - Lse[by, s_i, bz * block_H + h_i]
)
T.copy(acc_p, P_shared_cast)
T.gemm(
dO_shared, KV_shared, acc_dp, transpose_B=True, policy=T.GemmWarpPolicy.FullCol, clear_accum=True
)
for h_i, bi_i in T.Parallel(block_H, BS):
acc_dp[h_i, bi_i] = (
acc_p[h_i, bi_i] * (acc_dp[h_i, bi_i] - Delta[by, s_i, bz * block_H + h_i]) * sm_scale
)
T.copy(acc_dp, dP_shared_cast)
T.gemm(dP_shared_cast, KV_shared, acc_dq, policy=T.GemmWarpPolicy.FullCol)
T.gemm(dP_shared_cast, KV_tail_shared, acc_dq_tail, policy=T.GemmWarpPolicy.FullCol)
T.gemm(
dP_shared_cast,
Q_shared,
acc_dkv,
transpose_A=True,
policy=T.GemmWarpPolicy.FullCol,
clear_accum=True,
)
T.gemm(P_shared_cast, dO_shared, acc_dkv, transpose_A=True, policy=T.GemmWarpPolicy.FullCol)
T.clear(acc_dkv_tail)
T.gemm(dP_shared_cast, Q_tail_shared, acc_dkv_tail, transpose_A=True, policy=T.GemmWarpPolicy.FullCol)
for s in range(split_store):
for bi_i, d_i in T.Parallel(BS, D):
if bi_i < BS // split_store:
acc_dkv_shared[bi_i, d_i] = acc_dkv[bi_i + s * (BS // split_store), d_i]
for bi_i, d_i in T.Parallel(BS, D_tail):
if bi_i < BS // split_store:
acc_dkv_tail_shared[bi_i, d_i] = acc_dkv_tail[bi_i + s * (BS // split_store), d_i]
for bi_i, d_i in T.Parallel(BS // split_store, D // 4):
T.atomic_addx4(
dKV[
by,
Indices[by, s_i, bz // NH, i_i * BS + bi_i + s * (BS // split_store)],
bz // NH,
d_i * 4,
],
acc_dkv_shared[bi_i, d_i * 4],
)
for bi_i, d_i in T.Parallel(BS // split_store, D_tail // 4):
T.atomic_addx4(
dKV[
by,
Indices[by, s_i, bz // NH, i_i * BS + bi_i + s * (BS // split_store)],
bz // NH,
D + d_i * 4,
],
acc_dkv_tail_shared[bi_i, d_i * 4],
)
T.copy(acc_dq, dQ_shared)
T.copy(acc_dq_tail, dQ_tail_shared)
T.copy(dQ_shared, dQ[by, s_i, bz * block_H : (bz + 1) * block_H, :D])
T.copy(dQ_tail_shared, dQ[by, s_i, bz * block_H : (bz + 1) * block_H, D:])
return sparse_mla_bwd_kernel
def sparse_mla_bwd(q, kv, o, do, indices, lse, sm_scale=None):
assert q.is_contiguous()
assert kv.is_contiguous()
assert indices.is_contiguous()
assert lse.is_contiguous()
B, S, H, dim_plus_tail_dim = q.shape
_, S_kv, kv_group, _ = kv.shape
assert kv.shape[-1] == dim_plus_tail_dim
assert kv.shape[0] == B
D = 512
D_tail = dim_plus_tail_dim - D
topk = indices.shape[-1]
assert indices.shape == (B, S, kv_group, topk)
assert lse.shape == (B, S, H)
preprocess_kernel = preprocess(H, D)
bwd_kernel = bwd(H, D, D_tail, topk, kv_group, sm_scale, True)
postprocess_kernel = postprocess(D, D_tail, kv_group)
delta = preprocess_kernel(o, do)
dkv = torch.zeros_like(kv, dtype=torch.float32)
dq = bwd_kernel(q, kv, do, indices, lse, delta, dkv)
dkv = postprocess_kernel(dkv)
return dq, dkv
@@ -0,0 +1,195 @@
# Vendored from tile-ai/tilelang (Apache 2.0), modified for dynamic shapes.
import tilelang
from tilelang import language as T
@tilelang.jit(
out_idx=[-2, -1],
pass_configs={
tilelang.PassConfigKey.TL_DISABLE_TMA_LOWER: True,
tilelang.PassConfigKey.TL_DISABLE_WARP_SPECIALIZED: True,
},
)
def sparse_mla_fwd(
heads,
dim,
tail_dim,
topk,
kv_group=1,
sm_scale=None,
is_causal=True,
CP0=True,
block_I=64,
num_stages=2,
threads=256,
):
assert dim == tilelang.math.next_power_of_2(dim), f"haven't check padding correctness yet, dim={dim}"
assert tail_dim == tilelang.math.next_power_of_2(tail_dim), f"haven't check padding correctness yet, dim={tail_dim}"
assert is_causal is True, "non-casual is not supported"
assert topk % block_I == 0, "otherwise will load some index=0 thus causing wrong kv to be loaded"
if sm_scale is None:
sm_scale = (1.0 / (dim + tail_dim)) ** 0.5 * 1.44269504 # log2(e)
else:
sm_scale = sm_scale * 1.44269504 # log2(e)
batch = T.dynamic("batch")
seq_len = T.dynamic("seq_len")
seq_len_kv = T.dynamic("seq_len_kv")
head_kv = heads // kv_group
q_shape = [batch, seq_len, heads, dim + tail_dim]
kv_shape = [batch, seq_len_kv, kv_group, dim + tail_dim]
o_shape = [batch, seq_len, heads, dim]
indices_shape = [batch, seq_len, kv_group, topk]
lse_shape = [batch, seq_len, heads]
indices_dtype = T.int32
dtype = T.bfloat16
accum_dtype = T.float32
H = head_kv
padded_H = max(tilelang.math.next_power_of_2(head_kv), 16)
if padded_H != H:
assert kv_group == 1, (
"here we solve the H padding automatically, other wise you should handle Q copy and Output copy"
" with your mask (when kv_group == 1, use g_i * padded_H:(g_i+1) * padded_H would be handled"
" automatically)"
)
BI = block_I
NI = tilelang.cdiv(topk, block_I)
D = dim
D_tail = tail_dim
if head_kv > 64:
assert head_kv % 64 == 0, "head_kv should be a multiple of 64"
REPLICATE_H = head_kv // 64
else:
REPLICATE_H = 1
H_per_block = padded_H if REPLICATE_H == 1 else 64
@T.prim_func
def main(
Q: T.Tensor(q_shape, dtype), # type: ignore
KV: T.Tensor(kv_shape, dtype), # type: ignore
Indices: T.Tensor(indices_shape, indices_dtype), # type: ignore
Output: T.Tensor(o_shape, dtype), # type: ignore
Lse: T.Tensor(lse_shape, accum_dtype), # type: ignore
):
with T.Kernel(seq_len * REPLICATE_H, batch, kv_group, threads=threads) as (
bx,
by,
bz,
):
Q_shared = T.alloc_shared([H_per_block, D], dtype)
Q_tail_shared = T.alloc_shared([H_per_block, D_tail], dtype)
KV_shared = T.alloc_shared([BI, D], dtype)
K_tail_shared = T.alloc_shared([BI, D_tail], dtype)
O_shared = T.alloc_shared([H_per_block, D], dtype) # noqa: F841
Lse_shared = T.alloc_shared([H_per_block], accum_dtype) # noqa: F841
mask = T.alloc_fragment([BI], "bool")
acc_o = T.alloc_fragment([H_per_block, D], accum_dtype)
acc_s = T.alloc_fragment([H_per_block, BI], accum_dtype)
S_shared = T.alloc_shared([H_per_block, BI], dtype)
sumexp = T.alloc_fragment([H_per_block], accum_dtype)
sumexp_i = T.alloc_fragment([H_per_block], accum_dtype)
alpha = T.alloc_fragment([H_per_block], accum_dtype)
m_i = T.alloc_fragment([H_per_block], accum_dtype)
m_i_prev = T.alloc_fragment([H_per_block], accum_dtype)
T.fill(acc_o, 0)
T.fill(sumexp, 0)
T.fill(m_i, -(2**30))
b_i, g_i = by, bz
s_i = bx if REPLICATE_H == 1 else (bx // REPLICATE_H)
q_i = s_i
max_kv_i = q_i
H0 = g_i * padded_H + (0 if REPLICATE_H == 1 else (bx % REPLICATE_H) * 64)
H1 = H0 + H_per_block
T.copy(Q[b_i, s_i, H0:H1, :D], Q_shared)
T.copy(Q[b_i, s_i, H0:H1, D:], Q_tail_shared)
for i_i in T.Pipelined(NI, num_stages=num_stages):
for bi_i in T.Parallel(BI):
mask[bi_i] = Indices[b_i, s_i, g_i, i_i * BI + bi_i] <= max_kv_i
for bi_i, d_i in T.Parallel(BI, D):
KV_shared[bi_i, d_i] = KV[b_i, Indices[b_i, s_i, g_i, i_i * BI + bi_i], g_i, d_i]
for bi_i, d_i in T.Parallel(BI, D_tail):
K_tail_shared[bi_i, d_i] = KV[b_i, Indices[b_i, s_i, g_i, i_i * BI + bi_i], g_i, D + d_i]
for h_i, bi_i in T.Parallel(H_per_block, BI):
acc_s[h_i, bi_i] = T.if_then_else(mask[bi_i], 0, -T.infinity(acc_s.dtype))
T.gemm(
Q_shared,
KV_shared,
acc_s,
transpose_B=True,
policy=T.GemmWarpPolicy.FullRow,
)
T.gemm(
Q_tail_shared,
K_tail_shared,
acc_s,
transpose_B=True,
policy=T.GemmWarpPolicy.FullRow,
)
T.copy(m_i, m_i_prev)
T.reduce_max(acc_s, m_i, dim=1, clear=False)
for h_i in T.Parallel(H_per_block):
m_i[h_i] = T.max(m_i[h_i], m_i_prev[h_i])
for h_i in T.Parallel(H_per_block):
alpha[h_i] = T.exp2((m_i_prev[h_i] - m_i[h_i]) * sm_scale)
for h_i, bi_i in T.Parallel(H_per_block, BI):
acc_s[h_i, bi_i] = T.exp2(acc_s[h_i, bi_i] * sm_scale - m_i[h_i] * sm_scale)
T.reduce_sum(acc_s, sumexp_i, dim=1)
for h_i in T.Parallel(H_per_block):
sumexp[h_i] = sumexp[h_i] * alpha[h_i] + sumexp_i[h_i]
for h_i, d_i in T.Parallel(H_per_block, D):
acc_o[h_i, d_i] = acc_o[h_i, d_i] * alpha[h_i]
T.copy(acc_s, S_shared)
T.gemm(S_shared, KV_shared, acc_o, policy=T.GemmWarpPolicy.FullRow)
for h_i, d_i in T.Parallel(H_per_block, D):
acc_o[h_i, d_i] /= sumexp[h_i]
for h_i in T.Parallel(H_per_block):
sumexp[h_i] = T.log2(sumexp[h_i]) + m_i[h_i] * sm_scale
T.copy(acc_o, Output[b_i, s_i, H0:H1, :])
T.copy(sumexp, Lse[b_i, s_i, H0:H1])
return main
def sparse_mla_fwd_interface(q, kv, indices, sm_scale=None, d_v=512, block_I=64, num_stages=2, threads=256):
assert q.is_contiguous() and kv.is_contiguous() and indices.is_contiguous()
batch, seq_len, heads, dim_plus_tail_dim = q.shape
_, seq_len_kv, kv_group, _ = kv.shape
assert dim_plus_tail_dim == 576, "you should assign dim otherwise"
dim = d_v
assert kv.shape[-1] == dim_plus_tail_dim
assert kv.shape[0] == batch
tail_dim = dim_plus_tail_dim - dim
_, _, _, topk = indices.shape
assert indices.shape == (batch, seq_len, kv_group, topk)
kernel = sparse_mla_fwd(
heads,
dim,
tail_dim,
topk,
kv_group,
sm_scale,
True,
block_I=block_I,
num_stages=num_stages,
threads=threads,
)
out, lse = kernel(q, kv, indices)
return out, lse
+43 -81
View File
@@ -91,6 +91,20 @@ class FlashAttention(nn.Module):
if self._flash_attn_version == 4:
self._flash_attn_call = torch._dynamo.disable(self.func)
def _compute_attention(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, cu_seqlens, max_seqlen):
"""Run the flash attention kernel. q/k/v are [total_tokens, heads, dim]."""
args = [q, k, v, cu_seqlens, cu_seqlens]
if self._flash_attn_version != 4:
args.extend([max_seqlen, max_seqlen])
kwargs: dict = {"causal": True}
sliding_window = getattr(self, "sliding_window", None)
if sliding_window is not None:
kwargs["window_size"] = (sliding_window - 1, 0)
out = self._flash_attn_call(*args, **kwargs)
if isinstance(out, tuple):
out = out[0]
return out
def forward(
self,
hidden_states: torch.Tensor,
@@ -129,22 +143,7 @@ class FlashAttention(nn.Module):
key_states = key_states.transpose(1, 2)
value_states = value_states.transpose(1, 2)
args = [
query_states[0],
key_states[0],
value_states[0],
cu_seqlens,
cu_seqlens,
]
if self._flash_attn_version != 4:
args.extend([max_seqlen, max_seqlen])
out = self._flash_attn_call(
*args,
causal=True,
)
if isinstance(out, tuple):
out = out[0]
out = self._compute_attention(query_states[0], key_states[0], value_states[0], cu_seqlens, max_seqlen)
out = out.contiguous()
attn_output = out.view(1, out.shape[0], -1)
@@ -242,11 +241,12 @@ ATTN_IMPL2CLASS = {
}
def substitute_prime_rl_flash_attn(
def substitute_ring_attn(
process_group: torch.distributed.ProcessGroup,
heads_k_stride: int,
attn_impl: str = "flash_attention_2",
) -> None:
"""Patch _compute_attention on FlashAttention (and AfmoeFlashAttention) to use ring attention."""
from ring_flash_attn import llama3_flash_attn_varlen_func
from .ring_attn import ring_fa3_varlen_func
@@ -254,72 +254,34 @@ def substitute_prime_rl_flash_attn(
use_fa3 = attn_impl == "flash_attention_3"
ring_func = ring_fa3_varlen_func if use_fa3 else llama3_flash_attn_varlen_func
class RingFlashAttention(FlashAttention):
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> tuple[torch.Tensor, torch.Tensor | None]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
def _ring_compute_attention(self, q, k, v, cu_seqlens, max_seqlen):
from ring_flash_attn.adapters.hf_adapter import DATA_PARAMS
query_states = self.q_proj(hidden_states)
key_states = self.k_proj(hidden_states)
value_states = self.v_proj(hidden_states)
window_size = (-1, -1)
sliding_window = getattr(self, "sliding_window", None)
if sliding_window is not None:
window_size = (sliding_window - 1, 0)
if self.use_qk_norm and self.qk_norm_type == "per_layer":
query_states = self.q_norm(query_states)
key_states = self.k_norm(key_states)
out = ring_func(
q,
k,
v,
cu_seqlens_q=DATA_PARAMS["cu_seqlens_q"],
cu_seqlens_k=DATA_PARAMS["cu_seqlens_k"],
max_seqlen_q=DATA_PARAMS["max_seqlen_q"],
max_seqlen_k=DATA_PARAMS["max_seqlen_k"],
local_k_slice=DATA_PARAMS["local_k_slice"],
causal=True,
window_size=window_size,
group=process_group,
heads_k_stride=heads_k_stride,
)
if isinstance(out, tuple):
out = out[0]
return out
query_states = query_states.view(hidden_shape)
key_states = key_states.view(hidden_shape)
value_states = value_states.view(hidden_shape)
FlashAttention._compute_attention = _ring_compute_attention
if self.use_qk_norm and self.qk_norm_type == "per_head":
query_states = self.q_norm(query_states)
key_states = self.k_norm(key_states)
from prime_rl.trainer.models.afmoe.modeling_afmoe import AfmoeFlashAttention
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
value_states = value_states.transpose(1, 2)
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
from ring_flash_attn.adapters.hf_adapter import DATA_PARAMS
cu_seqlens_q = DATA_PARAMS["cu_seqlens_q"]
cu_seqlens_k = DATA_PARAMS["cu_seqlens_k"]
max_seqlen_q = DATA_PARAMS["max_seqlen_q"]
max_seqlen_k = DATA_PARAMS["max_seqlen_k"]
local_k_slice = DATA_PARAMS["local_k_slice"]
# TODO: Can we optimize the rotary application instead of double transpose?
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
value_states = value_states.transpose(1, 2)
out = ring_func(
query_states[0],
key_states[0],
value_states[0],
cu_seqlens_q=cu_seqlens_q,
cu_seqlens_k=cu_seqlens_k,
max_seqlen_q=max_seqlen_q,
max_seqlen_k=max_seqlen_k,
local_k_slice=local_k_slice,
causal=True,
group=process_group,
heads_k_stride=heads_k_stride,
)
if isinstance(out, tuple):
out = out[0]
out = out.contiguous()
attn_output = out.view(1, out.shape[0], -1)
attn_weights = None
attn_output = self.o_proj(attn_output)
return attn_output, attn_weights
FlashAttention.forward = RingFlashAttention.forward
AfmoeFlashAttention._compute_attention = _ring_compute_attention
@@ -15,6 +15,7 @@ def _fa3_varlen_forward(
max_seqlen_k: int,
softmax_scale: float,
causal: bool,
window_size: tuple[int, int] = (-1, -1),
) -> tuple[torch.Tensor, torch.Tensor]:
from flash_attn_interface import _flash_attn_forward
@@ -32,6 +33,8 @@ def _fa3_varlen_forward(
"causal": causal,
}
)
if "window_size" in params:
params["window_size"] = window_size
out, lse, _, _ = _flash_attn_forward(**params)
return out, lse
@@ -52,6 +55,7 @@ def _fa3_varlen_backward(
dv: torch.Tensor,
softmax_scale: float,
causal: bool,
window_size: tuple[int, int] = (-1, -1),
) -> None:
from flash_attn_interface import _flash_attn_backward
@@ -75,6 +79,8 @@ def _fa3_varlen_backward(
"causal": causal,
}
)
if "window_size" in params:
params["window_size"] = window_size
_flash_attn_backward(**params)
@@ -100,6 +106,8 @@ class _RingFA3Varlen(torch.autograd.Function):
heads_k_stride: int,
causal: bool,
group_name: str,
window_size_left: int = -1,
window_size_right: int = -1,
) -> torch.Tensor:
group = dist.group.WORLD
for pg in dist.distributed_c10d._world.pg_map:
@@ -108,6 +116,7 @@ class _RingFA3Varlen(torch.autograd.Function):
break
local_k_slice = slice(local_k_slice_start, local_k_slice_stop)
window_size = (window_size_left, window_size_right)
softmax_scale = q.shape[-1] ** (-0.5)
out_list = []
lse_list = []
@@ -146,6 +155,7 @@ class _RingFA3Varlen(torch.autograd.Function):
max_seqlen_k=max_seqlen_k,
softmax_scale=softmax_scale,
causal=causal,
window_size=window_size,
)
out_list.append(out_i)
lse_list.append(lse_i)
@@ -161,6 +171,7 @@ class _RingFA3Varlen(torch.autograd.Function):
ctx.heads_k_stride = heads_k_stride
ctx.causal = causal
ctx.group_name = group_name
ctx.window_size = window_size
return out
@staticmethod
@@ -234,6 +245,7 @@ class _RingFA3Varlen(torch.autograd.Function):
dv=dv_i,
softmax_scale=ctx.softmax_scale,
causal=causal,
window_size=ctx.window_size,
)
if heads_k_stride != nheads_k:
@@ -250,8 +262,9 @@ class _RingFA3Varlen(torch.autograd.Function):
dv[:, i : i + heads_k_stride] = dv_i
# Grads for: q, k, v, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k,
# local_k_slice_start, local_k_slice_stop, heads_k_stride, causal, group_name
return dq, dk, dv, None, None, None, None, None, None, None, None, None
# local_k_slice_start, local_k_slice_stop, heads_k_stride, causal, group_name,
# window_size_left, window_size_right
return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None
def ring_fa3_varlen_func(
@@ -266,6 +279,7 @@ def ring_fa3_varlen_func(
causal: bool,
heads_k_stride: int,
group: dist.ProcessGroup,
window_size: tuple[int, int] = (-1, -1),
) -> torch.Tensor:
return _RingFA3Varlen.apply(
q,
@@ -280,4 +294,6 @@ def ring_fa3_varlen_func(
heads_k_stride,
causal,
group.group_name,
window_size[0],
window_size[1],
)
@@ -115,3 +115,34 @@ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
q_embed = torch.cat([q_embed, q_pass], dim=-1)
k_embed = torch.cat([k_embed, k_pass], dim=-1)
return q_embed, k_embed
def apply_rotary_pos_emb_interleave(q, k, cos, sin, unsqueeze_dim=1):
"""Interleaved RoPE: converts from [r0, i0, r1, i1, ...] layout before applying rotation.
Args:
q (`torch.Tensor`): The query tensor.
k (`torch.Tensor`): The key tensor.
cos (`torch.Tensor`): The cosine part of the rotary embedding.
sin (`torch.Tensor`): The sine part of the rotary embedding.
unsqueeze_dim (`int`, *optional*, defaults to 1):
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
Returns:
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
"""
cos = cos.unsqueeze(unsqueeze_dim)
sin = sin.unsqueeze(unsqueeze_dim)
b, h, s, d = q.shape
q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
b, h, s, d = k.shape
k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed
+6 -6
View File
@@ -8,7 +8,7 @@ from torch import nn
from torch.distributed.tensor import DTensor
from torch.optim import SGD, AdamW, Optimizer
from prime_rl.trainer.config import OptimizerConfigType
from prime_rl.trainer.config import OptimizerConfig
from prime_rl.trainer.parallel_dims import ParallelDims
from prime_rl.trainer.runs import get_multi_run_manager
from prime_rl.trainer.world import get_world
@@ -110,7 +110,7 @@ class CPUOffloadOptimizer:
def setup_optimizer(
config: OptimizerConfigType,
config: OptimizerConfig,
named_params: list[tuple[str, nn.Parameter]],
parallel_dims: ParallelDims,
lora: bool = False,
@@ -140,7 +140,7 @@ def setup_optimizer(
def _create_optimizer(
config: OptimizerConfigType,
config: OptimizerConfig,
named_params: list[tuple[str, nn.Parameter]],
parallel_dims: ParallelDims,
lr: float | None = None,
@@ -169,7 +169,7 @@ def _create_optimizer(
def _create_muon_optimizer(
config: OptimizerConfigType,
config: OptimizerConfig,
named_params: list[tuple[str, nn.Parameter]],
parallel_dims: ParallelDims,
lr: float | None = None,
@@ -252,7 +252,7 @@ def _create_muon_optimizer(
class MultiLoRAOptimizer:
def __init__(self, config: OptimizerConfigType, parallel_dims: ParallelDims):
def __init__(self, config: OptimizerConfig, parallel_dims: ParallelDims):
self.config = config
self.parallel_dims = parallel_dims
self.multi_run_manager = get_multi_run_manager()
@@ -309,5 +309,5 @@ class MultiLoRAOptimizer:
return self.optimizers[idx].param_groups[0]["lr"]
def setup_multi_optimizer(config: OptimizerConfigType, parallel_dims: ParallelDims) -> MultiLoRAOptimizer:
def setup_multi_optimizer(config: OptimizerConfig, parallel_dims: ParallelDims) -> MultiLoRAOptimizer:
return MultiLoRAOptimizer(config, parallel_dims)
@@ -6,11 +6,11 @@ from prime_rl.trainer.config import LoRAConfig
from prime_rl.trainer.rl.broadcast.base import WeightBroadcast
from prime_rl.trainer.rl.broadcast.filesystem import FileSystemWeightBroadcast
from prime_rl.trainer.rl.broadcast.nccl import NCCLWeightBroadcast
from prime_rl.trainer.rl.config import WeightBroadcastConfigType
from prime_rl.trainer.rl.config import WeightBroadcastConfig
def setup_weight_broadcast(
output_dir: Path, config: WeightBroadcastConfigType, lora_config: LoRAConfig | None = None
output_dir: Path, config: WeightBroadcastConfig, lora_config: LoRAConfig | None = None
) -> WeightBroadcast:
if config.type == "nccl":
return NCCLWeightBroadcast(output_dir, config, torch.cuda.current_device())
+18 -22
View File
@@ -1,7 +1,7 @@
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
from pydantic import BaseModel, Discriminator, Field, Tag, model_validator
from pydantic import BaseModel, ConfigDict, Field, model_validator
from prime_rl.trainer.config import (
AdamWConfig,
@@ -9,18 +9,20 @@ from prime_rl.trainer.config import (
CheckpointConfig,
ConstantSchedulerConfig,
ModelConfig,
OptimizerConfigType,
SchedulerConfigType,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
)
from prime_rl.transport.config import FileSystemTransportConfig, TransportConfigType
from prime_rl.transport.config import FileSystemTransportConfig, TransportConfig
from prime_rl.utils.config import HeartbeatConfig, LogConfig, MetricsServerConfig, WandbConfig
from prime_rl.utils.pydantic_config import BaseConfig, BaseSettings
class LossConfig(BaseConfig):
class DefaultLossConfig(BaseModel):
"""Config for the default loss."""
model_config = ConfigDict(extra="forbid")
type: Literal["default"] = "default"
ratio_type: Annotated[Literal["token", "sequence"], Field(description="Type of importance ratio to use.")] = "token"
@@ -81,15 +83,9 @@ class CustomLossConfig(BaseModel):
kwargs: Annotated[dict[str, Any], Field(default_factory=dict, description="Kwargs to pass to the loss function")]
def _loss_config_discriminator(v: Any) -> str:
if isinstance(v, dict):
return v.get("type", "default")
return getattr(v, "type", "default")
LossConfigType: TypeAlias = Annotated[
Annotated[LossConfig, Tag("default")] | Annotated[CustomLossConfig, Tag("custom")],
Discriminator(_loss_config_discriminator),
LossConfig: TypeAlias = Annotated[
DefaultLossConfig | CustomLossConfig,
Field(discriminator="type"),
]
@@ -135,7 +131,9 @@ class NCCLWeightBroadcastConfig(BaseWeightBroadcastConfig):
inference_world_size: Annotated[int, Field(description="The number of GPUs used for inference.")] = 1
WeightBroadcastConfigType: TypeAlias = FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig
WeightBroadcastConfig: TypeAlias = Annotated[
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig, Field(discriminator="type")
]
class RLTrainerConfig(BaseSettings):
@@ -151,22 +149,20 @@ class RLTrainerConfig(BaseSettings):
data: DataLoaderConfig = DataLoaderConfig()
# The loss configuration
loss: LossConfigType = LossConfig()
loss: LossConfig = DefaultLossConfig()
# The optimizer configuration
optim: Annotated[OptimizerConfigType, Field(discriminator="type")] = AdamWConfig()
optim: OptimizerConfig = AdamWConfig()
# The learning rate scheduler configuration
scheduler: Annotated[SchedulerConfigType, Field(discriminator="type")] = ConstantSchedulerConfig()
scheduler: SchedulerConfig = ConstantSchedulerConfig()
# The checkpoint configuration
ckpt: CheckpointConfig | None = None
weight_broadcast: Annotated[WeightBroadcastConfigType, Field(discriminator="type")] = (
FileSystemWeightBroadcastConfig()
)
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
rollout_transport: Annotated[TransportConfigType, Field(discriminator="type")] = FileSystemTransportConfig()
rollout_transport: TransportConfig = FileSystemTransportConfig()
# The logging configuration
log: LogConfig = LogConfig()
+2 -2
View File
@@ -10,7 +10,7 @@ from prime_rl.trainer.rl.config import FakeDataLoaderConfig
from prime_rl.trainer.rl.packer import BasePacker, setup_packer
from prime_rl.trainer.runs import get_multi_run_manager
from prime_rl.trainer.world import get_world
from prime_rl.transport import MicroBatch, MicroBatchReceiver, TransportConfigType, setup_micro_batch_receiver
from prime_rl.transport import MicroBatch, MicroBatchReceiver, TransportConfig, setup_micro_batch_receiver
class TensorMicroBatch(TypedDict):
@@ -142,7 +142,7 @@ class DataLoader:
seq_len: int,
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
config: TransportConfigType,
config: TransportConfig,
):
self.world = get_world()
+3 -3
View File
@@ -6,7 +6,7 @@ from beartype import beartype as typechecker
from jaxtyping import Bool, Float, Int, jaxtyped
from torch import Tensor
from prime_rl.trainer.rl.config import CustomLossConfig, LossConfig, LossConfigType
from prime_rl.trainer.rl.config import CustomLossConfig, DefaultLossConfig, LossConfig
from prime_rl.utils.utils import import_object
@@ -104,7 +104,7 @@ def _safe_mean(values: Tensor, mask: Tensor) -> Tensor:
return values[mask].sum() / denom
def default_loss_fn(inputs: LossInputs, loss_config: LossConfig) -> LossOutputs:
def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossOutputs:
"""Masked importance sampling with KL against the inference policy, and optional masking strategies."""
trainer_logprobs = inputs.trainer_logprobs
inference_logprobs = inputs.inference_logprobs
@@ -173,7 +173,7 @@ def default_loss_fn(inputs: LossInputs, loss_config: LossConfig) -> LossOutputs:
return LossOutputs(loss=loss, metrics=metrics)
def setup_loss_fn(loss_config: LossConfigType) -> LossFn:
def setup_loss_fn(loss_config: LossConfig) -> LossFn:
"""Setup the loss function based on config."""
if isinstance(loss_config, CustomLossConfig):
custom_fn = import_object(loss_config.import_path)
+5 -5
View File
@@ -11,7 +11,7 @@ from prime_rl.transport import (
MicroBatch,
MicroBatchSender,
TrainingSample,
TransportConfigType,
TransportConfig,
setup_micro_batch_sender,
setup_training_batch_receiver,
)
@@ -28,7 +28,7 @@ class BasePacker(ABC):
seq_len: int,
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
config: TransportConfigType,
config: TransportConfig,
start_step: int = 0,
):
self.logger = get_logger()
@@ -56,7 +56,7 @@ class SinglePacker(BasePacker):
seq_len: int,
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
config: TransportConfigType,
config: TransportConfig,
start_step: int = 0,
):
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, start_step)
@@ -94,7 +94,7 @@ class MultiPacker(BasePacker):
seq_len: int,
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
config: TransportConfigType,
config: TransportConfig,
start_step: int = 0,
):
super().__init__(dp_world_size, seq_len, pad_to_multiple_of, tokenizer, config, start_step)
@@ -311,7 +311,7 @@ def setup_packer(
seq_len: int,
pad_to_multiple_of: int,
tokenizer: PreTrainedTokenizer,
transport_config: TransportConfigType,
transport_config: TransportConfig,
start_step: int = 0,
) -> BasePacker:
multi_run_manager = get_multi_run_manager()
+4 -4
View File
@@ -5,7 +5,7 @@ from datetime import timedelta
# Import environment before any other imports
# ruff: noqa: I001
from prime_rl.trainer.models.layers.attn import substitute_prime_rl_flash_attn
from prime_rl.trainer.models.layers.attn import substitute_ring_attn
from prime_rl.trainer.rl.broadcast import setup_weight_broadcast
from prime_rl.utils.act_offloading import maybe_activation_offloading
import torch
@@ -16,7 +16,7 @@ from prime_rl.trainer.ckpt import setup_ckpt_managers
from prime_rl.trainer.multi_ckpt import setup_multi_checkpoint_manager
from prime_rl.trainer.optim import setup_optimizer, setup_multi_optimizer
from prime_rl.trainer.scheduler import setup_scheduler, setup_multi_scheduler
from prime_rl.trainer.rl.config import LossConfig, RLTrainerConfig
from prime_rl.trainer.rl.config import DefaultLossConfig, RLTrainerConfig
from prime_rl.trainer.rl.data import DataLoader, FakeDataLoader
from prime_rl.utils.cp import (
setup_cp_params,
@@ -172,7 +172,7 @@ def train(config: RLTrainerConfig):
if parallel_dims.cp_enabled:
substitute_hf_flash_attn(parallel_dims.world_mesh["cp"].get_group(), heads_k_stride=1)
substitute_prime_rl_flash_attn(
substitute_ring_attn(
parallel_dims.world_mesh["cp"].get_group(),
heads_k_stride=1,
attn_impl=config.model.attn,
@@ -294,7 +294,7 @@ def train(config: RLTrainerConfig):
seq_len = micro_batches[0]["input_ids"].shape[1]
# Normalize by the local number of unmasked tokens in the batch (per-batch length normalization)
if isinstance(config.loss, LossConfig) and config.loss.ratio_type == "token":
if isinstance(config.loss, DefaultLossConfig) and config.loss.ratio_type == "token":
loss_scale = sum(micro_batch["loss_mask"].sum().item() for micro_batch in micro_batches)
else:
loss_scale = batch_size
+4 -4
View File
@@ -3,7 +3,7 @@ from __future__ import annotations
from torch.optim import Optimizer
from torch.optim.lr_scheduler import ConstantLR, CosineAnnealingLR, LinearLR, LRScheduler, SequentialLR
from prime_rl.trainer.config import SchedulerConfigType
from prime_rl.trainer.config import SchedulerConfig
from prime_rl.trainer.optim import CPUOffloadOptimizer, MultiLoRAOptimizer
from prime_rl.trainer.runs import get_multi_run_manager
from prime_rl.utils.logger import get_logger
@@ -88,7 +88,7 @@ def setup_cosine_scheduler(
def setup_scheduler(
optimizer: Optimizer | CPUOffloadOptimizer,
scheduler_config: SchedulerConfigType,
scheduler_config: SchedulerConfig,
max_steps: int | None,
lr: float,
) -> LRScheduler:
@@ -131,7 +131,7 @@ class MultiLoRAScheduler:
def __init__(
self,
scheduler_config: SchedulerConfigType,
scheduler_config: SchedulerConfig,
max_steps: int | None,
):
self.scheduler_config = scheduler_config
@@ -178,7 +178,7 @@ class MultiLoRAScheduler:
def setup_multi_scheduler(
optimizer: MultiLoRAOptimizer,
scheduler_config: SchedulerConfigType,
scheduler_config: SchedulerConfig,
max_steps: int | None,
) -> MultiLoRAScheduler:
"""Create a MultiLoRAScheduler for managing per-run schedulers."""
+138 -20
View File
@@ -1,7 +1,7 @@
from pathlib import Path
from typing import Annotated, Literal, TypeAlias
from pydantic import BaseModel, Field, model_validator
from pydantic import BaseModel, ConfigDict, Field, model_validator
from prime_rl.trainer.config import (
AdamWConfig,
@@ -9,8 +9,9 @@ from prime_rl.trainer.config import (
CheckpointConfig,
ConstantSchedulerConfig,
ModelConfig,
OptimizerConfigType,
SchedulerConfigType,
OptimizerConfig,
SchedulerConfig,
SlurmConfig,
TokenizerConfig,
)
from prime_rl.utils.config import HeartbeatConfig, LogConfig, WandbConfig
@@ -101,12 +102,64 @@ class SFTDataConfig(BaseDataConfig):
return self
DataConfigType: TypeAlias = FakeDataConfig | SFTDataConfig
DataConfig: TypeAlias = Annotated[FakeDataConfig | SFTDataConfig, Field(discriminator="type")]
class BaseDeploymentConfig(BaseModel):
"""Base deployment config for SFT."""
model_config = ConfigDict(extra="forbid")
gpus_per_node: Annotated[int, Field(description="Number of GPUs per node.")] = 8
class SingleNodeDeploymentConfig(BaseDeploymentConfig):
"""Configures a single-node SFT deployment."""
type: Literal["single_node"] = "single_node"
num_gpus: Annotated[int, Field(description="Number of GPUs.")] = 1
@model_validator(mode="after")
def validate_gpu_count(self):
if self.num_gpus > self.gpus_per_node:
raise ValueError(f"num_gpus ({self.num_gpus}) exceeds gpus_per_node ({self.gpus_per_node}).")
return self
class MultiNodeDeploymentConfig(BaseDeploymentConfig):
"""Configures a multi-node SFT deployment."""
type: Literal["multi_node"] = "multi_node"
num_nodes: Annotated[int, Field(description="Number of training nodes.")] = 2
nodes_per_fsdp_group: Annotated[
int | None,
Field(
description="Number of nodes per FSDP island. Auto-sets model.dp_replicate = num_nodes / nodes_per_fsdp_group."
),
] = None
SFTDeploymentConfig: TypeAlias = Annotated[
SingleNodeDeploymentConfig | MultiNodeDeploymentConfig, Field(discriminator="type")
]
class SFTTrainerConfig(BaseSettings):
"""Configures the SFT trainer"""
slurm: Annotated[
SlurmConfig | None,
Field(
description="SLURM configuration. If set, the run will be submitted as a SLURM job instead of running locally.",
exclude=True,
),
] = None
deployment: SFTDeploymentConfig = SingleNodeDeploymentConfig()
# The model configuration
model: ModelConfig = ModelConfig()
@@ -114,13 +167,13 @@ class SFTTrainerConfig(BaseSettings):
tokenizer: TokenizerConfig = TokenizerConfig()
# The data configuration
data: Annotated[DataConfigType, Field(discriminator="type")] = SFTDataConfig()
data: DataConfig = SFTDataConfig()
# The optimizer configuration
optim: Annotated[OptimizerConfigType, Field(discriminator="type")] = AdamWConfig()
optim: OptimizerConfig = AdamWConfig()
# The learning rate scheduler configuration
scheduler: Annotated[SchedulerConfigType, Field(discriminator="type")] = ConstantSchedulerConfig()
scheduler: SchedulerConfig = ConstantSchedulerConfig()
# The checkpoint configuration
ckpt: CheckpointConfig | None = None
@@ -138,6 +191,13 @@ class SFTTrainerConfig(BaseSettings):
),
] = Path("outputs")
clean_output_dir: Annotated[
bool,
Field(
description="If true, delete the output directory before starting training. Required to overwrite an output directory that contains checkpoints from a previous run when not resuming.",
),
] = False
max_steps: Annotated[
int | None,
Field(description="Maximum number of steps to run training for. If None, will run indefinitely."),
@@ -169,12 +229,36 @@ class SFTTrainerConfig(BaseSettings):
HeartbeatConfig | None, Field(description="The heartbeat config for monitoring training progress.")
] = None
### Pre-validation normalization
@model_validator(mode="before")
@classmethod
def normalize_deployment(cls, data):
if not isinstance(data, dict):
return data
deployment = data.get("deployment")
if isinstance(deployment, dict) and deployment.get("type") == "multi_node":
for key in ("num_gpus",):
deployment.pop(key, None)
return data
### Validate configs (e.g. raise for unsupported (combinations of) configs)
@model_validator(mode="after")
def auto_setup_bench(self):
if self.bench is not None:
self.max_steps = 4 # 1 Warmup + 3 Benchmark
if self.ckpt: # Do not checkpoint
self.ckpt = None
def validate_deployment(self):
if self.deployment.type == "multi_node" and self.slurm is None:
raise ValueError("Must use SLURM for multi-node deployment.")
return self
@model_validator(mode="after")
def validate_slurm_output_dir(self):
if self.slurm is None:
return self
if self.output_dir == Path("outputs"):
raise ValueError(
"output_dir must be explicitly set when using SLURM (not the default 'outputs'). "
"Set output_dir to a unique experiment path, e.g. '/shared/experiments/my-sft-run'."
)
return self
@model_validator(mode="after")
@@ -230,14 +314,6 @@ class SFTTrainerConfig(BaseSettings):
raise ValueError("Muon optimizer does not support FSDP CPU offload")
return self
@model_validator(mode="after")
def auto_setup_tokenizer(self):
if self.tokenizer.name is None:
self.tokenizer.name = self.model.name
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_and_disable_chunked_loss(self):
if isinstance(self.model.fused_lm_head_chunk_size, int):
@@ -254,3 +330,45 @@ class SFTTrainerConfig(BaseSettings):
raise ValueError("EP is only supported with the custom implementation or auto mode")
return self
### Auto-setup and validate shared configs
@model_validator(mode="after")
def auto_setup_bench(self):
if self.bench is not None:
self.max_steps = 4 # 1 Warmup + 3 Benchmark
if self.ckpt: # Do not checkpoint
self.ckpt = None
return self
@model_validator(mode="after")
def auto_setup_tokenizer(self):
if self.tokenizer.name is None:
self.tokenizer.name = self.model.name
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_deployment(self):
if self.deployment.type == "multi_node":
if self.deployment.nodes_per_fsdp_group is not None:
if self.deployment.num_nodes % self.deployment.nodes_per_fsdp_group != 0:
raise ValueError(
f"deployment.num_nodes ({self.deployment.num_nodes}) must be divisible by "
f"deployment.nodes_per_fsdp_group ({self.deployment.nodes_per_fsdp_group})"
)
self.model.dp_replicate = self.deployment.num_nodes // self.deployment.nodes_per_fsdp_group
return self
@model_validator(mode="after")
def auto_setup_slurm_template(self):
if self.slurm is not None and self.slurm.template_path is None:
import prime_rl
templates_dir = Path(prime_rl.__file__).parent / "templates"
if self.deployment.type == "single_node":
self.slurm.template_path = templates_dir / "single_node_sft.sbatch.j2"
else:
self.slurm.template_path = templates_dir / "multi_node_sft.sbatch.j2"
return self
+3 -5
View File
@@ -12,7 +12,7 @@ from torch.utils.data import IterableDataset, get_worker_info
from torchdata.stateful_dataloader import StatefulDataLoader
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.trainer.sft.config import DataConfigType, LossMaskConfig
from prime_rl.trainer.sft.config import DataConfig, LossMaskConfig
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
@@ -541,9 +541,7 @@ def setup_and_interleave_datasets(
return dataset
def setup_dataset(
tokenizer: PreTrainedTokenizer, config: DataConfigType, non_dp_size: int = 1
) -> StatefulIterableDataset:
def setup_dataset(tokenizer: PreTrainedTokenizer, config: DataConfig, non_dp_size: int = 1) -> StatefulIterableDataset:
if config.type == "fake":
# Shouldnt matter to handle non_dp_size if dataset is random
return FakeDataset(
@@ -596,7 +594,7 @@ def setup_dataset(
raise ValueError(f"Invalid dataset type: {config.type}")
def setup_dataloader(dataset: StatefulIterableDataset, config: DataConfigType) -> StatefulDataLoader:
def setup_dataloader(dataset: StatefulIterableDataset, config: DataConfig) -> StatefulDataLoader:
if config.pack_function == "stack":
stacking_dataset = StackDataset(dataset, config.seq_len * config.micro_batch_size)
return StatefulDataLoader(stacking_dataset, batch_size=1, collate_fn=stack_collate)
View File
+2 -2
View File
@@ -8,7 +8,7 @@ from torch.nn import CrossEntropyLoss
# Import environment before any other imports
# ruff: noqa: I001
from prime_rl.trainer.models.layers.attn import substitute_prime_rl_flash_attn
from prime_rl.trainer.models.layers.attn import substitute_ring_attn
from prime_rl.utils.act_offloading import maybe_activation_offloading
import torch
from torch.profiler import profile, ProfilerActivity, record_function
@@ -94,7 +94,7 @@ def train(config: SFTTrainerConfig):
if parallel_dims.cp_enabled:
assert config.data.seq_len % parallel_dims.cp == 0, "Sequence length must be divisible by CP degree"
substitute_hf_flash_attn(parallel_dims.world_mesh["cp"].get_group(), heads_k_stride=1)
substitute_prime_rl_flash_attn(
substitute_ring_attn(
parallel_dims.world_mesh["cp"].get_group(),
heads_k_stride=1,
attn_impl=config.model.attn,
+5 -5
View File
@@ -1,7 +1,7 @@
from pathlib import Path
from prime_rl.transport.base import MicroBatchReceiver, MicroBatchSender, TrainingBatchReceiver, TrainingBatchSender
from prime_rl.transport.config import TransportConfigType
from prime_rl.transport.config import TransportConfig
from prime_rl.transport.filesystem import (
FileSystemMicroBatchReceiver,
FileSystemMicroBatchSender,
@@ -17,7 +17,7 @@ from prime_rl.transport.zmq import (
)
def setup_training_batch_sender(output_dir: Path, transport: TransportConfigType) -> TrainingBatchSender:
def setup_training_batch_sender(output_dir: Path, transport: TransportConfig) -> TrainingBatchSender:
if transport.type == "filesystem":
return FileSystemTrainingBatchSender(output_dir)
elif transport.type == "zmq":
@@ -26,7 +26,7 @@ def setup_training_batch_sender(output_dir: Path, transport: TransportConfigType
raise ValueError(f"Invalid transport type: {transport.type}")
def setup_training_batch_receiver(transport: TransportConfigType) -> TrainingBatchReceiver:
def setup_training_batch_receiver(transport: TransportConfig) -> TrainingBatchReceiver:
if transport.type == "filesystem":
return FileSystemTrainingBatchReceiver()
elif transport.type == "zmq":
@@ -36,7 +36,7 @@ def setup_training_batch_receiver(transport: TransportConfigType) -> TrainingBat
def setup_micro_batch_sender(
output_dir: Path, data_world_size: int, current_step: int, transport: TransportConfigType
output_dir: Path, data_world_size: int, current_step: int, transport: TransportConfig
) -> MicroBatchSender:
if transport.type == "filesystem":
return FileSystemMicroBatchSender(output_dir, data_world_size, current_step)
@@ -47,7 +47,7 @@ def setup_micro_batch_sender(
def setup_micro_batch_receiver(
output_dir: Path, data_rank: int, current_step: int, transport: TransportConfigType
output_dir: Path, data_rank: int, current_step: int, transport: TransportConfig
) -> MicroBatchReceiver:
if transport.type == "filesystem":
return FileSystemMicroBatchReceiver(output_dir, data_rank, current_step)
+1 -1
View File
@@ -24,4 +24,4 @@ class ZMQTransportConfig(BaseTransportConfig):
hwm: Annotated[int, Field(description="High water mark (max messages in queue) for ZMQ sockets.")] = 10
TransportConfigType: TypeAlias = FileSystemTransportConfig | ZMQTransportConfig
TransportConfig: TypeAlias = Annotated[FileSystemTransportConfig | ZMQTransportConfig, Field(discriminator="type")]
+7 -5
View File
@@ -96,31 +96,33 @@ class StaticInferencePool:
pass
async def setup_inference_pool(client_config: ClientConfig, model_name: str) -> InferencePool:
async def setup_inference_pool(
client_config: ClientConfig, model_name: str, client_type: str = "openai_chat_completions"
) -> InferencePool:
"""Create an inference pool from config (static or elastic)."""
logger = get_logger()
if client_config.is_elastic:
from prime_rl.utils.elastic import ElasticInferencePool
return await ElasticInferencePool.from_config(client_config, model_name=model_name)
return await ElasticInferencePool.from_config(client_config, model_name=model_name, client_type=client_type)
logger.info(
f"Initializing static inference pool (base_url={', '.join(client_config.base_url)}, "
f"api_key_var={client_config.api_key_var}, headers={client_config.headers})"
)
return StaticInferencePool(
clients=setup_clients(client_config),
clients=setup_clients(client_config, client_type=client_type),
admin_clients=setup_admin_clients(client_config),
skip_model_check=client_config.skip_model_check,
)
def setup_clients(client_config: ClientConfig) -> list[vf.ClientConfig]:
def setup_clients(client_config: ClientConfig, client_type: str = "openai_chat_completions") -> list[vf.ClientConfig]:
def setup_client(client_idx: int, base_url: str) -> vf.ClientConfig:
return vf.ClientConfig(
client_idx=client_idx,
client_type="openai_chat_completions_token",
client_type=client_type,
api_base_url=base_url,
api_key_var=client_config.api_key_var,
timeout=client_config.timeout,
+8 -2
View File
@@ -107,6 +107,7 @@ class ElasticInferencePool:
model_name: str,
port: int = 8000,
sync_interval: float = 5.0,
client_type: str = "openai_chat_completions",
):
self.logger = get_logger()
self.hostname = hostname
@@ -115,6 +116,7 @@ class ElasticInferencePool:
self.base_model_name = model_name # Keep original for health checks
self.port = port
self.sync_interval = sync_interval
self.client_type = client_type
self._servers: dict[str, ServerState] = {}
self._admin_clients: dict[str, AsyncClient] = {}
@@ -129,7 +131,9 @@ class ElasticInferencePool:
self._started = False
@classmethod
async def from_config(cls, config: ClientConfig, model_name: str) -> ElasticInferencePool:
async def from_config(
cls, config: ClientConfig, model_name: str, client_type: str = "openai_chat_completions"
) -> ElasticInferencePool:
if config.elastic is None:
raise ValueError("Elastic inference pool requires elastic config")
pool = cls(
@@ -138,6 +142,7 @@ class ElasticInferencePool:
model_name=model_name,
port=config.elastic.port,
sync_interval=config.elastic.sync_interval,
client_type=client_type,
)
await pool.start()
return pool
@@ -168,7 +173,8 @@ class ElasticInferencePool:
base_url=urls,
api_key_var=self.client_config.api_key_var,
headers=self.client_config.headers,
)
),
client_type=self.client_type,
)
if urls
else []
+32
View File
@@ -1,4 +1,5 @@
import asyncio
import shutil
import time
from pathlib import Path
@@ -58,6 +59,37 @@ def resolve_latest_ckpt_step(ckpt_dir: Path) -> int | None:
return latest_step
def has_checkpoints(output_dir: Path) -> bool:
"""Check if the output directory contains any checkpoints."""
ckpt_dir = get_ckpt_dir(output_dir)
return ckpt_dir.exists() and any(ckpt_dir.iterdir())
def validate_output_dir(output_dir: Path, *, resuming: bool, clean: bool) -> None:
"""Validate the output directory before training starts.
Raises if the directory contains checkpoints from a previous run, unless
explicitly resuming or opting into cleaning. Other artifacts (logs,
rollouts, configs) are fine and don't trigger the error.
"""
if not output_dir.exists():
return
if resuming:
return
if clean:
logger = get_logger()
logger.warning(f"Cleaning existing output directory: {output_dir}")
shutil.rmtree(output_dir)
return
if has_checkpoints(output_dir):
raise FileExistsError(
f"Output directory '{output_dir}' already contains checkpoints from a previous run. "
f"To resume the latest step of the previous run, set ckpt.resume_step=-1 or --ckpt.resume-step -1 via CLI. "
f"To delete the existing directory and start fresh, set clean_output_dir=true or --clean-output-dir via CLI. "
f"Otherwise use a unique output_dir for this experiment."
)
def sync_wait_for_path(path: Path, interval: int = 1, log_interval: int = 10) -> None:
logger = get_logger()
wait_time = 0
+32
View File
@@ -0,0 +1,32 @@
import subprocess
from subprocess import Popen
from threading import Event, Thread
def cleanup_threads(threads: list[Thread]):
"""Cleanup a list of threads"""
for thread in threads:
thread.join(timeout=5)
def cleanup_processes(processes: list[Popen]):
"""Cleanup a list of subprocesses"""
for process in processes:
if process.poll() is None:
process.terminate()
try:
process.wait(timeout=60)
except subprocess.TimeoutExpired:
process.kill()
def monitor_process(process: Popen, stop_event: Event, error_queue: list, process_name: str):
"""Monitor a subprocess and signal errors via shared queue."""
process.wait()
if process.returncode != 0:
err_msg = f"{process_name.capitalize()} failed with exit code {process.returncode}"
if process.stderr:
err_msg += f"\n{process.stderr.read().decode('utf-8')}"
error_queue.append(RuntimeError(err_msg))
stop_event.set()
+20 -2
View File
@@ -6,7 +6,7 @@ from typing import Annotated, ClassVar, Type, TypeVar
import tomli
import tomli_w
from pydantic import BaseModel, ConfigDict, Field, field_validator
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from pydantic_settings import BaseSettings as PydanticBaseSettings
from pydantic_settings import (
PydanticBaseSettingsSource,
@@ -85,6 +85,25 @@ class BaseSettings(PydanticBaseSettings):
file_secret_settings,
)
@model_validator(mode="before")
@classmethod
def _default_discriminator_types(cls, data: dict) -> dict:
"""For discriminated-union fields whose default carries a ``type``, inject it when missing.
Without ``nested_model_default_partial_update`` the ``type`` tag is no
longer merged in automatically, so we do it here for every field whose
default instance exposes one.
"""
if not isinstance(data, dict):
return data
for field_name, field_info in cls.model_fields.items():
val = data.get(field_name)
if isinstance(val, dict) and "type" not in val:
default = field_info.default
if isinstance(default, BaseModel) and hasattr(default, "type"):
val["type"] = default.type
return data
# Pydantic settings configuration
model_config = SettingsConfigDict(
env_prefix="PRIME_",
@@ -93,7 +112,6 @@ class BaseSettings(PydanticBaseSettings):
cli_kebab_case=True,
cli_implicit_flags=True,
cli_use_class_docs_for_groups=True,
nested_model_default_partial_update=True, # Allows partial updates to nested model default objects
)
+2 -2
View File
@@ -7,7 +7,7 @@ from prime_rl.orchestrator.advantage import (
default_advantage_fn,
setup_advantage_fn,
)
from prime_rl.orchestrator.config import AdvantageConfig, CustomAdvantageConfig
from prime_rl.orchestrator.config import CustomAdvantageConfig, DefaultAdvantageConfig
def test_default_advantage_fn_simple_mean():
@@ -39,7 +39,7 @@ def test_compute_advantages_with_config():
rewards = [1.0, 0.5, 0.8, 0.2, 0.9, 0.1]
lengths = [10, 12, 8, 15, 11, 9]
result = compute_advantages(rewards, lengths, samples_per_problem=3, advantage_config=AdvantageConfig())
result = compute_advantages(rewards, lengths, samples_per_problem=3, advantage_config=DefaultAdvantageConfig())
assert len(result) == 6
# First 3 should sum to ~0 (mean subtracted)

Some files were not shown because too many files have changed in this diff Show More