File size: 2,383 Bytes
e58c676
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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()