caug37 commited on
Commit
14bb7c0
·
verified ·
1 Parent(s): 359579b

docs: trim README to actual documentation (292 -> 173 lines)

Browse files
Files changed (1) hide show
  1. README.md +61 -221
README.md CHANGED
@@ -1,12 +1,8 @@
1
  # guac-coder
2
 
3
- LLM fine-tuning for research code and scientific writing. This repo houses projects that use
4
- LLM responses containing Python code snippets for research tasks, starting with a **GRPO
5
- (Group Relative Policy Optimization) RL adapter** for text-generation models.
6
-
7
- The core idea: instead of teaching a model to write *any* working Python, teach it to write
8
- Python that matches a specific, opinionated set of research-code conventions. Those
9
- conventions are encoded as **13 rule-based rewards** that score generated code in `[-1, 1]`.
10
 
11
  ## Install
12
 
@@ -25,7 +21,7 @@ and is collected by `compute_grpo_rewards()`:
25
  | # | Rule | Function | Intent |
26
  |---|---|---|---|
27
  | 1 | chroptiks preference | `chroptiks_preference_reward` | reward `chroptiks` for plotting |
28
- | 2 | no seaborn | `no_seaborn_reward` | punish `seaborn` (**hard gate** -- see below) |
29
  | 3 | no plot grids | `no_plot_grids_reward` | punish `grid(...)` |
30
  | 4 | no plot titles | `no_plot_titles_reward` | punish `title(...)` |
31
  | 5 | no bar graphs | `no_bargraphs_reward` | punish bar/barh/pie charts |
@@ -40,283 +36,127 @@ and is collected by `compute_grpo_rewards()`:
40
 
41
  The unweighted mean of the 13 rules is the scalar reward (`combined_grpo_reward`).
42
 
43
- ### Seaborn is disqualifying, not a soft penalty
44
-
45
- `seaborn` is a **hard gate**, not merely rule 2. If the snippet uses seaborn,
46
- every rule collapses to `SEABORN_FLOOR` (`-1.0`) and the total is `-1.0`,
47
- whatever else the script does right:
48
-
49
- ```python
50
- >>> combined_grpo_reward(EXCELLENT_SCRIPT_THAT_IMPORTS_SEABORN) # logging, to_csv,
51
- -1.0 # chroptiks, resume, __main__ guard
52
- >>> combined_grpo_reward(CLEAN_BUT_PLAIN_SCRIPT)
53
- 0.154
54
- ```
55
-
56
- This is deliberate. Each rule rewards the *absence* of a violation, so a soft
57
- penalty let a well-structured seaborn script outscore honest code -- the rules
58
- were paying for seaborn. The gate applies in **every** rater:
59
-
60
- | rater | how the gate applies |
61
- |---|---|
62
- | `static` | requires no request |
63
- | `decision` | decided from the code, so the model is never called and cannot disagree |
64
- | `llm` (legacy) | short-circuits before the judge, so a generous judge cannot offset it |
65
-
66
- All three forms are caught -- a plain import, `from seaborn import ...`, and a
67
- bare `sns.`/`seaborn.` call with no visible import:
68
-
69
- ```python
70
- from guac_coder import detect_seaborn, uses_seaborn
71
- detect_seaborn("from seaborn import scatterplot") # 'from seaborn import scatterplot'
72
- detect_seaborn("def f(): sns.barplot()") # 'sns. usage'
73
- detect_seaborn("import matplotlib.pyplot as plt") # None (not gated)
74
- ```
75
-
76
- `matplotlib` is discouraged (it loses rule 1 to `chroptiks`) but is **not**
77
- disqualifying; only seaborn is.
78
 
79
- A **legacy** 12-rule path also lives in `guac_coder/rewards.py`
80
- (`compute_static_rewards` / `compute_total_reward`), plus an optional LLM-as-judge
81
- component (`compute_llm_judge_reward`) that calls `npcpy.llm_funcs.get_llm_response`
82
- with `format="json"`. The newer `grpo_rewards` path is the default everywhere.
83
-
84
- ## Raters: static, decision, or llm
85
 
