guac-coder / guac_coder /grpo_evaluator.py
caug37's picture
Upload folder using huggingface_hub
498f80b verified
Raw History Blame Contribute Delete
8.85 kB
"""
GRPO (Group Relative Policy Optimization) evaluator for guac-coder.
Uses npcpy.get_llm_response with format='json' to obtain structured
evaluations from an LLM judge for generated research code.
Punishments and rewards align with the guac-coder research-code style guide:
1. punish seaborn use
2. punish use of grids in plots
3. punish use of titles in plots
4. punish use of bargraphs and other low-info plots
5. prefer pd.DataFrames and .to_csv over csv dict writer
6. punish unnecessary explanatory / narrative comments
7. punish try/except usage
8. punish classes in most cases
9. reward proper logger.logging and punish prints
10. punish batch data writes, prefer intermittent writes
11. punish when code is not resumable from a checkpoint
12. punish bare scripts (no main guard or entrypoint)
"""
import json
import logging
from 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.",
}
}