Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c7dc7929a0 | ||
|
|
0d2a7f5a12 | ||
|
|
1cb5d91ab2 | ||
|
|
d05744678e | ||
|
|
67c20ba8c8 | ||
|
|
683377520e | ||
|
|
7a7dd80291 | ||
|
|
c012c45cf7 | ||
|
|
5af45e4310 | ||
|
|
e03be50a86 | ||
|
|
625b93c5e4 |
@@ -1,19 +1,3 @@
|
||||
# BugBot Instructions
|
||||
|
||||
## Changelog Enforcement
|
||||
|
||||
Any PR that introduces **breaking** configuration changes must update `CHANGELOG.md`. Breaking changes are those that require users to update existing configs:
|
||||
|
||||
- **Renamed** config fields (old name no longer accepted)
|
||||
- **Removed** config fields (field deleted or moved to a different path)
|
||||
- **Moved** config fields (field relocated in the config hierarchy)
|
||||
|
||||
Additive changes (new fields with defaults, new optional features) and default value changes do **not** require a changelog entry.
|
||||
|
||||
Config files live in:
|
||||
|
||||
- `src/prime_rl/configs/`
|
||||
|
||||
If breaking changes are detected without a corresponding `CHANGELOG.md` update, request that the author add an entry.
|
||||
|
||||
Any PR that introduces a new custom model must also provide a table showing mean KL mismatch across 20 steps on math environment on this new model with `batch_size=64`. All the entries in the table must lower than 0.015. If this is not present, request the author to add such a table.
|
||||
|
||||
-189
@@ -1,189 +0,0 @@
|
||||
# Changelog
|
||||
|
||||
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
|
||||
|
||||
- **fp32 MoE routing enabled by default**: `trainer.model.moe_router_dtype` (new field) defaults to `"float32"` — custom-impl MoE router gates keep fp32 weights through forward/backward (exempt from the FSDP bf16 cast) and compute the gate GEMM and routing logits in fp32. `inference.enable_fp32_router_logits` (new field) defaults to `true` — DeepSeek-family models served by vLLM (incl. GLM-5.x) emit fp32 router logits via `out_dtype=float32` on the gate. Both change MoE numerics for existing runs (routing logits are no longer rounded to bf16; near-tie expert selections can differ). Set `moe_router_dtype = "bfloat16"` / `enable_fp32_router_logits = false` to restore the previous behavior. Non-MoE and HF-impl models are unaffected. (2026-07-04)
|
||||
- **`[[orchestrator.train.env]].ratio` now defaults to `1` and no longer accepts unset/`None`**: Each train env's sampling weight defaults to `1` (equal weight per env) instead of `None`. The `None`-for-all-envs mode — which sampled proportional to each env's dataset size (the "natural task distribution") — is removed, along with the all-or-none constraint (any subset of envs may now set `ratio`; the rest default to `1`). Multi-env configs that relied on the old default now sample each env equally rather than proportional to dataset size; set each env's `ratio` explicitly to restore a proportional (or any other) mix. (2026-07-02)
|
||||
- **`orchestrator.algo.length_penalty` restructured to a single `linear` shape; `tokens`/`turns` length penalties removed**: The `grpo`-family length penalty keeps the `[orchestrator.algo.length_penalty]` key but is collapsed to a single `type = "linear"` shape; the discriminated `type = "tokens" | "turns"` efficiency-shaping variants (and the `efficiency_shaping` helper) are removed. The linear penalty subtracts a `pass_rate`-scaled penalty from each reward before the GRPO baseline, summing three terms — `num_output_tokens_weight` × output tokens, `num_input_tokens_weight` × input (non-output) tokens, and `num_turns_weight` × turns — each normalized by the group's own max for that quantity. Field renames within the penalty: `coef` → `num_output_tokens_weight` (default `0.25`), `context_coef` → `num_input_tokens_weight` (default `0.1`), `turns_coef` → `num_turns_weight` (default `0.1`); the `gate_by_correctness` flag is removed. `extra="forbid"` rejects the old keys, so existing configs must migrate. (2026-06-29)
|
||||
- **`model.fused_lm_head_token_chunk_size` `"auto"` option removed**: The `"auto"` value is no longer accepted. Use an explicit integer (e.g. `8192`) or `"disabled"`. The `"auto"` value previously resolved to `8192` for RL training — set `fused_lm_head_token_chunk_size = 8192` explicitly to get the same behavior.
|
||||
- **Memory-saving defaults enabled**: `trainer.model.ac`, `trainer.model.ac_offloading`, `trainer.model.compile`, `trainer.model.optim_cpu_offload`, and `trainer.model.fused_lm_head_token_chunk_size` are now enabled by default to provide sane memory-efficient defaults out of the box. Specifically: `ac` defaults to `ActivationCheckpointConfig()` (full mode), `ac_offloading` defaults to `ActivationOffloadingConfig()`, `compile` defaults to `CompileConfig()` (`fullgraph=false`), `optim_cpu_offload` defaults to `true`, and `fused_lm_head_token_chunk_size` defaults to `1024`. SFT training silently disables `fused_lm_head_token_chunk_size` (sets it to `"disabled"`). Configs using `max_concurrent_runs > 1` must explicitly set `optim_cpu_offload = false`. To disable any of these, set the field to `None` / `"None"` / `false` / `"disabled"` as appropriate.
|
||||
- **`model.ep` defaults to `"auto"`**: The `ep` field type changed from `int` to `int | Literal["auto"]`, defaulting to `"auto"`. At trainer startup, `resolve_ep()` checks if the model is MoE (via `AutoConfig`); if so, it resolves to `min(fsdp_island_size, 8)` where `fsdp_island_size = world_size // dp_replicate`. For non-MoE models, `"auto"` resolves to 1 (no-op). Set `ep` to an explicit integer to override.
|
||||
- **verifiers v1 training integration** (collection of removals/renames). The orchestrator now trains against a v1 env server returning `vf.Trace` rollouts, renderer-only, with a unified token schema.
|
||||
- **`[[orchestrator.train.env]]` is now a v1 `vf.EnvServerConfig`**: a v1 env is `taskset = { id = "<id>" }` + `harness = { id = "default", runtime = { type = "subprocess" } }`. A bare `id = "<id>"` (optionally with `args`) runs the v0 env through the verifiers legacy bridge — old flat `id`/`args`-only configs keep working as legacy envs; v1 envs must use the `taskset`/`harness` shape.
|
||||
- **`orchestrator.train.env` no longer defaults to a `reverse-text` env**: the default is now empty (`[]`), so configs must declare `[[orchestrator.train.env]]` explicitly.
|
||||
- **`...env[].num_workers` → `pool`**: per-env worker sizing moves to a `pool` config (`static`/`elastic`). Back-compat: `num_workers = N` maps to `pool = { type = "static", num_workers = N }` and `"auto"` to the default elastic pool; the group-level `orchestrator.train.num_workers` / `orchestrator.eval.num_workers` are removed.
|
||||
- **`orchestrator.renderer` is now required (MITO removed)**: it was `RendererConfig | None`, where `renderer = None` selected the MITO path; training is now renderer-only, so `renderer` is non-optional. Drop `renderer = None` / `renderer = "None"`.
|
||||
- **`...client.timeout` / `...client.connect_timeout` removed**: the v1 rollout client manages its own timeouts. Drop these from `[orchestrator.student.client]` and `[orchestrator.teacher.client]`. (2026-06-23)
|
||||
- **`orchestrator.advantage` length-penalty overhaul + length-weighted baseline**: `length_penalty` is now a single shape — a linear penalty that subtracts `coef * pass_rate * (model completion tokens / orchestrator.seq_len)` from each reward before the baseline subtraction (`pass_rate` = group mean reward, so solved-often problems get the strongest concision pressure and never-solved groups get none), with an optional `gate_by_correctness` flag (default `false`) that restricts the penalty to correct rollouts (`reward == 1`). The previous discriminated `type = "tokens" | "turns"` efficiency-shaping variants and the per-penalty `max_length` field have been removed — configure `[orchestrator.advantage.length_penalty]` with `coef` (and optionally `gate_by_correctness`) instead; the denominator is always `orchestrator.seq_len`. Also adds `orchestrator.advantage.length_weighted_baseline` (default `false`): when enabled, the GRPO baseline is the token-length-weighted mean reward (`sum(len_i * reward_i) / sum(len_i)`) instead of the plain mean. (2026-06-03)
|
||||
- **`trainer.experimental.token_export` removed → `trainer.enable_token_export`**: `TrainerExperimentalConfig` and the `[trainer.experimental] token_export = true` setting have been removed with no migration alias. Existing trainer configs must delete the `[trainer.experimental]` block and set the new top-level trainer flag instead: `enable_token_export = true` in a trainer config file, or `trainer.enable_token_export = true` when nested under `[trainer]` in an RL config. The trainer entrypoint CLI flag is `--enable-token-export`. (2026-06-10)
|
||||
- **`inference.kv_cache_offload.cpu_bytes` removed → discriminated `type` config**: The flat `[inference.kv_cache_offload]` block with a single `cpu_bytes` field is replaced by a backend-discriminated union with composable `cpu`/`disk` tiers. Migrate native CPU offload from `[inference.kv_cache_offload]\ncpu_bytes = N` to `[inference.kv_cache_offload]\ntype = "native"` plus `[inference.kv_cache_offload.cpu]\nnum_bytes = N`. A `type = "mooncake"` backend (per-node distributed store; multi-node/SLURM only) and an optional `[inference.kv_cache_offload.disk]\npath = "..."` tier (layered behind cpu) are also available. `extra="forbid"` rejects the old `cpu_bytes` key, so existing configs must migrate. (2026-06-02)
|
||||
- **Orchestrator async-pipeline rewrite** (collection of removals/renames). The orchestrator was rewritten to overlap train/eval rollouts on a shared concurrency limiter; several config fields were removed or renamed.
|
||||
- **`orchestrator.seed` removed**: was only consumed by the deleted buffer; no replacement.
|
||||
- **`orchestrator.eval.eval_base_model` → `orchestrator.eval.skip_first_step`** (semantics inverted): `eval_base_model = true` becomes `skip_first_step = false` (the default — run the step-0 eval before any train rollouts). No alias; configs setting `eval_base_model` must rename.
|
||||
- **`orchestrator.eval.skip_eval_on_resume` (and its alias `skip_eval_on_restart`) removed**: folded into `skip_first_step`. Resume no longer re-fires an already-completed eval (deduped via per-env last-eval-step tracking in the checkpointed progress).
|
||||
- **`orchestrator.eval.cancel_inflight_rollouts_on_eval` removed**: the drain-switch overlap (stop scheduling new train, let in-flight train drain while eval queues) is now the only eval transition mode.
|
||||
- **`ckpt.skip_buffer` removed**: there is no buffer to skip.
|
||||
- **`[orchestrator.buffer]` removed** (difficulty pools): the whole block and every key (`seed`, `easy_threshold`, `hard_threshold`, `easy_fraction`, `hard_fraction`, `online_difficulty_filtering`, `hash_keys`) are gone, with no alias — `extra="forbid"` rejects the block, so existing configs must delete it. To preserve `online_difficulty_filtering = true`, enforce the zero-advantage pre-batch filter: `[[orchestrator.pre_batch_filters]]\ntype = "zero_advantage"\nenforce = true`.
|
||||
- **`orchestrator.filters` → `orchestrator.post_batch_filters`** (renamed, no alias): existing configs setting `[[orchestrator.filters]]` must rename to `[[orchestrator.post_batch_filters]]` (`extra="forbid"` rejects the old key). A new `pre_batch_filters` list is also available. Filters are **train-only** now — eval rollouts are no longer filtered.
|
||||
- **`orchestrator.max_off_policy_steps` now also applies to eval** (behavior change, field unchanged): eval rollouts that fall more than `max_off_policy_steps` versions behind the policy are cancelled, same as train. (2026-05-29)
|
||||
- **`sampling.min_tokens`, `sampling.repetition_penalty`, `sampling.seed` removed**: Dropped from both `TrainSamplingConfig` and `EvalSamplingConfig` (group-level `[orchestrator.train.sampling]` / `[orchestrator.eval.sampling]` and per-env `[[orchestrator.train.env.sampling]]` / `[[orchestrator.eval.env.sampling]]`). `min_tokens` suppressed natural EOS, `repetition_penalty` distorts the on-policy sampling distribution, and `seed` wasn't pulling its weight — none belonged on the supported config surface. Existing configs setting any of these must delete the field. Hard-deprecation, no migration window. (2026-05-27)
|
||||
- **`wandb.shared` removed**: The deprecation shim that popped `wandb.shared` from input dicts with a `FutureWarning` (introduced in #2649) is gone. The `rl` entrypoint always uses shared W&B mode now, and existing configs that still set `wandb.shared = true` (or `false`) will fail validation. Drop the field from your config. (2026-05-27)
|
||||
- **`max_async_level` and `strict_async_level` removed**: The async-execution semantics between trainer and orchestrator are now design invariants, not config knobs. The trainer always runs exactly one step ahead of inference, and the orchestrator always adopts the freshest checkpoint that doesn't violate the one-step barrier. The shared top-level `max_async_level`, the per-sub-config `trainer.max_async_level` / `orchestrator.max_async_level`, and `orchestrator.strict_async_level` have all been removed. Existing configs setting any of these must drop the field; the previous defaults (`max_async_level = 1`, `strict_async_level = false`) match the new hardcoded behavior. Bench mode no longer bypasses the weight-ckpt wait (the `int(1e9)` workaround is gone) and `multimodal/rl_color_codeword_feat_renderer.toml`'s prior `max_async_level = 0` (fully synchronous on-policy) is no longer expressible. (2026-05-25)
|
||||
- **`teacher_inference` removed from RL entrypoint**: The `[teacher_inference]` config block and the `deployment.num_teacher_gpus` / `deployment.num_teacher_nodes` fields have been removed. The `rl` entrypoint now only manages the student-policy inference server. External teachers (used by OPD and local-vLLM SFT) must be started manually (e.g. `CUDA_VISIBLE_DEVICES=1 uv run inference --model.name <teacher> --server.port 8001 ...`) and pointed at via `[orchestrator.teacher.client]`. Existing configs using `[teacher_inference]` or `deployment.num_teacher_gpus` / `deployment.num_teacher_nodes` must drop those fields and bring up the teacher out-of-band. (2026-05-25)
|
||||
- **`rollouts_per_example` → `group_size`**: The orchestrator-level field, the group-level `[orchestrator.eval]` field, and the per-env `[[orchestrator.eval.env]]` field have all been renamed. The old name still parses as a validation alias (in both TOML and CLI), so existing configs keep working without changes; new configs should prefer `group_size`. (2026-05-22)
|
||||
- **`AdvantageInputs` / `AdvantageOutputs` are now per-group, and `AdvantageOutputs.advantages` is a plain `list[float]`** (second breaking change to this API in three weeks). `AdvantageInputs.rollouts` is now `list[vf.RolloutOutput]` (a single group) instead of `list[list[vf.RolloutOutput]]`, and `AdvantageOutputs.advantages` is now `list[float]` instead of a 2D `Float[Tensor, "num_examples rollouts_per_example"]`. `compute_advantages` calls `advantage_fn` once per group, which lets partial-group training (groups smaller than `rollouts_per_example` after rollout errors) round-trip without the previous bucket-by-size workaround. Custom advantage functions must drop the outer list dimension and return a list of floats — e.g. `AdvantageOutputs(advantages=(rewards - rewards.mean(dim=1, keepdim=True)).tolist())` becomes `AdvantageOutputs(advantages=[r - mean for r in rewards])` (or `.tolist()` if you keep torch internally). (2026-05-22)
|
||||
- **`[model.vlm]` requires `orchestrator.use_renderer = true`**: VLMs must go through the renderer path; the `vlm_requires_renderer` validator rejects `use_renderer = false` when `[model.vlm]` is set. The renderer owns the HF processor per-slot and ships generic `mm_kwargs` keyed by the model's forward signature. Since `use_renderer` already defaults to `true`, most VLM configs need no change. (2026-05-19)
|
||||
- **First-class `training_mode` + batch-driven loss dispatch** (collection of removals/renames). Loss selection is now driven by `TrainingSample.training_mode` (`rl` / `opd` / `sft`), set under `[orchestrator]`. The trainer is mode-agnostic and dispatches per batch.
|
||||
- **`orchestrator.use_sft_loss` removed**: replaced by `[orchestrator] training_mode = "sft"`. The orchestrator stamps each sample's `training_mode` and the trainer dispatches to `sft_loss_fn` per batch.
|
||||
- **`orchestrator.teacher_rollout_model` removed (no alias)**: configs must rename to `[orchestrator.teacher]` (`teacher_model` is also accepted as a back-compat alias for `teacher`). Used in both opd and sft modes; the role is determined by `training_mode`.
|
||||
- **`orchestrator.model` → `orchestrator.student`**: renamed for symmetry with `orchestrator.teacher`. Legacy `[orchestrator.model]` and a flat `[orchestrator.model.lora]`-style layout are aliased via a back-compat shim, so most existing configs still parse. New code should use `[orchestrator.student.*]`.
|
||||
- **`trainer.loss.type = "sft"` removed (`SFTLossConfig` deleted)**: zero-field discriminator that is now implied by `training_mode = "sft"`. `trainer.loss` collapsed to a `DefaultLossConfig | CustomLossConfig` union. Existing configs setting `[trainer.loss] type = "sft"` must remove that line; the orchestrator-level `training_mode = "sft"` is enough.
|
||||
- **`trainer.loss.teacher_tau` removed from `DefaultLossConfig`**: the teacher-KL term is now exclusive to `opd_loss_fn` (which inlines `teacher_tau = 1.0`). `default_loss_fn` only handles reward-driven RL and no longer accepts a `teacher_tau`. Configs that set `teacher_tau` on `[trainer.loss]` will fail validation — switch to `[orchestrator] training_mode = "opd"` (which uses `opd_loss_fn` with the value baked in).
|
||||
- **`trainer.loss` only applies to rl-mode batches**: opd and sft don't read `trainer.loss`. `opd_loss_fn`'s knobs (dppo_mask_*, kl_tau) are inlined as literals; tweak them by editing the function. `CustomLossConfig` overrides the rl-mode loss only — opd and sft always use their dedicated fns. (2026-05-19)
|
||||
- **`orchestrator.use_token_client` removed**: The server-tokenized TITO path has been deprecated end-to-end. The orchestrator-side config flag (`use_token_client`), the verifiers client_type (`openai_chat_completions_token`), and the inference server's `/v1/chat/completions/tokens` route (along with the `OpenAIServingChatWithTokens` wrapper) are all gone. The orchestrator now picks between renderer-backed TITO (`use_renderer = true`, default) and MITO (`use_renderer = false`, fallback). Existing configs with `use_token_client = true` must migrate to `use_renderer = true` (or `use_renderer = false` for MITO); configs with `use_token_client = false` can simply drop the field. (2026-05-19)
|
||||
- **`orchestrator.advantage.length_penalty` → discriminated sub-config**: The scalar `length_penalty: Literal["tokens","turns"] | None` is replaced by a `LengthPenaltyConfig | None` discriminated on `type`. Token shaping now takes weighted completion + tool-response token costs. Migration: `length_penalty = "tokens"` becomes `[orchestrator.advantage.length_penalty]\ntype = "tokens"` (default weights `completion_weight = 1.0`, `tool_response_weight = 1.0` — total context). `length_penalty = "turns"` becomes `[orchestrator.advantage.length_penalty]\ntype = "turns"`. (2026-05-06)
|
||||
- **`orchestrator.advantage.length_shaping` → `orchestrator.advantage.length_penalty`**: The boolean `length_shaping` flag has been replaced by `length_penalty: Literal["tokens", "turns"] | None` (default: `None`). `length_shaping = true` becomes `length_penalty = "tokens"`; `length_shaping = false` becomes `length_penalty = None`. The new `"turns"` option applies the same correctness-gated efficiency shaping using trajectory turn count instead of completion-token count. (2026-05-01)
|
||||
- **`AdvantageInputs` API**: Replaced the `rewards`/`completion_lengths`/`num_turns` tensor fields with a single `rollouts: list[list[vf.RolloutOutput]]` (grouped by problem). Custom advantage functions can now access any rollout metadata. Existing custom advantages must update their signatures and extract per-rollout fields directly (e.g. `torch.tensor([[r["reward"] for r in g] for g in inputs.rollouts])`). (2026-05-01)
|
||||
- **`orchestrator.teacher_rollout_model` now requires `orchestrator.use_sft_loss = true`**: External teacher rollout configs no longer rely on `trainer.loss.type = "sft"` to select SFT loss. Existing hard-distill configs must set `orchestrator.use_sft_loss = true` alongside `orchestrator.teacher_rollout_model`; the orchestrator validates the pair and stamps training samples with the per-batch SFT loss bool. (2026-04-26)
|
||||
- **`model.attn = "eager"` (NEW option)**: Added `eager` as a valid value for the `model.attn` field. Required for GPT-OSS models on non-Hopper GPUs, since the only flash attention kernel GPT-OSS supports (`kernels-community/vllm-flash-attn3`) is Hopper-only. A clear error message is raised at model load time if GPT-OSS is used without `eager` on unsupported hardware. Also added `kernels` as a core dependency. (2026-04-05)
|
||||
- **`[[orchestrator.env]]` → `[[orchestrator.train.env]]`**: Training environments and sampling are now configured under `[orchestrator.train]`. The old `[[orchestrator.env]]` and `[orchestrator.sampling]` paths are auto-translated with a deprecation warning and will be removed in a future release. (2026-04-09)
|
||||
- **Per-env sampling overrides (NEW)**: Both `TrainEnvConfig` and `EvalEnvConfig` now accept a `[sampling]` section for per-env overrides. Unset fields inherit from the group-level sampling config (`[orchestrator.train.sampling]` or `[orchestrator.eval.sampling]`). (2026-04-09)
|
||||
- **Per-env eval sampling overrides**: `EvalEnvConfig` now accepts a `[sampling]` section. Unset fields inherit from `[orchestrator.eval.sampling]`. All `EvalSamplingConfig` fields remain nullable (None = defer to inference server default). (2026-04-09)
|
||||
- **`orchestrator.buffer.env_ratios` → per-env `orchestrator.train.env[].ratio`**: `buffer.env_ratios` has been removed. Set `ratio` on each `[[orchestrator.train.env]]` entry instead. Ratios must be all-or-nothing across envs (either all have a ratio or none do). (2026-04-05)
|
||||
- **`orchestrator.val` removed**: The `[orchestrator.val]` config section (`ValConfig`) has been removed. Existing configs must delete this section. (2026-04-05)
|
||||
- **`orchestrator.max_concurrent` removed**: Concurrency limiting via `max_concurrent` and the global semaphore have been removed. Existing configs must delete this field. (2026-04-05)
|
||||
- **`orchestrator.buffer.hash_keys` default changed**: Default changed from `["task", "prompt"]` to `["env_name", "prompt"]`. The `task` field is no longer overridden by the orchestrator for env identification; `env_name` is used instead. Buffer checkpoints using the old default may not resume correctly. (2026-04-05)
|
||||
- **`orchestrator.eval.env[].failed_rollouts` metric is now a ratio**: The `eval/{name}/failed_rollouts` metric now reports a ratio (0.0–1.0) instead of a raw count. Dashboards keying on this metric should be updated. (2026-04-05)
|
||||
- **`orchestrator.sampling.temp_scheduler` removed**: Temperature scheduling (`TemperatureSchedulerConfig`) has been removed. `sampling.temperature` is now a required `float` (default `1.0`). Existing configs using `temp_scheduler` must replace it with a fixed `temperature` value. (2026-04-05)
|
||||
- **`orchestrator.verification` removed**: The `[orchestrator.verification]` config section (`VerificationConfig`) has been removed. Rollout scoring is now always enabled. Existing configs must delete this section. (2026-04-05)
|
||||
- **`orchestrator.eval.env[].skip_first` removed**: The `skip_first` field on `EvalEnvConfig` has been removed. Existing configs using this field must delete it. (2026-04-05)
|
||||
- **`EvalSaveHFConfig` removed**: Unused config class removed. (2026-04-09)
|
||||
- **`orchestrator.env[].max_total_completion_tokens` (NEW)**: Added `max_total_completion_tokens: int` to `EnvConfig` (default: `-1`, disabled). Limits the total completion tokens across all turns in a multi-turn rollout. Auto-populated into `extra_env_kwargs` and applied via the verifiers `set_max_total_completion_tokens()` setter. Works for both training and eval environments. (2026-04-06)
|
||||
- **`sampling.max_tokens` → `sampling.max_completion_tokens`**: Renamed `max_tokens` to `max_completion_tokens` in both `SamplingConfig` and `EvalSamplingConfig` for consistency with OpenAI API naming. The old name is accepted with a deprecation warning. (2026-04-06)
|
||||
- **`log.file` and `log.env_worker_logs` removed**: Removed `log.file` (from `LogConfig` and `SharedLogConfig`) and `log.env_worker_logs` (from `LogConfig`). Python file logging is replaced by deployment-level capture. Existing configs using these fields must delete them. Log paths unified: `.stdout` files renamed to `.log`, SLURM logs moved from `slurm/` to `logs/`. (2026-03-31)
|
||||
- **`trainer.log.ranks_filter` (NEW)**: Added `ranks_filter: list[int]` to `TrainerLogConfig` (default: `[0]`). Controls which ranks appear in trainer console output via torchrun's `--local-ranks-filter`. (2026-03-31)
|
||||
- **`wandb.log_extras.sample_ratio` / monitor sample logging defaults**: `wandb.log_extras.sample_ratio` is now actually applied to W&B sample-table logging via the shared monitor sampler (it was previously a no-op for WandB). Separately, the orchestrator no longer hard-caps sample logging to 8 rollouts before monitor-level sampling runs, so when monitor `sample_ratio` is `None`, monitors now receive and may log the full rollout batch for a step instead of at most 8 rollouts. This affects both W&B and Prime monitor sample logging behavior. (2026-03-27)
|
||||
- **`[model.vlm].freeze_vision_encoder`**: Added to `VLMConfig`. Controls whether the vision encoder is frozen (default: `true`). When `false`, the vision encoder is trainable and FSDP-sharded per-block. Has no effect with LoRA. Moved from `[trainer.model].freeze_vision_encoder` into the VLM sub-config. (2026-03-25)
|
||||
- **`loss_impl = "quack_fused"` (SFT)**: Added `quack_fused` option for the SFT `loss_impl` field. Uses quack-kernels for chunked linear + cross-entropy with CuTe DSL CUDA kernels, avoiding full logits materialization. Requires `quack-kernels` package. Does not support Gemma logit softcapping. Custom model impl (`model.impl = "custom"`) also gains quack RMSNorm acceleration on CUDA automatically. (2026-03-26)
|
||||
- **`model.ac.targets`**: Removed the `mamba` selective activation checkpoint target and folded that behavior into the broader `linear_attn` target. Existing configs using `targets = ["mamba"]` will now fail validation at runtime with `ValueError`; switch them to `targets = ["linear_attn"]`. The `linear_attn` target description now covers supported token mixers outside the standard softmax-attention path, including NemotronH Mamba layers, Qwen3.5-MoE GatedDeltaNet layers, and AFMoE sliding-window attention layers. (2026-03-28)
|
||||
- **`model.tp` (trainer `ModelConfig`)**: Removed from the trainer model config. Existing trainer configs must delete this field; it is no longer accepted. (2026-03-26)
|
||||
- **`orchestrator.env[].num_workers`**: Added configurable env server worker count (`int | "auto"`, default: `"auto"`). When `"auto"`, scales based on concurrency (1 worker per 256 concurrent rollouts). Only used when the orchestrator spawns the env server (i.e. `address` is not set). (2026-03-25)
|
||||
- **`[model.vlm]` (NEW — replaces auto-detection)**: VLM mode is now opt-in via a `[model.vlm]` sub-config with required `vision_encoder_attr` and `language_model_attr` fields. There is no auto-detection — if you train a VLM, you must add `[model.vlm]`. Existing multimodal configs need the new section. See `docs/multimodal.md` for the table of known model attrs. (2026-03-24)
|
||||
- **`model.optimization_dtype` / `model.reduce_dtype` (VLM models, RL only)**: VLM dtype validation now only applies to RL training (`TrainerConfig`), not SFT. VLM models used with `sft` no longer require `optimization_dtype='bfloat16'` / `reduce_dtype='bfloat16'`. RL training still enforces both to match vLLM inference. (2026-03-24)
|
||||
- **`model.ep_comm_backend`**: Added expert-parallel communication backend selection. Accepted values are `torch` (default, uses TorchTitan all-to-all collectives) and `deepep` (uses DeepEP custom kernels). This field only affects configurations with expert parallelism enabled via `model.ep > 1`. (2026-03-22)
|
||||
- **`model.deepep_num_sms`**: Added DeepEP SM allocation control for intranode dispatch/combine kernels (default: `20`, minimum: `1`). This field is only used when `model.ep_comm_backend='deepep'`; it also determines the internode RDMA channel count (`num_channels = num_sms / 2`). (2026-03-22)
|
||||
- **`model.deepep_token_chunk_size`**: Added optional token chunk size for DeepEP MoE pipelining (default: `None`, minimum: `1`). When set, DeepEP dispatch for chunk `i+1` overlaps expert compute for chunk `i`. This field is only used when `model.ep_comm_backend='deepep'`. (2026-03-22)
|
||||
- **`model.optimization_dtype` / `model.reduce_dtype` (VLM models)**: Added validation that VLM models must use `optimization_dtype='bfloat16'` and `reduce_dtype='bfloat16'` to match vLLM inference. Previously valid configs with `float32` (the default) are now rejected for VLM model names. Set both fields to `"bfloat16"` when training VLMs. (2026-03-21)
|
||||
- **`model.ac.mode`** and **`model.ac.targets`**: Added selective activation checkpointing configuration. `model.ac.mode` accepts `full` (default) or `selective`. When `selective`, `model.ac.targets` selects subcomponents to checkpoint. Supported public targets are currently `norm`, `attention_sdpa`, `mla_up_proj`, and `routed_experts`; runtime validation remains the source of truth. `model.ac.targets` defaults to `["norm"]`, and selective mode requires at least one target. (2026-03-20)
|
||||
- **`orchestrator.advantage.length_shaping_alpha` → `orchestrator.advantage.length_shaping`**: Replaced GR³ (`length_shaping_alpha: float | None`) with correctness-gated efficiency shaping (`length_shaping: bool`, default: `false`). No hyperparameter needed, no `online_difficulty_filtering` requirement. Existing configs using `length_shaping_alpha` must switch to `length_shaping = true`. (2026-04-13)
|
||||
- **`orchestrator.advantage.length_weighted_mean`**: Removed. The default advantage now always uses the plain per-problem mean baseline unless `orchestrator.advantage.length_shaping` is enabled. Existing configs must delete this field. (2026-03-19)
|
||||
- **`prime_monitor.log_extras.sample_ratio`**: Added ratio-based rollout sampling (0.0–1.0, default: None). When set, caps the number of rollouts logged per step to `len(rollouts) * sample_ratio`. `None` preserves current behavior (log all rollouts). Interacts with existing `interval` gate which still runs first. (2026-03-12)
|
||||
- **`client.connect_timeout`**: Added configurable TCP connect timeout for inference API requests (default: 30.0s). Previously hardcoded to 5.0s. Helps with vLLM or cluster flakiness (2026-03-11)
|
||||
- **`model.fused_lm_head_token_chunk_size`**: Added as the fused LM-head chunking field for the token-chunked implementation. Unlike the removed `model.fused_lm_head_chunk_size`, this chunks over flattened sequence tokens rather than vocabulary rows. `model.fused_lm_head_chunk_size` is no longer accepted; switch configs to `model.fused_lm_head_token_chunk_size` explicitly. (2026-03-09)
|
||||
- **`slurm.pre_run_command`**: Added optional shell command to run on the head node before starting the job. Useful for cleanup routines (e.g. killing stale processes, removing lock files). For all-nodes execution, wrap with `srun` in the command string (default: None) (2026-03-08)
|
||||
- **`slurm.nodelist`**, **`slurm.exclude`**, **`slurm.account`**, **`slurm.time`**: Added common SLURM scheduling options (all default: None) (2026-03-08)
|
||||
- **`orchestrator.verification.enabled`**: Added top-level rollout verification switch. `orchestrator.buffer.skip_verification` has been removed; use `verification.enabled = false` instead. When disabled, rewards are always 0 and reward-dependent buffer features (`online_difficulty_filtering`, `easy_threshold`, `hard_threshold`) must be unset (2026-03-03)
|
||||
- **`client.dp_rank_count`**: Added configuration for data-parallel inference routing. When > 1, each `client.base_url` is expanded into `dp_rank_count` logical clients and pinned via `X-data-parallel-rank` to keep multi-turn rollouts on a consistent DP rank (default: 1) (2026-03-03)
|
||||
- **`model.lora`**: Moved from `model.experimental.lora` to `model.lora` (no longer experimental) (#1440, 2025-12-16)
|
||||
- Auto-set `api_server_count=1` on inference when LoRA is enabled, because vLLM doesn't support hotloading for multiple API servers (#1422, 2025-12-17)
|
||||
- **`inference.model.rope_scaling`**: Added RoPE scaling configuration passthrough to vLLM (#1447 2025-12-17)
|
||||
- **`orchestrator.env_mix`**: Deprecated in favor of `orchestrator.buffer.env_ratios` (#1450, 2025-12-18)
|
||||
- **`orchestrator.buffer.hash_keys`**: Added hash keys configuration for buffer checkpointing (#1450, 2025-12-18)
|
||||
- **`orchestrator.buffer.env_ratios`**: Added environment ratio configuration for buffer sampling (#1450, 2025-12-18)
|
||||
- **`orchestrator.buffer.skip_verification`**: Added configuration to skip verification of rollouts using the environment's rubric. If True, rewards are always set to 0. Cannot be used with `online_difficulty_filtering=True` or when `easy_threshold`/`hard_threshold` are set (default: False)
|
||||
- **`orchestrator.ckpt.buffer_path`**: Deprecated (#1450, 2025-12-18)
|
||||
- **`orchestrator.buffer.easy_fraction`** and **`orchestrator.buffer.hard_fraction`**: Easy and hard fraction now defines the fraction of easy and hard problems to convert to normal when resuming, whereas previously it was the ratio of easy/ hard samples to sample per step (#1450, 2025-12-18)
|
||||
- **`orchestrator.teacher_model`**: Added teacher model configuration for computing teacher logprobs (e.g. for distillation). Supports `TeacherModelConfig` (custom model) or `None` (disabled). Renamed from `reference_model` (2025-12-20)
|
||||
- **`seq_len`**: Added root-level `seq_len` config that sets both `trainer.model.seq_len` and `orchestrator.seq_len`. Added validation that `trainer.model.seq_len >= orchestrator.seq_len` (2025-12-18)
|
||||
- **`trainer.loss.sequence_mask_ratio_low`** and **`trainer.loss.sequence_mask_ratio_high`**: Renamed to `trainer.loss.sequence_mask_low` and `trainer.loss.sequence_mask_high` (2025-12-19)
|
||||
- **`trainer.loss.token_mask_high`** and **`trainer.loss.token_mask_low`**: Added token-level importance ratio masking thresholds (2025-12-19)
|
||||
- **`trainer.loss.sequence_clip_high`**: Added sequence-level importance ratio clipping threshold (2025-12-19)
|
||||
- **`trainer.loss.geo_mask_high`** and **`trainer.loss.geo_mask_low`**: Added geometric importance ratio masking thresholds (2025-12-19)
|
||||
- **`trainer.loss.adv_tau`**: Added tau parameter for advantages (default: 1.0)
|
||||
- **`trainer.loss.teacher_tau`**: Added tau parameter for teacher logprobs (default: 0.0). Renamed from `ref_tau`
|
||||
- **`teacher_gpu_ids`**: Added GPU IDs for teacher inference server. When set, automatically starts a teacher inference server and configures `orchestrator.teacher_model`
|
||||
- **`teacher_inference`**: Added optional teacher inference config. Defaults to copying from `inference` config with port 8001
|
||||
- **`{orchestrator,trainer}.transport.zmq`**: Added ZMQ transport for training batches and micro batches (#1446, 2025-12-22)
|
||||
- **`model.impl`**: Changed default from `hf` to `auto`. With `auto`, the implementation automatically selects `custom` if supported for the model, otherwise falls back to `hf` (#1488, 2025-12-27)
|
||||
- **`orchestrator.eval.skip_eval_on_resume`**: Added flag (default `True`) to skip the first potentially redundant online eval immediately after resuming from a checkpoint (#1491, 2025-12-27)
|
||||
- **`trainer.weight_broadcast.adapter_only`**: Removed. Adapter-only behavior is now automatically derived from the presence of LoRA configuration (2025-12-27)
|
||||
- **`ckpt.keep`**: Renamed to `ckpt.keep_last`. Added `ckpt.keep_interval` to keep checkpoints at every N steps permanently (2025-12-31)
|
||||
- **`MultiLoRAMoE`**: QwenMoE now supports training expert loras and this is enabled by default in the `target_modules`. (2026-01-01)
|
||||
- **`model.fused_lm_head_chunk_size`**: Added chunk size configuration for fused LM head to enable memory-efficient chunked logprob computation. When set, splits vocabulary into chunks to avoid materializing full [N, V] logit tensor (default: None) (#1525, 2026-01-03)
|
||||
- **`model.fused_lm_head_chunk_size`**: RL training now auto-sets this to 2048 if not specified (except when `impl='liger_kernel'`). SFT training continues to use None (2026-01-05)
|
||||
- **`trainer.metrics_server`**: Added optional Prometheus metrics server for trainer observability. Exposes `/metrics` endpoint with step, loss, throughput, grad_norm, etc. Disabled by default (default: None) (#1547, 2026-01-06)
|
||||
- **`model.lora.alpha`**: Changed default from 16.0 to 32.0 (2026-01-10)
|
||||
- **`orchestrator.env.log`**: Added logging configuration for environment workers. If set, enables logging with `level` (str, default: "warn") and `vf_level` (str, default: "warn") fields. If None (default), logging is disabled (#1561, 2026-01-13)
|
||||
- **`eval.watcher`**: Added flag (default `False`) to watch `weights_dir` for newly-created stable checkpoints and evaluate them as they appear (2026-01-14)
|
||||
- **`orchestrator.log.env_worker_logs`**: Added flag (default `False`) to write env worker logs to `logs/env_workers/{env_name}.log` (2026-01-15)
|
||||
- **`orchestrator.env.log`**: Removed. Use `orchestrator.log` for env worker logging instead (2026-01-15)
|
||||
- **`orchestrator.eval.retry.reraise`**: Changed default from `True` to `False`. When `False`, raises `tenacity.RetryError` after retries are exhausted instead of the original exception, allowing failed eval environments to be skipped with a warning (#1586, 2026-01-14)
|
||||
- **`model.ep`**: Expert parallelism now supported (with auto/custom impl only), changed from the old behaviour when `ep>1` was a no-op to a proper parallelization of the MoE layers. (#1595, 2026-01-15)
|
||||
- **`orchestrator.reload_weights_on_start`**: Removed. The reload was a no-op in practice since vLLM servers already start with base weights, and LoRA runs skipped it. (#1829, 2026-02-19)
|
||||
- **`orchestrator.client.elastic`**: Added elastic inference pool with DNS-based service discovery. Supports dynamic server scaling via any DNS hostname with multiple A records (Kubernetes headless services, Consul, Route53, etc.). Automatically syncs LoRA adapters on new servers and only exposes ready servers to workers (#1617, 2026-01-19)
|
||||
- **`model.fused_lm_head_chunk_size`**: Replaced chunk size `int | None` setting with `int | Literal["auto", "disabled"]` setting. `auto` auto-sets to 2048 if possible. `disabled` explicitly disables chunked loss (use vanilla LM head). Default behaviour is to use `auto` for RL training and `disabled` for SFT training. (not changed from previous version) (#1649, 2026-01-23)
|
||||
- **`client.skip_model_check`**: Added configuration to skip checking if the model is available in the inference pool. Useful for external APIs or API keys that don't support the /models endpoint (default: False) (#1543, 2026-01-06)
|
||||
- **`orchestrator.sampling.temp_scheduler`**: Added optional temperature schedule configuration with linear and cosine schedules. Set either `sampling.temperature` (constant) or `sampling.temp_scheduler` (schedule), not both. Default remains 1.0 if neither is set. (2026-01-27)
|
||||
- **`orchestrator.trajectory_strategy`**: Deprecated. Interleaving now automatically handles extension breaks by starting a new sample when the prefix doesn't match, achieving best-of-both behavior. The setting is ignored and interleaved mode is always used. (2026-01-30)
|
||||
- **`model.impl`**: Removed `liger_kernel` model implementation from supported options. The Liger kernel dependency remains for SFT loss. (2026-01-30)
|
||||
- **`log.json_logging`**: Added JSON structured logging option for log aggregation systems (Loki, Grafana, etc.). Outputs flat newline-delimited JSON with `timestamp`, `level`, `message`, `module`, `function`, `line` fields. Available on root `log`, `trainer.log`, and `orchestrator.log` (default: False) (2026-01-28)
|
||||
- **`model.optim_cpu_offload`**: Added flag to offload optimizer states to CPU without moving parameters (default: False) (2026-01-31)
|
||||
- **`orchestrator.tasks_per_minute`**: Added optional rate limiting for sandbox tasks per environment worker. Uses token bucket algorithm. If None (default), no rate limiting is applied (2026-02-02)
|
||||
- **`model.cp`**: When `cp>1` with `attn="flash_attention_3"`, require `model.impl="custom"` (FA3 ring-attention kernel only in custom path) (2026-02-06)
|
||||
- **`model.attn`**: Added `fa4` as an attention implementation option. Flash attention 4 is only supported with the custom implementation (#1726, 2026-02-06)
|
||||
- **`inference.model.enable_prefix_caching`**: Added flag to enable prefix caching in vLLM. Passed to vLLM as `--enable-prefix-caching` (default: None) (2026-02-08)
|
||||
- **`orchestrator.env.address`**: Added address field on `EnvConfig`. If set, connect to an environment server at this address; if None, spawn a server in a subprocess (2026-02-06)
|
||||
- **`orchestrator.env.extra_env_kwargs`**: Added on `EnvConfig`. Extra kwargs passed to the env (e.g. seq_len, interleaved_rollouts, score_rollouts). Auto-populated by the orchestrator for training envs; generally not recommended for user override. Main use case is to match these kwargs when running an env in an isolated environment server (default: {}) (2026-02-06)
|
||||
- **`OrchestratorConfig`**: Removed `workers_per_env`, `max_env_worker_restarts`, and `mask_env_responses` (2026-02-06)
|
||||
- **`EvalSaveDiskConfig`**, **`EvalSaveConfig`**, **`RetryConfig`**, **`OnlineEvalConfig`**: Removed (2026-02-06)
|
||||
- **`TemperatureScheduleConfig`**: Renamed to `TemperatureSchedulerConfig` (2026-02-06)
|
||||
- **`optim.mu`**: Added Muon momentum (`mu`) config field (default: 0.95). Previously hardcoded to Muon class default. Also fixed `optim.betas1`/`optim.betas2` not being passed through to the Muon optimizer (2026-02-09)
|
||||
- **`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)
|
||||
- **`orchestrator.token_batch_size`** and **`orchestrator.max_inflight_rollouts`**: Added token-based batching via `token_batch_size` and explicit in-flight rollout control via `max_inflight_rollouts` (2026-02-23)
|
||||
- **`orchestrator.batch_size`**: Now optional and mutually exclusive with `token_batch_size`. If neither is set, defaults to rollout mode with `batch_size=128` (2026-02-23)
|
||||
- **`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-02-23)
|
||||
- **`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 `SFTConfig` (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 `SFTConfig` (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)
|
||||
- **Config consolidation**: All config modules moved into `prime_rl.configs` subpackage. `utils/config.py` + `transport/config.py` → `configs/shared.py`; `trainer/config.py` + `trainer/rl/config.py` → `configs/trainer.py`; `trainer/sft/config.py` → `configs/sft.py`; `orchestrator/config.py` → `configs/orchestrator.py`; `inference/config.py` → `configs/inference.py`; `rl_config.py` → `configs/rl.py`. Class renames: `SFTTrainerConfig` → `SFTConfig`, `RLTrainerConfig` → `TrainerConfig`. Component prefixes dropped from orchestrator and inference config classes (e.g. `OrchestratorCheckpointConfig` → `CheckpointConfig`). TypeAlias renames: dropped `Type` suffix (e.g. `LossConfigType` → `LossConfig`, `TransportConfigType` → `TransportConfig`), renamed `LossConfig` class → `DefaultLossConfig`. No TOML key changes. (2026-02-24)
|
||||
- **`trainer.enable_router_replay`**: Added flag to enable router replay. If True, will return routed experts in the batch. This is only supported if `enable_return_routed_experts=True` in the inference config or pass `--enable-return-routed-experts` to vLLM server. This is only supported for custom models. (2026-02-22)
|
||||
- **`inference.enable_return_routed_experts`**: Added flag to enable return routed experts. Passed to vLLM as `--enable-return-routed-experts` (2026-02-22)
|
||||
- **`orchestrator.oversampling_factor`**: Added rollout-only over-sampling config that resolves `max_inflight_rollouts = int(batch_size * oversampling_factor)` when `max_inflight_rollouts` is unset. Cannot be used with `token_batch_size` or together with explicit `max_inflight_rollouts` (2026-02-25)
|
||||
- **`sft.val`**: Added optional periodic SFT validation with `val/loss` and `val/num_tokens` logging. Configure via `sft.val.data` (validation dataset) and `sft.val.interval` (every N steps, default 50). Runs the full validation dataset each pass. (2026-02-26)
|
||||
- **`model.fused_lm_head_chunk_size`**: Changed default value from 2048 to 8192 for RL training (2026-02-26)
|
||||
- **`inference.data_parallel_size_local`** and **`inference.data_parallel_rpc_port`**: Added data-parallel node-local controls for vLLM, passed as `--data-parallel-size-local` and `--data-parallel-rpc-port` (defaults: `None`, `13345`) (2026-02-26)
|
||||
- **`dump_config`**: Removed from `RLConfig`. Replaced by `dry_run` (see below) (2026-02-26)
|
||||
- **`slurm.dry_run`**: Removed from `SlurmConfig`. Replaced by top-level `dry_run` (see below) (2026-02-26)
|
||||
- **`dry_run`**: Added to `RLConfig` and `SFTConfig` (default: `False`). When set, validates the config, writes resolved subconfigs to `output_dir/configs/`, and exits without starting any processes. Works the same for both local and SLURM runs (2026-02-26)
|
||||
- **Config output location**: Resolved subconfigs are now always written to `output_dir/configs/` instead of `.pydantic_config/<uuid>/`. This applies to both local and SLURM entrypoints, and for both single-node and multi-node deployments (2026-02-26)
|
||||
- **SFT config filename**: The resolved SFT trainer config is now written as `sft.toml` instead of `trainer.toml` (2026-02-26)
|
||||
- **Inference entrypoint**: Moved from `prime_rl.inference.server` to `prime_rl.entrypoints.inference`. No change to CLI usage (`uv run inference`) (2026-02-26)
|
||||
- **`[slurm]` (inference)**: Added SLURM configuration to `InferenceConfig`. When present, `uv run inference` generates and submits an sbatch script instead of running locally. Each SLURM node runs an independent vLLM replica (no cross-node parallelism) (2026-02-26)
|
||||
- **`[deployment]` (inference)**: Added deployment configuration. `type = "single_node"` (default) with `gpus_per_node`. `type = "multi_node"` with `num_nodes` and `gpus_per_node` — requires `[slurm]` (2026-02-26)
|
||||
- **`inference.output_dir`**: Added directory for SLURM logs and generated scripts (default: `"outputs"`) (2026-02-26)
|
||||
- **`inference.dry_run`**: Added flag (default: `False`). When set, validates config, writes resolved config to `output_dir/configs/`, and exits without starting inference or submitting SLURM jobs (2026-02-26)
|
||||
- **`orchestrator.teacher_rollout_model`**: Added optional external rollout model configuration. When set, rollouts are generated from this endpoint/model instead of the student inference server. Accepts a `TeacherRolloutModelConfig` with `client` and `model` sub-fields, or `None` (default: `None`) (2026-02-26)
|
||||
- **`trainer.loss.type = "sft"`**: Added SFT loss variant. Set `trainer.loss.type = "sft"` to use masked negative log-likelihood loss instead of the default RL loss (2026-02-26)
|
||||
- **`trainer.loss.type = "custom"`**: Added custom loss variant. Set `trainer.loss.type = "custom"` with `import_path` (e.g. `"my_module.my_loss"`) and optional `kwargs` to use an external loss function (2026-02-26)
|
||||
- **`trainer.loss` (default loss)**: Made IPO (DPPO-Binary TV variant ([arxiv](https://arxiv.org/pdf/2602.04879)) + Kimi-K2.5 KL ([Kimi-K2.5](https://arxiv.org/pdf/2602.02276))) the default loss. Removed `ratio_type`, `token_mask_low`, `token_mask_high`, `sequence_clip_high`, `geo_mask_low`, `geo_mask_high`, `sequence_mask_low`, `sequence_mask_high`. Added `ipo_mask_low` (default: 0.2) and `ipo_mask_high` (default: 0.2) for token-level probability-difference masking. Changed `kl_tau` default from `0.0` to `1e-3`. (2026-03-02)
|
||||
- **Metrics logging overhaul**: All orchestrator metrics now follow a `{metric}/{scope}/{stat}` naming convention where scope is `all` (global) or an env name. Per-env breakdowns are always logged (previously only when >1 env). Key renames: `reward/mean` → `reward/all/mean`, `batch/solve_none` → `solve_none/all`, `val_reward/` → `val/reward/`, `metrics/{name}` → `metrics/{env}/{name}`, `stop_condition/{sc}` → `stop_condition/all/{sc}`, `error/mean` → `error/all/mean`. New per-env metrics: `solve_none/{env}`, `solve_all/{env}`, `effective_batch_size/{env}`, `stop_condition/{env}/generation_truncated`, `stop_condition/{env}/{sc}`, `error/{env}/mean`, plus per-env breakdowns for `seq_len`, `prefill_len`, `decode_len`, `is_truncated`, `samples_per_rollout`, `num_turns`, `generation_ms`, `scoring_ms`. Removed: `reward/std`, `reward/median`, per-error-type breakdown (`error/{error_type}`). Env name `"all"` is reserved and rejected at config validation. Env name validation now strips `@version` suffixes to match runtime behavior (e.g. `math@1.0` and `math@2.0` correctly detected as duplicates). Solve stats now use `example_id` grouping instead of index arithmetic (pre-existing bug fix). (2026-03-08)
|
||||
- **`wandb.shared`** (experimental): Added shared W&B mode that logs trainer and orchestrator metrics to a single W&B run instead of two separate runs. Uses `wandb.Settings(mode="shared")` (requires wandb SDK >= 0.19.9). Enabled by default on the RL entrypoint. Disable with `--wandb.shared False`. Run ID is communicated via `WANDB_SHARED_RUN_ID` env var; process role via `WANDB_SHARED_LABEL`. Non-primary processes retry `wandb.init` up to 30 times waiting for the primary to create the run. Works with multi-node SLURM. (2026-03-18)
|
||||
- **`wandb.id`**: Removed from `WandbConfig`. Run IDs are now managed internally via env vars for shared mode. (2026-03-18)
|
||||
- **`trainer.ckpt.skip_optimizer`**: Added flag to skip loading optimizer states when resuming training. When set, only the model weights are loaded from the checkpoint. (2026-03-24)
|
||||
Vendored
+1
-1
Submodule deps/renderers updated: 5904fa24aa...201f88516c
Vendored
+1
-1
Submodule deps/research-environments updated: 06232831fd...dd80d75bc8
Vendored
+1
-1
Submodule deps/verifiers updated: 31415cd32a...1cfdd39cc2
@@ -107,6 +107,8 @@ ep_comm_backend = "torch" # or "deepep"
|
||||
|
||||
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. We reccomend using `ulysses` style CP for most of the models to get the most throughput. Some models (e.g. GLM-5) only support `ring` style CP. Wrong setting will be rejected on validation.
|
||||
|
||||
`ulysses` head-shards Q/K/V, so the CP degree must divide `num_attention_heads`. GQA models with fewer KV heads than the CP degree (e.g. NemotronH: 32 query heads, 2 KV heads) are supported via KV-head replication; the CP degree must then be a multiple of `num_key_value_heads`. Hybrid Mamba layers head-shard independently (`cp_mamba`), which requires the CP degree to divide `mamba_num_heads` and `n_groups`.
|
||||
|
||||
```toml
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
|
||||
+12
-4
@@ -144,12 +144,20 @@ Two accepted layouts:
|
||||
|
||||
If both columns are present, `messages` takes precedence.
|
||||
|
||||
**Tool definitions.** For tool-use SFT, add a `tools` column (OpenAI function-calling format) or `tool_defs` ([`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) rollout format). Each row's value can be either a list of dicts or a JSON-encoded string of a list — both are accepted, and `tool_defs` rows are auto-converted to OAI shape before being passed into the chat template's `tools=...` argument. The `chat_template_kwargs` column, if present, is forwarded verbatim into `apply_chat_template`.
|
||||
**Tool definitions and renderer controls.** For tool-use SFT, add a `tools` column (OpenAI function-calling format) or `tool_defs` ([`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) rollout format). Each row's value can be either a list of dicts or a JSON-encoded string of a list — both are accepted, and `tool_defs` rows are auto-converted to OAI shape before being passed into the renderer.
|
||||
|
||||
**Position-dependent chat templates.** Multi-turn SFT under the default tokenization path (`build_incremental_token_mask`) requires that tokenizing the first _k_ turns of a conversation be a strict prefix of tokenizing all _n ≥ k_ turns. Qwen3's upstream template _violates_ this — it strips past `<think>` blocks across user turns, silently corrupting the loss mask. Two fixes:
|
||||
Renderer-backed SFT reads template controls from the typed `[renderer]` config in the SFT TOML. For example:
|
||||
|
||||
```toml
|
||||
[renderer]
|
||||
name = "qwen3"
|
||||
enable_thinking = false
|
||||
```
|
||||
|
||||
If a model needs another template control, add it to that model's renderer config in `renderers` (for example a new field on the relevant `*RendererConfig`) and consume it in the renderer implementation.
|
||||
|
||||
**Renderer-backed tokenization.** SFT tokenization is renderer-only. The [`renderers`](algorithms.md#renderers) package owns message-to-token conversion and loss attribution end-to-end, so position-dependent chat templates (for example templates that strip past `—` blocks across user turns) do not corrupt the loss mask. `[renderer]` defaults to `name = "auto"`; set a typed renderer config only when you need model-specific template controls. Hand-coded renderers ship for Qwen3, Qwen3.5, GLM-5, GLM-4.5, Kimi K2/K2.5, MiniMax M2, DeepSeek V3, Nemotron 3, GPT-OSS.
|
||||
|
||||
- **Enable the renderer** (set a typed `[renderer]` config, e.g. `name = "qwen3"`, recommended; defaults to `"auto"` for RL). The [`renderers`](algorithms.md#renderers) package owns tokenization end-to-end and is robust to position-dependent templates. Hand-coded renderers ship for Qwen3, Qwen3.5, GLM-5, GLM-4.5, Kimi K2/K2.5, MiniMax M2, DeepSeek V3, Nemotron 3, GPT-OSS. Not supported for VLMs.
|
||||
- **Patched chat template** — the prime-rl–patched checkpoints (e.g. `PrimeIntellect/Qwen3-0.6B`, used in `examples/reverse_text/sft.toml`) ship a chat template that preserves thinking. Or supply your own.
|
||||
|
||||
See [Algorithms § Multi-Turn Trajectories](algorithms.md#multi-turn-trajectories) for the full picture.
|
||||
|
||||
|
||||
@@ -30,9 +30,6 @@ max_completion_tokens = 1024
|
||||
[inference.parallel]
|
||||
dp = 6
|
||||
|
||||
# Qwen3 finetune with the standard PI template patch (byte-identical to
|
||||
# PrimeIntellect/Qwen3-0.6B base); always re-emits prior <think> blocks.
|
||||
# Match that with renderer thinking_retention.
|
||||
# Fine-tune inherits the PrimeIntellect Qwen3 template byte-for-byte.
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
thinking_retention = "all"
|
||||
name = "prime-qwen3"
|
||||
|
||||
@@ -366,6 +366,9 @@ class InferenceConfig(BaseConfig):
|
||||
gpu_memory_utilization: float = 0.9
|
||||
"""GPU memory utilization. Forwarded as ``--gpu-memory-utilization``."""
|
||||
|
||||
quantization: Literal["mxfp8", "fp8_per_block"] | None = None
|
||||
"""Online inference quantization method. Forwarded as ``--quantization``."""
|
||||
|
||||
api_server_count: int = Field(1, ge=0)
|
||||
"""API servers to run. Forwarded as ``--api-server-count``. Set to 0 for headless mode."""
|
||||
|
||||
@@ -432,6 +435,24 @@ class InferenceConfig(BaseConfig):
|
||||
raise ValueError("Must use SLURM for multi-node / disaggregated deployment.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_mxfp8_requires_sm100(self):
|
||||
"""Reject MXFP8 when validation runs on a non-SM100 CUDA host."""
|
||||
if self.quantization != "mxfp8":
|
||||
return self
|
||||
|
||||
try:
|
||||
import torch
|
||||
except ModuleNotFoundError as exc:
|
||||
raise ValueError("inference.quantization='mxfp8' requires torch to validate SM100 support.") from exc
|
||||
|
||||
if torch.cuda.is_available():
|
||||
capability = torch.cuda.get_device_capability()
|
||||
if capability != (10, 0):
|
||||
detected = f"SM{capability[0]}{capability[1]}"
|
||||
raise ValueError(f"inference.quantization='mxfp8' requires SM100, detected {detected}.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_llmd_no_routed_experts(self):
|
||||
"""Reject routed-expert return with the llm-d router (breaks P/D, unverified for multi-node)."""
|
||||
@@ -576,6 +597,7 @@ class InferenceConfig(BaseConfig):
|
||||
"max_lora_rank": "max_lora_rank",
|
||||
"lora_target_modules": "lora_target_modules",
|
||||
"gpu_memory_utilization": "gpu_memory_utilization",
|
||||
"quantization": "quantization",
|
||||
"api_server_count": "api_server_count",
|
||||
"enable_return_routed_experts": "enable_return_routed_experts",
|
||||
"enable_expert_parallel": "enable_expert_parallel",
|
||||
@@ -625,6 +647,10 @@ class InferenceConfig(BaseConfig):
|
||||
if hasattr(namespace, "lora_target_modules") and namespace.lora_target_modules is None:
|
||||
delattr(namespace, "lora_target_modules")
|
||||
|
||||
# Remove quantization if not set so vLLM can infer it from the checkpoint.
|
||||
if namespace.quantization is None:
|
||||
delattr(namespace, "quantization")
|
||||
|
||||
# Remove rope_scaling if not set (vLLM doesn't accept None)
|
||||
if hasattr(namespace, "rope_scaling"):
|
||||
if namespace.rope_scaling is None:
|
||||
|
||||
@@ -3,7 +3,8 @@ from pathlib import Path
|
||||
from typing import Annotated, Literal, TypeAlias
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
from renderers import RendererConfig
|
||||
from renderers import AutoRendererConfig, DefaultRendererConfig, RendererConfig
|
||||
from renderers.base import MODEL_RENDERER_MAP
|
||||
|
||||
from prime_rl.configs.shared import (
|
||||
EnvVars,
|
||||
@@ -175,13 +176,8 @@ class SFTConfig(BaseConfig):
|
||||
|
||||
tokenizer: TokenizerConfig = TokenizerConfig()
|
||||
|
||||
renderer: RendererConfig | None = None
|
||||
"""Typed renderer config (``renderers.RendererConfig`` discriminated
|
||||
union). When set, SFT tokenizes samples through the ``renderers``
|
||||
library (single ``render()`` + ``message_indices`` mask) instead of
|
||||
the default ``build_incremental_token_mask`` path. Required for chat
|
||||
templates that render position-dependently (e.g. Qwen3, Qwen3.5).
|
||||
``None`` (default) uses the legacy tokenization path."""
|
||||
renderer: RendererConfig = AutoRendererConfig()
|
||||
"""Renderer config. Defaults to auto-selecting from the tokenizer model name."""
|
||||
|
||||
data: DataConfig = SFTDataConfig()
|
||||
|
||||
@@ -271,6 +267,28 @@ class SFTConfig(BaseConfig):
|
||||
raise ValueError("Must use SLURM for multi-node deployment.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_typed_renderer(self):
|
||||
"""Require a typed renderer whenever SFT renders real samples."""
|
||||
if self.data.type == "fake" and self.val is None:
|
||||
return self
|
||||
|
||||
model_id = self.tokenizer.name or self.model.name
|
||||
if isinstance(self.renderer, AutoRendererConfig):
|
||||
if model_id in MODEL_RENDERER_MAP:
|
||||
return self
|
||||
reason = f"no typed renderer is registered for {model_id!r}"
|
||||
elif isinstance(self.renderer, DefaultRendererConfig):
|
||||
reason = "renderer.name='default' selects DefaultRenderer"
|
||||
else:
|
||||
return self
|
||||
|
||||
raise ValueError(
|
||||
f"SFT requires a typed renderer with sampled-token and content attribution, but {reason}. "
|
||||
"Implement and register the renderer in the renderers package, or explicitly select an existing "
|
||||
"typed renderer only when its template is verified to match."
|
||||
)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_pack_function(self):
|
||||
if self.model.cp > 1:
|
||||
@@ -319,9 +337,9 @@ class SFTConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_renderer_vs_vlm(self):
|
||||
if self.renderer is not None and self.model.vlm is not None:
|
||||
if self.model.vlm is not None:
|
||||
raise ValueError(
|
||||
"renderer is not supported for VLMs in SFT. The renderer tokenizes "
|
||||
"renderer-only SFT does not support VLMs yet. The renderer tokenizes "
|
||||
"text-only message dicts client-side and cannot handle image inputs."
|
||||
)
|
||||
return self
|
||||
|
||||
+5
-2
@@ -67,7 +67,7 @@ flash-attn-cute = [
|
||||
"flash-attn-4",
|
||||
]
|
||||
disagg = [
|
||||
"deep-ep ; platform_machine == 'x86_64'",
|
||||
"deep-ep ; platform_machine == 'x86_64' or platform_machine == 'aarch64'",
|
||||
"deep-gemm",
|
||||
"nixl",
|
||||
"nixl-cu12 ; platform_machine == 'x86_64'",
|
||||
@@ -203,7 +203,10 @@ vllm = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-ep = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }
|
||||
deep-ep = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.1.0+1fd57b0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-gemm = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
|
||||
+32
-6
@@ -2,11 +2,13 @@
|
||||
|
||||
SESSION_NAME="prime-rl"
|
||||
OUTPUT_DIR="outputs"
|
||||
AGENT="claude"
|
||||
|
||||
# Optional CLI parsing
|
||||
# Supports:
|
||||
# -s|--session-name NAME
|
||||
# -o|--output-dir DIR
|
||||
# -a|--agent AGENT (claude|codex, default: claude)
|
||||
# Positional: [SESSION_NAME [OUTPUT_DIR]]
|
||||
POSITIONAL=()
|
||||
while [[ $# -gt 0 ]]; do
|
||||
@@ -27,8 +29,17 @@ while [[ $# -gt 0 ]]; do
|
||||
OUTPUT_DIR="$2"
|
||||
shift 2
|
||||
;;
|
||||
-a|--agent)
|
||||
if [[ -z "$2" ]]; then
|
||||
echo "Error: --agent requires a value (claude|codex)" >&2
|
||||
exit 1
|
||||
fi
|
||||
AGENT="$2"
|
||||
shift 2
|
||||
;;
|
||||
-h|--help)
|
||||
echo "Usage: $0 [-s SESSION_NAME] [-o OUTPUT_DIR] [SESSION_NAME [OUTPUT_DIR]]" >&2
|
||||
echo "Usage: $0 [-s SESSION_NAME] [-o OUTPUT_DIR] [-a AGENT] [SESSION_NAME [OUTPUT_DIR]]" >&2
|
||||
echo " -a, --agent claude|codex (default: claude)" >&2
|
||||
exit 0
|
||||
;;
|
||||
--)
|
||||
@@ -86,10 +97,10 @@ tmux send-keys -t "$SESSION_NAME:Logs.2" \
|
||||
tmux send-keys -t "$SESSION_NAME:Logs.3" \
|
||||
"tail -F ${LOG_DIR}/inference.log 2>/dev/null" C-m
|
||||
|
||||
# Window 2: Claude Code with log context
|
||||
tmux new-window -t "$SESSION_NAME" -n "Claude"
|
||||
tmux send-keys -t "$SESSION_NAME:Claude" \
|
||||
"claude --permission-mode auto --append-system-prompt 'You are monitoring a prime-rl training run. The output directory is ${OUTPUT_DIR}. Log paths:
|
||||
# Window 2: Agent (claude code or codex) with log context
|
||||
tmux new-window -t "$SESSION_NAME" -n "Agent"
|
||||
|
||||
AGENT_PROMPT="You are monitoring a prime-rl training run. The output directory is ${OUTPUT_DIR}. Log paths:
|
||||
Trainer: ${LOG_DIR}/trainer.log
|
||||
All nodes: ${LOG_DIR}/trainer/node_*.log
|
||||
All ranks: ${LOG_DIR}/trainer/torchrun/*/*/*/*.log
|
||||
@@ -98,7 +109,22 @@ tmux send-keys -t "$SESSION_NAME:Claude" \
|
||||
Envs: ${LOG_DIR}/envs/*/*.log
|
||||
Train envs: ${LOG_DIR}/envs/train/*.log
|
||||
You are running inside tmux session \"${SESSION_NAME}\". The Launcher window (window 0) is where the user runs launch commands. You can read its contents with: tmux capture-pane -t ${SESSION_NAME}:Launcher -p
|
||||
Help the user monitor and debug this run.'" C-m
|
||||
Help the user monitor and debug this run."
|
||||
|
||||
case "$AGENT" in
|
||||
claude)
|
||||
tmux send-keys -t "$SESSION_NAME:Agent" \
|
||||
"claude --permission-mode auto --append-system-prompt \"${AGENT_PROMPT}\"" C-m
|
||||
;;
|
||||
codex)
|
||||
tmux send-keys -t "$SESSION_NAME:Agent" \
|
||||
"codex --yolo \"${AGENT_PROMPT}\"" C-m
|
||||
;;
|
||||
*)
|
||||
echo "Error: unknown agent '$AGENT' (expected claude|codex)" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
# Pane title styling
|
||||
tmux set-option -t "$SESSION_NAME" -g pane-border-status top
|
||||
|
||||
@@ -19,6 +19,31 @@ def apply_shared_vllm_patches():
|
||||
monkey_patch_vllm_padded_input_scrub()
|
||||
monkey_patch_return_routed_experts_with_nixl_connector()
|
||||
monkey_patch_kv_xfer_finished_tolerate_freed()
|
||||
monkey_patch_online_fp8_parameter_cast()
|
||||
|
||||
|
||||
def monkey_patch_online_fp8_parameter_cast():
|
||||
"""Pass plain tensors to vLLM's compiled block-FP8 caster.
|
||||
|
||||
Layerwise reload restores ``ModelWeightParameter`` objects before online
|
||||
quantization. TorchDynamo recursively dispatches that tensor subclass while
|
||||
tracing ``per_block_cast_to_fp8``. ``Parameter.data`` shares storage but is
|
||||
a plain tensor, matching the input accepted during the initial model load.
|
||||
"""
|
||||
from torch.nn import Parameter
|
||||
from vllm.model_executor.layers.quantization.online import fp8
|
||||
|
||||
original_cast = fp8.per_block_cast_to_fp8
|
||||
if getattr(original_cast, "_prime_rl_unwraps_parameters", False):
|
||||
return
|
||||
|
||||
def _per_block_cast_to_fp8(x, *args, **kwargs):
|
||||
if isinstance(x, Parameter):
|
||||
x = x.data
|
||||
return original_cast(x, *args, **kwargs)
|
||||
|
||||
_per_block_cast_to_fp8._prime_rl_unwraps_parameters = True
|
||||
fp8.per_block_cast_to_fp8 = _per_block_cast_to_fp8
|
||||
|
||||
|
||||
def monkey_patch_kv_xfer_finished_tolerate_freed():
|
||||
|
||||
@@ -323,25 +323,23 @@ class Orchestrator:
|
||||
else:
|
||||
get_logger().info("Training from scratch")
|
||||
|
||||
# Sync inference to the incoming policy before the first step, whether fresh (v0 = base) or
|
||||
# resumed (v{resume_step}). This pauses inference and rendezvouses with the trainer's
|
||||
# first-step broadcast (train.py), so inference serves the correct policy from step 1. Keeping
|
||||
# it unconditional makes trainer/orchestrator startup symmetric and avoids the resume deadlock
|
||||
# where inference waited for weights the trainer only sent at the end of a step.
|
||||
sync_version = self.resume_step if self.resume_step is not None else 0
|
||||
check_exists = config.weight_broadcast.type != "nccl"
|
||||
# Wait for the trainer's startup broadcast to land. On a fresh start there is no ckpt block,
|
||||
# so fall back to a default timeout instead of not waiting at all (which would raise before
|
||||
# broadcasts/step_0/STABLE is written when using filesystem weight broadcast).
|
||||
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else STARTUP_WEIGHT_WAIT_TIMEOUT_S
|
||||
weights_path = get_weight_dir(
|
||||
config.output_dir, sync_version, check_exists=check_exists, wait_timeout=wait_timeout
|
||||
)
|
||||
await self.policy_inference.update_weights(weights_path, lora_name=self.lora_name, step=sync_version)
|
||||
if self.lora_name is not None:
|
||||
self.policy_inference.update_model_name(self.lora_name)
|
||||
self.policy.model_name = self.lora_name
|
||||
self.policy.version = sync_version
|
||||
# Sync inference to the incoming policy before the first step when resuming or when using
|
||||
# NCCL, which rendezvouses with the trainer's first-step broadcast (train.py). A fresh
|
||||
# filesystem run needs no sync (the base model IS policy v0) and must not wait for a
|
||||
# startup broadcast: runs registered after the trainer's first step never receive one.
|
||||
if self.resume_step is not None or config.weight_broadcast.type == "nccl":
|
||||
sync_version = self.resume_step if self.resume_step is not None else 0
|
||||
check_exists = config.weight_broadcast.type != "nccl"
|
||||
# Without a ckpt block, fall back to a default timeout instead of not waiting at all.
|
||||
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else STARTUP_WEIGHT_WAIT_TIMEOUT_S
|
||||
weights_path = get_weight_dir(
|
||||
config.output_dir, sync_version, check_exists=check_exists, wait_timeout=wait_timeout
|
||||
)
|
||||
await self.policy_inference.update_weights(weights_path, lora_name=self.lora_name, step=sync_version)
|
||||
if self.lora_name is not None:
|
||||
self.policy_inference.update_model_name(self.lora_name)
|
||||
self.policy.model_name = self.lora_name
|
||||
self.policy.version = sync_version
|
||||
|
||||
self.train_source = TrainSource(self.train_envs, seed=42)
|
||||
self.eval_source: EvalSource | None = (
|
||||
|
||||
@@ -37,3 +37,28 @@ def quantize_to_fp8_blockwise(weight: Tensor, block_size: int = 128) -> tuple[Te
|
||||
|
||||
quantized = blocks_fp8.permute(0, 2, 1, 3).reshape(padded_rows, padded_cols)[:rows, :cols].contiguous()
|
||||
return quantized, scales.float().contiguous()
|
||||
|
||||
|
||||
def quantize_to_vllm_kernel_format(weight: Tensor, block_size: int = 128) -> tuple[Tensor, Tensor]:
|
||||
"""Quantize a weight into the FP8 layout used by vLLM kernels.
|
||||
|
||||
Hopper kernels consume the regular blockwise scale grid. On SM100, vLLM's
|
||||
DeepGEMM kernels instead use UE8M0 scales in an architecture-specific packed
|
||||
layout. Reuse vLLM's own post-processing so tensors sent over the kernel
|
||||
weight-transfer path have the same representation as the loaded parameters.
|
||||
"""
|
||||
quantized, scales = quantize_to_fp8_blockwise(weight, block_size)
|
||||
|
||||
if not weight.is_cuda or torch.cuda.get_device_capability(weight.device) != (10, 0):
|
||||
return quantized, scales
|
||||
|
||||
from vllm.model_executor.layers.quantization.utils.fp8_utils import (
|
||||
deepgemm_post_process_fp8_weight_block,
|
||||
)
|
||||
|
||||
return deepgemm_post_process_fp8_weight_block(
|
||||
wq=quantized,
|
||||
ws=scales,
|
||||
quant_block_shape=(block_size, block_size),
|
||||
use_e8m0=True,
|
||||
)
|
||||
|
||||
@@ -2,7 +2,7 @@ import torch
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.trainer.conversion_utils import get_max_layer_num
|
||||
from prime_rl.trainer.models.fp8 import quantize_to_fp8_blockwise
|
||||
from prime_rl.trainer.models.fp8 import quantize_to_vllm_kernel_format
|
||||
|
||||
|
||||
def _is_moe_layer(state_dict: dict[str, Tensor], layer_idx: int) -> bool:
|
||||
@@ -157,7 +157,7 @@ def convert_tt_layer_to_vllm_kernel(
|
||||
|
||||
def add_maybe_fp8(name: str, tensor: Tensor) -> None:
|
||||
if quantize_fp8 and tensor.ndim == 2:
|
||||
fp8_weight, scale = quantize_to_fp8_blockwise(tensor)
|
||||
fp8_weight, scale = quantize_to_vllm_kernel_format(tensor)
|
||||
out[name] = fp8_weight
|
||||
scale_name = name.removesuffix(".weight") + ".weight_scale_inv"
|
||||
out[scale_name] = scale
|
||||
@@ -231,8 +231,8 @@ def convert_tt_layer_to_vllm_kernel(
|
||||
w2_fp8: list[Tensor] = []
|
||||
w2_scales: list[Tensor] = []
|
||||
for expert_idx in range(w1.shape[0]):
|
||||
expert_w13_fp8, expert_w13_scales = quantize_to_fp8_blockwise(w13[expert_idx])
|
||||
expert_w2_fp8, expert_w2_scales = quantize_to_fp8_blockwise(w2[expert_idx])
|
||||
expert_w13_fp8, expert_w13_scales = quantize_to_vllm_kernel_format(w13[expert_idx])
|
||||
expert_w2_fp8, expert_w2_scales = quantize_to_vllm_kernel_format(w2[expert_idx])
|
||||
w13_fp8.append(expert_w13_fp8)
|
||||
w13_scales.append(expert_w13_scales)
|
||||
w2_fp8.append(expert_w2_fp8)
|
||||
|
||||
@@ -148,6 +148,9 @@ class LagunaConfig(PretrainedConfig):
|
||||
for params in nested.values():
|
||||
params.setdefault("rope_type", "default")
|
||||
|
||||
# vLLM ignores this override and derives YaRN scaling from factor; match it for rollout/trainer parity.
|
||||
nested["full_attention"].pop("attention_factor", None)
|
||||
|
||||
self.rope_parameters = nested
|
||||
self.partial_rotary_factor = None
|
||||
|
||||
|
||||
@@ -798,6 +798,7 @@ class MoE(nn.Module):
|
||||
self.expert_bias = torch.zeros(self.experts.num_experts, dtype=torch.float32)
|
||||
|
||||
|
||||
@torch.compile(dynamic=True)
|
||||
def relu2(x: torch.Tensor) -> torch.Tensor:
|
||||
return F.relu(x).square()
|
||||
|
||||
|
||||
@@ -19,8 +19,17 @@ Key benefit: the attention kernel itself does not need to be CP-aware. The
|
||||
all-to-all is purely on Q/K/V tensors, so this works out of the box with
|
||||
softmax flash-attn, linear attention, mamba, etc., without rewriting kernels.
|
||||
|
||||
GQA models with fewer KV heads than cp_size (e.g. NemotronH: 32 query heads, 2
|
||||
KV heads) are handled by replicating each KV head cp_size / num_key_value_heads
|
||||
times before the seq->head all-to-all. Query heads are grouped contiguously in
|
||||
GQA, so the replicated layout lands every rank on exactly the KV head its local
|
||||
query-head slice attends to; the backward of the replication sums gradients
|
||||
over replicas, which is the exact GQA KV gradient.
|
||||
|
||||
Constraints:
|
||||
- cp_size must divide both num_attention_heads and num_key_value_heads.
|
||||
- cp_size must divide num_attention_heads.
|
||||
- cp_size must divide num_key_value_heads, OR num_key_value_heads must divide
|
||||
cp_size (the KV-replication path).
|
||||
- Sequence length must be divisible by cp_size.
|
||||
"""
|
||||
|
||||
@@ -41,6 +50,24 @@ def update_ulysses_params(cu_seqlens: torch.Tensor, max_seqlen: int) -> None:
|
||||
ULYSSES_PARAMS["max_seqlen"] = int(max_seqlen)
|
||||
|
||||
|
||||
def _replicate_kv_heads(t: torch.Tensor, cp_size: int) -> torch.Tensor:
|
||||
"""Replicate KV heads so a GQA tensor with fewer heads than cp_size can be
|
||||
head-sharded: [S_local, H_kv, D] -> [S_local, cp_size, D].
|
||||
|
||||
Each KV head is repeated cp_size / H_kv times. GQA groups query heads
|
||||
contiguously (query head j attends KV head j // (H_q / H_kv)), so after the
|
||||
seq->head all-to-all rank r holds query heads [r * H_q/cp, (r+1) * H_q/cp)
|
||||
— all attending KV head floor(r * H_kv / cp) — and replica index r maps to
|
||||
the same head: floor(r / (cp / H_kv)). The backward sums gradients over
|
||||
replicas, which is exactly the GQA KV gradient.
|
||||
"""
|
||||
s_local, h, d = t.shape
|
||||
assert cp_size % h == 0, (
|
||||
f"num_key_value_heads ({h}) must divide cp_size ({cp_size}) for the ulysses KV-replication path"
|
||||
)
|
||||
return t.repeat_interleave(cp_size // h, dim=1)
|
||||
|
||||
|
||||
def _all_to_all_seq_to_head(t: torch.Tensor, cp_size: int, cp_group: dist.ProcessGroup) -> torch.Tensor:
|
||||
"""Redistribute [S_local, H, D] -> [S_global, H_local, D].
|
||||
|
||||
@@ -48,7 +75,10 @@ def _all_to_all_seq_to_head(t: torch.Tensor, cp_size: int, cp_group: dist.Proces
|
||||
ends up with the full sequence but only H/cp_size heads. Differentiable.
|
||||
"""
|
||||
s_local, h, d = t.shape
|
||||
assert h % cp_size == 0, f"num_heads ({h}) must be divisible by cp_size ({cp_size})"
|
||||
assert h % cp_size == 0, (
|
||||
f"num_heads ({h}) must be divisible by cp_size ({cp_size}); "
|
||||
"for GQA KV tensors with fewer heads than cp_size, replicate first via _replicate_kv_heads"
|
||||
)
|
||||
h_local = h // cp_size
|
||||
|
||||
# [S_local, cp_size, H_local, D] -> [cp_size, S_local, H_local, D]
|
||||
@@ -96,8 +126,15 @@ def ulysses_flash_attn_varlen_func(
|
||||
|
||||
`cu_seqlens_*` and `max_seqlen_*` describe the *full* (un-sharded) sequence,
|
||||
because after the seq->head all-to-all each rank holds the full sequence.
|
||||
|
||||
GQA with num_key_value_heads < cp_size: K/V heads are replicated up to
|
||||
cp_size before the all-to-all (see `_replicate_kv_heads`), so each rank runs
|
||||
grouped attention on its query-head slice with the single matching KV head.
|
||||
"""
|
||||
q = _all_to_all_seq_to_head(q, cp_size, cp_group)
|
||||
if k.shape[1] < cp_size:
|
||||
k = _replicate_kv_heads(k, cp_size)
|
||||
v = _replicate_kv_heads(v, cp_size)
|
||||
k = _all_to_all_seq_to_head(k, cp_size, cp_group)
|
||||
v = _all_to_all_seq_to_head(v, cp_size, cp_group)
|
||||
|
||||
|
||||
@@ -266,12 +266,13 @@ def train(config: TrainerConfig):
|
||||
logger.debug(f"Starting training step {progress.step}")
|
||||
step_start_time = time.perf_counter()
|
||||
|
||||
# Broadcast the incoming policy (v{progress.step-1}) before waiting for its rollouts. #2896
|
||||
# broadcasts at the END of a step, so the first step would otherwise block on rollouts the
|
||||
# inference engines cannot produce until they receive v{progress.step-1} (the orchestrator
|
||||
# pauses inference at startup to sync it). This happens whether resuming (v{checkpoint_step})
|
||||
# or starting fresh (v0), keeping trainer and orchestrator startup symmetric.
|
||||
if progress.step == start_step and weight_broadcast is not None:
|
||||
# With NCCL, broadcast the incoming policy (v{progress.step-1}) before waiting for its
|
||||
# rollouts: #2896 broadcasts at the END of a step, so the first step would otherwise block
|
||||
# on rollouts the paused inference engines cannot produce until they receive
|
||||
# v{progress.step-1}. Filesystem broadcast needs no startup rendezvous (fresh: base model
|
||||
# = v0; resume: the orchestrator reads its checkpoint dir), and a one-shot startup
|
||||
# broadcast would miss multi-run runs registered after the first step.
|
||||
if progress.step == start_step and weight_broadcast is not None and config.weight_broadcast.type == "nccl":
|
||||
logger.info(f"Broadcasting startup policy weights (v{progress.step - 1}) to inference engines")
|
||||
multi_run_manager.wait_for_run(0)
|
||||
for idx in multi_run_manager.used_idxs:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import json
|
||||
import uuid
|
||||
from collections import defaultdict
|
||||
from typing import Literal, TypedDict, cast
|
||||
from typing import Any, Literal, TypedDict, cast
|
||||
|
||||
import torch
|
||||
from datasets import Dataset, interleave_datasets, load_dataset
|
||||
@@ -15,13 +15,7 @@ from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.configs.sft import DataConfig, LossMaskConfig, SFTDataConfig
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.chat_template import (
|
||||
IncrementalTokenizationError,
|
||||
build_incremental_token_mask,
|
||||
deserialize_tool_calls,
|
||||
normalize_messages,
|
||||
strip_message_content,
|
||||
)
|
||||
from prime_rl.utils.chat_template import deserialize_tool_calls, normalize_messages
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
STACKING_DATASET_BUCKET_TIMEOUT = 10
|
||||
@@ -114,13 +108,33 @@ class FakeDataset(StatefulIterableDataset):
|
||||
yield fake_sample
|
||||
|
||||
|
||||
def _drop_null_fields(value: Any, path: tuple[str, ...] = ()) -> Any:
|
||||
"""Recursively strip ``None``-valued keys from dict structures.
|
||||
|
||||
PyArrow's JSON loader unifies schemas across rows, so heterogeneous
|
||||
OAI content blocks (text vs image_url) end up with all union keys
|
||||
filled with ``None`` where absent. That confuses permissive
|
||||
content-type predicates inside renderers (e.g. ``"image_url" in item``
|
||||
returns ``True`` even when the value is null). Strip the noise before
|
||||
handing messages off to the renderer. Tool-call arguments are opaque
|
||||
JSON payloads, so preserve their null values.
|
||||
"""
|
||||
if path[-3:] == ("tool_calls", "function", "arguments"):
|
||||
return value
|
||||
if isinstance(value, dict):
|
||||
return {k: _drop_null_fields(v, (*path, k)) for k, v in value.items() if v is not None}
|
||||
if isinstance(value, list):
|
||||
return [_drop_null_fields(v, path) for v in value]
|
||||
return value
|
||||
|
||||
|
||||
class SFTDataset(StatefulIterableDataset):
|
||||
"""A dataset wrapping a HF SFT dataset with prompt/completion or raw messages format."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dataset: Dataset,
|
||||
tokenizer: PreTrainedTokenizer | None,
|
||||
renderer: Renderer,
|
||||
shuffle: bool = True,
|
||||
seed: int = 0,
|
||||
seq_len: int = 128,
|
||||
@@ -128,24 +142,18 @@ class SFTDataset(StatefulIterableDataset):
|
||||
loss_mask_config: LossMaskConfig = LossMaskConfig(),
|
||||
max_examples: int | None = None,
|
||||
max_epochs: int | None = None,
|
||||
renderer: Renderer | None = None,
|
||||
):
|
||||
super().__init__()
|
||||
self.logger = get_logger()
|
||||
self.dataset = dataset
|
||||
self.num_examples = len(self.dataset)
|
||||
self.tokenizer = tokenizer
|
||||
self.renderer = renderer
|
||||
self.shuffle = shuffle
|
||||
self.seed = seed
|
||||
self.seq_len = seq_len
|
||||
self.loss_mask_config = loss_mask_config
|
||||
self.max_examples = max_examples
|
||||
self.max_epochs = max_epochs
|
||||
self.renderer = renderer
|
||||
self._warned_chat_template_kwargs = False
|
||||
|
||||
if self.tokenizer is None:
|
||||
self.logger.warning("No tokenizer provided, will not process examples")
|
||||
|
||||
# If specified, select a subset of the dataset
|
||||
if self.max_examples is not None:
|
||||
@@ -163,16 +171,14 @@ class SFTDataset(StatefulIterableDataset):
|
||||
self.data_world_size = get_world().world_size // non_dp_size * num_workers
|
||||
|
||||
def _process(self, example: dict) -> dict | None:
|
||||
# Skip processing if no tokenizer was provided
|
||||
if self.tokenizer is None:
|
||||
return example
|
||||
|
||||
def resolve_messages(example: dict) -> list[dict]:
|
||||
# `messages` takes precedence over explicit split fields and is interpreted
|
||||
# as a whole-chat training sample with an empty prompt.
|
||||
if "messages" in example:
|
||||
# as a whole-chat training sample with an empty prompt. Null-check rather
|
||||
# than key-check: Arrow schema union adds `messages: null` to
|
||||
# prompt/completion rows whenever other rows have a `messages` column.
|
||||
if example.get("messages") is not None:
|
||||
messages = normalize_messages(example["messages"], default_role="assistant")
|
||||
elif "prompt" in example and "completion" in example:
|
||||
elif example.get("prompt") is not None and example.get("completion") is not None:
|
||||
messages = normalize_messages(example["prompt"], default_role="user") + normalize_messages(
|
||||
example["completion"], default_role="assistant"
|
||||
)
|
||||
@@ -182,22 +188,17 @@ class SFTDataset(StatefulIterableDataset):
|
||||
"or both 'prompt' and 'completion' columns for SFT"
|
||||
)
|
||||
|
||||
# Deserialize tool call arguments from message list, if present - assumes OAI format
|
||||
# Reference: https://platform.openai.com/docs/guides/function-calling#handling-function-calls
|
||||
messages = deserialize_tool_calls(messages)
|
||||
|
||||
# Strip content from all messages so that incremental tokenization works
|
||||
# NOTE: This has the side effect that we do never train on leading or trailing whitespace
|
||||
return strip_message_content(messages)
|
||||
# Strip nulls before deserializing so genuine nulls inside tool-call
|
||||
# argument strings survive.
|
||||
messages = [_drop_null_fields(m) for m in messages]
|
||||
return deserialize_tool_calls(messages)
|
||||
|
||||
messages = resolve_messages(example)
|
||||
|
||||
# Parse available tools, if present - assumes OAI format
|
||||
# Reference: https://platform.openai.com/docs/guides/function-calling#function-tool-example
|
||||
# Accepts either `tools` or `tool_defs` (the verifiers rollout format),
|
||||
# as either a JSON-encoded string of a list or a list of dicts. Tools
|
||||
# arriving in the verifiers shape are converted to OAI form so any
|
||||
# downstream chat template can consume them.
|
||||
# Parse available tools, if present - assumes OAI format. Accepts either
|
||||
# `tools` or `tool_defs` (the verifiers rollout format), as either a
|
||||
# JSON-encoded string of a list or a list of dicts; verifiers-shaped
|
||||
# tools are converted to OAI form for the chat template.
|
||||
raw_tools = example.get("tools", example.get("tool_defs"))
|
||||
if not raw_tools:
|
||||
tools = []
|
||||
@@ -223,55 +224,37 @@ class SFTDataset(StatefulIterableDataset):
|
||||
assert "role" in message, "Message must have a role"
|
||||
match message["role"]:
|
||||
case "user":
|
||||
return True if self.loss_mask_config.user else False
|
||||
return self.loss_mask_config.user
|
||||
case "assistant":
|
||||
return True if self.loss_mask_config.assistant else False
|
||||
return self.loss_mask_config.assistant
|
||||
case "system":
|
||||
return True if self.loss_mask_config.system else False
|
||||
return self.loss_mask_config.system
|
||||
case "tool":
|
||||
return True if self.loss_mask_config.tool else False
|
||||
return self.loss_mask_config.tool
|
||||
case _:
|
||||
raise ValueError(f"Invalid message role: {message['role']}")
|
||||
|
||||
if self.renderer is not None:
|
||||
if example.get("chat_template_kwargs") and not self._warned_chat_template_kwargs:
|
||||
self.logger.warning(
|
||||
"Example carries chat_template_kwargs but a renderer is configured; "
|
||||
"renderers don't forward chat_template_kwargs (model-specific "
|
||||
"renderers bake their template behavior in). These kwargs will "
|
||||
"be ignored. Further warnings suppressed for this dataset."
|
||||
)
|
||||
self._warned_chat_template_kwargs = True
|
||||
# Defer to the renderer's sampled_mask by default: a role filter would
|
||||
# drop sampled stop markers attributed to the next message (e.g. GLM's
|
||||
# turn-closing <|user|> / <|observation|>).
|
||||
role_to_mask = None if self.loss_mask_config.assistant else should_mask
|
||||
|
||||
input_ids, loss_mask = build_training_sample(
|
||||
self.renderer,
|
||||
messages,
|
||||
role_to_mask=should_mask,
|
||||
tools=tools,
|
||||
)
|
||||
else:
|
||||
try:
|
||||
input_ids, loss_mask = build_incremental_token_mask(
|
||||
self.tokenizer,
|
||||
messages,
|
||||
role_to_mask=should_mask,
|
||||
tools=tools,
|
||||
chat_template_kwargs=example.get("chat_template_kwargs", {}),
|
||||
collapse_consecutive_tool_messages=True,
|
||||
)
|
||||
except IncrementalTokenizationError as e:
|
||||
self.logger.warning(f"Skipping example {example.get('__index', '')}: {e}")
|
||||
return None
|
||||
# Non-assistant roles are opted into the loss via the renderer's
|
||||
# body-only path: the message content is trained, not the role
|
||||
# scaffolding (e.g. <|im_start|>assistant) the harness emits.
|
||||
content_sft_roles = {role for role in ("user", "system", "tool") if getattr(self.loss_mask_config, role)}
|
||||
sample = build_training_sample(
|
||||
self.renderer,
|
||||
messages,
|
||||
role_to_mask=role_to_mask,
|
||||
tools=tools,
|
||||
content_sft_roles=content_sft_roles or None,
|
||||
ensure_final_stop=True,
|
||||
)
|
||||
input_ids = list(sample.token_ids)
|
||||
loss_mask = list(sample.loss_mask)
|
||||
|
||||
# If EOS token is not found, manually append it
|
||||
if not self.tokenizer.eos_token_id in input_ids:
|
||||
self.logger.warning(
|
||||
f"Did not find EOS token ID {self.tokenizer.eos_token_id} in input_ids. Is something wrong with the chat template? Manually appending EOS token..."
|
||||
)
|
||||
input_ids.append(cast(int, self.tokenizer.eos_token_id))
|
||||
loss_mask.append(True)
|
||||
|
||||
# Prepare inputs
|
||||
# Causal shift: model predicts next token from current.
|
||||
target_ids = input_ids.copy()[1:]
|
||||
loss_mask = loss_mask[1:]
|
||||
input_ids = input_ids[:-1]
|
||||
@@ -280,15 +263,16 @@ class SFTDataset(StatefulIterableDataset):
|
||||
self.logger.warning(
|
||||
f"Skipping example {example.get('__index', '')} because no trainable tokens were found within the context window ({self.seq_len}). This is to prevent NaN loss."
|
||||
)
|
||||
return
|
||||
return None
|
||||
|
||||
assert len(input_ids) == len(loss_mask) == len(target_ids), (
|
||||
f"input_ids, loss_mask and target_ids must have the same length, but got {len(input_ids)=}, {len(loss_mask)=}, {len(target_ids)=}"
|
||||
)
|
||||
assert sum(loss_mask) > 0, "There are no tokens in this sample that contribute to the loss"
|
||||
assert self.tokenizer.eos_token_id in target_ids, "EOS token ID must be present in target_ids"
|
||||
assert set(self.renderer.get_stop_token_ids()) & set(target_ids), (
|
||||
"A renderer stop token must be present in target_ids"
|
||||
)
|
||||
|
||||
# Create sample (with one fake target for the last token)
|
||||
return {
|
||||
"input_ids": input_ids,
|
||||
"target_ids": target_ids,
|
||||
@@ -297,9 +281,6 @@ class SFTDataset(StatefulIterableDataset):
|
||||
}
|
||||
|
||||
def __iter__(self):
|
||||
"""
|
||||
Apply chat template and tokenize a single example in prompt + completion format (https://github.com/huggingface/trl/blob/de27d612b026526ba39b88eee348994d7636e033/trl/trainer/sft_trainer.py#L661)
|
||||
"""
|
||||
dataset = self.dataset.shuffle(seed=self.epoch + self.seed) if self.shuffle else self.dataset
|
||||
while True:
|
||||
self.step += 1
|
||||
@@ -585,21 +566,25 @@ def setup_dataset(
|
||||
) -> StatefulIterableDataset:
|
||||
if config.type == "fake":
|
||||
return FakeDataset(
|
||||
vocab_size=tokenizer.vocab_size, seq_len=config.seq_len, length=config.length, input_ids=config.input_ids
|
||||
vocab_size=tokenizer.vocab_size,
|
||||
seq_len=config.seq_len,
|
||||
length=config.length,
|
||||
input_ids=config.input_ids,
|
||||
)
|
||||
elif config.type == "sft":
|
||||
if renderer is None:
|
||||
raise ValueError("SFT data requires a renderer.")
|
||||
if raw_dataset is None:
|
||||
raw_dataset = load_sft_dataset(config)
|
||||
return SFTDataset(
|
||||
raw_dataset,
|
||||
tokenizer,
|
||||
renderer,
|
||||
shuffle=config.shuffle,
|
||||
seed=config.seed,
|
||||
seq_len=config.seq_len,
|
||||
loss_mask_config=config.loss_mask,
|
||||
non_dp_size=non_dp_size,
|
||||
max_epochs=max_epochs,
|
||||
renderer=renderer,
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"Invalid dataset type: {config.type}")
|
||||
|
||||
@@ -5,7 +5,6 @@ from contextlib import nullcontext
|
||||
from datetime import timedelta
|
||||
|
||||
from renderers.base import create_renderer
|
||||
from renderers.default import DefaultRenderer
|
||||
from ring_flash_attn import substitute_hf_flash_attn
|
||||
from torch.nn import CrossEntropyLoss
|
||||
|
||||
@@ -162,17 +161,12 @@ def train(config: SFTConfig):
|
||||
logger.info(f"Initializing tokenizer ({config.tokenizer})")
|
||||
tokenizer = setup_tokenizer(config.tokenizer)
|
||||
|
||||
# Fake data never renders messages, so a model without a hand-coded renderer
|
||||
# can still be used to benchmark step time / memory. Validation data is
|
||||
# always real, so it needs the renderer even when training data is fake.
|
||||
renderer = None
|
||||
if config.renderer is not None:
|
||||
if config.data.type != "fake" or config.val is not None:
|
||||
renderer = create_renderer(tokenizer, config.renderer)
|
||||
if isinstance(renderer, DefaultRenderer):
|
||||
raise ValueError(
|
||||
f"renderer set for {config.tokenizer.name!r} resolved to DefaultRenderer. "
|
||||
"DefaultRenderer falls back to incremental apply_chat_template and does NOT "
|
||||
"fix position-dependent chat templates — the bug the renderer client is meant to solve. "
|
||||
"Either use a model with a hand-coded renderer (see renderers.base.MODEL_RENDERER_MAP), "
|
||||
"set [renderer] name=<hand-coded renderer> explicitly, or remove the [renderer] block."
|
||||
)
|
||||
logger.info(f"Initialized {type(renderer).__name__} for {config.tokenizer.name}")
|
||||
|
||||
# Set up the optimizer
|
||||
|
||||
@@ -1,13 +1,5 @@
|
||||
import json
|
||||
from typing import Any, Callable
|
||||
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
|
||||
class IncrementalTokenizationError(ValueError):
|
||||
"""Raised when incremental tokenization produces inconsistent token prefixes."""
|
||||
|
||||
pass
|
||||
from typing import Any
|
||||
|
||||
|
||||
def normalize_messages(messages: Any, default_role: str) -> list[dict[str, Any]]:
|
||||
@@ -56,79 +48,3 @@ def deserialize_tool_calls(messages: list[dict[str, Any]]) -> list[dict[str, Any
|
||||
)
|
||||
|
||||
return deserialized_messages
|
||||
|
||||
|
||||
def strip_message_content(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
def _strip(message: dict[str, Any]) -> dict[str, Any]:
|
||||
content = message.get("content")
|
||||
if isinstance(content, str):
|
||||
return {**message, "content": content.strip()}
|
||||
return message
|
||||
|
||||
return [_strip(message) for message in messages]
|
||||
|
||||
|
||||
def should_add_generation_prompt(messages: list[dict[str, Any]], idx: int) -> bool:
|
||||
role = messages[idx].get("role")
|
||||
if role not in ("user", "tool"):
|
||||
return False
|
||||
if idx + 1 >= len(messages):
|
||||
return False
|
||||
return messages[idx + 1].get("role") == "assistant"
|
||||
|
||||
|
||||
def render_messages(
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
messages: list[dict[str, Any]],
|
||||
*,
|
||||
tools: list[dict[str, Any]] | None = None,
|
||||
chat_template_kwargs: dict[str, Any] | None = None,
|
||||
add_generation_prompt: bool = False,
|
||||
) -> list[int]:
|
||||
kwargs = dict(chat_template_kwargs or {})
|
||||
kwargs["add_generation_prompt"] = add_generation_prompt
|
||||
if tools is not None:
|
||||
kwargs["tools"] = tools
|
||||
kwargs["return_dict"] = False
|
||||
return list(tokenizer.apply_chat_template(messages, **kwargs))
|
||||
|
||||
|
||||
def build_incremental_token_mask(
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
messages: list[dict[str, Any]],
|
||||
*,
|
||||
role_to_mask: Callable[[dict[str, Any]], bool],
|
||||
tools: list[dict[str, Any]] | None = None,
|
||||
chat_template_kwargs: dict[str, Any] | None = None,
|
||||
collapse_consecutive_tool_messages: bool = False,
|
||||
) -> tuple[list[int], list[bool]]:
|
||||
token_mask: list[bool] = []
|
||||
prev_ids: list[int] = []
|
||||
prev_len = 0
|
||||
|
||||
for idx, message in enumerate(messages):
|
||||
role = message.get("role")
|
||||
if collapse_consecutive_tool_messages and role == "tool" and idx + 1 < len(messages):
|
||||
if messages[idx + 1].get("role") == "tool":
|
||||
continue
|
||||
|
||||
cur_ids = render_messages(
|
||||
tokenizer,
|
||||
messages[: idx + 1],
|
||||
tools=tools,
|
||||
chat_template_kwargs=chat_template_kwargs,
|
||||
add_generation_prompt=should_add_generation_prompt(messages, idx),
|
||||
)
|
||||
|
||||
if prev_ids != cur_ids[:prev_len]:
|
||||
raise IncrementalTokenizationError(
|
||||
f"Mismatch in incremental tokenization with chat template at message {idx} (role={role}). "
|
||||
"This usually means the chat template is not stable under incremental application. "
|
||||
"The sample will be skipped."
|
||||
)
|
||||
|
||||
token_mask.extend([role_to_mask(message)] * (len(cur_ids) - prev_len))
|
||||
prev_ids = cur_ids
|
||||
prev_len = len(cur_ids)
|
||||
|
||||
return prev_ids, token_mask
|
||||
|
||||
@@ -55,8 +55,15 @@ def _build_rollout(
|
||||
)
|
||||
parent = len(nodes) - 1
|
||||
|
||||
# Trace token counts are usage-based, so carry provider usage on the final sampled turn:
|
||||
# every model-generated token as completion, the leading prompt + tool observations as the
|
||||
# fed-in context (num_input_tokens = num_total_tokens - num_output_tokens).
|
||||
output_tokens = sum(sampled_lengths)
|
||||
input_tokens = 1 + sum(obs_lengths)
|
||||
|
||||
for i, n_sampled in enumerate(sampled_lengths):
|
||||
ids = _take(n_sampled)
|
||||
is_last = i == len(sampled_lengths) - 1
|
||||
nodes.append(
|
||||
vf.MessageNode(
|
||||
message=vf.AssistantMessage(content="a"),
|
||||
@@ -65,6 +72,7 @@ def _build_rollout(
|
||||
logprobs=[-0.1] * n_sampled,
|
||||
sampled=True,
|
||||
parent=parent,
|
||||
usage=vf.Usage(prompt_tokens=input_tokens, completion_tokens=output_tokens) if is_last else None,
|
||||
)
|
||||
)
|
||||
parent = len(nodes) - 1
|
||||
|
||||
@@ -547,6 +547,26 @@ def test_orchestrator_renderer_auto_accepts_mapped_model():
|
||||
assert config.renderer.name == "auto"
|
||||
|
||||
|
||||
def test_sft_renderer_auto_accepts_prime_qwen_model():
|
||||
config = SFTConfig.model_validate({"model": {"name": "PrimeIntellect/Qwen3-0.6B"}})
|
||||
assert config.renderer.name == "auto"
|
||||
|
||||
|
||||
def test_sft_rejects_default_renderer_for_real_data():
|
||||
with pytest.raises(ValidationError, match="requires a typed renderer"):
|
||||
SFTConfig.model_validate({"renderer": {"name": "default"}})
|
||||
|
||||
|
||||
def test_sft_allows_unused_default_renderer_for_fake_data():
|
||||
config = SFTConfig.model_validate(
|
||||
{
|
||||
"data": {"type": "fake"},
|
||||
"renderer": {"name": "default"},
|
||||
}
|
||||
)
|
||||
assert config.renderer.name == "default"
|
||||
|
||||
|
||||
def test_orchestrator_explicit_renderer_skips_unmapped_check():
|
||||
"""Explicit renderer.name bypasses the auto-resolution check — user opted in."""
|
||||
config = OrchestratorConfig.model_validate(
|
||||
|
||||
@@ -2,64 +2,125 @@ from collections import Counter
|
||||
|
||||
import pytest
|
||||
from datasets import Dataset, interleave_datasets
|
||||
from renderers import create_renderer
|
||||
from renderers.base import RenderedTokens
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
from prime_rl.trainer.sft.data import SFTDataset
|
||||
from prime_rl.trainer.sft.data import SFTDataset, _drop_null_fields
|
||||
from prime_rl.trainer.utils import print_sample
|
||||
|
||||
_BOS_TOKEN_ID = 0
|
||||
_STOP_TOKEN_ID = 1
|
||||
|
||||
|
||||
def _sample_token_ids(value: str) -> list[int]:
|
||||
return [ord(char) + 2 for char in value]
|
||||
|
||||
|
||||
class _DummyRenderer:
|
||||
def render(self, messages, **kwargs):
|
||||
content_ids = _sample_token_ids(messages[-1]["content"])
|
||||
token_ids = [_BOS_TOKEN_ID, *content_ids, _STOP_TOKEN_ID]
|
||||
return RenderedTokens(
|
||||
token_ids=token_ids,
|
||||
message_indices=[-1, *([len(messages) - 1] * (len(content_ids) + 1))],
|
||||
sampled_mask=[False, *([True] * (len(content_ids) + 1))],
|
||||
)
|
||||
|
||||
def get_stop_token_ids(self):
|
||||
return [_STOP_TOKEN_ID]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def build_dummy_dataset():
|
||||
return lambda letter, num_examples: Dataset.from_list([{"text": f"{letter}{i}"} for i in range(num_examples)])
|
||||
return lambda letter, num_examples: Dataset.from_list(
|
||||
[{"messages": [{"role": "assistant", "content": f"{letter}{i}"}]} for i in range(num_examples)]
|
||||
)
|
||||
|
||||
|
||||
def test_init_sft_dataset(build_dummy_dataset):
|
||||
@pytest.fixture
|
||||
def dummy_renderer():
|
||||
return _DummyRenderer()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"arguments",
|
||||
[
|
||||
pytest.param('{"reasoning_effort": null}', id="json-string"),
|
||||
pytest.param({"reasoning_effort": None}, id="dict"),
|
||||
],
|
||||
)
|
||||
def test_drop_null_fields_preserves_tool_call_arguments(arguments):
|
||||
message = {
|
||||
"role": "assistant",
|
||||
"content": [{"type": "text", "text": "Calling a tool", "image_url": None}],
|
||||
"tool_calls": [{"function": {"name": "listReasoningModels", "arguments": arguments}}],
|
||||
"metadata": {"arguments": {"unrelated_null": None}},
|
||||
}
|
||||
|
||||
cleaned = _drop_null_fields(message)
|
||||
|
||||
assert cleaned["tool_calls"][0]["function"]["arguments"] == arguments
|
||||
assert cleaned["content"] == [{"type": "text", "text": "Calling a tool"}]
|
||||
assert cleaned["metadata"] == {"arguments": {}}
|
||||
|
||||
|
||||
def test_init_sft_dataset(build_dummy_dataset, dummy_renderer):
|
||||
"""Tests basic initialization."""
|
||||
dataset = build_dummy_dataset("a", 1)
|
||||
sft_dataset = SFTDataset(dataset, tokenizer=None)
|
||||
sft_dataset = SFTDataset(dataset, dummy_renderer)
|
||||
assert sft_dataset is not None
|
||||
|
||||
|
||||
def test_raise_error_if_no_prompt_and_completion(build_dummy_dataset):
|
||||
"""Tests that an error is raised if no supported SFT message fields are provided."""
|
||||
dataset = build_dummy_dataset("a", 1)
|
||||
dataset = Dataset.from_list([{"text": "a0"}])
|
||||
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
|
||||
sft_dataset = SFTDataset(dataset, tokenizer=tokenizer)
|
||||
sft_dataset = SFTDataset(dataset, create_renderer(tokenizer))
|
||||
with pytest.raises(ValueError):
|
||||
next(iter(sft_dataset))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("max_epochs", [1, 2, 4])
|
||||
def test_sft_first_exhausted(build_dummy_dataset, max_epochs: int):
|
||||
def test_sft_first_exhausted(build_dummy_dataset, dummy_renderer, max_epochs: int):
|
||||
a = build_dummy_dataset("a", 1)
|
||||
b = build_dummy_dataset("b", 2)
|
||||
ds = [a, b]
|
||||
dataset = interleave_datasets(ds, stopping_strategy="first_exhausted")
|
||||
dataset = SFTDataset(dataset, tokenizer=None, shuffle=False, max_epochs=max_epochs)
|
||||
dataset = SFTDataset(dataset, dummy_renderer, shuffle=False, max_epochs=max_epochs)
|
||||
num_samples = 0
|
||||
sampling_order = []
|
||||
for x in dataset:
|
||||
sampling_order.append(x["text"])
|
||||
sampling_order.append(x["target_ids"][:-1])
|
||||
num_samples += 1
|
||||
assert num_samples == max_epochs * min([len(d) for d in ds]) * len(ds)
|
||||
assert sampling_order == ["a0", "b0"] * max_epochs
|
||||
assert sampling_order == [_sample_token_ids("a0"), _sample_token_ids("b0")] * max_epochs
|
||||
|
||||
|
||||
@pytest.mark.parametrize("max_epochs", [1, 2, 4])
|
||||
def test_sft_all_exhausted(build_dummy_dataset, max_epochs: int):
|
||||
def test_sft_all_exhausted(build_dummy_dataset, dummy_renderer, max_epochs: int):
|
||||
a = build_dummy_dataset("a", 1)
|
||||
b = build_dummy_dataset("b", 2)
|
||||
ds = [a, b]
|
||||
dataset = interleave_datasets(ds, stopping_strategy="all_exhausted")
|
||||
dataset = SFTDataset(dataset, tokenizer=None, shuffle=False, max_epochs=max_epochs)
|
||||
dataset = SFTDataset(dataset, dummy_renderer, shuffle=False, max_epochs=max_epochs)
|
||||
num_samples = 0
|
||||
sampling_order = []
|
||||
for x in dataset:
|
||||
sampling_order.append(x["text"])
|
||||
sampling_order.append(x["target_ids"][:-1])
|
||||
num_samples += 1
|
||||
assert num_samples == max_epochs * max([len(d) for d in ds]) * len(ds)
|
||||
print(sampling_order)
|
||||
assert sampling_order == ["a0", "b0", "a0", "b1"] * max_epochs
|
||||
assert (
|
||||
sampling_order
|
||||
== [
|
||||
_sample_token_ids("a0"),
|
||||
_sample_token_ids("b0"),
|
||||
_sample_token_ids("a0"),
|
||||
_sample_token_ids("b1"),
|
||||
]
|
||||
* max_epochs
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -70,21 +131,21 @@ def test_sft_all_exhausted(build_dummy_dataset, max_epochs: int):
|
||||
pytest.param((9 / 10, 1 / 10), id="high_low_probs"),
|
||||
],
|
||||
)
|
||||
def test_sft_all_exhausted_with_probs(build_dummy_dataset, probs: list[float]):
|
||||
def test_sft_all_exhausted_with_probs(build_dummy_dataset, dummy_renderer, probs: list[float]):
|
||||
"""Tests that the ratio of samples from different datasets is as specified, in expectation."""
|
||||
a = build_dummy_dataset("a", int(1e3))
|
||||
b = build_dummy_dataset("b", int(10e3))
|
||||
ds = [a, b]
|
||||
dataset = interleave_datasets(ds, stopping_strategy="all_exhausted", probabilities=probs)
|
||||
dataset = SFTDataset(dataset, tokenizer=None, shuffle=False, max_epochs=1)
|
||||
dataset = SFTDataset(dataset, dummy_renderer, shuffle=False, max_epochs=1)
|
||||
num_samples = 0
|
||||
sampling_freq = []
|
||||
for x in dataset:
|
||||
sampling_freq.append(x["text"][0])
|
||||
sampling_freq.append(x["target_ids"][0])
|
||||
num_samples += 1
|
||||
sampling_freq = Counter(sampling_freq)
|
||||
ratio_a = sampling_freq["a"] / num_samples
|
||||
ratio_b = sampling_freq["b"] / num_samples
|
||||
ratio_a = sampling_freq[ord("a") + 2] / num_samples
|
||||
ratio_b = sampling_freq[ord("b") + 2] / num_samples
|
||||
assert ratio_a > probs[0] * 0.8 and ratio_a < probs[0] * 1.2, (
|
||||
f"Expected frequency of samples from a to be between {probs[0] * 0.8} and {probs[0] * 1.2}, but got {ratio_a}"
|
||||
)
|
||||
@@ -93,10 +154,10 @@ def test_sft_all_exhausted_with_probs(build_dummy_dataset, probs: list[float]):
|
||||
)
|
||||
|
||||
|
||||
def test_sft_dataset_state(build_dummy_dataset):
|
||||
def test_sft_dataset_state(build_dummy_dataset, dummy_renderer):
|
||||
"""Tests the state of the dataset within and across epochs."""
|
||||
dataset = build_dummy_dataset("", 4)
|
||||
dataset = SFTDataset(dataset, tokenizer=None, shuffle=False, max_epochs=2)
|
||||
dataset = SFTDataset(dataset, dummy_renderer, shuffle=False, max_epochs=2)
|
||||
dataiter = iter(dataset)
|
||||
|
||||
# Initial state
|
||||
@@ -105,24 +166,24 @@ def test_sft_dataset_state(build_dummy_dataset):
|
||||
# Epoch 1
|
||||
for i in range(4):
|
||||
sample = next(dataiter)
|
||||
assert sample["text"] == str(i)
|
||||
assert sample["target_ids"][:-1] == _sample_token_ids(str(i))
|
||||
assert dataset.state_dict() == {"epoch": 0, "step": i + 1}
|
||||
|
||||
# Epoch 2
|
||||
for i in range(4):
|
||||
sample = next(dataiter)
|
||||
assert sample["text"] == str(i)
|
||||
assert sample["target_ids"][:-1] == _sample_token_ids(str(i))
|
||||
assert dataset.state_dict() == {"epoch": 1, "step": 4 + i + 1}
|
||||
|
||||
with pytest.raises(StopIteration):
|
||||
next(dataiter)
|
||||
|
||||
|
||||
def test_sft_dataset_state_resume(build_dummy_dataset):
|
||||
def test_sft_dataset_state_resume(build_dummy_dataset, dummy_renderer):
|
||||
"""Tests resuming the dataset from checkpoint in between epochs."""
|
||||
dataset = SFTDataset(
|
||||
build_dummy_dataset("", 4),
|
||||
tokenizer=None,
|
||||
dummy_renderer,
|
||||
shuffle=False,
|
||||
max_epochs=2,
|
||||
)
|
||||
@@ -134,8 +195,7 @@ def test_sft_dataset_state_resume(build_dummy_dataset):
|
||||
# Epoch 1
|
||||
for i in range(4):
|
||||
sample = next(dataiter)
|
||||
print(sample["text"])
|
||||
assert sample["text"] == str(i)
|
||||
assert sample["target_ids"][:-1] == _sample_token_ids(str(i))
|
||||
assert dataset.state_dict() == {"epoch": 0, "step": i + 1}
|
||||
|
||||
# Resuming from checkpoint cross epoch
|
||||
@@ -143,7 +203,7 @@ def test_sft_dataset_state_resume(build_dummy_dataset):
|
||||
del dataset
|
||||
dataset = SFTDataset(
|
||||
build_dummy_dataset("", 4),
|
||||
tokenizer=None,
|
||||
dummy_renderer,
|
||||
shuffle=False,
|
||||
max_epochs=2,
|
||||
)
|
||||
@@ -153,8 +213,7 @@ def test_sft_dataset_state_resume(build_dummy_dataset):
|
||||
# Epoch 2.1
|
||||
for i in range(2):
|
||||
sample = next(dataiter)
|
||||
print(sample["text"])
|
||||
assert sample["text"] == str(i)
|
||||
assert sample["target_ids"][:-1] == _sample_token_ids(str(i))
|
||||
assert dataset.state_dict() == {"epoch": 1, "step": 4 + i + 1}
|
||||
|
||||
# Resuming from checkpoint mid epoch
|
||||
@@ -162,7 +221,7 @@ def test_sft_dataset_state_resume(build_dummy_dataset):
|
||||
del dataset
|
||||
dataset = SFTDataset(
|
||||
build_dummy_dataset("", 4),
|
||||
tokenizer=None,
|
||||
dummy_renderer,
|
||||
shuffle=False,
|
||||
max_epochs=2,
|
||||
)
|
||||
@@ -172,8 +231,7 @@ def test_sft_dataset_state_resume(build_dummy_dataset):
|
||||
# Epoch 2.2
|
||||
for i in range(2, 4):
|
||||
sample = next(dataiter)
|
||||
print(sample["text"])
|
||||
assert sample["text"] == str(i)
|
||||
assert sample["target_ids"][:-1] == _sample_token_ids(str(i))
|
||||
assert dataset.state_dict() == {"epoch": 1, "step": 4 + i + 1}
|
||||
|
||||
with pytest.raises(StopIteration):
|
||||
@@ -194,7 +252,7 @@ def test_multiturn_loss_mask():
|
||||
]
|
||||
)
|
||||
tokenizer = AutoTokenizer.from_pretrained("PrimeIntellect/Qwen3-0.6B") # Properly handles multi-turn think
|
||||
dataset = SFTDataset(dataset, tokenizer=tokenizer, max_examples=1)
|
||||
dataset = SFTDataset(dataset, create_renderer(tokenizer), max_examples=1)
|
||||
sample = next(iter(dataset))
|
||||
print_sample(sample["input_ids"], sample["loss_mask"], tokenizer)
|
||||
|
||||
@@ -257,7 +315,7 @@ def test_multiturn_loss_mask_with_tools():
|
||||
|
||||
dataset = Dataset.from_list([tool_example])
|
||||
tokenizer = AutoTokenizer.from_pretrained("PrimeIntellect/Qwen3-0.6B") # Properly handles multi-turn think
|
||||
dataset = SFTDataset(dataset, tokenizer=tokenizer, max_examples=1)
|
||||
dataset = SFTDataset(dataset, create_renderer(tokenizer), max_examples=1)
|
||||
sample = next(iter(dataset))
|
||||
print_sample(sample["input_ids"], sample["loss_mask"], tokenizer)
|
||||
|
||||
@@ -282,10 +340,14 @@ def test_messages_rows_are_equivalent_to_empty_prompt_completion():
|
||||
]
|
||||
|
||||
tokenizer = AutoTokenizer.from_pretrained("PrimeIntellect/Qwen3-0.6B")
|
||||
messages_dataset = SFTDataset(Dataset.from_list([{"messages": messages}]), tokenizer=tokenizer, max_examples=1)
|
||||
messages_dataset = SFTDataset(
|
||||
Dataset.from_list([{"messages": messages}]),
|
||||
create_renderer(tokenizer),
|
||||
max_examples=1,
|
||||
)
|
||||
split_dataset = SFTDataset(
|
||||
Dataset.from_list([{"prompt": [], "completion": messages}]),
|
||||
tokenizer=tokenizer,
|
||||
create_renderer(tokenizer),
|
||||
max_examples=1,
|
||||
)
|
||||
|
||||
@@ -304,11 +366,36 @@ def test_messages_take_precedence_over_prompt_and_completion():
|
||||
"completion": [{"role": "assistant", "content": "Ignored completion"}],
|
||||
}
|
||||
|
||||
messages_dataset = SFTDataset(Dataset.from_list([row]), tokenizer=tokenizer, max_examples=1)
|
||||
messages_dataset = SFTDataset(
|
||||
Dataset.from_list([row]),
|
||||
create_renderer(tokenizer),
|
||||
max_examples=1,
|
||||
)
|
||||
expected_dataset = SFTDataset(
|
||||
Dataset.from_list([{"prompt": [], "completion": row["messages"]}]),
|
||||
tokenizer=tokenizer,
|
||||
create_renderer(tokenizer),
|
||||
max_examples=1,
|
||||
)
|
||||
|
||||
assert next(iter(messages_dataset)) == next(iter(expected_dataset))
|
||||
|
||||
|
||||
def test_null_messages_falls_back_to_prompt_and_completion():
|
||||
# Arrow schema union adds `messages: None` to prompt/completion rows when
|
||||
# other rows in the file have a `messages` column
|
||||
tokenizer = AutoTokenizer.from_pretrained("PrimeIntellect/Qwen3-0.6B")
|
||||
prompt = [{"role": "user", "content": "What is 2+2?"}]
|
||||
completion = [{"role": "assistant", "content": "4"}]
|
||||
|
||||
mixed_row_dataset = SFTDataset(
|
||||
Dataset.from_list([{"messages": None, "prompt": prompt, "completion": completion}]),
|
||||
create_renderer(tokenizer),
|
||||
max_examples=1,
|
||||
)
|
||||
expected_dataset = SFTDataset(
|
||||
Dataset.from_list([{"prompt": prompt, "completion": completion}]),
|
||||
create_renderer(tokenizer),
|
||||
max_examples=1,
|
||||
)
|
||||
|
||||
assert next(iter(mixed_row_dataset)) == next(iter(expected_dataset))
|
||||
|
||||
@@ -41,7 +41,9 @@ members = [
|
||||
"alphabet-sort-v1",
|
||||
"apex-shortlist-v1",
|
||||
"arxivmath-v1",
|
||||
"automationbench-v1",
|
||||
"bfcl-v3-v1",
|
||||
"browsecomp-plus-v1",
|
||||
"browsecomp-v1",
|
||||
"browser-cua-example",
|
||||
"browser-dom-example",
|
||||
@@ -107,6 +109,7 @@ members = [
|
||||
"scicode-v1",
|
||||
"scratchpad-v1",
|
||||
"self-reward",
|
||||
"senior-swe-bench-v1",
|
||||
"sentence-repeater",
|
||||
"simpleqa-v1",
|
||||
"simpleqa-verified-v1",
|
||||
@@ -457,6 +460,40 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "automation-bench"
|
||||
version = "1.0.5"
|
||||
source = { git = "https://github.com/mikasenghaas/AutomationBench.git?rev=6f0e683#6f0e6834930cf6906ed932e9c5b716206def40d7" }
|
||||
dependencies = [
|
||||
{ name = "anthropic" },
|
||||
{ name = "httpx" },
|
||||
{ name = "pydantic" },
|
||||
{ name = "python-dotenv" },
|
||||
{ name = "rich" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "automationbench-v1"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/tool_use/automationbench_v1" }
|
||||
dependencies = [
|
||||
{ name = "automation-bench" },
|
||||
{ name = "datasets" },
|
||||
{ name = "mcp" },
|
||||
{ name = "openai" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "automation-bench", git = "https://github.com/mikasenghaas/AutomationBench.git?rev=6f0e683" },
|
||||
{ name = "datasets" },
|
||||
{ name = "mcp", specifier = "<2" },
|
||||
{ name = "openai" },
|
||||
{ name = "verifiers", specifier = ">=0.2.1.dev42" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "backoff"
|
||||
version = "2.2.1"
|
||||
@@ -634,6 +671,18 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/1e/e2/0e93b865f648b5519360846669a35f28ee8f4e1d93d054f6850d8afbabde/blis-1.3.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:8177879fd3590b5eecdd377f9deafb5dc8af6d684f065bd01553302fb3fcf9a7", size = 14250939, upload-time = "2025-11-17T12:27:53.847Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bm25s"
|
||||
version = "0.3.9"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "numpy" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/7c/ab/39d08d4589dad6f5735a6b03ee083088dc37fba57fa45d4a0749393b9295/bm25s-0.3.9.tar.gz", hash = "sha256:895c679d952b7de8355edb5f3e1a620a1e2f294d1d42b919bf0821cce2e2f597", size = 80528, upload-time = "2026-05-13T23:08:20.952Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/48/83/06582913e2af0cf498cc478350070490b019c6f6b523cb8b6cfafd32f009/bm25s-0.3.9-py3-none-any.whl", hash = "sha256:db997475e82c9e81262b83fefe6a71304f2fdd0dafd037c8929828865fa6d465", size = 74475, upload-time = "2026-05-13T23:08:19.557Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "boto3"
|
||||
version = "1.43.40"
|
||||
@@ -662,6 +711,31 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/dc/8c/5f7e73fd66b28f0705bc55d7060d41ef72328b656b86ca53e75765b3ba2c/botocore-1.43.40-py3-none-any.whl", hash = "sha256:0bc9d352267c9e48415c5d7bb61ff05c3f193eac2fc7e69cfd229a05fbab67d6", size = 15323870, upload-time = "2026-07-03T00:28:12.56Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "browsecomp-plus-v1"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/search/browsecomp_plus_v1" }
|
||||
dependencies = [
|
||||
{ name = "bm25s" },
|
||||
{ name = "datasets" },
|
||||
{ name = "mcp" },
|
||||
{ name = "openai" },
|
||||
{ name = "pystemmer" },
|
||||
{ name = "tokenizers" },
|
||||
{ name = "verifiers" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "bm25s", specifier = ">=0.2.0" },
|
||||
{ name = "datasets" },
|
||||
{ name = "mcp", specifier = ">=1,<2" },
|
||||
{ name = "openai" },
|
||||
{ name = "pystemmer" },
|
||||
{ name = "tokenizers" },
|
||||
{ name = "verifiers", specifier = ">=0.2.0" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "browsecomp-v1"
|
||||
version = "0.1.0"
|
||||
@@ -1292,10 +1366,24 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/05/7f/798705f5296a58ca505d600456748d1be48078eac8a7050d8a98bc9edb89/decorator-5.3.1-py3-none-any.whl", hash = "sha256:f47fe6fdbd2edd623ecfe36875d37aba411624e2670dd395dddae1358689bb3c", size = 10365, upload-time = "2026-05-18T06:03:26.517Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deep-ep"
|
||||
version = "1.1.0+1fd57b0"
|
||||
source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.1.0+1fd57b0-cp312-cp312-linux_aarch64.whl" }
|
||||
resolution-markers = [
|
||||
"platform_machine == 'aarch64' and sys_platform == 'linux'",
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.1.0+1fd57b0-cp312-cp312-linux_aarch64.whl", hash = "sha256:fdfa7e1f79ed152948fb86330d4fcbf560d7d50fd78d3a96caf83d4bd1b61521" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deep-ep"
|
||||
version = "1.2.1+29d31c0"
|
||||
source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }
|
||||
resolution-markers = [
|
||||
"platform_machine == 'x86_64' and sys_platform == 'linux'",
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", hash = "sha256:a52b709d62c4dfc46a018b988724a7c10894125091aef596bf6d68e94c2b564e" },
|
||||
]
|
||||
@@ -4876,7 +4964,8 @@ dependencies = [
|
||||
|
||||
[package.optional-dependencies]
|
||||
all = [
|
||||
{ name = "deep-ep", marker = "platform_machine == 'x86_64'" },
|
||||
{ name = "deep-ep", version = "1.1.0+1fd57b0", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.1.0+1fd57b0-cp312-cp312-linux_aarch64.whl" }, marker = "platform_machine != 'x86_64'" },
|
||||
{ name = "deep-ep", version = "1.2.1+29d31c0", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64'" },
|
||||
{ name = "deep-gemm", version = "2.5.0+891d57b", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl" }, marker = "platform_machine != 'x86_64'" },
|
||||
{ name = "deep-gemm", version = "2.5.0+891d57b", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64'" },
|
||||
{ name = "flash-attn", marker = "platform_machine == 'x86_64'" },
|
||||
@@ -4889,7 +4978,8 @@ all = [
|
||||
{ name = "vllm-router", version = "0.1.26", source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_x86_64.whl" }, marker = "platform_machine == 'x86_64'" },
|
||||
]
|
||||
disagg = [
|
||||
{ name = "deep-ep", marker = "platform_machine == 'x86_64'" },
|
||||
{ name = "deep-ep", version = "1.1.0+1fd57b0", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.1.0+1fd57b0-cp312-cp312-linux_aarch64.whl" }, marker = "platform_machine != 'x86_64'" },
|
||||
{ name = "deep-ep", version = "1.2.1+29d31c0", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64'" },
|
||||
{ name = "deep-gemm", version = "2.5.0+891d57b", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl" }, marker = "platform_machine != 'x86_64'" },
|
||||
{ name = "deep-gemm", version = "2.5.0+891d57b", source = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }, marker = "platform_machine == 'x86_64'" },
|
||||
{ name = "nixl" },
|
||||
@@ -4934,6 +5024,7 @@ requires-dist = [
|
||||
{ name = "aiolimiter", specifier = ">=1.2.1" },
|
||||
{ name = "beartype", specifier = ">=0.21.0" },
|
||||
{ name = "datasets", specifier = ">=4.0.0" },
|
||||
{ name = "deep-ep", marker = "platform_machine == 'aarch64' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.1.0+1fd57b0-cp312-cp312-linux_aarch64.whl" },
|
||||
{ name = "deep-ep", marker = "platform_machine == 'x86_64' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" },
|
||||
{ name = "deep-gemm", marker = "platform_machine == 'aarch64' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl" },
|
||||
{ name = "deep-gemm", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'disagg'" },
|
||||
@@ -5482,6 +5573,18 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/0c/34/c110ecc14814be490f258549192579ec02a9f3792587e933b254bcd24aa7/pyqwest-0.6.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:8de70fc18b524e09883b161f79fe21a647302a0c9950ecefeb34a1c1f27269a9", size = 5764873, upload-time = "2026-05-19T03:20:17.61Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pystemmer"
|
||||
version = "3.1.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/78/95/bb893462b08db211b248f6b1aaa0dc07d068dc86f180178bc9072fef86bb/pystemmer-3.1.0.tar.gz", hash = "sha256:083cc3ed90f4c3b0668f8e31c2925cbb4db3bf0fd6d710e0ad0914f33685f7df", size = 302551, upload-time = "2026-05-22T11:23:44.581Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/06/55/78699a2621a472be98bae7fb36bdda610b7d1c8bcd8ff448301230260cf9/pystemmer-3.1.0-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:550bd609aa8dc324033eb1c8d34bfd68649183bbdab871ff534332dcafdc5e5a", size = 752410, upload-time = "2026-05-22T11:14:12.075Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/67/63/e3937ac1df5243e94bde11fc1e57584480de419587f46a4badf5088e7ca6/pystemmer-3.1.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7c6db50dd5e92a2a0acf2b2cec55fddcff3928bf490e26d0c45bc0483272a46c", size = 761062, upload-time = "2026-05-22T11:14:13.78Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e7/63/1f7ef438e19029025fc73fe95480d0dbb2ff323f1aec9c087ad9eb952afb/pystemmer-3.1.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:b86b0b14634788060cab98ad0cae023620aa7b29f9155e8b474632fc80793405", size = 756304, upload-time = "2026-05-22T11:14:15.419Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/ad/5e/816d59b780aa552c87a7e25148005f41be18193482b122d67c6235741b31/pystemmer-3.1.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:6a1289aa31f5f613a31916e7d4e6eaf6b0e6e70a3d494bf08b1d999a0aaf458e", size = 754520, upload-time = "2026-05-22T11:14:16.754Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pytest"
|
||||
version = "9.0.3"
|
||||
@@ -6121,6 +6224,17 @@ requires-dist = [
|
||||
{ name = "verifiers", specifier = ">=0.1.4" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "senior-swe-bench-v1"
|
||||
version = "0.1.0"
|
||||
source = { editable = "deps/research-environments/environments/swe/senior_swe_bench_v1" }
|
||||
dependencies = [
|
||||
{ name = "verifiers", extra = ["harbor"] },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.2.1.dev40" }]
|
||||
|
||||
[[package]]
|
||||
name = "sentence-repeater"
|
||||
version = "0.1.1"
|
||||
|
||||
Reference in New Issue
Block a user