86
  The 13 rules can be judged three ways. Pick with `--rater` (CLI), `rater`
87
- (`RewardConfig`), or the `rater=` argument in Python.
88
 
89
  | rater | how it scores | cost | needs |
90
  |---|---|---|---|
91
  | `static` (default) | regex + AST inspection, no model | free | nothing |
92
- | `decision` | Ollama `/v1/systemone` decision model (`clef`) | 1 local request | Ollama >= 0.35 + pulled model |
93
  | `llm` | generative LLM-as-judge returning JSON | 1 full generation | API key / `npcpy` |
94
 
95
- ### The decision rater
96
-
97
- `guac_coder/decision_judge.py` replaces the full LLM call with a **decision
98
- model**: the candidate code is posted as `state` alongside 17 typed yes/no
99
- questions, and the endpoint returns a calibrated `P(true)` for each in a single
100
- request. There is no prose to parse and no reasoning budget to exhaust.
101
 
102
  ```bash
103
- ollama pull clef # 27B, ~18-20 GB local
104
  guac-reward --task demo --code script.py --rater decision --rater-model clef
105
- guac-reward --task demo --code script.py --rater decision --rater-model clef:cloud # no download
106
  guac-train --rater decision --rater-model clef:cloud --iterations 100
107
- guac-coder trace --models qwen3.5:0.8b --rater decision --rater-model clef:cloud
108
  ```
109
 
110
- Flags: `--rater-model`, `--rater-base-url`, `--rater-threshold` (probability
111
- cutoff for the multi-state rules, default `0.5`), and `--rater-on-error`
112
- (`static` falls back to the regex rules, `zero` returns neutral rewards,
113
  `raise` propagates).
114
 
115
- Each of the 17 questions maps onto one of the 13 rule names produced by
116
- `compute_grpo_rewards`, and each rule reproduces the exact interval its static
117
- counterpart emits (for example `no_seaborn_reward` is `-1.0` on a violation and
118
- `+0.5` when clean). Decision scores and static scores are therefore directly
119
- comparable and mixable, and values are clamped into `[-1, 1]`.
120
-
121
  ```python
122
  from guac_coder import DecisionJudgeConfig, compute_decision_rewards, combined_decision_reward
123
 
124
  cfg = DecisionJudgeConfig(model="clef:cloud", threshold=0.5, on_error="static")
125
  rules = compute_decision_rewards(code, cfg=cfg) # same 13 keys as compute_grpo_rewards
126
- total = combined_decision_reward(code, cfg=cfg) # same normalization as combined_grpo_reward
127
- ```
128
 
129
- Because the judge is injectable, the path is testable offline:
130
-
131
- ```python
132
  compute_decision_rewards(code, cfg=cfg, judge_fn=lambda code, cfg=None: {q: 1.0 for q in QUESTIONS})
133
  ```
134
 
135
- ## Iterating on the rewards: rater audit
136
 
137
- Changing a reward rule is only safe if you can measure the change. `guac-audit`
138
- scores a directory of labeled `.py` cases with two raters and reports
139
- per-rule agreement:
140
 
141
  ```bash
142
  guac-audit --corpus ./audit_corpus --rater-a static --rater-b decision \
143
  --rater-model tev1:0.8b --output /tmp/audit.json
144
  ```
145
 
