"""12-rule code reward function for GRPO training. Evaluates Python code against guac-coder style preferences using both regex-based static analysis and LLM-as-judge structured evaluation. """ import ast import json import logging import re from 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", # Bare usage without a visible import (pasted snippets, aliased imports). r"\b(?:sns|seaborn)\s*\.", ] _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. Seaborn is disqualifying: the total collapses to :data:`guac_coder.grpo_rewards.SEABORN_FLOOR` regardless of anything else in the snippet, matching the 13-rule path so the two agree. """ from guac_coder.grpo_rewards import SEABORN_FLOOR, uses_seaborn if uses_seaborn(code): return SEABORN_FLOOR 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 1 2. grid_use: 0 if plot grids present, else 1 3. title_use: 0 if plot titles present, else 1 4. bargraph_use: 0 if bar graphs or similar simple plots used, else 1 5. dataframe_csv: 1 if pd.DataFrame.to_csv used, 0 if csv.DictWriter used, 0.5 otherwise 6. narrative_comments: 0 if narrative/story comments exist, else 1 7. tryexcept: 0 if try/except used, else 1 8. classes: 0 if classes defined, else 1 9. logging: 1 if logging module used properly, 0 if print used, 0.5 otherwise 10. intermittent_writes: 1 if writes are intermittent/resumable, 0 if batch dumped 11. resumable: 1 if checkpoint/resume pattern present, else 0 12. structured: 1 if code has functions or __main__ guard, 0 if bare script 13. 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. Seaborn short-circuits the whole blend to :data:`guac_coder.grpo_rewards.SEABORN_FLOOR`. A weighted average would let a generous LLM judge offset the penalty, which defeats the point of a hard gate; the LLM judge is not even called. """ from guac_coder.grpo_rewards import SEABORN_FLOOR, uses_seaborn if uses_seaborn(code): return { "total": SEABORN_FLOOR, "static": SEABORN_FLOOR, "llm": 0.0, "static_components": {}, "llm_components": {}, } 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, }