CLI Reference¶
All commands available through the palingenesis entry point.
pgs train, pgs fit, pgs prepare and pgs distill take overrides of single options as --section.option value (for example --train.learning_rate 1e-5); the options are in the configuration reference.
| I want to | Command |
|---|---|
| start from an example config | pgs init |
| train (SFT, DPO, off-policy distillation, LoRA) | pgs train |
| know whether a config fits in memory | pgs profile |
| find the fastest memory setting that fits | pgs fit |
| check data, masking and config before a run | pgs diagnose, pgs inspect, pgs validate |
| follow a running training | pgs monitor, pgs loss |
| read what RL / distillation rollouts do | pgs rollouts |
| evaluate a checkpoint on tasks (GSM8K, MATH-500, MMLU-Pro, IFEval, function calling, my own) | pgs eval |
| compare two checkpoints' evaluations (intervals, paired tests, pass@k) | pgs compare |
| keep the RL prompts the policy solves sometimes | pgs screen |
| find, audit or run an RL / evaluation environment | pgs env |
| build or check contrastive twin preference pairs | pgs pairs |
| on-policy distillation / RL | pgs distill, pgs rl |
Commands¶
init¶
Write a shipped example config to start from (works after pip install, no checkout needed).
pgs init --list # sft, dpo, distill, kd, lora, rl
pgs init sft # ./sft.yaml
pgs init rl my_rl.yaml # another file name (--force overwrites)
train¶
The main training command. Usually launched via torchrun for proper distributed setup.
Equivalent to:
pgs scenario validates, generates, audits and exports multi-role RL data and plans a cluster layout (pgs scenario patterns | check | list | generate | audit | export | plan; Multi-Agent RL); training on a scenario is pgs rl with a scenario: section. pgs scenario patterns lists the patterns that run on an ordinary RL dataset with their row fields and options; pgs scenario check --config rl.yaml [--n N] [--json] checks that dataset against the config's pattern (fields, rewards, one rendered prompt per role) and runs the audit on its rows (exit 1 on a failure).
LoRA is a trainer plugin of pgs train, not a separate command: pgs init lora, then pgs train --config lora.yaml (LoRA guide). In pgs rl it is the config's lora: section (LoRA in RL).
distill¶
On-policy distillation: the student samples with its current weights, each prompt's teacher scores those exact tokens, and the student is pulled toward the teacher's distribution (full-vocabulary reverse KL for a teacher sharing the student's vocabulary, byte-aligned chunks across different tokenizers). Rollouts come from the trainer's own generate or from vLLM (rollout.backend); teachers run in-process or on a vLLM server; several teachers can each take their own prompt sources. Overrides: --section.option value, and --teachers.<name>.option / --sources.<name>.option for the named mappings.
pgs distill --config configs/distill_math.yaml # Qwen3-1.7B -> Qwen3-0.6B, vLLM rollouts
pgs distill --config configs/distill_xtok.yaml # teacher with another tokenizer
pgs distill --config configs/distill_multi.yaml # one teacher per prompt source
pgs distill --config configs/distill_math.yaml --train.learning_rate 1e-6 --teachers.qwen3_1_7b.backend vllm
See the On-Policy Distillation guide.
Off-policy distillation (fixed data, the teacher's distributions as targets) is a mode of pgs train: distill.enabled: true (pgs init kd). See the Off-Policy Distillation guide.
distill-cache¶
Precompute a teacher's top-k log-probabilities at every trained position of the training config's data, for off-policy distillation against a teacher you cannot run every step. The cache is content-addressed (found by each document's tokens and mask, whatever the order, packing or rank count), sharded, memory-mapped, resumable, and checked against the student's vocabulary.
pgs distill-cache --config kd.yaml --teacher big --out caches/big --top_k 64 # HF teacher
torchrun --nproc_per_node 8 -m palingenesis.distill.build --config kd.yaml --teacher big
pgs distill-cache --config kd.yaml --teacher big --backend vllm --tensor_parallel_size 4
Options: --teacher (a name in distill.teachers with a model), --out (default: the teacher's cache), --backend hf|vllm, --top_k, --temperature (hf), --max_batch_tokens, --max_docs, --lp_dtype float16|float32, --gpu_memory_utilization and --tensor_parallel_size (vllm), and --section.option value overrides of the config.
distill-score¶
Annotate a multiple-choice pool with its teacher's own answers (teacher_answer, teacher_correct) so you can filter or reweight before training — pure KL distills the teacher's errors too. One batched forward per row, no generation. Scores the first mcqa source (or --source NAME) with that source's teacher; accepts the same overrides as distill.
rl¶
Reinforcement learning: groups of rollouts scored by rewards (checked answers, tests, judges, environments), one policy-gradient step per batch. See the Reinforcement Learning guide.
env¶
The environment catalogue: built-in environments and those other packages register (entry-point group palingenesis.environments). See Environments.
pgs env list [--family tool-calling] [--trainable | --eval-only] [--permissive] [--json]
pgs env info text-to-sql [--json] # data, tools, verifier, sandbox, licence, an example prompt, RL config lines
pgs env test text-to-sql [--n 32] [--seed 0] [--dataset D] [--json] # or several names, or --all; exit 1 on a failure
pgs env run text-to-sql --model runs/sft/final --k 4 [--n 64] [--output results.jsonl] [--json]
pgs env rows text-to-sql --n 2000 --seed 1 -o rows.jsonl [--option difficulty=3]
pgs env new acme/my-env [--dir .] [--family other]
A name is a registered environment, or module:SPEC / path/to/file.py:SPEC for one under development.
testis the audit: the entry's oracle policy must pass every row, its degenerate policies (plus an empty reply, a refusal, the prompt repeated and tool spam) no more than the entry's chance level, and the oracle again on reused instances. Reward-hacking holes are listed with the policy and the first row it passes. No model, no GPU.runplays k episodes per row with a model through the RL rollout loop and reports pass@1, pass@k, the mean reward, finish reasons, the tool error rate and episodes/s. Options:--backend vllm | sglang | hf,--temperature(0.7),--top_p,--top_k,--thinking on | off | default,--dataset(a dataset of the entry or a file of rows),--option key=value(generator options),--max_turns,--max_new_tokens,--max_model_len,--max_concurrent,--tool_timeout,--gpu_memory_utilization,--env_args '{...}',--sandbox docker | process | agent_sandbox(code environments; default docker).--outputwrites per-row results thatpgs comparereads.rowswrites rows forpgs rland prints theenv:/data:/rollout:lines of the config. Evaluation-only entries are refused unless--allow-eval-only.newwrites a package skeleton: the environment, itsEnvSpec, the entry point, and a test that runs the audit.
harbor¶
Harbor task directories (one Docker environment with tests per task). See Harbor Environments.
pgs harbor check data/harbor_tasks [--workers 8] [--json] [--workdir /app] # oracle must pass, nop must not; exit 1 if any task is invalid
pgs harbor rows data/harbor_tasks data/harbor_rows.jsonl [--no-system] # training rows {task_dir, messages}
harness¶
Harness profiles for Harbor tasks: list them, and record what a real agent harness sends to its model. See Harness Profiles.
pgs harness profiles # built-in profiles and their sources
pgs harness serve --script turns.json --out requests.jsonl [--port 8000] [--model NAME]
pgs harness capture opencode --task task_steps/ --script turns.json --out captures/opencode [--harbor 0.24.0]
quantize¶
Post-training FP4 / FP8 quantisation (round to nearest, max or MSE-optimal scales) into the compressed-tensors checkpoint vLLM loads, and optionally its dequantized bf16 twin. See Quantisation-Aware Training.
pgs quantize --model Qwen/Qwen3.5-0.8B --format nvfp4 --scales mse --out ptq-nvfp4 [--dequantized ptq-nvfp4-bf16]
pgs quantize --model M --format fp8 --activations fp8 --out m-fp8 # W8A8, dynamic per-token activations
pgs quantize --model M --format nvfp4 --activations nvfp4 --calibration texts.txt --out m-w4a4
Options: --format {nvfp4,mxfp4,fp8,fp8_block}, --activations {none,fp8,nvfp4,mxfp4}, --scales {max,mse},
--mx_rounding {floor,even,ceil}, --exclude REGEX ..., --calibration FILE (NVFP4 activations' static scale),
--device. Prints one JSON line (layers, mean and max relative weight error).
merge¶
Weight-space merging of checkpoints that share an architecture. See Model Merging.
pgs merge interpolate START END --lam 0.3 -o OUT # START + lam (END - START)
pgs merge linear A:0.7 B:0.3 -o OUT # weights sum to 1 (--unnormalized to allow others)
pgs merge soup A B C -o OUT # mean
pgs merge task-arithmetic --base BASE A:1 B:0.3 -o OUT # BASE + sum l_i (W_i - BASE)
pgs merge model-stock --base BASE A B C -o OUT # BASE + t (mean - BASE), t per tensor from agreement
pgs merge ram --base BASE A B -o OUT # unique changes kept whole, shared ones averaged
pgs merge materialize CKPT --template EXPORT -o OUT # complete a partial checkpoint
Common options: --template (tensor set, layout, dtype and files of the output), --missing {error,template},
--dtype {bf16,fp16,fp32}, --rounding {nearest,stochastic} and --seed (stochastic rounding keeps edits below
one bf16 ulp; see Precision of small edits), --overwrite.
surgery¶
Margin surgery: a minimal-norm weight edit that moves a decision's margins back to target values. See Margin Surgery.
pgs surgery run --config surgery.yaml [--set trust=0.2 --set families.cont.groups=8] [--overwrite]
pgs surgery margins --model REF --model CUR --twins TWINS.jsonl --decision "<tool_call>" [--prefix-side pos|neg|both]
pgs surgery span --model CUR --groups TWINS.jsonl --targets TARGET.jsonl --decision "<|im_end|>" --k 1,4,16
margins prints mean / SE / greedy share per model (common and differential with both); span prints the fraction
of the target set's margin gradient inside the span of K group gradients. Common options: --micro-batch,
--max-side-tokens, --dtype, --device, --limit, --json.
internals¶
Read a model's internals: residual-stream capture, linear probes per layer, logit / tuned lens, checkpoint comparison, steering, ablation and activation patching. See Reading Model Internals.
pgs internals run --config internals.yaml [--set layers=12-20] [--overwrite]
pgs internals capture --model M --data rows.jsonl --out acts/m [--position last_prompt] [--layers all] [--store-dtype bfloat16]
pgs internals probe --acts acts/m --out probes/m [--test it=acts/m_it] [--kind logistic|diffmean|lda] [--bootstrap 1000]
pgs internals compare --a acts/base --b acts/sft
pgs internals lens --model M --data chats.jsonl [--position assistant_all] [--decision "<tool_call>"] [--tuned lens.safetensors]
pgs internals tuned-lens --model M --data chats.jsonl --out lens.safetensors [--steps 250]
pgs internals causal --model M --probe probes/m/best.safetensors --data rows.jsonl --decision TOKEN [--alphas -2,-1,0,1,2]
pgs internals patch --model M --twins twins.jsonl --decision "<tool_call>" [--offsets -1,-2,-3] [--mode denoise|noise]
pgs internals steer --model M --probe P --prompt "..." [--alpha 0,1,2] [--positions all|last_and_new]
pgs internals score --probe P --data rows.jsonl --out scored.jsonl [--column known] [--gate fpr_0.05]
Model options: --dtype, --device, --chat-template-kwargs '{"enable_thinking": false}', --batch-size,
--max-tokens (longer rows are dropped), --limit (the last three on every command that reads a data file). Most
commands take --json.
autopilot¶
Zero-config autonomous training. Profiles hardware, sweeps LR, trains to completion.
prepare¶
Clean training data with the tokenizer alone: drop the rows training would drop and exact duplicates, hold out an eval set that shares no prompt with the training data, cap sources, select a row or token budget. Dumps parquet (default) or jsonl, a prepared_meta.json report and dropped.jsonl (every removed row with its reason).
Reads the same YAML as training — tokenizer, dataset, masking options and the preprocess: section all come from one file, and the usual --section.field overrides apply:
pgs prepare --config configs/qwen35_4b/a100_80gb.yaml
pgs prepare --config cfg.yaml --preprocess.eval_holdout 200 --preprocess.budget 5000
Afterwards, training consumes the output automatically:
pgs prepare --model Qwen/Qwen3.5-4B --data raw.jsonl --output prepared/ \
--eval_holdout 200 --max_per_prompt 2 --group_field source --max_per_group 20000
| Flag | Meaning |
|---|---|
--no_dedupe |
Keep exact duplicates |
--max_per_prompt N |
At most N rows that share a prompt |
--group_field F, --max_per_group N, --max_tokens_per_group N |
Caps per value of column F |
--eval_holdout N |
Held-out eval set |
--budget N, --token_budget N |
Random subset of N rows / N tokens |
--score, --min_ppl, --max_ppl, --strategy, --hes |
Scoring with the model: experimental, off by default |
Raw text (mode: pretrain sources) is cleaned without a model:
pgs prepare --data raw_corpus.jsonl --output prepared/corpus --mode pretrain \
--near_dedupe 0.8 --decontaminate benchmarks/*.jsonl --min_chars 200 --eval_holdout 500
| Flag | Raw text (--mode pretrain) |
|---|---|
--text_field |
The text column (default text) |
--no_dedupe |
Keep exact duplicate documents (same text up to case and whitespace) |
--near_dedupe T |
Drop near-duplicates at or above Jaccard similarity T of the word 5-gram sets (MinHash; 0 = off) |
--decontaminate FILE..., --decontaminate_ngram N, --decontaminate_fields COL... |
Drop documents sharing an N-word n-gram (default 13) with the evaluation files (every string column, or the named ones) |
--decontaminate_shared_share S |
N-grams in more than share S of an evaluation file's rows are not matched (default 0.2, off with --decontaminate_fields; 0 = match all) |
--min_chars N |
Drop documents shorter than N characters |
--eval_holdout N |
Hold out N whole documents, drawn after deduplication (eval_data.*) |
--model |
Optional: only to report token counts |
pgs prepare --config cpt.yaml does the same for every mode: pretrain entry of data.sources, with the options of the preprocess section. See the pretraining guide.
See the Data Preparation guide for the full workflow.
prepare-multi¶
Prepares each source of a sources file on its own and writes manifest.json with every source's rows, tokens and share of examples and of tokens at its weight. Raw-text sources (mode: pretrain) are cleaned like pgs prepare --mode pretrain: --decontaminate, --decontaminate_ngram, --decontaminate_fields, --near_dedupe and --min_chars apply to them (dedupe, near_dedupe, min_chars, eval_holdout, max_samples and seed can also be set per source).
diagnose¶
Run pre/post-training health checks.
inspect¶
Show tokenization and masking for sample data.
validate¶
Validate masking correctness across many samples.
profile¶
Memory for a config: parameters, optimizer states and gradients exactly, activations roughly. --measure runs two real optimizer steps on the GPU and reports the true peak.
fit¶
Measure the fastest memory settings (activation checkpointing mode, SeCO chunk size) that fit a memory budget, with the real trainer on worst-case rows (every row at data.max_seq_length), each setting in its own process. The report gives the peak and the throughput of each setting and recommends the fastest one under the budget, as command-line options and config lines; exit code 1 when none fits.
pgs fit --config config.yaml # budget: this GPU
pgs fit --config config.yaml --gpu 24 # budget: 24 GiB
pgs fit --config config.yaml --first-fit # stop at the first setting that fits
| Option | Default | Meaning |
|---|---|---|
--gpu |
this GPU's memory (on a GPU that shares the host's RAM, such as DGX Spark: the host memory available now) | budget in GiB |
--headroom |
0.92 |
share of the budget the measured peak may use |
--steps |
3 |
optimizer steps per setting (the last one is timed) |
--first-fit |
off | stop at the first setting that fits |
--json |
off | print the report as JSON |
What it measures and how to read it: Single GPU: trading speed for memory.
monitor¶
Check status of a running training from its log file (pgs train, pgs rl and pgs distill logs alike).
loss¶
Analyze a training loss curve.
rollouts¶
Read the trajectory dumps of pgs rl / pgs distill (logging.dump_trajectories): finish-reason shares (stop / length / turn limit), reward components, tool error rates and latency per tool, the loop share, the slowest turns and tool calls, the worst trajectories. Exit code 1 when an alarm fires (--threshold name=value moves one). See Observability.
eval¶
Evaluate a checkpoint on tasks defined in YAML (ours, or task files of lm-evaluation-harness) with the prompt rendering, chat template arguments, tool-call parsing, environments and rewards of training. One engine serves the run; single-turn tasks are submitted at once and scored while the engine generates; multiple choice is scored by log-likelihood with one prefill per question. Each task and thinking mode is one result, written in the pgs compare format. See the Evaluation guide.
pgs eval --model runs/sft/final --suite core # the curated suite: a table, summary.json, report.md
pgs eval --model runs/sft/final --tasks gsm8k,math500 --k 4 --modes plain,think --out eval/sft
pgs eval --model runs/sft/final --tasks path/to/lm_eval/tasks/gsm8k/gsm8k.yaml # an lm-eval task file
pgs eval --config eval.yaml # model, engine, run, sampling, modes, tasks
pgs eval --model runs/sft/final --tasks my_task.yaml,mmlu_pro --limit 500 --temperature 0.7 --top_p 0.8 --top_k 20
pgs eval --list # built-in tasks and suites
| Option | |
|---|---|
--model |
the checkpoint (a Hugging Face id or a path) |
--tasks |
comma-separated built-in names or task YAML files (ours or lm-eval's; globs expand) |
--suite |
a built-in suite (core, quick, multilingual, loglikelihood) or a suite YAML file |
--template |
chat or completion (raw text) for every task; default: the task's own (lm-eval tasks: completion) |
--num_fewshot |
lm-eval tasks: few-shot examples (default: the task's) |
--k |
samples per item (default 1) |
--modes |
thinking modes, each a separate result: default (the template's own), plain (enable_thinking: false), think (enable_thinking: true), or modes the config defines |
--out |
the output directory (default eval_results) |
--limit, --head |
items per task: a fixed-seed sample, the same for every checkpoint; --head keeps the first items instead (lm-eval's --limit) |
--replicas, --devices |
engines per GPU; the GPUs (default: one engine on each visible GPU) |
--score_workers |
scorer processes (-1 automatic, 0 threads) |
--cache_dir, --no_cache |
the generation cache (default ~/.cache/palingenesis/eval, or $PGS_EVAL_CACHE) |
--contamination |
training data files or directories: n-gram overlap with the prompts |
--categories |
per-category lines in the table |
--push_to_hub |
upload the output directory to a (private) dataset repository |
--temperature, --top_p, --top_k, --presence_penalty, --max_tokens |
sampling, over every task's and mode's own. Unset: the model's generation_config.json; without one, greedy at k = 1 |
--backend, --max_model_len |
the engine: vllm (default), sglang, hf; its context length |
--resume |
keep the items already in the result files |
--no_samples |
do not write the per-sample files |
--json |
print the run summary as JSON |
--section.option value |
any option of the evaluation config: --run.chunk 256, --engine.gpu_memory_utilization 0.4 |
Writes <task>.<mode>.jsonl (per item: id, scores, cluster), <task>.<mode>.samples.jsonl, <task>.<mode>.summary.json, report.md and summary.json (mean score, unbiased pass@k, bootstrap and Wilson intervals, tokens, truncation and loop shares). Exit code 1 on a config error or when nothing could be scored.
pgs compare eval/base/gsm8k.think.jsonl eval/sft/gsm8k.think.jsonl --require not_worse --margin 0.02
compare¶
Score an evaluation with intervals, or compare two checkpoints on the same items. Input: JSONL result files (pgs eval writes them; any harness can), one row per item with an id and its samples' scores (scores: [1, 0, 1], or one correct / score / reward), optionally a cluster (items that are not independent: paraphrases, translations, one task's variants resample together).
pgs compare results_a.jsonl # mean score and pass@k with bootstrap intervals
pgs compare base.jsonl candidate.jsonl --k 1,4,8 --json # paired on the common ids
pgs compare base.jsonl candidate.jsonl --require not_worse --margin 0.02 # exit 1 unless met
Per file: the mean score (per item, then over items) and the unbiased pass@k (Chen et al. 2021, 1 - C(n-c, k) / C(n, k) per item) for every k up to the smallest sample count, each with a percentile bootstrap interval over items or clusters. For two files: B - A of each metric with a paired bootstrap interval and p-value, a sign-flip permutation p-value (exact up to 20 items or clusters), and the exact McNemar test when both have one 0 / 1 sample per item. Items in only one file are counted and left out (--strict: an error). --require better needs the interval of the mean-score difference above 0; --require not_worse its lower end above -margin. The statistics are in palingenesis.evalstats (standard library only) for use from scripts.
screen¶
Difficulty screening of an RL prompt pool: k rollouts per row with the RL config's rendering, environment and rewards; rows with --min_rate < pass rate < --max_rate go to <output>.kept.jsonl. Resumable. See Screening the pool.
pairs¶
Contrastive twin pairs for preference training: prompts that differ by a small edit and need different answers, each pair's rejected side being the sibling's answer, in both directions. check reports identical sides, contradictions, duplicates, twin pairs and their direction balance in any DPO file. See Contrastive twin pairs.
pgs pairs build twins.jsonl -o twin_pairs.jsonl [--prediction_field model_answer --only_misread]
pgs pairs check dpo_rows.jsonl --require_balanced
version¶
Show installed versions.