146
- ```
147
- Rater audit: static vs decision over 13 cases
148
- compared: 13 mean total: static=0.1482 decision=0.1823
149
-
150
- rule n agree abstain static>0,decision<0 mean gap
151
- objective_comments_reward 11 0.00 10 0 1.50
152
- pandas_csv_preference_reward 11 0.80 6 1 2.00
153
- no_classes_reward 11 0.82 0 2 1.50
154
- resumable_checkpoint_reward 11 0.82 0 0 2.00
155
- no_bargraphs_reward 11 0.91 0 1 1.50
156
- not_bare_script_reward 11 0.91 0 0 1.50
157
- no_seaborn_reward 11 1.00 0 0 0.00
158
- no_plot_grids_reward 11 1.00 0 0 0.00
159
- no_plot_titles_reward 11 1.00 0 0 0.00
160
- no_try_except_reward 11 1.00 0 0 0.00
161
- logging_over_print_reward 11 1.00 5 0 0.00
162
- chroptiks_preference_reward 11 1.00 9 0 0.00
163
- intermittent_writes_reward 11 n/a 11 0 0.00
164
-
165
- Labeled accuracy (rater vs corpus labels):
166
- static 1.00 (30/30 checked)
167
- decision 0.80 (24/30 checked)
168
-
169
- Verdict: 1 rule(s) below 0.8 agreement: objective_comments_reward.
170
- ```
171
-
172
- `intermittent_writes_reward` shows `n/a`: the decision model abstained on all
173
- 11 cases, so there is nothing to compare -- not a 0% agreement.
174
-
175
- How to read it:
176
-
177
- * **agree** -- share of cases where both raters took the *same* position.
178
- A `0.0` from one side is scored as an **abstention**, not a contradiction,
179
- so a rule that legitimately returns "no opinion" does not look broken.
180
- * **static>0, decision<0** -- static **rewards** code the other rater calls a
181
- violation. This is the dangerous direction: it pays the model to write bad
182
- code, and it is the first thing to fix.
183
- * **Verdict** -- `INCONCLUSIVE` when no case was scored by both raters. A
184
- failed rater is never silently replaced by the one being audited; the audit
185
- sets `on_error="raise"` so a broken endpoint shows up as a failure.
186
-
187
- Cases are plain `.py` files; `labels.json` may map filenames to expected rule
188
- values for an informal `static vs expectation` check.
189
-
190
- ### Known static blind spots (found by the audit)
191
-
192
- These all **rewarded** violating code before being fixed, and each now has a
193
- regression case in `audit_corpus/`:
194
-
195
- | violation | why the old regex missed it |
196
- |---|---|
197
- | `sns.barplot(...)`, `sns.countplot(...)` | pattern was the bare token `bar(`, which never matches after a `.` |
198
- | `plt.bar(...)`, `ax.barh(...)` | same prefix problem |
199
- | `sns.set_style("whitegrid")` | enables grids via a *string*, never calls `grid(...)` |
200
- | `plt.style.use("seaborn-v0_8-whitegrid")` | same |
201
- | `from seaborn import scatterplot` | only `import seaborn` was matched, so this scored **+0.077** |
202
- | bare `sns.barplot(...)`, no import | usage without an import was invisible, also **+0.077** |
203
-
204
- Run the audit after any reward change and diff the report against the previous
205
- one -- agreement going down, or a new `static>0, decision<0` entry, means the
206
- edit introduced a hole.
207
-
208
- **Agreement is not accuracy.** A weak second rater can disagree with a correct
209
- rule. Always read the labeled-accuracy block, which is why the corpus carries
210
- labels. Measured on the current 13-case corpus:
211
-
212
- | rater | labeled accuracy |
213
- |---|---|
214
- | `static` | **1.00** (30/30) |
215
- | `decision` with `tev1:0.8b` | 0.80 (24/30) |
216
- | `decision` with `clef:cloud` | not measurable here (account out of credits; the audit reports `INCONCLUSIVE` rather than false agreement) |
217
-
218
- So a small local decision model is *not* yet a trustworthy oracle: with
219
- `tev1:0.8b` it claimed `clean_full.py` used bars, defined classes and skipped
220
- `to_csv`, all of which are false. Use the decision rater as a second opinion to
221
- *find* suspected static holes, then confirm each one against the labels -- and
222
- size up to a stronger decision model before trusting its score in training.
223
-
224
- ### Known scoring issue: the free-credit floor
225
-
226
- Every rule returns positive credit for *not* violating, so a snippet that does
227
- nothing collects a large total:
228
-
229
- | snippet | total |
230
- |---|---|
231
- | `x = 1` | `+0.077` |
232
- | `viol_grids_titles.py` (grids **and** titles) | `+0.038` |
233
- | empty / `pass` / comments only | `-1.000` |
234
-
235
- So `x = 1` outranks a script that has two real violations. Seaborn is the one
236
- exception: the hard gate puts it at `-1.000`, below everything. Two consequences
237
- of the floor remain for the *other* rules:
238
 
