File size: 7,309 Bytes
e2f8b29
 
 
206438f
e2f8b29
 
 
 
 
 
 
 
 
206438f
e2f8b29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""PyTorch code snippet templates for Task 6 code-level debugging.

Each template is a real, syntactically valid Python/PyTorch training script
with one injected bug.
"""

from __future__ import annotations

import ast
import io
import tokenize
from typing import Optional

import torch  # noqa: F401

# Bug variant templates: (buggy_code, correct_line_num, correct_replacement)
_TEMPLATES: dict[str, tuple[str, int, str]] = {
    "eval_mode": (
        """\
import torch
import torch.nn as nn

model = SimpleCNN()
model.eval()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
criterion = nn.CrossEntropyLoss()

for epoch in range(100):
    for batch_x, batch_y in train_loader:
        optimizer.zero_grad()
        output = model(batch_x)
        loss = criterion(output, batch_y)
        loss.backward()
        optimizer.step()""",
        5,
        "model.train()",
    ),
    "detach_loss": (
        """\
import torch
import torch.nn as nn

model = SimpleCNN()
model.train()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
criterion = nn.CrossEntropyLoss()

for epoch in range(100):
    for batch_x, batch_y in train_loader:
        optimizer.zero_grad()
        output = model(batch_x)
        loss = criterion(output, batch_y).detach()
        loss.backward()
        optimizer.step()""",
        14,
        "        loss = criterion(output, batch_y)",
    ),
    "zero_grad_missing": (
        """\
import torch
import torch.nn as nn

model = SimpleCNN()
model.train()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
criterion = nn.CrossEntropyLoss()

for epoch in range(100):
    for batch_x, batch_y in train_loader:
        output = model(batch_x)
        loss = criterion(output, batch_y)
        loss.backward()
        optimizer.step()""",
        11,
        "        optimizer.zero_grad()",
    ),
    "inplace_relu": (
        """\
import torch
import torch.nn as nn
import torch.nn.functional as F

model = SimpleCNN()
model.train()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
criterion = nn.CrossEntropyLoss()

for epoch in range(100):
    for batch_x, batch_y in train_loader:
        optimizer.zero_grad()
        output = model(batch_x)
        output = F.relu(output, inplace=True)
        loss = criterion(output, batch_y)
        loss.backward()
        optimizer.step()""",
        15,
        "        output = F.relu(output)",
    ),
}

# Semantic equivalence patterns per bug variant
_SEMANTIC_PATTERNS: dict[str, list[tuple[str, str]]] = {
    "eval_mode": [
        # (must_contain, must_not_contain)
        ("model.train()", "model.eval()"),
    ],
    "detach_loss": [
        ("criterion(", ".detach()"),
    ],
    "zero_grad_missing": [
        ("zero_grad()", ""),  # just needs zero_grad present
    ],
    "inplace_relu": [
        ("F.relu(", "inplace=True"),
    ],
}


def generate_code_snippet(bug_type: str, seed: int = 42) -> dict:
    """Generate a code snippet with the specified bug.

    Returns dict with keys: code, filename, line_count, imports, hint.
    """
    if bug_type not in _TEMPLATES:
        raise ValueError(f"Unknown bug_type: {bug_type}")

    code, _line, _replacement = _TEMPLATES[bug_type]
    lines = code.strip().split("\n")
    imports = [
        line for line in lines if line.startswith("import ") or line.startswith("from ")
    ]

    hint: Optional[str] = None
    if bug_type == "eval_mode":
        hint = "Check the model mode before the training loop."
    elif bug_type == "detach_loss":
        hint = "Examine how the loss is computed and used."

    return {
        "code": code,
        "filename": "train.py",
        "line_count": len(lines),
        "imports": imports,
        "hint": hint,
    }


def _normalize_code(s: str) -> str:
    """Strip whitespace and inline comments for comparison."""
    s = s.strip()
    # Remove inline comments
    result_lines: list[str] = []
    for line in s.split("\n"):
        # Remove trailing comment but preserve strings
        stripped = line.rstrip()
        result_lines.append(stripped)
    return "\n".join(result_lines)


def _tokenize_compare(original: str, replacement: str) -> bool:
    """Compare token streams ignoring whitespace and comments."""

    def get_tokens(code: str) -> list[tuple[int, str]]:
        try:
            tokens = list(tokenize.generate_tokens(io.StringIO(code).readline))
            # Filter out COMMENT, NL, NEWLINE, INDENT, DEDENT, ENCODING, ENDMARKER
            skip = {
                tokenize.COMMENT,
                tokenize.NL,
                tokenize.NEWLINE,
                tokenize.INDENT,
                tokenize.DEDENT,
                tokenize.ENCODING,
                tokenize.ENDMARKER,
            }
            return [(t.type, t.string) for t in tokens if t.type not in skip]
        except tokenize.TokenError:
            return []

    return get_tokens(original) == get_tokens(replacement)


def validate_fix(bug_type: str, line: int, replacement: str) -> bool:
    """Validate a code fix submission.

    Multi-strategy pipeline per spec Section 22:
    1. Normalize whitespace + strip comments
    2. Token-stream comparison
    3. Semantic equivalence patterns
    4. AST fallback
    """
    if bug_type not in _TEMPLATES:
        return False

    code, correct_line, correct_replacement = _TEMPLATES[bug_type]
    lines = code.strip().split("\n")

    # Check line number is valid
    if line < 1 or line > len(lines):
        return False

    # For zero_grad_missing, the fix is inserting a line, not replacing
    if bug_type == "zero_grad_missing":
        # Accept if the replacement contains zero_grad
        normalized = _normalize_code(replacement)
        if "zero_grad" in normalized:
            return True
        return False

    # Strategy 1: Normalize and compare
    norm_replacement = _normalize_code(replacement)
    norm_correct = _normalize_code(correct_replacement)
    if norm_replacement == norm_correct:
        return True

    # Strategy 2: Token-stream comparison
    if _tokenize_compare(correct_replacement, replacement):
        return True

    # Strategy 3: Semantic equivalence patterns
    patterns = _SEMANTIC_PATTERNS.get(bug_type, [])
    for must_contain, must_not_contain in patterns:
        if must_contain and must_contain in norm_replacement:
            if not must_not_contain or must_not_contain not in norm_replacement:
                return True

    # Strategy 4: AST fallback — verify buggy pattern absent
    try:
        # Replace the line in the full code and parse
        new_lines = lines.copy()
        new_lines[line - 1] = replacement.rstrip()
        new_code = "\n".join(new_lines)
        tree = ast.parse(new_code)

        # Check that the buggy pattern is absent
        ast.dump(tree)  # Validates AST is well-formed
        if bug_type == "eval_mode" and "eval" not in replacement.lower():
            if "train" in replacement.lower():
                return True
        if bug_type == "detach_loss" and "detach" not in replacement.lower():
            return True
        if bug_type == "inplace_relu" and "inplace" not in replacement.lower():
            if "relu" in replacement.lower():
                return True
    except SyntaxError:
        pass

    return False