File size: 13,329 Bytes
498f80b 359579b 498f80b 359579b 498f80b 359579b 498f80b 359579b 498f80b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 | """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,
}
|