239
- * absolute reward values are not comparable across snippets of different
240
- structure; only the *ranking within a GRPO group* is meaningful;
241
- * the shared "clean" credit (`+0.5` on eight rules) dwarfs the individual
242
- penalties, which weakens the gradient for the rules that matter.
 
243
 
244
- `not_bare_script_reward` returning `+0.5` for *any* function definition is part
245
- of this: one `def` earns full credit for structural quality while contributing
246
- nothing. This is the largest open item in the reward design, and exactly the
247
- kind of change the audit exists to validate.
248
-
249
-
250
- ## Layout
251
-
252
- ```
253
- guac_coder/
254
- config.py GRPOConfig, RewardConfig, DataConfig
255
- data.py research task prompts, prompt building, SFT pair generation, repo scraping
256
- rewards.py legacy 12-rule static rewards + LLM judge
257
- grpo_rewards.py 13-rule reward set + AST analyzer (default path)
258
- grpo_evaluator.py rule-key constants + LLM judge prompt build/parse
259
- decision_judge.py Ollama System-One decision rater (17 typed yes/no questions)
260
- grpo_pipeline.py GuacRewardAdapter, build_trainer, run_grpo (npcpy.ft.rl bridge)
261
- training.py train_grpo loop (MLX preferred, torch fallback), checkpoints
262
- cli.py guac-coder / guac-train / guac-eval / guac-reward entrypoints
263
- tests/ 60 tests covering rewards, evaluator, pipeline, and raters
264
- ```
265
 
266
  ## Usage
267
 
268
- Score a snippet with the 13 rules (default):
269
-
270
  ```bash
 
271
  guac-reward --task "plot embedding space" --code path/to/script.py
272
  guac-reward --task "plot embedding space" --code path/to/script.py --json
273
- guac-reward --task "plot embedding space" --code path/to/script.py --legacy
274
- ```
275
-
276
- Evaluate with the legacy static + LLM-judge split:
277
 
278
- ```bash
279
  guac-eval --file path/to/script.py
280
  guac-eval --file path/to/script.py --json --judge-model gpt-4o
281
- ```
282
 
283
- Train (defaults to the 13-rule rewards, matching the CLI):
284
-
285
- ```bash
286
  guac-train --model Qwen/Qwen2.5-Coder-7B --output-dir ./grpo_output --iterations 100
287
- guac-train --legacy-rewards # optimize the legacy rewards.py score instead
 
 
 
288
  ```
289
 
290
- Equivalent subcommand form: `guac-coder train|eval|reward ...`
291
 
292
  From Python:
293
 
294
  ```python
295
- from guac_coder import compute_grpo_rewards, combined_grpo_reward
296
 
297
  rules = compute_grpo_rewards(code)
298
  total = combined_grpo_reward(code)
299
- ```
300
-
301
- Both scoring paths are selectable from Python as well:
302
-
303
- ```python
304
- from guac_coder import GuacRewardAdapter, run_grpo, train_grpo
305
 
306
  GuacRewardAdapter(use_grpo_rewards=True)(code) # 13-rule score (default)
307
  GuacRewardAdapter(use_grpo_rewards=False)(code) # legacy static + judge score
 
308
 
309
- train_grpo(cfg, reward_cfg, get_llm_response_fn, use_grpo_rewards=True)
310
- run_grpo(use_grpo_rewards=True, ...)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
311
  ```
312
 
313
  ## Training details
314
 
315
  - Backend: `mlx` when `mlx-lm` is importable (Apple Silicon), otherwise `transformers` + `torch`.
316
- - Group sampling: `group_size` completions per prompt at `temperature`; rewards are
317
- computed per completion and converted into GRPO advantages (`epsilon`, `beta` in `GRPOConfig`).
318
- - Metrics: one JSON line per iteration appended to `<output-dir>/metrics.jsonl`, including
319
- the reward mode, per-sample rewards, and scalar reward (`total`, `static`, `llm`).
320
  - Checkpoints: `<output-dir>/checkpoint_XXXXX.pkl` every `checkpoint_interval` iterations;
