kernel-opt-rl / code /reward.py
guychuk's picture
Upload folder using huggingface_hub
e58c676 verified
Raw History Blame Contribute Delete
2.38 kB
"""Offline rewards (no GPU needed) for both subsets.
With a GPU, the real reward is measured latency (or run the task through KernelGYM).
These are the cheap proxies for rollouts without hardware.
"""
import difflib
import json
import re
# --------------------------------------------------------------------------- tuned_configs
def parse_answer(completion: str) -> dict | None:
"""Last parseable flat JSON object in the completion."""
for m in reversed(re.findall(r"\{[^{}]*\}", completion)):
try:
return json.loads(m)
except json.JSONDecodeError:
pass
return None
def config_reward(pred: dict | None, best: dict) -> float:
"""Score a predicted launch config against the autotuned best config, in [0, 1].
`best` example: {"BLOCK_SIZE_M": 16, "BLOCK_SIZE_N": 64, "BLOCK_SIZE_K": 128,
"GROUP_SIZE_M": 1, "num_warps": 4, "num_stages": 5}
"""
# TODO(you): define the partial-credit scheme.
raise NotImplementedError
def reward(completion: str, best_config: str) -> float:
return config_reward(parse_answer(completion), json.loads(best_config))
# --------------------------------------------------------------------------- kernel_commits
EDIT_RE = re.compile(r"<<<<<<< SEARCH\n(.*?)\n=======\n(.*?)\n?>>>>>>> REPLACE", re.S)
def apply_edits(code: str, completion: str) -> str | None:
"""Apply SEARCH/REPLACE blocks in order; None if there are none or any SEARCH text isn't in the file."""
edits = EDIT_RE.findall(completion)
if not edits:
return None
for search, replace in edits:
if search not in code:
return None
code = code.replace(search, replace, 1)
return code
def _changed_lines(before: str, after: str) -> str:
diff = difflib.unified_diff(before.splitlines(), after.splitlines(), lineterm="", n=0)
return "\n".join(l for l in diff if l[:1] in "+-" and not l.startswith(("+++", "---")))
def patch_reward(completion: str, before_code: str, after_code: str) -> float:
"""SWE-RL-style: -1 for malformed/inapplicable edits, else similarity of the changed lines to the real commit's."""
pred = apply_edits(before_code, completion)
if pred is None:
return -1.0
return difflib.SequenceMatcher(None, _changed_lines(before_code, pred), _changed_lines(before_code, after_code)).ratio()