Files
prime-rl/docs/development.md
T
d8219c2957 feat: post eval regression results to Slack (#4409)
## Summary

- Each eval job of the regression workflow posts one Slack message for
its config when it ends. The message has the verdict, the model, the
gated metrics against the baseline, and a link to the workflow run.
- The post goes to the `SLACK_WEBHOOK_URL` repo secret. The step skips
when the secret is not set.
- Only nightly (`schedule`) and manual (`workflow_dispatch`) runs with
one repeat post. PR runs and multi-repeat baseline runs do not.
- The post happens in the eval job, not in the summary job. GSM8K
reports after about 12 min and does not wait for the 4 h
Terminal-Bench-2.1 job. The stuck Parallel / Invariance GPU job also no
longer delays the results.
- An eval that crashes, times out, or is cancelled posts "no repeat
finished". A job that hits `timeout-minutes` ends as cancelled, so the
step runs on `always()`.
- The comment on the eval job timeout says that agent evals cap their
rollout time in the config. It said they have no rollout timeout.
- `eval.py summarize --slack <path>` writes the webhook payload. The
comparison logic moves into `gate()`, which the Markdown table and the
Slack message share. The Markdown summary output is unchanged.
- `docs/development.md` mentions the Slack post.

Example message (from the last Terminal-Bench-2.1 PR run):

```
✅ Eval regression: Terminal-Bench-2.1: no regression
internal/deepseek-v4.1-flash-1017-ci · 82 tasks × 1 rollouts · workflow run
✅ Accuracy: 59.76% vs 65.85% ± 2.86% (Δ −6.10%, tolerance ±9.40%)
✅ Time to finish (s): 14453 vs 14475 ± 11 (Δ −22, tolerance ±3619)
✅ Error rate: 4.88% vs 1.95% ± 0.67% (Δ +2.93%, tolerance ±10.00%)
✅ Truncation rate: 0.00% vs 0.00% ± 0.00% (Δ +0.00%, tolerance ±1.00%)
```

## Verification

- I rendered the payload locally from the saved Terminal-Bench-2.1 PR
result, a GSM8K baseline repeat, and an empty result set.
- The Markdown summary of the new `eval.py` is byte-identical to the one
on `main`.
- The commit has `[skip ci]`, so this PR does not start the 4 h
Terminal-Bench-2.1 eval. A manual dispatch of GSM8K only on this branch
tests the Slack post.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Changes are CI notifications and reporting refactor only; no runtime
training/inference paths, with webhook posting gated and non-blocking
(`|| true` on summarize).
> 
> **Overview**
> Nightly and manual regression **eval** jobs now **post one Slack
message per config** as soon as that matrix job finishes, instead of
waiting on the aggregate summary job. Posts use the `SLACK_WEBHOOK_URL`
secret (skipped if unset), run on **`always()`** so
timeouts/cancellations still notify, and are limited to **non-PR runs
with a single repeat** (baseline multi-repeat runs still report only in
the GitHub summary).
> 
> **`eval.py`** gains shared **`gate()`** logic for baseline comparison,
a **`slack()`** webhook payload builder, and **`summarize --slack
<path>`**; Markdown gating output is intended to stay the same.
**`docs/development.md`** documents the Slack behavior, and the eval job
timeout comment now notes that agent eval configs cap rollout time per
config.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
2b54672427872d136f30620afee1fb1b3ebf2931. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 19:08:22 -08:00

11 KiB
Raw Blame History

Development

This page covers workflows for developing on prime-rl itself — running the test suite, contributing changes, and adding new model architectures with the small-scale tooling we use to iterate on MoE families without booting up a 100B+ run.

Table of Contents

Test Suite

The test suite is split into three tiers.

Layout

  • tests/unit/ — fast-running, hermetic tests for isolated logic: config parsing and validation, advantage / loss / scheduler / packer math, individual dataset paths, model-conversion roundtrips, etc. Tests that need a GPU are tagged with the gpu marker.
  • tests/integration/ — full-stack RL/SFT runs on a tiny model end-to-end through inference + orchestrator + trainer.
  • tests/regression/ — nightly regression suites: test_parallel_invariance.py, which checks that DP/CP/EP layouts train the same first step as a single GPU, and evals from configs/eval/ compared against baselines/eval/.

Running Tests Locally

uv run pytest -v                                           # everything
uv run pytest tests/unit -v                                # unit only
uv run pytest tests/integration -v                         # integration only
uv run pytest -v -m "not gpu"                              # CPU-only subset (mirrors CPU CI)
uv run pytest -v -m gpu                                    # GPU-only subset
uv run pytest tests/integration/test_reverse_text.py -vvs  # one specific scenario

CI Workflows

Workflow Trigger What runs Where
tests.yml CPU jobs: every PR + push to main. gsm8k_eval: relevant changes in non-draft PRs, every push to main, manual dispatch CPU: pytest tests/unit -m "not gpu", plus a slim-wheel install check that prime-rl-configs imports cleanly without heavy deps (no torch / vllm / transformers / wandb / verifiers / datasets / liger / loguru in sys.modules). Separate hosted gsm8k_eval job ubuntu-latest
gpu.yml On a PR: applying the gpu-ci label (Triage or higher). Also every merge to main and manual dispatch Full GPU suite: pytest tests/unit -m gpu, plus RL/SFT integration scenarios (reverse_text, reverse_text_sft, reverse_text_sft_lora, reverse_text_lora, reverse_text_moe, reverse_text_rl_opd, reverse_text_rl_sft, alphabet_sort) with max-parallel: 5 Self-hosted prime-rl-2xh200 k8s scale set (2xH200); ubuntu-latest for the trigger check
regression.yml 03:00 PST daily + manual workflow_dispatch (suite picks one suite; eval_config picks one eval config); eval also on PRs that touch it parallel: tests/regression/test_parallel_invariance.py (layouts that need more than 2 GPUs skip). eval: every tests/regression/configs/eval/*.toml (gsm8k, PI-TerminalBench2.1) against Prime Inference, each compared against its baseline in tests/regression/baselines/eval/. Nightly and manual runs post one Slack message per config through the SLACK_WEBHOOK_URL secret eval: ubuntu-latest. parallel: prime-rl-2xh200

Pushes to a PR do not run GPU jobs. To run the GPU suite on a PR's current commit, apply the gpu-ci label (drafts included). The workflow removes the label when it starts, so re-apply it to run again after new pushes or to retry. A new trigger cancels the PR's queued or in-flight GPU run. Fork PRs cannot run GPU CI: a maintainer can push the branch to this repo and label that PR. A PR with merge conflicts cannot run it until the conflicts are resolved.

Markers

Two pytest markers are declared in pyproject.toml (addopts = "--strict-markers"):

  • gpu — gate a test that needs CUDA. CPU CI uses -m "not gpu"; the GPU unit job uses -m gpu.
  • slow — gate a test that's expensive enough you'd usually skip it locally. Deselect with -m "not slow".

Pre-Commit Hooks

Install the pre-commit hooks before your first commit so ruff check + format run on staged Python files automatically:

uv run pre-commit install

Adding a New Model

Bringing up a new model family is three steps: implement the modeling code, register a mini preset, and run the smoke test. The preset and smoke test let you iterate on the modeling code at ~0.5B scale on 1–2 GPUs instead of paying the cost of the full-size model — useful for catching bugs in modeling code, state-dict conversions, and pipeline integration before scaling.

Implement the Modeling Code

Drop the modeling code under src/prime_rl/trainer/models/<arch>/ (HF-compatible config, modeling, and weight conversion). Mirror the layout of an existing family — glm4_moe/ or qwen3_moe/ are good starting points.

Register a Mini Preset

Add an entry to scripts/mini_moe.py so the smoke-test workflow can build a ~0.5B test model in your architecture. The preset names the config class, picks small dimensions, and wires up the HF + prime-rl model classes plus a tokenizer source:

ARCH_PRESETS = {
    "glm4_moe": {
        "config_class": Glm4MoeConfig,
        "config_kwargs": dict(hidden_size=1024, num_hidden_layers=24, n_routed_experts=8, ...),
        "hf_model_class": HFGlm4MoeForCausalLM,
        "prime_model_class": PrimeRLGlm4MoeForCausalLM,
        "tokenizer_source": "THUDM/GLM-4-9B-0414",
    },
    # add your arch here
}

Run the Smoke Test

Build the mini model. This creates a ~543M-parameter GLM-4 MoE (1024 hidden, 24 layers, 8 experts) with random weights, copies the tokenizer from the original GLM-4 model, and verifies the HF↔prime-rl roundtrip is lossless:

uv run python scripts/mini_moe.py --arch glm4_moe --output-dir ./mini-glm-moe

To re-verify the roundtrip after a modeling-code change without re-creating the model:

uv run python scripts/mini_moe.py --arch glm4_moe --output-dir ./mini-glm-moe --verify-only

Warm up the random-weight mini model with SFT on reverse-text so KL divergence becomes meaningful in the RL phase. Loss drops from ~12 to ~2.5 — the output won't be coherent, but the distribution is non-trivial. A pre-built SFT'd checkpoint lives at samsja/mini-glm-moe if you want to skip this step:

uv run sft \
  --model.name ./mini-glm-moe \
  --data.name PrimeIntellect/Reverse-Text-SFT \
  --max_steps 200 \
  --optim.lr 1e-4 \
  --ckpt

Then run the full RL stack on reverse-text:

uv run rl @ configs/ci/integration/reverse-text-moe/start.toml \
  --model.name samsja/mini-glm-moe \
  --inference.vllm.gpu-memory-utilization 0.7 \
  --inference.vllm.max-model-len 2048

What to look for:

  • No crashes. Validates the full inference + orchestrator + trainer pipeline end-to-end.
  • Finite, non-zero KL. Confirms the reference distribution is meaningful.
  • Loss reasonable. Not NaN, not stuck.

Don't expect reward to climb meaningfully in 20 steps on a random model.

Requirements for merging a new model

Before merging a new model, you need to ensure the following:

  • The model is correctly registered and defines and all the required methods - such as convert_hf_layer_to_tt and convert_tt_layer_to_hf.
  • The small smoke test passes.

In the PR that adds the new model, you also need to provide a table covering the KL mismatch across 20 steps on math environment with batch_size=64. All the entries in the table must lower than 0.015. If this is not met, the PR will not be merged (unless reasonable justification is provided). This is to ensure all our models are consistent and their implementations match the implementations in the inference framework.

Adding a Custom VLM Implementation

VLM training (any run with [model.vlm] set, SFT or RL) is custom-implementation-only: get_model rejects models without a custom PrimeRL VLM class at load time. To make a new VLM family trainable, extend a custom text model with a composite VLM body. The unified dense/MoE Qwen3.5 implementation in models/qwen3_5/ is the reference. The pieces, in dependency order:

  1. Custom text model first. The VLM body wraps a custom *ForCausalLM (see Adding a New Model), so the text side — including its state-dict conversion and KL-mismatch table — comes first.
  2. Composite VLM body. A *VLMModel that holds the vision encoder and custom text model, embeds tokens, runs vision, scatters image embeddings over placeholder tokens, and builds MRoPE 3D positions from mm_token_type_ids whenever image_grid_thw is given (the renderer owns the token→modality mapping; the trainer always passes plain position_ids, which the model uses for text-only rows). Keep the vision encoder at model.model.visual and the text model at model.model.language_model: FSDP, freezing, activation checkpointing, compile, the MoE runtime and NCCL weight broadcast find them there (trainer/vlm.py). The unified *ForCausalLM dispatches on the config: composite config → VLM path, text config → text path.
  3. Always run the vision encoder. Text-only micro-batches must feed the encoder dummy pixels and graft the result into the graph with zero contribution (inputs_embeds + image_embeds.sum() * 0.0) so FSDP/EP collectives stay symmetric across ranks when the encoder is trainable.
  4. Packed-boundary consumption. Samples pack into shared rows with per-document boundaries in seq_lens; every custom model's forward() declares the typed seq_lens/seq_lens_are_pre_shard parameters (the trainer passes them unconditionally) and must honor the boundaries — varlen flash cu_seqlens, linear-attention state resets per document, and a loud rejection on attention paths that can't (see the packed-batch guard in any modeling file). Set supports_packed_multimodal_training on the VLM model once packed rows are handled — RL fails loudly at startup for VLM models without it.
  5. Registration. Register the composite model_type in _CUSTOM_VLM_MAPPING (models/__init__.py) so get_model dispatches to the custom class. RL turns raw image refs into vision kwargs with the model class's materialize_images(refs, processor); Qwen3.5 and Qwen3.8 Flash Next each define it in their vision.py, and a new family implements its own.
  6. Context parallelism (optional). CP-capable VLMs hold a CPContext on all modules which need to be CP-aware and shard embeds/positions inside the model after the vision merge; the trainers defer sharding to the model for every batch with images.
  7. Validation. Same bar as text models: the KL-mismatch table for the text path, plus an SFT run and an RL run on a real multimodal dataset (the color-codeword environment is the reference task).