321
  resume with `--resume-from <output-dir>/checkpoint_XXXXX.pkl`.
322
 
 
1
  # guac-coder
2
 
3
+ LLM fine-tuning for research code and scientific writing. Currently a **GRPO** RL adapter
4
+ that teaches a model to write Python matching an opinionated set of research-code
5
+ conventions, encoded as **13 rule-based rewards** scored in `[-1, 1]`.
 
 
 
 
6
 
7
  ## Install
8
 
 
21
  | # | Rule | Function | Intent |
22
  |---|---|---|---|
23
  | 1 | chroptiks preference | `chroptiks_preference_reward` | reward `chroptiks` for plotting |
24
+ | 2 | no seaborn | `no_seaborn_reward` | punish `seaborn` (disqualifying: scores -1.0) |
25
  | 3 | no plot grids | `no_plot_grids_reward` | punish `grid(...)` |
26
  | 4 | no plot titles | `no_plot_titles_reward` | punish `title(...)` |
27
  | 5 | no bar graphs | `no_bargraphs_reward` | punish bar/barh/pie charts |
 
36
 
37
  The unweighted mean of the 13 rules is the scalar reward (`combined_grpo_reward`).
38
 
39
+ Because each rule rewards the *absence* of a violation, a snippet that does nothing still
40
+ collects positive credit (`x = 1` scores `+0.077`, while a script with two real violations
41
+ scores lower). Only rankings *within* a GRPO group are meaningful, not absolute values.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
+ ## Raters
 
 
 
 
 
44
 
45
  The 13 rules can be judged three ways. Pick with `--rater` (CLI), `rater`
46
+ (`RewardConfig`), or `rater=` in Python.
47
 
48
  | rater | how it scores | cost | needs |
49
  |---|---|---|---|
50
  | `static` (default) | regex + AST inspection, no model | free | nothing |
51
+ | `decision` | Ollama `/v1/systemone` decision model | 1 local request | Ollama >= 0.35 + pulled model |
52
  | `llm` | generative LLM-as-judge returning JSON | 1 full generation | API key / `npcpy` |
53
 
54
+ The `decision` rater posts the candidate code as `state` alongside 17 typed yes/no
55
+ questions and gets a calibrated `P(true)` for each in one request — no prose to parse. Each
56
+ of the 17 maps onto one of the 13 rule names and reproduces the same interval its static
57
+ counterpart emits, so the two are comparable and mixable.
 
 
58
 
59
  ```bash
60
+ ollama pull clef
61
  guac-reward --task demo --code script.py --rater decision --rater-model clef
 
62
  guac-train --rater decision --rater-model clef:cloud --iterations 100
 
63
  ```
64
 
65
+ Flags: `--rater-model`, `--rater-base-url`, `--rater-threshold` (default `0.5`), and
66
+ `--rater-on-error` (`static` falls back to the regex rules, `zero` returns neutral rewards,
 
67
  `raise` propagates).
68
 
 
 
 
 
 
 
69
  ```python
70
  from guac_coder import DecisionJudgeConfig, compute_decision_rewards, combined_decision_reward
71
 
72
  cfg = DecisionJudgeConfig(model="clef:cloud", threshold=0.5, on_error="static")
73
  rules = compute_decision_rewards(code, cfg=cfg) # same 13 keys as compute_grpo_rewards
74
+ total = combined_decision_reward(code, cfg=cfg) # same normalization
 
75
 
76
+ # judge is injectable, so the path is testable offline
 
 
77
  compute_decision_rewards(code, cfg=cfg, judge_fn=lambda code, cfg=None: {q: 1.0 for q in QUESTIONS})
78
  ```
79
 
80
+ ## Auditing reward changes
81
 
82
+ Changing a rule is only safe if you can measure the change. `guac-audit` scores a
83
+ directory of labeled `.py` cases with two raters and reports per-rule agreement:
 
84
 
