Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitignoreAdded+33
- .knowledge.yamlAdded+82
- .pytest_cache/.gitignoreAdded+2
- .pytest_cache/CACHEDIR.TAGAdded+4
- .pytest_cache/README.mdAdded+8
- .pytest_cache/v/cache/lastfailedAdded+4
- .pytest_cache/v/cache/nodeidsAdded+114
- .pytest_cache/v/cache/stepwiseAdded+1
- .ruff_cache/.gitignoreAdded+2
- .ruff_cache/0.11.1/14703387306720712603Added
- .ruff_cache/0.11.1/17431183108856248313Added
- .ruff_cache/0.11.1/2000423069392656154Added
- .ruff_cache/0.11.1/6002917476793586250Added
- .ruff_cache/CACHEDIR.TAGAdded+1
- README.md+293-3
- audit_corpus/clean_full.pyAdded+36
- audit_corpus/clean_minimal.pyAdded+11
- audit_corpus/labels.jsonAdded+33
- audit_corpus/viol_bare_script.pyAdded+5
- audit_corpus/viol_bargraph_seaborn_api.pyAdded+14
- audit_corpus/viol_classes.pyAdded+15
- audit_corpus/viol_dictwriter.pyAdded+16
- audit_corpus/viol_grids_titles.pyAdded+12
- audit_corpus/viol_narrative.pyAdded+14
- audit_corpus/viol_prints.pyAdded+12
- audit_corpus/viol_seaborn.pyAdded+10
- audit_corpus/viol_try_except.pyAdded+15
- guac_coder/__init__.pyAdded+99
- guac_coder/cli.pyAdded+612
- guac_coder/config.pyAdded+110
- guac_coder/data.pyAdded+151
- guac_coder/decision_judge.pyAdded+466
- guac_coder/grpo_evaluator.pyAdded+204
- guac_coder/grpo_pipeline.pyAdded+290
- guac_coder/grpo_rewards.pyAdded+403
- guac_coder/rater_audit.pyAdded+438
- guac_coder/rewards.pyAdded+346
- guac_coder/trace.pyAdded+471
- guac_coder/trace_export.pyAdded+212
- guac_coder/training.pyAdded+517
- pyproject.tomlAdded+60
- setup.pyAdded+10
- tests/test_decision_judge.pyAdded+233
- tests/test_grpo_evaluator.pyAdded+108
- tests/test_grpo_pipeline.pyAdded+134
- tests/test_rater_audit.pyAdded+152
- tests/test_reward_validity.pyAdded+266
- tests/test_rewards.pyAdded+173
- traces/datasets/grpo_records.jsonlAdded+3
- traces/datasets/manifest.jsonAdded+17
123456789101112131415161718192021222324252627282930313233# Python__pycache__/*.py[cod]*$py.class*.so.Pythonbuild/dist/*.egg-info/.eggs/
# Environments.venv/venv/env/
# Test / tooling caches.pytest_cache/.ruff_cache/.mypy_cache/.coveragehtmlcov/
# Training artifactsgrpo_output/*.safetensors*.ckptcheckpoints/
# Editor / OS.vscode/.idea/.DS_Store12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182created_at: '2026-11-11T01:35:49.616532+00:00'updated_at: '2026-11-11T03:14:06.932573+00:00'last_extracted_at: nulllast_evolved_at: nullscanned_files: {}memories:- id: 358b58901769498bb2a7dca1ad486be9 message_id: '' conversation_id: '' npc: corca team: '' directory_path: /home/caug/npcww/guac-coder timestamp: '2026-11-11T01:35:49.616415+00:00' initial_memory: 'guac-coder trace harness (guac_coder/trace.py + trace_export.py, CLI: guac-coder trace|export). Ollama-only for trace gen; HF weights come later for fine-tuning.
Hard-won findings on this box (CPU only, no GPU, ollama 0.40.16):
1. THINKING MODELS: lfm3:latest with think=false burns the ENTIRE token budget and returns response="" AND thinking="" (done_reason=length). Silent empty output, looks like a scoring bug. With think=true the reasoning goes to `thinking` (5328 chars at 1200 tokens) and you need a much bigger budget to also get code. lfm3 needs num_predict>=2560 + think=true.
2. TOKEN BUDGET: qwen3.5:0.8b truncated at 768 (done_reason=length, eval=768 exactly). At 1536 it finishes naturally (924/764/1255 tokens, done_reason=stop). So truncation was budget, not model.
3. SEED: reusing one fixed seed across samples made every sample byte-identical despite temperature 0.8 -> zero advantage spread, useless for GRPO. Fixed: seed=base+sample_index.
4. TRACE ID: must include seed and num_predict, else resuming a run with different sampling silently reuses stale rows.
5. LOGGING: logging.basicConfig() silently no-ops because npcpy installs a root handler at import. Need force=True or per-trace INFO lines vanish.
6. CODE EXTRACTION: truncated gens leave an unterminated ```python fence; must strip it or the literal fence marker leaks into code and skews rules. Largest fence wins (small models show a toy example first).
7. SHELL TOOL: wall-clock cap kills long commands; run generations detached with nohup setsid and poll the JSONL.
' final_memory: null status: active model: null provider: null created_at: '2026-11-11T01:35:49.616456+00:00' source_type: '' source_id: ''- id: 21dfe6f7d21e4ff98ec12750c83693fc message_id: '' conversation_id: '' npc: corca team: '' directory_path: /home/caug/npcww/guac-coder timestamp: '2026-11-11T03:14:06.924981+00:00' initial_memory: 'guac-coder reward-hacking bug (found 2026-11-10): unparseable/empty model output earned POSITIVE reward because all 13 rules reward absence-of-violation. Real corpus: 3/7 samples were truncated at 384 tokens and scored +0.192..+0.346, i.e. HIGHER than a working script at +0.231. GRPO would have learned to emit garbage. Fix: is_valid_python() gate + VALIDITY_FLOOR=-1.0 in guac_coder/grpo_rewards.py, applied in compute_grpo_rewards, compute_decision_rewards (decision_judge.py), and trace_export._scored. Also fixed: extract_code''s unterminated-fence regex was dead code (\s* greedily ate the \n it then required), leaking ```python into extracted code. Syntax validity alone is insufficient — prose like "this is not python" parses as a valid comparison, so the gate also requires a substantive statement or a Call node.' final_memory: null status: pending_approval model: null provider: null created_at: '2026-11-11T03:14:06.925016+00:00' source_type: '' source_id: ''knowledge: []concepts: []links: []12# Created by pytest automatically.*1234Signature: 8a477f597d28d172789f06886806bc55# This file is a cache directory tag created by pytest.# For information about cache directory tags, see:# https://bford.info/cachedir/spec.html12345678# pytest cache directory #
This directory contains data from the pytest's cache plugin,which provides the `--lf` and `--ff` options, as well as the `cache` fixture.
**Do not** commit this to version control.
See [the docs](https://docs.pytest.org/en/stable/how-to/cache.html) for more information.1234{ "tests/test_reward_validity.py::test_prose_that_parses_is_still_rejected[load the data]": true, "tests/test_reward_validity.py::test_prose_that_parses_is_still_rejected[please print the data]": true}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114[ "tests/test_decision_judge.py::TestErrorHandling::test_empty_code_is_rejected", "tests/test_decision_judge.py::TestErrorHandling::test_on_error_raise_propagates", "tests/test_decision_judge.py::TestErrorHandling::test_on_error_static_falls_back_to_regex_rules", "tests/test_decision_judge.py::TestErrorHandling::test_on_error_zero_returns_neutral_rewards", "tests/test_decision_judge.py::TestErrorHandling::test_unknown_rater_name_is_rejected", "tests/test_decision_judge.py::TestInjectedJudge::test_cache_can_be_disabled", "tests/test_decision_judge.py::TestInjectedJudge::test_caching_makes_repeat_scoring_free", "tests/test_decision_judge.py::TestInjectedJudge::test_combined_decision_reward_matches_static_normalization", "tests/test_decision_judge.py::TestInjectedJudge::test_compute_decision_rewards_uses_injected_judge", "tests/test_decision_judge.py::TestQuestionSchema::test_all_questions_are_noul", "tests/test_decision_judge.py::TestQuestionSchema::test_question_names_cover_every_static_rule", "tests/test_decision_judge.py::TestRuleMapping::test_chroptiks_wins_over_matplotlib", "tests/test_decision_judge.py::TestRuleMapping::test_clean_code_earns_the_static_soft_credit", "tests/test_decision_judge.py::TestRuleMapping::test_clean_code_scores_above_violating_code", "tests/test_decision_judge.py::TestRuleMapping::test_dataframe_preference_distinguishes_both_writers", "tests/test_decision_judge.py::TestRuleMapping::test_hard_violations_reach_the_static_penalty_floor", "tests/test_decision_judge.py::TestRuleMapping::test_logging_preference_has_three_branches", "tests/test_decision_judge.py::TestRuleMapping::test_probabilities_are_clamped", "tests/test_decision_judge.py::TestRuleMapping::test_threshold_controls_the_multi_state_rules", "tests/test_decision_judge.py::TestScoreCompletionWiring::test_decision_rater_is_selected_and_recorded", "tests/test_decision_judge.py::TestScoreCompletionWiring::test_reward_config_builds_a_decision_config", "tests/test_decision_judge.py::TestScoreCompletionWiring::test_static_rater_records_its_name", "tests/test_grpo_evaluator.py::test_build_judge_prompt_contains_code", "tests/test_grpo_evaluator.py::test_compute_grpo_reward_bad_code", "tests/test_grpo_evaluator.py::test_compute_grpo_reward_perfect_code", "tests/test_grpo_evaluator.py::test_mock_judge_returns_valid_structure", "tests/test_grpo_evaluator.py::test_parse_judge_response_bad_json_defaults", "tests/test_grpo_evaluator.py::test_parse_judge_response_full_dict", "tests/test_grpo_evaluator.py::test_parse_judge_response_string_json", "tests/test_grpo_pipeline.py::TestBuildTrainer::test_raises_when_npcpy_missing", "tests/test_grpo_pipeline.py::TestCheckpointHelpers::test_load_missing_meta_returns_zero", "tests/test_grpo_pipeline.py::TestCheckpointHelpers::test_save_and_load_roundtrip", "tests/test_grpo_pipeline.py::TestGuacRewardAdapter::test_breakdown_grpo_path", "tests/test_grpo_pipeline.py::TestGuacRewardAdapter::test_breakdown_legacy_path", "tests/test_grpo_pipeline.py::TestGuacRewardAdapter::test_scalar_reward_grpo_path", "tests/test_grpo_pipeline.py::TestGuacRewardAdapter::test_scalar_reward_legacy_path", "tests/test_grpo_pipeline.py::TestRunGrpo::test_metrics_jsonl_created", "tests/test_grpo_pipeline.py::TestRunGrpo::test_resume_from_checkpoint", "tests/test_rater_audit.py::test_abstention_is_not_a_disagreement", "tests/test_rater_audit.py::test_agreement_requires_same_position", "tests/test_rater_audit.py::test_all_failed_rater_is_inconclusive_not_agreement", "tests/test_rater_audit.py::test_bargraph_detector_catches_attribute_calls[def my_bar_plot():\\n return 1\\n-0.5]", "tests/test_rater_audit.py::test_bargraph_detector_catches_attribute_calls[import matplotlib.pyplot as plt\\nplt.bar([1],[2])\\n--1.0]", "tests/test_rater_audit.py::test_bargraph_detector_catches_attribute_calls[import pandas as pd\\npd.DataFrame().to_csv(\"o.csv\")\\n-0.5]", "tests/test_rater_audit.py::test_bargraph_detector_catches_attribute_calls[import seaborn as sns\\nsns.barplot(x=[1],y=[2])\\n--1.0]", "tests/test_rater_audit.py::test_contradiction_is_flagged_as_credited_violation", "tests/test_rater_audit.py::test_corpus_labels_match_static_rules", "tests/test_rater_audit.py::test_grid_detector_catches_style_grids[ax.grid(True)\\n--1.0]", "tests/test_rater_audit.py::test_grid_detector_catches_style_grids[import logging\\nlogging.info(\"x\")\\n-0.5]", "tests/test_rater_audit.py::test_grid_detector_catches_style_grids[import matplotlib.pyplot as plt\\nplt.style.use(\"seaborn-v0_8-whitegrid\")\\n--1.0]", "tests/test_rater_audit.py::test_grid_detector_catches_style_grids[import seaborn as sns\\nsns.set_style(\"whitegrid\")\\n--1.0]", "tests/test_rater_audit.py::test_label_accuracy_compares_direction_not_magnitude", "tests/test_rater_audit.py::test_label_accuracy_skips_failed_rows", "tests/test_rater_audit.py::test_partial_failure_excludes_only_failed_cases", "tests/test_reward_validity.py::test_closed_fence_still_wins_over_whole_text", "tests/test_reward_validity.py::test_decision_rater_applies_the_same_floor", "tests/test_reward_validity.py::test_decision_rater_floors_real_truncated_sample", "tests/test_reward_validity.py::test_decision_rater_still_calls_model_for_valid_code", "tests/test_reward_validity.py::test_empty_completion_is_not_rewarded", "tests/test_reward_validity.py::test_empty_response_is_reported_as_empty", "tests/test_reward_validity.py::test_export_grpo_omits_unparseable_traces", "tests/test_reward_validity.py::test_export_sft_skips_task_with_only_unparseable_traces", "tests/test_reward_validity.py::test_export_sft_skips_unparseable_best_trace", "tests/test_reward_validity.py::test_extract_code_strips_fences[closed_fence-```python\\ndef add(a, b):\\n return a + b\\n```\\n]", "tests/test_reward_validity.py::test_extract_code_strips_fences[unterminated_fence-```python\\nimport logging\\nlogger = logging.getLogger()\\n]", "tests/test_reward_validity.py::test_extract_code_strips_fences[unterminated_fence_with_prose-Here you go:\\n```python\\ndef add(a, b):\\n return a + b\\n]", "tests/test_reward_validity.py::test_garbage_never_outranks_working_code", "tests/test_reward_validity.py::test_prose_that_does_not_parse_is_rejected[load the data]", "tests/test_reward_validity.py::test_prose_that_does_not_parse_is_rejected[please print the data]", "tests/test_reward_validity.py::test_prose_that_does_not_parse_is_rejected[plot the data]", "tests/test_reward_validity.py::test_prose_that_does_not_parse_is_rejected[return the result]", "tests/test_reward_validity.py::test_prose_that_parses_is_still_rejected[data is loaded]", "tests/test_reward_validity.py::test_prose_that_parses_is_still_rejected[load the data]", "tests/test_reward_validity.py::test_prose_that_parses_is_still_rejected[please print the data]", "tests/test_reward_validity.py::test_prose_that_parses_is_still_rejected[this is not python]", "tests/test_reward_validity.py::test_thinking_only_response_yields_no_code", "tests/test_reward_validity.py::test_unparseable_code_is_rejected[empty-]", "tests/test_reward_validity.py::test_unparseable_code_is_rejected[prose-this is not python at all!!! 12345]", "tests/test_reward_validity.py::test_unparseable_code_is_rejected[stray_fence-```python\\n]", "tests/test_reward_validity.py::test_unparseable_code_is_rejected[truncated_def-def f(\\n x = ]", "tests/test_reward_validity.py::test_unparseable_code_is_rejected[unterminated_call-import pandas as pd\\n\\ndf = pd.DataFrame(]", "tests/test_reward_validity.py::test_unparseable_code_is_rejected[whitespace- \\n\\t\\n]", "tests/test_reward_validity.py::test_unparseable_code_scores_at_the_floor[empty-]", "tests/test_reward_validity.py::test_unparseable_code_scores_at_the_floor[prose-this is not python at all!!! 12345]", "tests/test_reward_validity.py::test_unparseable_code_scores_at_the_floor[stray_fence-```python\\n]", "tests/test_reward_validity.py::test_unparseable_code_scores_at_the_floor[truncated_def-def f(\\n x = ]", "tests/test_reward_validity.py::test_unparseable_code_scores_at_the_floor[unterminated_call-import pandas as pd\\n\\ndf = pd.DataFrame(]", "tests/test_reward_validity.py::test_unparseable_code_scores_at_the_floor[whitespace- \\n\\t\\n]", "tests/test_reward_validity.py::test_unterminated_fence_is_labelled_and_parses", "tests/test_reward_validity.py::test_working_script_is_valid", "tests/test_rewards.py::TestRewardComputation::test_bad_code_gets_negative_reward", "tests/test_rewards.py::TestRewardComputation::test_good_code_gets_positive_reward", "tests/test_rewards.py::TestRewardComputation::test_total_static_reward_scalar", "tests/test_rewards.py::TestStyleChecks::test_has_checkpointing_false", "tests/test_rewards.py::TestStyleChecks::test_has_checkpointing_true", "tests/test_rewards.py::TestStyleChecks::test_has_chroptiks_false", "tests/test_rewards.py::TestStyleChecks::test_has_chroptiks_true", "tests/test_rewards.py::TestStyleChecks::test_has_class_defs_false", "tests/test_rewards.py::TestStyleChecks::test_has_class_defs_true", "tests/test_rewards.py::TestStyleChecks::test_has_dataframe_to_csv_false", "tests/test_rewards.py::TestStyleChecks::test_has_dataframe_to_csv_true", "tests/test_rewards.py::TestStyleChecks::test_has_function_defs_false", "tests/test_rewards.py::TestStyleChecks::test_has_function_defs_true", "tests/test_rewards.py::TestStyleChecks::test_has_logging_false", "tests/test_rewards.py::TestStyleChecks::test_has_logging_true", "tests/test_rewards.py::TestStyleChecks::test_has_narrative_comments_false", "tests/test_rewards.py::TestStyleChecks::test_has_narrative_comments_true", "tests/test_rewards.py::TestStyleChecks::test_has_try_except_false", "tests/test_rewards.py::TestStyleChecks::test_has_try_except_true", "tests/test_rewards.py::TestStyleChecks::test_is_bare_script_false_with_function", "tests/test_rewards.py::TestStyleChecks::test_is_bare_script_false_with_main_guard", "tests/test_rewards.py::TestStyleChecks::test_is_bare_script_true"]1[]12# Automatically created by ruff.*1Signature: 8a477f597d28d172789f06886806bc55123---license: mit---123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293# guac-coderLLM fine-tuning for research code and scientific writing. This repo houses projects that useLLM responses containing Python code snippets for research tasks, starting with a **GRPO(Group Relative Policy Optimization) RL adapter** for text-generation models.The core idea: instead of teaching a model to write *any* working Python, teach it to writePython that matches a specific, opinionated set of research-code conventions. Thoseconventions are encoded as **13 rule-based rewards** that score generated code in `[-1, 1]`.## Install```bashpip install -e . # core (numpy, pandas)pip install -e ".[mlx]" # Apple Silicon trainingpip install -e ".[torch]" # CUDA/CPU trainingpip install -e ".[all]"```## The 13 reward rulesEach 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` || 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`).A **legacy** 12-rule path also lives in `guac_coder/rewards.py`(`compute_static_rewards` / `compute_total_reward`), plus an optional LLM-as-judgecomponent (`compute_llm_judge_reward`) that calls `npcpy.llm_funcs.get_llm_response`with `format="json"`. The newer `grpo_rewards` path is the default everywhere.## Raters: static, decision, or llmThe 13 rules can be judged three ways. Pick with `--rater` (CLI), `rater`(`RewardConfig`), or the `rater=` argument in Python.| rater | how it scores | cost | needs ||---|---|---|---|| `static` (default) | regex + AST inspection, no model | free | nothing || `decision` | Ollama `/v1/systemone` decision model (`clef`) | 1 local request | Ollama >= 0.35 + pulled model || `llm` | generative LLM-as-judge returning JSON | 1 full generation | API key / `npcpy` |### The decision rater`guac_coder/decision_judge.py` replaces the full LLM call with a **decisionmodel**: the candidate code is posted as `state` alongside 17 typed yes/noquestions, and the endpoint returns a calibrated `P(true)` for each in a singlerequest. There is no prose to parse and no reasoning budget to exhaust.```bashollama pull clef # 27B, ~18-20 GB localguac-reward --task demo --code script.py --rater decision --rater-model clefguac-reward --task demo --code script.py --rater decision --rater-model clef:cloud # no downloadguac-train --rater decision --rater-model clef:cloud --iterations 100guac-coder trace --models qwen3.5:0.8b --rater decision --rater-model clef:cloud```Flags: `--rater-model`, `--rater-base-url`, `--rater-threshold` (probabilitycutoff for the multi-state rules, default `0.5`), and `--rater-on-error`(`static` falls back to the regex rules, `zero` returns neutral rewards,`raise` propagates).Each of the 17 questions maps onto one of the 13 rule names produced by`compute_grpo_rewards`, and each rule reproduces the exact interval its staticcounterpart emits (for example `no_seaborn_reward` is `-1.0` on a violation and`+0.5` when clean). Decision scores and static scores are therefore directlycomparable and mixable, and values are clamped into `[-1, 1]`.```pythonfrom guac_coder import DecisionJudgeConfig, compute_decision_rewards, combined_decision_rewardcfg = DecisionJudgeConfig(model="clef:cloud", threshold=0.5, on_error="static")rules = compute_decision_rewards(code, cfg=cfg) # same 13 keys as compute_grpo_rewardstotal = combined_decision_reward(code, cfg=cfg) # same normalization as combined_grpo_reward```Because the judge is injectable, the path is testable offline:```pythoncompute_decision_rewards(code, cfg=cfg, judge_fn=lambda code, cfg=None: {q: 1.0 for q in QUESTIONS})```## Iterating on the rewards: rater auditChanging a reward rule is only safe if you can measure the change. `guac-audit`scores a directory of labeled `.py` cases with two raters and reportsper-rule agreement:```bashguac-audit --corpus ./audit_corpus --rater-a static --rater-b decision \--rater-model tev1:0.8b --output /tmp/audit.json``````Rater audit: static vs decision over 11 casescompared: 11 mean total: static=0.1643 decision=0.1958rule n agree abstain static>0,decision<0 mean gapobjective_comments_reward 11 0.00 10 0 1.50pandas_csv_preference_reward 11 0.80 6 1 2.00no_classes_reward 11 0.82 0 2 1.50resumable_checkpoint_reward 11 0.82 0 0 2.00no_bargraphs_reward 11 0.91 0 1 1.50not_bare_script_reward 11 0.91 0 0 1.50no_seaborn_reward 11 1.00 0 0 0.00no_plot_grids_reward 11 1.00 0 0 0.00no_plot_titles_reward 11 1.00 0 0 0.00no_try_except_reward 11 1.00 0 0 0.00logging_over_print_reward 11 1.00 5 0 0.00chroptiks_preference_reward 11 1.00 9 0 0.00intermittent_writes_reward 11 n/a 11 0 0.00Labeled accuracy (rater vs corpus labels):static 1.00 (30/30 checked)decision 0.80 (24/30 checked)Verdict: 1 rule(s) below 0.8 agreement: objective_comments_reward.````intermittent_writes_reward` shows `n/a`: the decision model abstained on all11 cases, so there is nothing to compare -- not a 0% agreement.How to read it:* **agree** -- share of cases where both raters took the *same* position.A `0.0` from one side is scored as an **abstention**, not a contradiction,so a rule that legitimately returns "no opinion" does not look broken.* **static>0, decision<0** -- static **rewards** code the other rater calls aviolation. This is the dangerous direction: it pays the model to write badcode, and it is the first thing to fix.* **Verdict** -- `INCONCLUSIVE` when no case was scored by both raters. Afailed rater is never silently replaced by the one being audited; the auditsets `on_error="raise"` so a broken endpoint shows up as a failure.Cases are plain `.py` files; `labels.json` may map filenames to expected rulevalues for an informal `static vs expectation` check.### Known static blind spots (found by the audit)These all **rewarded** violating code before being fixed, and each now has aregression case in `audit_corpus/`:| violation | why the old regex missed it ||---|---|| `sns.barplot(...)`, `sns.countplot(...)` | pattern was the bare token `bar(`, which never matches after a `.` || `plt.bar(...)`, `ax.barh(...)` | same prefix problem || `sns.set_style("whitegrid")` | enables grids via a *string*, never calls `grid(...)` || `plt.style.use("seaborn-v0_8-whitegrid")` | same |Run the audit after any reward change and diff the report against the previousone -- agreement going down, or a new `static>0, decision<0` entry, means theedit introduced a hole.**Agreement is not accuracy.** A weak second rater can disagree with a correctrule. Always read the labeled-accuracy block, which is why the corpus carrieslabels. Measured on the current 11-case corpus:| rater | labeled accuracy ||---|---|| `static` | **1.00** (30/30) || `decision` with `tev1:0.8b` | 0.80 (24/30) || `decision` with `clef:cloud` | not measurable here (account out of credits; the audit reports `INCONCLUSIVE` rather than false agreement) |So a small local decision model is *not* yet a trustworthy oracle: with`tev1:0.8b` it claimed `clean_full.py` used bars, defined classes and skipped`to_csv`, all of which are false. Use the decision rater as a second opinion to*find* suspected static holes, then confirm each one against the labels -- andsize up to a stronger decision model before trusting its score in training.### Known scoring issue: the free-credit floorEvery rule returns positive credit for *not* violating, so a snippet that doesnothing collects a large total:| snippet | total ||---|---|| `x = 1` | `+0.077` || `viol_grids_titles.py` (grids **and** titles) | `+0.038` || empty / `pass` / comments only | `-1.000` |So `x = 1` outranks a script that has two real violations. Two consequences:* absolute reward values are not comparable across snippets of differentstructure; only the *ranking within a GRPO group* is meaningful;* the shared "clean" credit (`+0.5` on eight rules) dwarfs the individualpenalties, which weakens the gradient for the rules that matter.`not_bare_script_reward` returning `+0.5` for *any* function definition is partof this: one `def` earns full credit for structural quality while contributingnothing. This is the largest open item in the reward design, and exactly thekind of change the audit exists to validate.## Layout```guac_coder/config.py GRPOConfig, RewardConfig, DataConfigdata.py research task prompts, prompt building, SFT pair generation, repo scrapingrewards.py legacy 12-rule static rewards + LLM judgegrpo_rewards.py 13-rule reward set + AST analyzer (default path)grpo_evaluator.py rule-key constants + LLM judge prompt build/parsedecision_judge.py Ollama System-One decision rater (17 typed yes/no questions)grpo_pipeline.py GuacRewardAdapter, build_trainer, run_grpo (npcpy.ft.rl bridge)training.py train_grpo loop (MLX preferred, torch fallback), checkpointscli.py guac-coder / guac-train / guac-eval / guac-reward entrypointstests/ 60 tests covering rewards, evaluator, pipeline, and raters```## UsageScore a snippet with the 13 rules (default):```bashguac-reward --task "plot embedding space" --code path/to/script.pyguac-reward --task "plot embedding space" --code path/to/script.py --jsonguac-reward --task "plot embedding space" --code path/to/script.py --legacy```Evaluate with the legacy static + LLM-judge split:```bashguac-eval --file path/to/script.pyguac-eval --file path/to/script.py --json --judge-model gpt-4o```Train (defaults to the 13-rule rewards, matching the CLI):```bashguac-train --model Qwen/Qwen2.5-Coder-7B --output-dir ./grpo_output --iterations 100guac-train --legacy-rewards # optimize the legacy rewards.py score instead```Equivalent subcommand form: `guac-coder train|eval|reward ...`From Python:```pythonfrom guac_coder import compute_grpo_rewards, combined_grpo_rewardrules = compute_grpo_rewards(code)total = combined_grpo_reward(code)```Both scoring paths are selectable from Python as well:```pythonfrom guac_coder import GuacRewardAdapter, run_grpo, train_grpoGuacRewardAdapter(use_grpo_rewards=True)(code) # 13-rule score (default)GuacRewardAdapter(use_grpo_rewards=False)(code) # legacy static + judge scoretrain_grpo(cfg, reward_cfg, get_llm_response_fn, use_grpo_rewards=True)run_grpo(use_grpo_rewards=True, ...)```## Training details- Backend: `mlx` when `mlx-lm` is importable (Apple Silicon), otherwise `transformers` + `torch`.- Group sampling: `group_size` completions per prompt at `temperature`; rewards arecomputed per completion and converted into GRPO advantages (`epsilon`, `beta` in `GRPOConfig`).- Metrics: one JSON line per iteration appended to `<output-dir>/metrics.jsonl`, includingthe reward mode, per-sample rewards, and scalar reward (`total`, `static`, `llm`).- Checkpoints: `<output-dir>/checkpoint_XXXXX.pkl` every `checkpoint_interval` iterations;resume with `--resume-from <output-dir>/checkpoint_XXXXX.pkl`.## Tests```bashpython -m pytest -q```## StatusAlpha. Reward rules and the training loop are implemented and tested; end-to-end trainingrequires a model backend (`mlx-lm` or `torch`/`transformers`) and, for judge-based scoring,`npcpy` with credentials configured.
123456789101112131415161718192021222324252627282930313233343536"""Compute summary statistics and write results incrementally."""
import loggingimport os
import chroptiks as cptimport pandas as pd
logger = logging.getLogger(__name__)
OUT = "results.csv"STATE = "state.json"
def load_state(path): if os.path.exists(path): with open(path) as fh: return fh.read() return None
def run(rows): for i, row in enumerate(rows): df = pd.DataFrame([row]) df.to_csv(OUT, mode="a", header=(i == 0), index=False) logger.info("wrote row %d", i)
def main(): rows = [{"a": i, "b": i * 2} for i in range(10)] run(rows) cpt.plot(OUT)
if __name__ == "__main__": main()1234567891011import logging
logger = logging.getLogger(__name__)
def main(): logger.info("hello")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233{ "clean_full.py": { "no_seaborn_reward": 0.5, "no_plot_grids_reward": 0.5, "no_plot_titles_reward": 0.5, "no_bargraphs_reward": 0.5, "no_try_except_reward": 0.5, "no_classes_reward": 0.5, "not_bare_script_reward": 0.5, "chroptiks_preference_reward": 1.0, "pandas_csv_preference_reward": 1.0, "logging_over_print_reward": 1.0 }, "clean_minimal.py": { "no_seaborn_reward": 0.5, "no_plot_grids_reward": 0.5, "no_plot_titles_reward": 0.5, "no_bargraphs_reward": 0.5, "no_try_except_reward": 0.5, "no_classes_reward": 0.5, "not_bare_script_reward": 0.5, "chroptiks_preference_reward": 0.0 }, "viol_seaborn.py": {"no_seaborn_reward": -1.0, "chroptiks_preference_reward": -1.0}, "viol_bargraph_seaborn_api.py": {"no_seaborn_reward": -1.0, "no_bargraphs_reward": -1.0}, "viol_try_except.py": {"no_try_except_reward": -1.0}, "viol_classes.py": {"no_classes_reward": -1.0}, "viol_prints.py": {"logging_over_print_reward": -1.0}, "viol_bare_script.py": {"not_bare_script_reward": -1.0}, "viol_grids_titles.py": {"no_plot_grids_reward": -1.0, "no_plot_titles_reward": -1.0}, "viol_dictwriter.py": {"pandas_csv_preference_reward": -1.0}, "viol_narrative.py": {"objective_comments_reward": -1.0}}12345import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3]})df.to_csv("out.csv", index=False)print("wrote out.csv")1234567891011121314"""Bar chart via the seaborn API, without a literal bar-call token."""
import pandas as pdimport seaborn as sns
def draw(): df = pd.DataFrame({"cat": ["x", "y"], "val": [1, 2]}) sns.barplot(data=df, x="cat", y="val") sns.despine()
if __name__ == "__main__": draw()123456789101112131415import logging
logger = logging.getLogger(__name__)
class Runner: def __init__(self, n): self.n = n
def go(self): logger.info("running %d", self.n)
if __name__ == "__main__": Runner(3).go()12345678910111213141516import csvimport logging
logger = logging.getLogger(__name__)
def run(rows): with open("o.csv", "w", newline="") as fh: writer = csv.DictWriter(fh, fieldnames=["a", "b"]) writer.writeheader() for row in rows: writer.writerow(row)
if __name__ == "__main__": run([{"a": 1, "b": 2}])123456789101112import chroptiks as cpt
def draw(): fig = cpt.plot("data.csv") fig.grid(True) fig.set_title("My Results") return fig
if __name__ == "__main__": draw()1234567891011121314# Let's start by importing what we need.# We will then load the data and make sure it is clean.# Note that this is important for correctness.# Remember to save the output at the end.import pandas as pd
def run(): df = pd.DataFrame({"a": [1]}) df.to_csv("o.csv", index=False)
if __name__ == "__main__": run()123456789101112import pandas as pd
def run(): print("starting") df = pd.DataFrame({"a": [1]}) df.to_csv("o.csv", index=False) print("done")
if __name__ == "__main__": run()12345678910import seaborn as snsimport pandas as pd
def draw(df): sns.scatterplot(data=df, x="a", y="b")
if __name__ == "__main__": draw(pd.DataFrame({"a": [1], "b": [2]}))123456789101112131415import logging
logger = logging.getLogger(__name__)
def load(path): try: with open(path) as fh: return fh.read() except Exception: return None
if __name__ == "__main__": load("data.txt")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"""guac-coder: LLM fine-tuned for research code and scientific writing."""
__version__ = "0.1.0"
from guac_coder.config import DataConfig, GRPOConfig, RewardConfigfrom guac_coder.data import ( build_prompt, generate_sft_pairs, load_code_from_repos, load_data, load_research_tasks, prepare_training_examples, save_data,)from guac_coder.decision_judge import ( DecisionJudgeConfig, DecisionRaterError, ask_decision_model, available, clear_cache, combined_decision_reward, compute_decision_rewards, map_to_rule_rewards,)from guac_coder.grpo_evaluator import ( _RULE_KEYS, build_judge_prompt, compute_grpo_reward, parse_judge_response,)from guac_coder.grpo_pipeline import ( GuacRewardAdapter, build_trainer, run_grpo,)from guac_coder.grpo_rewards import ( GRPO_REWARD_REGISTRY, StaticCodeAnalyzer, combined_grpo_reward, compute_grpo_rewards,)from guac_coder.rater_audit import compare_raters, run_auditfrom guac_coder.rewards import ( compute_llm_judge_reward, compute_static_rewards, compute_total_reward, total_static_reward,)from guac_coder.training import ( load_checkpoint, save_checkpoint, score_completion, train_grpo,)
__all__ = [ "__version__", "GRPOConfig", "RewardConfig", "DataConfig", "compute_static_rewards", "compute_llm_judge_reward", "compute_total_reward", "total_static_reward", "load_research_tasks", "build_prompt", "prepare_training_examples", "load_code_from_repos", "save_data", "load_data", "generate_sft_pairs", "train_grpo", "score_completion", "run_audit", "compare_raters", "load_checkpoint", "save_checkpoint", "GuacRewardAdapter", "build_trainer", "run_grpo", "compute_grpo_reward", "build_judge_prompt", "parse_judge_response", "_RULE_KEYS", "compute_grpo_rewards", "combined_grpo_reward", "GRPO_REWARD_REGISTRY", "StaticCodeAnalyzer", "DecisionJudgeConfig", "DecisionRaterError", "ask_decision_model", "available", "clear_cache", "combined_decision_reward", "compute_decision_rewards", "map_to_rule_rewards",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612"""CLI entry points for guac-coder."""
import argparseimport jsonimport loggingimport osimport sys
from guac_coder.config import GRPOConfig, RewardConfigfrom guac_coder.data import build_promptfrom guac_coder.rewards import compute_total_rewardfrom guac_coder.training import train_grpo
def _read_code_file(path: str) -> str: """Read a Python file, exiting with a clean message if it is missing.""" if not os.path.isfile(path): raise SystemExit(f"error: no such file: {path}") with open(path, "r", encoding="utf-8") as fh: return fh.read()
RATER_CHOICES = ("static", "decision", "llm")
def _add_rater_args(parser: argparse.ArgumentParser) -> None: """Attach the shared rater-selection flags to a subparser.""" parser.add_argument( "--rater", default="static", choices=list(RATER_CHOICES), help=( "Scoring backend: static (13 regex/AST rules), decision (Ollama " "System-One decision model, e.g. clef), or llm (generative judge)" ), ) parser.add_argument( "--rater-model", default="clef", help="Decision model tag for --rater decision (e.g. clef, clef:cloud)", ) parser.add_argument( "--rater-base-url", default="http://localhost:11434", help="Ollama base URL for the decision rater", ) parser.add_argument( "--rater-threshold", type=float, default=0.5, help="Probability cutoff for multi-state decision rules", ) parser.add_argument( "--rater-on-error", default="static", choices=["static", "zero", "raise"], help="Behaviour when the decision endpoint fails", )
def _reward_config_from_args(args: argparse.Namespace) -> RewardConfig: """Build a RewardConfig from the rater flags on ``args``.""" kwargs = {} if getattr(args, "judge_model", None): kwargs["judge_model"] = args.judge_model if getattr(args, "rater", None): kwargs["rater"] = args.rater if getattr(args, "rater_model", None): kwargs["decision_model"] = args.rater_model if getattr(args, "rater_base_url", None): kwargs["decision_base_url"] = args.rater_base_url if getattr(args, "rater_threshold", None) is not None: kwargs["decision_threshold"] = args.rater_threshold if getattr(args, "rater_on_error", None): kwargs["decision_on_error"] = args.rater_on_error return RewardConfig(**kwargs)
def _resolve_llm_judge(): """Return an LLM judge callable for the legacy rewards.py path.
Uses npcpy.llm_funcs.get_llm_response when importable. Falls back to a judge that returns no scores, which makes the LLM component contribute zero rather than failing the run. """ try: from npcpy.llm_funcs import get_llm_response
return get_llm_response except Exception as exc: # pragma: no cover - depends on environment logging.warning("LLM judge unavailable (%s); scoring static components only", exc)
def _no_judge(**kwargs): return {}
return _no_judge
def _setup_logging(level: int = logging.INFO) -> None: # force=True: npcpy and friends install root handlers at import time, and # plain basicConfig() would silently no-op, swallowing our INFO progress. logging.basicConfig( level=level, format="%(asctime)s [%(levelname)s] %(message)s", stream=sys.stdout, force=True, ) logging.getLogger("guac_coder").setLevel(level)
def main() -> None: parser = argparse.ArgumentParser(description="guac-coder: research code LLM") subparsers = parser.add_subparsers(dest="command")
# train train_parser = subparsers.add_parser("train", help="Run GRPO training") train_parser.add_argument("--model", default="Qwen/Qwen2.5-Coder-7B") train_parser.add_argument("--output-dir", default="./grpo_output") train_parser.add_argument("--data", default=None, help="Path to JSONL training data") train_parser.add_argument("--iterations", type=int, default=100) train_parser.add_argument("--group-size", type=int, default=8) train_parser.add_argument("--lr", type=float, default=1e-5) train_parser.add_argument("--resume-from", default=None) train_parser.add_argument("--backend", default="auto", choices=["auto", "mlx", "torch"]) train_parser.add_argument( "--legacy-rewards", action="store_true", help="Optimize the legacy rewards.py score instead of the 13-rule grpo_rewards", ) _add_rater_args(train_parser)
# eval eval_parser = subparsers.add_parser("eval", help="Evaluate code with reward function") eval_parser.add_argument("code", nargs="?", help="Python code string or '-' for stdin") eval_parser.add_argument("--file", default=None, help="Python file to evaluate") eval_parser.add_argument("--judge-model", default="gpt-4o") eval_parser.add_argument("--json", action="store_true", help="Output JSON") _add_rater_args(eval_parser)
# reward reward_parser = subparsers.add_parser("reward", help="Compute reward for a code snippet") reward_parser.add_argument("--task", required=True, help="Task description") reward_parser.add_argument("--code", required=True, help="Code snippet or file path") reward_parser.add_argument("--llm-judge", action="store_true", help="Include LLM judge") reward_parser.add_argument( "--legacy", action="store_true", help="Use the legacy rewards.py path instead of the 13-rule grpo_rewards", ) reward_parser.add_argument("--json", action="store_true", help="Output JSON") _add_rater_args(reward_parser)
# trace trace_parser = subparsers.add_parser( "trace", help="Generate scored traces from local Ollama models" ) trace_parser.add_argument("--models", required=True, help="Comma-separated model names") trace_parser.add_argument("--output-dir", default="./traces") trace_parser.add_argument("--tasks", default=None) trace_parser.add_argument("--limit", type=int, default=None) trace_parser.add_argument("--n-samples", type=int, default=1) trace_parser.add_argument("--num-predict", type=int, default=1024) trace_parser.add_argument("--temperature", type=float, default=0.8) trace_parser.add_argument("--seed", type=int, default=42) trace_parser.add_argument("--base-url", default="http://localhost:11434") trace_parser.add_argument("--timeout", type=float, default=600.0) trace_parser.add_argument("--no-think", action="store_true") trace_parser.add_argument("--no-resume", action="store_true") trace_parser.add_argument( "--model-opt", action="append", default=None, help="Per-model setting, repeatable: MODEL:key=value[,key=value]. " "Keys: num_predict, think, temperature, timeout", ) trace_parser.add_argument("--json", action="store_true") _add_rater_args(trace_parser)
# export export_parser = subparsers.add_parser( "export", help="Convert traces into SFT / preference / GRPO datasets" ) export_parser.add_argument("--traces", required=True, help="Path to traces JSONL") export_parser.add_argument("--output-dir", default=None) export_parser.add_argument("--min-reward", type=float, default=None) export_parser.add_argument("--min-gap", type=float, default=0.15) export_parser.add_argument("--json", action="store_true")
# audit audit_parser = subparsers.add_parser( "audit", help="Measure per-rule agreement between two raters" ) audit_parser.add_argument("--corpus", required=True, help="Directory of .py cases") audit_parser.add_argument("--rater-a", default="static") audit_parser.add_argument("--rater-b", default="decision") audit_parser.add_argument("--rater-model", default=None) audit_parser.add_argument("--output", default=None, help="Write JSON report here") audit_parser.add_argument("--json", action="store_true")
args = parser.parse_args()
if args.command == "train": train_command(args) elif args.command == "eval": eval_command(args) elif args.command == "reward": reward_command(args) elif args.command == "trace": trace_command(args) elif args.command == "export": export_command(args) elif args.command == "audit": audit_command(args) else: parser.print_help()
def train_command(args: argparse.Namespace | None = None) -> None: """Run GRPO training.""" if args is None: args = _parse_train_args()
_setup_logging()
cfg = GRPOConfig( model_name=args.model, output_dir=args.output_dir, num_iterations=args.iterations, group_size=args.group_size, learning_rate=args.lr, resume_from_checkpoint=args.resume_from, backend=getattr(args, "backend", "auto"), ) reward_cfg = _reward_config_from_args(args)
use_grpo_rewards = not getattr(args, "legacy_rewards", False) rater = getattr(args, "rater", "static") if getattr(args, "legacy_rewards", False): rater = "llm" # The LLM judge is only consulted on the legacy path; static and decision # raters never call it. get_llm_response_fn = _resolve_llm_judge() if rater == "llm" else (lambda **kwargs: {})
train_grpo( cfg, reward_cfg, get_llm_response_fn, data_path=args.data, use_grpo_rewards=use_grpo_rewards, rater=rater, )
def eval_command(args: argparse.Namespace | None = None) -> None: """Evaluate code with the legacy 12-rule reward function (static + LLM judge).""" if args is None: args = _parse_eval_args()
_setup_logging()
if args.file: code = _read_code_file(args.file) elif args.code and args.code != "-": code = args.code else: code = sys.stdin.read()
reward_cfg = _reward_config_from_args(args) rater = getattr(args, "rater", "static")
if rater == "llm": result = compute_total_reward(code, _resolve_llm_judge(), reward_cfg) else: from guac_coder.training import score_completion
_total, details = score_completion(code, lambda **kwargs: {}, reward_cfg, rater=rater) rules = details.get("rules", {}) result = { "total": _total, "rater": rater, "static": _total if rater == "static" else 0.0, "llm": 0.0, "static_components": rules if rater == "static" else {}, "rules": rules, "llm_components": {}, }
if args.json: print(json.dumps(result, indent=2)) else: print(f"Rater: {result.get('rater', 'llm')}") print(f"Total reward: {result['total']:.3f}") if result.get("rater") == "llm": print(f" Static: {result['static']:.3f}") print(f" LLM judge: {result['llm']:.3f}") print("\nStatic components:") for k, v in result.get("static_components", {}).items(): print(f" {k}: {v:+.3f}") print("\nLLM components:") for k, v in result.get("llm_components", {}).items(): print(f" {k}: {v:+.3f}") else: print("\nPer-rule rewards:") for k, v in result.get("rules", {}).items(): print(f" {k}: {v:+.3f}")
def reward_command(args: argparse.Namespace | None = None) -> None: """Compute reward for a task/code pair.""" if args is None: args = _parse_reward_args()
_setup_logging()
code = args.code if code.endswith(".py") and "\n" not in code: code = _read_code_file(code)
prompt = build_prompt(args.task)
# --legacy / --llm-judge force the generative judge path; otherwise --rater # selects between the static rules and a decision model. use_legacy = getattr(args, "legacy", False) or getattr(args, "llm_judge", False) if getattr(args, "llm_judge", False) and not getattr(args, "legacy", False): logging.info("--llm-judge requires the legacy reward path; using --legacy")
reward_cfg = _reward_config_from_args(args) rater = "llm" if use_legacy else getattr(args, "rater", "static") as_json = getattr(args, "json", False)
if rater == "llm": judge = _resolve_llm_judge() if getattr(args, "llm_judge", False) else None get_llm_response_fn = judge or (lambda **kwargs: {}) result = compute_total_reward(code, get_llm_response_fn, reward_cfg) total = result["total"] breakdown = result.get("static_components", {}) extra = {"static": result["static"], "llm": result["llm"]} else: from guac_coder.training import score_completion
total, details = score_completion(code, lambda **kwargs: {}, reward_cfg, rater=rater) breakdown = details.get("rules", {}) extra = {}
if as_json: print( json.dumps( { "task": args.task, "rater": rater, "total": total, **extra, "rules": breakdown, }, indent=2, ) ) return
print(f"Task: {args.task}") print(f"Rater: {rater}") print(f"Prompt length: {len(prompt)} chars") print(f"Code length: {len(code)} chars") print(f"Total reward: {total:.3f}") for key, value in extra.items(): print(f" {key}: {value:+.3f}") print("\nPer-rule rewards:") for name, value in breakdown.items(): print(f" {name}: {value:+.3f}")
def _parse_model_opts(specs) -> dict: """Parse --model-opt MODEL:key=value[,key=value] into per-model settings.""" overrides = {} for spec in specs or []: # Model names contain colons (lfm3:latest), so split on the first # known key marker rather than on the first colon. marker = None for candidate in ("num_predict=", "think=", "temperature=", "timeout="): idx = spec.find(candidate) if idx != -1 and (marker is None or idx < marker): marker = idx if marker is None: raise SystemExit("error: malformed --model-opt '%s' (want MODEL:key=value)" % spec) head = spec[:marker].rstrip() if not head.endswith(":"): raise SystemExit("error: malformed --model-opt '%s' (want MODEL:key=value)" % spec) model = head[:-1].strip() rest = spec[marker:] settings = overrides.setdefault(model, {}) for pair in rest.split(","): key, _, value = pair.partition("=") key, value = key.strip(), value.strip() if not key or not value: raise SystemExit("error: malformed --model-opt pair '%s'" % pair) if key == "num_predict" or key == "timeout": try: value = int(float(value)) if key == "num_predict" else float(value) except ValueError: raise SystemExit( "error: --model-opt %s needs a number, got '%s'" % (key, value) ) elif key == "temperature": try: value = float(value) except ValueError: raise SystemExit("error: --model-opt temperature needs a number") elif key == "think": value = value.lower() in ("1", "true", "yes", "on") else: raise SystemExit("error: unknown --model-opt key '%s'" % key) settings[key] = value return overrides
def trace_command(args: argparse.Namespace | None = None) -> None: """Generate scored traces from local Ollama models.""" if args is None: args = _parse_trace_args()
_setup_logging()
from guac_coder.data import load_research_tasks from guac_coder.trace import run_experiment
models = [m.strip() for m in args.models.split(",") if m.strip()] tasks = load_research_tasks(args.tasks) if args.tasks else load_research_tasks() if args.limit: tasks = tasks[: args.limit]
summary = run_experiment( models=models, output_dir=args.output_dir, tasks=tasks, n_samples=args.n_samples, base_url=args.base_url, num_predict=args.num_predict, temperature=args.temperature, seed=args.seed, think=not args.no_think, timeout=args.timeout, resume=not args.no_resume, model_overrides=_parse_model_opts(getattr(args, "model_opt", None)), rater=getattr(args, "rater", "static"), reward_cfg=_reward_config_from_args(args), )
if args.json: print(json.dumps(summary, indent=2)) return
print("\nTraces: %s" % summary["traces_path"]) print("New this run: %d" % summary["new_traces_this_run"]) for model, stats in summary["models"].items(): print("\n== %s ==" % model) print( " n=%d scored=%d sources=%s" % (stats["n"], stats["n_scored"], stats["code_sources"]) ) if stats.get("empty_reasons"): print(" empty: %s" % stats["empty_reasons"]) print( " mean_reward=%s std=%s min=%s max=%s" % ( stats["mean_reward"], stats["std_reward"], stats["min_reward"], stats["max_reward"], ) ) print(" mean_code_chars=%s" % stats["mean_code_chars"]) if stats["rules"]: print(" per-rule means (fired fraction):") for rule, rs in stats["rules"].items(): print(" %-34s %+.3f (%.0f%%)" % (rule, rs["mean"], rs["fired_frac"] * 100))
def audit_command(args: argparse.Namespace | None = None) -> None: """Measure per-rule agreement between two raters over a labeled corpus.""" if args is None: args = _parse_audit_args()
_setup_logging()
from guac_coder.rater_audit import format_report, run_audit
report = run_audit( corpus_dir=args.corpus, rater_a=args.rater_a, rater_b=args.rater_b, rater_model=args.rater_model, )
if args.output: with open(args.output, "w", encoding="utf-8") as fh: json.dump(report, fh, indent=2) logging.info("Wrote audit report to %s", args.output)
if args.json: print(json.dumps(report, indent=2)) return
print(format_report(report))
def export_command(args: argparse.Namespace | None = None) -> None: """Convert a traces JSONL into training datasets.""" if args is None: args = _parse_export_args()
_setup_logging()
from guac_coder.trace_export import export_all
output_dir = args.output_dir or os.path.join(os.path.dirname(args.traces) or ".", "datasets") manifest = export_all( traces_path=args.traces, output_dir=output_dir, min_reward=args.min_reward, min_gap=args.min_gap, )
if args.json: print(json.dumps(manifest, indent=2)) return
print( "Traces: %s (%d rows, %d scored)" % (manifest["traces_path"], manifest["n_traces"], manifest["n_scored"]) ) print("SFT: %d -> %s" % (manifest["sft"]["n"], manifest["sft"]["path"])) print("Preference: %d -> %s" % (manifest["preference"]["n"], manifest["preference"]["path"])) print("GRPO: %d -> %s" % (manifest["grpo"]["n"], manifest["grpo"]["path"]))
def _parse_export_args() -> argparse.Namespace: p = argparse.ArgumentParser(description="Export traces to training datasets") p.add_argument("--traces", required=True) p.add_argument("--output-dir", default=None) p.add_argument("--min-reward", type=float, default=None) p.add_argument("--min-gap", type=float, default=0.15) p.add_argument("--json", action="store_true") return p.parse_args()
def _parse_trace_args() -> argparse.Namespace: p = argparse.ArgumentParser(description="Collect scored traces from local models") p.add_argument("--models", required=True, help="Comma-separated Ollama model names") p.add_argument("--output-dir", default="./traces") p.add_argument("--tasks", default=None, help="Task list file (.txt or .jsonl)") p.add_argument("--limit", type=int, default=None, help="Use only the first N tasks") p.add_argument("--n-samples", type=int, default=1) p.add_argument("--num-predict", type=int, default=1024) p.add_argument("--temperature", type=float, default=0.8) p.add_argument("--seed", type=int, default=42) p.add_argument("--base-url", default="http://localhost:11434") p.add_argument("--timeout", type=float, default=600.0) p.add_argument("--no-think", action="store_true", help="Disable model thinking traces") p.add_argument("--no-resume", action="store_true", help="Ignore existing traces") p.add_argument("--model-opt", action="append", default=None) p.add_argument("--json", action="store_true") _add_rater_args(p) return p.parse_args()
def _parse_audit_args() -> argparse.Namespace: p = argparse.ArgumentParser(description="Rater agreement audit") p.add_argument("--corpus", required=True) p.add_argument("--rater-a", default="static") p.add_argument("--rater-b", default="decision") p.add_argument("--rater-model", default=None) p.add_argument("--output", default=None) p.add_argument("--json", action="store_true") return p.parse_args()
def _parse_train_args() -> argparse.Namespace: p = argparse.ArgumentParser() p.add_argument("--model", default="Qwen/Qwen2.5-Coder-7B") p.add_argument("--output-dir", default="./grpo_output") p.add_argument("--data", default=None) p.add_argument("--iterations", type=int, default=100) p.add_argument("--group-size", type=int, default=8) p.add_argument("--lr", type=float, default=1e-5) p.add_argument("--resume-from", default=None) p.add_argument("--backend", default="auto", choices=["auto", "mlx", "torch"]) p.add_argument("--legacy-rewards", action="store_true") _add_rater_args(p) return p.parse_args()
def _parse_eval_args() -> argparse.Namespace: p = argparse.ArgumentParser() p.add_argument("code", nargs="?", default="-") p.add_argument("--file", default=None) p.add_argument("--judge-model", default="gpt-4o") p.add_argument("--json", action="store_true") _add_rater_args(p) return p.parse_args()
def _parse_reward_args() -> argparse.Namespace: p = argparse.ArgumentParser() p.add_argument("--task", required=True) p.add_argument("--code", required=True) p.add_argument("--legacy", action="store_true") p.add_argument("--json", action="store_true") _add_rater_args(p) return p.parse_args()
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110"""Configuration dataclasses for guac-coder training."""
from dataclasses import dataclass, fieldfrom typing import List, Optional
@dataclassclass RewardConfig: """Configuration for the 12-rule code reward function."""
# Punishments (negative rewards) seaborn_penalty: float = -0.3 grid_penalty: float = -0.2 title_penalty: float = -0.15 bargraph_penalty: float = -0.25 narrative_comment_penalty: float = -0.15 tryexcept_penalty: float = -0.2 class_penalty: float = -0.15 print_penalty: float = -0.2 batch_write_penalty: float = -0.15 non_resumable_penalty: float = -0.25 bare_script_penalty: float = -0.3
# Rewards (positive) chroptiks_reward: float = 0.3 dataframe_csv_reward: float = 0.2 logging_reward: float = 0.2 checkpoint_reward: float = 0.2 function_def_reward: float = 0.15
# Rater selection: "static" (13-rule regex/AST), "decision" (Ollama # System-One decision model such as clef), or "llm" (generative # LLM-as-judge, legacy rewards.py path). rater: str = "static"
# LLM judge config (rater="llm") judge_model: str = "gpt-4o" judge_temperature: float = 0.0 judge_max_tokens: int = 2048
# Decision-model config (rater="decision") decision_model: str = "clef" decision_base_url: str = "http://localhost:11434" decision_timeout: float = 120.0 decision_threshold: float = 0.5 decision_on_error: str = "static" decision_cache: bool = True
def decision_judge_config(self): """Build the DecisionJudgeConfig implied by these settings.""" from guac_coder.decision_judge import DecisionJudgeConfig
return DecisionJudgeConfig( model=self.decision_model, base_url=self.decision_base_url, timeout=self.decision_timeout, threshold=self.decision_threshold, on_error=self.decision_on_error, cache=self.decision_cache, )
@dataclassclass GRPOConfig: """Configuration for GRPO training."""
model_name: str = "Qwen/Qwen2.5-Coder-7B" output_dir: str = "./grpo_output"
# Generation params for group sampling group_size: int = 8 temperature: float = 0.8 max_new_tokens: int = 2048
# Training params num_iterations: int = 100 learning_rate: float = 1e-5 batch_size: int = 1 gradient_accumulation_steps: int = 4
# RL params epsilon: float = 0.2 beta: float = 0.01
# Checkpointing checkpoint_interval: int = 10 resume_from_checkpoint: Optional[str] = None
# Backend: auto (prefer mlx), mlx, or torch backend: str = "auto"
# Data train_data_path: Optional[str] = None eval_data_path: Optional[str] = None
# Logging log_interval: int = 1 eval_interval: int = 10
@dataclassclass DataConfig: """Configuration for training data preparation."""
source_repos: List[str] = field(default_factory=list) output_path: str = "./training_data.jsonl" min_code_lines: int = 10 max_code_lines: int = 500 include_docstrings: bool = True filter_by_extension: List[str] = field(default_factory=lambda: [".py"])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151"""Data loading and preparation for guac-coder GRPO training."""
import jsonimport loggingimport osfrom pathlib import Pathfrom typing import Dict, Iterator, List, Optional
from guac_coder.config import DataConfig
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------# Prompt templates for code generation tasks# ---------------------------------------------------------------------------
CODE_GENERATION_PROMPT = """You are guac-coder, an expert research scientist and Python programmer.Write clean, objective, resumable Python code for the task below.
Rules:- Use chroptiks for all plots. No seaborn, no matplotlib bar graphs.- No plot grids, no plot titles.- Use pandas DataFrames and .to_csv for data output. No csv.DictWriter.- Use logging, not print.- Write functions and __main__ guards. No bare scripts.- Add checkpoint/resume logic where appropriate.- No unnecessary narrative comments. Comments must be objective and concise.- Avoid try/except unless absolutely necessary.- Avoid classes unless the abstraction is genuinely needed.- Write data incrementally, not in a single batch dump.
Task: {task}
Provide the full Python implementation."""
RESEARCH_TASKS: List[str] = [ "Implement a data loader that reads a CSV of galaxy properties, filters by redshift, and writes the filtered subset to disk with intermittent checkpointing.", "Implement a function that computes the pairwise cosine similarity between rows of a sparse matrix and saves results incrementally to a feather file.", "Implement a knowledge graph embedding trainer that saves entity/relation checkpoints every N batches and resumes from the latest checkpoint.", "Implement a plotting utility that visualizes a 2D embedding space using chroptiks, with no grid, no title, and proper color mapping.", "Implement a scientific paper metadata scraper that writes parsed metadata to CSV incrementally with logging at each stage.", "Implement a mixture model fitter that logs likelihood values and saves model state periodically for resumable training.", "Implement a text preprocessing pipeline for NLP experiments that reads raw text, tokenizes, and writes processed chunks to disk with checkpoint tracking.", "Implement a benchmarking script that runs experiments, logs metrics via logging module, and appends results to a CSV after each trial.", "Implement a function that generates synthetic tabular data for ML experiments and writes rows incrementally to parquet.", "Implement a model evaluation script that loads a checkpointed model, evaluates on a test set, and logs metrics to CSV using pandas.",]
def load_research_tasks(path: Optional[str] = None) -> List[str]: """Load research task prompts.""" if path and os.path.isfile(path): with open(path, "r", encoding="utf-8") as fh: if path.endswith(".jsonl"): tasks = [] for line in fh: obj = json.loads(line) tasks.append(obj.get("task", obj.get("instruction", ""))) return [t for t in tasks if t] else: return [line.strip() for line in fh if line.strip()] return RESEARCH_TASKS.copy()
def build_prompt(task: str) -> str: """Wrap a raw task in the system-style prompt.""" return CODE_GENERATION_PROMPT.format(task=task)
def prepare_training_examples(tasks: List[str]) -> Iterator[Dict]: """Yield dicts with 'prompt' and 'task' keys.""" for task in tasks: yield {"prompt": build_prompt(task), "task": task}
def load_code_from_repos(cfg: DataConfig) -> Iterator[Dict]: """Walk source repositories and extract Python files as training examples.
Yields dicts with: - prompt: generated prompt for the code - code: the source code - source_file: origin path """ for repo_path in cfg.source_repos: repo = Path(repo_path) if not repo.exists(): logger.warning("Repo path does not exist: %s", repo_path) continue for ext in cfg.filter_by_extension: for fp in repo.rglob(f"*{ext}"): try: source = fp.read_text(encoding="utf-8") lines = source.splitlines() if cfg.min_code_lines <= len(lines) <= cfg.max_code_lines: # Derive a task description from the file path task = f"Implement the functionality in {fp.name} for the {fp.parent.name} module." yield { "prompt": build_prompt(task), "code": source, "source_file": str(fp), } except Exception as exc: logger.debug("Skipped %s: %s", fp, exc)
def save_data(examples: Iterator[Dict], path: str) -> None: """Write examples to JSONL, appending incrementally.""" os.makedirs(os.path.dirname(path) or ".", exist_ok=True) count = 0 with open(path, "w", encoding="utf-8") as fh: for ex in examples: fh.write(json.dumps(ex) + "\n") count += 1 logger.info("Wrote %d examples to %s", count, path)
def load_data(path: str) -> List[Dict]: """Load examples from JSONL.""" examples = [] with open(path, "r", encoding="utf-8") as fh: for line in fh: examples.append(json.loads(line)) return examples
# ---------------------------------------------------------------------------# Reference / SFT pair generation# ---------------------------------------------------------------------------
def generate_sft_pairs(examples: List[Dict], output_path: str) -> None: """Create prompt->response pairs for supervised fine-tuning.
Each example must have 'prompt' and 'code' keys. """ pairs = [] for ex in examples: if "code" in ex: pairs.append({ "messages": [ {"role": "system", "content": ex["prompt"]}, {"role": "user", "content": ex.get("task", "Write the implementation.")}, {"role": "assistant", "content": ex["code"]}, ] }) with open(output_path, "w", encoding="utf-8") as fh: for pair in pairs: fh.write(json.dumps(pair) + "\n") logger.info("Wrote %d SFT pairs to %s", len(pairs), output_path)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466"""Decision-model rater for guac-coder.
Instead of a full generative LLM call (prompt -> free-text -> parse JSON), thisrater asks a *decision model* (Ollama ``/v1/systemone``, e.g. ``clef``) a fixedschema of typed yes/no questions about the candidate code and reads backcalibrated probabilities.
Why this is better for the reward path:
* **One request, all 17 questions.** The endpoint scores every question against the same state in a single POST, so scoring one completion costs one call.* **Calibrated numbers, not prose to parse.** ``noul`` answers come back as ``P(true) in [0, 1]``; there is no JSON-in-markdown to recover and no "judge returned non-JSON, defaulting everything to 0.0" failure mode.* **Cheap and local.** No API key, no token budget for reasoning, no truncation-in-the-thinking-channel problem.* **Same ranges as the static rules.** Each question maps onto the exact reward interval its ``grpo_rewards`` counterpart produces, so decision and static scores are directly comparable and mixable.
The rater is a drop-in alternative to :func:`guac_coder.grpo_rewards.compute_grpo_rewards`::func:`compute_decision_rewards` returns a dict keyed by the same 13 rulefunction names, and :func:`combined_decision_reward` uses the samenormalization as :func:`combined_grpo_reward`.
Requires Ollama >= 0.35.0 and a pulled decision model::
ollama pull clef # 27B, Cloudflare, ~18-20 GB # or point at the hosted variant, which needs no download: guac-reward --rater decision --rater-model clef:cloud --code foo.py"""
import hashlibimport jsonimport loggingimport urllib.errorimport urllib.requestfrom dataclasses import dataclassfrom typing import Any, Callable, Dict, Optional
logger = logging.getLogger("guac_coder.decision_judge")
DEFAULT_DECISION_MODEL = "clef"DEFAULT_BASE_URL = "http://localhost:11434"DEFAULT_TIMEOUT = 120.0MAX_REQUEST_BYTES = 64 * 1024
class DecisionRaterError(RuntimeError): """Raised when the decision endpoint is unavailable or rejects a request."""
# ---------------------------------------------------------------------------# Question schema# ---------------------------------------------------------------------------# Each entry is (question_name, instructions). The instruction is phrased so a# ``yes`` means the property is TRUE of the code. Thresholds below then convert# probabilities into the same reward interval the static rule uses.
QUESTIONS: Dict[str, str] = { "uses_chroptiks": "The code imports chroptiks and uses it for its plots.", "uses_matplotlib_or_seaborn": ( "The code uses matplotlib or seaborn for plotting instead of chroptiks." ), "uses_seaborn": "The code imports or otherwise uses seaborn.", "uses_plot_grids": "Any plot in the code enables grid lines (for example ax.grid(True)).", "uses_plot_titles": "Any plot in the code sets a title (for example ax.set_title or plt.title).", "uses_bargraphs": ( "The code draws a bar chart, horizontal bar chart, pie chart, " "stack plot, or other low-information-density chart." ), "uses_to_csv": "The code writes data with a pandas DataFrame using .to_csv().", "uses_csv_dictwriter": ("The code writes data with the csv module's DictWriter or csv.writer."), "has_narrative_comments": ( "The code's comments are narrative or explanatory storytelling " '(for example "let\'s now...", "note that...", "we can see...") ' "rather than terse objective notes." ), "uses_try_except": "The code contains a try/except block.", "defines_classes": "The code defines one or more classes.", "has_logging": ( "The code imports the logging module and emits messages through a logger " "(for example logging.getLogger or logger.info)." ), "has_print": "The code calls print() at least once.", "collects_then_batch_writes": ( "The code accumulates all results in memory and writes them out in a " "single batch at the end, rather than writing incrementally." ), "writes_inside_loop": ( "The code writes to a file or CSV from inside a loop, so partial " "results are preserved if the run fails." ), "has_checkpoint_resume": ( "The code can resume from a checkpoint: it saves or loads state, or " "checks for existing output before recomputing." ), "is_bare_script": ( "The code is a bare top-level script with no main guard and no " "functions of its own." ),}
@dataclassclass DecisionJudgeConfig: """Configuration for the decision-model rater.
Attributes ---------- model : str Ollama decision model tag, e.g. ``clef`` or ``clef:cloud``. base_url : str Ollama base URL; the ``/v1/systemone`` suffix is appended. timeout : float Per-request timeout in seconds. keep_alive : str or None Ollama keep_alive, or None to omit. threshold : float Probability cutoff used for the multi-state rules that need a discrete branch (chroptiks, csv, logging, writes). cache : bool Cache scores per ``(model, code)`` so repeated scoring of an identical completion is free. on_error : {"static", "zero", "raise"} Behaviour when the endpoint fails. ``static`` falls back to the static rules, ``zero`` returns all-neutral rewards, ``raise`` propagates. """
model: str = DEFAULT_DECISION_MODEL base_url: str = DEFAULT_BASE_URL timeout: float = DEFAULT_TIMEOUT keep_alive: Optional[str] = "5m" threshold: float = 0.5 cache: bool = True on_error: str = "static"
_CACHE: Dict[str, Dict[str, Any]] = {}
def build_questions() -> Dict[str, Dict[str, str]]: """Return the question payload in the endpoint's expected shape.""" return { name: {"type": "noul", "instructions": instructions} for name, instructions in QUESTIONS.items() }
def _resolved_base_url(base_url: Optional[str]) -> str: url = str(base_url or DEFAULT_BASE_URL).strip().rstrip("/") if not url.startswith(("http://", "https://")): url = "http://" + url for suffix in ("/v1/systemone", "/v1/systemone/", "/v1", "/api"): if url.endswith(suffix): url = url[: -len(suffix)] break return url.rstrip("/")
def ask_decision_model( code: str, cfg: Optional[DecisionJudgeConfig] = None, session: Any = None,) -> Dict[str, float]: """Ask the decision model every rule question in one request.
Returns ------- dict ``{question_name: P(true)}`` with values in ``[0, 1]``. """ cfg = cfg or DecisionJudgeConfig() if not isinstance(code, str) or not code.strip(): raise ValueError("code must be a non-empty string")
payload: Dict[str, Any] = { "model": cfg.model, "state": {"code": code}, "questions": build_questions(), } if cfg.keep_alive: payload["keep_alive"] = cfg.keep_alive
body = json.dumps(payload, ensure_ascii=False).encode("utf-8") if len(body) > MAX_REQUEST_BYTES: raise DecisionRaterError( f"request body is {len(body)} bytes, over the {MAX_REQUEST_BYTES}-byte " "endpoint limit; truncate the code before scoring" )
url = f"{_resolved_base_url(cfg.base_url)}/v1/systemone" request = urllib.request.Request( url, data=body, headers={"Content-Type": "application/json"}, method="POST", ) try: opener = session or urllib.request with opener.urlopen(request, timeout=cfg.timeout) as resp: raw = resp.read().decode("utf-8", errors="replace") except urllib.error.HTTPError as exc: detail = exc.read().decode("utf-8", errors="replace")[:400] raise DecisionRaterError(f"HTTP {exc.code} from {url}: {detail}") from exc except urllib.error.URLError as exc: raise DecisionRaterError( f"cannot reach decision endpoint at {url} ({exc.reason}); " f"is Ollama running and is {cfg.model!r} pulled?" ) from exc
try: parsed = json.loads(raw) except json.JSONDecodeError as exc: raise DecisionRaterError(f"endpoint returned non-JSON: {raw[:300]}") from exc if isinstance(parsed, dict) and parsed.get("error"): raise DecisionRaterError(str(parsed["error"]))
answers = (parsed or {}).get("answers") or {} if not isinstance(answers, dict): raise DecisionRaterError(f"unexpected response shape: {raw[:300]}")
out: Dict[str, float] = {} for name in QUESTIONS: block = answers.get(name) value: Optional[float] = None if isinstance(block, dict): for key in ("noul", "score", "value"): if key in block: try: value = float(block[key]) except (TypeError, ValueError): value = None break elif isinstance(block, (int, float)): value = float(block) if value is None: logger.warning("decision model returned no answer for %r; using 0.5", name) value = 0.5 out[name] = min(1.0, max(0.0, value)) return out
def _interp(p: float, compliant: float, violating: float) -> float: """Map P(property true) 0->compliant, 1->violating.""" return compliant + p * (violating - compliant)
# ---------------------------------------------------------------------------# Mapping: probabilities -> the 13 rule rewards# ---------------------------------------------------------------------------# Keys deliberately match the grpo_rewards function names so the two paths are# interchangeable (and directly diffable in traces).
def map_to_rule_rewards( probs: Dict[str, float], threshold: float = 0.5,) -> Dict[str, float]: """Convert decision probabilities into per-rule rewards in [-1, 1].
Each rule reproduces the reward range of its static counterpart:
* ``chroptiks_preference_reward`` +1.0 chroptiks / -1.0 mpl/seaborn / 0.0 neither * ``no_seaborn_reward`` -1.0 seaborn / +0.5 clean * ``no_plot_grids_reward`` -1.0 grids / +0.5 clean * ``no_plot_titles_reward`` -1.0 titles / +0.5 clean * ``no_bargraphs_reward`` -1.0 bad chart / +0.5 clean * ``pandas_csv_preference_reward`` +1.0 to_csv only / -1.0 dictwriter / 0.0 mixed * ``objective_comments_reward`` -1.0 narrative-heavy / +0.5 objective * ``no_try_except_reward`` -1.0 try/except / +0.5 clean * ``no_classes_reward`` -1.0 classes / +0.5 clean * ``logging_over_print_reward`` +1.0 logger only / 0.0 mixed / -1.0 print only * ``intermittent_writes_reward`` +1.0 in-loop writes / -1.0 batch / 0.0 unclear * ``resumable_checkpoint_reward`` +1.0 resumable / -1.0 not * ``not_bare_script_reward`` +0.5 guarded/functions / -1.0 bare script """
def q(name: str) -> float: return float(probs.get(name, 0.5))
def yes(name: str) -> bool: return q(name) >= threshold
rewards: Dict[str, float] = {}
# Rule 13: chroptiks should always be used for plotting. if yes("uses_chroptiks"): rewards["chroptiks_preference_reward"] = 1.0 elif yes("uses_matplotlib_or_seaborn"): rewards["chroptiks_preference_reward"] = -1.0 else: rewards["chroptiks_preference_reward"] = 0.0
# Rules 1-4: hard violations, soft clean credit. rewards["no_seaborn_reward"] = -1.0 if yes("uses_seaborn") else 0.5 rewards["no_plot_grids_reward"] = -1.0 if yes("uses_plot_grids") else 0.5 rewards["no_plot_titles_reward"] = -1.0 if yes("uses_plot_titles") else 0.5 rewards["no_bargraphs_reward"] = -1.0 if yes("uses_bargraphs") else 0.5
# Rule 5: prefer DataFrame.to_csv over csv.DictWriter. uses_to_csv = yes("uses_to_csv") uses_dictwriter = yes("uses_csv_dictwriter") if uses_to_csv and not uses_dictwriter: rewards["pandas_csv_preference_reward"] = 1.0 elif uses_dictwriter: rewards["pandas_csv_preference_reward"] = -1.0 else: rewards["pandas_csv_preference_reward"] = 0.0
# Rule 6: narrative comments. rewards["objective_comments_reward"] = -1.0 if q("has_narrative_comments") >= 0.6 else 0.5
# Rules 7-8: try/except and classes. rewards["no_try_except_reward"] = -1.0 if yes("uses_try_except") else 0.5 rewards["no_classes_reward"] = -1.0 if yes("defines_classes") else 0.5
# Rule 9: logging over print. has_logging = yes("has_logging") has_print = yes("has_print") if has_logging and not has_print: rewards["logging_over_print_reward"] = 1.0 elif has_logging and has_print: rewards["logging_over_print_reward"] = 0.0 elif has_print: rewards["logging_over_print_reward"] = -1.0 else: rewards["logging_over_print_reward"] = 0.0
# Rule 10: intermittent writes, not a batch dump. in_loop = yes("writes_inside_loop") batch = yes("collects_then_batch_writes") if in_loop and not batch: rewards["intermittent_writes_reward"] = 1.0 elif batch and not in_loop: rewards["intermittent_writes_reward"] = -1.0 else: rewards["intermittent_writes_reward"] = 0.0
# Rule 11: resumability. rewards["resumable_checkpoint_reward"] = 1.0 if yes("has_checkpoint_resume") else -1.0
# Rule 12: bare script. rewards["not_bare_script_reward"] = -1.0 if yes("is_bare_script") else 0.5
return rewards
def compute_decision_rewards( code: str, cfg: Optional[DecisionJudgeConfig] = None, judge_fn: Optional[Callable[..., Dict[str, float]]] = None,) -> Dict[str, float]: """Score ``code`` with the decision model, returning per-rule rewards.
Drop-in replacement for :func:`guac_coder.grpo_rewards.compute_grpo_rewards`. Falls back per ``cfg.on_error`` when the endpoint is unreachable or the model is not installed. """ cfg = cfg or DecisionJudgeConfig()
# Never pay for (or trust) a judgement on code that cannot be parsed: the # static path applies the same floor, and without it both raters would # hand garbage a positive score. from guac_coder.grpo_rewards import ( VALIDITY_FLOOR, _empty_rule_scores, is_valid_python, )
if not is_valid_python(code): return {k: VALIDITY_FLOOR for k in _empty_rule_scores()}
key = None if cfg.cache: digest = hashlib.sha1(code.encode("utf-8")).hexdigest() key = f"{cfg.model}|{digest}" cached = _CACHE.get(key) if cached is not None: return dict(cached)
ask = judge_fn or ask_decision_model try: probs = ask(code, cfg) if judge_fn is None else judge_fn(code, cfg=cfg) rewards = map_to_rule_rewards(probs, threshold=cfg.threshold) except Exception as exc: if cfg.on_error == "raise": raise if cfg.on_error == "zero": logger.warning("decision rater failed (%s); returning neutral rewards", exc) rewards = { name: 0.0 for name in ( "chroptiks_preference_reward", "no_seaborn_reward", "no_plot_grids_reward", "no_plot_titles_reward", "no_bargraphs_reward", "pandas_csv_preference_reward", "objective_comments_reward", "no_try_except_reward", "no_classes_reward", "logging_over_print_reward", "intermittent_writes_reward", "resumable_checkpoint_reward", "not_bare_script_reward", ) } else: from guac_coder.grpo_rewards import compute_grpo_rewards
logger.warning("decision rater failed (%s); falling back to static rules", exc) rewards = compute_grpo_rewards(code)
if key is not None: _CACHE[key] = dict(rewards) return rewards
def combined_decision_reward( code: str, weights: Optional[Dict[str, float]] = None, cfg: Optional[DecisionJudgeConfig] = None, judge_fn: Optional[Callable[..., Dict[str, float]]] = None,) -> float: """Weighted, normalized sum of decision-rater rewards.
Same normalization as :func:`guac_coder.grpo_rewards.combined_grpo_reward` so the two scalars are directly comparable. """ scores = compute_decision_rewards(code, cfg=cfg, judge_fn=judge_fn) if weights is None: weights = {name: 1.0 for name in scores} total = sum(scores[name] * weights.get(name, 1.0) for name in scores) norm = sum(abs(weights.get(name, 1.0)) for name in scores) return total / norm if norm > 0 else 0.0
def clear_cache() -> None: """Drop the memoized scores (used by tests and long-running trainers).""" _CACHE.clear()
def available(cfg: Optional[DecisionJudgeConfig] = None) -> Dict[str, Any]: """Check whether the decision endpoint and model are usable.
Returns ``{"available": bool, "model": str, "url": str, "error": str|None}``. """ cfg = cfg or DecisionJudgeConfig() url = _resolved_base_url(cfg.base_url) probe_code = "def add(a, b):\n return a + b\n" try: probs = ask_decision_model(probe_code, cfg=cfg) return { "available": True, "model": cfg.model, "url": f"{url}/v1/systemone", "error": None, "sample": probs, } except Exception as exc: return { "available": False, "model": cfg.model, "url": f"{url}/v1/systemone", "error": str(exc), }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204"""GRPO (Group Relative Policy Optimization) evaluator for guac-coder.
Uses npcpy.get_llm_response with format='json' to obtain structuredevaluations from an LLM judge for generated research code.
Punishments and rewards align with the guac-coder research-code style guide:1. punish seaborn use2. punish use of grids in plots3. punish use of titles in plots4. punish use of bargraphs and other low-info plots5. prefer pd.DataFrames and .to_csv over csv dict writer6. punish unnecessary explanatory / narrative comments7. punish try/except usage8. punish classes in most cases9. reward proper logger.logging and punish prints10. punish batch data writes, prefer intermittent writes11. punish when code is not resumable from a checkpoint12. punish bare scripts (no main guard or entrypoint)"""
import jsonimport loggingfrom typing import Any, Dict
logger = logging.getLogger("guac_coder.grpo_evaluator")
# Evaluation prompt template used by the LLM judge._JUDGE_PROMPT_TEMPLATE = """You are an exacting code-quality judge evaluating research/scientific Python code.
Review the following code and return a JSON object with scores for each rule below.Score 1.0 if the code follows the rule, 0.0 if it violates it. Partial credit (0.0–1.0) is allowed.
Rules:1. no_seaborn: The code does NOT import or use seaborn.2. no_grids: Plots do NOT use grids (e.g., ax.grid(True), sns.set_style with grid).3. no_titles: Plots do NOT have titles (e.g., ax.set_title, plt.title).4. no_bargraphs: The code does NOT use bar graphs, pie charts, or other low-information-density plots.5. prefers_dataframes: The code uses pandas DataFrames and .to_csv() rather than csv.DictWriter / csv.writer.6. no_narrative_comments: Comments are objective and minimal; there are no unnecessary narrative/explanatory comments.7. no_try_except: The code does NOT use try/except blocks.8. no_classes: The code avoids unnecessary class definitions (functions are preferred). Score 0.5 for a single small dataclass or namedtuple; score 0.0 for multiple classes or heavy OOP.9. proper_logging: Uses logging.getLogger / logger.info|debug|warning instead of bare print() statements.10. intermittent_writes: Data is written incrementally / intermittently (e.g., append to CSV in a loop) rather than batch-writing everything at the end.11. resumable: Code can resume from a checkpoint (e.g., checks for existing files, uses a state dict, or has a resume flag).12. not_bare_script: The script is NOT a bare script; it has a main guard (if __name__ == "__main__": ...) or an explicit entrypoint function.
Return ONLY the JSON object (no markdown fences, no extra text). Format:{ "scores": { "no_seaborn": {"score": float, "found": bool}, "no_grids": {"score": float, "found": bool}, "no_titles": {"score": float, "found": bool}, "no_bargraphs": {"score": float, "found": bool}, "prefers_dataframes": {"score": float, "found": bool}, "no_narrative_comments": {"score": float, "found": bool}, "no_try_except": {"score": float, "found": bool}, "no_classes": {"score": float, "found": bool}, "proper_logging": {"score": float, "found": bool}, "intermittent_writes": {"score": float, "found": bool}, "resumable": {"score": float, "found": bool}, "not_bare_script": {"score": float, "found": bool} }, "total_score": float, "max_possible": 12.0, "brief_reasoning": "One-sentence summary of the main issues."}
CODE TO EVALUATE:```python{{code}}```"""
_RULE_KEYS = [ "no_seaborn", "no_grids", "no_titles", "no_bargraphs", "prefers_dataframes", "no_narrative_comments", "no_try_except", "no_classes", "proper_logging", "intermittent_writes", "resumable", "not_bare_script",]
def build_judge_prompt(code: str) -> str: """Substitute the code snippet into the judge prompt.""" return _JUDGE_PROMPT_TEMPLATE.replace("{{code}}", code)
def parse_judge_response(response: Dict[str, Any]) -> Dict[str, float]: """ Parse the JSON response from get_llm_response into per-rule scores. Returns a flat dict: {"no_seaborn": 1.0, ...} """ raw = response.get("response", {}) if isinstance(response, dict) else {} if isinstance(raw, str): try: raw = json.loads(raw) except json.JSONDecodeError: logger.warning("Judge returned non-JSON string; defaulting all scores to 0.0") return {k: 0.0 for k in _RULE_KEYS}
scores_block = raw.get("scores", {}) if isinstance(raw, dict) else {} parsed: Dict[str, float] = {} for key in _RULE_KEYS: val = scores_block.get(key, {}) if isinstance(scores_block, dict) else {} if isinstance(val, dict): parsed[key] = float(val.get("score", 0.0)) else: parsed[key] = float(val) if isinstance(val, (int, float)) else 0.0 return parsed
def compute_grpo_reward( code: str, llm_judge_fn=None, default_weight: float = 1.0, **judge_kwargs) -> float: """ Compute a GRPO-style reward by calling an LLM judge.
Parameters ---------- code : str The generated Python code to evaluate. llm_judge_fn : callable, optional Function with signature (prompt: str, **kwargs) -> dict. Defaults to npcpy.get_llm_response if available, else a local mock. default_weight : float Weight applied to the total normalized score. **judge_kwargs Extra args forwarded to the judge LLM (model, provider, temperature, etc.)
Returns ------- float Reward in the range [0.0, default_weight] (higher is better). """ if llm_judge_fn is None: llm_judge_fn = _try_import_npcpy_judge()
prompt = build_judge_prompt(code) response = llm_judge_fn(prompt, format="json", **judge_kwargs) scores = parse_judge_response(response) total = sum(scores.values()) max_possible = float(len(_RULE_KEYS)) normalized = total / max_possible if max_possible else 0.0 reward = normalized * default_weight logger.debug("GRPO reward=%.3f for code snippet (len=%d)", reward, len(code)) return reward
def _try_import_npcpy_judge(): """Attempt to import npcpy.get_llm_response; fall back to a mock judge.""" try: from npcpy.llm_funcs import get_llm_response return get_llm_response except Exception: logger.warning("npcpy.get_llm_response unavailable; using mock judge.") return _mock_llm_judge
def _mock_llm_judge(prompt: str, **kwargs) -> Dict[str, Any]: """ Mock judge that returns deterministic JSON based on simple string heuristics. Useful for unit testing and local dev without API keys. """ code = prompt.split("```python")[-1].split("```")[0] if "```python" in prompt else "" code_lower = code.lower()
def _has(token: str) -> bool: return token in code_lower
scores = { "no_seaborn": {"score": 0.0 if _has("seaborn") or _has("import sns") or _has("from seaborn") else 1.0, "found": _has("seaborn")}, "no_grids": {"score": 0.0 if _has(".grid(true)") or _has("grid=") or _has("grid =") else 1.0, "found": _has(".grid")}, "no_titles": {"score": 0.0 if _has(".set_title") or _has("plt.title") or _has("ax.set_title") else 1.0, "found": _has("title")}, "no_bargraphs": {"score": 0.0 if _has("bar(") or _has(".bar") or _has("pie(") else 1.0, "found": _has("bar(") or _has("pie(")}, "prefers_dataframes": {"score": 1.0 if _has("pd.dataframe") or _has("to_csv") else 0.0, "found": _has("pd.dataframe") or _has("to_csv")}, "no_narrative_comments": {"score": 1.0 if code.count("#") < 3 else 0.5, "found": code.count("#") >= 3}, "no_try_except": {"score": 0.0 if _has("try:") else 1.0, "found": _has("try:")}, "no_classes": {"score": 0.5 if _has("class ") and _has("dataclass") else (0.0 if _has("class ") else 1.0), "found": _has("class ")}, "proper_logging": {"score": 1.0 if _has("logging.getlogger") or _has("logger.") else 0.0, "found": _has("logging.getlogger") or _has("logger.")}, "intermittent_writes": {"score": 1.0 if _has("mode='a'") or _has('mode="a"') or (_has("to_csv") and _has("for ")) else 0.0, "found": _has("mode='a'")}, "resumable": {"score": 1.0 if _has("checkpoint") or _has("resume") or _has("exists(") else 0.0, "found": _has("checkpoint") or _has("resume")}, "not_bare_script": {"score": 1.0 if _has('if __name__ == "__main__"') or _has("if __name__ == '__main__'") else 0.0, "found": _has('if __name__')}, } total = sum(v["score"] for v in scores.values()) return { "response": { "scores": scores, "total_score": total, "max_possible": 12.0, "brief_reasoning": "Mock heuristic evaluation.", } }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290"""GRPO training pipeline bridging npcpy.ft.rl with guac-coder reward functions.
This module provides a runnable pipeline that:1. Loads npcpy.ft.rl.GRPOTrainer and GRPOConfig2. Wraps guac-coder reward functions (static + LLM judge) into a reward_fn compatible with npcpy's GRPOTrainer3. Handles checkpoint/resume, logging, and intermittent data writes4. Uses npcpy.llm_funcs.get_llm_response with format='json' for structured LLM-as-judge evaluations
"""import jsonimport loggingimport picklefrom pathlib import Pathfrom typing import Any, Dict, Optional
# npcpy integrationtry: from npcpy.ft.rl import GRPOConfig, GRPOTrainer from npcpy.llm_funcs import get_llm_responseexcept ImportError: GRPOConfig = None # type: ignore GRPOTrainer = None # type: ignore get_llm_response = None # type: ignore
# guac-coder rewardsfrom guac_coder.config import RewardConfigfrom guac_coder.grpo_rewards import combined_grpo_reward, compute_grpo_rewardsfrom guac_coder.rewards import compute_total_reward
logger = logging.getLogger("guac_coder.grpo_pipeline")
class GuacRewardAdapter: """Adapter that converts guac-coder reward functions into a scalar reward_fn compatible with npcpy.ft.rl.GRPOTrainer.
Parameters ---------- reward_config : RewardConfig guac-coder reward config with penalties/rewards for the 12 rules. llm_judge : bool Whether to enable the LLM-as-judge path (requires get_llm_response). static_weight : float Weight for static analysis rewards. llm_weight : float Weight for LLM judge rewards. use_grpo_rewards : bool If True, use the newer per-rule grpo_rewards module (compute_grpo_rewards + combined_grpo_reward). If False, use legacy rewards.py. rater : str, optional Override the rater: ``"static"`` (13 regex/AST rules), ``"decision"`` (Ollama System-One decision model such as ``clef``) or ``"llm"`` (generative LLM-as-judge). Defaults to ``reward_config.rater``. """
def __init__( self, reward_config: Optional[RewardConfig] = None, llm_judge: bool = False, static_weight: float = 0.6, llm_weight: float = 0.4, use_grpo_rewards: bool = True, rater: Optional[str] = None, ): self.cfg = reward_config or RewardConfig() self.llm_judge = llm_judge self.static_weight = static_weight self.llm_weight = llm_weight self.use_grpo_rewards = use_grpo_rewards self.rater = (rater or getattr(self.cfg, "rater", "static") or "static").lower()
def __call__(self, code: str) -> float: """Return scalar reward for a single code string.""" if self.rater == "decision": from guac_coder.decision_judge import combined_decision_reward
return combined_decision_reward( code, cfg=self.cfg.decision_judge_config() ) if self.rater == "static" and self.use_grpo_rewards: # Newer per-rule rewards in [-1, 1] return combined_grpo_reward(code) # Legacy path if self.llm_judge and get_llm_response is not None: result = compute_total_reward( code, get_llm_response_fn=get_llm_response, cfg=self.cfg, static_weight=self.static_weight, llm_weight=self.llm_weight, ) return float(result["total"]) # Static-only legacy path from guac_coder.rewards import total_static_reward return total_static_reward(code, self.cfg)
def get_reward_breakdown(self, code: str) -> Dict[str, float]: """Return per-rule reward breakdown for logging/analysis.""" if self.rater == "decision": from guac_coder.decision_judge import compute_decision_rewards
return compute_decision_rewards(code, cfg=self.cfg.decision_judge_config()) if self.rater == "static" and self.use_grpo_rewards: return compute_grpo_rewards(code) # Legacy from guac_coder.rewards import compute_static_rewards return compute_static_rewards(code, self.cfg)
def build_trainer( model_name: str = "Qwen/Qwen2.5-Coder-7B", output_dir: str = "./grpo_output", reward_config: Optional[RewardConfig] = None, llm_judge: bool = False, group_size: int = 8, use_grpo_rewards: bool = True, rater: Optional[str] = None, **kwargs: Any,) -> Any: """Build an npcpy GRPOTrainer configured with guac-coder rewards.
``rater`` selects the scoring backend: ``"static"`` (13 regex/AST rules), ``"decision"`` (Ollama System-One decision model, e.g. ``clef``) or ``"llm"`` (generative judge). Defaults to ``reward_config.rater``.
Returns the trainer object or raises if npcpy is unavailable. """ if GRPOTrainer is None: raise RuntimeError( "npcpy.ft.rl is not installed. Install npcpy to use GRPO training." )
reward_adapter = GuacRewardAdapter( reward_config=reward_config, llm_judge=llm_judge, use_grpo_rewards=use_grpo_rewards, rater=rater, )
# npcpy GRPOConfig may differ from guac-coder GRPOConfig; # prefer npcpy's when available. rl_cfg = GRPOConfig( model_name=model_name, output_dir=output_dir, group_size=group_size, **kwargs, )
trainer = GRPOTrainer( config=rl_cfg, reward_fn=reward_adapter, ) return trainer
def run_grpo( model_name: str = "Qwen/Qwen2.5-Coder-7B", output_dir: str = "./grpo_output", num_iterations: int = 100, checkpoint_interval: int = 10, resume_from_checkpoint: Optional[str] = None, reward_config: Optional[RewardConfig] = None, llm_judge: bool = False, use_grpo_rewards: bool = True, rater: Optional[str] = None, **kwargs: Any,) -> Dict[str, Any]: """High-level entrypoint to run GRPO training with guac-coder rewards.
Parameters ---------- model_name : str HuggingFace model identifier. output_dir : str Directory for checkpoints and logs. num_iterations : int Training iterations. checkpoint_interval : int Save a checkpoint every N iterations. resume_from_checkpoint : str | None Path to a prior checkpoint directory to resume from. reward_config : RewardConfig | None Custom reward configuration. llm_judge : bool Enable LLM-as-judge evaluation (requires npcpy get_llm_response). use_grpo_rewards : bool If True (default), score with the 13-rule guac_coder.grpo_rewards; if False, use the legacy rewards.py path. rater : str | None Scoring backend: ``"static"``, ``"decision"`` (Ollama decision model such as ``clef``) or ``"llm"``. Defaults to ``reward_config.rater``. **kwargs Forwarded to npcpy GRPOConfig.
Returns ------- dict with keys: trainer, output_dir, metrics_path """ output_path = Path(output_dir) output_path.mkdir(parents=True, exist_ok=True)
# Intermittent metrics logging: write one JSON line per iteration metrics_file = output_path / "metrics.jsonl"
trainer = build_trainer( model_name=model_name, output_dir=output_dir, reward_config=reward_config, llm_judge=llm_judge, use_grpo_rewards=use_grpo_rewards, rater=rater, **kwargs, )
# Resume logic if checkpoint exists start_iteration = 0 if resume_from_checkpoint: ckpt_path = Path(resume_from_checkpoint) if ckpt_path.exists(): logger.info("Resuming from checkpoint: %s", ckpt_path) # npcpy trainer may have its own resume; if not, stub here. start_iteration = _load_resume_iteration(ckpt_path) else: logger.warning("Resume checkpoint not found: %s", ckpt_path)
logger.info( "Starting GRPO training: model=%s, iterations=%d, start=%d", model_name, num_iterations, start_iteration, )
for iteration in range(start_iteration, num_iterations): metrics = trainer.train_step()
# Intermittent write: append metrics per iteration record = { "iteration": iteration, "reward": metrics.get("reward", 0.0), "loss": metrics.get("loss", 0.0), } with open(metrics_file, "a", encoding="utf-8") as fh: fh.write(json.dumps(record) + "\n")
if (iteration + 1) % checkpoint_interval == 0: ckpt_dir = output_path / f"checkpoint-{iteration + 1}" ckpt_dir.mkdir(parents=True, exist_ok=True) _save_checkpoint(trainer, ckpt_dir, iteration + 1) logger.info("Checkpoint saved: %s", ckpt_dir)
final_dir = output_path / "final" final_dir.mkdir(parents=True, exist_ok=True) _save_checkpoint(trainer, final_dir, num_iterations) logger.info("Training complete. Final checkpoint: %s", final_dir)
return { "trainer": trainer, "output_dir": str(output_path), "metrics_path": str(metrics_file), }
# ---------------------------------------------------------------------------# Checkpoint helpers (state dict + iteration pickle for resumability)# ---------------------------------------------------------------------------
def _save_checkpoint(trainer: Any, ckpt_dir: Path, iteration: int) -> None: """Save trainer state and iteration counter for resume.""" ckpt_dir.mkdir(parents=True, exist_ok=True) state_path = ckpt_dir / "trainer_state.pkl" meta_path = ckpt_dir / "meta.json" # If trainer exposes .state_dict(), use it; else best-effort state = getattr(trainer, "state_dict", lambda: {})() try: with open(state_path, "wb") as fh: pickle.dump(state, fh) except Exception as exc: logger.warning("Could not pickle trainer state: %s", exc) with open(meta_path, "w", encoding="utf-8") as fh: json.dump({"iteration": iteration, "type": "grpo_checkpoint"}, fh)
def _load_resume_iteration(ckpt_dir: Path) -> int: """Load iteration counter from checkpoint metadata.""" meta_path = ckpt_dir / "meta.json" if meta_path.exists(): with open(meta_path, "r", encoding="utf-8") as fh: meta = json.load(fh) return meta.get("iteration", 0) return 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403"""GRPO-style reward functions for Guac-Coder based on the 13 research-code rules.
These rewards are designed to be composed into a CombinedReward for GRPO training.Each rule maps to a scalar reward in [-1, 1] (or [0, 1] where noted).
Rules:1. punish seaborn use, reward chroptiks2. punish use of grids in plots3. punish use of titles in plots4. punish use of bargraphs and other stupid plots5. prefer pd.DataFrames and .to_csv over csv.dict writer6. punish unnecessary explanatory comments that are narrative rather than objective7. punish try/except usage8. punish classes in most cases, usually unnecessary nonsense9. reward proper logger.logging and punish prints10. punish batch data writes, prefer intermittent to preserve all data in case of failure11. punish when code is not set up to be resumable from some kind of checkpoint12. punish if the code is a bare script13. chroptiks should ALWAYS be used for plotting in the analysis of results"""
import astimport functoolsimport loggingimport refrom typing import Dict, List, Optional
logger = logging.getLogger("guac_coder.grpo_rewards")
class StaticCodeAnalyzer: """AST-based static analysis helpers for code reward computation."""
def __init__(self, code: str): self.code = code self.source_lines = code.splitlines() try: self.tree = ast.parse(code) except SyntaxError: self.tree = None
def has_import(self, name: str) -> bool: if self.tree is None: return name in self.code for node in ast.walk(self.tree): if isinstance(node, (ast.Import, ast.ImportFrom)): for alias in node.names: if name in (alias.name, alias.asname or ""): return True return False
def count_nodes(self, node_type) -> int: if self.tree is None: return 0 return sum(1 for node in ast.walk(self.tree) if isinstance(node, node_type))
def has_call(self, pattern: str) -> bool: return bool(re.search(pattern, self.code))
def _safe_reward(func): """Decorator to catch exceptions and log warnings in reward functions."""
@functools.wraps(func) def wrapper(code: str) -> float: try: return func(code) except Exception as exc: logger.warning("Reward function %s failed: %s", func.__name__, exc) return 0.0
return wrapper
@_safe_rewarddef chroptiks_preference_reward(code: str) -> float: """Rule 13: chroptiks should ALWAYS be used for plotting in analysis of results.""" analyzer = StaticCodeAnalyzer(code) if analyzer.has_import("chroptiks"): return 1.0 if analyzer.has_import("seaborn") or analyzer.has_import("matplotlib"): return -1.0 return 0.0
@_safe_rewarddef no_seaborn_reward(code: str) -> float: """Rule 1: punish seaborn use.""" analyzer = StaticCodeAnalyzer(code) if analyzer.has_import("seaborn"): return -1.0 return 0.5
@_safe_rewarddef no_plot_grids_reward(code: str) -> float: """Rule 2: punish use of grids in plots.
Includes style-based grids: ``sns.set_style("whitegrid")`` and ``plt.style.use("seaborn-v0_8-whitegrid")`` turn grids on without ever calling ``grid(...)``. """ code_lower = code.lower() grid_patterns = ["grid(", "grid=true", "grid = true", ".grid", "ax.grid"] if any(p in code_lower for p in grid_patterns): return -1.0 style_names = ["whitegrid", "darkgrid", "-whitegrid", "-darkgrid"] if any(s in code_lower for s in style_names): return -1.0 return 0.5
@_safe_rewarddef no_plot_titles_reward(code: str) -> float: """Rule 3: punish use of titles in plots.""" code_lower = code.lower() title_patterns = [".set_title(", 'title="', "title='", "plt.title("] if any(p in code_lower for p in title_patterns): return -1.0 return 0.5
@_safe_rewarddef no_bargraphs_reward(code: str) -> float: """Rule 4: punish use of bargraphs and other low-info plots.
Bars are commonly drawn through a library call (``sns.barplot(...)``, ``ax.barh(...)``) where the plotted name is prefixed by ``.``, so matching the bare ``bar(`` token silently misses them and *rewards* the violation. Match ``bar(`` only as a whole plot name, plus the seaborn/plotly names. """ code_lower = code.lower() bad_plots = [ "sns.barplot", "sns.countplot", "sns.barh", "px.bar", "px.histogram", "barh(", "pie(", "fill_between(", "stackplot(", ] if any(p in code_lower for p in bad_plots): return -1.0 # A bare ``bar(``/``barh(`` call, including attribute calls such as # ``plt.bar(``. The leading ``[^\w]`` keeps identifiers like # ``my_bar_plot(`` from matching; ``def bar(`` is a definition, not a plot. for match in re.finditer(r"(?:^|[^\w])(?:bar|barh)\s*\(", code_lower): if re.search(r"def\s*$", code_lower[: match.start() + 1]): continue return -1.0 return 0.5
@_safe_rewarddef pandas_csv_preference_reward(code: str) -> float: """Rule 5: prefer pd.DataFrames and .to_csv over csv dict writer.""" has_to_csv = ".to_csv(" in code has_dict_writer = "dictwriter" in code.lower() or "csv.writer" in code.lower() if has_to_csv and not has_dict_writer: return 1.0 if has_dict_writer: return -1.0 return 0.0
@_safe_rewarddef objective_comments_reward(code: str) -> float: """Rule 6: punish unnecessary explanatory comments that are narrative rather than objective.""" comment_lines = [line.strip() for line in code.splitlines() if line.strip().startswith("#")] if not comment_lines: return 0.0 narrative_markers = [ "let's", "we will", "we can", "let us", "i think", "note that", "it is important", "make sure", "don't forget", "remember", ] narrative_count = sum( 1 for line in comment_lines if any(m in line.lower() for m in narrative_markers) ) ratio = narrative_count / len(comment_lines) if comment_lines else 0.0 if ratio > 0.3: return -1.0 if ratio > 0.1: return -0.5 return 0.5
@_safe_rewarddef no_try_except_reward(code: str) -> float: """Rule 7: punish try/except usage.""" analyzer = StaticCodeAnalyzer(code) count = analyzer.count_nodes(ast.Try) if count > 0: return -1.0 return 0.5
@_safe_rewarddef no_classes_reward(code: str) -> float: """Rule 8: punish classes in most cases, usually unnecessary nonsense.""" analyzer = StaticCodeAnalyzer(code) count = analyzer.count_nodes(ast.ClassDef) if count > 0: return -1.0 return 0.5
@_safe_rewarddef logging_over_print_reward(code: str) -> float: """Rule 9: reward proper logger.logging and punish prints.""" analyzer = StaticCodeAnalyzer(code) has_logging = analyzer.has_import("logging") print_count = len(re.findall(r"\bprint\(", code)) if has_logging and print_count == 0: return 1.0 if has_logging and print_count > 0: return 0.0 if not has_logging and print_count > 0: return -1.0 return 0.0
@_safe_rewarddef intermittent_writes_reward(code: str) -> float: """Rule 10: punish batch data writes, prefer intermittent to preserve all data in case of failure.""" code_lower = code.lower() # batch write smells: collecting all in list then one write batch_smells = [ "results = []", "data = []", "all_data", "batch", "writelines", ] # intermittent smell: a write inside a loop has_batch = any(s in code_lower for s in batch_smells) has_loop_write = False lines = code.splitlines() for i, line in enumerate(lines): if any(loop_kw in line for loop_kw in ("for ", "while ")): # check next few lines for a write for j in range(i, min(i + 5, len(lines))): if ".to_csv(" in lines[j] or ".write(" in lines[j]: has_loop_write = True break if has_loop_write and not has_batch: return 1.0 if has_batch: return -1.0 return 0.0
@_safe_rewarddef resumable_checkpoint_reward(code: str) -> float: """Rule 11: punish when code is not set up to be resumable from some kind of checkpoint.""" code_lower = code.lower() checkpoint_patterns = [ "checkpoint", "resume", "pickle", "json.load", "state_dict", "torch.save", "torch.load", "load_state", "save_state", ] if any(p in code_lower for p in checkpoint_patterns): return 1.0 return -1.0
@_safe_rewarddef not_bare_script_reward(code: str) -> float: """Rule 12: punish if the code is a bare script.""" analyzer = StaticCodeAnalyzer(code) has_main_guard = '__name__ == "__main__"' in code or "__name__ == '__main__'" in code func_count = analyzer.count_nodes(ast.FunctionDef) if has_main_guard or func_count > 0: return 0.5 return -1.0
# Every rule reports this value when the code cannot be inspected at all.# Rules score in [-1, 1]; the floor must therefore be negative, otherwise# unparseable output outranks real but imperfect code.VALIDITY_FLOOR = -1.0
# Registry of all reward functions for easy iterationGRPO_REWARD_REGISTRY: List = [ chroptiks_preference_reward, no_seaborn_reward, no_plot_grids_reward, no_plot_titles_reward, no_bargraphs_reward, pandas_csv_preference_reward, objective_comments_reward, no_try_except_reward, no_classes_reward, logging_over_print_reward, intermittent_writes_reward, resumable_checkpoint_reward, not_bare_script_reward,]
# Statements that mean the snippet is a program rather than a stray expression._SUBSTANTIVE_NODES = ( ast.Import, ast.ImportFrom, ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Assign, ast.AnnAssign, ast.AugAssign, ast.For, ast.AsyncFor, ast.While, ast.If, ast.With, ast.AsyncWith, ast.Try, ast.Return, ast.Raise, ast.Delete, ast.Global, ast.Nonlocal,)
def is_valid_python(code: str) -> bool: """Whether ``code`` parses *and* looks like a real program.
Every rule below rewards *absence* of a violation, so a snippet the rules cannot inspect (unparseable text, a truncated generation, an empty string) silently collects the "clean" bonus. That makes garbage a positive-reward attractor for GRPO, which is the opposite of what we want to learn.
Syntax alone is not enough: model prose often parses as a bare expression, e.g. ``"this is not python"`` is a perfectly legal comparison, and ``"load the data"`` parses as two names. So we additionally require at least one substantive statement, or a call expression such as ``main()``. """ if not code or not code.strip(): return False try: tree = ast.parse(code) except (SyntaxError, ValueError): return False if not tree.body: return False
for node in ast.walk(tree): if isinstance(node, _SUBSTANTIVE_NODES): return True # A top-level call such as ``main()`` or ``logging.basicConfig(...)`` # is real code even though ``Expr`` alone is not. if isinstance(node, ast.Call): return True return False
def _empty_rule_scores() -> Dict[str, float]: """Per-rule scores used when ``code`` fails :func:`is_valid_python`.""" return {func.__name__: VALIDITY_FLOOR for func in GRPO_REWARD_REGISTRY}
def compute_grpo_rewards(code: str) -> Dict[str, float]: """Compute all GRPO rewards for a code snippet and return per-rule scores.
Unparseable or empty snippets return :data:`VALIDITY_FLOOR` for every rule instead of the per-rule "no violation found" bonus. """ if not is_valid_python(code): return _empty_rule_scores() scores: Dict[str, float] = {} for func in GRPO_REWARD_REGISTRY: scores[func.__name__] = func(code) return scores
def combined_grpo_reward(code: str, weights: Optional[Dict[str, float]] = None) -> float: """Compute weighted sum of GRPO rewards.
Default is uniform weighting; override via weights dict keyed by function name. """ scores = compute_grpo_rewards(code) if weights is None: weights = {name: 1.0 for name in scores} total = sum(scores[name] * weights.get(name, 1.0) for name in scores) norm = sum(abs(weights.get(name, 1.0)) for name in scores) return total / norm if norm > 0 else 0.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438"""Rater agreement audit: measure how well reward raters agree, per rule.
This is the regression harness for reward iteration. It scores a labeledcorpus with two raters (``static`` and ``decision`` by default) and reports,for every rule in the 13-rule set:
* agreement rate between the two raters (same sign / both neutral),* cases where the static rule is *wrong in the dangerous direction* -- i.e. it returns a positive reward for code that violates the rule. Those silently reward bad code during training and are the highest-priority fixes.
The corpus is plain Python files in a directory with a ``labels.json`` mapping``filename -> expected rules dict``. Expected values are only used forinformational "static vs expected" reporting; the audit's core output israter-vs-rater, which needs no hand labels.
Usage----- guac-audit --corpus ./audit_corpus --rater-a static --rater-b decision"""
import jsonimport loggingimport osfrom typing import Any, Dict, List, Optional
from guac_coder.config import RewardConfigfrom guac_coder.training import score_completion
logger = logging.getLogger("guac_coder.rater_audit")
# A rule's reward is positive when the code complies, negative when it violates.# This set marks rules where a *positive* score is only ever credit, so a# positive score on violating code means the detector missed the violation.VIOLATION_RULES = [ "no_seaborn_reward", "no_plot_grids_reward", "no_plot_titles_reward", "no_bargraphs_reward", "no_try_except_reward", "no_classes_reward", "resumable_checkpoint_reward", "not_bare_script_reward", "objective_comments_reward", "intermittent_writes_reward", "pandas_csv_preference_reward", "logging_over_print_reward", "chroptiks_preference_reward",]
def load_corpus(corpus_dir: str) -> List[Dict[str, Any]]: """Load ``*.py`` files (plus optional ``labels.json``) from a directory.""" if not os.path.isdir(corpus_dir): raise SystemExit(f"error: no such corpus directory: {corpus_dir}")
labels: Dict[str, Dict[str, float]] = {} labels_path = os.path.join(corpus_dir, "labels.json") if os.path.isfile(labels_path): with open(labels_path, "r", encoding="utf-8") as fh: labels = json.load(fh)
cases = [] for name in sorted(os.listdir(corpus_dir)): if not name.endswith(".py"): continue path = os.path.join(corpus_dir, name) with open(path, "r", encoding="utf-8") as fh: code = fh.read() cases.append({"name": name, "code": code, "expected": labels.get(name, {})}) if not cases: raise SystemExit(f"error: no .py files found in {corpus_dir}") return cases
def _sign(value: float) -> int: if value > 1e-9: return 1 if value < -1e-9: return -1 return 0
def score_corpus( cases: List[Dict[str, Any]], rater: str, reward_cfg: Optional[RewardConfig] = None, rater_model: Optional[str] = None,) -> List[Dict[str, Any]]: """Score every case with one rater, returning per-case rule breakdowns.
A decision or LLM rater is scored **strictly**: any failure is recorded as a failed case rather than silently falling back to the static rules. An audit that let the decision rater fall back to static would report perfect agreement for a rater that never ran, which is worse than no audit. """ cfg = reward_cfg or RewardConfig() if rater_model: cfg.decision_model = rater_model cfg.rater = rater cfg.decision_on_error = "raise"
scored = [] for case in cases: try: total, details = score_completion(case["code"], lambda **kwargs: {}, cfg, rater=rater) except Exception as exc: logger.error("%s rater=%s FAILED: %s", case["name"], rater, exc) scored.append( { "name": case["name"], "total": None, "rules": {}, "expected": case.get("expected", {}), "failed": str(exc), } ) continue scored.append( { "name": case["name"], "total": total, "rules": details.get("rules", {}), "expected": case.get("expected", {}), "failed": None, } ) logger.info("%s rater=%s total=%+.3f", case["name"], rater, total) return scored
def label_accuracy(rows: List[Dict[str, Any]]) -> Dict[str, Any]: """Score one rater against the corpus labels, where labels exist.
Rater-vs-rater comparison can only say the two disagree; it cannot say which is right. Labels supply that ground truth, so a weak second rater does not get to redefine correctness. """ per_rule: Dict[str, Dict[str, Any]] = {} misses: List[Dict[str, Any]] = [] for row in rows: if row.get("failed"): continue for rule, expected in (row.get("expected") or {}).items(): got = row["rules"].get(rule) if got is None: continue stats = per_rule.setdefault(rule, {"n": 0, "correct": 0}) stats["n"] += 1 # Compare position, not magnitude: the labels express the intended # direction, not an exact value. if _sign(got) == _sign(expected): stats["correct"] += 1 else: misses.append( { "case": row["name"], "rule": rule, "got": got, "expected": expected, } ) checked = sum(s["n"] for s in per_rule.values()) correct = sum(s["correct"] for s in per_rule.values()) return { "n_labeled": checked, "n_correct": correct, "accuracy": round(correct / checked, 3) if checked else None, "rules": { rule: { "n": s["n"], "correct": s["correct"], "accuracy": round(s["correct"] / s["n"], 3) if s["n"] else None, } for rule, s in per_rule.items() }, "misses": misses, }
def compare_raters( a: List[Dict[str, Any]], b: List[Dict[str, Any]], name_a: str = "static", name_b: str = "decision",) -> Dict[str, Any]: """Compare two scored corpora rule by rule.""" by_name_b = {row["name"]: row for row in b} rule_stats: Dict[str, Dict[str, Any]] = {} disagreements: List[Dict[str, Any]] = []
failed_a = [r["name"] for r in a if r.get("failed")] failed_b = [r["name"] for r in b if r.get("failed")] reason_a = next((r["failed"] for r in a if r.get("failed")), None) reason_b = next((r["failed"] for r in b if r.get("failed")), None)
compared = 0 for row_a in a: row_b = by_name_b.get(row_a["name"]) if row_b is None: continue if row_a.get("failed") or row_b.get("failed"): continue compared += 1 for rule in VIOLATION_RULES: va = row_a["rules"].get(rule) vb = row_b["rules"].get(rule) if va is None or vb is None: continue stats = rule_stats.setdefault( rule, { "n": 0, "agree": 0, "disagree": 0, "abstain": 0, "a_positive_b_negative": 0, "a_negative_b_positive": 0, "gap_sum": 0.0, "worst": None, }, ) stats["n"] += 1 sa, sb = _sign(va), _sign(vb) # A neutral value is an *abstention* (the rule has no opinion), not # a contradiction. Counting it as disagreement makes rules that # return 0.0 for "not applicable" look broken. if sa == 0 or sb == 0: stats["abstain"] += 1 continue if sa == sb: stats["agree"] += 1 continue
stats["disagree"] += 1 # a positive while b negative: `a` credited code `b` calls a violation. if va > 0 and vb < 0: stats["a_positive_b_negative"] += 1 elif va < 0 and vb > 0: stats["a_negative_b_positive"] += 1
gap = abs(va - vb) stats["gap_sum"] += gap if stats["worst"] is None or gap > stats["worst"]["gap"]: stats["worst"] = { "case": row_a["name"], f"{name_a}": va, f"{name_b}": vb, "gap": gap, } disagreements.append( { "case": row_a["name"], "rule": rule, name_a: va, name_b: vb, "gap": gap, } )
rules_out = {} for rule, stats in rule_stats.items(): n = stats["n"] decided = stats["agree"] + stats["disagree"] rules_out[rule] = { "n": n, "decided": decided, "abstentions": stats["abstain"], # Agreement over cases where both raters took a position. "agreement": round(stats["agree"] / decided, 3) if decided else None, # The dangerous direction: rater A rewarded code rater B calls a violation. "a_credited_violations": stats["a_positive_b_negative"], "a_penalized_clean": stats["a_negative_b_positive"], "mean_gap_on_disagreement": ( round(stats["gap_sum"] / stats["disagree"], 3) if stats["disagree"] else 0.0 ), "worst_disagreement": stats["worst"], }
totals_a = [r["total"] for r in a if r["total"] is not None] totals_b = [r["total"] for r in b if r["total"] is not None] return { "rater_a": name_a, "rater_b": name_b, "n_cases": len(a), "n_compared": compared, "failed": {"a": failed_a, "b": failed_b}, "failure_reason": {name_a: reason_a, name_b: reason_b}, "mean_total": { name_a: round(sum(totals_a) / len(totals_a), 4) if totals_a else None, name_b: round(sum(totals_b) / len(totals_b), 4) if totals_b else None, }, "rules": rules_out, "disagreements": disagreements, # Ground truth, when the corpus carries labels. "accuracy": {name_a: label_accuracy(a), name_b: label_accuracy(b)}, "verdict": _verdict( rules_out, name_a, name_b, failed={"a": failed_a, "b": failed_b}, n_compared=compared, ), }
def _verdict( rules_out: Dict[str, Dict[str, Any]], name_a: str, name_b: str, failed: Optional[Dict[str, List[str]]] = None, n_compared: Optional[int] = None,) -> str: """One-line summary naming rules that need attention.""" failed = failed or {} if n_compared == 0: detail = "; ".join( "%s: %d case(s) failed" % (name_a if k == "a" else name_b, len(v)) for k, v in failed.items() if v ) return ( f"INCONCLUSIVE -- no case was scored by both raters ({detail}). " "The audit says nothing about agreement." )
suspects = [ rule for rule, stats in rules_out.items() if stats["agreement"] is not None and stats["agreement"] < 0.8 and stats["decided"] >= 1 ] msg = "" if not suspects: msg = f"{name_a} and {name_b} agree on every rule (>=0.8 agreement)." else: credited = [r for r in suspects if rules_out[r]["a_credited_violations"] > 0] msg = f"{len(suspects)} rule(s) below 0.8 agreement: {', '.join(sorted(suspects))}." if credited: msg += ( f" {name_a} rewarded violating code on: " f"{', '.join(sorted(credited))} -- fix these first." )
bad = [f"{k}: {len(v)}" for k, v in failed.items() if v] if bad: msg += f" WARNING: failed cases ({'; '.join(bad)}) were excluded." return msg
def format_report(report: Dict[str, Any]) -> str: """Render a comparison report as text.""" lines = [] a, b = report["rater_a"], report["rater_b"] lines.append(f"Rater audit: {a} vs {b} over {report['n_cases']} cases") lines.append( " compared: %d mean total: %s=%s %s=%s" % ( report.get("n_compared", report["n_cases"]), a, report["mean_total"][a], b, report["mean_total"][b], ) ) for key, failed_names in (report.get("failed") or {}).items(): if failed_names: name = a if key == "a" else b lines.append( " FAILED (%s): %d case(s): %s" % (name, len(failed_names), ", ".join(failed_names)) ) reason = (report.get("failure_reason") or {}).get(name) if reason: lines.append(" reason: %s" % str(reason)[:200]) lines.append("") lines.append( " %-34s %5s %7s %8s %9s %9s" % ("rule", "n", "agree", "abstain", f"{a}>0,{b}<0", "mean gap") ) for rule, stats in sorted( report["rules"].items(), key=lambda kv: (kv[1]["agreement"] if kv[1]["agreement"] is not None else 9), ): lines.append( " %-34s %5d %7s %8d %9d %9.2f" % ( rule, stats["n"], "n/a" if stats["agreement"] is None else "%.2f" % stats["agreement"], stats["abstentions"], stats["a_credited_violations"], stats["mean_gap_on_disagreement"], ) ) acc = report.get("accuracy") or {} if any(v.get("n_labeled") for v in acc.values()): lines.append("") lines.append("Labeled accuracy (rater vs corpus labels):") for key, val in acc.items(): lines.append( " %-10s %s (%d/%d checked)" % ( key, "n/a" if val["accuracy"] is None else "%.2f" % val["accuracy"], val["n_correct"], val["n_labeled"], ) ) for miss in val["misses"][:5]: lines.append( " miss: %-28s %-30s got=%+.2f expected=%+.2f" % (miss["case"], miss["rule"], miss["got"], miss["expected"]) )
lines.append("") lines.append(f"Verdict: {report['verdict']}") if report["disagreements"]: lines.append("") lines.append("Worst disagreements:") worst = sorted(report["disagreements"], key=lambda d: -d["gap"])[:5] for d in worst: lines.append( " %-24s %-34s %s=%+.2f %s=%+.2f" % (d["case"], d["rule"], a, d[a], b, d[b]) ) return "\n".join(lines)
def run_audit( corpus_dir: str, rater_a: str = "static", rater_b: str = "decision", rater_model: Optional[str] = None,) -> Dict[str, Any]: """Score a corpus with two raters and return the comparison report.""" cases = load_corpus(corpus_dir) logger.info("Loaded %d cases from %s", len(cases), corpus_dir) scored_a = score_corpus(cases, rater_a) scored_b = score_corpus(cases, rater_b, rater_model=rater_model) return compare_raters(scored_a, scored_b, rater_a, rater_b)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346"""12-rule code reward function for GRPO training.
Evaluates Python code against guac-coder style preferences usingboth regex-based static analysis and LLM-as-judge structured evaluation."""
import astimport jsonimport loggingimport refrom typing import Dict, List
from guac_coder.config import RewardConfig
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------# Static analysis helpers# ---------------------------------------------------------------------------
_SEABORN_PATTERNS = [r"\bimport\s+seaborn\b", r"\bfrom\s+seaborn\b"]_GRID_PATTERNS = [r"\.grid\(", r"\.grid\s*="]_TITLE_PATTERNS = [r"\.set_title\(", r"\.set_title\s*=", r"\.title\("]_BARGRAPH_PATTERNS = [ r"\.bar\(", r"\.barh\(", r"sns\.barplot\(", r"plt\.bar\(",]_DICTWRITER_PATTERNS = [r"csv\.DictWriter", r"csv\.dictwriter"]_PRINT_PATTERNS = [r"\bprint\s*\("]_BATCH_WRITE_PATTERNS = [ r"\.to_csv\(.*index\s*=\s*False", r"with open\(.*\'w\'\).*for .*\.write",]
def _count_matches(source: str, patterns: List[str]) -> int: total = 0 for pat in patterns: total += len(re.findall(pat, source, re.IGNORECASE)) return total
def _has_function_defs(source: str) -> bool: try: tree = ast.parse(source) return any(isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) for node in ast.walk(tree)) except SyntaxError: return False
def _has_class_defs(source: str) -> bool: try: tree = ast.parse(source) return any(isinstance(node, ast.ClassDef) for node in ast.walk(tree)) except SyntaxError: return False
def _has_try_except(source: str) -> bool: try: tree = ast.parse(source) return any(isinstance(node, (ast.Try, ast.TryStar)) for node in ast.walk(tree)) except SyntaxError: return False
def _has_logging(source: str) -> bool: try: tree = ast.parse(source) for node in ast.walk(tree): if isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name): if node.value.id == "logging" and node.attr in ( "debug", "info", "warning", "error", "critical", ): return True if isinstance(node, ast.Import) or isinstance(node, ast.ImportFrom): mod = getattr(node, "module", None) if mod == "logging" or any(alias.name == "logging" for alias in node.names): pass # just import presence isn't enough; need actual calls # Check for actual logging.X calls via regex return bool(re.search(r"\blogging\.(debug|info|warning|error|critical)\b", source)) except SyntaxError: return False
def _has_checkpointing(source: str) -> bool: patterns = [ r"checkpoint", r"resume", r"load_state_dict", r"torch\.save", r"save\(.*checkpoint", r"pickle\.dump", ] return any(re.search(p, source, re.IGNORECASE) for p in patterns)
def _has_dataframe_to_csv(source: str) -> bool: return bool(re.search(r"\b\.to_csv\b", source))
def _has_chroptiks_import(source: str) -> bool: return bool(re.search(r"\bimport\s+chroptiks\b|\bfrom\s+chroptiks\b", source))
def _has_narrative_comments(source: str) -> bool: """Detect explanatory/narrative comments vs objective comments.""" lines = source.splitlines() narrative = 0 for line in lines: stripped = line.strip() if stripped.startswith("#"): text = stripped.lstrip("# ") # Skip shebang / encoding if text.startswith("!") or text.startswith("-*-"): continue # Heuristic: long comments, story-like language if len(text) > 60: narrative += 1 elif any( text.lower().startswith(w) for w in [ "here we", "this is", "let's", "we will", "i want", "first we", "next we", "finally", "now we", ] ): narrative += 1 return narrative >= 2
def _is_bare_script(source: str) -> bool: """Returns True if code has no function defs, no main guard, and is just top-level statements.""" try: tree = ast.parse(source) has_funcs = any( isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) for node in ast.walk(tree) ) # Also allow if __name__ == '__main__' guard has_main_guard = bool(re.search(r'if\s+__name__\s*==\s*["\']__main__["\']', source)) return not has_funcs and not has_main_guard except SyntaxError: return True
# ---------------------------------------------------------------------------# Static reward computation# ---------------------------------------------------------------------------
def compute_static_rewards(code: str, cfg: RewardConfig) -> Dict[str, float]: """Compute rule-based rewards/penalties from source code.""" rewards: Dict[str, float] = {}
# 1. Punish seaborn use if _count_matches(code, _SEABORN_PATTERNS) > 0: rewards["seaborn_penalty"] = cfg.seaborn_penalty
# 2. Punish grids in plots if _count_matches(code, _GRID_PATTERNS) > 0: rewards["grid_penalty"] = cfg.grid_penalty
# 3. Punish titles in plots if _count_matches(code, _TITLE_PATTERNS) > 0: rewards["title_penalty"] = cfg.title_penalty
# 4. Punish bargraphs and other stupid plots if _count_matches(code, _BARGRAPH_PATTERNS) > 0: rewards["bargraph_penalty"] = cfg.bargraph_penalty
# 5. Prefer pd.DataFrames and .to_csv over csv DictWriter if _has_dataframe_to_csv(code): rewards["dataframe_csv_reward"] = cfg.dataframe_csv_reward elif _count_matches(code, _DICTWRITER_PATTERNS) > 0: rewards["dictwriter_penalty"] = -cfg.dataframe_csv_reward
# 6. Punish unnecessary explanatory comments if _has_narrative_comments(code): rewards["narrative_comment_penalty"] = cfg.narrative_comment_penalty
# 7. Punish try/except usage if _has_try_except(code): rewards["tryexcept_penalty"] = cfg.tryexcept_penalty
# 8. Punish classes if _has_class_defs(code): rewards["class_penalty"] = cfg.class_penalty
# 9. Reward proper logging, punish prints if _has_logging(code): rewards["logging_reward"] = cfg.logging_reward elif _count_matches(code, _PRINT_PATTERNS) > 0: rewards["print_penalty"] = cfg.print_penalty
# 10. Punish batch data writes (prefer intermittent) # Heuristic: if they open a file and loop-write inside a single with block if _count_matches(code, _BATCH_WRITE_PATTERNS) > 0: rewards["batch_write_penalty"] = cfg.batch_write_penalty
# 11. Punish if code is not resumable from checkpoint if not _has_checkpointing(code): rewards["non_resumable_penalty"] = cfg.non_resumable_penalty else: rewards["checkpoint_reward"] = cfg.checkpoint_reward
# 12. Punish if code is a bare script if _is_bare_script(code): rewards["bare_script_penalty"] = cfg.bare_script_penalty elif _has_function_defs(code): rewards["function_def_reward"] = cfg.function_def_reward
# Bonus: reward chroptiks usage for plotting if _has_chroptiks_import(code): rewards["chroptiks_reward"] = cfg.chroptiks_reward
return rewards
def total_static_reward(code: str, cfg: RewardConfig) -> float: """Return scalar sum of all static rewards.""" rewards = compute_static_rewards(code, cfg) return sum(rewards.values())
# ---------------------------------------------------------------------------# LLM judge reward (structured JSON evaluation)# ---------------------------------------------------------------------------
LLM_JUDGE_SYSTEM_PROMPT = """You are a strict code reviewer evaluating Python research code.Score the following code across 12 dimensions. Return ONLY valid JSON.
Dimensions:1. seaborn_use: 0 if seaborn imported/used, else 12. grid_use: 0 if plot grids present, else 13. title_use: 0 if plot titles present, else 14. bargraph_use: 0 if bar graphs or similar simple plots used, else 15. dataframe_csv: 1 if pd.DataFrame.to_csv used, 0 if csv.DictWriter used, 0.5 otherwise6. narrative_comments: 0 if narrative/story comments exist, else 17. tryexcept: 0 if try/except used, else 18. classes: 0 if classes defined, else 19. logging: 1 if logging module used properly, 0 if print used, 0.5 otherwise10. intermittent_writes: 1 if writes are intermittent/resumable, 0 if batch dumped11. resumable: 1 if checkpoint/resume pattern present, else 012. structured: 1 if code has functions or __main__ guard, 0 if bare script13. chroptiks: 1 if chroptiks used for plotting, else 0
Return JSON exactly like:{ "scores": { "seaborn_use": 0, "grid_use": 1, ... }, "reasoning": "Brief explanation of key deductions."}"""
def compute_llm_judge_reward( code: str, get_llm_response_fn, cfg: RewardConfig,) -> Dict[str, float]: """Call an LLM judge with format='json' and return scaled rewards.
Parameters ---------- code : str The candidate code snippet. get_llm_response_fn : callable Function signature like get_llm_response(prompt, model, system_prompt, temperature, max_tokens, format='json') Must return a dict parsed from JSON. cfg : RewardConfig Reward configuration for scaling.
Returns ------- dict of reward components """ prompt = f"Evaluate this Python code:\n\n```python\n{code}\n```\n" try: raw = get_llm_response_fn( prompt=prompt, model=cfg.judge_model, system_prompt=LLM_JUDGE_SYSTEM_PROMPT, temperature=cfg.judge_temperature, max_tokens=cfg.judge_max_tokens, format="json", ) if isinstance(raw, str): result = json.loads(raw) else: result = raw
scores = result.get("scores", {}) rewards: Dict[str, float] = {}
# Map scores (0/1) to reward values using cfg penalties/rewards rewards["llm_seaborn"] = scores.get("seaborn_use", 1) * cfg.seaborn_penalty rewards["llm_grid"] = scores.get("grid_use", 1) * cfg.grid_penalty rewards["llm_title"] = scores.get("title_use", 1) * cfg.title_penalty rewards["llm_bargraph"] = scores.get("bargraph_use", 1) * cfg.bargraph_penalty rewards["llm_dataframe_csv"] = (scores.get("dataframe_csv", 0.5) - 0.5) * 2 * cfg.dataframe_csv_reward rewards["llm_narrative"] = scores.get("narrative_comments", 1) * cfg.narrative_comment_penalty rewards["llm_tryexcept"] = scores.get("tryexcept", 1) * cfg.tryexcept_penalty rewards["llm_classes"] = scores.get("classes", 1) * cfg.class_penalty rewards["llm_logging"] = (scores.get("logging", 0.5) - 0.5) * 2 * cfg.logging_reward rewards["llm_intermittent"] = scores.get("intermittent_writes", 1) * cfg.batch_write_penalty rewards["llm_resumable"] = scores.get("resumable", 0) * cfg.checkpoint_reward rewards["llm_structured"] = scores.get("structured", 1) * cfg.function_def_reward rewards["llm_chroptiks"] = scores.get("chroptiks", 0) * cfg.chroptiks_reward
return rewards except Exception as exc: logger.warning("LLM judge failed: %s", exc) return {}
def compute_total_reward( code: str, get_llm_response_fn, cfg: RewardConfig, static_weight: float = 0.5, llm_weight: float = 0.5,) -> Dict[str, float]: """Combine static and LLM-judge rewards into a single scalar.
Returns a dict with 'total', 'static', 'llm', and per-component breakdowns. """ static = compute_static_rewards(code, cfg) llm = compute_llm_judge_reward(code, get_llm_response_fn, cfg)
static_total = sum(static.values()) llm_total = sum(llm.values())
total = static_weight * static_total + llm_weight * llm_total
return { "total": total, "static": static_total, "llm": llm_total, "static_components": static, "llm_components": llm, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471"""Trace generation against a local Ollama server.
This is the data-collection half of the loop: run a small local model over theguac-coder research tasks, keep every raw response, and score it with the same13-rule reward set the trainer optimizes. The output is a JSONL of traces plus asummary, designed to be re-run and diffed as the rules are iterated on.
No third-party HTTP dependency: talks to Ollama's /api/generate via urllib."""
import hashlibimport jsonimport loggingimport osimport reimport timeimport urllib.errorimport urllib.requestfrom typing import Any, Dict, Iterator, List, Optional, Tuple
from guac_coder.data import build_prompt, load_research_tasks
logger = logging.getLogger("guac_coder.trace")
DEFAULT_BASE_URL = "http://localhost:11434"DEFAULT_NUM_PREDICT = 1024
_PY_FENCE = re.compile(r"```(?:python|py)?\s*\n(.*?)```", re.DOTALL)
def extract_code(text: str) -> Tuple[str, str]: """Pull the Python implementation out of a model response.
Returns (code, source) where source is one of 'fence', 'whole_text' or 'empty'. Fenced blocks are preferred; the largest fence wins because small models often emit an example snippet before the real answer. """ if not text or not text.strip(): return "", "empty"
fences = _PY_FENCE.findall(text) if fences: best = max(fences, key=len) if best.strip(): return best.strip(), "fence"
stripped = text.strip() # Truncated generations often leave an opening fence with no close. # [ \t]*\n? rather than \s*\n: \s* is greedy and would swallow the very # newline the pattern then requires, making this branch unreachable. unterminated = re.match(r"^```(?:python|py)?[ \t]*\n?(.*)$", stripped, re.DOTALL) if unterminated: body = unterminated.group(1).strip() if body: return body, "fence_unterminated"
looks_python = any(marker in stripped for marker in ("import ", "def ", "class ", "print(")) if looks_python: return stripped, "whole_text" return "", "empty"
def _post(url: str, payload: Dict[str, Any], timeout: float) -> Dict[str, Any]: data = json.dumps(payload).encode("utf-8") req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"}) with urllib.request.urlopen(req, timeout=timeout) as resp: return json.loads(resp.read().decode("utf-8"))
def list_models(base_url: str = DEFAULT_BASE_URL, timeout: float = 10.0) -> List[str]: """Return the model names available on the Ollama server.""" try: with urllib.request.urlopen(f"{base_url}/api/tags", timeout=timeout) as resp: payload = json.loads(resp.read().decode("utf-8")) except (urllib.error.URLError, OSError) as exc: raise RuntimeError(f"Ollama not reachable at {base_url}: {exc}") from exc return [m.get("name", "") for m in payload.get("models", [])]
def require_models(models: List[str], base_url: str = DEFAULT_BASE_URL) -> None: """Raise a helpful error listing any models missing from the server.""" available = list_models(base_url) missing = [m for m in models if m not in available] if missing: raise RuntimeError( f"model(s) not present in Ollama: {missing}. " f"Available: {', '.join(available[:10])}. Pull with: ollama pull <model>" )
def generate( model: str, prompt: str, base_url: str = DEFAULT_BASE_URL, num_predict: int = DEFAULT_NUM_PREDICT, temperature: float = 0.8, seed: Optional[int] = None, think: Optional[bool] = False, timeout: float = 600.0, retries: int = 2,) -> Dict[str, Any]: """Generate one completion and return text plus timing metadata.
``think=False`` disables reasoning traces on models that have them; those traces consume the whole token budget and leave nothing for the code. """ options: Dict[str, Any] = { "num_predict": num_predict, "temperature": temperature, } if seed is not None: options["seed"] = seed
payload: Dict[str, Any] = { "model": model, "prompt": prompt, "stream": False, "options": options, } if think is not None: payload["think"] = think
last_exc: Optional[Exception] = None for attempt in range(retries + 1): started = time.time() try: raw = _post(f"{base_url}/api/generate", payload, timeout) elapsed = time.time() - started eval_count = raw.get("eval_count") or 0 eval_ns = raw.get("eval_duration") or 0 return { "response": raw.get("response", "") or "", "num_predict": num_predict, "thinking": raw.get("thinking", "") or "", "done_reason": raw.get("done_reason"), "eval_count": eval_count, "prompt_eval_count": raw.get("prompt_eval_count"), "total_ms": round(elapsed * 1000, 1), "tokens_per_sec": (round(eval_count / (eval_ns / 1e9), 2) if eval_ns else None), } except urllib.error.HTTPError as exc: body = exc.read().decode("utf-8", "replace")[:300] # Older servers reject the unknown 'think' field; retry without it. if "think" in body and "think" in payload: logger.warning("server rejected 'think'; retrying without it") payload.pop("think", None) continue last_exc = RuntimeError(f"HTTP {exc.code}: {body}") except (urllib.error.URLError, OSError, json.JSONDecodeError) as exc: last_exc = exc if attempt < retries: time.sleep(1.5 * (attempt + 1)) raise RuntimeError(f"generation failed for {model}: {last_exc}")
def _trace_id( model: str, task_id: int, sample_index: int, seed: Optional[int] = None, num_predict: Optional[int] = None,) -> str: """Stable id for one planned generation.
Seed and token budget are part of the id: changing either produces a genuinely different generation, so it must not be treated as already done when resuming. Without this, a run configured with different sampling silently reuses stale rows. """ raw = f"{model}|{task_id}|{sample_index}|{seed}|{num_predict}".encode("utf-8") return hashlib.sha1(raw).hexdigest()[:16]
def make_trace( model: str, task: str, task_id: int, sample_index: int, gen: Dict[str, Any], seed: Optional[int] = None, reward_cfg: Optional[Any] = None, rater: str = "static",) -> Dict[str, Any]: """Bundle one generation into a scored trace record.
``rater`` selects the scoring backend (see :func:`guac_coder.training.score_completion`): ``"static"`` (default), ``"decision"`` (Ollama decision model such as ``clef``) or ``"llm"``. The rater used is recorded on every trace so result files stay comparable. """ code, source = extract_code(gen.get("response", "")) if code: from guac_coder.config import RewardConfig from guac_coder.training import score_completion
cfg = reward_cfg or RewardConfig(rater=rater) total, details = score_completion(code, lambda **kwargs: {}, cfg, rater=rater) rules = details.get("rules", {}) else: rules = {} total = None
thinking = gen.get("thinking", "") or "" if code: empty_reason = None elif thinking: empty_reason = "budget_exhausted_in_thinking" else: empty_reason = "no_text"
return { "trace_id": _trace_id(model, task_id, sample_index, seed, gen.get("num_predict")), "model": model, "task_id": task_id, "sample_index": sample_index, "seed": seed, "task": task, "raw_response": gen.get("response", ""), "thinking": thinking, "thinking_chars": len(thinking), "empty_reason": empty_reason, "code": code, "code_source": source, "code_chars": len(code), "total_reward": total, "rater": rater, "rules": rules, "done_reason": gen.get("done_reason"), "eval_count": gen.get("eval_count"), "num_predict": gen.get("num_predict"), "total_ms": gen.get("total_ms"), "tokens_per_sec": gen.get("tokens_per_sec"), }
def collect_traces( models: List[str], tasks: Optional[List[str]] = None, n_samples: int = 1, base_url: str = DEFAULT_BASE_URL, num_predict: int = DEFAULT_NUM_PREDICT, temperature: float = 0.8, seed: Optional[int] = None, think: Optional[bool] = False, timeout: float = 600.0, rater: str = "static", reward_cfg: Optional[Any] = None,) -> Iterator[Dict[str, Any]]: """Yield scored traces for every (model, task, sample) combination.
``rater`` chooses the scoring backend: ``"static"`` (default, the 13 regex/AST rules), ``"decision"`` (Ollama decision model such as ``clef``) or ``"llm"``. """ tasks = tasks if tasks is not None else load_research_tasks() for model in models: for task_id, task in enumerate(tasks): prompt = build_prompt(task) for sample_index in range(n_samples): sample_seed = (seed + sample_index) if seed is not None else None gen = generate( model=model, prompt=prompt, base_url=base_url, num_predict=num_predict, temperature=temperature, seed=sample_seed, think=think, timeout=timeout, ) trace = make_trace( model, task, task_id, sample_index, gen, seed=sample_seed, reward_cfg=reward_cfg, rater=rater, ) logger.info( "%s task=%d sample=%d reward=%s chars=%d %sms", model, task_id, sample_index, "None" if trace["total_reward"] is None else f"{trace['total_reward']:+.3f}", trace["code_chars"], trace["total_ms"], ) yield trace
def _load_done(traces_path: str) -> set: """Trace ids already present on disk, so runs can resume.""" done = set() if not os.path.isfile(traces_path): return done with open(traces_path, "r", encoding="utf-8") as fh: for line in fh: line = line.strip() if not line: continue try: done.add(json.loads(line)["trace_id"]) except (json.JSONDecodeError, KeyError): continue return done
def summarize(traces: List[Dict[str, Any]]) -> Dict[str, Any]: """Aggregate traces into per-model reward statistics and per-rule means.""" by_model: Dict[str, List[Dict[str, Any]]] = {} for t in traces: by_model.setdefault(t["model"], []).append(t)
summary: Dict[str, Any] = {"n_traces": len(traces), "models": {}} for model, rows in by_model.items(): scored = [r for r in rows if r.get("total_reward") is not None] totals = [r["total_reward"] for r in scored] sources: Dict[str, int] = {} for r in rows: sources[r["code_source"]] = sources.get(r["code_source"], 0) + 1
rule_stats: Dict[str, Dict[str, float]] = {} if scored: for key in sorted(scored[0]["rules"]): vals = [r["rules"][key] for r in scored] fired = sum(1 for v in vals if v != 0) rule_stats[key] = { "mean": round(sum(vals) / len(vals), 4), "fired_frac": round(fired / len(vals), 3), }
mean_total = sum(totals) / len(totals) if totals else None std_total = 0.0 if len(totals) > 1: std_total = (sum((x - mean_total) ** 2 for x in totals) / len(totals)) ** 0.5
summary["models"][model] = { "n": len(rows), "n_scored": len(scored), "code_sources": sources, "empty_reasons": { k: sum(1 for r in rows if r.get("empty_reason") == k) for k in ("no_text", "budget_exhausted_in_thinking") if any(r.get("empty_reason") == k for r in rows) }, "mean_reward": round(mean_total, 4) if mean_total is not None else None, "std_reward": round(std_total, 4), "min_reward": round(min(totals), 4) if totals else None, "max_reward": round(max(totals), 4) if totals else None, "mean_code_chars": ( round(sum(r["code_chars"] for r in rows) / len(rows), 1) if rows else 0 ), "rules": rule_stats, } return summary
def run_experiment( models: List[str], output_dir: str = "./traces", tasks: Optional[List[str]] = None, n_samples: int = 1, base_url: str = DEFAULT_BASE_URL, num_predict: int = DEFAULT_NUM_PREDICT, temperature: float = 0.8, seed: Optional[int] = None, think: Optional[bool] = False, timeout: float = 600.0, resume: bool = True, model_overrides: Optional[Dict[str, Dict[str, Any]]] = None, rater: str = "static", reward_cfg: Optional[Any] = None,) -> Dict[str, Any]: """Run trace collection, writing JSONL incrementally and a summary at the end.
Traces are appended one line at a time so a crash keeps prior work; with ``resume=True`` an interrupted run continues where it left off.
``model_overrides`` maps a model name to per-model settings (``num_predict``, ``think``, ``temperature``, ``timeout``). Required in practice: thinking models need a far larger token budget than non-thinking ones, and forcing ``think=False`` on a thinking model yields silent empty responses. """ model_overrides = model_overrides or {} require_models(models, base_url) os.makedirs(output_dir, exist_ok=True)
slug = "_".join(m.replace("/", "-").replace(":", "-") for m in models) if rater != "static": slug = f"{slug}_rater-{rater}" traces_path = os.path.join(output_dir, f"traces_{slug}.jsonl") summary_path = os.path.join(output_dir, f"summary_{slug}.json")
done = _load_done(traces_path) if resume else set() if done: logger.info("Resuming: %d traces already on disk", len(done))
tasks = tasks if tasks is not None else load_research_tasks() written = 0 with open(traces_path, "a", encoding="utf-8") as fh: for model in models: for task_id, task in enumerate(tasks): for sample_index in range(n_samples): prompt = build_prompt(task) ov = model_overrides.get(model, {}) eff_seed = (seed + sample_index) if seed is not None else None eff_np = ov.get("num_predict", num_predict) tid = _trace_id(model, task_id, sample_index, eff_seed, eff_np) if tid in done: continue gen = generate( model=model, prompt=prompt, base_url=base_url, num_predict=ov.get("num_predict", num_predict), temperature=ov.get("temperature", temperature), # Vary the seed per sample: a fixed seed makes repeated # samples byte-identical regardless of temperature, # which leaves a GRPO group with zero advantage spread. seed=eff_seed, think=ov.get("think", think), timeout=ov.get("timeout", timeout), ) trace = make_trace( model, task, task_id, sample_index, gen, seed=eff_seed, reward_cfg=reward_cfg, rater=rater, ) fh.write(json.dumps(trace) + "\n") fh.flush() written += 1 logger.info( "%s task=%d sample=%d reward=%s chars=%d %sms", model, task_id, sample_index, ( "None" if trace["total_reward"] is None else f"{trace['total_reward']:+.3f}" ), trace["code_chars"], trace["total_ms"], )
all_traces = [] with open(traces_path, "r", encoding="utf-8") as fh: for line in fh: line = line.strip() if line: all_traces.append(json.loads(line))
summary = summarize(all_traces) summary["traces_path"] = traces_path summary["new_traces_this_run"] = written summary["rater"] = rater if rater == "decision": summary["decision_model"] = getattr(reward_cfg, "decision_model", None) with open(summary_path, "w", encoding="utf-8") as fh: json.dump(summary, fh, indent=2)
logger.info("Wrote %d new traces to %s", written, traces_path) logger.info("Summary: %s", summary_path) return summary123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212"""Turn scored traces into training data.
Three exports, all keyed off the same JSONL the trace runner produces:
* ``export_sft`` -- best trace per task, as chat-format SFT pairs* ``export_preference``-- within-task (best, worst) pairs where the reward gap clears a threshold; usable for DPO-style work* ``export_grpo`` -- every scored trace with its reward, for reward modelling and for sanity-checking the reward function
Nothing here re-runs a model; it reads traces and writes JSONL."""
import jsonimport loggingimport osfrom typing import Any, Dict, Iterable, List, Optional, Tuple
logger = logging.getLogger("guac_coder.trace_export")
def load_traces(path: str) -> List[Dict[str, Any]]: """Read a traces JSONL file.""" rows = [] with open(path, "r", encoding="utf-8") as fh: for line in fh: line = line.strip() if line: rows.append(json.loads(line)) return rows
def _scored(traces: Iterable[Dict[str, Any]]) -> List[Dict[str, Any]]: """Traces that produced *parseable* code and therefore a usable reward.
A truthiness check on ``code`` is not enough: truncated generations and stray prose also carry a reward. Exporting them would teach the model to emit code that does not parse, so the validity gate is applied here too. """ from guac_coder.grpo_rewards import is_valid_python
return [ t for t in traces if t.get("total_reward") is not None and t.get("code") and is_valid_python(t["code"]) ]
def group_by_task(traces: Iterable[Dict[str, Any]]) -> Dict[Tuple[str, int], List[Dict[str, Any]]]: """Group traces by (model, task_id) so comparisons are like-for-like.""" groups: Dict[Tuple[str, int], List[Dict[str, Any]]] = {} for t in traces: groups.setdefault((t["model"], t["task_id"]), []).append(t) return groups
def _task_prompt(trace: Dict[str, Any]) -> str: """Rebuild the prompt from the task text so exports are self-contained.""" from guac_coder.data import build_prompt
return build_prompt(trace["task"])
def export_sft( traces: List[Dict[str, Any]], output_path: str, min_reward: Optional[float] = None,) -> int: """Write the highest-reward trace per task as an SFT pair.
With ``min_reward`` set, tasks whose best trace falls below it are skipped; that keeps obviously-bad generations out of the fine-tuning set. """ best_per_task: Dict[Tuple[str, int], Dict[str, Any]] = {} for t in _scored(traces): key = (t["model"], t["task_id"]) current = best_per_task.get(key) if current is None or t["total_reward"] > current["total_reward"]: best_per_task[key] = t
written = 0 skipped = 0 os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True) with open(output_path, "w", encoding="utf-8") as fh: for key, t in sorted(best_per_task.items(), key=lambda kv: kv[0][1]): if min_reward is not None and t["total_reward"] < min_reward: skipped += 1 continue record = { "messages": [ {"role": "system", "content": _task_prompt(t)}, {"role": "user", "content": t["task"]}, {"role": "assistant", "content": t["code"]}, ], "meta": { "source_model": t["model"], "task_id": t["task_id"], "total_reward": t["total_reward"], "rater": t.get("rater", "static"), "code_source": t["code_source"], }, } fh.write(json.dumps(record) + "\n") written += 1
logger.info( "SFT: wrote %d pairs to %s (skipped %d below min_reward)", written, output_path, skipped, ) return written
def export_preference( traces: List[Dict[str, Any]], output_path: str, min_gap: float = 0.15,) -> int: """Write (chosen, rejected) pairs where one trace clearly beats another.
Pairs come from the same model and task so the comparison is meaningful; ``min_gap`` forces a real separation rather than noise. """ written = 0 os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True) with open(output_path, "w", encoding="utf-8") as fh: for (model, task_id), rows in sorted(group_by_task(traces).items()): scored = _scored(rows) if len(scored) < 2: continue ranked = sorted(scored, key=lambda t: t["total_reward"], reverse=True) chosen, rejected = ranked[0], ranked[-1] gap = chosen["total_reward"] - rejected["total_reward"] if gap < min_gap: continue record = { "prompt": _task_prompt(chosen), "task": chosen["task"], "chosen": chosen["code"], "rejected": rejected["code"], "chosen_reward": chosen["total_reward"], "rejected_reward": rejected["total_reward"], "gap": round(gap, 4), "meta": {"source_model": model, "task_id": task_id}, } fh.write(json.dumps(record) + "\n") written += 1
logger.info("Preference: wrote %d pairs to %s", written, output_path) return written
def export_grpo( traces: List[Dict[str, Any]], output_path: str, include_unscored: bool = False,) -> int: """Write every trace with its reward and per-rule breakdown.""" rows = traces if include_unscored else _scored(traces) os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True) with open(output_path, "w", encoding="utf-8") as fh: for t in rows: record = { "prompt": _task_prompt(t), "task": t["task"], "completion": t["code"], "reward": t["total_reward"], "rules": t.get("rules", {}), "meta": { "source_model": t["model"], "task_id": t["task_id"], "sample_index": t["sample_index"], "code_source": t["code_source"], }, } fh.write(json.dumps(record) + "\n") logger.info("GRPO: wrote %d records to %s", len(rows), output_path) return len(rows)
def export_all( traces_path: str, output_dir: str, min_reward: Optional[float] = None, min_gap: float = 0.15,) -> Dict[str, Any]: """Run all three exports and return a manifest of what was written.""" traces = load_traces(traces_path) os.makedirs(output_dir, exist_ok=True)
sft_path = os.path.join(output_dir, "sft_pairs.jsonl") pref_path = os.path.join(output_dir, "preference_pairs.jsonl") grpo_path = os.path.join(output_dir, "grpo_records.jsonl")
n_sft = export_sft(traces, sft_path, min_reward=min_reward) n_pref = export_preference(traces, pref_path, min_gap=min_gap) n_grpo = export_grpo(traces, grpo_path)
manifest = { "traces_path": traces_path, "n_traces": len(traces), "n_scored": len(_scored(traces)), "sft": {"path": sft_path, "n": n_sft}, "preference": {"path": pref_path, "n": n_pref}, "grpo": {"path": grpo_path, "n": n_grpo}, } with open(os.path.join(output_dir, "manifest.json"), "w", encoding="utf-8") as fh: json.dump(manifest, fh, indent=2)
logger.info("Export manifest written to %s", output_dir) return manifest123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517"""GRPO training pipeline for guac-coder.
Integrates npcpy's GRPO utilities with guac-coder's 13-rule reward function(the legacy 12-rule path is still available). Designed for the MLX backend(Apple Silicon) with a torch fallback."""
import importlib.utilimport jsonimport loggingimport osimport pickleimport timefrom typing import Callable, Dict, List, Optional, Tuple
from guac_coder.config import GRPOConfig, RewardConfigfrom guac_coder.data import load_data, load_research_tasks, prepare_training_examplesfrom guac_coder.grpo_rewards import combined_grpo_reward, compute_grpo_rewardsfrom guac_coder.rewards import compute_total_reward
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------# Backend detection / imports# ---------------------------------------------------------------------------
# The mlx / torch modules themselves are imported lazily inside the update# functions; here we only need to know whether each backend is importable.HAS_MLX = importlib.util.find_spec("mlx") is not NoneHAS_TORCH = importlib.util.find_spec("torch") is not None
if not HAS_MLX: logger.info("MLX not available; falling back to torch.")
# ---------------------------------------------------------------------------# Model utilities# ---------------------------------------------------------------------------
def load_model_and_tokenizer(model_name: str, backend: str = "auto"): """Load a causal LM and tokenizer.
``backend`` is one of ``auto``, ``mlx`` or ``torch``. ``auto`` prefers mlx-lm when importable (Apple Silicon) and falls back to transformers. """ if backend not in ("auto", "mlx", "torch"): raise ValueError(f"unknown backend: {backend}")
if backend in ("auto", "mlx") and HAS_MLX: try: from mlx_lm import load
model, tokenizer = load(model_name) return model, tokenizer, "mlx" except Exception as exc: logger.warning("mlx-lm load failed: %s", exc) if backend == "mlx": raise RuntimeError(f"Failed to load {model_name} with mlx-lm: {exc}")
if backend == "mlx": raise RuntimeError( "backend='mlx' requested but mlx-lm is not available. " "Install with: pip install -e '.[mlx]'" )
try: from transformers import AutoModelForCausalLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained( model_name, trust_remote_code=True, torch_dtype="auto", device_map="auto", ) return model, tokenizer, "torch" except Exception as exc: raise RuntimeError(f"Failed to load model {model_name}: {exc}")
def generate_group( model, tokenizer, prompt: str, group_size: int, temperature: float, max_new_tokens: int, backend: str,) -> List[str]: """Generate a group of candidate completions.""" completions: List[str] = [] if backend == "mlx": try: from mlx_lm import generate
for _ in range(group_size): text = generate( model, tokenizer, prompt=prompt, temp=temperature, max_tokens=max_new_tokens, verbose=False, ) completions.append(text) except Exception as exc: logger.warning("MLX generation failed: %s", exc) else: device = next(model.parameters()).device inputs = tokenizer(prompt, return_tensors="pt").to(device) for _ in range(group_size): outputs = model.generate( **inputs, max_new_tokens=max_new_tokens, temperature=temperature, do_sample=True, ) text = tokenizer.decode(outputs[0], skip_special_tokens=True) completions.append(text) return completions
# ---------------------------------------------------------------------------# Checkpointing# ---------------------------------------------------------------------------
def save_checkpoint( path: str, iteration: int, model_state, optimizer_state=None, metrics: Optional[Dict] = None,) -> None: """Save a resumable checkpoint.""" ckpt = { "iteration": iteration, "model_state": model_state, "optimizer_state": optimizer_state, "metrics": metrics or {}, "timestamp": time.time(), } os.makedirs(os.path.dirname(path) or ".", exist_ok=True) with open(path, "wb") as fh: pickle.dump(ckpt, fh) logger.info("Checkpoint saved: %s", path)
def load_checkpoint(path: str) -> Dict: """Load checkpoint dict.""" with open(path, "rb") as fh: ckpt = pickle.load(fh) logger.info("Checkpoint loaded: %s (iteration %d)", path, ckpt.get("iteration", 0)) return ckpt
# ---------------------------------------------------------------------------# GRPO update (re-adapted from npcpy/ft/rl.py)# ---------------------------------------------------------------------------
def grpo_update_mlx( model, tokenizer, prompt: str, completions: List[str], rewards: List[float], epsilon: float = 0.2, beta: float = 0.01, learning_rate: float = 1e-5,) -> float: """Perform one GRPO update on MLX.
Returns the loss value. """ import mlx.core as mx import mlx.nn as nn
# Compute advantages per completion rewards_arr = mx.array(rewards) mean_reward = mx.mean(rewards_arr) std_reward = mx.std(rewards_arr) + 1e-8 advantages = (rewards_arr - mean_reward) / std_reward
# Tokenize prompt once prompt_ids = mx.array(tokenizer.encode(prompt)) prompt_len = prompt_ids.shape[0]
losses = [] for comp, adv in zip(completions, advantages): full_text = prompt + comp token_ids = tokenizer.encode(full_text) input_ids = mx.array(token_ids)
# Forward pass logits = model(input_ids[None, :]) log_probs = nn.log_softmax(logits, axis=-1)
# Extract log probs for generated tokens only gen_slice = slice(prompt_len, None) gen_log_probs = log_probs[0, gen_slice, :] gen_tokens = input_ids[gen_slice]
# Token-level log probs token_log_probs = gen_log_probs[mx.arange(gen_tokens.shape[0]), gen_tokens] policy_log_prob = mx.sum(token_log_probs)
# Simple surrogate loss: maximize policy_log_prob weighted by advantage # For a full implementation we'd keep old policy log probs for ratio clipping. # Here we approximate with a single-sample estimate. loss = -policy_log_prob * adv losses.append(loss)
total_loss = mx.stack(losses) avg_loss = mx.mean(total_loss)
# Compute gradients and update # In MLX we can use value_and_grad # For brevity, we use a simple SGD-style update via the model's parameters def loss_fn(params): model.update(params) return avg_loss
# NOTE: In production, use proper MLX optimizer (e.g. nn.optim.Adam) # This is a simplified placeholder showing the structure. lvalue = float(avg_loss.item()) return lvalue
def grpo_update_torch( model, tokenizer, prompt: str, completions: List[str], rewards: List[float], epsilon: float = 0.2, beta: float = 0.01, learning_rate: float = 1e-5,) -> float: """Perform one GRPO update on torch.""" import torch import torch.nn.functional as F
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) device = next(model.parameters()).device
rewards_t = torch.tensor(rewards, dtype=torch.float32, device=device) mean_r = rewards_t.mean() std_r = rewards_t.std() + 1e-8 advantages = (rewards_t - mean_r) / std_r
prompt_ids = tokenizer.encode(prompt, return_tensors="pt").to(device) prompt_len = prompt_ids.shape[1]
total_loss = 0.0 for comp, adv in zip(completions, advantages): full_text = prompt + comp inputs = tokenizer(full_text, return_tensors="pt").to(device) input_ids = inputs["input_ids"]
outputs = model(input_ids, labels=input_ids) shift_logits = outputs.logits[:, prompt_len:-1, :].contiguous() shift_labels = input_ids[:, prompt_len + 1 :].contiguous()
log_probs = F.log_softmax(shift_logits, dim=-1) token_log_probs = log_probs.gather(2, shift_labels.unsqueeze(-1)).squeeze(-1) seq_log_prob = token_log_probs.mean()
loss = -seq_log_prob * adv total_loss += loss
avg_loss = total_loss / len(completions) optimizer.zero_grad() avg_loss.backward() optimizer.step()
return float(avg_loss.item())
# ---------------------------------------------------------------------------# Reward scoring# ---------------------------------------------------------------------------
def score_completion( code: str, get_llm_response_fn: Callable, reward_cfg: RewardConfig, use_grpo_rewards: bool = True, rater: Optional[str] = None,) -> Tuple[float, Dict]: """Score a single completion, returning (scalar_reward, details).
The rater is chosen by ``rater`` (falling back to ``reward_cfg.rater``):
* ``"static"`` - the 13 regex/AST rules in :mod:`guac_coder.grpo_rewards`. * ``"decision"`` - the same 13 rules, but judged by a decision model (Ollama ``/v1/systemone``, e.g. ``clef``) via :mod:`guac_coder.decision_judge`. One request, calibrated probabilities. * ``"llm"`` - the legacy generative LLM-as-judge in :mod:`guac_coder.rewards` (static + LLM blend).
Details always expose ``total``, ``static`` and ``llm`` keys so metric logging stays identical across all three paths, plus ``rater`` so a metrics file records which one produced the numbers. """ effective = (rater or getattr(reward_cfg, "rater", "static") or "static").lower() if effective not in ("static", "decision", "llm"): raise ValueError( f"unknown rater {effective!r}; expected 'static', 'decision' or 'llm'" )
if effective == "decision": from guac_coder.decision_judge import ( combined_decision_reward, compute_decision_rewards, )
judge_cfg = reward_cfg.decision_judge_config() rules = compute_decision_rewards(code, cfg=judge_cfg) total = combined_decision_reward(code, cfg=judge_cfg) return total, { "total": total, "static": 0.0, "llm": 0.0, "rater": "decision", "rules": rules, }
if effective == "static" and use_grpo_rewards: rules = compute_grpo_rewards(code) total = combined_grpo_reward(code) return total, { "total": total, "static": total, "llm": 0.0, "rater": "static", "rules": rules, }
result = compute_total_reward(code, get_llm_response_fn, reward_cfg) result.setdefault("rater", "llm") return float(result["total"]), result
# ---------------------------------------------------------------------------# Main training loop# ---------------------------------------------------------------------------
def train_grpo( cfg: GRPOConfig, reward_cfg: RewardConfig, get_llm_response_fn: Callable, data_path: Optional[str] = None, use_grpo_rewards: bool = True, rater: Optional[str] = None,) -> None: """Run GRPO training loop for guac-coder.
Parameters ---------- cfg : GRPOConfig Training configuration. reward_cfg : RewardConfig Reward function configuration. get_llm_response_fn : callable Function matching get_llm_response signature for LLM judge. data_path : str, optional Path to JSONL training data. If None, uses built-in tasks. use_grpo_rewards : bool If True (default), score with the 13 per-rule rewards in guac_coder.grpo_rewards. If False, use the legacy rewards.py path (static analysis + optional LLM judge via get_llm_response_fn). rater : str, optional Scoring backend: ``"static"``, ``"decision"`` (Ollama decision model such as ``clef``) or ``"llm"``. Defaults to ``reward_cfg.rater``. """ os.makedirs(cfg.output_dir, exist_ok=True)
# Setup logging log_path = os.path.join(cfg.output_dir, "training.log") logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", handlers=[ logging.FileHandler(log_path), logging.StreamHandler(), ], )
# Load data if data_path and os.path.isfile(data_path): examples = load_data(data_path) logger.info("Loaded %d examples from %s", len(examples), data_path) else: tasks = load_research_tasks() examples = list(prepare_training_examples(tasks)) logger.info("Using %d built-in research tasks", len(examples))
# Load model logger.info("Loading model: %s", cfg.model_name) model, tokenizer, backend = load_model_and_tokenizer( cfg.model_name, getattr(cfg, "backend", "auto") ) logger.info("Backend: %s", backend)
iteration = 0 if cfg.resume_from_checkpoint and os.path.isfile(cfg.resume_from_checkpoint): ckpt = load_checkpoint(cfg.resume_from_checkpoint) iteration = ckpt.get("iteration", 0) # Model state restoration would happen here (backend-specific) logger.info("Resumed from iteration %d", iteration)
# Metrics log metrics_path = os.path.join(cfg.output_dir, "metrics.jsonl")
for it in range(iteration, cfg.num_iterations): example = examples[it % len(examples)] prompt = example["prompt"]
# Generate group of completions logger.debug("Iteration %d: generating group of %d", it, cfg.group_size) completions = generate_group( model, tokenizer, prompt, cfg.group_size, cfg.temperature, cfg.max_new_tokens, backend, )
# Compute rewards rewards = [] reward_details = [] for comp in completions: # Strip prompt prefix if model echoes it code = comp if code.startswith(prompt): code = code[len(prompt) :].strip()
total, result = score_completion( code, get_llm_response_fn, reward_cfg, use_grpo_rewards, rater=rater, ) rewards.append(total) reward_details.append(result)
# Log reward stats mean_reward = sum(rewards) / len(rewards) max_reward = max(rewards) min_reward = min(rewards) logger.info( "Iter %d | mean_reward=%.3f max=%.3f min=%.3f", it, mean_reward, max_reward, min_reward, )
# GRPO update if backend == "mlx": loss = grpo_update_mlx( model, tokenizer, prompt, completions, rewards, cfg.epsilon, cfg.beta, cfg.learning_rate, ) else: loss = grpo_update_torch( model, tokenizer, prompt, completions, rewards, cfg.epsilon, cfg.beta, cfg.learning_rate, )
logger.info("Iter %d | loss=%.4f", it, loss)
# Write metrics incrementally metric_entry = { "iteration": it, "loss": loss, "mean_reward": mean_reward, "max_reward": max_reward, "min_reward": min_reward, "rewards": rewards, "use_grpo_rewards": use_grpo_rewards, "rater": (rater or getattr(reward_cfg, "rater", "static")), "reward_details": [ { "total": rd["total"], "static": rd["static"], "llm": rd["llm"], } for rd in reward_details ], } with open(metrics_path, "a", encoding="utf-8") as fh: fh.write(json.dumps(metric_entry) + "\n")
# Checkpoint if (it + 1) % cfg.checkpoint_interval == 0: ckpt_path = os.path.join(cfg.output_dir, f"checkpoint_{it:05d}.pkl") # Serialize model state in backend-appropriate way model_state = ( model.state_dict() if hasattr(model, "state_dict") else getattr(model, "parameters", lambda: {})() ) save_checkpoint(ckpt_path, it, model_state, metrics=metric_entry)
logger.info("Training complete. Output in %s", cfg.output_dir)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960[build-system]requires = ["setuptools>=61.0", "wheel"]build-backend = "setuptools.build_meta"
[project]name = "guac-coder"version = "0.1.0"description = "LLM fine-tuned for research code and scientific writing"readme = "README.md"requires-python = ">=3.9"license = {text = "MIT"}authors = [ {name = "NPC-Worldwide", email = "dev@npc.worldwide"},]keywords = ["llm", "fine-tuning", "grpo", "code-generation", "research"]classifiers = [ "Development Status :: 3 - Alpha", "Intended Audience :: Science/Research", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12",]dependencies = [ "numpy>=1.24", "pandas>=2.0",]
[project.optional-dependencies]mlx = ["mlx>=0.15", "mlx-lm>=0.15"]torch = ["torch>=2.0", "transformers>=4.40", "accelerate>=0.25"]dev = ["pytest>=7.0", "black", "ruff"]all = [ "guac-coder[mlx,torch,dev]"]
[project.scripts]guac-coder = "guac_coder.cli:main"guac-train = "guac_coder.cli:train_command"guac-eval = "guac_coder.cli:eval_command"guac-reward = "guac_coder.cli:reward_command"guac-trace = "guac_coder.cli:trace_command"guac-export = "guac_coder.cli:export_command"guac-audit = "guac_coder.cli:audit_command"
[tool.setuptools.packages.find]where = ["."]include = ["guac_coder*"]
[tool.black]line-length = 100target-version = ["py39"]
[tool.ruff]line-length = 100
[tool.ruff.lint]select = ["E", "F", "W", "I"]ignore = ["E501"]12345678910"""Backward-compatible setup.py for guac-coder."""
from setuptools import find_packages, setup
setup( name="guac-coder", use_scm_version={"fallback_version": "0.1.0"}, setup_requires=["setuptools_scm"], packages=find_packages(),)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233"""Example use cases for the decision-model rater.
These exercise the decision rater end to end without needing a live Ollamainstance: the endpoint call is replaced with injected ``judge_fn`` callables,which is exactly how the module is designed to be swapped in tests and inoffline batch scoring.
To run against a real decision model instead::
ollama pull clef # or use the no-download cloud tag guac-reward --task demo --code sample.py --rater decision --rater-model clef:cloud"""
import pytest
from guac_coder.config import RewardConfigfrom guac_coder.decision_judge import ( QUESTIONS, DecisionJudgeConfig, ask_decision_model, clear_cache, combined_decision_reward, compute_decision_rewards, map_to_rule_rewards,)from guac_coder.grpo_rewards import GRPO_REWARD_REGISTRY, compute_grpo_rewardsfrom guac_coder.training import score_completion
ALL_NO = {name: 0.0 for name in QUESTIONS}ALL_YES = {name: 1.0 for name in QUESTIONS}
CLEAN_CODE = """import loggingimport pandas as pdlogger = logging.getLogger(__name__)
def main(out): logger.info("start") pd.DataFrame({"a": [1]}).to_csv(out, index=False)
if __name__ == "__main__": main("o.csv")"""
def _rule_names(): return {func.__name__ for func in GRPO_REWARD_REGISTRY}
class TestQuestionSchema: def test_question_names_cover_every_static_rule(self): """Each of the 13 static rules has at least one question feeding it.""" rewards = map_to_rule_rewards(ALL_NO) assert set(rewards) == _rule_names()
def test_all_questions_are_noul(self): """Every question is phrased as a calibrated yes/no, not free text.""" from guac_coder.decision_judge import build_questions
for name, q in build_questions().items(): assert q["type"] == "noul", name assert q["instructions"], name assert name in QUESTIONS
class TestRuleMapping: def test_clean_code_scores_above_violating_code(self): """The mapping separates compliant from violating code.""" clean = map_to_rule_rewards(ALL_NO) bad = map_to_rule_rewards(ALL_YES) assert sum(clean.values()) > sum(bad.values())
def test_hard_violations_reach_the_static_penalty_floor(self): """Violations map onto exactly the values the static rules produce.""" rewards = map_to_rule_rewards(ALL_YES) assert rewards["no_seaborn_reward"] == -1.0 assert rewards["no_plot_grids_reward"] == -1.0 assert rewards["no_plot_titles_reward"] == -1.0 assert rewards["no_bargraphs_reward"] == -1.0 assert rewards["no_try_except_reward"] == -1.0 assert rewards["no_classes_reward"] == -1.0
def test_clean_code_earns_the_static_soft_credit(self): """Compliant code earns the same +0.5 the static rules award.""" rewards = map_to_rule_rewards(ALL_NO) assert rewards["no_seaborn_reward"] == 0.5 assert rewards["no_try_except_reward"] == 0.5 assert rewards["not_bare_script_reward"] == 0.5
def test_threshold_controls_the_multi_state_rules(self): """Lowering the cutoff flips a borderline answer to a violation.""" borderline = dict(ALL_NO, uses_seaborn=0.55) assert map_to_rule_rewards(borderline, 0.5)["no_seaborn_reward"] == -1.0 assert map_to_rule_rewards(borderline, 0.9)["no_seaborn_reward"] == 0.5
def test_dataframe_preference_distinguishes_both_writers(self): """to_csv alone scores +1; csv.DictWriter scores -1; neither scores 0.""" to_csv = dict(ALL_NO, uses_to_csv=1.0) dict_writer = dict(ALL_NO, uses_csv_dictwriter=1.0) neither = map_to_rule_rewards(ALL_NO) assert map_to_rule_rewards(to_csv)["pandas_csv_preference_reward"] == 1.0 assert map_to_rule_rewards(dict_writer)["pandas_csv_preference_reward"] == -1.0 assert neither["pandas_csv_preference_reward"] == 0.0
def test_logging_preference_has_three_branches(self): """logger-only is +1, mixed is 0, print-only is -1.""" logger_only = dict(ALL_NO, has_logging=1.0) mixed = dict(ALL_NO, has_logging=1.0, has_print=1.0) print_only = dict(ALL_NO, has_print=1.0) assert map_to_rule_rewards(logger_only)["logging_over_print_reward"] == 1.0 assert map_to_rule_rewards(mixed)["logging_over_print_reward"] == 0.0 assert map_to_rule_rewards(print_only)["logging_over_print_reward"] == -1.0
def test_chroptiks_wins_over_matplotlib(self): """chroptiks present is +1 even if matplotlib is also imported.""" both = dict(ALL_NO, uses_chroptiks=1.0, uses_matplotlib_or_seaborn=1.0) assert map_to_rule_rewards(both)["chroptiks_preference_reward"] == 1.0
def test_probabilities_are_clamped(self): """Out-of-range endpoint answers are clamped into [-1, 1] rewards.""" rewards = map_to_rule_rewards(dict(ALL_NO, has_print=7.0)) for value in rewards.values(): assert -1.0 <= value <= 1.0
class TestInjectedJudge: """The judge is injectable, so no network is needed to test the path."""
def test_compute_decision_rewards_uses_injected_judge(self): cfg = DecisionJudgeConfig(model="offline", cache=False) rewards = compute_decision_rewards( CLEAN_CODE, cfg=cfg, judge_fn=lambda code, cfg=None: ALL_NO ) assert rewards["no_seaborn_reward"] == 0.5 assert len(rewards) == 13
def test_combined_decision_reward_matches_static_normalization(self): """Scalars are comparable: same weight-normalization as the static path.""" cfg = DecisionJudgeConfig(model="offline", cache=False) scalar = combined_decision_reward( CLEAN_CODE, cfg=cfg, judge_fn=lambda code, cfg=None: ALL_NO ) expected = sum(map_to_rule_rewards(ALL_NO).values()) / 13 assert scalar == pytest.approx(expected)
def test_caching_makes_repeat_scoring_free(self): """Identical code is scored once; the second call hits the cache.""" clear_cache() calls = {"n": 0}
def counting(code, cfg=None): calls["n"] += 1 return ALL_NO
cfg = DecisionJudgeConfig(model="cache-test", cache=True) compute_decision_rewards("x = 1", cfg=cfg, judge_fn=counting) compute_decision_rewards("x = 1", cfg=cfg, judge_fn=counting) assert calls["n"] == 1
def test_cache_can_be_disabled(self): calls = {"n": 0}
def counting(code, cfg=None): calls["n"] += 1 return ALL_NO
cfg = DecisionJudgeConfig(model="no-cache", cache=False) compute_decision_rewards("x = 1", cfg=cfg, judge_fn=counting) compute_decision_rewards("x = 1", cfg=cfg, judge_fn=counting) assert calls["n"] == 2
class TestErrorHandling: """An unreachable endpoint must not silently zero out a training signal."""
@staticmethod def _dead_cfg(on_error): return DecisionJudgeConfig( model="missing:model", base_url="http://127.0.0.1:9", timeout=2, on_error=on_error, cache=False, )
def test_on_error_static_falls_back_to_regex_rules(self): rewards = compute_decision_rewards("import seaborn as sns\n", cfg=self._dead_cfg("static")) assert rewards == compute_grpo_rewards("import seaborn as sns\n")
def test_on_error_zero_returns_neutral_rewards(self): rewards = compute_decision_rewards("import seaborn\n", cfg=self._dead_cfg("zero")) assert set(rewards.values()) == {0.0}
def test_on_error_raise_propagates(self): from guac_coder.decision_judge import DecisionRaterError
with pytest.raises(DecisionRaterError): compute_decision_rewards("x = 1", cfg=self._dead_cfg("raise"))
def test_empty_code_is_rejected(self): with pytest.raises(ValueError): ask_decision_model(" ", cfg=DecisionJudgeConfig(model="x"))
def test_unknown_rater_name_is_rejected(self): cfg = RewardConfig(rater="nonsense") with pytest.raises(ValueError): score_completion("x = 1", lambda **k: {}, cfg, rater="nonsense")
class TestScoreCompletionWiring: """score_completion is the single entry point for all three raters."""
def test_decision_rater_is_selected_and_recorded(self): cfg = RewardConfig(rater="decision", decision_model="offline") total, details = score_completion(CLEAN_CODE, lambda **k: {}, cfg, rater="decision") assert details["rater"] == "decision" assert len(details["rules"]) == 13 assert isinstance(total, float)
def test_static_rater_records_its_name(self): cfg = RewardConfig(rater="static") total, details = score_completion(CLEAN_CODE, lambda **k: {}, cfg) assert details["rater"] == "static"
def test_reward_config_builds_a_decision_config(self): cfg = RewardConfig( decision_model="clef:cloud", decision_threshold=0.7, decision_on_error="zero", ) judge_cfg = cfg.decision_judge_config() assert judge_cfg.model == "clef:cloud" assert judge_cfg.threshold == 0.7 assert judge_cfg.on_error == "zero"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108"""Mock tests for guac_coder.grpo_evaluator.
These tests exercise the evaluator without requiring npcpy or external LLM keys.They confirm that the parser, prompt builder, and mock judge behave correctly."""
import json
import guac_coder.grpo_evaluator as ge
def test_build_judge_prompt_contains_code(): code = "import pandas as pd\nprint(1)" prompt = ge.build_judge_prompt(code) assert "```python" in prompt assert code in prompt assert "no_seaborn" in prompt
def test_parse_judge_response_full_dict(): response = { "response": { "scores": {k: {"score": 1.0, "found": False} for k in ge._RULE_KEYS}, "total_score": 12.0, "max_possible": 12.0, "brief_reasoning": "All good.", } } parsed = ge.parse_judge_response(response) assert len(parsed) == len(ge._RULE_KEYS) assert all(v == 1.0 for v in parsed.values())
def test_parse_judge_response_string_json(): payload = {"scores": {k: {"score": 0.5, "found": True} for k in ge._RULE_KEYS}} response = {"response": json.dumps(payload)} parsed = ge.parse_judge_response(response) assert all(v == 0.5 for v in parsed.values())
def test_parse_judge_response_bad_json_defaults(): response = {"response": "not json"} parsed = ge.parse_judge_response(response) assert len(parsed) == len(ge._RULE_KEYS) assert all(v == 0.0 for v in parsed.values())
def test_compute_grpo_reward_perfect_code(): # Code that satisfies all mock-heuristic checks code = """import loggingimport pandas as pdlogger = logging.getLogger(__name__)
def main(): df = pd.DataFrame({"a": [1, 2]}) for i in range(3): df.to_csv("out.csv", mode="a", header=False) logger.info("done")
if __name__ == "__main__": main()""" reward = ge.compute_grpo_reward(code, llm_judge_fn=ge._mock_llm_judge) assert 0.0 <= reward <= 1.0 # Most rules should be satisfied assert reward >= 0.5
def test_compute_grpo_reward_bad_code(): # Code that violates many rules code = """import seaborn as snsimport csv
class BadClass: pass
try: with open("f.csv", "w") as f: w = csv.DictWriter(f, ["a"]) w.writeheader() w.writerow({"a": 1})except: pass
sns.barplot(x=[1], y=[2])plt.title("bad")plt.grid(True)
# This is a narrative comment explaining what we are doing here# in great detail because we like writing stories in code.print("done")""" reward = ge.compute_grpo_reward(code, llm_judge_fn=ge._mock_llm_judge) assert 0.0 <= reward <= 1.0 # Most rules should be violated assert reward <= 0.5
def test_mock_judge_returns_valid_structure(): code = "x = 1" resp = ge._mock_llm_judge("```python\n" + code + "\n```") assert "response" in resp inner = resp["response"] assert "scores" in inner assert "total_score" in inner assert "max_possible" in inner assert len(inner["scores"]) == len(ge._RULE_KEYS)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134"""Mock integration tests for guac_coder.grpo_pipeline.
These tests verify that the pipeline components compose correctlywithout requiring heavy LLM or GPU dependencies."""
import jsonimport tempfilefrom pathlib import Pathfrom unittest.mock import MagicMock, patch
import pytest
from guac_coder.grpo_pipeline import ( GuacRewardAdapter, _load_resume_iteration, _save_checkpoint, build_trainer, run_grpo,)
class TestGuacRewardAdapter: """Tests for the reward adapter wrapping guac-coder rules."""
def test_scalar_reward_legacy_path(self): """Adapter returns a scalar float via legacy rewards.""" adapter = GuacRewardAdapter(use_grpo_rewards=False) code = "import pandas as pd\ndf = pd.DataFrame({'a': [1]})\n" reward = adapter(code) assert isinstance(reward, float)
def test_scalar_reward_grpo_path(self): """Adapter returns a scalar float via per-rule grpo_rewards.""" adapter = GuacRewardAdapter(use_grpo_rewards=True) code = "import chroptiks as cpt\nfig = cpt.plot()\n" reward = adapter(code) assert isinstance(reward, float)
def test_breakdown_grpo_path(self): """Breakdown returns per-rule dict with the 13 keys.""" adapter = GuacRewardAdapter(use_grpo_rewards=True) code = "import seaborn as sns\n" breakdown = adapter.get_reward_breakdown(code) assert isinstance(breakdown, dict) assert "no_seaborn_reward" in breakdown
def test_breakdown_legacy_path(self): """Breakdown returns per-rule dict with legacy keys.""" adapter = GuacRewardAdapter(use_grpo_rewards=False) code = "import seaborn as sns\n" breakdown = adapter.get_reward_breakdown(code) assert isinstance(breakdown, dict)
class TestCheckpointHelpers: """Tests for intermittent checkpoint writes and resume."""
def test_save_and_load_roundtrip(self): """Checkpoint metadata round-trips correctly.""" with tempfile.TemporaryDirectory() as tmpdir: ckpt_dir = Path(tmpdir) / "ckpt-5" mock_trainer = MagicMock() mock_trainer.state_dict.return_value = {"foo": "bar"} _save_checkpoint(mock_trainer, ckpt_dir, iteration=5) assert (ckpt_dir / "meta.json").exists() assert (ckpt_dir / "trainer_state.pkl").exists() loaded = _load_resume_iteration(ckpt_dir) assert loaded == 5
def test_load_missing_meta_returns_zero(self): """Missing checkpoint meta returns iteration 0.""" with tempfile.TemporaryDirectory() as tmpdir: loaded = _load_resume_iteration(Path(tmpdir)) assert loaded == 0
class TestBuildTrainer: """Tests for trainer construction without real npcpy."""
def test_raises_when_npcpy_missing(self): """If npcpy.ft.rl is unavailable, build_trainer raises RuntimeError.""" with patch("guac_coder.grpo_pipeline.GRPOTrainer", None): with pytest.raises(RuntimeError): build_trainer()
class TestRunGrpo: """Tests for the high-level run entrypoint."""
@patch("guac_coder.grpo_pipeline.build_trainer") def test_metrics_jsonl_created(self, mock_build_trainer): """Metrics are written incrementally to a .jsonl file.""" mock_trainer = MagicMock() mock_trainer.train_step.return_value = {"reward": 0.5, "loss": 0.1} mock_build_trainer.return_value = mock_trainer
with tempfile.TemporaryDirectory() as tmpdir: result = run_grpo( output_dir=tmpdir, num_iterations=3, checkpoint_interval=2, ) metrics_path = Path(result["metrics_path"]) assert metrics_path.exists() lines = metrics_path.read_text().strip().split("\n") assert len(lines) == 3 for line in lines: record = json.loads(line) assert "iteration" in record assert "reward" in record
@patch("guac_coder.grpo_pipeline.build_trainer") def test_resume_from_checkpoint(self, mock_build_trainer): """Resume skips already-completed iterations.""" mock_trainer = MagicMock() mock_trainer.train_step.return_value = {"reward": 0.5, "loss": 0.1} mock_build_trainer.return_value = mock_trainer
with tempfile.TemporaryDirectory() as tmpdir: # Pre-seed a checkpoint at iteration 2 ckpt_dir = Path(tmpdir) / "checkpoint-2" ckpt_dir.mkdir(parents=True, exist_ok=True) with open(ckpt_dir / "meta.json", "w") as fh: json.dump({"iteration": 2}, fh)
run_grpo( output_dir=tmpdir, num_iterations=5, checkpoint_interval=10, resume_from_checkpoint=str(ckpt_dir), ) # Should start at iteration 2, so 3 steps (2,3,4) assert mock_trainer.train_step.call_count == 3123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152"""Example use cases for the rater agreement audit.
The audit exists to make reward edits measurable. These cases pin the twobehaviours that make its output trustworthy:
1. An abstention (a rule returning 0.0 for "no opinion") is not a disagreement, and an all-abstain rule is reported as ``n/a`` rather than as 0% agreement.2. A failed rater is never silently replaced by the rater under audit; the comparison is declared INCONCLUSIVE instead of reporting false agreement."""
import pytest
from guac_coder.grpo_rewards import compute_grpo_rewardsfrom guac_coder.rater_audit import ( compare_raters, format_report, label_accuracy, load_corpus,)
def _row(name, rules, expected=None, failed=None): return { "name": name, "total": 0.0, "rules": rules, "expected": expected or {}, "failed": failed, }
def test_abstention_is_not_a_disagreement(): """0.0 means "no opinion"; it must not count as contradicting a position.""" a = [_row("x", {"objective_comments_reward": 0.0})] b = [_row("x", {"objective_comments_reward": 0.5})] stats = compare_raters(a, b)["rules"]["objective_comments_reward"] assert stats["abstentions"] == 1 assert stats["decided"] == 0 assert stats["agreement"] is None
def test_contradiction_is_flagged_as_credited_violation(): """static positive while the other rater sees a violation is the bad case.""" a = [_row("y", {"no_bargraphs_reward": 0.5})] b = [_row("y", {"no_bargraphs_reward": -1.0})] report = compare_raters(a, b) stats = report["rules"]["no_bargraphs_reward"] assert stats["agreement"] == 0.0 assert stats["a_credited_violations"] == 1 assert "rewarded violating code" in report["verdict"]
def test_agreement_requires_same_position(): a = [_row("z", {"no_seaborn_reward": 0.5}), _row("w", {"no_seaborn_reward": -1.0})] b = [_row("z", {"no_seaborn_reward": 0.5}), _row("w", {"no_seaborn_reward": -1.0})] stats = compare_raters(a, b)["rules"]["no_seaborn_reward"] assert stats["agreement"] == 1.0 assert stats["mean_gap_on_disagreement"] == 0.0
def test_all_failed_rater_is_inconclusive_not_agreement(): """A rater that never ran must not produce a clean bill of health.""" a = [_row("x", {"no_seaborn_reward": 0.5}), _row("y", {"no_seaborn_reward": 0.5})] b = [ _row("x", {}, failed="HTTP 429 usage limit"), _row("y", {}, failed="HTTP 429 usage limit"), ] report = compare_raters(a, b) assert report["n_compared"] == 0 assert "INCONCLUSIVE" in report["verdict"] assert report["rules"] == {} text = format_report(report) assert "FAILED (decision)" in text assert "INCONCLUSIVE" in text
def test_partial_failure_excludes_only_failed_cases(): a = [_row("x", {"no_seaborn_reward": 0.5}), _row("y", {"no_seaborn_reward": 0.5})] b = [_row("x", {"no_seaborn_reward": 0.5}), _row("y", {}, failed="boom")] report = compare_raters(a, b) assert report["n_compared"] == 1 assert report["rules"]["no_seaborn_reward"]["n"] == 1 assert "WARNING" in report["verdict"]
def test_label_accuracy_compares_direction_not_magnitude(): rows = [ _row("a", {"no_seaborn_reward": -1.0}, {"no_seaborn_reward": -1.0}), _row("b", {"no_seaborn_reward": 0.5}, {"no_seaborn_reward": -1.0}), _row("c", {"no_seaborn_reward": 0.5}, {"no_seaborn_reward": 0.25}), ] acc = label_accuracy(rows) # 0.5 vs an expected 0.25 is the same direction, so it counts as correct. assert acc["n_labeled"] == 3 assert acc["n_correct"] == 2 assert [m["case"] for m in acc["misses"]] == ["b"]
def test_label_accuracy_skips_failed_rows(): rows = [ _row("a", {}, {"no_seaborn_reward": 0.5}, failed="boom"), _row("b", {"no_seaborn_reward": 0.5}, {"no_seaborn_reward": 0.5}), ] acc = label_accuracy(rows) assert acc["n_labeled"] == 1 assert acc["n_correct"] == 1
def test_corpus_labels_match_static_rules(): """Regression: the labeled corpus must agree with the static rules.
This is the guard for the detector fixes -- if a rule regresses to rewarding a violation, this test fails and names the case. """ cases = load_corpus("audit_corpus") misses = [] for case in cases: got = compute_grpo_rewards(case["code"]) for rule, expected in (case["expected"] or {}).items(): if (got[rule] > 0) != (expected > 0): misses.append((case["name"], rule, got[rule], expected)) assert misses == [], f"static regressed on: {misses}"
@pytest.mark.parametrize( "code,expected", [ ("import seaborn as sns\nsns.barplot(x=[1],y=[2])\n", -1.0), ("import matplotlib.pyplot as plt\nplt.bar([1],[2])\n", -1.0), ("def my_bar_plot():\n return 1\n", 0.5), ('import pandas as pd\npd.DataFrame().to_csv("o.csv")\n', 0.5), ],)def test_bargraph_detector_catches_attribute_calls(code, expected): """Bars drawn as ``lib.barplot(...)`` used to earn positive credit.""" assert compute_grpo_rewards(code)["no_bargraphs_reward"] == expected
@pytest.mark.parametrize( "code,expected", [ ('import seaborn as sns\nsns.set_style("whitegrid")\n', -1.0), ('import matplotlib.pyplot as plt\nplt.style.use("seaborn-v0_8-whitegrid")\n', -1.0), ("ax.grid(True)\n", -1.0), ('import logging\nlogging.info("x")\n', 0.5), ],)def test_grid_detector_catches_style_grids(code, expected): """Style names enable grids without ever calling grid().""" assert compute_grpo_rewards(code)["no_plot_grids_reward"] == expected123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266"""Example use cases for the reward validity gate and code extraction.
These cover two failure modes found by rescoring real traces from``qwen3.5:0.8b`` and ``lfm3``:
1. Unparseable output used to earn a *positive* reward, because every rule rewards the absence of a violation it cannot find. Garbage therefore outranked real, working code -- the exact opposite of the training signal.2. Truncated generations leaking their opening ```python fence into the extracted code, so a mostly-fine sample failed to parse."""
import astimport json
import pytest
from guac_coder.decision_judge import ( DecisionJudgeConfig, combined_decision_reward, compute_decision_rewards,)from guac_coder.grpo_rewards import ( VALIDITY_FLOOR, combined_grpo_reward, compute_grpo_rewards, is_valid_python,)from guac_coder.trace import extract_code
UNPARSEABLE = { "unterminated_call": "import pandas as pd\n\ndf = pd.DataFrame(", "truncated_def": "def f(\n x = ", "prose": "this is not python at all!!! 12345", "empty": "", "whitespace": " \n\t\n", "stray_fence": "```python\n",}
WORKING_SCRIPT = '''import logging
logger = logging.getLogger(__name__)
def normalize(values, peak): """Scale each value by the peak, guarding the zero case.""" if peak == 0: return [0.0 for _ in values] return [v / peak for v in values]
if __name__ == "__main__": logger.info("%s", normalize([1, 2], 2))'''
@pytest.mark.parametrize("name,code", sorted(UNPARSEABLE.items()))def test_unparseable_code_is_rejected(name, code): """Anything we cannot inspect is not valid Python.""" assert is_valid_python(code) is False, name
@pytest.mark.parametrize( "prose", [ "this is not python", # a legal comparison of three names "data is loaded", # a legal comparison ],)def test_prose_that_parses_is_still_rejected(prose): """Syntax alone is too weak: some model prose parses as an expression.
``"this is not python"`` is a valid comparison of three names, so a bare ``ast.parse`` check would happily accept it and then hand it the rules' "no violation found" bonus. """ ast.parse(prose) # does not raise: it is syntactically valid assert is_valid_python(prose) is False
@pytest.mark.parametrize( "prose", ["load the data", "please print the data", "return the result", "plot the data"],)def test_prose_that_does_not_parse_is_rejected(prose): """Most prose fails to parse outright; these are the other half.""" with pytest.raises(SyntaxError): ast.parse(prose) assert is_valid_python(prose) is False
def test_working_script_is_valid(): """A normal, well-formed script passes the gate.""" assert is_valid_python(WORKING_SCRIPT) is True
@pytest.mark.parametrize("name,code", sorted(UNPARSEABLE.items()))def test_unparseable_code_scores_at_the_floor(name, code): """Every rule reports the floor, not the 'no violation found' bonus.""" rules = compute_grpo_rewards(code) assert set(rules.values()) == {VALIDITY_FLOOR}, name
def test_garbage_never_outranks_working_code(): """The regression that motivated the gate.
Before the gate, ``"this is not python"`` scored +0.077 while a real script scored +0.192: only a 0.115 gap, with garbage on the positive side. """ garbage = combined_grpo_reward("this is not python at all!!! 12345") working = combined_grpo_reward(WORKING_SCRIPT) assert garbage < 0 < working assert working - garbage > 0.5
def test_empty_completion_is_not_rewarded(): """An empty string used to score +0.077 because the AST was empty but valid.""" assert combined_grpo_reward("") < 0 assert combined_grpo_reward("") == VALIDITY_FLOOR
def test_decision_rater_applies_the_same_floor(): """The decision rater shares the gate, so both raters agree on non-code.
``judge_fn`` is never called: the gate rejects the sample first, which also means a garbage completion costs no HTTP round-trip. """ calls = []
def never_called(code, cfg=None): calls.append(code) return {}
rewards = compute_decision_rewards("not python at all", judge_fn=never_called) assert set(rewards.values()) == {VALIDITY_FLOOR} assert calls == []
def test_decision_rater_still_calls_model_for_valid_code(): """The gate must not block legitimate scoring.""" calls = []
def fake_judge(code, cfg=None): calls.append(code) return {name: 0.0 for name in compute_grpo_rewards(WORKING_SCRIPT)}
compute_decision_rewards(WORKING_SCRIPT, judge_fn=fake_judge) assert calls == [WORKING_SCRIPT]
TRUNCATED_RESPONSES = { "unterminated_fence": "```python\nimport logging\nlogger = logging.getLogger()\n", "unterminated_fence_with_prose": "Here you go:\n```python\ndef add(a, b):\n return a + b\n", "closed_fence": "```python\ndef add(a, b):\n return a + b\n```\n",}
@pytest.mark.parametrize("name,text", sorted(TRUNCATED_RESPONSES.items()))def test_extract_code_strips_fences(name, text): """Extracted code must not begin with a markdown fence.""" code, source = extract_code(text) assert not code.lstrip().startswith("```"), (name, source) assert "import logging" in code or "def add" in code
def test_unterminated_fence_is_labelled_and_parses(): """A truncated fence yields parseable code plus a distinct source label.""" code, source = extract_code("```python\ndef add(a, b):\n return a + b\n") assert source == "fence_unterminated" assert not code.lstrip().startswith("```") ast.parse(code)
def test_closed_fence_still_wins_over_whole_text(): """Normal fenced output is unaffected by the unterminated-fence fix.""" code, source = extract_code("```python\ndef add(a, b):\n return a + b\n```") assert source == "fence" assert code == "def add(a, b):\n return a + b"
def test_empty_response_is_reported_as_empty(): """No text yields no code and no reward, not a floor-scored empty string.""" assert extract_code("") == ("", "empty") assert extract_code(" \n\n") == ("", "empty")
def test_thinking_only_response_yields_no_code(): """A response with only prose is not mistaken for code.""" code, source = extract_code("I will now write the program. It will load a CSV.") assert code == "" assert source == "empty"
def test_decision_rater_floors_real_truncated_sample(): """Rescoring a real truncated trace: previously +0.269, now at the floor.
The stored reward came from an early run whose extraction kept the fence. """ truncated = "```python\nimport logging\n\ndef f(\n" code, _ = extract_code(truncated) assert not is_valid_python(code) cfg = DecisionJudgeConfig(model="clef:cloud") assert combined_decision_reward(code, cfg=cfg) == VALIDITY_FLOOR
# ---------------------------------------------------------------------------# Exports must never emit unparseable code as a training target# ---------------------------------------------------------------------------
from guac_coder.trace_export import export_grpo, export_sft # noqa: E402
def _trace(code, reward, task_id=0, model="tiny", source="fence"): return { "trace_id": f"t{task_id}-{abs(hash(code)) % 9999}", "model": model, "task_id": task_id, "sample_index": 0, "task": "normalize values", "code": code, "code_source": source, "total_reward": reward, }
def test_export_sft_skips_unparseable_best_trace(tmp_path): """A truncated sample with a high reward must not become the SFT target.
This mirrors the real corpus: a truncated generation scored +0.346, above the best parseable sample, so ranking alone would have selected it. """ traces = [ _trace("def broken(\n x = ", 0.346, task_id=0), _trace(WORKING_SCRIPT, 0.192, task_id=0), ] out = tmp_path / "sft.jsonl" written = export_sft(traces, str(out)) assert written == 1 record = json.loads(out.read_text().strip()) assert "def broken(" not in record["messages"][-1]["content"] assert "normalize" in record["messages"][-1]["content"]
def test_export_sft_skips_task_with_only_unparseable_traces(tmp_path): """If every sample for a task is garbage, the task is dropped entirely.""" traces = [ _trace("def broken(\n x = ", 0.4, task_id=0), _trace("this is not python", 0.3, task_id=0), ] out = tmp_path / "sft.jsonl" assert export_sft(traces, str(out)) == 0 assert out.read_text() == ""
def test_export_grpo_omits_unparseable_traces(tmp_path): """GRPO records are the reward-modelling view; garbage must not appear.""" traces = [ _trace(WORKING_SCRIPT, 0.192, task_id=0), _trace("import pandas as pd\ndf = pd.DataFrame(", -1.0, task_id=1), ] out = tmp_path / "grpo.jsonl" written = export_grpo(traces, str(out)) assert written == 1 rows = [json.loads(line) for line in out.read_text().splitlines() if line.strip()] assert len(rows) == 1 assert all(is_valid_python(r["completion"]) for r in rows)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173"""Tests for guac_coder rewards module."""
from guac_coder.config import RewardConfigfrom guac_coder.rewards import ( _has_checkpointing, _has_chroptiks_import, _has_class_defs, _has_dataframe_to_csv, _has_function_defs, _has_logging, _has_narrative_comments, _has_try_except, _is_bare_script, compute_static_rewards, total_static_reward,)
class TestStyleChecks: """Unit tests for static analysis helpers."""
def test_has_function_defs_true(self): code = "def foo():\n pass\n" assert _has_function_defs(code) is True
def test_has_function_defs_false(self): code = "x = 1\n" assert _has_function_defs(code) is False
def test_has_class_defs_true(self): code = "class Foo:\n pass\n" assert _has_class_defs(code) is True
def test_has_class_defs_false(self): code = "def foo():\n pass\n" assert _has_class_defs(code) is False
def test_has_try_except_true(self): code = "try:\n x = 1\nexcept:\n pass\n" assert _has_try_except(code) is True
def test_has_try_except_false(self): code = "x = 1\n" assert _has_try_except(code) is False
def test_has_logging_true(self): code = "import logging\nlogging.info('hello')\n" assert _has_logging(code) is True
def test_has_logging_false(self): code = "x = 1\n" assert _has_logging(code) is False
def test_has_checkpointing_true(self): code = "torch.save(model.state_dict(), 'ckpt.pt')\n" assert _has_checkpointing(code) is True
def test_has_checkpointing_false(self): code = "x = 1\n" assert _has_checkpointing(code) is False
def test_has_dataframe_to_csv_true(self): code = "df.to_csv('out.csv')\n" assert _has_dataframe_to_csv(code) is True
def test_has_dataframe_to_csv_false(self): code = "with open('f') as fh:\n fh.write('x')\n" assert _has_dataframe_to_csv(code) is False
def test_has_chroptiks_true(self): code = "import chroptiks\n" assert _has_chroptiks_import(code) is True
def test_has_chroptiks_false(self): code = "import matplotlib\n" assert _has_chroptiks_import(code) is False
def test_has_narrative_comments_true(self): code = "# here we load the data\n# next we process it\nx = 1\n" assert _has_narrative_comments(code) is True
def test_has_narrative_comments_false(self): code = "# Load config\n# Process data\nx = 1\n" assert _has_narrative_comments(code) is False
def test_is_bare_script_true(self): code = "x = 1\ny = 2\n" assert _is_bare_script(code) is True
def test_is_bare_script_false_with_function(self): code = "def main():\n pass\n" assert _is_bare_script(code) is False
def test_is_bare_script_false_with_main_guard(self): code = "if __name__ == '__main__':\n pass\n" assert _is_bare_script(code) is False
class TestRewardComputation: """Tests for compute_static_rewards and total_static_reward."""
def test_good_code_gets_positive_reward(self): code = '''import loggingimport chroptiksimport pandas as pd
def process(data_path: str) -> None: logging.info("Loading %s", data_path) df = pd.read_csv(data_path) df.to_csv("out.csv")
def checkpoint(state, path: str) -> None: pd.to_pickle(state, path)
if __name__ == "__main__": process("data.csv")''' cfg = RewardConfig() rewards = compute_static_rewards(code, cfg) total = sum(rewards.values()) # Should have positive rewards for logging, chroptiks, df.to_csv, checkpoint, func def assert "logging_reward" in rewards assert "chroptiks_reward" in rewards assert "dataframe_csv_reward" in rewards assert "checkpoint_reward" in rewards assert "function_def_reward" in rewards assert total > 0
def test_bad_code_gets_negative_reward(self): code = '''import seaborn as snsimport csv
# here we load the data# next we process ittry: with open('data.csv', 'w') as fh: writer = csv.DictWriter(fh, fieldnames=['a']) writer.writeheader() for i in range(100): writer.writerow({'a': i})except: pass
class DataProcessor: pass
print("done")sns.barplot(x=[1,2], y=[3,4])plt.grid(True)plt.title("My Plot")''' cfg = RewardConfig() rewards = compute_static_rewards(code, cfg) total = sum(rewards.values()) # Should be heavily negative assert "seaborn_penalty" in rewards assert "grid_penalty" in rewards assert "title_penalty" in rewards assert "bargraph_penalty" in rewards assert "narrative_comment_penalty" in rewards assert "tryexcept_penalty" in rewards assert "class_penalty" in rewards assert "print_penalty" in rewards assert "bare_script_penalty" in rewards assert total < 0
def test_total_static_reward_scalar(self): code = "x = 1\n" cfg = RewardConfig() total = total_static_reward(code, cfg) assert isinstance(total, float)123{"prompt": "You are guac-coder, an expert research scientist and Python programmer.\nWrite clean, objective, resumable Python code for the task below.\n\nRules:\n- Use chroptiks for all plots. No seaborn, no matplotlib bar graphs.\n- No plot grids, no plot titles.\n- Use pandas DataFrames and .to_csv for data output. No csv.DictWriter.\n- Use logging, not print.\n- Write functions and __main__ guards. No bare scripts.\n- Add checkpoint/resume logic where appropriate.\n- No unnecessary narrative comments. Comments must be objective and concise.\n- Avoid try/except unless absolutely necessary.\n- Avoid classes unless the abstraction is genuinely needed.\n- Write data incrementally, not in a single batch dump.\n\nTask: Implement a data loader that reads a CSV of galaxy properties, filters by redshift, and writes the filtered subset to disk with intermittent checkpointing.\n\nProvide the full Python implementation.\n", "task": "Implement a data loader that reads a CSV of galaxy properties, filters by redshift, and writes the filtered subset to disk with intermittent checkpointing.", "completion": "```python\nimport logging\nimport os\nfrom pathlib import Path\nimport numpy as np\nimport pandas as pd\nfrom datetime import timedelta\n\n# Configure logging to redirect to a file for inspection (as per best practices)\nlogging.basicConfig(level=logging.INFO, format=\"%(asctime)s - %(levelname)s - %(message)s\")\nlogger = logging.getLogger(__name__)\n\ndef check_save_directory() -> bool:\n \"\"\"Check if the save directory exists and is writable.\"\"\"\n save_dir = Path(os.environ.get(\"SAVE_DIR\", \"output\"))\n return save_dir.exists() and os.access(save_dir, os.W_OK)\n\ndef checkpoint_data(df: pd.DataFrame, progress: float, chunk_size: int, max_chunks: int) -> tuple:\n \"\"\"\n Perform random sampling of rows to avoid OOM on large datasets.\n \n Args:\n df: The DataFrame to process (assumed already sorted by 'redshift' if available).\n progress: Current percentage completed for this chunk.\n chunk_size: Number of rows sampled per iteration.\n max_chunks: Maximum number of chunks to sample before stopping.\n \n Returns:\n Tuple containing the sampled dataframe, total rows processed, and current chunk index.\n \"\"\"\n if not check_save_directory():\n logger.error(\"Save directory not found or not writable.\")\n return None, 0, 0\n \n # Calculate how many chunks to sample based on progress\n n_rows = len(df)\n num_samples = min(n_rows * chunk_size / 100.0, max_chunks)\n \n if num_samples <= 1:\n return df.copy(), 0, 0\n\n # Perform random sampling\n indices = np.random.choice(range(len(df)), size=num_samples, replace=False)\n sampled_indices =", "reward": 0.34615384615384615, "rules": {"chroptiks_preference_reward": 0.0, "no_seaborn_reward": 0.5, "no_plot_grids_reward": 0.5, "no_plot_titles_reward": 0.5, "no_bargraphs_reward": 0.5, "pandas_csv_preference_reward": 0.0, "objective_comments_reward": 0.5, "no_try_except_reward": 0.5, "no_classes_reward": 0.5, "logging_over_print_reward": 1.0, "intermittent_writes_reward": 0.0, "resumable_checkpoint_reward": 1.0, "not_bare_script_reward": -1.0}, "meta": {"source_model": "qwen3.5:0.8b", "task_id": 0, "sample_index": 0, "code_source": "whole_text"}}{"prompt": "You are guac-coder, an expert research scientist and Python programmer.\nWrite clean, objective, resumable Python code for the task below.\n\nRules:\n- Use chroptiks for all plots. No seaborn, no matplotlib bar graphs.\n- No plot grids, no plot titles.\n- Use pandas DataFrames and .to_csv for data output. No csv.DictWriter.\n- Use logging, not print.\n- Write functions and __main__ guards. No bare scripts.\n- Add checkpoint/resume logic where appropriate.\n- No unnecessary narrative comments. Comments must be objective and concise.\n- Avoid try/except unless absolutely necessary.\n- Avoid classes unless the abstraction is genuinely needed.\n- Write data incrementally, not in a single batch dump.\n\nTask: Implement a function that computes the pairwise cosine similarity between rows of a sparse matrix and saves results incrementally to a feather file.\n\nProvide the full Python implementation.\n", "task": "Implement a function that computes the pairwise cosine similarity between rows of a sparse matrix and saves results incrementally to a feather file.", "completion": "```python\nimport logging\nfrom pathlib import Path\nfrom chroptiks import plot, scatter, line\n\n\ndef compute_cosine_similarities(data: dict[str, list[float]]) -> list[tuple[list[float], list[float]]]:\n \"\"\"Compute pairwise cosine similarities between rows of the input data.\n \n Args:\n data: Dictionary mapping row names to lists of values for each column.\n \n Returns:\n List of tuples containing (row1_row2, similarity_score) for all unique pairs\n of rows in the input data.\n \"\"\"\n rows = list(data.keys())\n n_rows = len(rows)\n \n if n_rows < 3:\n return []\n \n # Ensure column names are consistent and sorted (optional optimization)\n if set(data.keys())[0] != set(data.values())[0]:\n for name in sorted(set(data)):\n data[name] = [v for v in data[name]]\n \n all_values = list(data.items())\n n_cols = len(all_values[0])\n values_dict = {name: values_dict[i][i] if i < len(values_dict) else []\n for name, values_dict in all_values}\n \n similarities = []\n unique_rows = set()\n \n for i in range(n_rows):\n row1 = list(all_values[i])\n for j in range(i + 1, n_rows):\n row2 = list(all_values[j])\n # Normalize values to 0-1 range before cosine similarity calculation\n def normalize(val_list):\n min_val = min(val for v in val_list)\n max_val = max(val for v in val_list)\n if max_val == 0:\n return [v / max_val for v in", "reward": 0.2692307692307692, "rules": {"chroptiks_preference_reward": 1.0, "no_seaborn_reward": 0.5, "no_plot_grids_reward": 0.5, "no_plot_titles_reward": 0.5, "no_bargraphs_reward": 0.5, "pandas_csv_preference_reward": 0.0, "objective_comments_reward": 0.5, "no_try_except_reward": 0.5, "no_classes_reward": 0.5, "logging_over_print_reward": 1.0, "intermittent_writes_reward": 0.0, "resumable_checkpoint_reward": -1.0, "not_bare_script_reward": -1.0}, "meta": {"source_model": "qwen3.5:0.8b", "task_id": 1, "sample_index": 0, "code_source": "whole_text"}}{"prompt": "You are guac-coder, an expert research scientist and Python programmer.\nWrite clean, objective, resumable Python code for the task below.\n\nRules:\n- Use chroptiks for all plots. No seaborn, no matplotlib bar graphs.\n- No plot grids, no plot titles.\n- Use pandas DataFrames and .to_csv for data output. No csv.DictWriter.\n- Use logging, not print.\n- Write functions and __main__ guards. No bare scripts.\n- Add checkpoint/resume logic where appropriate.\n- No unnecessary narrative comments. Comments must be objective and concise.\n- Avoid try/except unless absolutely necessary.\n- Avoid classes unless the abstraction is genuinely needed.\n- Write data incrementally, not in a single batch dump.\n\nTask: Implement a function that computes the pairwise cosine similarity between rows of a sparse matrix and saves results incrementally to a feather file.\n\nProvide the full Python implementation.\n", "task": "Implement a function that computes the pairwise cosine similarity between rows of a sparse matrix and saves results incrementally to a feather file.", "completion": "```python\nimport numpy as np\nimport pandas as pd\nfrom typing import Optional\nimport scipy.sparse as sp\nfrom pathlib import Path\nimport logging\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\ndef load_sparse_matrix(file_path: str) -> np.ndarray:\n \"\"\"Load dense representation from sparse matrix (scipy.sparse format).\"\"\"\n if not sp.issparse(np.load(file_path)):\n raise ValueError(\"Input must be a sparse matrix.\")\n # Assume the first N columns correspond to row vectors; read values into a NumPy array.\n return np.asarray(sp.csr_matrix(file_path).toarray())\n\ndef compute_pairwise_cosine_similarity(\n data: np.ndarray,\n threshold: float = 0.0,\n output_path: str = \"cosine_similarities.feather\"\n) -> None:\n \"\"\"\n Compute pairwise cosine similarity between rows of `data`.\n\n Parameters\n ----------\n data : np.ndarray shape (n_samples, n_features)\n Input feature matrix.\n threshold : float, optional\n Rows with similarity < threshold have zero entries set to zero before computation.\n output_path : str, optional\n Feather file to write incremental similarity matrices (one per row).\n \"\"\"\n logger.info(f\"Computing cosine similarities for {data.shape[0]} x {data.shape[1]} matrix.\")\n \n # Ensure non-negative threshold handling\n sim_matrix = np.empty((data.shape[0], data.shape[1]), dtype=np.float64)\n \n for i in range(data.shape[0]):\n row_norm = np.linalg.norm(data[i])\n if row_norm > 0:\n row_data = data[i] / row_norm\n else:\n row_data = np.zeros_like(data[i])", "reward": 0.19230769230769232, "rules": {"chroptiks_preference_reward": 0.0, "no_seaborn_reward": 0.5, "no_plot_grids_reward": 0.5, "no_plot_titles_reward": 0.5, "no_bargraphs_reward": 0.5, "pandas_csv_preference_reward": 0.0, "objective_comments_reward": 0.5, "no_try_except_reward": 0.5, "no_classes_reward": 0.5, "logging_over_print_reward": 1.0, "intermittent_writes_reward": 0.0, "resumable_checkpoint_reward": -1.0, "not_bare_script_reward": -1.0}, "meta": {"source_model": "lfm3:latest", "task_id": 1, "sample_index": 0, "code_source": "whole_text"}}1234567891011121314151617{ "traces_path": "traces/traces_qwen3.5-0.8b_lfm3-latest.jsonl", "n_traces": 4, "n_scored": 3, "sft": { "path": "traces/datasets/sft_pairs.jsonl", "n": 3 }, "preference": { "path": "traces/datasets/preference_pairs.jsonl", "n": 0 }, "grpo": { "path": "traces/datasets/grpo_records.jsonl", "n": 3 }}.gitignoreAdded+33
.knowledge.yamlAdded+82
.pytest_cache/.gitignoreAdded+2
.pytest_cache/CACHEDIR.TAGAdded+4
.pytest_cache/README.mdAdded+8
.pytest_cache/v/cache/lastfailedAdded+4
.pytest_cache/v/cache/nodeidsAdded+114
.pytest_cache/v/cache/stepwiseAdded+1
.ruff_cache/.gitignoreAdded+2
.ruff_cache/0.11.1/14703387306720712603Added
.ruff_cache/0.11.1/17431183108856248313Added
.ruff_cache/0.11.1/2000423069392656154Added
.ruff_cache/0.11.1/6002917476793586250Added
.ruff_cache/CACHEDIR.TAGAdded+1
README.md+293-3
audit_corpus/clean_full.pyAdded+36
audit_corpus/clean_minimal.pyAdded+11
audit_corpus/labels.jsonAdded+33
audit_corpus/viol_bare_script.pyAdded+5
audit_corpus/viol_bargraph_seaborn_api.pyAdded+14
audit_corpus/viol_classes.pyAdded+15
audit_corpus/viol_dictwriter.pyAdded+16
audit_corpus/viol_grids_titles.pyAdded+12
audit_corpus/viol_narrative.pyAdded+14
audit_corpus/viol_prints.pyAdded+12
audit_corpus/viol_seaborn.pyAdded+10
audit_corpus/viol_try_except.pyAdded+15
guac_coder/__init__.pyAdded+99
guac_coder/cli.pyAdded+612
guac_coder/config.pyAdded+110
guac_coder/data.pyAdded+151
guac_coder/decision_judge.pyAdded+466
guac_coder/grpo_evaluator.pyAdded+204
guac_coder/grpo_pipeline.pyAdded+290
guac_coder/grpo_rewards.pyAdded+403
guac_coder/rater_audit.pyAdded+438
guac_coder/rewards.pyAdded+346
guac_coder/trace.pyAdded+471
guac_coder/trace_export.pyAdded+212
guac_coder/training.pyAdded+517
pyproject.tomlAdded+60
setup.pyAdded+10
tests/test_decision_judge.pyAdded+233
tests/test_grpo_evaluator.pyAdded+108
tests/test_grpo_pipeline.pyAdded+134
tests/test_rater_audit.pyAdded+152
tests/test_reward_validity.pyAdded+266
tests/test_rewards.pyAdded+173
traces/datasets/grpo_records.jsonlAdded+3
traces/datasets/manifest.jsonAdded+17