# guac-coder LLM fine-tuning for research code and scientific writing. Currently a **GRPO** RL adapter that teaches a model to write Python matching an opinionated set of research-code conventions, encoded as **13 rule-based rewards** scored in `[-1, 1]`. ## Install ```bash pip install -e . # core (numpy, pandas) pip install -e ".[mlx]" # Apple Silicon training pip install -e ".[torch]" # CUDA/CPU training pip install -e ".[all]" ``` ## The 13 reward rules Each rule is a function in `guac_coder/grpo_rewards.py`, returns a scalar in `[-1, 1]`, and is collected by `compute_grpo_rewards()`: | # | Rule | Function | Intent | |---|---|---|---| | 1 | chroptiks preference | `chroptiks_preference_reward` | reward `chroptiks` for plotting | | 2 | no seaborn | `no_seaborn_reward` | punish `seaborn` (disqualifying: scores -1.0) | | 3 | no plot grids | `no_plot_grids_reward` | punish `grid(...)` | | 4 | no plot titles | `no_plot_titles_reward` | punish `title(...)` | | 5 | no bar graphs | `no_bargraphs_reward` | punish bar/barh/pie charts | | 6 | pandas CSV | `pandas_csv_preference_reward` | prefer `pd.DataFrame.to_csv` over `csv.DictWriter` | | 7 | objective comments | `objective_comments_reward` | punish narrative/explanatory comments | | 8 | no try/except | `no_try_except_reward` | punish `try/except` | | 9 | no classes | `no_classes_reward` | punish unnecessary classes | | 10 | logging over print | `logging_over_print_reward` | reward `logging`, punish `print` | | 11 | intermittent writes | `intermittent_writes_reward` | write incrementally, not in one batch | | 12 | resumable | `resumable_checkpoint_reward` | require checkpoint/resume support | | 13 | not a bare script | `not_bare_script_reward` | require functions / `__main__` guard | The unweighted mean of the 13 rules is the scalar reward (`combined_grpo_reward`). Because each rule rewards the *absence* of a violation, a snippet that does nothing still collects positive credit (`x = 1` scores `+0.077`, while a script with two real violations scores lower). Only rankings *within* a GRPO group are meaningful, not absolute values. ## Raters The 13 rules can be judged three ways. Pick with `--rater` (CLI), `rater` (`RewardConfig`), or `rater=` in Python. | rater | how it scores | cost | needs | |---|---|---|---| | `static` (default) | regex + AST inspection, no model | free | nothing | | `decision` | Ollama `/v1/systemone` decision model | 1 local request | Ollama >= 0.35 + pulled model | | `llm` | generative LLM-as-judge returning JSON | 1 full generation | API key / `npcpy` | The `decision` rater posts the candidate code as `state` alongside 17 typed yes/no questions and gets a calibrated `P(true)` for each in one request — no prose to parse. Each of the 17 maps onto one of the 13 rule names and reproduces the same interval its static counterpart emits, so the two are comparable and mixable. ```bash ollama pull clef guac-reward --task demo --code script.py --rater decision --rater-model clef guac-train --rater decision --rater-model clef:cloud --iterations 100 ``` Flags: `--rater-model`, `--rater-base-url`, `--rater-threshold` (default `0.5`), and `--rater-on-error` (`static` falls back to the regex rules, `zero` returns neutral rewards, `raise` propagates). ```python from guac_coder import DecisionJudgeConfig, compute_decision_rewards, combined_decision_reward cfg = DecisionJudgeConfig(model="clef:cloud", threshold=0.5, on_error="static") rules = compute_decision_rewards(code, cfg=cfg) # same 13 keys as compute_grpo_rewards total = combined_decision_reward(code, cfg=cfg) # same normalization # judge is injectable, so the path is testable offline compute_decision_rewards(code, cfg=cfg, judge_fn=lambda code, cfg=None: {q: 1.0 for q in QUESTIONS}) ``` ## Auditing reward changes Changing a rule is only safe if you can measure the change. `guac-audit` scores a directory of labeled `.py` cases with two raters and reports per-rule agreement: ```bash guac-audit --corpus ./audit_corpus --rater-a static --rater-b decision \ --rater-model tev1:0.8b --output /tmp/audit.json ``` The dangerous column is `static>0, decision<0`: static *rewards* code another rater calls a violation, meaning we pay the model to write bad code. Fix those first. Agreement is not accuracy — a weak second rater can disagree with a correct rule, so read the labeled-accuracy block too. On the current corpus `static` scores 1.00 against the labels; `tev1:0.8b` scores 0.80 and has produced clearly false violations, so treat a small local decision model as a way to *find* suspected static holes, not as an oracle. Confirm each against the labels before trusting its score in training. Run the audit after any reward change and diff against the previous report. Agreement going down, or a new `static>0, decision<0` entry, means the edit introduced a hole. ## Usage ```bash # score a snippet with the 13 rules (default) guac-reward --task "plot embedding space" --code path/to/script.py guac-reward --task "plot embedding space" --code path/to/script.py --json # legacy static + LLM-judge split guac-eval --file path/to/script.py guac-eval --file path/to/script.py --json --judge-model gpt-4o # train guac-train --model Qwen/Qwen2.5-Coder-7B --output-dir ./grpo_output --iterations 100 guac-train --legacy-rewards # generate scored traces from local Ollama models guac-coder trace --models qwen3.5:0.8b --num-predict 1536 --n-samples 2 ``` Equivalent subcommand form: `guac-coder train|eval|reward|trace|export|audit ...` From Python: ```python from guac_coder import compute_grpo_rewards, combined_grpo_reward, GuacRewardAdapter rules = compute_grpo_rewards(code) total = combined_grpo_reward(code) GuacRewardAdapter(use_grpo_rewards=True)(code) # 13-rule score (default) GuacRewardAdapter(use_grpo_rewards=False)(code) # legacy static + judge score ``` ## Layout ``` guac_coder/ config.py GRPOConfig, RewardConfig, DataConfig data.py research task prompts, prompt building, SFT pair generation rewards.py legacy 12-rule static rewards + LLM judge grpo_rewards.py 13-rule reward set + AST analyzer (default path) grpo_evaluator.py rule-key constants + LLM judge prompt build/parse decision_judge.py Ollama System-One decision rater (17 yes/no questions) grpo_pipeline.py GuacRewardAdapter, build_trainer, run_grpo training.py train_grpo loop (MLX preferred, torch fallback), checkpoints trace.py trace generation against a local Ollama server trace_export.py traces -> SFT / preference / GRPO datasets cli.py entrypoints audit_corpus/ labeled .py cases for rater agreement tests/ ``` ## Training details - Backend: `mlx` when `mlx-lm` is importable (Apple Silicon), otherwise `transformers` + `torch`. - Group sampling: `group_size` completions per prompt at `temperature`; rewards are computed per completion and converted into GRPO advantages (`epsilon`, `beta` in `GRPOConfig`). - Metrics: one JSON line per iteration in `/metrics.jsonl`. - Checkpoints: `/checkpoint_XXXXX.pkl` every `checkpoint_interval` iterations; resume with `--resume-from /checkpoint_XXXXX.pkl`. ## Tests ```bash python -m pytest -q ``` ## Status Alpha. Reward rules and the training loop are implemented and tested; end-to-end training requires a model backend (`mlx-lm` or `torch`/`transformers`) and, for judge-based scoring, `npcpy` with credentials configured.