Run this model with HF Jobs
Run HilaryTorn/rl-training-debug-artifacts on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/HilaryTorn/rl-training-debug-artifacts. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/HilaryTorn/rl-training-debug-artifacts on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use HilaryTorn/rl-training-debug-artifacts with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- PEFT
How to use HilaryTorn/rl-training-debug-artifacts with PEFT:
Task type is invalid.
- Notebooks
- Google Colab
- Kaggle
Add files using upload-large-folder tool
Browse filesFiles changed (50)
- ARTIFACT_INDEX.mdAdded+42
- README.mdAdded+311
- SHA256SUMSAdded+115
- code/build_dpo_pairs.pyAdded+644
- code/evaluate_heldout_reward.pyAdded+346
- code/evaluate_livecodebench.pyAdded+331
- code/filter_dpo_pairs.pyAdded+302
- code/merge_adapter_for_eval.pyAdded+106
- code/prompts.pyAdded+68
- code/rewards.pyAdded+360
- code/train_rl.pyAdded+1131
- configs/dpo.yamlAdded+29
- configs/dpo_length_clean_4b.yamlAdded+24
- configs/dpo_length_clean_4b_base125.yamlAdded+28
- configs/dpo_length_clean_9b.yamlAdded+23
- configs/dpo_probe_4b.yamlAdded+35
- configs/dpo_tuned_9b.yamlAdded+26
- configs/grpo.yamlAdded+56
- configs/grpo_probe_4b.yamlAdded+63
- configs/grpo_probe_9b.yamlAdded+35
- configs/grpo_probe_9b_aggressive_mb4.yamlAdded+30
- configs/grpo_probe_9b_mb1.yamlAdded+30
- configs/grpo_probe_9b_mb4.yamlAdded+30
- configs/grpo_probe_9b_mb8.yamlAdded+30
- configs/grpo_probe_9b_r32_mb4.yamlAdded+31
- configs/grpo_random_4b_base_len4k.yamlAdded+34
- configs/grpo_random_4b_base_len4k_largebatch.yamlAdded+31
- configs/grpo_tuned_4b.yamlAdded+32
- configs/grpo_tuned_9b.yamlAdded+32
- configs/ppo.yamlAdded+33
- configs/ppo_tuned_9b.yamlAdded+29
- logs/formal-4b-after-dpo-v4.logAdded
- logs/formal-4b-dpo-v4.logAdded
- logs/formal-9b-sequence-v4.logAdded
- logs/grpo-9b-probe-aggressive-mb4-step16.logAdded+10
- logs/grpo-9b-probe-lr1e6-b005-const-mb4-final.logAdded+11
- logs/grpo-9b-probe-r32a64-mb4-step16.logAdded+10
- metadata/runs/qwen35-4b-base-dpo-cleanprompt-len4k-n1000-step125-s0/run_metadata.jsonAdded+63
- metadata/runs/qwen35-4b-base-dpo-len4k-v1-n709-step125-s0/run_metadata.jsonAdded+63
- metadata/runs/qwen35-4b-base-grpo-random1000-cleanprompt-len4k-lr5e6-b001-mb4-u20-s0-stopped-step39/run_metadata.jsonAdded+62
- metadata/runs/qwen35-4b-dpo-m0-v4-formal-n1000-s0/run_metadata.jsonAdded+76
- metadata/runs/qwen35-4b-dpo-probe-lrup-n1000-s0/run_metadata.jsonAdded+66
- metadata/runs/qwen35-4b-grpo-m0-v4-formal-n1000-s0/reward_log.jsonlAdded+4
- metadata/runs/qwen35-4b-grpo-m0-v4-formal-n1000-s0/run_metadata.jsonAdded+94
- metadata/runs/qwen35-9b-dpo-tuned-v3-noeval-formal-n1000-s0/run_metadata.jsonAdded+74
- metadata/runs/qwen35-9b-grpo-probe-lr1e6-b005-const-mb4-final-n1000-s0/run_metadata.jsonAdded+67
- metadata/runs/qwen35-9b-grpo-probe-r32a64-mb4-step16-n1000-s0/run_metadata.jsonAdded+67
- metadata/runs/qwen35-9b-grpo-tuned-v3-noeval-formal-n1000-s0/run_metadata.jsonAdded+95
- metadata/runs/qwen35-9b-ppo-tuned-v3-noeval-formal-n1000-s0/run_metadata.jsonAdded+64
- reports/rl_training_debug_report.mdAdded+295
123456789101112131415161718192021222324252627282930313233343536373839404142# Artifact index
This repository is a curated debugging handoff. It is not a claim that anyincluded adapter improves the base model.
## Checkpoints
| Directory | Base | Configuration | Why included ||---|---|---|---|| `checkpoints/4b-base-dpo-cleanprompt/step-28` | `Qwen/Qwen3.5-4B` | DPO, LR 1e-6, beta 0.1, LoRA r16/a32 | Early checkpoint with the best held-out partial-reward signal || `checkpoints/4b-base-dpo-cleanprompt/step-125` | `Qwen/Qwen3.5-4B` | Same run | Final checkpoint, showing late degradation || `checkpoints/9b-dpo-length-clean/step-8` | `prism-drift/qwen35-9b-m0-v4` | DPO on 245 length-clean pairs | Early dev improvement || `checkpoints/9b-dpo-length-clean/step-12` | `prism-drift/qwen35-9b-m0-v4` | Same run | Checkpoint associated with held-out reversal || `checkpoints/9b-grpo-probes/default-step-16` | `prism-drift/qwen35-9b-m0-v4` | LR 1e-6, beta 0.05, LoRA r16/a32 | Default probe || `checkpoints/9b-grpo-probes/aggressive-step-16` | `prism-drift/qwen35-9b-m0-v4` | LR 5e-6, beta 0.01, LoRA r16/a32 | LR/beta probe || `checkpoints/9b-grpo-probes/r32a64-step-16` | `prism-drift/qwen35-9b-m0-v4` | LR 1e-6, beta 0.05, LoRA r32/a64 | Higher-capacity probe |
Each checkpoint contains only:
- `adapter_model.safetensors`- `adapter_config.json`- `trainer_state.json`- the generated checkpoint `README.md`
No optimizer, scheduler, RNG, duplicated reference adapter, tokenizer copy, ormerged full-model cache is included.
## Supporting evidence
- `evaluations/`: exact completion-level artifacts and summaries used in the report.- `data/`: final 4B Base DPO pairs, the 4B/9B M0 length-clean subsets, and the final Base sweep/cohort manifests.- `metadata/runs/`: immutable run metadata and available checkpoint-time reward logs.- `logs/`: selected formal-run and hyperparameter-probe logs.- `configs/`: training configurations used during the investigation.- `code/`: the relevant training, filtering, merge, and evaluation utilities as they existed when this package was assembled.- `reports/rl_training_debug_report.md`: the full narrative report.
`SHA256SUMS` covers every uploaded file other than `SHA256SUMS` itself.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311---library_name: peftlicense: apache-2.0tags: - qwen3.5 - reinforcement-learning - dpo - grpo - ppo - debuggingbase_model: - Qwen/Qwen3.5-4B - prism-drift/qwen35-4b-m0-v4 - prism-drift/qwen35-9b-m0-v4---
# RL Training Debugging Report
Date: 2026-08-26 Status: diagnostic; no robust performance improvement established
## Executive summary
We ran a sequence of DPO, GRPO, and PPO experiments on Qwen3.5 4B and 9B,first from project M0 checkpoints and later directly from the originalQwen/Qwen3.5-4B base model. We varied the learning rate, KL/DPO/GRPOcoefficient, LoRA capacity, batch construction, sequence length, trainingduration, and dataset filtering rules. We also rebuilt the 4B DPO data withfresh Base-model rollouts after determining that the original preferencepairs were tied to M0 and contained substantial truncation and length bias.
The training paths are operational: gradients are non-zero, DPO preferenceaccuracy and margins move, GRPO has non-zero reward variance, PPO can completewith non-finite-gradient guards, and merged adapters contain weights that aredifferent from both the base model and one another. However, these optimizationsignals have not translated into a stable improvement on held-out verifierreward or LiveCodeBench. A few early checkpoints improved small developmentsubsets, but the gains either disappeared on a larger held-out split orreversed on an external benchmark. Later checkpoints often performed worse.
The current evidence is therefore consistent with noisy or mismatchedpreference/reward supervision, checkpoint overtraining, and generation-lengthpathologies rather than a trainer that is simply not updating the model.
## Scope
The experiments covered:
- Models: Qwen3.5 4B and 9B.- Starting points: project M0-v4 checkpoints and the original Qwen3.5 Base.- Algorithms: DPO, GRPO, and PPO.- Main training cohort size: 1,000 prompts.- Evaluation data: NVIDIA Nemotron-RL coding dev/held-out splits and a small LiveCodeBench v6 diagnostic subset.- Checkpoint cadence: every 4 optimizer steps for the later formal and debug runs.- Checkpoint policy: adapter-only artifacts; optimizer, scheduler, and RNG states are intentionally excluded from the shared debug package.
## Experiment progression
### 1. Initial M0-v4 runs
The first formal comparison trained DPO, GRPO, and PPO from the 4B and 9BM0-v4 checkpoints on aligned 1,000-prompt cohorts.
Representative initial configuration:
| Method | LR | Coefficient | LoRA | Length | Batch construction ||---|---:|---:|---:|---:|---|| DPO | 1e-6 | beta=0.05 | r=16, alpha=32 | max length 2,048 | micro-batch 1, grad accumulation 8 || GRPO | 1e-6 | beta=0.05 | r=16, alpha=32 | completion 1,024 | 8 prompts x 8 rollouts || PPO | 1e-6 | initial KL=0.05 | r=16, alpha=32 | response 1,024 | micro-batch 1, grad accumulation 8 |
The four checkpoint-time verifier estimates at steps 4, 12, 40, and 125 werenon-monotonic. For example:
- 4B DPO: 0.2156, 0.2128, 0.2406, 0.2156.- 4B GRPO: 0.2208, 0.2401, 0.1993, 0.2186.- 9B GRPO: 0.2554, 0.2346, 0.2376, 0.2387.- 9B PPO: 0.2450, 0.2328, 0.2542, 0.2257.
These are noisy checkpoint estimates rather than a fixed, large held-outevaluation, but they show that training reward did not rise consistently.
PPO additionally encountered non-finite gradients late in the 4B run. Thepath was instrumented with finite-loss/gradient diagnostics and guarded updateskipping. The recovered run completed 125 steps after skipping eightnon-finite updates, but this established plumbing robustness, not a reliableperformance gain.
### 2. Hyperparameter probes
The explored ranges included:
- Learning rate: 5e-7, 1e-6, 5e-6, and 1e-5.- DPO/GRPO beta: 0.01, 0.05, and 0.1.- PPO initial KL coefficient: 0.05 and 0.1.- LoRA capacity: r=16/alpha=32 and r=32/alpha=64.- Micro-batch size: 1, 2, 4, and 8, with gradient accumulation adjusted to retain the intended effective batch.- Schedules: default decay and constant-with-warmup variants.- GRPO completion length: 1,024, 1,536, and 4,096.- DPO maximum sequence length: 2,048, 2,560, and 6,144.- Early stopping/checkpoint selection at steps 4, 8, 12, 16, 28, and 40, versus training through step 125.
The 9B tuned formal configuration lowered the learning rate to 5e-7, increasedDPO/GRPO beta or PPO initial KL to 0.1, and increased the DPO/rollout length to2,560/1,536. Training completed, but it did not establish a robust held-outgain.
For faster GRPO diagnosis, we then compared three 9B step-16 probes:
- Default probe: LR=1e-6, beta=0.05, r=16/alpha=32.- Aggressive probe: LR=5e-6, beta=0.01, r=16/alpha=32.- Higher-capacity probe: LR=1e-6, beta=0.05, r=32/alpha=64.
On one fixed 100-prompt held-out diagnostic, the r=32/alpha=64 checkpoint wasthe strongest of these probes:
| Model | Mean test-case pass fraction | Strict full-pass rate ||---|---:|---:|| 9B M0 | 22.42% | 16% || 9B GRPO r32/alpha64 step 16 | 24.48% | 20% |
The mean improvement was +2.05 percentage points, but its bootstrap intervalfor partial reward crossed zero. The strict-rate interval was positive on thissmall sample, so this checkpoint is useful for debugging but is not sufficientevidence of a general improvement.
A 4B high-LR DPO probe (LR=1e-5, beta=0.01, r=16/alpha=32) substantiallychanged the training objective: the aggregate train loss was 0.563 and latemini-batch preference accuracies reached 0.8-0.9. This showed that a strongeroptimizer setting can fit the preference pairs, but no corresponding robusttask-performance gain was established.
Increasing batch size primarily improved throughput. It did not by itselfresolve the performance problem.
### 3. Removing truncated and length-confounded DPO pairs
The original M0-derived DPO artifacts each contained 1,000 pairs. We removedpairs whose chosen or rejected response was near the generation cap andcontrolled response-length mismatch. This left:
- 4B M0: 433 length-clean pairs.- 9B M0: 245 length-clean pairs.
The 4B M0 length-clean run degraded relative to M0 across most earlycheckpoints. The 9B run produced a promising but unstable early result:
| Evaluation | Baseline | Checkpoint | Partial reward | Strict full pass ||---|---:|---:|---:|---:|| 9B dev, 250 prompts | M0 | step 8 | 35.13% -> 38.51% | 25.2% -> 29.2% || 9B held-out, 500 prompts | M0 | step 12 | 33.49% -> 31.48% | 25.4% -> 22.6% |
Thus, filtering removed a real confounder but did not produce a stablegeneralization gain. The apparent early dev improvement reversed on the largerheld-out evaluation.
### 4. Switching from M0 to the original Base model
The original preference data was generated and selected around M0 behavior.We therefore restarted from Qwen/Qwen3.5-4B and regenerated the DPO pairs.
The first Base rollout reused the old 1,000-prompt cohort:
- 8 samples per prompt.- Temperature 1.0.- Maximum completion length 4,096.- Truncation buffer 24 tokens.- Maximum chosen/rejected token-count difference 512.- Minimum reward margin 0.5.- 709 valid pairs were retained.
After correcting the prompt pipeline, a larger Base-model sweep processed3,081 candidate prompts from the NVIDIA training pool with the same K=8 and4,096-token rollout settings. It produced 1,174 eligible pairs, from which afixed 1,000-pair DPO cohort was frozen.
This final dataset addressed both the M0-conditioned selection issue and theknown training-pair truncation/length confound.
### 5. Final 4B Base DPO run
Final configuration:
| Parameter | Value ||---|---|| Base model | Qwen/Qwen3.5-4B, revision 851bf6e806ef... || Training pairs | 1,000 Base-generated, clean-prompt pairs || Learning rate | 1e-6 || Scheduler | constant with 2 warmup steps || DPO beta | 0.1 || LoRA | r=16, alpha=32, dropout=0 || Effective batch | 8 (micro-batch 2 x accumulation 4) || Maximum sequence length | 6,144 || Maximum prompt length | 1,024 || Training duration | 125 steps || Save interval | 4 steps |
The run completed in 2,527 seconds with aggregate train loss 0.6922. At step125, the logged mini-batch loss was 0.6631 and preference accuracy was 0.625.This is a weak but non-zero optimization signal.
#### NVIDIA held-out diagnostic: 100 fixed prompts
The same 100 prompts were evaluated for Base, step 28, and step 125 with onedeterministic rollout and an 8,192-token completion cap.
| Model | Mean test-case pass fraction | Strict full-pass rate | Non-zero reward | Truncation ||---|---:|---:|---:|---:|| Base | 29.62% | 22% | 43% | 49% || Step 28 | 32.44% | 22% | 48% | 43% || Step 125 | 27.06% | 17% | 46% | 44% |
Step 28 improved partial reward by +2.82 percentage points relative to Base,with paired bootstrap 95% interval [+0.05, +6.30]. It did not increase thenumber of fully solved prompts. Step 125 was worse than Base by 2.55 points inpartial reward and 5 points in strict full-pass rate.
The 43-49% truncation rates remain a major validity problem even at an 8Kcompletion cap. These numbers must therefore be treated as provisional.
#### LiveCodeBench v6 diagnostic: 20 fixed problems
The same first 20 sorted release-v6 problems were run with n=1, temperature 0,a 32,768-token completion budget, and merged adapters.
| Model | pass@1 | Truncation ||---|---:|---:|| Base | 11/20 (55%) | 0% || Step 28 | 8/20 (40%) | 10% || Step 125 | 10/20 (50%) | 0% |
The held-out partial-reward signal at step 28 did not reproduce on this smallexternal benchmark. The sample is too small for a definitive benchmark claim,but it provides no support for selecting step 28 as a generally better codingmodel.
The evaluation loader was also fixed during this stage. Qwen3.5 PEFT adaptersare merged into the language tower and then placed back into the full Qwen3.5container before direct vLLM evaluation. Tensor-level checks confirmed thatBase, step 28, and step 125 used distinct weights.
### 6. Base-model GRPO attempt
A separate 4B Base GRPO experiment randomly sampled 1,000 prompts rather thanusing the old M0-selected subset. Its main configuration was LR=5e-6,beta=0.01, K=8, 20 unique prompts per step, 4,096-token completions, and alarger batch/accumulation arrangement to use the available H200 efficiently.The run was stopped after step 39 when priority shifted to DPO rollout and DPOtraining. It is incomplete and should not be interpreted as a negative GRPOresult.
## Interpretation
The experiments rule out several simple explanations:
- The adapters are not identical to Base; the weights genuinely changed.- The trainers are not completely signal-free; gradients, DPO margins, GRPO reward variance, and preference accuracy move.- The problem is not solved by a single learning-rate, beta, batch-size, or LoRA-rank change.- Removing obviously truncated pairs is necessary but not sufficient.- Training longer is not consistently beneficial; early checkpoints are often better than step 125.
The remaining leading hypotheses are:
1. Preference-pair noise or mismatch between pair selection and the final full-verifier objective.2. A weak/sparse reward signal that is easy to fit locally but does not improve complete solutions.3. Length and termination behavior that remains pathological at evaluation time, even after cleaning the training pairs.4. Overtraining on a 1,000-prompt cohort, especially after the earliest useful updates.5. Evaluation variance from single-rollout measurements and small benchmark subsets.
## Recommended next diagnostics
1. Inspect paired Base/step-28 generations on prompts where partial reward changed, separating real algorithmic improvements from formatting or termination effects.2. Evaluate Base and early checkpoints with multiple rollouts per prompt and a termination policy that eliminates cap-driven censoring.3. Audit the verifier-derived DPO pairs for semantic correctness, not only reward margin and length validity.4. Compare gradient/update scale and KL-to-Base across steps 4-32 to determine whether useful behavior is overwritten later.5. Run a larger LiveCodeBench subset only after the termination behavior is controlled.
## Shared artifact selection
The accompanying Hugging Face debug repository contains representativeadapter-only checkpoints rather than every saved point:
- 4B Base DPO clean-prompt: steps 28 and 125.- 9B length-clean DPO: steps 8 and 12, capturing the early-dev improvement and subsequent held-out reversal.- 9B GRPO step-16 probes: default, aggressive LR/beta, and r32/alpha64.- Run metadata, trainer states, selected reward logs, evaluation summaries, configs, and the relevant training/evaluation utility code.
Optimizer, scheduler, RNG, duplicated reference adapters, tokenizer copies,rollout text dumps, and full merged-model evaluation caches are intentionallyexcluded.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141159dc6f4dc74d32ece5c3c9db628274403e304213e708aef0e8c3af34f4d27bb28 ./ARTIFACT_INDEX.mdf9e54e9bedb2d5eea4f47f1a8b0ca8e535006eaa31063e47c4bca207dfaa2573 ./README.mddccfc00f2be5379db37fb03290674e747ddaa2e8cefe6d225bf832660a4f326b ./checkpoints/4b-base-dpo-cleanprompt/step-125/README.md681ebe8edfa6e8857387be4e02272ba8fd5063100eee8d94f8a93a62f4917e45 ./checkpoints/4b-base-dpo-cleanprompt/step-125/adapter_config.jsonec012ccdf7d664b1604f415f2dc102afc238e82c06075cf4e097fb11c430fea1 ./checkpoints/4b-base-dpo-cleanprompt/step-125/adapter_model.safetensorsb74c79e259bec1e642a6f10a69e4981b5a3722e369fae24358cf27a514b6470e ./checkpoints/4b-base-dpo-cleanprompt/step-125/trainer_state.jsondccfc00f2be5379db37fb03290674e747ddaa2e8cefe6d225bf832660a4f326b ./checkpoints/4b-base-dpo-cleanprompt/step-28/README.md681ebe8edfa6e8857387be4e02272ba8fd5063100eee8d94f8a93a62f4917e45 ./checkpoints/4b-base-dpo-cleanprompt/step-28/adapter_config.json09992ebf298239e7b4d9a46bfb0e200ceaf4c528fd37fa8666a20ff055a5681f ./checkpoints/4b-base-dpo-cleanprompt/step-28/adapter_model.safetensors288204421913a47ed990a1866ecb7a0056ff811dadca4821b77fd1d7d30bff85 ./checkpoints/4b-base-dpo-cleanprompt/step-28/trainer_state.json85df73b79a05c43fb4f4f540c504ee22d621efc952dcf24bfb609a4f8e85268b ./checkpoints/9b-dpo-length-clean/step-12/README.md28485664183f7e63b72c0bf4c3f60e38ba8e672bd244d5b1e67ca6a8ee740d38 ./checkpoints/9b-dpo-length-clean/step-12/adapter_config.json1ec2cc55f581e43c90bba37f83c3e49cbcc5286d16be309efff9f03ffa56c269 ./checkpoints/9b-dpo-length-clean/step-12/adapter_model.safetensorscc92d60a76000054eb01364d1c907e8796c9e878a71274fdc6bf9992007f8584 ./checkpoints/9b-dpo-length-clean/step-12/trainer_state.json85df73b79a05c43fb4f4f540c504ee22d621efc952dcf24bfb609a4f8e85268b ./checkpoints/9b-dpo-length-clean/step-8/README.md28485664183f7e63b72c0bf4c3f60e38ba8e672bd244d5b1e67ca6a8ee740d38 ./checkpoints/9b-dpo-length-clean/step-8/adapter_config.json86c2cd06acd15b9f688cbf217e771cce9b36c0867b6688b0389d953d3dc3a693 ./checkpoints/9b-dpo-length-clean/step-8/adapter_model.safetensors3fd5d84912278d80129c6d11c4b2bdd1f86067dd1437f16bff386a576c79a9f6 ./checkpoints/9b-dpo-length-clean/step-8/trainer_state.jsonaae4dfc7113265e0d7a79af9ea2b358c95501f90e7fae713861c5ad9fa264a38 ./checkpoints/9b-grpo-probes/aggressive-step-16/README.md60a378b208d3cf659019e5d28243062f976f9c87b5644a09cbd5bf1a5d97e378 ./checkpoints/9b-grpo-probes/aggressive-step-16/adapter_config.jsonbddda849befa744f26f6fffccdd56f951b22b16840c645bfb6dded906d40edc7 ./checkpoints/9b-grpo-probes/aggressive-step-16/adapter_model.safetensors9b0c02d55aa428fc93eb5cbdf431a292a2be415542ca8000901557b52dad2718 ./checkpoints/9b-grpo-probes/aggressive-step-16/trainer_state.jsondb38a7f801446332301e0e709ea2d3308c82e995fbd298f60cd1fe9cc72c3a01 ./checkpoints/9b-grpo-probes/default-step-16/README.mdce034191837c415fc9b4a366e209ed14c0435ededee835b0a73e5e2ce9361a69 ./checkpoints/9b-grpo-probes/default-step-16/adapter_config.jsondbd9d0ba0195369653e86a410cdd709cf67f088cbeac5eea0cea9a4cd419ecb7 ./checkpoints/9b-grpo-probes/default-step-16/adapter_model.safetensors89468163137fbb366da4c69317566f98b2d75205db2b5fccf3fb55df602588a5 ./checkpoints/9b-grpo-probes/default-step-16/trainer_state.jsonaae4dfc7113265e0d7a79af9ea2b358c95501f90e7fae713861c5ad9fa264a38 ./checkpoints/9b-grpo-probes/r32a64-step-16/README.md16006eb854e7d8f27ece3f682b4390fe8ff2c318a3fd4908e382bc5f5d920e37 ./checkpoints/9b-grpo-probes/r32a64-step-16/adapter_config.json0d8fc808403c4078c1cee6c1ff4403803da84c47c62ef386cf3dfff938fdb0b8 ./checkpoints/9b-grpo-probes/r32a64-step-16/adapter_model.safetensors4ab1bc9ebccc2fbd5ac302d3330e36806406bf602c4562497c27984bd2f863a7 ./checkpoints/9b-grpo-probes/r32a64-step-16/trainer_state.json3a2e2739406f70e654d0c11ebed864e42419bb223a76cdbcdc45ebf564f835fe ./code/build_dpo_pairs.pye914fdbce905497e416209d37c496febb1fdb3c87b0ec01e562d66c1a299a723 ./code/evaluate_heldout_reward.pyeafdd908346dd4dc19885f70425c414e4ff77af0c843a662c6f0db0c38e4c13b ./code/evaluate_livecodebench.pyb29fbdaa424dcc8d84a26ff765cc5084272b23fbd935b0bca088223b0fbfb444 ./code/filter_dpo_pairs.pyb99a8496390675a57ae086f8c4eeab139bdb2f8a536dfe59d11f88025605cd96 ./code/merge_adapter_for_eval.py3073f06edd253c7ce9f9ba32fa20929b9fe13d160bb74edb1651ce1233416825 ./code/prompts.py2b410e096a2b2d64a8a3dd82670bd84f8e62d1991ce1290c4b7b8a282c9c71ad ./code/rewards.py90d216172da0833d30fd99604c532b11fddaa19b0a81d60ee6f0044aebac6fca ./code/train_rl.pydefcc2ceb7f1a5707de17e38f00922ea0040745419cde93344a3f55b9880a0f6 ./configs/dpo.yamlb05e566754ff6786cf6e75b80262f6e6fe39b0ebe4e14ba0a9dd04ca4606161c ./configs/dpo_length_clean_4b.yaml147737cfd13b01a5bbdf7fbc2159ced3ac0b0a6da6cccd93e954ec9b2bf3bdaa ./configs/dpo_length_clean_4b_base125.yamlb6233bb0c231bbac627b6cd7f847699bc768f4a27f37124f759b83b46bdb7b3f ./configs/dpo_length_clean_9b.yaml7a271dfc19ffee5f434e7a9c8e0b4fbc447922c1e0ae2b3fa123efbf4b8a6054 ./configs/dpo_probe_4b.yaml637e851ef90a156098da08364b6e5b7b354909bd8d676e0a1ac5ae95eb24fc86 ./configs/dpo_tuned_9b.yaml67d77a2d61c5d126d698ef927bd60cecf6c2b691da158b9734b81cf5ac182bc5 ./configs/grpo.yamld3fd0a6ad0a1d4a7a7fee2e87888ab55bf5ef713b311f9bfdb88d27d020fce86 ./configs/grpo_probe_4b.yaml77ecedb2c4e709ad17ceaa2f46f9158b783299600fc2b20dee4de01c0bcc167a ./configs/grpo_probe_9b.yaml27b9231a325918ccc85d475f8b0ea8e3004fa3ba890f39be6628623a54d397f4 ./configs/grpo_probe_9b_aggressive_mb4.yamlc98a3f0aa75d1187f1a68338341535784e55b7bcb66365703cb367cb61eb1278 ./configs/grpo_probe_9b_mb1.yaml82bb0d6b9c5ac48280bff9f128f8c63a57675e4b0549f6e5d0fda8a57b38c780 ./configs/grpo_probe_9b_mb4.yaml50d99ca68dcb1401f4a3add6f3639a24839aa2b072122241be7f625b3c1a4aaa ./configs/grpo_probe_9b_mb8.yaml922f8bfdc5a4810c251e4a253696ef6d3370fc71e97030fc64dd4bb7ba0f80d2 ./configs/grpo_probe_9b_r32_mb4.yamlf3beee57ae0f5519dc320ff71d3427625a5a3d5b4928cac796e62b2b9b0cfceb ./configs/grpo_random_4b_base_len4k.yaml15839dbb3733e965ce718b3bf6d45750068f186c2f69135a2920c75f5bb8895a ./configs/grpo_random_4b_base_len4k_largebatch.yamlc849278379db659a0154e4b4d3935a50289e079bb78829fc457b2b0a3f32c018 ./configs/grpo_tuned_4b.yamlfe950e333b91ad812a98cb824e1ca2bde5fbf106a17ac7fd8e5382a059ea2e35 ./configs/grpo_tuned_9b.yaml0a59500a0045f71e935e77c3063d5c1e8aa4ef2bbfba106b2ca2fba32dafd8e2 ./configs/ppo.yaml2efb9e58ee735631ac379ab8ff787d7a41d5a6b0876d11850ae967b326ee00c7 ./configs/ppo_tuned_9b.yaml94386ff193c3d7b72b66dbce85c398c57fcd3bab4d77f2c5a5aedab79708bd16 ./data/4b-base-cleanprompt/cohort-manifest.jsondd10034c79383f50747d853673250d55d9f0afedc61cfba969f6e8d72ff23455 ./data/4b-base-cleanprompt/dpo-n1000.jsonl262bc69746e0c3959069b4875051556deb3929ae8df6608b74afb8446743d77a ./data/4b-base-cleanprompt/sweep-manifest.jsonf5cc9b8ba04965fa9a26fc727991e853d97662a441b50538d41b356e1df0f552 ./data/m0-length-clean/4b-n433.jsonlad73d28c14482d8345601dcb21cb0999c95910d57a063c4d7207995f2012a806 ./data/m0-length-clean/9b-n245.jsonle728b0ee2e1dd1c7bf4b3f3084b0649cd6fabcdaa2e1aa859259d8f690de12aa ./evaluations/4b-base-dpo/heldout100-len8k/completions.jsonl18452750601882e286f183fe53df55c6572c05a9fbd34615b40e065963458d4e ./evaluations/4b-base-dpo/heldout100-len8k/summary.jsonfe4715b777ab7f6806cf0a984aca6cf56fed6923dc5b14f93744d46d26bbd16c ./evaluations/4b-base-dpo/livecodebench20/base/generations.jsonl83e44f4e2b3f3cb9a8dd0baca1bf924ec13c483ace514d0163e5a1c8f7e9f9bd ./evaluations/4b-base-dpo/livecodebench20/base/manifest.jsonebf45ee7a7e0d84c0da6ca0118a1f7a74f814a4ec006f19df8d14b087b5a48c3 ./evaluations/4b-base-dpo/livecodebench20/base/summary.json9df5acf5e0294aa3be23093f4fab9c083ac2970974e3a458375b47b2517c6c10 ./evaluations/4b-base-dpo/livecodebench20/step125/generations.jsonlfdf3e609b4962e95ddabcb20d8faf291476262d306a14f08bab6a69623f5a2e7 ./evaluations/4b-base-dpo/livecodebench20/step125/manifest.json229e862406990d8fa46fe960560940ec62347d73912af4e0b8f4199a87fc80e4 ./evaluations/4b-base-dpo/livecodebench20/step125/summary.jsonf6bf3cbb535a79fb5ca5c5603595d7e8f81853aadb2bf1c8be57a96acccc52cf ./evaluations/4b-base-dpo/livecodebench20/step28/generations.jsonl6b04402926e14d79c63f5b6691be0ce7085fec3dbe29bf1ae91248c703e535fa ./evaluations/4b-base-dpo/livecodebench20/step28/manifest.jsonb275dca87b84c7e85d5d53b9f33b1a2146d4432a9566c981fcdc63824d1ec2a7 ./evaluations/4b-base-dpo/livecodebench20/step28/summary.jsonf3a079dfd7b95d2d751146b4cb2d5da966b79ceafe2b940e3ec6e51612b11465 ./evaluations/9b-dpo-length-clean/step12-heldout500/completions.jsonl2fc143dcb00804de42881040f8266f5c9dbe824fd82e1ddbb9571006ea303edb ./evaluations/9b-dpo-length-clean/step12-heldout500/summary.json15d0cd0a3d025d0516ae6f5973751c64bb46f77f14ccb72b039c33c23cacc456 ./evaluations/9b-dpo-length-clean/step8-dev250/completions.jsonlbf54a6d3ad84b09494d69250f27716657fbc6b052b8d34f796bb8660ee3e1242 ./evaluations/9b-dpo-length-clean/step8-dev250/summary.jsonf15086fea843f7b63b6f26125481e38cc9163db56c55fa2585b6374b1e81ae63 ./evaluations/9b-grpo-probes/completions.jsonl43b46435f0a94bd4548bda3b3bbd18bb048edc25fc9b9ac299ae27054b754b58 ./evaluations/9b-grpo-probes/summary.json6693e2ba239a9afc03a4190e592cf069bcf30761bfdc36a339f09cf0e6b59dd5 ./evaluations/9b-grpo-probes/summary_aggressive.json28772b4eddea18be8c0ea83b2943f3ab60d1b7502b2027f9f89d2b2da8688cbb ./evaluations/9b-grpo-probes/summary_r32.jsone7c935ffd74227183dbc085b1a1198ae6b1985921ba64be3821d9e6687330be1 ./logs/formal-4b-after-dpo-v4.log9f8ef6205098795921fb750214bdb0a65b5254ea50cfe9b8ddc6d757d15342e6 ./logs/formal-4b-dpo-v4.loge38704d8cc78c81f2f94d7c8aad3c14d2cef523404c8d142dfa4598b9dd8f223 ./logs/formal-9b-sequence-v4.log646a9bb4df5e36a9fabc84d58eba8913b19b91c356f3ec00e86543489267efdd ./logs/grpo-9b-probe-aggressive-mb4-step16.log6e91da8dec237518dcd221bf3619c8a0fb09fb2703c9e6673598368706715ddf ./logs/grpo-9b-probe-lr1e6-b005-const-mb4-final.log60c7bfae18edac87246fb9f18a92390e1de72479493eaf07bf7835ed11a3133e ./logs/grpo-9b-probe-r32a64-mb4-step16.log864784ecb09c898df2fd0e79b725376ed4d3487a957dd98cca38842ce162db25 ./metadata/runs/qwen35-4b-base-dpo-cleanprompt-len4k-n1000-step125-s0/run_metadata.jsonca103c4a9b321d683c9d85689baa9714d6f1d81b40815ac3efe9d289f69e6418 ./metadata/runs/qwen35-4b-base-dpo-len4k-v1-n709-step125-s0/run_metadata.json05069d971f5da58f2207ca8213021c439f40b0d549c943e1339e41052acc75d2 ./metadata/runs/qwen35-4b-base-dpo-length-clean-v1-n433-step125-s0/run_metadata.jsonfa74f68a983cff84e51c0f1cf06b475db4334d044833d1a3fb915b9f344dcc4b ./metadata/runs/qwen35-4b-base-grpo-random1000-cleanprompt-len4k-lr5e6-b001-mb4-u20-s0-stopped-step39/run_metadata.json355a9dcda1ed8653f0950c7d4b625af27978a08e90c11086a7369b9c1e8af6ef ./metadata/runs/qwen35-4b-dpo-length-clean-v1-n433-step16-s0/run_metadata.json3f7440f1455b890604b3ca297877e6e2714334d813dbb7daab1893161e2b496e ./metadata/runs/qwen35-4b-dpo-m0-v4-formal-n1000-s0/reward_log.jsonlb1b36d25b38256d75946af254406d61add50ff138d2d11898f9b7c9658f6fe54 ./metadata/runs/qwen35-4b-dpo-m0-v4-formal-n1000-s0/run_metadata.json254dc01f4875cf1ccf68d563bd33d16e7b103b7d437ff6ffcd0ce19f768c5109 ./metadata/runs/qwen35-4b-dpo-probe-lrup-n1000-s0/run_metadata.jsone98f6fb6b662d3f4d7c974a3520d80cf8e8cf76c6222512744f44a1abe404525 ./metadata/runs/qwen35-4b-grpo-m0-v4-formal-n1000-s0/reward_log.jsonl5518aa5c64fa83891ba88f6aebbc9586451d5fbff89e6868b95ab4151878a930 ./metadata/runs/qwen35-4b-grpo-m0-v4-formal-n1000-s0/run_metadata.json41b8aabaf4a9ce7979ed96f74be78f6437754e2da09491868af4ec387f74b9f2 ./metadata/runs/qwen35-4b-grpo-probe-lrup-n1000-s0/run_metadata.json1e788361a37829b5c39ea633367ea5d5aa030d89b0f550db9b24c4cd7d5a17c9 ./metadata/runs/qwen35-4b-ppo-m0-v4-formal-n1000-s0/reward_log.jsonl6666a189b7677b9011e504b923bb9479d9fdaf347813a814ba541cc30042b951 ./metadata/runs/qwen35-4b-ppo-m0-v4-formal-n1000-s0/run_metadata.json466a1c11216378c0ef85e4b3d2539a777191f8ac15989ed42cde75cdd378ccd2 ./metadata/runs/qwen35-9b-dpo-length-clean-v1-n245-s0/run_metadata.json8043e11fec193ba5643c0a2583433199659e50a3bc61fcec447f95579fd2d4da ./metadata/runs/qwen35-9b-dpo-m0-v4-formal-n1000-s0/reward_log.jsonle49a9fe34f2e06a810ddefd516f3bee84ab73599a3a7c925b97138eb1b940d73 ./metadata/runs/qwen35-9b-dpo-m0-v4-formal-n1000-s0/run_metadata.json5804897f63adbfda8fd5bdafce5d593bff2bfe1906491c8b9c02f14580d64967 ./metadata/runs/qwen35-9b-dpo-tuned-v3-noeval-formal-n1000-s0/run_metadata.json727f0ac77220abc483d3564523c1d0aefe0d1e784bfd6ae6f08ef76e373078b2 ./metadata/runs/qwen35-9b-grpo-m0-v4-formal-n1000-s0/reward_log.jsonl0899a5c64183705440b71a020de8e28272b6f8b25194c60db08c2b7a180479a5 ./metadata/runs/qwen35-9b-grpo-m0-v4-formal-n1000-s0/run_metadata.json2d3454211eb00d6df83386a48edcb9037c507ee21e2a10b1da80afe35940d7ef ./metadata/runs/qwen35-9b-grpo-probe-aggressive-mb4-step16-n1000-s0/run_metadata.json0649c0e845a6e12700f257577c6d4776de4a217552c0a303e700abfb87a70342 ./metadata/runs/qwen35-9b-grpo-probe-lr1e6-b005-const-mb4-final-n1000-s0/run_metadata.json8f450f947d67443b4ca6639c54ecc5e284f7fbea32b9d5e2e77cbe1f867483c6 ./metadata/runs/qwen35-9b-grpo-probe-r32a64-mb4-step16-n1000-s0/run_metadata.jsonbe92fe9114ef4824095f68d8c9308d4ce61969fc0e29fd30390e3dfc88409655 ./metadata/runs/qwen35-9b-grpo-tuned-v3-noeval-formal-n1000-s0/run_metadata.json0f348bb053a424e7b22edf120d7bde805d97ff68bcdb40e8b0795df4270ccc8c ./metadata/runs/qwen35-9b-ppo-m0-v4-formal-n1000-s0/reward_log.jsonl3be5c87a60cf12a2e03966f31d0aff06315ff96b54b2655aa07c120dc7ce418a ./metadata/runs/qwen35-9b-ppo-m0-v4-formal-n1000-s0/run_metadata.jsonfcab84e2346fe1cdac452e603c58538a89f67833e9ada9d83430344a6a870bb0 ./metadata/runs/qwen35-9b-ppo-tuned-v3-noeval-formal-n1000-s0/run_metadata.json60f8e34294e2010ff14755a23ace8deef1317fc43c2ee46104e398d1695cb942 ./reports/rl_training_debug_report.md123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644#!/usr/bin/env python3"""Build DPO preference pairs from the SAME problem pool and verifier as PPO/GRPO.
DPO can't consume the reward directly, so we manufacture preferences from it:sample K completions per prompt from the base (or SFT) model, score each with theI/O verifier, pair best vs worst, and keep only pairs with``pass_rate(chosen) - pass_rate(rejected) >= --margin`` (default 0.5). Thepreference signal thus comes from the same verifier as the online arms — no humanpreference data, one shared objective across PPO/GRPO/DPO.
Input: a canonical coding_task_v1 prompts JSONL ({prompt, verifier}).Output: a DPO JSONL ({prompt, chosen, rejected, chosen_reward, rejected_reward}).Optionally also writes per-prompt score summaries for learnable-band filtering.
Sampling has three backends (grading is always local — it executes code): - local transformers (default, --backend hf): loads --model on this box. - in-process vLLM (--backend vllm): ~10x faster sweep in a dedicated vLLM env. - vLLM endpoint (--endpoint): samples via the OpenAI-compatible /completions API, so the full candidate-pool run can hit an existing serving endpoint instead of loading the model here. This keeps generation off paid AWS GPU per the Inference Rule (docs/cost.md).
# local smoke python rl_training/build_dpo_pairs.py \ --model Qwen/Qwen3.5-0.8B --device cpu --limit 10 \ --prompts data/rl/nemotron_train_1000.jsonl \ --out data/rl/nemotron_dpo_pairs.jsonl --K 8 --margin 0.5
# full run against a vLLM endpoint python rl_training/build_dpo_pairs.py \ --model Qwen/Qwen3.5-0.8B \ --endpoint http://localhost:8000/v1 \ --api_key_file api_keys/api_key_vllm_endpoint.txt \ --prompts data/rl/nemotron_train_1000.jsonl \ --out data/rl/nemotron_dpo_pairs.jsonl --K 8 --margin 0.5
SECURITY: runs model-generated code via the verifier — see rl_training/rewards.py."""
from __future__ import annotations
import argparseimport fcntlimport hashlibimport jsonimport osfrom pathlib import Pathimport shutilimport sysimport time
ROOT = Path(__file__).resolve().parent.parentif str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT))
def _sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest()
def _atomic_write_jsonl(path: Path, rows: list[dict]) -> None: """Replace a JSONL file atomically after flushing it to disk.""" path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_name(f".{path.name}.tmp-{os.getpid()}") try: with tmp.open("w") as handle: for row in rows: handle.write(json.dumps(row, ensure_ascii=True) + "\n") handle.flush() os.fsync(handle.fileno()) os.replace(tmp, path) finally: tmp.unlink(missing_ok=True)
def _atomic_write_json(path: Path, payload: dict) -> None: path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_name(f".{path.name}.tmp-{os.getpid()}") try: with tmp.open("w") as handle: json.dump(payload, handle, indent=2, ensure_ascii=True) handle.write("\n") handle.flush() os.fsync(handle.fileno()) os.replace(tmp, path) finally: tmp.unlink(missing_ok=True)
def _read_resume_jsonl(path: Path) -> list[dict]: """Read JSONL, recovering only a truncated final line from an interrupted write.""" if not path.exists(): return [] lines = path.read_text().splitlines() nonblank = [index for index, line in enumerate(lines) if line.strip()] last_nonblank = nonblank[-1] if nonblank else None rows: list[dict] = [] for index, line in enumerate(lines): if not line.strip(): continue try: rows.append(json.loads(line)) except json.JSONDecodeError as exc: if index != last_nonblank: raise SystemExit(f"{path}:{index + 1}: invalid JSON inside file: {exc}") from exc backup = path.with_name(f"{path.name}.resume-backup-{int(time.time())}") shutil.copy2(path, backup) _atomic_write_jsonl(path, rows) print(f"[dpo] recovered truncated final line in {path}; backup -> {backup}") break return rows
def _record_id(row: dict, *, source: Path, line_no: int) -> str: rid = row.get("record_id") if not isinstance(rid, str) or not rid: raise SystemExit(f"{source}:{line_no}: missing record_id") return rid
def _score_requires_pair(score_row: dict, margin: float) -> bool: pair_eligible = score_row.get("pair_eligible") if isinstance(pair_eligible, bool): return pair_eligible scores = score_row.get("scores") if not isinstance(scores, list) or not scores: return False return max(float(value) for value in scores) - min(float(value) for value in scores) >= margin
def _reconcile_resume_outputs( scores_path: Path, out_path: Path, score_rows: list[dict], pair_rows: list[dict], margin: float,) -> tuple[list[dict], list[dict]]: """Repair cross-file tails left by interruption before deciding what to skip.
A score row is the completion marker. If its expected pair is absent, drop that score so the prompt is resampled. Conversely, a pair without a score is an uncommitted orphan and is removed. """ score_by_id: dict[str, dict] = {} for line_no, row in enumerate(score_rows, 1): rid = _record_id(row, source=scores_path, line_no=line_no) if rid in score_by_id: raise SystemExit(f"{scores_path}:{line_no}: duplicate record_id {rid!r}") score_by_id[rid] = row
pair_by_id: dict[str, dict] = {} for line_no, row in enumerate(pair_rows, 1): rid = _record_id(row, source=out_path, line_no=line_no) if rid in pair_by_id: raise SystemExit(f"{out_path}:{line_no}: duplicate record_id {rid!r}") pair_by_id[rid] = row
repaired_scores = [ row for rid, row in score_by_id.items() if not _score_requires_pair(row, margin) or rid in pair_by_id ] committed_score_ids = {row["record_id"] for row in repaired_scores} repaired_pairs = [ row for rid, row in pair_by_id.items() if rid in committed_score_ids and _score_requires_pair(score_by_id[rid], margin) ] removed_scores = len(score_rows) - len(repaired_scores) removed_pairs = len(pair_rows) - len(repaired_pairs) if removed_scores or removed_pairs: _atomic_write_jsonl(scores_path, repaired_scores) _atomic_write_jsonl(out_path, repaired_pairs) print( f"[dpo] repaired interrupted transaction tail: " f"resample_scores={removed_scores}, orphan_pairs={removed_pairs}" ) return repaired_scores, repaired_pairs
def _acquire_sweep_lock(path: Path): path.parent.mkdir(parents=True, exist_ok=True) handle = path.open("a+") try: fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError as exc: handle.close() raise SystemExit(f"Another process is already writing this sweep: {path}") from exc handle.write(f"pid={os.getpid()}\n") handle.flush() return handle
def _durable_jsonl_write(handle, row: dict) -> None: handle.write(json.dumps(row, ensure_ascii=True) + "\n") handle.flush() os.fsync(handle.fileno())
# Sampling MUST match TRL's GRPO rollout distribution (temperature-only,# top_p=1, no top_k) so pair construction is on-policy for the online arms.# All backends override the model's own generation_config defaults, which for# Qwen chat models would otherwise silently apply top_p/top_k.
def _hf_completions(rows, args, tokenizer): """Yield (row, rendered_prompt, completions) via Transformers generate.""" import torch from transformers import AutoModelForCausalLM
from rl_training.prompts import render_coding_prompt
dtype = torch.bfloat16 if torch.cuda.is_available() and torch.cuda.is_bf16_supported() else torch.float32 model = AutoModelForCausalLM.from_pretrained( args.model, revision=args.model_revision, trust_remote_code=True, dtype=dtype, ) if args.device == "auto": device = "cuda" if torch.cuda.is_available() else "cpu" else: device = args.device model.to(device) model.eval() print(f"[dpo] backend=hf device: {device}")
for row in rows: formatted_prompt = render_coding_prompt(tokenizer, row["prompt"]) enc = tokenizer(formatted_prompt, return_tensors="pt").to(model.device) with torch.no_grad(): out = model.generate( **enc, do_sample=True, temperature=args.temperature, top_p=1.0, top_k=0, max_new_tokens=args.max_new_tokens, num_return_sequences=args.K, pad_token_id=tokenizer.eos_token_id, ) completions = [ tokenizer.decode(seq[enc["input_ids"].shape[1]:], skip_special_tokens=True) for seq in out ] yield row, formatted_prompt, completions
def _vllm_completions(rows, args, tokenizer, chunk_size: int = 64): """Yield (row, rendered_prompt, completions) via an in-process vLLM engine.
Runs in a separate environment from training (vLLM pins its own torch/CUDA; see rl_training/requirements-training.txt). Chunked so verifier scoring and progress interleave with generation instead of waiting for the full sweep. """ from vllm import LLM, SamplingParams
from rl_training.prompts import render_coding_prompt
llm = LLM( model=args.model, revision=args.model_revision, trust_remote_code=True, max_model_len=args.max_model_len, gpu_memory_utilization=args.gpu_memory_utilization, ) sampling = SamplingParams( n=args.K, temperature=args.temperature, top_p=1.0, top_k=-1, max_tokens=args.max_new_tokens, ) prompt_budget = args.max_model_len - args.max_new_tokens
def render(row): # Prompts should already be length-filtered at prep time; left-truncate # any stray overlong one (keeps the assistant header), matching the # trainer's truncation_side="left" fallback. prompt = render_coding_prompt(tokenizer, row["prompt"]) ids = tokenizer(prompt, add_special_tokens=False).input_ids if len(ids) > prompt_budget: prompt = tokenizer.decode(ids[-prompt_budget:]) return prompt
print(f"[dpo] backend=vllm max_model_len={args.max_model_len} " f"gpu_memory_utilization={args.gpu_memory_utilization}") for start in range(0, len(rows), chunk_size): chunk = rows[start : start + chunk_size] prompts = [render(row) for row in chunk] outputs = llm.generate(prompts, sampling, use_tqdm=False) for row, formatted_prompt, output in zip(chunk, prompts, outputs): yield row, formatted_prompt, [candidate.text for candidate in output.outputs]
def _endpoint_completions(rows, args, tokenizer): """Yield (row, rendered_prompt, completions) via an OpenAI-compatible vLLM /completions API.""" import requests
from rl_training.prompts import render_coding_prompt
base = args.endpoint.rstrip("/") url = f"{base}/completions" api_key = None if args.api_key_file: api_key = Path(args.api_key_file).read_text().strip() headers = {"Content-Type": "application/json"} if api_key: headers["Authorization"] = f"Bearer {api_key}" served_model = args.served_model_name or args.model print(f"[dpo] backend=endpoint url={url} model={served_model}")
for row in rows: formatted_prompt = render_coding_prompt(tokenizer, row["prompt"]) body = { "model": served_model, "prompt": formatted_prompt, "n": args.K, "max_tokens": args.max_new_tokens, "temperature": args.temperature, "top_p": 1.0, } resp = requests.post(url, headers=headers, json=body, timeout=args.endpoint_timeout) resp.raise_for_status() choices = resp.json().get("choices", []) completions = [choice.get("text", "") for choice in choices] yield row, formatted_prompt, completions
def main() -> None: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--model", required=True, help="Base/SFT model to sample candidates from (or served model id for --endpoint)") parser.add_argument("--model_revision", default=None, help="Pinned HF model commit/revision for local backends") parser.add_argument("--prompts", required=True, help="Prepared coding_task_v1 prompts JSONL") parser.add_argument("--out", required=True) parser.add_argument("--scores_out", default=None, help="Optional per-prompt score summary JSONL") parser.add_argument("--manifest_out", default=None, help="Optional sweep provenance manifest JSON") parser.add_argument("--backend", default="hf", choices=["hf", "vllm"], help="hf = Transformers generate (training env); vllm = in-process vLLM engine (separate env). Ignored when --endpoint is set.") parser.add_argument("--K", type=int, default=8, help="Candidates sampled per prompt") parser.add_argument("--margin", type=float, default=0.5, help="Min pass-rate gap to keep a pair") parser.add_argument("--max_new_tokens", type=int, default=1024) parser.add_argument( "--truncation_buffer_tokens", type=int, default=24, help="Treat completions within this many tokens of max_new_tokens as truncated", ) parser.add_argument( "--max_pair_token_delta", type=int, default=256, help="Maximum chosen/rejected completion-token difference", ) parser.add_argument("--temperature", type=float, default=1.0) # Shared reward budget: MUST match GRPO's training reward (rl_training/rewards.py # constants) so DPO pairs and the PPO reward model share GRPO's objective. parser.add_argument( "--max_tests", type=int, default=None, help="Tests per completion for scoring; defaults to the shared TRAIN_REWARD_MAX_TESTS. Must match GRPO.", ) parser.add_argument("--reward_timeout", type=float, default=None, help="Per-test timeout; defaults to the shared REWARD_TIMEOUT. Must match GRPO.") parser.add_argument("--device", default="auto", help="hf backend: 'auto', 'cpu', 'cuda', or a torch device") parser.add_argument("--gpu_memory_utilization", type=float, default=0.45, help="vllm backend: fraction of GPU memory to claim (GPU may be shared)") parser.add_argument("--max_model_len", type=int, default=4096, help="vllm backend: context window") parser.add_argument("--endpoint", default=None, help="OpenAI-compatible vLLM base URL (e.g. http://host:8000/v1). If set, sample via HTTP instead of --backend.") parser.add_argument("--served_model_name", default=None, help="Model id the endpoint serves, if different from --model") parser.add_argument("--api_key_file", default=None, help="File with the endpoint bearer token") parser.add_argument("--endpoint_timeout", type=float, default=300.0, help="Per-request HTTP timeout for --endpoint (seconds)") parser.add_argument("--limit", type=int, default=None, help="Cap number of prompts (debug)") parser.add_argument( "--resume", action="store_true", help="Append safely, skipping record IDs already present in --scores_out", ) args = parser.parse_args()
from tqdm.auto import tqdm from transformers import AutoTokenizer
from rl_training.data.schema import DPOPreferenceRecord, read_coding_jsonl from rl_training.data.filter_dpo_pairs import select_length_controlled_pair from rl_training.rewards import ( REWARD_TIMEOUT, TRAIN_REWARD_MAX_TESTS, score_completions, )
# Default to the shared reward budget so DPO pairs are graded identically to # GRPO's training reward without the caller having to remember the numbers. max_tests = args.max_tests if args.max_tests is not None else TRAIN_REWARD_MAX_TESTS reward_timeout = args.reward_timeout if args.reward_timeout is not None else REWARD_TIMEOUT
rows = read_coding_jsonl(args.prompts) if args.limit: rows = rows[: args.limit] target_rows = list(rows) if args.endpoint: sampler_kind = "endpoint" elif args.backend == "vllm": sampler_kind = "vllm" else: sampler_kind = "local"
# Recorded in every score/pair row so local-smoke, vllm, and endpoint runs are # auditable as the same procedure (differing only in where sampling ran). gen_meta = { "generator_model": args.model, "generator_model_revision": args.model_revision, "source_prompts_sha256": _sha256(Path(args.prompts).resolve()), "sampler": sampler_kind, "backend": args.backend, "endpoint": args.endpoint, "sample_k": args.K, "temperature": args.temperature, "max_new_tokens": args.max_new_tokens, "reward_max_tests": max_tests, "reward_timeout": reward_timeout, "pair_margin": args.margin, "truncation_buffer_tokens": args.truncation_buffer_tokens, "max_pair_token_delta": args.max_pair_token_delta, "served_model_name": args.served_model_name, }
out_path = Path(args.out) out_path.parent.mkdir(parents=True, exist_ok=True) scores_path = Path(args.scores_out) if args.scores_out else None if args.resume and scores_path is None: raise SystemExit("--resume requires --scores_out so completed record IDs are auditable") lock_base = scores_path or out_path lock_path = lock_base.with_suffix(lock_base.suffix + ".lock") lock_handle = _acquire_sweep_lock(lock_path)
existing_score_rows: list[dict] = [] existing_score_ids: set[str] = set() kept = 0 solved_any = 0 if args.resume and scores_path and scores_path.exists(): if not out_path.exists(): raise SystemExit( f"Cannot resume: {scores_path} exists but pair file {out_path} is missing" ) existing_score_rows = _read_resume_jsonl(scores_path) existing_pair_rows = _read_resume_jsonl(out_path) required_meta = tuple(gen_meta) for line_no, score_row in enumerate(existing_score_rows, 1): _record_id(score_row, source=scores_path, line_no=line_no) mismatches = [ key for key in required_meta if score_row.get(key) != gen_meta[key] ] if mismatches: raise SystemExit( f"Cannot resume {scores_path}: row {line_no} differs on {mismatches}. " "Use a new model sweep directory for different generation settings." ) existing_score_rows, existing_pair_rows = _reconcile_resume_outputs( scores_path, out_path, existing_score_rows, existing_pair_rows, args.margin ) for line_no, score_row in enumerate(existing_score_rows, 1): rid = score_row.get("record_id") if not isinstance(rid, str) or not rid: raise SystemExit(f"{scores_path}:{line_no}: missing record_id") if rid in existing_score_ids: raise SystemExit(f"{scores_path}:{line_no}: duplicate record_id {rid!r}") mismatches = [ key for key in required_meta if score_row.get(key) != gen_meta[key] ] if mismatches: raise SystemExit( f"Cannot resume {scores_path}: row {line_no} differs on {mismatches}. " "Use a new model sweep directory for different generation settings." ) existing_score_ids.add(rid) solved_any += int(float(score_row.get("max_score", 0.0)) > 0) kept = len(existing_pair_rows) rows = [ row for row in target_rows if (row.get("record_id") or row.get("hash_id")) not in existing_score_ids ] print(f"[dpo] resume: {len(existing_score_ids)} completed, {len(rows)} remaining") elif args.resume: if out_path.exists(): raise SystemExit( f"Cannot resume: pair file {out_path} exists but score file {scores_path} is missing" ) rows = target_rows
if not args.resume and (out_path.exists() or (scores_path and scores_path.exists())): raise SystemExit("Output files already exist; use --resume or choose a new sweep directory")
tokenizer = None completion_stream = iter(()) if rows: tokenizer = AutoTokenizer.from_pretrained( args.model, revision=args.model_revision, trust_remote_code=True, ) if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token if args.endpoint: completion_stream = _endpoint_completions(rows, args, tokenizer) elif args.backend == "vllm": completion_stream = _vllm_completions(rows, args, tokenizer) else: completion_stream = _hf_completions(rows, args, tokenizer)
scores_fout = None if scores_path: scores_path.parent.mkdir(parents=True, exist_ok=True) scores_fout = scores_path.open("a" if args.resume else "w") # prompts where at least one sample passed something progress = tqdm(total=len(rows), desc="[dpo] sampling+scoring", unit="prompt") processed_rows = 0 try: with out_path.open("a" if args.resume else "w") as fout: for i, (row, formatted_prompt, completions) in enumerate(completion_stream): # Prompts come rendered through the chat template, identical to # GRPO training, so scores/pairs transfer across arms. if len(completions) != args.K: raise RuntimeError( f"Sampler returned {len(completions)} completions for " f"{row.get('record_id')!r}; expected K={args.K}" ) scored = score_completions( completions, row["verifier"], timeout=reward_timeout, max_tests=max_tests ) scores = [score for score, _ in scored] score_row = { "schema": "prompt_score_v1", "record_id": row.get("record_id") or row.get("hash_id") or f"row-{i}", "dataset_id": row.get("dataset_id", "unknown"), **gen_meta, "scores": scores, "min_score": min(scores) if scores else 0.0, "max_score": max(scores) if scores else 0.0, "mean_score": sum(scores) / len(scores) if scores else 0.0, } pair, length_audit = select_length_controlled_pair( formatted_prompt, scored, tokenizer, margin=args.margin, max_new_tokens=args.max_new_tokens, truncation_buffer_tokens=args.truncation_buffer_tokens, max_pair_token_delta=args.max_pair_token_delta, ) score_row.update(length_audit) if pair is not None: record = DPOPreferenceRecord( record_id=row.get("record_id") or row.get("hash_id") or f"row-{i}", dataset_id=row.get("dataset_id", "unknown"), prompt=pair["prompt"], chosen=pair["chosen"], rejected=pair["rejected"], chosen_reward=pair["chosen_reward"], rejected_reward=pair["rejected_reward"], metadata={ "source_record_id": row.get("record_id") or row.get("hash_id"), "margin": args.margin, "length_filter": { "schema": "dpo_length_filter_v1", "chosen_tokens": length_audit["selected_chosen_tokens"], "rejected_tokens": length_audit["selected_rejected_tokens"], "token_delta": length_audit["selected_token_delta"], "truncation_threshold_tokens": length_audit[ "truncation_threshold_tokens" ], "truncation_buffer_tokens": args.truncation_buffer_tokens, "max_pair_token_delta": args.max_pair_token_delta, }, **gen_meta, }, ) # Pair is prepared first; the durable score row below is the # transaction's completion marker used by resume. _durable_jsonl_write(fout, record.to_json()) kept += 1 if scores_fout: _durable_jsonl_write(scores_fout, score_row) solved_any += int(any(score > 0 for score, _ in scored)) processed_rows += 1 progress.update(1) completed = len(existing_score_ids) + i + 1 progress.set_postfix(pairs=kept, solved=f"{solved_any}/{completed}") finally: progress.close() if scores_fout: scores_fout.close() completed_rows = len(existing_score_ids) + processed_rows if completed_rows != len(target_rows): raise SystemExit( f"Sweep ended after {completed_rows}/{len(target_rows)} prompts; " "completion manifest was not written" ) print( f"[dpo] done: {kept} pairs from {completed_rows}/{len(target_rows)} prompts " f"(margin>={args.margin}) -> {out_path}" ) if scores_path: print(f"[dpo] wrote score summaries -> {scores_path}") if args.manifest_out: manifest_path = Path(args.manifest_out) manifest_path.parent.mkdir(parents=True, exist_ok=True) prompts_path = Path(args.prompts).resolve() manifest = { "schema": "model_data_sweep_v1", "status": "complete", "generator": gen_meta, "inputs": { "prompts": str(prompts_path), "prompts_sha256": _sha256(prompts_path), "prompt_rows": len(target_rows), "limit": args.limit, }, "outputs": { "pairs": str(out_path.resolve()), "pairs_sha256": _sha256(out_path), "pair_rows": kept, "scores": str(scores_path.resolve()) if scores_path else None, "scores_sha256": _sha256(scores_path) if scores_path else None, "score_rows": completed_rows if scores_path else 0, }, "summary": { "prompts_with_any_positive_reward": solved_any, "pair_margin": args.margin, }, } _atomic_write_json(manifest_path, manifest) print(f"[dpo] wrote sweep manifest -> {manifest_path}")
# Keep a live reference until all outputs and the completion manifest are durable. lock_handle.close() lock_path.unlink(missing_ok=True)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346#!/usr/bin/env python3"""Evaluate M0 and aligned RL adapters on one frozen coding test split.
The endpoint must expose the base model and any requested LoRA aliases throughthe OpenAI-compatible completions API. Prompts are rendered through the samehelper used by training and checkpoint reward evaluation. Output is append-onlyand resumable at the (model, record_id) level."""
from __future__ import annotations
import argparseimport hashlibimport jsonimport mathimport randomimport timefrom collections import defaultdictfrom pathlib import Pathfrom statistics import meanfrom typing import Any
import requestsfrom transformers import AutoTokenizer
from rl_training.data.schema import read_coding_jsonlfrom rl_training.prompts import render_coding_promptfrom rl_training.rewards import REWARD_TIMEOUT, coding_reward
def sha256(path: Path) -> str: return hashlib.sha256(path.read_bytes()).hexdigest()
def read_jsonl(path: Path) -> list[dict[str, Any]]: if not path.is_file(): return [] return [json.loads(line) for line in path.read_text().splitlines() if line.strip()]
def request_completions( *, base_url: str, api_key: str | None, model: str, prompts: list[str], seed: int, max_tokens: int, temperature: float, timeout: int,) -> list[dict[str, Any]]: payload = { "model": model, "prompt": prompts, "n": 1, "max_tokens": max_tokens, "temperature": temperature, "seed": seed, } error: Exception | None = None for attempt in range(3): try: headers = {"Authorization": f"Bearer {api_key}"} if api_key else {} response = requests.post( f"{base_url.rstrip('/')}/completions", headers=headers, json=payload, timeout=timeout, ) response.raise_for_status() choices = response.json().get("choices") or [] ordered = sorted(choices, key=lambda item: int(item["index"])) if len(ordered) != len(prompts): raise RuntimeError( f"Expected {len(prompts)} completions from {model}, got {len(ordered)}" ) return [ { "text": str(item.get("text") or ""), "finish_reason": item.get("finish_reason"), } for item in ordered ] except (requests.RequestException, RuntimeError, ValueError) as exc: error = exc if attempt < 2: time.sleep(5 * (attempt + 1)) raise RuntimeError(f"Completion request failed for {model}: {error}")
def bootstrap_delta( baseline: list[float], treatment: list[float], *, seed: int, draws: int) -> dict[str, float]: if len(baseline) != len(treatment) or not baseline: raise ValueError("Paired bootstrap requires equal non-empty vectors") differences = [right - left for left, right in zip(baseline, treatment)] rng = random.Random(seed) estimates = sorted( mean(differences[rng.randrange(len(differences))] for _ in differences) for _ in range(draws) ) low_index = max(0, math.floor(0.025 * draws)) high_index = min(draws - 1, math.ceil(0.975 * draws) - 1) return { "mean_delta": mean(differences), "bootstrap_95_low": estimates[low_index], "bootstrap_95_high": estimates[high_index], "bootstrap_draws": draws, }
def analyze(rows: list[dict[str, Any]], model_names: list[str], draws: int) -> dict[str, Any]: by_model: dict[str, dict[str, dict[str, Any]]] = defaultdict(dict) for row in rows: key = str(row["model"]) record_id = str(row["record_id"]) if record_id in by_model[key]: raise ValueError(f"Duplicate result for {key}/{record_id}") by_model[key][record_id] = row baseline_name = model_names[0] baseline_ids = set(by_model[baseline_name]) if not baseline_ids: raise ValueError(f"No baseline results for {baseline_name}") if any(set(by_model[name]) != baseline_ids for name in model_names): raise ValueError("All models must cover exactly the same record IDs") ordered_ids = sorted(baseline_ids) metrics: dict[str, Any] = {} for name in model_names: rewards = [float(by_model[name][record_id]["reward"]) for record_id in ordered_ids] metrics[name] = { "n_prompts": len(rewards), "mean_test_case_pass_fraction": mean(rewards), "strict_full_pass_rate": mean(value == 1.0 for value in rewards), "nonzero_reward_rate": mean(value > 0.0 for value in rewards), } model_rows = [by_model[name][record_id] for record_id in ordered_ids] if all("probably_truncated" in row for row in model_rows): truncated = [bool(row["probably_truncated"]) for row in model_rows] finish_reasons: dict[str, int] = defaultdict(int) for row in model_rows: finish_reasons[str(row.get("finish_reason"))] += 1 nontruncated_rewards = [ reward for reward, is_truncated in zip(rewards, truncated) if not is_truncated ] metrics[name]["truncation"] = { "count": sum(truncated), "rate": mean(truncated), "finish_reasons": dict(sorted(finish_reasons.items())), "nontruncated_n": len(nontruncated_rewards), "nontruncated_mean_test_case_pass_fraction": ( mean(nontruncated_rewards) if nontruncated_rewards else None ), "nontruncated_strict_full_pass_rate": ( mean(value == 1.0 for value in nontruncated_rewards) if nontruncated_rewards else None ), } if name != baseline_name: baseline = [ float(by_model[baseline_name][record_id]["reward"]) for record_id in ordered_ids ] metrics[name]["paired_vs_m0"] = bootstrap_delta( baseline, rewards, seed=20260817, draws=draws ) full_baseline = [ float(by_model[baseline_name][record_id]["reward"] == 1.0) for record_id in ordered_ids ] full_treatment = [float(value == 1.0) for value in rewards] metrics[name]["paired_full_pass_vs_m0"] = bootstrap_delta( full_baseline, full_treatment, seed=20260818, draws=draws ) return { "schema": "rl_heldout_reward_analysis_v1", "baseline_model": baseline_name, "models": model_names, "metrics": metrics, }
def parse_models(values: list[str]) -> list[tuple[str, str]]: result = [] for value in values: if "=" not in value: raise ValueError(f"--model must be LABEL=SERVED_MODEL, got {value!r}") label, served = value.split("=", 1) if not label or not served: raise ValueError(f"Invalid --model value: {value!r}") result.append((label, served)) if len({label for label, _ in result}) != len(result): raise ValueError("Model labels must be unique") return result
def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--dataset", type=Path, required=True) parser.add_argument("--base-model", type=Path, required=True) parser.add_argument("--base-url", default="http://127.0.0.1:8110/v1") parser.add_argument( "--api-key-file", type=Path, default=None, help="Optional bearer-token file; omit for an unauthenticated localhost endpoint", ) parser.add_argument("--model", action="append", required=True) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--summary", type=Path, required=True) parser.add_argument("--batch-size", type=int, default=16) parser.add_argument("--max-tokens", type=int, default=512) parser.add_argument( "--truncation-buffer-tokens", type=int, default=24, help="Also flag completions this close to --max-tokens as probably truncated.", ) parser.add_argument("--temperature", type=float, default=1.0) parser.add_argument("--seed", type=int, default=42) parser.add_argument("--request-timeout", type=int, default=1800) parser.add_argument("--verifier-timeout", type=float, default=REWARD_TIMEOUT) parser.add_argument("--verifier-workers", type=int, default=32) parser.add_argument("--bootstrap-draws", type=int, default=10000) parser.add_argument( "--limit", type=int, default=None, help="Optional leading-record limit for smoke tests." ) args = parser.parse_args() models = parse_models(args.model) if args.batch_size < 1 or args.bootstrap_draws < 1: parser.error("--batch-size and --bootstrap-draws must be positive") if args.truncation_buffer_tokens < 0 or args.truncation_buffer_tokens >= args.max_tokens: parser.error("--truncation-buffer-tokens must be in [0, --max-tokens)") records = read_coding_jsonl(args.dataset) if args.limit is not None: if args.limit < 1: parser.error("--limit must be positive") records = records[: args.limit] tokenizer = AutoTokenizer.from_pretrained( args.base_model, trust_remote_code=True, local_files_only=True ) prompts = [render_coding_prompt(tokenizer, row["prompt"]) for row in records] prompt_token_counts = [ len(tokenizer(prompt, add_special_tokens=False)["input_ids"]) for prompt in prompts ] args.output.parent.mkdir(parents=True, exist_ok=True) args.summary.parent.mkdir(parents=True, exist_ok=True) existing = read_jsonl(args.output) completed = {(row["model"], row["record_id"]) for row in existing} api_key = args.api_key_file.read_text().strip() if args.api_key_file else None if args.api_key_file and not api_key: raise ValueError("API key file is empty")
with args.output.open("a") as handle: for model_index, (label, served_model) in enumerate(models): pending = [ index for index, row in enumerate(records) if (label, row["record_id"]) not in completed ] for offset in range(0, len(pending), args.batch_size): indices = pending[offset : offset + args.batch_size] batch_prompts = [prompts[index] for index in indices] request_seed = args.seed + indices[0] completion_results = request_completions( base_url=args.base_url, api_key=api_key, model=served_model, prompts=batch_prompts, seed=request_seed, max_tokens=args.max_tokens, temperature=args.temperature, timeout=args.request_timeout, ) verifiers = [records[index]["verifier"] for index in indices] completions = [result["text"] for result in completion_results] rewards = coding_reward( completions, verifier=verifiers, timeout=args.verifier_timeout, max_tests=None, num_workers=args.verifier_workers, ) for index, result, reward in zip(indices, completion_results, rewards): completion = result["text"] completion_token_count = len( tokenizer(completion, add_special_tokens=False)["input_ids"] ) finish_reason = result["finish_reason"] probably_truncated = ( finish_reason == "length" or completion_token_count >= args.max_tokens - args.truncation_buffer_tokens ) row = { "schema": "rl_heldout_reward_completion_v1", "dataset_sha256": sha256(args.dataset), "model": label, "served_model": served_model, "record_id": records[index]["record_id"], "dataset_index": index, "request_seed": request_seed, "temperature": args.temperature, "max_tokens": args.max_tokens, "prompt_token_count": prompt_token_counts[index], "completion_token_count": completion_token_count, "finish_reason": finish_reason, "probably_truncated": probably_truncated, "truncation_buffer_tokens": args.truncation_buffer_tokens, "completion": completion, "reward": float(reward), } handle.write(json.dumps(row, ensure_ascii=False) + "\n") handle.flush() print( f"[{label}] {min(offset + len(indices), len(pending))}/{len(pending)}", flush=True, )
all_rows = read_jsonl(args.output) labels = [label for label, _ in models] summary = analyze(all_rows, labels, args.bootstrap_draws) summary.update( { "dataset": str(args.dataset), "dataset_sha256": sha256(args.dataset), "dataset_rows": len(records), "rollouts_per_prompt": 1, "generation": { "temperature": args.temperature, "max_tokens": args.max_tokens, "seed": args.seed, }, "verifier": { "timeout": args.verifier_timeout, "max_tests": None, }, } ) args.summary.write_text(json.dumps(summary, indent=2) + "\n") print(json.dumps(summary, indent=2)) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331"""Generate and score Qwen3.5 checkpoints on official LiveCodeBench v6.
This runner deliberately reuses LiveCodeBench's dataset objects, codeextraction, and executable-code evaluator, while rendering prompts with thecheckpoint's own Qwen3.5 tokenizer. The upstream runner still hard-codes aQwen1.5 tokenizer for its Qwen prompt style and therefore cannot safely renderQwen3.5's explicit non-thinking template.
The official repository currently requires ``datasets==3.6.0`` because itsdataset is implemented as a loading script. Keep that dependency in anisolated environment; do not downgrade the RL training environment."""
from __future__ import annotations
import argparseimport gcimport hashlibimport jsonimport osimport subprocessimport sysfrom pathlib import Pathfrom typing import Any
SCHEMA = "livecodebench_qwen35_v1"
def _sha256_text(text: str) -> str: return hashlib.sha256(text.encode("utf-8")).hexdigest()
def _write_json(path: Path, value: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix(path.suffix + ".tmp") with temporary.open("w") as handle: json.dump(value, handle, indent=2, sort_keys=True) handle.write("\n") handle.flush() os.fsync(handle.fileno()) os.replace(temporary, path)
def _append_jsonl(handle, value: Any) -> None: handle.write(json.dumps(value, ensure_ascii=True) + "\n") handle.flush() os.fsync(handle.fileno())
def _read_jsonl(path: Path) -> list[dict[str, Any]]: if not path.exists(): return [] rows = [] with path.open() as handle: for line_no, line in enumerate(handle, 1): try: rows.append(json.loads(line)) except json.JSONDecodeError as exc: raise ValueError(f"invalid JSON at {path}:{line_no}") from exc return rows
def _load_lcb(lcb_root: Path, release_version: str): sys.path.insert(0, str(lcb_root)) from lcb_runner.benchmarks import load_code_generation_dataset
benchmark = load_code_generation_dataset(release_version) return sorted(benchmark, key=lambda row: row.question_id)
def _lcb_commit(lcb_root: Path) -> str: return subprocess.check_output( ["git", "-c", f"safe.directory={lcb_root}", "rev-parse", "HEAD"], cwd=lcb_root, text=True, ).strip()
def _format_prompts(benchmark, tokenizer) -> list[str]: from lcb_runner.prompts.code_generation import ( PromptConstants, get_generic_question_template_answer, )
prompts = [] for problem in benchmark: messages = [ {"role": "system", "content": PromptConstants.SYSTEM_MESSAGE_GENERIC}, {"role": "user", "content": get_generic_question_template_answer(problem)}, ] prompts.append( tokenizer.apply_chat_template( messages, tokenize=False, add_generation_prompt=True, enable_thinking=False, ) ) return prompts
def _config(args, lcb_commit: str, benchmark_size: int) -> dict[str, Any]: return { "schema": SCHEMA, "model": str(Path(args.model).resolve()), "model_label": args.model_label, "release_version": args.release_version, "limit": args.limit, "benchmark_size": benchmark_size, "lcb_commit": lcb_commit, "thinking": False, "n": args.n, "temperature": args.temperature, "top_p": args.top_p, "max_tokens": args.max_tokens, "max_model_len": args.max_model_len, "seed": args.seed, "stop": args.stop, }
def generate(args, benchmark, lcb_commit: str) -> None: from transformers import AutoTokenizer from vllm import LLM, SamplingParams
tokenizer = AutoTokenizer.from_pretrained(args.model, trust_remote_code=True) prompts = _format_prompts(benchmark, tokenizer) prompt_lengths = [ len(tokenizer(prompt, add_special_tokens=False)["input_ids"]) for prompt in prompts ] budget = args.max_model_len - args.max_tokens overlong = [ (problem.question_id, length) for problem, length in zip(benchmark, prompt_lengths) if length > budget ] if overlong: raise ValueError( f"{len(overlong)} LiveCodeBench prompts exceed the {budget}-token prompt " f"budget; refusing to truncate. First rows: {overlong[:5]}" )
output = Path(args.output) manifest_path = Path(args.manifest) config = _config(args, lcb_commit, len(benchmark)) config["prompt_tokens"] = { "minimum": min(prompt_lengths), "maximum": max(prompt_lengths), "mean": sum(prompt_lengths) / len(prompt_lengths), } if manifest_path.exists(): existing_manifest = json.loads(manifest_path.read_text()) comparable = {key: existing_manifest.get(key) for key in config if key != "prompt_tokens"} expected = {key: value for key, value in config.items() if key != "prompt_tokens"} if comparable != expected: raise ValueError("existing LiveCodeBench manifest does not match this run") else: _write_json(manifest_path, config)
existing = _read_jsonl(output) if args.resume else [] if output.exists() and not args.resume: output.unlink() by_id = {row["question_id"]: row for row in existing} unknown = set(by_id) - {row.question_id for row in benchmark} if unknown: raise ValueError(f"output contains unknown question IDs: {sorted(unknown)[:5]}")
llm = LLM( model=args.model, tokenizer=args.model, trust_remote_code=True, language_model_only=True, max_model_len=args.max_model_len, gpu_memory_utilization=args.gpu_memory_utilization, seed=args.seed, ) sampling = SamplingParams( n=args.n, max_tokens=args.max_tokens, temperature=args.temperature, top_p=args.top_p, stop=[args.stop] if args.stop else None, seed=args.seed, )
output.parent.mkdir(parents=True, exist_ok=True) with output.open("a") as handle: for start in range(0, len(benchmark), args.batch_size): problems = benchmark[start : start + args.batch_size] batch_prompts = prompts[start : start + args.batch_size] missing = [index for index, problem in enumerate(problems) if problem.question_id not in by_id] if not missing: continue generated = llm.generate([batch_prompts[index] for index in missing], sampling) for index, request_output in zip(missing, generated): problem = problems[index] candidates = [] for candidate in request_output.outputs: candidates.append( { "text": candidate.text, "token_count": len(candidate.token_ids), "finish_reason": candidate.finish_reason, "probably_truncated": ( candidate.finish_reason == "length" or len(candidate.token_ids) >= args.max_tokens - args.truncation_buffer_tokens ), } ) row = { "schema": SCHEMA, "question_id": problem.question_id, "prompt_sha256": _sha256_text(batch_prompts[index]), "prompt_tokens": prompt_lengths[start + index], "outputs": candidates, } _append_jsonl(handle, row) by_id[problem.question_id] = row print(f"[lcb] generated {len(by_id)}/{len(benchmark)} problems", flush=True)
del llm gc.collect()
def score(args, benchmark, lcb_commit: str) -> None: from lcb_runner.evaluation import codegen_metrics from lcb_runner.lm_styles import LMStyle from lcb_runner.utils.extraction_utils import extract_code
rows = _read_jsonl(Path(args.output)) by_id = {row["question_id"]: row for row in rows} missing = [row.question_id for row in benchmark if row.question_id not in by_id] if missing: raise ValueError(f"generation output is incomplete: missing {len(missing)} problems") generations = [] for problem in benchmark: outputs = by_id[problem.question_id]["outputs"] if len(outputs) != args.n: raise ValueError(f"{problem.question_id} has {len(outputs)} outputs, expected {args.n}") generations.append( [extract_code(candidate["text"], LMStyle.CodeQwenInstruct) for candidate in outputs] ) samples = [problem.get_evaluation_sample() for problem in benchmark] metrics, results, metadata = codegen_metrics( samples, generations, k_list=[1, 5, 10], num_process_evaluate=args.num_process_evaluate, timeout=args.timeout, ) cap_hits = sum( candidate["probably_truncated"] for row in rows for candidate in row["outputs"] ) total = sum(len(row["outputs"]) for row in rows) summary = { **_config(args, lcb_commit, len(benchmark)), "metrics": metrics, "truncated_generations": cap_hits, "total_generations": total, "truncation_rate": cap_hits / total, "per_problem_results": {str(key): value for key, value in results.items()}, "evaluator_metadata": metadata, } _write_json(Path(args.summary), summary) print(json.dumps({"metrics": metrics, "truncation_rate": cap_hits / total}, indent=2))
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--lcb-root", required=True) parser.add_argument("--model", required=True, help="A base model or already-merged checkpoint") parser.add_argument("--model-label", required=True) parser.add_argument("--output", required=True) parser.add_argument("--manifest", required=True) parser.add_argument("--summary", required=True) parser.add_argument("--mode", choices=("generate", "score", "both"), default="both") parser.add_argument("--release-version", default="release_v6") parser.add_argument( "--limit", type=int, default=0, help="Evaluate only the first N sorted problems (0 means the full release).", ) parser.add_argument("--n", type=int, default=10) parser.add_argument("--temperature", type=float, default=0.2) parser.add_argument("--top-p", type=float, default=0.95) parser.add_argument("--max-tokens", type=int, default=32768) parser.add_argument("--max-model-len", type=int, default=36864) parser.add_argument("--truncation-buffer-tokens", type=int, default=24) parser.add_argument("--stop", default="###") parser.add_argument("--seed", type=int, default=0) parser.add_argument("--batch-size", type=int, default=8) parser.add_argument("--gpu-memory-utilization", type=float, default=0.9) parser.add_argument("--num-process-evaluate", type=int, default=12) parser.add_argument("--timeout", type=int, default=6) parser.add_argument("--resume", action="store_true") args = parser.parse_args() if args.max_model_len <= args.max_tokens: parser.error("--max-model-len must exceed --max-tokens") if args.n < 1 or args.batch_size < 1 or args.limit < 0: parser.error("--n and --batch-size must be positive; --limit must be non-negative") return args
def main() -> None: args = parse_args() lcb_root = Path(args.lcb_root).resolve() # Upstream prompt modules load few-shot fixtures relative to the process # working directory. Resolve all of our paths first, then enter the pinned # checkout so those official assets are found regardless of the caller's # cwd. args.model = str(Path(args.model).resolve()) args.output = str(Path(args.output).resolve()) args.manifest = str(Path(args.manifest).resolve()) args.summary = str(Path(args.summary).resolve()) os.chdir(lcb_root) benchmark = _load_lcb(lcb_root, args.release_version) if args.limit: benchmark = benchmark[: args.limit] commit = _lcb_commit(lcb_root) if args.mode in ("generate", "both"): generate(args, benchmark, commit) if args.mode in ("score", "both"): score(args, benchmark, commit)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302#!/usr/bin/env python3"""Build and audit length-controlled DPO preference pairs.
The verifier establishes which completion is better, but a generation cap cansilently make response length a proxy for the label. This module provides thesame policy for both new sweeps and post-hoc repair of an existing pair file:
* reject completions at (or very near) the generation cap;* compare only chosen/rejected responses with a bounded token-length gap; and* retain the compatible pair with the largest verifier-reward margin.
Post-hoc repair cannot recover alternative candidates that were not stored, soit conservatively filters the existing chosen/rejected pair and writes a newartifact plus a provenance manifest. It never overwrites the source file."""
from __future__ import annotations
import argparseimport hashlibimport jsonimport osfrom pathlib import Pathfrom typing import Any
FILTER_SCHEMA = "dpo_length_filter_v1"DEFAULT_TRUNCATION_BUFFER_TOKENS = 24DEFAULT_MAX_PAIR_TOKEN_DELTA = 256
def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest()
def _atomic_write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(f".{path.name}.tmp-{os.getpid()}") try: with temporary.open("w") as handle: for row in rows: handle.write(json.dumps(row, ensure_ascii=True) + "\n") handle.flush() os.fsync(handle.fileno()) os.replace(temporary, path) finally: temporary.unlink(missing_ok=True)
def _atomic_write_json(path: Path, payload: dict[str, Any]) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(f".{path.name}.tmp-{os.getpid()}") try: with temporary.open("w") as handle: json.dump(payload, handle, indent=2, ensure_ascii=True) handle.write("\n") handle.flush() os.fsync(handle.fileno()) os.replace(temporary, path) finally: temporary.unlink(missing_ok=True)
def completion_token_lengths(tokenizer: Any, completions: list[str]) -> list[int]: return [ len(tokenizer(text, add_special_tokens=False)["input_ids"]) for text in completions ]
def truncation_threshold(max_new_tokens: int, buffer_tokens: int) -> int: if max_new_tokens < 1: raise ValueError("max_new_tokens must be positive") if buffer_tokens < 0 or buffer_tokens >= max_new_tokens: raise ValueError("truncation buffer must be in [0, max_new_tokens)") return max_new_tokens - buffer_tokens
def select_length_controlled_pair( prompt: str, scored_completions: list[tuple[float, str]], tokenizer: Any, *, margin: float, max_new_tokens: int, truncation_buffer_tokens: int = DEFAULT_TRUNCATION_BUFFER_TOKENS, max_pair_token_delta: int = DEFAULT_MAX_PAIR_TOKEN_DELTA,) -> tuple[dict[str, Any] | None, dict[str, Any]]: """Select the strongest reward pair after length/truncation controls.""" if max_pair_token_delta < 0: raise ValueError("max_pair_token_delta must be non-negative") threshold = truncation_threshold(max_new_tokens, truncation_buffer_tokens) texts = [str(text) for _, text in scored_completions] lengths = completion_token_lengths(tokenizer, texts) truncated = [length >= threshold for length in lengths] compatible: list[tuple[tuple[float, float, float, int, int], int, int]] = [] for chosen_index, (chosen_score, _) in enumerate(scored_completions): if truncated[chosen_index]: continue for rejected_index, (rejected_score, _) in enumerate(scored_completions): if chosen_index == rejected_index or truncated[rejected_index]: continue reward_margin = float(chosen_score) - float(rejected_score) length_delta = abs(lengths[chosen_index] - lengths[rejected_index]) if reward_margin < margin or length_delta > max_pair_token_delta: continue # Maximize verifier separation, then prefer the closest lengths. key = ( reward_margin, float(chosen_score), -float(rejected_score), -length_delta, -chosen_index, ) compatible.append((key, chosen_index, rejected_index))
audit: dict[str, Any] = { "completion_token_lengths": lengths, "completion_probably_truncated": truncated, "truncation_threshold_tokens": threshold, "truncation_buffer_tokens": truncation_buffer_tokens, "max_pair_token_delta": max_pair_token_delta, "compatible_pair_count": len(compatible), "pair_eligible": bool(compatible), } if not compatible: return None, audit
_, chosen_index, rejected_index = max(compatible) chosen_score, chosen = scored_completions[chosen_index] rejected_score, rejected = scored_completions[rejected_index] chosen_tokens = lengths[chosen_index] rejected_tokens = lengths[rejected_index] audit.update( { "selected_chosen_index": chosen_index, "selected_rejected_index": rejected_index, "selected_chosen_tokens": chosen_tokens, "selected_rejected_tokens": rejected_tokens, "selected_token_delta": abs(chosen_tokens - rejected_tokens), } ) return ( { "prompt": prompt, "chosen": chosen, "rejected": rejected, "chosen_reward": float(chosen_score), "rejected_reward": float(rejected_score), }, audit, )
def filter_existing_pair( row: dict[str, Any], tokenizer: Any, *, margin: float, max_new_tokens: int, truncation_buffer_tokens: int = DEFAULT_TRUNCATION_BUFFER_TOKENS, max_pair_token_delta: int = DEFAULT_MAX_PAIR_TOKEN_DELTA,) -> tuple[dict[str, Any] | None, str | None]: """Filter one already-materialized pair and annotate retained rows.""" threshold = truncation_threshold(max_new_tokens, truncation_buffer_tokens) chosen_tokens, rejected_tokens = completion_token_lengths( tokenizer, [str(row["chosen"]), str(row["rejected"])] ) reward_margin = float(row["chosen_reward"]) - float(row["rejected_reward"]) if reward_margin < margin: return None, "reward_margin" if chosen_tokens >= threshold: return None, "chosen_probably_truncated" if rejected_tokens >= threshold: return None, "rejected_probably_truncated" if abs(chosen_tokens - rejected_tokens) > max_pair_token_delta: return None, "pair_token_delta"
repaired = dict(row) metadata = dict(repaired.get("metadata") or {}) metadata["length_filter"] = { "schema": FILTER_SCHEMA, "chosen_tokens": chosen_tokens, "rejected_tokens": rejected_tokens, "token_delta": abs(chosen_tokens - rejected_tokens), "generation_max_new_tokens": max_new_tokens, "truncation_threshold_tokens": threshold, "truncation_buffer_tokens": truncation_buffer_tokens, "max_pair_token_delta": max_pair_token_delta, "minimum_reward_margin": margin, } repaired["metadata"] = metadata return repaired, None
def _row_generation_cap(row: dict[str, Any], explicit_cap: int | None) -> int: if explicit_cap is not None: return explicit_cap metadata = row.get("metadata") or {} value = metadata.get("max_new_tokens") if not isinstance(value, int) or value < 1: raise ValueError( "Could not infer max_new_tokens from pair metadata; pass " "--generation-max-new-tokens explicitly" ) return value
def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--input", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--manifest", type=Path, required=True) parser.add_argument("--tokenizer", required=True) parser.add_argument("--tokenizer-revision", default=None) parser.add_argument("--generation-max-new-tokens", type=int, default=None) parser.add_argument("--truncation-buffer-tokens", type=int, default=DEFAULT_TRUNCATION_BUFFER_TOKENS) parser.add_argument("--max-pair-token-delta", type=int, default=DEFAULT_MAX_PAIR_TOKEN_DELTA) parser.add_argument("--min-reward-margin", type=float, default=0.5) args = parser.parse_args()
from transformers import AutoTokenizer
from rl_training.data.schema import read_preference_jsonl
source = args.input.resolve() output = args.output.resolve() manifest_path = args.manifest.resolve() if source == output: parser.error("--output must differ from --input; source pairs are immutable") for path in (output, manifest_path): if path.exists(): parser.error(f"refusing to overwrite existing artifact: {path}")
tokenizer = AutoTokenizer.from_pretrained( args.tokenizer, revision=args.tokenizer_revision, trust_remote_code=True, local_files_only=Path(args.tokenizer).exists(), ) rows = read_preference_jsonl(source) kept: list[dict[str, Any]] = [] rejected_by_reason: dict[str, int] = {} inferred_caps: set[int] = set() for row in rows: cap = _row_generation_cap(row, args.generation_max_new_tokens) inferred_caps.add(cap) repaired, reason = filter_existing_pair( row, tokenizer, margin=args.min_reward_margin, max_new_tokens=cap, truncation_buffer_tokens=args.truncation_buffer_tokens, max_pair_token_delta=args.max_pair_token_delta, ) if repaired is None: assert reason is not None rejected_by_reason[reason] = rejected_by_reason.get(reason, 0) + 1 else: kept.append(repaired)
_atomic_write_jsonl(output, kept) manifest = { "schema": FILTER_SCHEMA, "status": "complete", "input": { "path": str(source), "sha256": sha256_file(source), "rows": len(rows), }, "tokenizer": { "name_or_path": args.tokenizer, "revision": args.tokenizer_revision, }, "filter": { "generation_max_new_tokens": sorted(inferred_caps), "truncation_buffer_tokens": args.truncation_buffer_tokens, "max_pair_token_delta": args.max_pair_token_delta, "minimum_reward_margin": args.min_reward_margin, }, "output": { "path": str(output), "sha256": sha256_file(output), "rows": len(kept), }, "summary": { "retention_rate": len(kept) / len(rows) if rows else 0.0, "rejected_rows": len(rows) - len(kept), "rejected_by_reason": rejected_by_reason, }, } _atomic_write_json(manifest_path, manifest) print(json.dumps(manifest["summary"], indent=2, sort_keys=True)) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106"""Materialize one PEFT checkpoint for single-model evaluation.
The merged directory is an evaluation cache, not a training checkpoint. Itcontains no optimizer state and may be deleted after its generations have beendurably written."""
from __future__ import annotations
import argparseimport hashlibimport jsonimport osfrom pathlib import Path
def _sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest()
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--base-model", required=True) parser.add_argument("--adapter", required=True) parser.add_argument("--output", required=True) args = parser.parse_args()
import torch from peft import PeftModel from transformers import ( AutoConfig, AutoModelForCausalLM, AutoModelForImageTextToText, AutoTokenizer, )
base = Path(args.base_model).resolve() adapter = Path(args.adapter).resolve() output = Path(args.output).resolve() if not base.is_dir() or not adapter.is_dir(): raise SystemExit("--base-model and --adapter must be existing local directories") if output.exists() and any(output.iterdir()): raise SystemExit(f"refusing to overwrite non-empty merged directory: {output}") output.mkdir(parents=True, exist_ok=True)
adapter_weights = adapter / "adapter_model.safetensors" if not adapter_weights.is_file(): raise SystemExit(f"adapter weights not found: {adapter_weights}")
tokenizer = AutoTokenizer.from_pretrained(base, trust_remote_code=True, local_files_only=True) model = AutoModelForCausalLM.from_pretrained( base, trust_remote_code=True, local_files_only=True, dtype=torch.bfloat16, device_map="cpu", ) merged = PeftModel.from_pretrained(model, adapter, local_files_only=True).merge_and_unload() base_config = AutoConfig.from_pretrained(base, trust_remote_code=True, local_files_only=True) if base_config.model_type == "qwen3_5" and hasattr(base_config, "vision_config"): # AutoModelForCausalLM intentionally extracts Qwen3.5's text model. A # bare Qwen3_5TextConfig cannot currently be loaded by vLLM 0.22.x, # which still expects the outer config's vision_config even in # language-model-only mode. Put the merged text tower and LM head back # into the original full-model container so direct evaluation remains # loadable while still using the merged adapter weights. full_model = AutoModelForImageTextToText.from_pretrained( base, trust_remote_code=True, local_files_only=True, dtype=torch.bfloat16, device_map="cpu", ) full_model.model.language_model = merged.model full_model.lm_head = merged.lm_head model_to_save = full_model container = "full_qwen3_5" else: model_to_save = merged container = "causal_lm" model_to_save.save_pretrained(output, safe_serialization=True, max_shard_size="5GB") tokenizer.save_pretrained(output) manifest = { "schema": "merged_peft_eval_cache_v1", "base_model": str(base), "adapter": str(adapter), "adapter_sha256": _sha256(adapter_weights), "dtype": "bfloat16", "container": container, "optimizer_state_included": False, } temporary = output / "merge_manifest.json.tmp" temporary.write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n") with temporary.open("r+") as handle: handle.flush() os.fsync(handle.fileno()) os.replace(temporary, output / "merge_manifest.json") print(f"[merge] {adapter} + {base} -> {output}")
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""Prompt formats shared by RL training, DPO pair generation, and reward eval."""
from __future__ import annotations
CODING_PYTHON_IO_PROMPT = """You are solving a competitive programming problem.
Write a complete Python 3 program that reads from standard input and writes to standard output.Return only the solution code. Do not include explanations.
Problem:{problem}"""
# Nemotron's normalized ``prompt`` field already contains this instruction# wrapper. Keeping it inside our own stricter code-only wrapper creates# conflicting instructions and makes Qwen3.5 emit long step-by-step comments# inside an unfinished code fence even when chat-template thinking is disabled.# Match the complete prefix exactly so ordinary problem statements are never# rewritten merely because they mention similar words.NEMOTRON_LEGACY_PROMPT_PREFIX = """You are a helpful and harmless assistant. You should think step-by-step before responding to the instruction below.
Please use python programming language only.
You must use ```python for just the final solution code block with the following format:```python# Your code here```
"""
def normalize_coding_problem(problem: str) -> str: problem = problem.strip() if problem.startswith(NEMOTRON_LEGACY_PROMPT_PREFIX): problem = problem.removeprefix(NEMOTRON_LEGACY_PROMPT_PREFIX).strip() return problem
def format_coding_prompt(problem: str, *, format_name: str = "python_io") -> str: problem = normalize_coding_problem(problem) if format_name == "raw": return problem if format_name == "python_io": return CODING_PYTHON_IO_PROMPT.format(problem=problem) raise ValueError(f"unknown coding prompt format {format_name!r}")
def render_coding_prompt(tokenizer, problem: str, *, format_name: str = "python_io") -> str: """Render the exact prompt string the policy is trained/evaluated on.
Chat-tuned models (all Qwen3.5 sizes) must see their chat template — feeding them raw text puts them in continuation mode and they ramble instead of answering. ``enable_thinking=False`` pins non-thinking mode across model sizes whose templates default differently; templates without that variable ignore it. Tokenizers without a chat template fall back to the raw format.
Every consumer of coding prompts (GRPO rollouts, the per-checkpoint reward callback, DPO pair generation, prompt-length filtering) must go through this one function so the token stream is identical everywhere. """ user_text = format_coding_prompt(problem, format_name=format_name) if getattr(tokenizer, "chat_template", None): return tokenizer.apply_chat_template( [{"role": "user", "content": user_text}], tokenize=False, add_generation_prompt=True, enable_thinking=False, ) return user_text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360"""Verifiable coding reward for the RL-drift study.
One reward definition, shared by every algorithm so the *objective* is identicalacross PPO / GRPO / DPO (the algorithm is the only thing that varies):
- GRPO calls ``coding_reward`` directly (TRL's ``reward_funcs`` API).- PPO in TRL is reward-*model* based, so its objective must come from an RM trained on this same signal — see rl_training/README.md for the confound note.- DPO never sees a reward at train time; its (chosen, rejected) pairs are built from this reward via ``build_preference_pairs`` so it chases the same target.
The main dataset (nvidia/Nemotron-RL-coding-competitive_coding) is competitiveprogramming with **stdin/stdout** tests, so the primary path is ``run_io_tests``:feed each input on stdin, compare normalized stdout to the expected output. Theolder ``run_unit_tests`` (Python ``assert`` snippets) is kept for assert-stylesets (MBPP / AceCode). Reward = fraction of tests passed, in [0, 1].
SECURITY: this executes model-generated code. The subprocess + timeout here is aspeed bump, not a sandbox. Run training on a throwaway box or wrap execution in areal sandbox (container / firejail / nsjail) before pointing it at any dataset."""
from __future__ import annotations
import osimport reimport subprocessimport sysimport tempfilefrom concurrent.futures import ThreadPoolExecutorfrom functools import partialfrom pathlib import Path
_CODE_FENCE = re.compile(r"```(?:[a-zA-Z0-9_+-]*)\n(.*?)```", re.DOTALL)
# Test cases run as subprocesses, so threads parallelize them fine (the GIL is# released while waiting). Too many workers makes CPU-bound solutions contend# and can push borderline cases over their timeout; cap conservatively. This is# the default pool size; the training path overrides it via reward_num_workers# (make_coding_reward -> coding_reward's num_workers) so concurrency tracks the# run config._MAX_WORKERS = int(os.environ.get("VERIFIER_MAX_WORKERS", str(min(32, os.cpu_count() or 8))))
# --- Shared reward definition (the study's single training objective) -----------# r(x, y) = fraction of tests passed. Every arm's TRAINING signal must use the# same reward, or the algorithm comparison is confounded:# - GRPO trains on the online reward over TRAIN_REWARD_MAX_TESTS tests;# - DPO trains on pairs built from that same reward (build_dpo_pairs.py defaults# to these constants);# - PPO trains a reward model on those same pairs.# The only cheapening vs the full suite is the test COUNT; the timeout is the same# as eval so a correct-but-slow solution is graded identically in both places.# The capped subset is spread evenly across the suite (see _subsample_indices),# NOT the first N, because suites are often ordered easy->hard and grading only the# easy prefix is reward-hackable. The subset is deterministic per prompt, so every# completion in a GRPO group is judged on the same tests.# Measurement (DriftCadenceCallback, final scoring) uses the FULL suite for a# higher-fidelity, post-hoc equal-reward comparison — that is reporting, not the# training objective, so it legitimately differs from the training r.TRAIN_REWARD_MAX_TESTS = 12# Canonical per-test timeout, shared by every arm's reward and by eval so a# correct-but-slow solution grades the same everywhere. Single source of truth:# the configs (grpo/ppo.yaml) and scripts/build_dpo_data.sh mirror this value.# 5s is comfortably above what a correct competitive solution needs.REWARD_TIMEOUT = 5.0
def _subsample_indices(n: int, max_tests: int | None) -> list[int]: """Evenly-spaced test indices spanning [0, n-1] inclusive (endpoints kept).
Deterministic in ``n`` alone, so a prompt's reward is a stable function and all completions to that prompt are graded on the same cases. Spreads across the suite rather than taking a contiguous prefix, so an easy->hard ordering can't be gamed by solving only the easy end. """ if max_tests is None or max_tests >= n: return list(range(n)) if max_tests <= 1: return [0] return sorted({round(i * (n - 1) / (max_tests - 1)) for i in range(max_tests)})
def _map_checks(checks: list, max_workers: int | None = None) -> list[bool]: """Run zero-arg test-case callables, in parallel when there are several.
``max_workers`` defaults to ``_MAX_WORKERS``; the training reward threads the run config's worker count through here so grading concurrency is tunable. """ workers = _MAX_WORKERS if max_workers is None else max_workers if len(checks) <= 1 or workers <= 1: return [check() for check in checks] with ThreadPoolExecutor(max_workers=min(workers, len(checks))) as pool: return list(pool.map(lambda check: check(), checks))
def extract_code(completion: str) -> str: """Pull the last fenced code block from a completion, else the raw text.""" blocks = _CODE_FENCE.findall(completion or "") return blocks[-1].strip() if blocks else (completion or "").strip()
def _completion_text(completion) -> str: """TRL hands completions as str (plain) or [{'role','content'}] (chat).""" if isinstance(completion, str): return completion return completion[-1]["content"]
def _run(code: str, stdin: str | None, timeout: float) -> tuple[int, str]: """Execute ``code`` as a script in a fresh process; return (returncode, stdout).""" with tempfile.TemporaryDirectory(prefix="drift-verify-") as workdir: script = Path(workdir) / "solution.py" script.write_text(code) try: result = subprocess.run( [sys.executable, str(script)], input=stdin, capture_output=True, text=True, timeout=timeout, cwd=workdir, ) return result.returncode, result.stdout except subprocess.TimeoutExpired: return -1, ""
def _normalize(text: str) -> str: """Canonicalize competitive-judge output: unify newlines, rstrip each line, drop trailing blank lines. Avoids false negatives from CRLF / trailing space.""" text = text.replace("\r\n", "\n").replace("\r", "\n") lines = [line.rstrip() for line in text.split("\n")] while lines and lines[-1] == "": lines.pop() return "\n".join(lines)
def _io_case_passes(code: str, stdin: str, expected: str, timeout: float) -> bool: rc, stdout = _run(code, stdin, timeout) return rc == 0 and _normalize(stdout) == _normalize(expected)
def _unit_case_passes(code: str, test: str, timeout: float) -> bool: rc, _ = _run(f"{code}\n\n{test}\n", None, timeout) return rc == 0
def _case_checks(completion: str, verifier: dict, timeout: float, max_tests: int | None = None) -> list: """One zero-arg callable per test case of a ``coding_task_v1`` verifier.
``max_tests`` caps the cases via ``_subsample_indices`` (a deterministic, spread-out subset) BEFORE building callables, so the training reward's cheap budget flows through the same test-case-level parallel path as full grading. """ code = extract_code(completion) if completion else "" verifier_type = verifier.get("type") if verifier_type in {"io_tests", "reference_io_tests"}: inputs, outputs = verifier["test_inputs"], verifier["test_outputs"] if not code or not inputs: return [] idx = _subsample_indices(len(inputs), max_tests) return [partial(_io_case_passes, code, inputs[i], outputs[i], timeout) for i in idx] if verifier_type == "unit_tests": tests = verifier["tests"] if not code or not tests: return [] idx = _subsample_indices(len(tests), max_tests) return [partial(_unit_case_passes, code, tests[i], timeout) for i in idx] raise ValueError(f"Unsupported verifier type: {verifier_type!r}")
def run_io_tests( code: str, inputs: list[str], outputs: list[str], timeout: float = 10.0, max_tests: int | None = None,) -> float: """stdin/stdout verifier (Nemotron / CodeContests). Pass fraction over cases.
``max_tests`` caps how many cases are executed (``None`` = all). During training this is set low (see make_coding_reward) so grading is cheap; eval and DPO-pair building leave it ``None`` for full-fidelity pass rates. """ verifier = {"type": "io_tests", "test_inputs": inputs, "test_outputs": outputs} return run_verifier(code, verifier, timeout, max_tests)
def run_unit_tests( code: str, tests: list[str], timeout: float = 10.0, max_tests: int | None = None,) -> float: """assert-style verifier (MBPP / AceCode). Pass fraction over snippets.""" return run_verifier(code, {"type": "unit_tests", "tests": tests}, timeout, max_tests)
def run_verifier(code: str, verifier: dict, timeout: float = 10.0, max_tests: int | None = None) -> float: """Dispatch a completion against a canonical ``coding_task_v1`` verifier.""" checks = _case_checks(code, verifier, timeout, max_tests) if not checks: return 0.0 results = _map_checks(checks) return sum(results) / len(checks)
def coding_reward( completions, verifier=None, test_inputs=None, test_outputs=None, timeout: float = 10.0, max_tests: int | None = None, num_workers: int | None = None, **kwargs,) -> list[float]: """GRPO/RLOO-compatible reward function.
TRL passes ``completions`` plus every dataset column as keyword arguments; canonical data uses a ``verifier`` column. Legacy top-level ``test_inputs``/``test_outputs`` are still accepted during migration.
``max_tests`` caps tests per completion (the shared training budget). ``num_workers`` sizes the grading pool; every (completion x test-case) pair across the whole rollout batch is flattened into one pool so the batch grades concurrently, not one completion at a time. Both are set by make_coding_reward from the run config; the bare defaults preserve the original full-suite, default-pool behavior. """ if verifier is None: if test_inputs is None or test_outputs is None: raise ValueError("coding_reward requires either verifier or test_inputs/test_outputs") verifier = [ {"type": "io_tests", "test_inputs": ti, "test_outputs": to} for ti, to in zip(test_inputs, test_outputs) ] # Flatten every (completion, test case) pair into one worker pool so the # whole rollout batch verifies concurrently, not one completion at a time. # max_tests is applied per completion inside _case_checks (spread subset). per_completion = [ _case_checks(_completion_text(c), v, timeout, max_tests) for c, v in zip(completions, verifier) ] flat_results = iter(_map_checks([check for checks in per_completion for check in checks], num_workers)) rewards = [] for checks in per_completion: results = [next(flat_results) for _ in checks] rewards.append(sum(results) / len(checks) if checks else 0.0) return rewards
def make_coding_reward( timeout: float = REWARD_TIMEOUT, max_tests: int | None = TRAIN_REWARD_MAX_TESTS, num_workers: int | None = None,) -> callable: """Bind training-time grading knobs onto ``coding_reward`` for TRL.
TRL calls the reward function with a fixed signature (no timeout / cap args), so the training config's cheap-grading settings are injected here instead. ``num_workers`` of ``None`` or ``<=0`` resolves to ``os.cpu_count()``. The returned callable keeps ``__name__ == 'coding_reward'`` because TRL uses it to name the reward's logged metric column. """ if num_workers and num_workers > 0: resolved_workers = num_workers else: # ``reward_num_workers: 0`` means "use the process default" in the # training configs. Respect the run-level cap before falling back to # the machine CPU count: a GRPO batch flattens completion x test-case # checks, so an unconstrained os.cpu_count() can exhaust file # descriptors while spawning verifier subprocesses. env_workers = os.environ.get("VERIFIER_MAX_WORKERS") try: resolved_workers = int(env_workers) if env_workers else (os.cpu_count() or 1) except ValueError as exc: raise ValueError("VERIFIER_MAX_WORKERS must be an integer") from exc if resolved_workers <= 0: raise ValueError("VERIFIER_MAX_WORKERS must be positive")
def coding_reward_fn(completions, **kwargs): return coding_reward( completions, timeout=timeout, max_tests=max_tests, num_workers=resolved_workers, **kwargs, )
coding_reward_fn.__name__ = "coding_reward" return coding_reward_fn
def score_completions( completions: list[str], verifier: dict, timeout: float = 10.0, max_tests: int | None = None, num_workers: int | None = None,) -> list[tuple[float, str]]: """Score candidate solutions with a canonical verifier.
``max_tests`` must match the training reward's budget when building DPO pairs / PPO reward-model data, so every arm shares one objective (build_dpo_pairs.py passes it). Left ``None`` (full suite) for eval/measurement.
Every (completion x test-case) pair is flattened into one worker pool so the whole candidate set grades concurrently, not one completion at a time — this fully uses VERIFIER_MAX_WORKERS during DPO pair generation. ``num_workers`` of ``None`` resolves to ``_MAX_WORKERS`` (the env-configured default). """ texts = [_completion_text(c) for c in completions] per_completion = [_case_checks(t, verifier, timeout, max_tests) for t in texts] flat_results = iter(_map_checks([check for checks in per_completion for check in checks], num_workers)) scored = [] for text, checks in zip(texts, per_completion): results = [next(flat_results) for _ in checks] scored.append((sum(results) / len(checks) if checks else 0.0, text)) return scored
def build_preference_pairs( prompt: str, completions: list[str], verifier: dict, timeout: float = 10.0, margin: float = 0.5, max_tests: int | None = None,) -> dict | None: """Turn scored candidates for one prompt into a DPO ``(chosen, rejected)`` row.
Scores every candidate with the same I/O verifier, pairs best vs worst, and keeps the pair only when ``best - worst >= margin`` (default 0.5, per the study design) so ties/near-ties don't inject label noise into DPO. """ scored = score_completions(completions, verifier, timeout, max_tests=max_tests) return build_preference_pair_from_scored(prompt, scored, margin=margin)
def build_preference_pair_from_scored( prompt: str, scored_completions: list[tuple[float, str]], margin: float = 0.5,) -> dict | None: """Build a DPO pair from already-scored ``(score, completion)`` candidates.""" scored = sorted(scored_completions) if not scored: return None worst_score, worst = scored[0] best_score, best = scored[-1] if best_score - worst_score < margin: return None return { "prompt": prompt, "chosen": _completion_text(best), "rejected": _completion_text(worst), "chosen_reward": best_score, "rejected_reward": worst_score, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131#!/usr/bin/env python3"""Unified RL fine-tuning harness for the preference-drift study.
Fine-tunes a base model on a coding dataset with one of three algorithms(PPO / GRPO / DPO), saving checkpoints on a fixed step cadence so the driftelicitation can be scored on each. The algorithm is the study's independentvariable; everything else is held fixed across runs: base model, dataset,reward/objective, optimizer-step budget, checkpoint cadence, and thereference-KL strength (beta / init_kl_coef).
DPO is offline preference optimization; PPO/GRPO are online RL. All three shareone objective because DPO's pairs and (optionally) PPO's reward model are builtfrom the SAME verifiable reward used by GRPO (rl_training/rewards.py).
Checkpoints land in <save_dir>/<run_name>/checkpoint-<step>/. Register them intoconfig.yaml with rl_training/register_checkpoints.py, then score each withrun_elicitations.py / run_utilities.py (values via the run_utilities_values entry).
Assumes TRL >= 0.15 (GRPOTrainer + Trainer-style PPOTrainer). Exact kwargs movebetween TRL releases; pin via rl_training/requirements-training.txt.
Examples: python -m rl_training.train_rl --algo grpo --config rl_training/configs/grpo.yaml \ --base_model Qwen/Qwen3.5-0.8B \ --dataset data/rl/coding_train.jsonl --seed 0 \ --save_dir runs --run_name qwen08b-grpo-s0 --use_lora
python -m rl_training.train_rl --algo dpo --config rl_training/configs/dpo.yaml \ --base_model Qwen/Qwen3.5-0.8B \ --dataset data/rl/coding_pairs.jsonl --seed 0 \ --save_dir runs --run_name qwen08b-dpo-s0 --use_lora"""
from __future__ import annotations
import argparseimport hashlibimport jsonimport mathimport osimport randomfrom pathlib import Pathimport sys
import yamlfrom transformers import TrainerCallback
ROOT = Path(__file__).resolve().parent.parentif str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT))
from rl_training.hub_checkpoints import ( LOCAL_FALLBACK_MARKER, add_formal_hub_arguments, prepare_formal_hub_upload, prepared_formal_hub_callback,)
def load_config(path: str, algo: str) -> dict: with open(path) as f: cfg = yaml.safe_load(f) if cfg.get("algo") != algo: raise ValueError(f"Config {path} is for algo {cfg.get('algo')!r}, not {algo!r}") return cfg
def audit_grpo_prompt_budget( cfg: dict, dataset_size: int, world_size: int = 1) -> dict[str, int]: """Validate GRPO cadence in unique prompts rather than completions.
TRL repeats each prompt ``num_generations`` times. Its ordinary batch and accumulation fields consequently count completion sequences, not unique training prompts. The formal comparison requires exactly one pass over the same 1,000 frozen prompts as DPO, with eight unique prompts per update. """ required = ( "per_device_train_batch_size", "gradient_accumulation_steps", "num_generations", "generation_batch_size", "unique_prompts_per_step", "expected_unique_prompts", "max_steps", ) missing = [key for key in required if key not in cfg] if missing: raise ValueError(f"GRPO config missing prompt-budget fields: {missing}")
completion_sequences_per_step = ( int(cfg["per_device_train_batch_size"]) * int(world_size) * int(cfg["gradient_accumulation_steps"]) ) num_generations = int(cfg["num_generations"]) if completion_sequences_per_step % num_generations: raise ValueError( "GRPO completion batch per optimizer step must be divisible by " f"num_generations: {completion_sequences_per_step} % {num_generations} != 0" ) unique_prompts_per_step = completion_sequences_per_step // num_generations if unique_prompts_per_step != int(cfg["unique_prompts_per_step"]): raise ValueError( "GRPO unique-prompt batch mismatch: completion batch " f"{completion_sequences_per_step} / K={num_generations} = " f"{unique_prompts_per_step}, configured " f"unique_prompts_per_step={cfg['unique_prompts_per_step']}" )
generation_batch_size = int(cfg["generation_batch_size"]) if generation_batch_size != completion_sequences_per_step: raise ValueError( "Formal GRPO requires one generation batch per optimizer update: " f"generation_batch_size={generation_batch_size}, " f"completion_sequences_per_step={completion_sequences_per_step}" ) if generation_batch_size % num_generations: raise ValueError( f"generation_batch_size={generation_batch_size} is not divisible by K={num_generations}" )
expected_unique_prompts = int(cfg["expected_unique_prompts"]) if dataset_size != expected_unique_prompts: raise ValueError( f"GRPO dataset has {dataset_size} unique prompts; expected " f"{expected_unique_prompts}" ) scheduled_unique_prompts = int(cfg["max_steps"]) * unique_prompts_per_step if scheduled_unique_prompts != expected_unique_prompts: raise ValueError( f"GRPO schedule consumes {scheduled_unique_prompts} unique prompts " f"({cfg['max_steps']} steps * {unique_prompts_per_step}); expected " f"{expected_unique_prompts}" ) return { "dataset_unique_prompts": dataset_size, "num_generations": num_generations, "completion_sequences_per_step": completion_sequences_per_step, "unique_prompts_per_step": unique_prompts_per_step, "scheduled_unique_prompts": scheduled_unique_prompts, }
def set_all_seeds(seed: int) -> None: import numpy as np import torch
random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed)
def read_jsonl(path: str) -> list[dict]: with open(path) as f: return [json.loads(line) for line in f if line.strip()]
def _file_sha256(path: str | None) -> str | None: if not path: return None digest = hashlib.sha256() with open(path, "rb") as handle: for chunk in iter(lambda: handle.read(1 << 20), b""): digest.update(chunk) return digest.hexdigest()
def build_run_metadata(cfg: dict, args: argparse.Namespace) -> dict: return { "schema": "rl_training_run_v1", "status": "running", "algo": args.algo, "base_model": args.base_model, "dataset": str(Path(args.dataset).resolve()), "dataset_sha256": _file_sha256(args.dataset), "eval_dataset": str(Path(args.eval_dataset).resolve()) if args.eval_dataset else None, "eval_dataset_sha256": _file_sha256(args.eval_dataset), "reward_model": args.reward_model, "allow_weak_reward_model": args.allow_weak_reward_model, "seed": args.seed, "run_name": args.run_name, "use_vllm": args.use_vllm, "vllm_mode": args.vllm_mode, "config": str(Path(args.config).resolve()), "config_sha256": _file_sha256(args.config), "trainer_config": cfg, "lora": { "enabled": args.use_lora, "r": args.lora_r, "alpha": args.lora_alpha, "dropout": args.lora_dropout, "bias": args.lora_bias, "target_modules": args.lora_target_modules, }, "hub_archive": { "enabled": bool(args.hub_repo_id), "repo_id": args.hub_repo_id, "private": args.hub_private, "base_model_id": args.hub_base_model_id, "base_revision": args.hub_base_revision, "cohort_manifest": ( str(args.cohort_manifest.resolve()) if args.cohort_manifest else None ), "cohort_manifest_sha256": ( _file_sha256(str(args.cohort_manifest)) if args.cohort_manifest else None ), "keep_local_checkpoints_during_training": args.hub_keep_local_checkpoints, }, }
def _metadata_signature(metadata: dict) -> dict: keys = ( "algo", "base_model", "dataset_sha256", "eval_dataset_sha256", "reward_model", "seed", "run_name", "use_vllm", "vllm_mode", "config_sha256", "trainer_config", "lora", ) signature = {key: metadata.get(key) for key in keys} # The archive destination is operational state, not training provenance. # A run must be able to migrate to another private repository when the # original namespace reaches its storage quota. Keep validating the fields # that pin the actual model revision and frozen cohort, while allowing the # repository, visibility, enablement, and local-retention policy to change. hub_archive = metadata.get("hub_archive") or {} signature["hub_provenance"] = { key: hub_archive.get(key) for key in ( "base_model_id", "base_revision", "cohort_manifest_sha256", ) } return signature
def write_run_metadata(output_dir: str, metadata: dict) -> None: Path(output_dir).mkdir(parents=True, exist_ok=True) with (Path(output_dir) / "run_metadata.json").open("w") as f: json.dump(metadata, f, indent=2) f.write("\n")
def load_prompt_dataset(path: str, tokenizer): """Online arms (GRPO/PPO). JSONL rows use canonical coding_task_v1: {"prompt": str, "verifier": {...}}.
Prompts are pre-rendered through the tokenizer's chat template (render_coding_prompt) so chat-tuned bases answer instead of continuing the problem text. ``verifier`` rides along as a dataset column so the reward function can dispatch across io_tests, unit_tests, and reference tests. """ from datasets import Dataset from rl_training.data.schema import read_coding_jsonl from rl_training.prompts import render_coding_prompt
rows = read_coding_jsonl(path) rows = [{**row, "prompt": render_coding_prompt(tokenizer, row["prompt"])} for row in rows] return Dataset.from_list(rows)
def load_ppo_prompt_dataset(path: str, tokenizer, max_prompt_length: int): """PPO arm. TRL's PPOTrainer consumes PRE-TOKENIZED prompts: a dataset with a single ``input_ids`` column. It generates responses internally and scores them with the reward model, so -- unlike GRPO -- it cannot carry the ``verifier`` column: PPO's default collator pads ``input_ids`` and would choke on the dict. The verifier is not needed at PPO train time anyway (reward comes from the RM; per-checkpoint verifier eval reads its own --eval_dataset). """ from datasets import Dataset from rl_training.data.schema import read_coding_jsonl from rl_training.prompts import render_coding_prompt
rows = read_coding_jsonl(path) records = [ {"input_ids": tokenizer( render_coding_prompt(tokenizer, row["prompt"]), truncation=True, max_length=max_prompt_length, )["input_ids"]} for row in rows ] return Dataset.from_list(records)
def load_preference_dataset(path: str): """DPO arm. JSONL rows: {"prompt": str, "chosen": str, "rejected": str}.
Build these offline from the verifiable reward with training/rewards.build_preference_pairs so the objective matches the online arms. """ from datasets import Dataset from rl_training.data.schema import read_preference_jsonl
rows = read_preference_jsonl(path) return Dataset.from_list([ {"prompt": r["prompt"], "chosen": r["chosen"], "rejected": r["rejected"]} for r in rows ])
class DriftCadenceCallback(TrainerCallback): """Log the verifiable reward on a fixed eval slice at every checkpoint.
GRPO/PPO already optimize the reward, but DPO never sees it — this makes the reward-vs-step curve comparable across ALL algorithms (the study's secondary matching axis). Appends one JSON line per checkpoint to <output_dir>/reward_log.jsonl.
When ``fig_path`` is set, the reward-vs-step figure is re-rendered on every Trainer log event (every logging_steps) and after every checkpoint eval, so the PNG can be watched during training. """
def __init__(self, tokenizer, eval_records, n_samples, reward_timeout, output_dir, fig_path=None, run_name=None, eval_steps=None): self.tokenizer = tokenizer self.eval_records = eval_records self.n_samples = n_samples self.reward_timeout = reward_timeout self.log_path = Path(output_dir) / "reward_log.jsonl" self.fig_path = Path(fig_path) if fig_path else None self.run_name = run_name or Path(output_dir).name self.eval_steps = set(eval_steps or []) self._plot_broken = False
def _refresh_figure(self, state): if self.fig_path is None or self._plot_broken: return from rl_training.plot_reward import ( eval_points_from_reward_log, plot_reward_curve, train_points_from_log_history, )
try: plot_reward_curve( train_points_from_log_history(state.log_history), eval_points_from_reward_log(self.log_path), self.fig_path, title=f"{self.run_name} — verifiable reward", ) except Exception as err: # a plotting failure must never kill training self._plot_broken = True print(f"[drift] disabling reward figure (plot failed: {err})")
def on_log(self, args, state, control, **kwargs): self._refresh_figure(state)
def on_save(self, args, state, control, model=None, **kwargs): from rl_training.prompts import render_coding_prompt from rl_training.rewards import run_verifier
if self.eval_steps and state.global_step not in self.eval_steps: return model = model or kwargs.get("model") if model is None: return # Experimental TRL PPO wraps the causal policy together with the value # model. Evaluate the policy, not the wrapper, at checkpoint cadence. if hasattr(model, "module"): model = model.module if hasattr(model, "policy"): model = model.policy was_training = model.training model.eval() total, count = 0.0, 0 import torch from tqdm.auto import tqdm
for rec in tqdm(self.eval_records, desc=f"[drift] reward eval @ step {state.global_step}", unit="prompt"): prompt = render_coding_prompt(self.tokenizer, rec["prompt"]) enc = self.tokenizer(prompt, return_tensors="pt").to(model.device) with torch.no_grad(): out = model.generate( **enc, max_new_tokens=512, do_sample=True, temperature=1.0, num_return_sequences=self.n_samples, pad_token_id=self.tokenizer.eos_token_id, ) for seq in out: text = self.tokenizer.decode(seq[enc["input_ids"].shape[1]:], skip_special_tokens=True) total += run_verifier(text, rec["verifier"], timeout=self.reward_timeout) count += 1 mean_reward = total / max(count, 1) with self.log_path.open("a") as f: f.write(json.dumps({"step": state.global_step, "eval_reward": mean_reward}) + "\n") print(f"[drift] step {state.global_step}: eval_reward={mean_reward:.4f}") self._refresh_figure(state) if was_training: model.train()
def _parse_lora_target_modules(value: str) -> list[str] | str: value = value.strip() if value == "all-linear": return value modules = [item.strip() for item in value.split(",") if item.strip()] if not modules: raise ValueError("--lora_target_modules must be 'all-linear' or a comma-separated module list") return modules
def _lora_config(args): from peft import LoraConfig, TaskType
return LoraConfig( task_type=TaskType.CAUSAL_LM, r=args.lora_r, lora_alpha=args.lora_alpha, lora_dropout=args.lora_dropout, bias=args.lora_bias, target_modules=_parse_lora_target_modules(args.lora_target_modules), )
def _maybe_apply_lora(model, args): if not args.use_lora: return model from peft import get_peft_model
model = get_peft_model(model, _lora_config(args)) print("[drift] LoRA enabled") model.print_trainable_parameters() return model
def _apply_ppo_value_lora(value_model, args): """LoRA-tune the PPO critic backbone while keeping its score head trainable.
TRL's experimental PPO optimizer owns both the policy and value model. A full 9B critic would therefore require full gradients and Adam state in addition to the policy and frozen reward model, which cannot fit on one 140 GiB GPU. Wrap only the sequence classifier's causal backbone so TRL's ``PolicyAndValueWrapper`` still sees the expected outer model and ``score`` head. """ from peft import LoraConfig, TaskType, get_peft_model
backbone_name = value_model.base_model_prefix backbone = getattr(value_model, backbone_name) value_lora_config = LoraConfig( task_type=TaskType.FEATURE_EXTRACTION, r=args.lora_r, lora_alpha=args.lora_alpha, lora_dropout=args.lora_dropout, bias=args.lora_bias, target_modules=_parse_lora_target_modules(args.lora_target_modules), ) setattr(value_model, backbone_name, get_peft_model(backbone, value_lora_config)) for parameter in value_model.score.parameters(): parameter.requires_grad = True trainable = sum(parameter.numel() for parameter in value_model.parameters() if parameter.requires_grad) total = sum(parameter.numel() for parameter in value_model.parameters()) print( "[drift] PPO value-model LoRA enabled: " f"trainable={trainable:,}/{total:,} ({100.0 * trainable / total:.4f}%)" ) return value_model
def _bf16_available() -> bool: import torch
return torch.cuda.is_available() and torch.cuda.is_bf16_supported()
def _load_base(base_model: str): import torch from transformers import AutoModelForCausalLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(base_model, trust_remote_code=True) if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token # TRL truncates prompts to max_prompt_length with the tokenizer's default # side. Qwen defaults to right-truncation, which cuts off the trailing # <|im_start|>assistant header and flips the model into plain-continuation # mode. Prompts should be length-filtered at prep time; left truncation is # the safe fallback for any stray overlong prompt. tokenizer.truncation_side = "left" # GRPO wall time is generation-dominated; bf16 roughly halves it vs fp32 # with no quality cost on Ampere+ GPUs. Fall back to fp32 elsewhere. dtype = torch.bfloat16 if _bf16_available() else torch.float32 model = AutoModelForCausalLM.from_pretrained(base_model, trust_remote_code=True, dtype=dtype) # TRL 0.24 writes an ``estimate_tokens`` flag into this mapping during # GRPOTrainer initialization. Newer Transformers model classes no longer # create it, so provide the small compatibility attribute when absent. if not hasattr(model, "warnings_issued"): model.warnings_issued = {} return model, tokenizer
def _load_policy(args): model, tokenizer = _load_base(args.base_model) return _maybe_apply_lora(model, args), tokenizer
def _make_callback(cfg, args, tokenizer, dataset_path, output_dir): """Reward-eval callback over a held slice. Needs prompts+tests, so for DPO (pairs file) point --eval_dataset at the online prompts file.
The reward-vs-step curve is a study readout, so failing to build the callback is loud: a bad eval dataset or config must not silently produce a run without reward_log.jsonl. """ if cfg.get("eval_reward_enabled", True) is False: print("[drift] in-training reward evaluation disabled by config") return None from rl_training.data.schema import read_coding_jsonl from rl_training.rewards import REWARD_TIMEOUT
fig_path = None if args.figures_dir: fig_path = Path(args.figures_dir) / args.run_name / "reward_curve.png" try: rows = read_coding_jsonl(dataset_path) eval_records = rows[: cfg["eval_reward_prompts"]] return DriftCadenceCallback( tokenizer, eval_records, cfg["eval_reward_samples"], cfg.get("reward_timeout", REWARD_TIMEOUT), output_dir, fig_path=fig_path, run_name=args.run_name, eval_steps=cfg.get("eval_reward_steps"), ) except (ValueError, KeyError) as err: raise SystemExit( f"Cannot build per-checkpoint reward callback from {dataset_path!r}: {err}\n" "Pass --eval_dataset pointing at a coding_task_v1 prompts file and ensure " "eval_reward_prompts/eval_reward_samples are set in the config." ) from err
def _make_coding_reward( output_dir: str, num_generations: int, timeout: float, max_tests: int | None, num_workers: int | None, log_rollouts: bool,): """Bind the shared reward budget; optionally persist auditable rollout samples.
timeout/max_tests/num_workers (the shared training budget) are bound via make_coding_reward so the objective is applied identically whether or not rollout logging is enabled — turning logging on must not change the reward. """ from rl_training.rewards import make_coding_reward
scorer = make_coding_reward(timeout=timeout, max_tests=max_tests, num_workers=num_workers)
if not log_rollouts: return scorer # already __name__ == 'coding_reward'
rank = os.environ.get("RANK", os.environ.get("LOCAL_RANK", "0")) log_path = Path(output_dir) / f"rollout_samples.rank{rank}.jsonl" call_index = 0
def logged_coding_reward(completions, prompts=None, verifier=None, record_id=None, **kwargs): nonlocal call_index assert len(completions) % num_generations == 0, ( f"reward batch of {len(completions)} is not divisible by " f"num_generations={num_generations}; rollout group stats would be wrong" ) rewards = scorer(completions, verifier=verifier, **kwargs) prompts = prompts or [None] * len(completions) record_id = record_id or [None] * len(completions) with log_path.open("a") as fout: for group_start in range(0, len(rewards), num_generations): group_rewards = rewards[group_start : group_start + num_generations] mean = sum(group_rewards) / len(group_rewards) variance = sum((reward - mean) ** 2 for reward in group_rewards) / max(len(group_rewards) - 1, 1) std = math.sqrt(variance) for index in range(group_start, min(group_start + num_generations, len(rewards))): row = { "schema": "grpo_rollout_v1", "reward_call": call_index, "record_id": record_id[index], "prompt": prompts[index], "completion": completions[index], "reward": rewards[index], "group_mean": mean, "group_std": std, "advantage": (rewards[index] - mean) / (std + 1e-4), } fout.write(json.dumps(row, ensure_ascii=True) + "\n") call_index += 1 return rewards
logged_coding_reward.__name__ = "coding_reward" return logged_coding_reward
def _patch_trl_optional_imports(use_vllm: bool = False) -> None: """Disable TRL's optional integrations before importing any trainer.
By default this project uses Transformers generation for rollouts. A shared environment may also contain vLLM, vllm-ascend, mergekit, or llm-blender; TRL imports those optional integrations eagerly even when they are not enabled, and a mismatched install (e.g. a vLLM built for a different CUDA) makes EVERY trainer import fail — DPO and PPO included, not just GRPO. Transformers 5 also changed _is_package_available() to return a tuple, which TRL 0.24 may interpret as truthy even when a package is absent. Normalize the flags and disable what this path does not use (keeping vLLM available when --use_vllm asks for it). """ import trl.import_utils as trl_import_utils
for name, value in vars(trl_import_utils).copy().items(): if name.endswith("_available") and isinstance(value, tuple): setattr(trl_import_utils, name, value[0]) disabled = [ "_vllm_ascend_available", "_mergekit_available", "_llm_blender_available", "_weave_available", ] if not use_vllm: disabled.append("_vllm_available") for name in disabled: if hasattr(trl_import_utils, name): setattr(trl_import_utils, name, False)
def train_grpo(cfg, args, output_dir): _patch_trl_optional_imports(use_vllm=args.use_vllm) from trl import GRPOConfig, GRPOTrainer
from rl_training.rewards import REWARD_TIMEOUT, TRAIN_REWARD_MAX_TESTS
model, tokenizer = _load_policy(args) dataset = load_prompt_dataset(args.dataset, tokenizer) prompt_budget = audit_grpo_prompt_budget(cfg, len(dataset), world_size=1) print(f"[drift] GRPO prompt-budget audit: {json.dumps(prompt_budget, sort_keys=True)}") grpo_kwargs = dict( output_dir=output_dir, max_steps=cfg["max_steps"], save_steps=cfg["save_steps"], logging_steps=cfg["logging_steps"], learning_rate=cfg["learning_rate"], per_device_train_batch_size=cfg["per_device_train_batch_size"], gradient_accumulation_steps=cfg["gradient_accumulation_steps"], beta=cfg["beta"], num_generations=cfg["num_generations"], generation_batch_size=cfg["generation_batch_size"], max_completion_length=cfg["max_completion_length"], save_only_model=True, bf16=_bf16_available(), seed=args.seed, report_to="none", ) # Keep the formal default unchanged, but allow controlled optimization # probes to prevent the learning rate from decaying almost to zero during # the single pass over the frozen cohort. for optional_key in ("lr_scheduler_type", "warmup_steps", "warmup_ratio"): if optional_key in cfg: grpo_kwargs[optional_key] = cfg[optional_key] # vLLM rollouts (Chunk 2, lever 2): controlled by the --use_vllm CLI flag. Only # pass the kwargs when enabled, so the default path stays valid on TRL builds # that predate these fields. Validate colocate mode on the target hardware # (Qwen3.5 hybrid attention) before use. if args.use_vllm: grpo_kwargs["use_vllm"] = True grpo_kwargs["vllm_mode"] = args.vllm_mode grpo_config = GRPOConfig(**grpo_kwargs) if grpo_config.steps_per_generation != cfg["gradient_accumulation_steps"]: raise ValueError( "TRL derived steps_per_generation=" f"{grpo_config.steps_per_generation}, expected " f"gradient_accumulation_steps={cfg['gradient_accumulation_steps']}" ) # Cheap training-time grading over the shared reward budget: a spread subset of # tests, parallel across the sampled group. Full-suite grading is preserved in # DriftCadenceCallback (eval). The budget must match DPO's pairs and PPO's RM # data — warn loudly if the config drifts from the canonical values. train_max_tests = cfg.get("train_max_tests", TRAIN_REWARD_MAX_TESTS) reward_timeout = cfg.get("reward_timeout", REWARD_TIMEOUT) if train_max_tests != TRAIN_REWARD_MAX_TESTS or reward_timeout != REWARD_TIMEOUT: print( f"[drift] WARNING: training reward budget (max_tests={train_max_tests}, " f"timeout={reward_timeout}) differs from the shared default " f"(max_tests={TRAIN_REWARD_MAX_TESTS}, timeout={REWARD_TIMEOUT}). DPO pairs " f"and the PPO reward model MUST use the same values or the objective is not " f"identical across arms." ) # One wrapper binds the shared budget (timeout/max_tests/num_workers) AND, when # log_rollouts is on, persists per-rollout reward/advantage rows for audit. reward_func = _make_coding_reward( output_dir=output_dir, num_generations=cfg["num_generations"], timeout=reward_timeout, max_tests=train_max_tests, num_workers=cfg.get("reward_num_workers"), log_rollouts=cfg.get("log_rollouts", False), ) trainer = GRPOTrainer( model=model, reward_funcs=[reward_func], args=grpo_config, train_dataset=dataset, processing_class=tokenizer, ) cb = _make_callback(cfg, args, tokenizer, args.eval_dataset or args.dataset, output_dir) if cb: trainer.add_callback(cb) hub_cb = prepared_formal_hub_callback(args, tokenizer) if hub_cb: trainer.add_callback(hub_cb) result = trainer.train() trainer.save_model(output_dir) tokenizer.save_pretrained(output_dir) if hub_cb: hub_cb.archive_final(Path(output_dir), trainer.state.global_step) return trainer.state.global_step, result.metrics
def train_dpo(cfg, args, output_dir): _patch_trl_optional_imports() from trl import DPOConfig, DPOTrainer
model, tokenizer = _load_policy(args) dataset = load_preference_dataset(args.dataset) dpo_kwargs = dict( output_dir=output_dir, max_steps=cfg["max_steps"], save_steps=cfg["save_steps"], logging_steps=cfg["logging_steps"], learning_rate=cfg["learning_rate"], per_device_train_batch_size=cfg["per_device_train_batch_size"], gradient_accumulation_steps=cfg["gradient_accumulation_steps"], beta=cfg["beta"], max_length=cfg["max_length"], save_only_model=True, gradient_checkpointing=True, bf16=_bf16_available(), seed=args.seed, report_to="none", ) for optional_key in ("lr_scheduler_type", "warmup_steps", "warmup_ratio"): if optional_key in cfg: dpo_kwargs[optional_key] = cfg[optional_key] dpo_config = DPOConfig(**dpo_kwargs) trainer = DPOTrainer( model=model, args=dpo_config, train_dataset=dataset, processing_class=tokenizer, ) if not args.eval_dataset: print("[drift] no --eval_dataset (prompts+tests); skipping per-checkpoint reward log for DPO") else: cb = _make_callback(cfg, args, tokenizer, args.eval_dataset, output_dir) if cb: trainer.add_callback(cb) hub_cb = prepared_formal_hub_callback(args, tokenizer) if hub_cb: trainer.add_callback(hub_cb) result = trainer.train() # save_steps may not divide max_steps (the headline ends at step 125 while # dense periodic saves are every four steps). Persist the true final LoRA # adapter at the run root just like the matched SFT trainer does. trainer.save_model(output_dir) tokenizer.save_pretrained(output_dir) if hub_cb: hub_cb.archive_final(Path(output_dir), trainer.state.global_step) return trainer.state.global_step, result.metrics
def _install_ppo_gradient_guard( trainer, max_grad_norm: float, nonfinite_skip_limit: int = 0) -> dict[str, int]: """Make TRL experimental PPO apply its advertised gradient clipping.
TRL 1.9's experimental PPO loop calls ``optimizer.step()`` directly and never consumes ``TrainingArguments.max_grad_norm``. On the formal 4B run this allowed one late update to turn every LoRA tensor into NaN. Wrap the Accelerate optimizer so clipping occurs only at a real (synchronized) optimizer step, and refuse a non-finite gradient before it can corrupt the weights saved by the next checkpoint. """ if max_grad_norm <= 0: raise ValueError("PPO max_grad_norm must be positive") if nonfinite_skip_limit < 0: raise ValueError("PPO nonfinite_skip_limit cannot be negative")
import torch
original_step = trainer.optimizer.step original_backward = trainer.accelerator.backward guard_state = { "nonfinite_gradient_updates_skipped": 0, "consecutive_nonfinite_gradient_updates": 0, "max_consecutive_nonfinite_gradient_updates": 0, }
def guarded_backward(loss, *backward_args, **backward_kwargs): if not torch.isfinite(loss.detach()).all(): trainer.optimizer.zero_grad(set_to_none=True) raise FloatingPointError( "PPO produced a non-finite scalar loss before backward; " f"loss={loss.detach().float().item()}; no optimizer update was applied" ) return original_backward(loss, *backward_args, **backward_kwargs)
def guarded_step(*step_args, **step_kwargs): if trainer.accelerator.sync_gradients: named_parameters = [ (name, parameter) for name, parameter in trainer.model.named_parameters() if parameter.requires_grad and parameter.grad is not None ] nonfinite = [] for name, parameter in named_parameters: finite = torch.isfinite(parameter.grad) if not finite.all(): nonfinite.append( ( name, int(torch.isnan(parameter.grad).sum().item()), int(torch.isposinf(parameter.grad).sum().item()), int(torch.isneginf(parameter.grad).sum().item()), parameter.grad.dtype, tuple(parameter.grad.shape), ) ) if nonfinite: summary = "; ".join( f"{name}:nan={nan_count},+inf={posinf_count},-inf={neginf_count}," f"dtype={dtype},shape={shape}" for name, nan_count, posinf_count, neginf_count, dtype, shape in nonfinite[:8] ) guard_state["nonfinite_gradient_updates_skipped"] += 1 guard_state["consecutive_nonfinite_gradient_updates"] += 1 guard_state["max_consecutive_nonfinite_gradient_updates"] = max( guard_state["max_consecutive_nonfinite_gradient_updates"], guard_state["consecutive_nonfinite_gradient_updates"], ) skipped = guard_state["nonfinite_gradient_updates_skipped"] trainer.optimizer.zero_grad(set_to_none=True) if skipped > nonfinite_skip_limit: raise FloatingPointError( "PPO non-finite gradient skip limit exceeded before optimizer.step(); " f"skipped={skipped},limit={nonfinite_skip_limit}," f"offending_params={len(nonfinite)}; first={summary}; " "the current policy was left unchanged and no poisoned checkpoint was saved" ) print( "[drift] WARNING: skipped non-finite PPO optimizer update " f"{skipped}/{nonfinite_skip_limit}; offending_params={len(nonfinite)}; " f"first={summary}" ) return None parameters = [parameter for _, parameter in named_parameters] grad_norm = trainer.accelerator.clip_grad_norm_(parameters, max_grad_norm) if not torch.isfinite(torch.as_tensor(grad_norm)).all(): trainer.optimizer.zero_grad(set_to_none=True) raise FloatingPointError( "PPO finite gradient elements produced a non-finite aggregate norm before " "optimizer.step(); " "the current policy was left unchanged and no poisoned checkpoint was saved" ) result = original_step(*step_args, **step_kwargs) guard_state["consecutive_nonfinite_gradient_updates"] = 0 return result
trainer.optimizer.step = guarded_step trainer.accelerator.backward = guarded_backward print( f"[drift] PPO gradient clipping enabled: max_grad_norm={max_grad_norm:g}; " f"nonfinite_skip_limit={nonfinite_skip_limit}" ) return guard_state
def _extract_train_metrics(result) -> dict: """Normalize Trainer and experimental-TRL train return values.""" return dict(getattr(result, "metrics", None) or {})
def _patch_qwen35_fallback_l2norm() -> None: """Keep Qwen3.5 fallback Q/K normalization in float32 for backward stability.
Transformers' no-FLA fallback normalizes BF16 Q/K tensors before casting the rest of the gated-delta calculation to float32. The forward values can remain finite while the BF16 normalization backward produces NaN gradients across the policy and value model. Preserve the public function's output dtype, but perform its reduction and reciprocal square root in float32. """ import torch from transformers.models.qwen3_5 import modeling_qwen3_5
if getattr(modeling_qwen3_5.l2norm, "_drift_float32", False): return
def stable_l2norm(x, dim: int = -1, eps: float = 1e-6): input_dtype = x.dtype x_float = x.float() inv_norm = torch.rsqrt((x_float * x_float).sum(dim=dim, keepdim=True) + eps) return (x_float * inv_norm).to(input_dtype)
stable_l2norm._drift_float32 = True modeling_qwen3_5.l2norm = stable_l2norm print("[drift] Qwen3.5 fallback Q/K l2norm uses float32 reduction")
def train_ppo(cfg, args, output_dir): # TRL's PPOTrainer optimizes a reward MODEL, not a Python reward fn. To keep # the objective identical to GRPO, --reward_model must be an RM trained on the # same verifiable signal (see rl_training/README.md). We refuse to run without # one rather than silently change the objective. if not args.reward_model: raise SystemExit( "PPO requires --reward_model (a sequence-classification RM trained on the " "same unit-test reward as GRPO). See rl_training/README.md 'PPO objective'." ) rm_manifest_path = Path(args.reward_model) / "reward_model_manifest.json" if not rm_manifest_path.is_file(): raise SystemExit(f"PPO reward-model manifest not found: {rm_manifest_path}") rm_manifest = json.loads(rm_manifest_path.read_text()) if rm_manifest.get("schema") != "reward_model_manifest_v1": raise SystemExit(f"Unexpected PPO reward-model manifest schema: {rm_manifest_path}") rm_accuracy = float(rm_manifest["held_out_pairwise_accuracy"]) if rm_accuracy < 0.6 and not args.allow_weak_reward_model: raise SystemExit( f"PPO refused weak reward model: held-out pairwise accuracy={rm_accuracy:.4f} < 0.60. " "For plumbing-only smoke tests, pass --allow_weak_reward_model; never use that flag " "for a formal experiment." ) if rm_accuracy < 0.6: print( f"[drift] WARNING: allowing weak RM accuracy={rm_accuracy:.4f} for plumbing-only PPO smoke" ) _patch_trl_optional_imports() _patch_qwen35_fallback_l2norm() import torch from transformers import AutoModelForSequenceClassification from trl.experimental.ppo import PPOConfig, PPOTrainer
model, tokenizer = _load_policy(args) # Decoder-only rollout generation requires left padding. Right padding can # make generation continue from pad tokens instead of the end of a prompt. tokenizer.padding_side = "left" # Experimental PPO can use the disabled LoRA adapter as its reference, # avoiding a redundant full reference model allocation. ref_model = None if not args.use_lora: ref_model, _ = _load_base(args.base_model) # Reward + value models share the RM checkpoint (a plain seq-classification # dir from train_reward_model.py). Match the policy dtype so activations line # up, and set pad_token_id: seq-classification scoring locates each sequence's # last non-pad token, so a missing pad id silently reads the wrong position. rm_dtype = torch.bfloat16 if _bf16_available() else torch.float32 reward_model = AutoModelForSequenceClassification.from_pretrained( args.reward_model, trust_remote_code=True, num_labels=1, dtype=rm_dtype ) value_model = AutoModelForSequenceClassification.from_pretrained( args.reward_model, trust_remote_code=True, num_labels=1, dtype=rm_dtype ) value_model = _apply_ppo_value_lora(value_model, args) reward_model.config.pad_token_id = tokenizer.pad_token_id value_model.config.pad_token_id = tokenizer.pad_token_id reward_model.config.get_text_config().pad_token_id = tokenizer.pad_token_id value_model.config.get_text_config().pad_token_id = tokenizer.pad_token_id # TRL's PolicyAndValueWrapper forwards gradient-checkpointing controls only # to the policy. The critic backbone is a second full causal backbone and, # without its own checkpointing, the 9B run retains enough activations to # exhaust a 140 GiB H200 during the first PPO minibatch. Enable it directly # before the wrapper/optimizer are constructed. This changes only the # activation-memory/computation tradeoff, not the PPO batch or objective. checkpointing_kwargs = {"use_reentrant": False} value_model.gradient_checkpointing_enable( gradient_checkpointing_kwargs=checkpointing_kwargs ) if hasattr(value_model.config, "use_cache"): value_model.config.use_cache = False print("[drift] PPO value-model gradient checkpointing enabled (use_reentrant=False)") dataset = load_ppo_prompt_dataset(args.dataset, tokenizer, cfg["max_prompt_length"]) ppo_config = PPOConfig( output_dir=output_dir, total_episodes=cfg["max_steps"] * cfg["per_device_train_batch_size"] * cfg["gradient_accumulation_steps"], save_steps=cfg["save_steps"], logging_steps=cfg["logging_steps"], learning_rate=cfg["learning_rate"], max_grad_norm=cfg["max_grad_norm"], per_device_train_batch_size=cfg["per_device_train_batch_size"], gradient_accumulation_steps=cfg["gradient_accumulation_steps"], kl_coef=cfg["init_kl_coef"], num_ppo_epochs=cfg["num_ppo_epochs"], num_sample_generations=cfg.get("num_sample_generations", 0), response_length=cfg["response_length"], save_only_model=True, gradient_checkpointing=True, gradient_checkpointing_kwargs=checkpointing_kwargs, stop_token="eos", # truncate generated responses at EOS before scoring bf16=_bf16_available(), seed=args.seed, report_to="none", ) trainer = PPOTrainer( args=ppo_config, processing_class=tokenizer, model=model, ref_model=ref_model, reward_model=reward_model, value_model=value_model, train_dataset=dataset, eval_dataset=dataset, ) gradient_guard_state = _install_ppo_gradient_guard( trainer, float(cfg["max_grad_norm"]), int(cfg.get("nonfinite_gradient_skip_limit", 0)), ) cb = _make_callback(cfg, args, tokenizer, args.eval_dataset or args.dataset, output_dir) if cb: trainer.add_callback(cb) hub_cb = prepared_formal_hub_callback(args, tokenizer) if hub_cb: trainer.add_callback(hub_cb) result = trainer.train() trainer.save_model(output_dir) tokenizer.save_pretrained(output_dir) if hub_cb: hub_cb.archive_final(Path(output_dir), trainer.state.global_step) # TRL's experimental PPOTrainer.train() performs the full loop but returns # None (unlike transformers.Trainer.train(), which returns TrainOutput). # The authoritative step/log history remains on trainer.state. metrics = _extract_train_metrics(result) metrics.update(gradient_guard_state) return trainer.state.global_step, metrics
TRAINERS = {"grpo": train_grpo, "dpo": train_dpo, "ppo": train_ppo}
def main() -> None: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--algo", required=True, choices=list(TRAINERS)) parser.add_argument("--config", required=True, help="rl_training/configs/<algo>.yaml") parser.add_argument("--base_model", required=True, help="HF id or local path of the base model") parser.add_argument("--dataset", required=True, help="JSONL: coding_task_v1 (grpo/ppo) or dpo_preference_v1 (dpo)") parser.add_argument("--eval_dataset", default=None, help="coding_task_v1 JSONL for per-checkpoint reward log") parser.add_argument("--reward_model", default=None, help="RM path for PPO (see README)") parser.add_argument( "--allow_weak_reward_model", action="store_true", help="Allow PPO with RM held-out accuracy <0.60 for plumbing smoke tests only", ) parser.add_argument("--seed", type=int, required=True) parser.add_argument("--save_dir", default="runs") parser.add_argument("--run_name", required=True) parser.add_argument( "--figures_dir", default="results", help="Reward-curve PNG goes to <figures_dir>/<run_name>/reward_curve.png, " "refreshed live during training ('' disables)", ) parser.add_argument( "--resume", default=None, help="unsupported for model-only checkpoints; retained only for an explicit error", ) parser.add_argument( "--use_vllm", action="store_true", help="GRPO rollouts via vLLM (needs vllm installed; default is Transformers generate)", ) parser.add_argument( "--vllm_mode", default="colocate", choices=["colocate", "server"], help="TRL vLLM mode; 'colocate' shares the training GPU, 'server' needs `trl vllm-serve`", ) parser.add_argument("--use_lora", action="store_true", help="Train LoRA adapters instead of full model weights") parser.add_argument("--lora_r", type=int, default=16) parser.add_argument("--lora_alpha", type=int, default=32) parser.add_argument("--lora_dropout", type=float, default=0.05) parser.add_argument("--lora_bias", default="none", choices=["none", "all", "lora_only"]) parser.add_argument( "--lora_target_modules", default="q_proj,k_proj,v_proj,o_proj,gate_proj,up_proj,down_proj", help="Comma-separated target modules, or 'all-linear'", ) add_formal_hub_arguments(parser) args = parser.parse_args()
if args.resume: raise SystemExit( "Periodic checkpoints intentionally omit optimizer/scheduler/RNG state and cannot " "resume training; diagnose the incomplete run, archive it, and restart the arm cleanly" )
cfg = load_config(args.config, args.algo) if args.hub_repo_id and not args.use_lora: raise SystemExit("Formal Hub checkpoint archival requires --use_lora") set_all_seeds(args.seed) output_dir = str(Path(args.save_dir) / args.run_name) output_path = Path(output_dir) metadata_path = output_path / "run_metadata.json" metadata = build_run_metadata(cfg, args) existing_run_entries = ( [path for path in output_path.iterdir() if path.name != LOCAL_FALLBACK_MARKER] if output_path.exists() else [] ) if existing_run_entries: raise SystemExit( "Run directory is not empty and model-only checkpoints cannot resume training; " f"diagnose/archive it and restart cleanly: {output_path}" ) try: prepare_formal_hub_upload(args, output_dir=output_path, algo=args.algo) except ValueError as exc: raise SystemExit(f"Formal Hub preflight failed: {exc}") from None output_path.mkdir(parents=True, exist_ok=True) write_run_metadata(output_dir, metadata) print(f"[drift] {args.algo} run '{args.run_name}' seed={args.seed} -> {output_dir}") global_step, metrics = TRAINERS[args.algo](cfg, args, output_dir) metadata["status"] = "complete" metadata["global_step"] = global_step metadata["train_metrics"] = metrics write_run_metadata(output_dir, metadata) print(f"[drift] done. Register checkpoints:\n" f" python rl_training/register_checkpoints.py --run_dir {output_dir} " f"--base_model {args.base_model} --algo {args.algo} --seed {args.seed}")
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829# DPO run config for the RL-drift study.## MATCHED ACROSS ALGORITHMS (keep in sync with ppo.yaml/grpo.yaml):# max_steps, save_steps, learning_rate, effective batch, and reference# regularization (beta here == init_kl_coef in PPO, beta in GRPO).## DPO is offline: it trains on (prompt, chosen, rejected) pairs and never sees# the reward at train time. To hold the objective fixed against the online arms,# those pairs are built from the SAME verifiable reward (build_preference_pairs# in training/rewards.py). Reward is still logged per checkpoint by the callback,# so DPO lands on the same reward-vs-drift plot as PPO/GRPO.
algo: dpo
max_steps: 125 # N=1000 / effective batch 8 = one epochsave_steps: 4 # dense saves; elicit only the selected steps belowlogging_steps: 10learning_rate: 1.0e-6per_device_train_batch_size: 1gradient_accumulation_steps: 8beta: 0.05 # DPO's reference-KL strength; matched to PPO/GRPO
# DPO-specificmax_length: 2048 # prompt + completion; matches grpo 1024+1024max_prompt_length: 1024 # matched to grpo.yaml/ppo.yaml
eval_reward_prompts: 64eval_reward_samples: 4eval_reward_steps: [4, 12, 40, 125]123456789101112131415161718192021222324# Diagnostic 4B DPO run on its model-specific length-controlled pair set.# This intentionally stops at 16 optimizer steps to test for the same early# improvement observed in the 9B run; checkpoints are saved every four steps.algo: dpo
max_steps: 16save_steps: 4logging_steps: 1learning_rate: 1.0e-6lr_scheduler_type: constant_with_warmupwarmup_steps: 2per_device_train_batch_size: 4gradient_accumulation_steps: 2beta: 0.1
# All retained prompt+completion sequences fit without trainer truncation.max_length: 2048max_prompt_length: 1024
# Select checkpoints with a separate fixed dev evaluation after training.eval_reward_enabled: falseeval_reward_prompts: 0eval_reward_samples: 1eval_reward_steps: []12345678910111213141516171819202122232425262728# Extended 4B base-init DPO run on the model-specific length-controlled pairs.# Keep the 16-step probe settings fixed and extend only the optimization budget.algo: dpo
max_steps: 125save_steps: 4logging_steps: 1learning_rate: 1.0e-6lr_scheduler_type: constant_with_warmupwarmup_steps: 2# DPO materializes chosen and rejected activations together. A micro-batch of# four OOMs when a ~4.8K-token pair is sampled even on H200; 2 x accumulation 4# preserves the effective batch of eight while fitting the audited long tail.per_device_train_batch_size: 2gradient_accumulation_steps: 4beta: 0.1
# The regenerated data uses up to 4,096 completion tokens with prompts capped# at 1,024. Keep enough room for both sides and the chat-template boundary;# pair preparation rejects cap-hit completions instead of training on truncation.max_length: 6144max_prompt_length: 1024
# Checkpoint selection is performed afterward on a fixed dev split.eval_reward_enabled: falseeval_reward_prompts: 0eval_reward_samples: 1eval_reward_steps: []1234567891011121314151617181920212223# Diagnostic 9B DPO run on the length-controlled 245-pair derivative.# One epoch at effective batch 8: ceil(245 / 8) = 31 optimizer steps.algo: dpo
max_steps: 31save_steps: 4logging_steps: 1learning_rate: 1.0e-6lr_scheduler_type: constant_with_warmupwarmup_steps: 3per_device_train_batch_size: 4gradient_accumulation_steps: 2beta: 0.1
# All retained prompt+completion sequences fit without trainer truncation.max_length: 2048max_prompt_length: 1024
# Select checkpoints with a separate fixed dev evaluation after training.eval_reward_enabled: falseeval_reward_prompts: 0eval_reward_samples: 1eval_reward_steps: []1234567891011121314151617181920212223242526272829303132333435# PROBE: optimization-budget test. Only learning_rate and beta differ from# dpo.yaml (1.0e-6 -> 1.0e-5, 0.05 -> 0.01). The preference pairs are cleanly# separated (mean chosen-rejected gap 0.896), so if rewards/accuracies stays# near the 0.625 of the formal run, the budget is not the binding constraint.
# DPO run config for the RL-drift study.## MATCHED ACROSS ALGORITHMS (keep in sync with ppo.yaml/grpo.yaml):# max_steps, save_steps, learning_rate, effective batch, and reference# regularization (beta here == init_kl_coef in PPO, beta in GRPO).## DPO is offline: it trains on (prompt, chosen, rejected) pairs and never sees# the reward at train time. To hold the objective fixed against the online arms,# those pairs are built from the SAME verifiable reward (build_preference_pairs# in training/rewards.py). Reward is still logged per checkpoint by the callback,# so DPO lands on the same reward-vs-drift plot as PPO/GRPO.
algo: dpo
max_steps: 125 # N=1000 / effective batch 8 = one epochsave_steps: 25 # dense saves; elicit only the selected steps belowlogging_steps: 5learning_rate: 1.0e-5per_device_train_batch_size: 8gradient_accumulation_steps: 1beta: 0.01 # DPO's reference-KL strength; matched to PPO/GRPO
# DPO-specificmax_length: 2048 # prompt + completion; matches grpo 1024+1024max_prompt_length: 1024 # matched to grpo.yaml/ppo.yaml
eval_reward_prompts: 64eval_reward_samples: 4eval_reward_steps: [4, 12, 40, 125]eval_reward_enabled: false1234567891011121314151617181920212223242526# Exploratory 9B DPO tuning config.## Uses the same frozen 1,000-prompt cohort and LoRA shape as the formal run.# The smaller learning rate and stronger reference regularization mirror the# 9B GRPO pilot that reversed the original negative held-out point estimate.
algo: dpo
max_steps: 125save_steps: 4logging_steps: 10learning_rate: 5.0e-7per_device_train_batch_size: 1gradient_accumulation_steps: 8beta: 0.1
# 1,024 prompt tokens plus the tuned 1,536-token response budget.max_length: 2560max_prompt_length: 1024
# The 500-prompt held-out evaluation is authoritative. Keep only the final# in-training dev checkpoint evaluation to avoid hours of duplicate sampling.eval_reward_prompts: 64eval_reward_samples: 4eval_reward_steps: [125]eval_reward_enabled: false1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556# GRPO run config for the RL-drift study.## MATCHED ACROSS ALGORITHMS (do not change one without changing ppo.yaml/dpo.yaml):# max_steps, save_steps, learning_rate, effective UNIQUE-PROMPT batch,# and the reference-regularization strength (beta here == init_kl_coef in PPO).# The study matches "amount of training" on OPTIMIZER STEPS and additionally logs# verifiable reward at every checkpoint (DriftCadenceCallback), so runs can also# be compared at equal reward post-hoc.
algo: grpo
max_steps: 125 # 1000 unique prompts / 8 unique prompts per updatesave_steps: 4 # dense saves; baseline step 0 is scored separatelylogging_steps: 10learning_rate: 1.0e-6per_device_train_batch_size: 1# GRPO repeats every prompt K=8 times. Therefore 64 completion-level# microbatches are needed for one optimizer update over 8 UNIQUE prompts.gradient_accumulation_steps: 64beta: 0.05 # KL-to-reference; the shared drift-budget dial
# GRPO-specificnum_generations: 8 # group size per promptgeneration_batch_size: 64 # 8 unique prompts * K=8 completions; one optimizer updateunique_prompts_per_step: 8expected_unique_prompts: 1000max_prompt_length: 1024max_completion_length: 1024 # competitive solutions + partial reasoning need >512 to terminate
# Shared reward budget (Chunk 2, lever 1). r(x,y) = fraction of tests passed.# This is THE study objective and must be identical across arms: GRPO's online# reward, DPO's pairs (build_dpo_pairs.py), and PPO's reward-model data all use# it. The canonical values live in rl_training/rewards.py (TRAIN_REWARD_MAX_TESTS,# REWARD_TIMEOUT); these mirror them. If you change one, change all three or the# algorithm comparison is confounded (train_rl.py warns on mismatch).# Cheapening vs the full suite is the test COUNT only; timeout matches eval so a# correct-but-slow solution grades the same in training and measurement. Tests# are spread across the suite (not the first N), so easy->hard ordering can't be# gamed. The complete stored verifier suite is kept for checkpoint evaluation.train_max_tests: 12 # tests per completion for the training reward (spread across the suite)reward_num_workers: 0 # 0 = auto (os.cpu_count); grade the sampled group concurrently
# vLLM rollouts (Chunk 2, lever 2): 2-5x on generation-bound GRPO. Controlled by# the --use_vllm / --vllm_mode CLI flags (train_rl.py), NOT this config, so there# is one source of truth. Off by default; turn on only after validating colocate# mode with Qwen3.5 hybrid attention on the target hardware (shakedown).
reward_timeout: 5.0 # per-test timeout; shared by training reward AND eval (mirror rl_training/rewards.py REWARD_TIMEOUT)
# Reward is evaluated at every checkpoint on this many held-out prompts.eval_reward_prompts: 64eval_reward_samples: 4eval_reward_steps: [4, 12, 40, 125]
# Persist prompt/completion/reward/advantage rows for rollout inspection.log_rollouts: true123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263# PROBE: optimization-budget test. Only learning_rate and beta differ from# grpo.yaml (1.0e-6 -> 5.0e-6, 0.05 -> 0.01). Everything defining the task --# cohort, K=8, 125 steps, train_max_tests, max_completion_length -- is unchanged,# so a rise in rollout reward isolates the update budget as the binding constraint.# In-training reward eval is off: its 512-token cap makes it truncation-dominated.
# GRPO run config for the RL-drift study.## MATCHED ACROSS ALGORITHMS (do not change one without changing ppo.yaml/dpo.yaml):# max_steps, save_steps, learning_rate, effective UNIQUE-PROMPT batch,# and the reference-regularization strength (beta here == init_kl_coef in PPO).# The study matches "amount of training" on OPTIMIZER STEPS and additionally logs# verifiable reward at every checkpoint (DriftCadenceCallback), so runs can also# be compared at equal reward post-hoc.
algo: grpo
max_steps: 125 # 1000 unique prompts / 8 unique prompts per updatesave_steps: 25 # dense saves; baseline step 0 is scored separatelylogging_steps: 5learning_rate: 5.0e-6per_device_train_batch_size: 8# GRPO repeats every prompt K=8 times. Therefore 64 completion-level# microbatches are needed for one optimizer update over 8 UNIQUE prompts.gradient_accumulation_steps: 8beta: 0.01 # KL-to-reference; the shared drift-budget dial
# GRPO-specificnum_generations: 8 # group size per promptgeneration_batch_size: 64 # 8 unique prompts * K=8 completions; one optimizer updateunique_prompts_per_step: 8expected_unique_prompts: 1000max_prompt_length: 1024max_completion_length: 1024 # competitive solutions + partial reasoning need >512 to terminate
# Shared reward budget (Chunk 2, lever 1). r(x,y) = fraction of tests passed.# This is THE study objective and must be identical across arms: GRPO's online# reward, DPO's pairs (build_dpo_pairs.py), and PPO's reward-model data all use# it. The canonical values live in rl_training/rewards.py (TRAIN_REWARD_MAX_TESTS,# REWARD_TIMEOUT); these mirror them. If you change one, change all three or the# algorithm comparison is confounded (train_rl.py warns on mismatch).# Cheapening vs the full suite is the test COUNT only; timeout matches eval so a# correct-but-slow solution grades the same in training and measurement. Tests# are spread across the suite (not the first N), so easy->hard ordering can't be# gamed. The complete stored verifier suite is kept for checkpoint evaluation.train_max_tests: 12 # tests per completion for the training reward (spread across the suite)reward_num_workers: 32 # 0 = auto (os.cpu_count); grade the sampled group concurrently
# vLLM rollouts (Chunk 2, lever 2): 2-5x on generation-bound GRPO. Controlled by# the --use_vllm / --vllm_mode CLI flags (train_rl.py), NOT this config, so there# is one source of truth. Off by default; turn on only after validating colocate# mode with Qwen3.5 hybrid attention on the target hardware (shakedown).
reward_timeout: 5.0 # per-test timeout; shared by training reward AND eval (mirror rl_training/rewards.py REWARD_TIMEOUT)
# Reward is evaluated at every checkpoint on this many held-out prompts.eval_reward_prompts: 64eval_reward_samples: 4eval_reward_steps: [4, 12, 40, 125]eval_reward_enabled: false
# Persist prompt/completion/reward/advantage rows for rollout inspection.log_rollouts: true1234567891011121314151617181920212223242526272829303132333435# 9B optimization probe. The cohort, K=8 rollout design, verifier budget, and# exact 1,000-prompt schedule match the completed tuned run. This probe changes# only the policy-update budget and microbatching: the completed run's KL was# ~3.6e-4 and its linear LR schedule had nearly decayed to zero by step 110.
algo: grpomax_steps: 125save_steps: 4logging_steps: 5learning_rate: 1.0e-6lr_scheduler_type: constant_with_warmupwarmup_steps: 5
# Preserve 64 completion sequences = 8 prompts x K=8 per optimizer update.# Start at microbatch 2 to improve utilization; fall back to 1 x 64 on OOM.per_device_train_batch_size: 2gradient_accumulation_steps: 32beta: 0.05
num_generations: 8generation_batch_size: 64unique_prompts_per_step: 8expected_unique_prompts: 1000max_prompt_length: 1024max_completion_length: 1536
train_max_tests: 12reward_num_workers: 32reward_timeout: 5.0
eval_reward_prompts: 64eval_reward_samples: 4eval_reward_steps: [4, 12, 40, 125]eval_reward_enabled: falselog_rollouts: true123456789101112131415161718192021222324252627282930# Short, local-only diagnostic for whether the 9B policy-update budget is the# bottleneck. A watchdog stops after checkpoint 16; no Hub arguments are used.
algo: grpomax_steps: 125save_steps: 4logging_steps: 4learning_rate: 5.0e-6lr_scheduler_type: constant_with_warmupwarmup_steps: 5per_device_train_batch_size: 4gradient_accumulation_steps: 16beta: 0.01
num_generations: 8generation_batch_size: 64unique_prompts_per_step: 8expected_unique_prompts: 1000max_prompt_length: 1024max_completion_length: 1536
train_max_tests: 12reward_num_workers: 32reward_timeout: 5.0
eval_reward_prompts: 64eval_reward_samples: 4eval_reward_steps: [4, 12, 40, 125]eval_reward_enabled: falselog_rollouts: true123456789101112131415161718192021222324252627282930# Memory-safe fallback for grpo_probe_9b.yaml. The effective batch and every# experimental parameter are identical; only microbatching differs.
algo: grpomax_steps: 125save_steps: 4logging_steps: 5learning_rate: 1.0e-6lr_scheduler_type: constant_with_warmupwarmup_steps: 5per_device_train_batch_size: 1gradient_accumulation_steps: 64beta: 0.05
num_generations: 8generation_batch_size: 64unique_prompts_per_step: 8expected_unique_prompts: 1000max_prompt_length: 1024max_completion_length: 1536
train_max_tests: 12reward_num_workers: 32reward_timeout: 5.0
eval_reward_prompts: 64eval_reward_samples: 4eval_reward_steps: [4, 12, 40, 125]eval_reward_enabled: falselog_rollouts: true123456789101112131415161718192021222324252627282930# Higher-throughput microbatch variant of grpo_probe_9b.yaml. The effective# completion batch remains 64, so this changes utilization, not the experiment.
algo: grpomax_steps: 125save_steps: 4logging_steps: 5learning_rate: 1.0e-6lr_scheduler_type: constant_with_warmupwarmup_steps: 5per_device_train_batch_size: 4gradient_accumulation_steps: 16beta: 0.05
num_generations: 8generation_batch_size: 64unique_prompts_per_step: 8expected_unique_prompts: 1000max_prompt_length: 1024max_completion_length: 1536
train_max_tests: 12reward_num_workers: 32reward_timeout: 5.0
eval_reward_prompts: 64eval_reward_samples: 4eval_reward_steps: [4, 12, 40, 125]eval_reward_enabled: falselog_rollouts: true123456789101112131415161718192021222324252627282930# Maximum-throughput microbatch variant. Effective completion batch remains 64# (8 x 8), matching every other 9B GRPO probe and the frozen prompt schedule.
algo: grpomax_steps: 125save_steps: 4logging_steps: 5learning_rate: 1.0e-6lr_scheduler_type: constant_with_warmupwarmup_steps: 5per_device_train_batch_size: 8gradient_accumulation_steps: 8beta: 0.05
num_generations: 8generation_batch_size: 64unique_prompts_per_step: 8expected_unique_prompts: 1000max_prompt_length: 1024max_completion_length: 1536
train_max_tests: 12reward_num_workers: 32reward_timeout: 5.0
eval_reward_prompts: 64eval_reward_samples: 4eval_reward_steps: [4, 12, 40, 125]eval_reward_enabled: falselog_rollouts: true12345678910111213141516171819202122232425262728293031# Local-only LoRA-capacity diagnostic. A watchdog stops after checkpoint 16.# Compared with the best r=16 probe, only LoRA r/alpha change at launch time;# alpha/r remains 2 so the adapter scaling is controlled.
algo: grpomax_steps: 125save_steps: 4logging_steps: 4learning_rate: 1.0e-6lr_scheduler_type: constant_with_warmupwarmup_steps: 5per_device_train_batch_size: 4gradient_accumulation_steps: 16beta: 0.05
num_generations: 8generation_batch_size: 64unique_prompts_per_step: 8expected_unique_prompts: 1000max_prompt_length: 1024max_completion_length: 1536
train_max_tests: 12reward_num_workers: 32reward_timeout: 5.0
eval_reward_prompts: 64eval_reward_samples: 4eval_reward_steps: [4, 12, 40, 125]eval_reward_enabled: falselog_rollouts: true12345678910111213141516171819202122232425262728293031323334# Qwen3.5-4B Base GRPO diagnostic on a seed-fixed random 1,000-prompt cohort.# The longer completion budget removes the 1,024-token cap that clipped roughly# 18-29% of completions in earlier 4B GRPO runs. The update strength matches# the already-stable 4B optimization probe, while a constant schedule avoids# decaying the learning rate to nearly zero during the single cohort pass.
algo: grpomax_steps: 125save_steps: 4logging_steps: 1learning_rate: 5.0e-6lr_scheduler_type: constant_with_warmupwarmup_steps: 5per_device_train_batch_size: 1gradient_accumulation_steps: 64beta: 0.01
num_generations: 8generation_batch_size: 64unique_prompts_per_step: 8expected_unique_prompts: 1000max_prompt_length: 1024max_completion_length: 4096
train_max_tests: 12reward_num_workers: 32reward_timeout: 5.0
# Evaluate externally on the fixed LiveCodeBench-100 slice after training.eval_reward_enabled: falseeval_reward_prompts: 0eval_reward_samples: 1eval_reward_steps: []log_rollouts: true12345678910111213141516171819202122232425262728293031# Large-batch version of the Base/random-cohort 4B GRPO diagnostic.# Twenty unique prompts and K=8 use 160 completions per optimizer update;# 50 updates therefore consume the frozen 1,000 prompts exactly once.
algo: grpomax_steps: 50save_steps: 4logging_steps: 1learning_rate: 5.0e-6lr_scheduler_type: constant_with_warmupwarmup_steps: 2per_device_train_batch_size: 4gradient_accumulation_steps: 40beta: 0.01
num_generations: 8generation_batch_size: 160unique_prompts_per_step: 20expected_unique_prompts: 1000max_prompt_length: 1024max_completion_length: 4096
train_max_tests: 12reward_num_workers: 32reward_timeout: 5.0
eval_reward_enabled: falseeval_reward_prompts: 0eval_reward_samples: 1eval_reward_steps: []log_rollouts: true1234567891011121314151617181920212223242526272829303132# Exploratory 4B GRPO tuning config.## This is intentionally separate from grpo.yaml: the original formal run is# preserved as the matched baseline. The training cohort, K=8 rollout design,# verifier budget, and 125 optimizer steps remain unchanged. The mild# regularization/learning-rate change is paired with a larger response budget# so coding solutions are less likely to be cut off during training.
algo: grpomax_steps: 125save_steps: 4logging_steps: 10learning_rate: 7.5e-7per_device_train_batch_size: 1gradient_accumulation_steps: 64beta: 0.075
num_generations: 8generation_batch_size: 64unique_prompts_per_step: 8expected_unique_prompts: 1000max_prompt_length: 1024max_completion_length: 1536
train_max_tests: 12reward_num_workers: 32reward_timeout: 5.0
eval_reward_prompts: 64eval_reward_samples: 4eval_reward_steps: [4, 12, 40, 125]log_rollouts: true1234567891011121314151617181920212223242526272829303132# Exploratory 9B GRPO tuning config.## The formal baseline remains in grpo.yaml. This keeps the same 1,000-prompt# cohort, K=8 rollouts, verifier budget, and 125 optimizer steps while reducing# update size and increasing the response budget. The 9B baseline had higher# KL and many more response-length truncations than 4B.
algo: grpomax_steps: 125save_steps: 4logging_steps: 10learning_rate: 5.0e-7per_device_train_batch_size: 1gradient_accumulation_steps: 64beta: 0.1
num_generations: 8generation_batch_size: 64unique_prompts_per_step: 8expected_unique_prompts: 1000max_prompt_length: 1024max_completion_length: 1536
train_max_tests: 12reward_num_workers: 32reward_timeout: 5.0
eval_reward_prompts: 64eval_reward_samples: 4eval_reward_steps: [4, 12, 40, 125]eval_reward_enabled: falselog_rollouts: true123456789101112131415161718192021222324252627282930313233# PPO run config for the RL-drift study.## MATCHED ACROSS ALGORITHMS (keep in sync with grpo.yaml/dpo.yaml):# max_steps, save_steps, learning_rate, effective batch, and reference# regularization (init_kl_coef here == beta in GRPO/DPO).## OBJECTIVE CAVEAT: TRL's PPOTrainer optimizes a reward *model*, not a Python# reward function. To keep the objective identical to GRPO's verifiable reward,# point --reward_model at an RM trained on the SAME unit-test signal (or the same# preference pairs DPO uses). The RM is then a controlled component, not a free# confound. See training/README.md.
algo: ppo
max_steps: 125 # N=1000 / effective batch 8 = one epochsave_steps: 4 # dense saves; elicit only selected stepslogging_steps: 10learning_rate: 1.0e-6max_grad_norm: 1.0 # TRL experimental PPO does not apply this unless train_rl installs the guardnonfinite_gradient_skip_limit: 8 # skip isolated unstable fallback updates; abort on the 9thper_device_train_batch_size: 1gradient_accumulation_steps: 8init_kl_coef: 0.05 # KL-to-reference; matched to GRPO/DPO beta
# PPO-specificnum_ppo_epochs: 4max_prompt_length: 1024 # matched to grpo.yaml/dpo.yamlresponse_length: 1024 # matched to grpo max_completion_lengthreward_timeout: 5.0 # per-test timeout; shared with GRPO/eval (mirror rl_training/rewards.py REWARD_TIMEOUT)
eval_reward_prompts: 64eval_reward_samples: 4eval_reward_steps: [4, 12, 40, 125]1234567891011121314151617181920212223242526272829# Exploratory 9B PPO tuning config.## Uses the same frozen 1,000-prompt cohort and validated reward model as the# formal run. The update is made more conservative while retaining PPO's# standard four optimization epochs per rollout batch.
algo: ppo
max_steps: 125save_steps: 4logging_steps: 10learning_rate: 5.0e-7max_grad_norm: 1.0nonfinite_gradient_skip_limit: 8per_device_train_batch_size: 1gradient_accumulation_steps: 8init_kl_coef: 0.1
num_ppo_epochs: 4max_prompt_length: 1024response_length: 1536reward_timeout: 5.0
# The 500-prompt held-out evaluation is authoritative. Keep only the final# in-training dev checkpoint evaluation to avoid hours of duplicate sampling.eval_reward_prompts: 64eval_reward_samples: 4eval_reward_steps: [125]eval_reward_enabled: false12345678910[transformers] The fast path is not available because one of the required library is not installed. Falling back to torch implementation. To install follow https://github.com/fla-org/flash-linear-attention#installation and https://github.com/Dao-AILab/causal-conv1d[drift] grpo run 'qwen35-9b-grpo-probe-aggressive-mb4-step16-n1000-s0' seed=0 -> /ndata/xianglin/ai_drift/runs/qwen35-9b-grpo-probe-aggressive-mb4-step16-n1000-s0
Loading weights: 0%| | 0/427 [00:00<?, ?it/s]
Loading weights: 100%|██████████| 427/427 [00:00<00:00, 4737.50it/s][transformers] The tokenizer has new PAD/BOS/EOS tokens that differ from the model config and generation config. The model config and generation config were aligned accordingly, being updated with the tokenizer's values. Updated tokens: {'eos_token_id': 248046, 'pad_token_id': 248044}.[drift] LoRA enabledtrainable params: 43,278,336 || all params: 8,997,081,600 || trainable%: 0.4810[drift] GRPO prompt-budget audit: {"completion_sequences_per_step": 64, "dataset_unique_prompts": 1000, "num_generations": 8, "scheduled_unique_prompts": 1000, "unique_prompts_per_step": 8}[drift] in-training reward evaluation disabled by config
0%| | 0/125 [00:00<?, ?it/s]
1%| | 1/125 [03:56<8:09:17, 236.75s/it]
2%|▏ | 2/125 [07:00<7:01:21, 205.54s/it]
2%|▏ | 3/125 [10:23<6:55:10, 204.18s/it]
3%|▎ | 4/125 [14:17<7:16:16, 216.33s/it]
3%|▎ | 4/125 [14:17<7:16:16, 216.33s/it]
4%|▍ | 5/125 [18:12<7:25:48, 222.90s/it]
5%|▍ | 6/125 [21:32<7:06:22, 214.98s/it]
6%|▌ | 7/125 [25:12<7:06:09, 216.69s/it]
6%|▋ | 8/125 [28:59<7:09:08, 220.08s/it]
6%|▋ | 8/125 [28:59<7:09:08, 220.08s/it]
7%|▋ | 9/125 [32:36<7:03:44, 219.18s/it]
8%|▊ | 10/125 [35:38<6:37:40, 207.48s/it]
9%|▉ | 11/125 [38:53<6:26:57, 203.67s/it]
10%|▉ | 12/125 [42:51<6:43:32, 214.27s/it]
10%|▉ | 12/125 [42:51<6:43:32, 214.27s/it]
10%|█ | 13/125 [46:35<6:45:31, 217.24s/it]
11%|█ | 14/125 [49:38<6:22:26, 206.73s/it]
12%|█▏ | 15/125 [53:24<6:30:00, 212.73s/it]
13%|█▎ | 16/125 [57:15<6:36:08, 218.06s/it]
13%|█▎ | 16/125 [57:15<6:36:08, 218.06s/it]
14%|█▎ | 17/125 [1:01:29<6:51:58, 228.88s/it]/home/xianglin/miniconda3/lib/python3.14/multiprocessing/resource_tracker.py:475: UserWarning: resource_tracker: There appear to be 1 leaked semaphore objects to clean up at shutdown: {'/loky-206935-rlcqwfn4'} warnings.warn(1234567891011[transformers] The fast path is not available because one of the required library is not installed. Falling back to torch implementation. To install follow https://github.com/fla-org/flash-linear-attention#installation and https://github.com/Dao-AILab/causal-conv1d[hub] authentication OK as xianglinyang; formal checkpoints -> prism-drift/qwen35-9b-m0-v4-grpo-probe-lr1e6-b005-checkpoints[hub] path namespace: base-prism-drift-qwen35-9b-m0-v4--rev-8f3d499236d7/cohort-9c9af61b6edc/grpo/seed-0/checkpoint-<step>[drift] grpo run 'qwen35-9b-grpo-probe-lr1e6-b005-const-mb4-final-n1000-s0' seed=0 -> /ndata/xianglin/ai_drift/runs/qwen35-9b-grpo-probe-lr1e6-b005-const-mb4-final-n1000-s0
Loading weights: 0%| | 0/427 [00:00<?, ?it/s]
Loading weights: 100%|██████████| 427/427 [00:00<00:00, 4590.86it/s][transformers] The tokenizer has new PAD/BOS/EOS tokens that differ from the model config and generation config. The model config and generation config were aligned accordingly, being updated with the tokenizer's values. Updated tokens: {'eos_token_id': 248046, 'pad_token_id': 248044}.[drift] LoRA enabledtrainable params: 43,278,336 || all params: 8,997,081,600 || trainable%: 0.4810[drift] GRPO prompt-budget audit: {"completion_sequences_per_step": 64, "dataset_unique_prompts": 1000, "num_generations": 8, "scheduled_unique_prompts": 1000, "unique_prompts_per_step": 8}[drift] in-training reward evaluation disabled by config
0%| | 0/125 [00:00<?, ?it/s]
1%| | 1/125 [03:49<7:53:59, 229.35s/it]
2%|▏ | 2/125 [06:44<6:44:27, 197.30s/it]
2%|▏ | 3/125 [10:34<7:11:39, 212.29s/it]
3%|▎ | 4/125 [14:35<7:30:51, 223.57s/it]
4%|▍ | 5/125 [18:50<7:49:48, 234.90s/it]
4%|▍ | 5/125 [18:50<7:49:48, 234.90s/it]
5%|▍ | 6/125 [22:30<7:35:51, 229.85s/it]
6%|▌ | 7/125 [25:39<7:05:38, 216.43s/it]
6%|▋ | 8/125 [28:41<6:40:56, 205.61s/it]
7%|▋ | 9/125 [33:03<7:11:53, 223.39s/it]
8%|▊ | 10/125 [37:01<7:16:46, 227.89s/it]
8%|▊ | 10/125 [37:01<7:16:46, 227.89s/it]
9%|▉ | 11/125 [41:03<7:21:11, 232.21s/it]
10%|▉ | 12/125 [44:26<7:00:24, 223.22s/it]
10%|█ | 13/125 [48:53<7:21:34, 236.56s/it]
11%|█ | 14/125 [52:45<7:14:58, 235.12s/it]
12%|█▏ | 15/125 [56:10<6:54:24, 226.04s/it]
12%|█▏ | 15/125 [56:10<6:54:24, 226.04s/it]
13%|█▎ | 16/125 [1:00:06<6:55:59, 228.98s/it]
14%|█▎ | 17/125 [1:04:43<7:18:21, 243.53s/it]12345678910[transformers] The fast path is not available because one of the required library is not installed. Falling back to torch implementation. To install follow https://github.com/fla-org/flash-linear-attention#installation and https://github.com/Dao-AILab/causal-conv1d[drift] grpo run 'qwen35-9b-grpo-probe-r32a64-mb4-step16-n1000-s0' seed=0 -> /ndata/xianglin/ai_drift/runs/qwen35-9b-grpo-probe-r32a64-mb4-step16-n1000-s0
Loading weights: 0%| | 0/427 [00:00<?, ?it/s]
Loading weights: 90%|████████▉ | 384/427 [00:00<00:00, 3824.96it/s]
Loading weights: 100%|██████████| 427/427 [00:00<00:00, 3724.54it/s][transformers] The tokenizer has new PAD/BOS/EOS tokens that differ from the model config and generation config. The model config and generation config were aligned accordingly, being updated with the tokenizer's values. Updated tokens: {'eos_token_id': 248046, 'pad_token_id': 248044}.[drift] LoRA enabledtrainable params: 86,556,672 || all params: 9,040,359,936 || trainable%: 0.9574[drift] GRPO prompt-budget audit: {"completion_sequences_per_step": 64, "dataset_unique_prompts": 1000, "num_generations": 8, "scheduled_unique_prompts": 1000, "unique_prompts_per_step": 8}[drift] in-training reward evaluation disabled by config
0%| | 0/125 [00:00<?, ?it/s]
1%| | 1/125 [03:36<7:27:51, 216.70s/it]
2%|▏ | 2/125 [07:20<7:33:18, 221.13s/it]
2%|▏ | 3/125 [10:51<7:20:15, 216.52s/it]
3%|▎ | 4/125 [14:43<7:28:52, 222.58s/it]
3%|▎ | 4/125 [14:43<7:28:52, 222.58s/it]
4%|▍ | 5/125 [18:41<7:36:06, 228.05s/it]
5%|▍ | 6/125 [22:23<7:28:00, 225.89s/it]
6%|▌ | 7/125 [26:20<7:31:39, 229.66s/it]
6%|▋ | 8/125 [30:17<7:32:26, 232.02s/it]
6%|▋ | 8/125 [30:17<7:32:26, 232.02s/it]
7%|▋ | 9/125 [34:04<7:25:38, 230.51s/it]
8%|▊ | 10/125 [38:04<7:27:00, 233.22s/it]
9%|▉ | 11/125 [41:57<7:23:11, 233.26s/it]
10%|▉ | 12/125 [45:53<7:20:47, 234.05s/it]
10%|▉ | 12/125 [45:53<7:20:47, 234.05s/it]
10%|█ | 13/125 [49:54<7:20:38, 236.06s/it]
11%|█ | 14/125 [53:43<7:12:58, 234.04s/it]
12%|█▏ | 15/125 [57:41<7:11:06, 235.15s/it]
13%|█▎ | 16/125 [1:01:35<7:06:28, 234.75s/it]
13%|█▎ | 16/125 [1:01:35<7:06:28, 234.75s/it]/home/xianglin/miniconda3/lib/python3.14/multiprocessing/resource_tracker.py:475: UserWarning: resource_tracker: There appear to be 1 leaked semaphore objects to clean up at shutdown: {'/loky-711951-mkklmvao'} warnings.warn(123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263{ "schema": "rl_training_run_v1", "status": "complete", "algo": "dpo", "base_model": "/ndata/xianglin/cache/huggingface/hub/models--Qwen--Qwen3.5-4B/snapshots/851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a", "dataset": "/ndata/xianglin/ai_drift/data/rl/v1/cohorts/qwen-qwen3-5-4b--rev-851bf6e806ef--data-fulltests-v2-cleanprompt-len4k-dpo-n1000-s0/artifacts/dpo.jsonl", "dataset_sha256": "dd10034c79383f50747d853673250d55d9f0afedc61cfba969f6e8d72ff23455", "eval_dataset": "/ndata/xianglin/ai_drift/data/rl/v1/sources/qwen-qwen3-5-4b--rev-851bf6e806ef--data-fulltests-v2/nemotron_rl_coding_competitive_dev.jsonl", "eval_dataset_sha256": "bd8e70f4e74d602aed4d8516ce9b1016689c0d87a30648db1f59e6c69344f850", "reward_model": null, "allow_weak_reward_model": false, "seed": 0, "run_name": "qwen35-4b-base-dpo-cleanprompt-len4k-n1000-step125-s0", "use_vllm": false, "vllm_mode": "colocate", "config": "/home/xianglin/git_space/ai-pref-drift/rl_training/configs/dpo_length_clean_4b_base125.yaml", "config_sha256": "147737cfd13b01a5bbdf7fbc2159ced3ac0b0a6da6cccd93e954ec9b2bf3bdaa", "trainer_config": { "algo": "dpo", "max_steps": 125, "save_steps": 4, "logging_steps": 1, "learning_rate": 1e-06, "lr_scheduler_type": "constant_with_warmup", "warmup_steps": 2, "per_device_train_batch_size": 2, "gradient_accumulation_steps": 4, "beta": 0.1, "max_length": 6144, "max_prompt_length": 1024, "eval_reward_enabled": false, "eval_reward_prompts": 0, "eval_reward_samples": 1, "eval_reward_steps": [] }, "lora": { "enabled": true, "r": 16, "alpha": 32, "dropout": 0.0, "bias": "none", "target_modules": "all-linear" }, "hub_archive": { "enabled": false, "repo_id": null, "private": true, "base_model_id": null, "base_revision": null, "cohort_manifest": "/ndata/xianglin/ai_drift/data/rl/v1/cohorts/qwen-qwen3-5-4b--rev-851bf6e806ef--data-fulltests-v2-cleanprompt-len4k-dpo-n1000-s0/manifest.json", "cohort_manifest_sha256": "94386ff193c3d7b72b66dbce85c398c57fcd3bab4d77f2c5a5aedab79708bd16", "keep_local_checkpoints_during_training": 1 }, "global_step": 125, "train_metrics": { "train_runtime": 2526.9157, "train_samples_per_second": 0.396, "train_steps_per_second": 0.049, "total_flos": 7.940894192959488e+16, "train_loss": 0.6921575565338135, "epoch": 1.0 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263{ "schema": "rl_training_run_v1", "status": "complete", "algo": "dpo", "base_model": "/ndata/xianglin/cache/huggingface/hub/models--Qwen--Qwen3.5-4B/snapshots/851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a", "dataset": "/ndata/xianglin/ai_drift/data/rl/v1/sweeps/qwen-qwen3-5-4b--rev-851bf6e806ef--data-fulltests-v2-len4k/dpo_pairs.jsonl", "dataset_sha256": "17a0ebab937505b172d26b0411059856632dc98a6b5fcf3fc57aef0ed4a46ddf", "eval_dataset": null, "eval_dataset_sha256": null, "reward_model": null, "allow_weak_reward_model": false, "seed": 0, "run_name": "qwen35-4b-base-dpo-len4k-v1-n709-step125-s0", "use_vllm": false, "vllm_mode": "colocate", "config": "/home/xianglin/git_space/ai-pref-drift/rl_training/configs/dpo_length_clean_4b_base125.yaml", "config_sha256": "147737cfd13b01a5bbdf7fbc2159ced3ac0b0a6da6cccd93e954ec9b2bf3bdaa", "trainer_config": { "algo": "dpo", "max_steps": 125, "save_steps": 4, "logging_steps": 1, "learning_rate": 1e-06, "lr_scheduler_type": "constant_with_warmup", "warmup_steps": 2, "per_device_train_batch_size": 2, "gradient_accumulation_steps": 4, "beta": 0.1, "max_length": 6144, "max_prompt_length": 1024, "eval_reward_enabled": false, "eval_reward_prompts": 0, "eval_reward_samples": 1, "eval_reward_steps": [] }, "lora": { "enabled": true, "r": 16, "alpha": 32, "dropout": 0.05, "bias": "none", "target_modules": "all-linear" }, "hub_archive": { "enabled": false, "repo_id": null, "private": true, "base_model_id": null, "base_revision": null, "cohort_manifest": null, "cohort_manifest_sha256": null, "keep_local_checkpoints_during_training": 1 }, "global_step": 125, "train_metrics": { "train_runtime": 2215.7426, "train_samples_per_second": 0.451, "train_steps_per_second": 0.056, "total_flos": 7.457979579174912e+16, "train_loss": 0.6899215207099915, "epoch": 1.4056338028169013 }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162{ "schema": "rl_training_run_v1", "status": "running", "algo": "grpo", "base_model": "/ndata/xianglin/cache/huggingface/hub/models--Qwen--Qwen3.5-4B/snapshots/851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a", "dataset": "/ndata/xianglin/ai_drift/data/rl/v1/cohorts/qwen-qwen3-5-4b--rev-851bf6e806ef--data-fulltests-v2-random-n1000-s0/train.jsonl", "dataset_sha256": "be5a6e36ecef87381b263a291ffc1588ad65f8d837c718dae0400d5252f0475f", "eval_dataset": "/ndata/xianglin/ai_drift/data/rl/v1/sources/qwen-qwen3-5-4b--rev-851bf6e806ef--data-fulltests-v2/nemotron_rl_coding_competitive_dev.jsonl", "eval_dataset_sha256": "bd8e70f4e74d602aed4d8516ce9b1016689c0d87a30648db1f59e6c69344f850", "reward_model": null, "allow_weak_reward_model": false, "seed": 0, "run_name": "qwen35-4b-base-grpo-random1000-cleanprompt-len4k-lr5e6-b001-mb4-u20-s0", "use_vllm": false, "vllm_mode": "colocate", "config": "/home/xianglin/git_space/ai-pref-drift/rl_training/configs/grpo_random_4b_base_len4k_largebatch.yaml", "config_sha256": "15839dbb3733e965ce718b3bf6d45750068f186c2f69135a2920c75f5bb8895a", "trainer_config": { "algo": "grpo", "max_steps": 50, "save_steps": 4, "logging_steps": 1, "learning_rate": 5e-06, "lr_scheduler_type": "constant_with_warmup", "warmup_steps": 2, "per_device_train_batch_size": 4, "gradient_accumulation_steps": 40, "beta": 0.01, "num_generations": 8, "generation_batch_size": 160, "unique_prompts_per_step": 20, "expected_unique_prompts": 1000, "max_prompt_length": 1024, "max_completion_length": 4096, "train_max_tests": 12, "reward_num_workers": 32, "reward_timeout": 5.0, "eval_reward_enabled": false, "eval_reward_prompts": 0, "eval_reward_samples": 1, "eval_reward_steps": [], "log_rollouts": true }, "lora": { "enabled": true, "r": 16, "alpha": 32, "dropout": 0.05, "bias": "none", "target_modules": "all-linear" }, "hub_archive": { "enabled": false, "repo_id": null, "private": true, "base_model_id": null, "base_revision": null, "cohort_manifest": "/ndata/xianglin/ai_drift/data/rl/v1/cohorts/qwen-qwen3-5-4b--rev-851bf6e806ef--data-fulltests-v2-random-n1000-s0/manifest.json", "cohort_manifest_sha256": "80b0ed146ec3a99af75f84a29a3c7fdfcc7a9ebf811a596560bb8e8b450032e0", "keep_local_checkpoints_during_training": 1 }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576{ "schema": "rl_training_run_v1", "status": "complete", "algo": "dpo", "base_model": "/ndata/xianglin/cache/huggingface/hub/models--prism-drift--qwen35-4b-m0-v4/snapshots/dca63300371b0265bd7099f87b9eed55937bea22", "dataset": "/ndata/xianglin/ai_drift/data/rl/v1/cohorts/prism-drift-qwen35-4b-m0-v4--rev-dca63300371b--data-fulltests-v2-shared-n1000-s0/artifacts/dpo.jsonl", "dataset_sha256": "e9ed7157881d0df0b25c159ab18c44125049eb6df34c3e95d90394a515a773eb", "eval_dataset": "/ndata/xianglin/ai_drift/data/rl/v1/sources/prism-drift-qwen35-4b-m0-v4--rev-dca63300371b--data-fulltests-v2/nemotron_rl_coding_competitive_dev.jsonl", "eval_dataset_sha256": "bd8e70f4e74d602aed4d8516ce9b1016689c0d87a30648db1f59e6c69344f850", "reward_model": null, "allow_weak_reward_model": false, "seed": 0, "run_name": "qwen35-4b-dpo-m0-v4-formal-n1000-s0", "use_vllm": false, "vllm_mode": "colocate", "config": "/home/xianglin/git_space/ai-pref-drift/rl_training/configs/dpo.yaml", "config_sha256": "defcc2ceb7f1a5707de17e38f00922ea0040745419cde93344a3f55b9880a0f6", "trainer_config": { "algo": "dpo", "max_steps": 125, "save_steps": 4, "logging_steps": 10, "learning_rate": 1e-06, "per_device_train_batch_size": 1, "gradient_accumulation_steps": 8, "beta": 0.05, "max_length": 2048, "max_prompt_length": 1024, "eval_reward_prompts": 64, "eval_reward_samples": 4, "eval_reward_steps": [ 4, 12, 40, 125 ] }, "lora": { "enabled": true, "r": 16, "alpha": 32, "dropout": 0.05, "bias": "none", "target_modules": "all-linear" }, "hub_archive": { "enabled": true, "repo_id": "prism-drift/qwen35-4b-m0-v4-formal-checkpoints", "private": true, "base_model_id": "prism-drift/qwen35-4b-m0-v4", "base_revision": "dca63300371b0265bd7099f87b9eed55937bea22", "cohort_manifest": "/ndata/xianglin/ai_drift/data/rl/v1/cohorts/prism-drift-qwen35-4b-m0-v4--rev-dca63300371b--data-fulltests-v2-shared-n1000-s0/manifest.json", "cohort_manifest_sha256": "25841624829a5f322426ae94317227b2764fac46f2866bf541d58b811c15ef19", "keep_local_checkpoints_during_training": 1 }, "global_step": 125, "train_metrics": { "train_runtime": 8114.458, "train_samples_per_second": 0.123, "train_steps_per_second": 0.015, "total_flos": 5.481732982205645e+16, "train_loss": 0.6916095848083497, "entropy": 0.30109241530299186, "num_tokens": 2189071.0, "logits/chosen": -1.1030423348838745, "logits/rejected": -1.0541350479702023, "mean_token_accuracy": 0.9252372816205024, "rewards/chosen": 0.005071954886079766, "rewards/rejected": -0.014144742659118493, "rewards/accuracies": 0.625, "rewards/margins": 0.019216697599040343, "logps/chosen": -101.77300157546998, "logps/rejected": -240.98444442749025, "epoch": 1.0 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566{ "schema": "rl_training_run_v1", "status": "complete", "algo": "dpo", "base_model": "/ndata/xianglin/cache/huggingface/hub/models--prism-drift--qwen35-4b-m0-v4/snapshots/dca63300371b0265bd7099f87b9eed55937bea22", "dataset": "/ndata/xianglin/ai_drift/elicitation_cache/rl-v4-data/cohorts/prism-drift-qwen35-4b-m0-v4--rev-dca63300371b--data-fulltests-v2-shared-n1000-s0/artifacts/dpo.jsonl", "dataset_sha256": "e9ed7157881d0df0b25c159ab18c44125049eb6df34c3e95d90394a515a773eb", "eval_dataset": "/ndata/xianglin/ai_drift/data/rl/v1/sources/qwen-qwen3-5-4b--rev-851bf6e806ef--data-fulltests-v2/nemotron_rl_coding_competitive_dev.jsonl", "eval_dataset_sha256": "bd8e70f4e74d602aed4d8516ce9b1016689c0d87a30648db1f59e6c69344f850", "reward_model": null, "allow_weak_reward_model": false, "seed": 0, "run_name": "qwen35-4b-dpo-probe-lrup-n1000-s0", "use_vllm": false, "vllm_mode": "colocate", "config": "/home/xianglin/git_space/ai-pref-drift/rl_training/configs/dpo_probe_4b.yaml", "config_sha256": "7a271dfc19ffee5f434e7a9c8e0b4fbc447922c1e0ae2b3fa123efbf4b8a6054", "trainer_config": { "algo": "dpo", "max_steps": 125, "save_steps": 25, "logging_steps": 5, "learning_rate": 1e-05, "per_device_train_batch_size": 8, "gradient_accumulation_steps": 1, "beta": 0.01, "max_length": 2048, "max_prompt_length": 1024, "eval_reward_prompts": 64, "eval_reward_samples": 4, "eval_reward_steps": [ 4, 12, 40, 125 ], "eval_reward_enabled": false }, "lora": { "enabled": true, "r": 16, "alpha": 32, "dropout": 0.05, "bias": "none", "target_modules": "all-linear" }, "hub_archive": { "enabled": false, "repo_id": null, "private": true, "base_model_id": null, "base_revision": null, "cohort_manifest": null, "cohort_manifest_sha256": null, "keep_local_checkpoints_during_training": 1 }, "global_step": 125, "train_metrics": { "train_runtime": 1288.3858, "train_samples_per_second": 0.776, "train_steps_per_second": 0.097, "total_flos": 7.77639526860718e+16, "train_loss": 0.5631999454498291, "epoch": 1.0 }}1234{"step": 4, "eval_reward": 0.2208215983862171}{"step": 12, "eval_reward": 0.24014836565198666}{"step": 40, "eval_reward": 0.199334726209443}{"step": 125, "eval_reward": 0.21864722559168956}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394{ "schema": "rl_training_run_v1", "status": "complete", "algo": "grpo", "base_model": "/ndata/xianglin/cache/huggingface/hub/models--prism-drift--qwen35-4b-m0-v4/snapshots/dca63300371b0265bd7099f87b9eed55937bea22", "dataset": "/ndata/xianglin/ai_drift/data/rl/v1/cohorts/prism-drift-qwen35-4b-m0-v4--rev-dca63300371b--data-fulltests-v2-shared-n1000-s0/train.jsonl", "dataset_sha256": "609640967aa437d754e39c3362f484aeccaeccb7a5895e55ed7a5a1170732c73", "eval_dataset": "/ndata/xianglin/ai_drift/data/rl/v1/sources/prism-drift-qwen35-4b-m0-v4--rev-dca63300371b--data-fulltests-v2/nemotron_rl_coding_competitive_dev.jsonl", "eval_dataset_sha256": "bd8e70f4e74d602aed4d8516ce9b1016689c0d87a30648db1f59e6c69344f850", "reward_model": null, "allow_weak_reward_model": false, "seed": 0, "run_name": "qwen35-4b-grpo-m0-v4-formal-n1000-s0", "use_vllm": false, "vllm_mode": "colocate", "config": "/home/xianglin/git_space/ai-pref-drift/rl_training/configs/grpo.yaml", "config_sha256": "67d77a2d61c5d126d698ef927bd60cecf6c2b691da158b9734b81cf5ac182bc5", "trainer_config": { "algo": "grpo", "max_steps": 125, "save_steps": 4, "logging_steps": 10, "learning_rate": 1e-06, "per_device_train_batch_size": 1, "gradient_accumulation_steps": 64, "beta": 0.05, "num_generations": 8, "generation_batch_size": 64, "unique_prompts_per_step": 8, "expected_unique_prompts": 1000, "max_prompt_length": 1024, "max_completion_length": 1024, "train_max_tests": 12, "reward_num_workers": 0, "reward_timeout": 5.0, "eval_reward_prompts": 64, "eval_reward_samples": 4, "eval_reward_steps": [ 4, 12, 40, 125 ], "log_rollouts": true }, "lora": { "enabled": true, "r": 16, "alpha": 32, "dropout": 0.05, "bias": "none", "target_modules": "all-linear" }, "hub_archive": { "enabled": true, "repo_id": "xianglinyang/qwen35-4b-m0-v4-formal-checkpoints", "private": true, "base_model_id": "prism-drift/qwen35-4b-m0-v4", "base_revision": "dca63300371b0265bd7099f87b9eed55937bea22", "cohort_manifest": "/ndata/xianglin/ai_drift/data/rl/v1/cohorts/prism-drift-qwen35-4b-m0-v4--rev-dca63300371b--data-fulltests-v2-shared-n1000-s0/manifest.json", "cohort_manifest_sha256": "25841624829a5f322426ae94317227b2764fac46f2866bf541d58b811c15ef19", "keep_local_checkpoints_during_training": 1 }, "global_step": 125, "train_metrics": { "train_runtime": 17264.5034, "train_samples_per_second": 0.463, "train_steps_per_second": 0.007, "total_flos": 0.0, "train_loss": 0.06510294103622437, "num_tokens": 8786887.0, "completions/mean_length": 484.625, "completions/min_length": 57.2, "completions/max_length": 1024.0, "completions/clipped_ratio": 0.175, "completions/mean_terminated_length": 373.176513671875, "completions/min_terminated_length": 57.2, "completions/max_terminated_length": 939.6, "rewards/coding_reward/mean": 0.34300347566604616, "rewards/coding_reward/std": 0.39796862602233884, "reward": 0.34300347566604616, "reward_std": 0.39796862602233884, "frac_reward_zero_std": 0.075, "kl": 0.00043241478386164546, "entropy": 0.2898900974774733, "clip_ratio/low_mean": 0.0, "clip_ratio/high_mean": 0.0, "clip_ratio/region_mean": 0.0, "clip_ratio/low_min": 0.0, "clip_ratio/high_max": 0.0, "step_time": 199.8664681014605, "epoch": 1.0 }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374{ "schema": "rl_training_run_v1", "status": "complete", "algo": "dpo", "base_model": "/ndata/xianglin/cache/huggingface/hub/models--prism-drift--qwen35-9b-m0-v4/snapshots/8f3d499236d7b9d38a1f616f6b3241b22a381047", "dataset": "/ndata/xianglin/ai_drift/elicitation_cache/rl-v4-data/cohorts/prism-drift-qwen35-9b-m0-v4--rev-8f3d499236d7--data-fulltests-v2-shared-n1000-s0/artifacts/dpo.jsonl", "dataset_sha256": "2bcd78ad2608d2c1cd5fce0e9439c5bf06e2c27d0a891900a59eafe5328cb514", "eval_dataset": "/ndata/xianglin/ai_drift/data/rl/v1/sources/qwen-qwen3-5-9b--rev-c20223623576--data-fulltests-v2/nemotron_rl_coding_competitive_dev.jsonl", "eval_dataset_sha256": "bd8e70f4e74d602aed4d8516ce9b1016689c0d87a30648db1f59e6c69344f850", "reward_model": null, "allow_weak_reward_model": false, "seed": 0, "run_name": "qwen35-9b-dpo-tuned-v3-noeval-formal-n1000-s0", "use_vllm": false, "vllm_mode": "colocate", "config": "/home/xianglin/git_space/ai-pref-drift/rl_training/configs/dpo_tuned_9b.yaml", "config_sha256": "637e851ef90a156098da08364b6e5b7b354909bd8d676e0a1ac5ae95eb24fc86", "trainer_config": { "algo": "dpo", "max_steps": 125, "save_steps": 4, "logging_steps": 10, "learning_rate": 5e-07, "per_device_train_batch_size": 1, "gradient_accumulation_steps": 8, "beta": 0.1, "max_length": 2560, "max_prompt_length": 1024, "eval_reward_prompts": 64, "eval_reward_samples": 4, "eval_reward_steps": [ 125 ], "eval_reward_enabled": false }, "lora": { "enabled": true, "r": 16, "alpha": 32, "dropout": 0.05, "bias": "none", "target_modules": "q_proj,k_proj,v_proj,o_proj,gate_proj,up_proj,down_proj" }, "hub_archive": { "enabled": true, "repo_id": "prism-drift/qwen35-9b-m0-v4-tuned-noeval-model-only-checkpoints", "private": false, "base_model_id": "prism-drift/qwen35-9b-m0-v4", "base_revision": "8f3d499236d7b9d38a1f616f6b3241b22a381047", "cohort_manifest": "/ndata/xianglin/ai_drift/elicitation_cache/rl-v4-data/cohorts/prism-drift-qwen35-9b-m0-v4--rev-8f3d499236d7--data-fulltests-v2-shared-n1000-s0/manifest.json", "cohort_manifest_sha256": "9c9af61b6edc36a621bd3980e4b246e59f2556bd91d6e994ab13b110856d6cc9", "keep_local_checkpoints_during_training": 1 }, "global_step": 125, "train_metrics": { "train_runtime": 4951.687, "train_samples_per_second": 0.202, "train_steps_per_second": 0.025, "total_flos": 1.3636746167134618e+17, "train_loss": 0.6915602741241456, "entropy": 0.3217525567859411, "num_tokens": 2512574.0, "logits/chosen": -1.9326618638542405, "logits/rejected": -2.08561068467799, "mean_token_accuracy": 0.916305759549141, "rewards/chosen": 0.003379707399290055, "rewards/rejected": -0.04095747038081754, "rewards/accuracies": 0.7, "rewards/margins": 0.04433717735810205, "logps/chosen": -160.92681617736815, "logps/rejected": -342.0299569129944, "epoch": 1.0 }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667{ "schema": "rl_training_run_v1", "status": "running", "algo": "grpo", "base_model": "/ndata/xianglin/cache/huggingface/hub/models--prism-drift--qwen35-9b-m0-v4/snapshots/8f3d499236d7b9d38a1f616f6b3241b22a381047", "dataset": "/ndata/xianglin/ai_drift/elicitation_cache/rl-v4-data/cohorts/prism-drift-qwen35-9b-m0-v4--rev-8f3d499236d7--data-fulltests-v2-shared-n1000-s0/train.jsonl", "dataset_sha256": "9a1f09248b0fba23c01037e7f211f5feac87a86bc704f3c8b9d326fda3f1dc0b", "eval_dataset": "/ndata/xianglin/ai_drift/data/rl/v1/sources/qwen-qwen3-5-9b--rev-c20223623576--data-fulltests-v2/nemotron_rl_coding_competitive_dev.jsonl", "eval_dataset_sha256": "bd8e70f4e74d602aed4d8516ce9b1016689c0d87a30648db1f59e6c69344f850", "reward_model": null, "allow_weak_reward_model": false, "seed": 0, "run_name": "qwen35-9b-grpo-probe-lr1e6-b005-const-mb4-final-n1000-s0", "use_vllm": false, "vllm_mode": "colocate", "config": "/home/xianglin/git_space/ai-pref-drift/rl_training/configs/grpo_probe_9b_mb4.yaml", "config_sha256": "82bb0d6b9c5ac48280bff9f128f8c63a57675e4b0549f6e5d0fda8a57b38c780", "trainer_config": { "algo": "grpo", "max_steps": 125, "save_steps": 4, "logging_steps": 5, "learning_rate": 1e-06, "lr_scheduler_type": "constant_with_warmup", "warmup_steps": 5, "per_device_train_batch_size": 4, "gradient_accumulation_steps": 16, "beta": 0.05, "num_generations": 8, "generation_batch_size": 64, "unique_prompts_per_step": 8, "expected_unique_prompts": 1000, "max_prompt_length": 1024, "max_completion_length": 1536, "train_max_tests": 12, "reward_num_workers": 32, "reward_timeout": 5.0, "eval_reward_prompts": 64, "eval_reward_samples": 4, "eval_reward_steps": [ 4, 12, 40, 125 ], "eval_reward_enabled": false, "log_rollouts": true }, "lora": { "enabled": true, "r": 16, "alpha": 32, "dropout": 0.05, "bias": "none", "target_modules": "all-linear" }, "hub_archive": { "enabled": true, "repo_id": "prism-drift/qwen35-9b-m0-v4-grpo-probe-lr1e6-b005-checkpoints", "private": false, "base_model_id": "prism-drift/qwen35-9b-m0-v4", "base_revision": "8f3d499236d7b9d38a1f616f6b3241b22a381047", "cohort_manifest": "/ndata/xianglin/ai_drift/elicitation_cache/rl-v4-data/cohorts/prism-drift-qwen35-9b-m0-v4--rev-8f3d499236d7--data-fulltests-v2-shared-n1000-s0/manifest.json", "cohort_manifest_sha256": "9c9af61b6edc36a621bd3980e4b246e59f2556bd91d6e994ab13b110856d6cc9", "keep_local_checkpoints_during_training": 1 }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667{ "schema": "rl_training_run_v1", "status": "running", "algo": "grpo", "base_model": "/ndata/xianglin/cache/huggingface/hub/models--prism-drift--qwen35-9b-m0-v4/snapshots/8f3d499236d7b9d38a1f616f6b3241b22a381047", "dataset": "/ndata/xianglin/ai_drift/elicitation_cache/rl-v4-data/cohorts/prism-drift-qwen35-9b-m0-v4--rev-8f3d499236d7--data-fulltests-v2-shared-n1000-s0/train.jsonl", "dataset_sha256": "9a1f09248b0fba23c01037e7f211f5feac87a86bc704f3c8b9d326fda3f1dc0b", "eval_dataset": "/ndata/xianglin/ai_drift/data/rl/v1/sources/qwen-qwen3-5-9b--rev-c20223623576--data-fulltests-v2/nemotron_rl_coding_competitive_dev.jsonl", "eval_dataset_sha256": "bd8e70f4e74d602aed4d8516ce9b1016689c0d87a30648db1f59e6c69344f850", "reward_model": null, "allow_weak_reward_model": false, "seed": 0, "run_name": "qwen35-9b-grpo-probe-r32a64-mb4-step16-n1000-s0", "use_vllm": false, "vllm_mode": "colocate", "config": "/home/xianglin/git_space/ai-pref-drift/rl_training/configs/grpo_probe_9b_r32_mb4.yaml", "config_sha256": "922f8bfdc5a4810c251e4a253696ef6d3370fc71e97030fc64dd4bb7ba0f80d2", "trainer_config": { "algo": "grpo", "max_steps": 125, "save_steps": 4, "logging_steps": 4, "learning_rate": 1e-06, "lr_scheduler_type": "constant_with_warmup", "warmup_steps": 5, "per_device_train_batch_size": 4, "gradient_accumulation_steps": 16, "beta": 0.05, "num_generations": 8, "generation_batch_size": 64, "unique_prompts_per_step": 8, "expected_unique_prompts": 1000, "max_prompt_length": 1024, "max_completion_length": 1536, "train_max_tests": 12, "reward_num_workers": 32, "reward_timeout": 5.0, "eval_reward_prompts": 64, "eval_reward_samples": 4, "eval_reward_steps": [ 4, 12, 40, 125 ], "eval_reward_enabled": false, "log_rollouts": true }, "lora": { "enabled": true, "r": 32, "alpha": 64, "dropout": 0.05, "bias": "none", "target_modules": "all-linear" }, "hub_archive": { "enabled": false, "repo_id": null, "private": true, "base_model_id": null, "base_revision": null, "cohort_manifest": null, "cohort_manifest_sha256": null, "keep_local_checkpoints_during_training": 1 }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495{ "schema": "rl_training_run_v1", "status": "complete", "algo": "grpo", "base_model": "/ndata/xianglin/cache/huggingface/hub/models--prism-drift--qwen35-9b-m0-v4/snapshots/8f3d499236d7b9d38a1f616f6b3241b22a381047", "dataset": "/ndata/xianglin/ai_drift/elicitation_cache/rl-v4-data/cohorts/prism-drift-qwen35-9b-m0-v4--rev-8f3d499236d7--data-fulltests-v2-shared-n1000-s0/train.jsonl", "dataset_sha256": "9a1f09248b0fba23c01037e7f211f5feac87a86bc704f3c8b9d326fda3f1dc0b", "eval_dataset": "/ndata/xianglin/ai_drift/data/rl/v1/sources/qwen-qwen3-5-9b--rev-c20223623576--data-fulltests-v2/nemotron_rl_coding_competitive_dev.jsonl", "eval_dataset_sha256": "bd8e70f4e74d602aed4d8516ce9b1016689c0d87a30648db1f59e6c69344f850", "reward_model": null, "allow_weak_reward_model": false, "seed": 0, "run_name": "qwen35-9b-grpo-tuned-v3-noeval-formal-n1000-s0", "use_vllm": false, "vllm_mode": "colocate", "config": "/home/xianglin/git_space/ai-pref-drift/rl_training/configs/grpo_tuned_9b.yaml", "config_sha256": "fe950e333b91ad812a98cb824e1ca2bde5fbf106a17ac7fd8e5382a059ea2e35", "trainer_config": { "algo": "grpo", "max_steps": 125, "save_steps": 4, "logging_steps": 10, "learning_rate": 5e-07, "per_device_train_batch_size": 1, "gradient_accumulation_steps": 64, "beta": 0.1, "num_generations": 8, "generation_batch_size": 64, "unique_prompts_per_step": 8, "expected_unique_prompts": 1000, "max_prompt_length": 1024, "max_completion_length": 1536, "train_max_tests": 12, "reward_num_workers": 32, "reward_timeout": 5.0, "eval_reward_prompts": 64, "eval_reward_samples": 4, "eval_reward_steps": [ 4, 12, 40, 125 ], "eval_reward_enabled": false, "log_rollouts": true }, "lora": { "enabled": true, "r": 16, "alpha": 32, "dropout": 0.05, "bias": "none", "target_modules": "q_proj,k_proj,v_proj,o_proj,gate_proj,up_proj,down_proj" }, "hub_archive": { "enabled": true, "repo_id": "prism-drift/qwen35-9b-m0-v4-tuned-noeval-model-only-checkpoints", "private": false, "base_model_id": "prism-drift/qwen35-9b-m0-v4", "base_revision": "8f3d499236d7b9d38a1f616f6b3241b22a381047", "cohort_manifest": "/ndata/xianglin/ai_drift/elicitation_cache/rl-v4-data/cohorts/prism-drift-qwen35-9b-m0-v4--rev-8f3d499236d7--data-fulltests-v2-shared-n1000-s0/manifest.json", "cohort_manifest_sha256": "9c9af61b6edc36a621bd3980e4b246e59f2556bd91d6e994ab13b110856d6cc9", "keep_local_checkpoints_during_training": 1 }, "global_step": 125, "train_metrics": { "train_runtime": 50556.6771, "train_samples_per_second": 0.158, "train_steps_per_second": 0.002, "total_flos": 0.0, "train_loss": 0.13397808361053468, "num_tokens": 11494885.0, "completions/mean_length": 888.88125, "completions/min_length": 160.2, "completions/max_length": 1536.0, "completions/clipped_ratio": 0.3, "completions/mean_terminated_length": 615.3835327148438, "completions/min_terminated_length": 160.2, "completions/max_terminated_length": 1450.4, "rewards/coding_reward/mean": 0.45394097566604613, "rewards/coding_reward/std": 0.444728285074234, "reward": 0.45394097566604613, "reward_std": 0.444728285074234, "frac_reward_zero_std": 0.075, "kl": 0.00035842735260303014, "entropy": 0.3263098503695801, "clip_ratio/low_mean": 0.0, "clip_ratio/high_mean": 0.0, "clip_ratio/region_mean": 0.0, "clip_ratio/low_min": 0.0, "clip_ratio/high_max": 0.0, "step_time": 396.31441430766137, "epoch": 1.0 }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364{ "schema": "rl_training_run_v1", "status": "complete", "algo": "ppo", "base_model": "/ndata/xianglin/cache/huggingface/hub/models--prism-drift--qwen35-9b-m0-v4/snapshots/8f3d499236d7b9d38a1f616f6b3241b22a381047", "dataset": "/ndata/xianglin/ai_drift/elicitation_cache/rl-v4-data/cohorts/prism-drift-qwen35-9b-m0-v4--rev-8f3d499236d7--data-fulltests-v2-shared-n1000-s0/train.jsonl", "dataset_sha256": "9a1f09248b0fba23c01037e7f211f5feac87a86bc704f3c8b9d326fda3f1dc0b", "eval_dataset": "/ndata/xianglin/ai_drift/data/rl/v1/sources/qwen-qwen3-5-9b--rev-c20223623576--data-fulltests-v2/nemotron_rl_coding_competitive_dev.jsonl", "eval_dataset_sha256": "bd8e70f4e74d602aed4d8516ce9b1016689c0d87a30648db1f59e6c69344f850", "reward_model": "/ndata/xianglin/ai_drift/runs/qwen35-9b-reward-model-m0-v4-formal-n1000-s0", "allow_weak_reward_model": false, "seed": 0, "run_name": "qwen35-9b-ppo-tuned-v3-noeval-formal-n1000-s0", "use_vllm": false, "vllm_mode": "colocate", "config": "/home/xianglin/git_space/ai-pref-drift/rl_training/configs/ppo_tuned_9b.yaml", "config_sha256": "2efb9e58ee735631ac379ab8ff787d7a41d5a6b0876d11850ae967b326ee00c7", "trainer_config": { "algo": "ppo", "max_steps": 125, "save_steps": 4, "logging_steps": 10, "learning_rate": 5e-07, "max_grad_norm": 1.0, "nonfinite_gradient_skip_limit": 8, "per_device_train_batch_size": 1, "gradient_accumulation_steps": 8, "init_kl_coef": 0.1, "num_ppo_epochs": 4, "max_prompt_length": 1024, "response_length": 1536, "reward_timeout": 5.0, "eval_reward_prompts": 64, "eval_reward_samples": 4, "eval_reward_steps": [ 125 ], "eval_reward_enabled": false }, "lora": { "enabled": true, "r": 16, "alpha": 32, "dropout": 0.05, "bias": "none", "target_modules": "q_proj,k_proj,v_proj,o_proj,gate_proj,up_proj,down_proj" }, "hub_archive": { "enabled": true, "repo_id": "prism-drift/qwen35-9b-m0-v4-tuned-noeval-model-only-checkpoints", "private": false, "base_model_id": "prism-drift/qwen35-9b-m0-v4", "base_revision": "8f3d499236d7b9d38a1f616f6b3241b22a381047", "cohort_manifest": "/ndata/xianglin/ai_drift/elicitation_cache/rl-v4-data/cohorts/prism-drift-qwen35-9b-m0-v4--rev-8f3d499236d7--data-fulltests-v2-shared-n1000-s0/manifest.json", "cohort_manifest_sha256": "9c9af61b6edc36a621bd3980e4b246e59f2556bd91d6e994ab13b110856d6cc9", "keep_local_checkpoints_during_training": 1 }, "global_step": 125, "train_metrics": { "nonfinite_gradient_updates_skipped": 0, "consecutive_nonfinite_gradient_updates": 0, "max_consecutive_nonfinite_gradient_updates": 0 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295# RL Training Debugging Report
Date: 2026-08-26 Status: diagnostic; no robust performance improvement established
## Executive summary
We ran a sequence of DPO, GRPO, and PPO experiments on Qwen3.5 4B and 9B,first from project M0 checkpoints and later directly from the originalQwen/Qwen3.5-4B base model. We varied the learning rate, KL/DPO/GRPOcoefficient, LoRA capacity, batch construction, sequence length, trainingduration, and dataset filtering rules. We also rebuilt the 4B DPO data withfresh Base-model rollouts after determining that the original preferencepairs were tied to M0 and contained substantial truncation and length bias.
The training paths are operational: gradients are non-zero, DPO preferenceaccuracy and margins move, GRPO has non-zero reward variance, PPO can completewith non-finite-gradient guards, and merged adapters contain weights that aredifferent from both the base model and one another. However, these optimizationsignals have not translated into a stable improvement on held-out verifierreward or LiveCodeBench. A few early checkpoints improved small developmentsubsets, but the gains either disappeared on a larger held-out split orreversed on an external benchmark. Later checkpoints often performed worse.
The current evidence is therefore consistent with noisy or mismatchedpreference/reward supervision, checkpoint overtraining, and generation-lengthpathologies rather than a trainer that is simply not updating the model.
## Scope
The experiments covered:
- Models: Qwen3.5 4B and 9B.- Starting points: project M0-v4 checkpoints and the original Qwen3.5 Base.- Algorithms: DPO, GRPO, and PPO.- Main training cohort size: 1,000 prompts.- Evaluation data: NVIDIA Nemotron-RL coding dev/held-out splits and a small LiveCodeBench v6 diagnostic subset.- Checkpoint cadence: every 4 optimizer steps for the later formal and debug runs.- Checkpoint policy: adapter-only artifacts; optimizer, scheduler, and RNG states are intentionally excluded from the shared debug package.
## Experiment progression
### 1. Initial M0-v4 runs
The first formal comparison trained DPO, GRPO, and PPO from the 4B and 9BM0-v4 checkpoints on aligned 1,000-prompt cohorts.
Representative initial configuration:
| Method | LR | Coefficient | LoRA | Length | Batch construction ||---|---:|---:|---:|---:|---|| DPO | 1e-6 | beta=0.05 | r=16, alpha=32 | max length 2,048 | micro-batch 1, grad accumulation 8 || GRPO | 1e-6 | beta=0.05 | r=16, alpha=32 | completion 1,024 | 8 prompts x 8 rollouts || PPO | 1e-6 | initial KL=0.05 | r=16, alpha=32 | response 1,024 | micro-batch 1, grad accumulation 8 |
The four checkpoint-time verifier estimates at steps 4, 12, 40, and 125 werenon-monotonic. For example:
- 4B DPO: 0.2156, 0.2128, 0.2406, 0.2156.- 4B GRPO: 0.2208, 0.2401, 0.1993, 0.2186.- 9B GRPO: 0.2554, 0.2346, 0.2376, 0.2387.- 9B PPO: 0.2450, 0.2328, 0.2542, 0.2257.
These are noisy checkpoint estimates rather than a fixed, large held-outevaluation, but they show that training reward did not rise consistently.
PPO additionally encountered non-finite gradients late in the 4B run. Thepath was instrumented with finite-loss/gradient diagnostics and guarded updateskipping. The recovered run completed 125 steps after skipping eightnon-finite updates, but this established plumbing robustness, not a reliableperformance gain.
### 2. Hyperparameter probes
The explored ranges included:
- Learning rate: 5e-7, 1e-6, 5e-6, and 1e-5.- DPO/GRPO beta: 0.01, 0.05, and 0.1.- PPO initial KL coefficient: 0.05 and 0.1.- LoRA capacity: r=16/alpha=32 and r=32/alpha=64.- Micro-batch size: 1, 2, 4, and 8, with gradient accumulation adjusted to retain the intended effective batch.- Schedules: default decay and constant-with-warmup variants.- GRPO completion length: 1,024, 1,536, and 4,096.- DPO maximum sequence length: 2,048, 2,560, and 6,144.- Early stopping/checkpoint selection at steps 4, 8, 12, 16, 28, and 40, versus training through step 125.
The 9B tuned formal configuration lowered the learning rate to 5e-7, increasedDPO/GRPO beta or PPO initial KL to 0.1, and increased the DPO/rollout length to2,560/1,536. Training completed, but it did not establish a robust held-outgain.
For faster GRPO diagnosis, we then compared three 9B step-16 probes:
- Default probe: LR=1e-6, beta=0.05, r=16/alpha=32.- Aggressive probe: LR=5e-6, beta=0.01, r=16/alpha=32.- Higher-capacity probe: LR=1e-6, beta=0.05, r=32/alpha=64.
On one fixed 100-prompt held-out diagnostic, the r=32/alpha=64 checkpoint wasthe strongest of these probes:
| Model | Mean test-case pass fraction | Strict full-pass rate ||---|---:|---:|| 9B M0 | 22.42% | 16% || 9B GRPO r32/alpha64 step 16 | 24.48% | 20% |
The mean improvement was +2.05 percentage points, but its bootstrap intervalfor partial reward crossed zero. The strict-rate interval was positive on thissmall sample, so this checkpoint is useful for debugging but is not sufficientevidence of a general improvement.
A 4B high-LR DPO probe (LR=1e-5, beta=0.01, r=16/alpha=32) substantiallychanged the training objective: the aggregate train loss was 0.563 and latemini-batch preference accuracies reached 0.8-0.9. This showed that a strongeroptimizer setting can fit the preference pairs, but no corresponding robusttask-performance gain was established.
Increasing batch size primarily improved throughput. It did not by itselfresolve the performance problem.
### 3. Removing truncated and length-confounded DPO pairs
The original M0-derived DPO artifacts each contained 1,000 pairs. We removedpairs whose chosen or rejected response was near the generation cap andcontrolled response-length mismatch. This left:
- 4B M0: 433 length-clean pairs.- 9B M0: 245 length-clean pairs.
The 4B M0 length-clean run degraded relative to M0 across most earlycheckpoints. The 9B run produced a promising but unstable early result:
| Evaluation | Baseline | Checkpoint | Partial reward | Strict full pass ||---|---:|---:|---:|---:|| 9B dev, 250 prompts | M0 | step 8 | 35.13% -> 38.51% | 25.2% -> 29.2% || 9B held-out, 500 prompts | M0 | step 12 | 33.49% -> 31.48% | 25.4% -> 22.6% |
Thus, filtering removed a real confounder but did not produce a stablegeneralization gain. The apparent early dev improvement reversed on the largerheld-out evaluation.
### 4. Switching from M0 to the original Base model
The original preference data was generated and selected around M0 behavior.We therefore restarted from Qwen/Qwen3.5-4B and regenerated the DPO pairs.
The first Base rollout reused the old 1,000-prompt cohort:
- 8 samples per prompt.- Temperature 1.0.- Maximum completion length 4,096.- Truncation buffer 24 tokens.- Maximum chosen/rejected token-count difference 512.- Minimum reward margin 0.5.- 709 valid pairs were retained.
After correcting the prompt pipeline, a larger Base-model sweep processed3,081 candidate prompts from the NVIDIA training pool with the same K=8 and4,096-token rollout settings. It produced 1,174 eligible pairs, from which afixed 1,000-pair DPO cohort was frozen.
This final dataset addressed both the M0-conditioned selection issue and theknown training-pair truncation/length confound.
### 5. Final 4B Base DPO run
Final configuration:
| Parameter | Value ||---|---|| Base model | Qwen/Qwen3.5-4B, revision 851bf6e806ef... || Training pairs | 1,000 Base-generated, clean-prompt pairs || Learning rate | 1e-6 || Scheduler | constant with 2 warmup steps || DPO beta | 0.1 || LoRA | r=16, alpha=32, dropout=0 || Effective batch | 8 (micro-batch 2 x accumulation 4) || Maximum sequence length | 6,144 || Maximum prompt length | 1,024 || Training duration | 125 steps || Save interval | 4 steps |
The run completed in 2,527 seconds with aggregate train loss 0.6922. At step125, the logged mini-batch loss was 0.6631 and preference accuracy was 0.625.This is a weak but non-zero optimization signal.
#### NVIDIA held-out diagnostic: 100 fixed prompts
The same 100 prompts were evaluated for Base, step 28, and step 125 with onedeterministic rollout and an 8,192-token completion cap.
| Model | Mean test-case pass fraction | Strict full-pass rate | Non-zero reward | Truncation ||---|---:|---:|---:|---:|| Base | 29.62% | 22% | 43% | 49% || Step 28 | 32.44% | 22% | 48% | 43% || Step 125 | 27.06% | 17% | 46% | 44% |
Step 28 improved partial reward by +2.82 percentage points relative to Base,with paired bootstrap 95% interval [+0.05, +6.30]. It did not increase thenumber of fully solved prompts. Step 125 was worse than Base by 2.55 points inpartial reward and 5 points in strict full-pass rate.
The 43-49% truncation rates remain a major validity problem even at an 8Kcompletion cap. These numbers must therefore be treated as provisional.
#### LiveCodeBench v6 diagnostic: 20 fixed problems
The same first 20 sorted release-v6 problems were run with n=1, temperature 0,a 32,768-token completion budget, and merged adapters.
| Model | pass@1 | Truncation ||---|---:|---:|| Base | 11/20 (55%) | 0% || Step 28 | 8/20 (40%) | 10% || Step 125 | 10/20 (50%) | 0% |
The held-out partial-reward signal at step 28 did not reproduce on this smallexternal benchmark. The sample is too small for a definitive benchmark claim,but it provides no support for selecting step 28 as a generally better codingmodel.
The evaluation loader was also fixed during this stage. Qwen3.5 PEFT adaptersare merged into the language tower and then placed back into the full Qwen3.5container before direct vLLM evaluation. Tensor-level checks confirmed thatBase, step 28, and step 125 used distinct weights.
### 6. Base-model GRPO attempt
A separate 4B Base GRPO experiment randomly sampled 1,000 prompts rather thanusing the old M0-selected subset. Its main configuration was LR=5e-6,beta=0.01, K=8, 20 unique prompts per step, 4,096-token completions, and alarger batch/accumulation arrangement to use the available H200 efficiently.The run was stopped after step 39 when priority shifted to DPO rollout and DPOtraining. It is incomplete and should not be interpreted as a negative GRPOresult.
## Interpretation
The experiments rule out several simple explanations:
- The adapters are not identical to Base; the weights genuinely changed.- The trainers are not completely signal-free; gradients, DPO margins, GRPO reward variance, and preference accuracy move.- The problem is not solved by a single learning-rate, beta, batch-size, or LoRA-rank change.- Removing obviously truncated pairs is necessary but not sufficient.- Training longer is not consistently beneficial; early checkpoints are often better than step 125.
The remaining leading hypotheses are:
1. Preference-pair noise or mismatch between pair selection and the final full-verifier objective.2. A weak/sparse reward signal that is easy to fit locally but does not improve complete solutions.3. Length and termination behavior that remains pathological at evaluation time, even after cleaning the training pairs.4. Overtraining on a 1,000-prompt cohort, especially after the earliest useful updates.5. Evaluation variance from single-rollout measurements and small benchmark subsets.
## Recommended next diagnostics
1. Inspect paired Base/step-28 generations on prompts where partial reward changed, separating real algorithmic improvements from formatting or termination effects.2. Evaluate Base and early checkpoints with multiple rollouts per prompt and a termination policy that eliminates cap-driven censoring.3. Audit the verifier-derived DPO pairs for semantic correctness, not only reward margin and length validity.4. Compare gradient/update scale and KL-to-Base across steps 4-32 to determine whether useful behavior is overwritten later.5. Run a larger LiveCodeBench subset only after the termination behavior is controlled.
## Shared artifact selection
The accompanying Hugging Face debug repository contains representativeadapter-only checkpoints rather than every saved point:
- 4B Base DPO clean-prompt: steps 28 and 125.- 9B length-clean DPO: steps 8 and 12, capturing the early-dev improvement and subsequent held-out reversal.- 9B GRPO step-16 probes: default, aggressive LR/beta, and r32/alpha64.- Run metadata, trainer states, selected reward logs, evaluation summaries, configs, and the relevant training/evaluation utility code.
Optimizer, scheduler, RNG, duplicated reference adapters, tokenizer copies,rollout text dumps, and full merged-model evaluation caches are intentionallyexcluded.ARTIFACT_INDEX.mdAdded+42
README.mdAdded+311
SHA256SUMSAdded+115
code/build_dpo_pairs.pyAdded+644
code/evaluate_heldout_reward.pyAdded+346
code/evaluate_livecodebench.pyAdded+331
code/filter_dpo_pairs.pyAdded+302
code/merge_adapter_for_eval.pyAdded+106
code/prompts.pyAdded+68
code/rewards.pyAdded+360
code/train_rl.pyAdded+1131
configs/dpo.yamlAdded+29
configs/dpo_length_clean_4b.yamlAdded+24
configs/dpo_length_clean_4b_base125.yamlAdded+28
configs/dpo_length_clean_9b.yamlAdded+23
configs/dpo_probe_4b.yamlAdded+35
configs/dpo_tuned_9b.yamlAdded+26
configs/grpo.yamlAdded+56
configs/grpo_probe_4b.yamlAdded+63
configs/grpo_probe_9b.yamlAdded+35
configs/grpo_probe_9b_aggressive_mb4.yamlAdded+30
configs/grpo_probe_9b_mb1.yamlAdded+30
configs/grpo_probe_9b_mb4.yamlAdded+30
configs/grpo_probe_9b_mb8.yamlAdded+30
configs/grpo_probe_9b_r32_mb4.yamlAdded+31
configs/grpo_random_4b_base_len4k.yamlAdded+34
configs/grpo_random_4b_base_len4k_largebatch.yamlAdded+31
configs/grpo_tuned_4b.yamlAdded+32
configs/grpo_tuned_9b.yamlAdded+32
configs/ppo.yamlAdded+33
configs/ppo_tuned_9b.yamlAdded+29
logs/formal-4b-after-dpo-v4.logAdded
logs/formal-4b-dpo-v4.logAdded
logs/formal-9b-sequence-v4.logAdded
logs/grpo-9b-probe-aggressive-mb4-step16.logAdded+10
logs/grpo-9b-probe-lr1e6-b005-const-mb4-final.logAdded+11
logs/grpo-9b-probe-r32a64-mb4-step16.logAdded+10
metadata/runs/qwen35-4b-base-dpo-cleanprompt-len4k-n1000-step125-s0/run_metadata.jsonAdded+63
metadata/runs/qwen35-4b-base-dpo-len4k-v1-n709-step125-s0/run_metadata.jsonAdded+63
metadata/runs/qwen35-4b-base-grpo-random1000-cleanprompt-len4k-lr5e6-b001-mb4-u20-s0-stopped-step39/run_metadata.jsonAdded+62
metadata/runs/qwen35-4b-dpo-m0-v4-formal-n1000-s0/run_metadata.jsonAdded+76
metadata/runs/qwen35-4b-dpo-probe-lrup-n1000-s0/run_metadata.jsonAdded+66
metadata/runs/qwen35-4b-grpo-m0-v4-formal-n1000-s0/reward_log.jsonlAdded+4
metadata/runs/qwen35-4b-grpo-m0-v4-formal-n1000-s0/run_metadata.jsonAdded+94
metadata/runs/qwen35-9b-dpo-tuned-v3-noeval-formal-n1000-s0/run_metadata.jsonAdded+74
metadata/runs/qwen35-9b-grpo-probe-lr1e6-b005-const-mb4-final-n1000-s0/run_metadata.jsonAdded+67
metadata/runs/qwen35-9b-grpo-probe-r32a64-mb4-step16-n1000-s0/run_metadata.jsonAdded+67
metadata/runs/qwen35-9b-grpo-tuned-v3-noeval-formal-n1000-s0/run_metadata.jsonAdded+95
metadata/runs/qwen35-9b-ppo-tuned-v3-noeval-formal-n1000-s0/run_metadata.jsonAdded+64
reports/rl_training_debug_report.mdAdded+295