A modular LoRA fine-tuning pipeline for Hugging Face causal language models and vision-language models. Reforge handles dataset loading, automatic schema detection, text cleaning, tokenization, training with smart early stopping (SFT or DPO preference tuning), LoRA merge, and final model export. Includes a browser-based web UI for interactive control.
Launch with reforge webui and open http://127.0.0.1:7861 — a zero-dependency dashboard (stdlib server, vanilla JS, canvas chart) that supervises the same agent-mode process the CLI runs.
| Setup | Preparing dataset | Live training |
|---|---|---|
![]() |
![]() |
![]() |
Setup with a live command preview · phase pills and a truthful "ETA unknown yet" state while the dataset loads · live loss curve with the EMA early-stopping overlay, signal/noise analysis, and human-readable feedback. All screenshots use synthetic demo data.
src/reforge/
├── __init__.py # Package marker
├── __main__.py # CLI entry point
├── config.py # Environment setup, paths, constants
├── profiles.py # Model profiles (Phi-2, Phi-3, etc.)
├── display.py # ANSI colors, banners, formatting
├── dataset.py # Dataset loading, schema detection, cleaning
├── tokenization.py # Tokenization, collation, length measurement
├── training.py # LoRA setup, model loading, training loop
├── early_stopping.py # EMA-based early stopping callback
├── batch.py # Batch mode: sequential chained stages
├── reporting.py # Training summary, loss curves, reports
├── agent.py # Agent mode: NDJSON events + run_state.json
├── utils.py # Model scanner, file picker, GC
├── webui_config.py # Web UI: argv builder + validation, model scan
└── webui.py # Web UI server + SPA — `reforge webui` (port 7861)
AGENTS.md (repo root) is the orientation guide for AI agents working on or driving Reforge.
# Run as a module
python -m reforge
# Or install and use the console script
pip install -e .
reforge
# Launch the browser-based web UI (http://127.0.0.1:7861)
reforge webui
# Specify a Hugging Face Hub dataset
python -m reforge --hf_dataset username/dataset-name
# Override the base model path
python -m reforge --base_model /path/to/your/model
# Preserve code formatting during cleaning
python -m reforge --code
# Preserve LaTeX equations
python -m reforge --latex
# Multimodal image+text training
python -m reforge --image
# DPO preference tuning (dataset with chosen + rejected columns; auto-detected)
python -m reforge preference_pairs.parquet --base_model /path/to/sft_model
# DPO with a custom beta (KL strength vs the reference model)
python -m reforge preference_pairs.parquet --base_model /path/to/sft_model --dpo_beta 0.05
# Force DPO interpretation on a dataset with unusual column names
python -m reforge pairs.parquet --base_model /path/to/sft_model --dpo
# Train for exactly 500 steps
python -m reforge --steps 500
# Disable early stopping and run full epochs
python -m reforge --force --epoch 3
# Agent mode: machine-readable NDJSON events on stdout + run_state.json
python -m reforge dataset.parquet --base_model /path/to/model --agent| Flag | Description |
|---|---|
--base_model PATH |
Path to a local Hugging Face model directory (skips picker) |
--hf_dataset ID |
Load a dataset from the Hugging Face Hub |
--image |
Enable multimodal (vision+text) training |
--dpo |
Force DPO training (normally auto-detected from chosen+rejected columns) |
--dpo_beta X |
DPO beta, KL strength vs the reference model (default: 0.1; DPO runs only) |
--batch D1 D2 ... |
Batch mode: train datasets in order, chaining merges (--batch manifest.json for per-stage control) |
--batch_dir PATH |
Resume an interrupted batch from its batch_<timestamp> directory |
--latex |
Preserve LaTeX/scientific notation during cleaning |
--code |
Preserve code formatting and indentation |
--epoch N |
Number of training epochs (default: 1) |
--steps N |
Train for exactly N steps (overrides epoch) |
--batch_size N |
Per-device batch size override (default: 1) |
--grad_accum N |
Gradient accumulation steps override (default: model profile) |
--max_length N |
Override auto (P95) max sequence length in tokens; min 128 |
--truncate |
Force keeping rows longer than --max_length by left-truncating leading context (the trained reply and its trailing end-of-turn token survive). Default is auto: engages whenever any row would otherwise be dropped |
--no_truncate |
Disable auto truncation; restore strict dropping of overlong rows |
--force |
Disable early stopping |
--agent |
Agent mode: NDJSON events on stdout + pollable run_state.json |
--agent_schema |
Print the machine-readable agent contract as JSON and exit 0 (also: reforge agent-schema) |
--dry_run |
Preflight: validate args/dataset/model and print the resolved training plan as JSON (no weights loaded) |
--agent_log PATH |
Also tee the agent NDJSON stream to a file |
Training mode is auto-detected from column names (aliases in parentheses):
| Mode | Required columns | Optional columns | Trains with |
|---|---|---|---|
dpo |
chosen (response, answer, completion, accepted, output, solution) and rejected (unpreferred, worse, answer_2, response_2, output_2) |
question (prompt, instruction, input, query, context, problem) |
TRL DPOTrainer |
sft |
chosen |
question |
HF Trainer |
causal |
text (prompt) |
— | HF Trainer |
chat |
messages |
— | HF Trainer |
multimodal |
image + text (--image) |
— | HF Trainer |
Detection checks dpo before sft, so a dataset with both completions is
always read as preference pairs. DPO rows become {prompt, chosen, rejected}
(or chat-message lists when the tokenizer has a chat template); TRL tokenizes
them internally. Use --dpo to force DPO on non-standard column names —
the run fails preflight with invalid_dataset if both completions are missing.
- Train SFT on your instruction dataset as usual →
merged/+success.txt. - Run DPO on a preference-pair dataset without passing
--base_model— the training chain picks up the SFT-merged model as the base automatically (or pass--base_model /path/to/mergedexplicitly). - Watch
rewards/accuraciesclimb in the web UI log while loss decreases.beta(default 0.1) controls KL pressure vs the reference model: higher = stay closer to the SFT model, lower = more aggressive alignment.
Train several datasets in order, each stage training on the previous stage's merged model — the canonical workflow is SFT → SFT → DPO → final merge:
# Inline list: global flags apply to every stage
python -m reforge --batch sft_math.parquet sft_code.parquet dpo_pairs.parquet --base_model /path/to/base
# Manifest: per-stage control
python -m reforge --batch manifest.json --base_model /path/to/baseManifest format:
{
"base_model": "C:/path/to/base-model",
"stages": [
{"dataset": "sft_math.parquet", "epochs": 2},
{"dataset": "sft_code.parquet", "code": true, "force": true, "steps": 300},
{"dataset": "dpo_pairs.parquet", "dpo_beta": 0.1}
]
}Per-stage keys map to the CLI flags: dataset/hf_dataset, name, epochs, steps, force, dpo, dpo_beta, latex, code, batch_size, grad_accum, max_length, truncate/no_truncate. A stage whose dataset has chosen+rejected columns trains as DPO automatically.
Behavior:
- Each stage is a complete Reforge run in its own dir (
batch_<timestamp>/stage_01/…), so early stopping, checkpointing, and merging behave exactly as in single runs — early stopping resets per stage. - The final model is the last stage's
stage_0N/merged. Completed stages' merged models are deleted once the next stage completes (only the running stage's predecessor is ever needed). Set"keep_stage_merges": trueto keep all. - Stage 1 requires an explicit
--base_model(CLI or manifest) — batch never chains from a staleReforge_Output/mergedsilently. - Resume: interrupt with Ctrl+C (the current stage saves its adapter), then rerun with
--batch_dir <batch_dir>. Completed stages are skipped; the interrupted stage resumes from its checkpoints. A stage whose merge was interrupted is detected (nosuccess.txt) and restarted cleanly. --dry_run --batch manifest.jsonvalidates every stage and prints per-stage plans without touching the GPU.
| Variable | Default | Description |
|---|---|---|
HF_HOME |
~/.cache/huggingface |
Root for all HF cache types |
HF_HUB_CACHE |
~/.cache/huggingface/hub |
Root for the Hugging Face model cache |
REFORGE_MODELS_DIR |
~/HF_Models |
Directory to scan for local models |
REFORGE_OUTPUT_DIR |
~/Reforge_Output |
Default output directory |
NO_COLOR |
unset | Disables all ANSI color output |
FORCE_COLOR |
unset | Forces color output even when stdout is not a TTY |
TERM=dumb |
unset | Disables color output (standard convention) |
REFORGE_AGENT=1 |
unset | Enables agent mode (same as --agent) |
- Automatic training mode detection — inspects dataset columns and selects the right pipeline: SFT (instruction/response), DPO (preference pairs: chosen+rejected), causal (raw text), chat (messages), or multimodal (image+text).
- DPO (preference tuning) — preference-pair datasets train with TRL's
DPOTrainer: LoRA adapters on the 4-bit base with the adapter-disabled base weights acting as the reference model (no second copy in VRAM),betaconfigurable via--dpo_beta. Intended workflow: SFT first, then DPO — the SFT run's merged model automatically becomes the DPO run's base via the training chain. Preference alignment is visible live (rewards/accuraciesin the web UI console tail). - Batch mode (
--batch) — train a list of datasets in order with chained merges (SFT → SFT → DPO). Per-stage control via a JSON manifest; automatic resume frombatch_state.json; per-stage early stopping; disk-friendly (intermediate merges auto-reclaimed). - Built-in data cleaning — strips LaTeX, HTML, markdown artifacts, unicode garbage, emoji, junk tokens, and e-commerce noise. Configurable modes for math, LaTeX-preserving, and code-preserving workflows.
- Model profiles — ships with tuned configs for Phi-2, Phi-3, Phi-3-Vision, and more. Falls back to sensible defaults for unlisted models.
- Smart early stopping — EMA-based loss plateau/worsening detection with exposure floors, LR gates, and dynamic hard caps.
- Automatic sequence length — measures token length distribution (P95) and sets
max_lengthaccordingly. - Smart long-row handling — rows longer than
max_lengthare kept by left-truncating leading context (the trained reply and its trailing end-of-turn token survive), never silently dropped. Automatic;--truncate/--no_truncateoverride. - Checkpoint resumption — interrupted runs resume from the last checkpoint automatically.
- Cross-platform file picker — native dialogs on all platforms.
- Local model picker — scans
~/HF_Models/and the Hugging Face hub cache, then presents an interactive numbered list. - Post-training summary — formatted report with loss statistics, trend, and unicode sparkline. Writes a full
training_report.json. - Web UI (
reforge webui/reforge ui, orpython -m reforge webui --port 7861 --no-browser) — a dependency-free local server (stdlibhttp.server) serving a single-page dashboard athttp://127.0.0.1:7861: config cards (paths, training, performance, flags/DPO, batch stage editor with reorder), a live command preview, start/stop with the same validations, aDATASET → MODEL → TRAIN → MERGEphase tracker (spinner/✓/✗ states) + progress bar with a tqdm-style info linestep 450/1000 · 45% · [03:12<03:54 · 1.9 it/s]+ ETA/stat chips, a canvas loss chart, the full loss analysis (grade/trend/SNR/exposure/ideal-zone), a console tail (showsrewards/accuracies-style DPO detail from the event stream), and a results view fed bytraining_report.json. Launches the child in agent mode and consumes the NDJSON event stream; no extra packages required.
- Self-describing contract —
reforge --agent-schema(orreforge agent-schema) prints the complete machine-readable contract as one JSON object: CLI arguments, event vocabulary and fields,run_state.jsonkeys, exit codes, error codes, dataset schemas, model profiles, artifact map, and an example session. Generated from the live argparse parser and pipeline constants, so it cannot drift. Agents should call this first. - Preflight —
reforge --dry_run --base_model PATH dataset.parquetvalidates everything and prints the resolved training plan (steps, epochs, scheduler, warmup, early-stop caps, LoRA config) as JSON without loading weights. Exit 0 = safe to launch, 2 = errors listed with codes. - NDJSON event stream on stdout — one JSON object per line:
run_started,dataset_loaded,training_started,step(loss, percent, ETA),checkpoint_saved,early_stop_check,early_stop_triggered,training_complete,merge_started,merge_complete,run_complete,run_failed,run_interrupted. Each event carries astagefield (loading/preparing/training/exporting). - Pollable state file —
<output_dir>/run_state.jsonholds the latest snapshot (schemaversion, status, step, loss, ETA, stage, error, exit code), rewritten atomically after every event; safe to poll from a background process. - Structured failures —
run_failed/training_failedevents carry a machine-branchableerror_codeand a remediationhint(missing_base_model,undetectable_schema,cuda_oom,model_not_found,dataset_not_found,invalid_dataset,missing_dataset,dataset_too_small,checkpoint_base_mismatch,invalid_base_model,tokenizer_load_failed,unknown_args). - Rich
dataset_loaded— includes detectedtraining_mode, rawcolumns,mapped_roles(question/chosen/rejected/image → column),cleaning_mode, andshuffle_seed. - Pure stdout in agent mode — pretty/console output is diverted to stderr, so stdout parses line-by-line as JSON. Highly recommended to pass
--base_modeland a dataset argument, since interactive pickers are unavailable in agent mode (it fails fast with exit code 2 instead of blocking on stdin). - Meaningful exit codes —
0success,1runtime/training failure,2invalid arguments or dataset,130interrupted.
{"ts": "2026-11-10T19:05:14Z", "event": "step", "stage": "training", "step": 100, "total_steps": 1500, "loss": 2.4131, "pct": 6.7, "eta_sec": 612}
{"ts": "2026-11-10T19:16:12Z", "event": "run_complete", "stage": "complete", "merged_dir": "C:/Users/you/Reforge_Output/merged", "exit_code": 0}See AGENTS.md for the full agent-facing guide (structure, monitoring, failure handling). A portable skill for skill-compatible agent harnesses is bundled at skills/reforge/SKILL.md.
- Load — reads a
.parquetfile or HF Hub dataset, auto-detects training schema. - Clean — mode-appropriate text normalization.
- Tokenize — P95-based length detection, tokenizes with dynamic padding.
- Train — LoRA adapters, CUDA warmup, Hugging Face
Trainer(or TRLDPOTrainerfor preference-pair datasets). - Stop — early stopping via EMA plateau/worsening detection.
- Report — summary banner, training_report.json.
- Merge — LoRA adapter merged back into the base model.
- Chain — merged model becomes the base for the next run.
Edit the MODEL_PROFILES dictionary in src/reforge/profiles.py.
MIT