85
  ```bash
86
  guac-audit --corpus ./audit_corpus --rater-a static --rater-b decision \
87
  --rater-model tev1:0.8b --output /tmp/audit.json
88
  ```
89
 
90
+ The dangerous column is `static>0, decision<0`: static *rewards* code another rater calls a
91
+ violation, meaning we pay the model to write bad code. Fix those first.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
 
93
+ Agreement is not accuracy — a weak second rater can disagree with a correct rule, so read
94
+ the labeled-accuracy block too. On the current corpus `static` scores 1.00 against the
95
+ labels; `tev1:0.8b` scores 0.80 and has produced clearly false violations, so treat a small
96
+ local decision model as a way to *find* suspected static holes, not as an oracle. Confirm
97
+ each against the labels before trusting its score in training.
98
 
99
+ Run the audit after any reward change and diff against the previous report. Agreement going
100
+ down, or a new `static>0, decision<0` entry, means the edit introduced a hole.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
  ## Usage
103
 
 
 
104
  ```bash
105
+ # score a snippet with the 13 rules (default)
106
  guac-reward --task "plot embedding space" --code path/to/script.py
107
  guac-reward --task "plot embedding space" --code path/to/script.py --json
 
 
 
 
108
 
109
+ # legacy static + LLM-judge split
110
  guac-eval --file path/to/script.py
111
  guac-eval --file path/to/script.py --json --judge-model gpt-4o
 
112
 
113
+ # train
 
 
114
  guac-train --model Qwen/Qwen2.5-Coder-7B --output-dir ./grpo_output --iterations 100
115
+ guac-train --legacy-rewards
116
+
117
+ # generate scored traces from local Ollama models
118
+ guac-coder trace --models qwen3.5:0.8b --num-predict 1536 --n-samples 2
119
  ```
120
 
121
+ Equivalent subcommand form: `guac-coder train|eval|reward|trace|export|audit ...`
122
 
123
  From Python:
124
 
125
  ```python
126
+ from guac_coder import compute_grpo_rewards, combined_grpo_reward, GuacRewardAdapter
127
 
128
  rules = compute_grpo_rewards(code)
129
  total = combined_grpo_reward(code)
 
 
 
 
 
 
130
 
131
  GuacRewardAdapter(use_grpo_rewards=True)(code) # 13-rule score (default)
132
  GuacRewardAdapter(use_grpo_rewards=False)(code) # legacy static + judge score
133
+ ```
134
 
135
+ ## Layout
136
+
137
+ ```
138
+ guac_coder/
139
+ config.py GRPOConfig, RewardConfig, DataConfig
140
+ data.py research task prompts, prompt building, SFT pair generation
141
+ rewards.py legacy 12-rule static rewards + LLM judge
142
+ grpo_rewards.py 13-rule reward set + AST analyzer (default path)
143
+ grpo_evaluator.py rule-key constants + LLM judge prompt build/parse
144
+ decision_judge.py Ollama System-One decision rater (17 yes/no questions)
145
+ grpo_pipeline.py GuacRewardAdapter, build_trainer, run_grpo
146
+ training.py train_grpo loop (MLX preferred, torch fallback), checkpoints
147
+ trace.py trace generation against a local Ollama server
148
+ trace_export.py traces -> SFT / preference / GRPO datasets
149
+ cli.py entrypoints
150
+ audit_corpus/ labeled .py cases for rater agreement
151
+ tests/
152
  ```
153
 
154
  ## Training details
155
 
156
  - Backend: `mlx` when `mlx-lm` is importable (Apple Silicon), otherwise `transformers` + `torch`.
157
+ - Group sampling: `group_size` completions per prompt at `temperature`; rewards are computed
158
+ per completion and converted into GRPO advantages (`epsilon`, `beta` in `GRPOConfig`).
159
+ - Metrics: one JSON line per iteration in `<output-dir>/metrics.jsonl`.
 
160
  - Checkpoints: `<output-dir>/checkpoint_XXXXX.pkl` every `checkpoint_interval` iterations;
161
  resume with `--resume-from <output-dir>/checkpoint_XXXXX.pkl`.
162