File size: 7,681 Bytes
d66cd5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# /// script
# dependencies = ["transformers>=4.46.0", "torch", "peft", "bitsandbytes", "accelerate", "datasets", "tqdm", "protobuf", "sentencepiece", "mistral-common>=1.5.0", "huggingface_hub"]
# ///

"""
Prompt Comparison Test: Direct vs Reasoning
Tests if "code only" prompt improves fine-tuned model scores on HumanEval subset
"""

import os
import re
import json
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
from peft import PeftModel
from datasets import load_dataset
from tqdm import tqdm
from huggingface_hub import HfApi

print("=" * 60)
print("PROMPT COMPARISON TEST")
print("Direct Code vs Reasoning Prompt")
print("=" * 60)

# Configuration
BASE_MODEL = "mistralai/Devstral-Small-2505"
FINETUNED_ADAPTER = "stmasson/alizee-coder-devstral-1-small"
OUTPUT_REPO = "stmasson/alizee-coder-devstral-1-small"
TEMPERATURE = 0.1
MAX_NEW_TOKENS = 512
NUM_SAMPLES = 50  # Subset for quick test

# GPU
print(f"\nGPU available: {torch.cuda.is_available()}")
if torch.cuda.is_available():
    print(f"GPU: {torch.cuda.get_device_name(0)}")
    print(f"Memory: {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB")

# 4-bit config
bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.bfloat16,
    bnb_4bit_use_double_quant=True,
)

def load_dataset_subset():
    print("\nLoading HumanEval...")
    ds = load_dataset("openai/openai_humaneval", split="test")
    ds = ds.select(range(min(NUM_SAMPLES, len(ds))))
    print(f"Using {len(ds)} problems")
    return ds

def load_model():
    print(f"\nLoading {BASE_MODEL} + {FINETUNED_ADAPTER}...")

    tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL, trust_remote_code=True)
    if tokenizer.pad_token is None:
        tokenizer.pad_token = tokenizer.eos_token

    model = AutoModelForCausalLM.from_pretrained(
        BASE_MODEL,
        quantization_config=bnb_config,
        device_map="auto",
        trust_remote_code=True,
        torch_dtype=torch.bfloat16,
    )

    model = PeftModel.from_pretrained(model, FINETUNED_ADAPTER)
    model = model.merge_and_unload()
    model.eval()
    print("Model loaded and merged")
    return model, tokenizer

def extract_code(text):
    """Extract Python code from output"""
    # Try ```python blocks
    m = re.findall(r'```python\s*(.*?)\s*```', text, re.DOTALL)
    if m:
        return m[-1].strip()
    # Try ``` blocks
    m = re.findall(r'```\s*(.*?)\s*```', text, re.DOTALL)
    if m:
        return m[-1].strip()
    return text.strip()

def extract_body(code):
    """Extract function body if full function returned"""
    if code.strip().startswith("def "):
        lines = code.split('\n')
        body = []
        in_func = False
        for line in lines:
            if line.strip().startswith("def "):
                in_func = True
                continue
            if in_func:
                body.append(line)
        if body:
            return '\n'.join(body)
    return code

def generate_direct(model, tokenizer, prompt):
    """Direct code prompt - no reasoning"""
    p = f"<s>[INST] Complete this Python function. Output ONLY the code, no explanations:\n\n{prompt}[/INST]"

    inputs = tokenizer(p, return_tensors="pt", truncation=True, max_length=2048).to(model.device)
    with torch.no_grad():
        out = model.generate(
            **inputs,
            max_new_tokens=MAX_NEW_TOKENS,
            temperature=TEMPERATURE,
            do_sample=TEMPERATURE > 0,
            pad_token_id=tokenizer.pad_token_id,
        )

    raw = tokenizer.decode(out[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True)
    code = extract_code(raw)
    code = extract_body(code)

    # Stop at boundaries
    for stop in ["\ndef ", "\nclass ", "\nif __name__"]:
        if stop in code:
            code = code[:code.index(stop)]

    return code

def generate_reasoning(model, tokenizer, prompt):
    """Reasoning prompt - original approach"""
    p = f"<s>[INST] Solve this programming problem with detailed reasoning:\n\n{prompt}[/INST]"

    inputs = tokenizer(p, return_tensors="pt", truncation=True, max_length=2048).to(model.device)
    with torch.no_grad():
        out = model.generate(
            **inputs,
            max_new_tokens=MAX_NEW_TOKENS * 2,
            temperature=TEMPERATURE,
            do_sample=TEMPERATURE > 0,
            pad_token_id=tokenizer.pad_token_id,
        )

    raw = tokenizer.decode(out[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True)
    code = extract_code(raw)
    code = extract_body(code)

    return code

def check_syntax(code):
    try:
        compile(code, '<string>', 'exec')
        return True
    except:
        return False

def evaluate(samples, dataset):
    passed = 0
    total = len(samples)
    ds_dict = {p["task_id"]: p for p in dataset}

    for s in samples:
        task_id = s["task_id"]
        completion = s["completion"]
        problem = ds_dict.get(task_id)
        if not problem:
            continue

        full = problem["prompt"] + completion
        if not check_syntax(full):
            continue

        try:
            g = {}
            exec(full, g)
            entry = problem.get("entry_point", task_id.split("/")[-1])
            if entry in g:
                passed += 1
        except:
            pass

    return {"pass@1": passed / total if total > 0 else 0, "passed": passed, "total": total}

def main():
    dataset = load_dataset_subset()
    model, tokenizer = load_model()

    # Test 1: Direct prompt
    print("\n" + "=" * 60)
    print("TEST 1: DIRECT CODE PROMPT")
    print("=" * 60)
    direct = []
    for p in tqdm(dataset, desc="Direct"):
        try:
            c = generate_direct(model, tokenizer, p["prompt"])
        except:
            c = "# error"
        direct.append({"task_id": p["task_id"], "completion": c})

    r_direct = evaluate(direct, dataset)
    print(f"Direct: {r_direct['pass@1']*100:.1f}% ({r_direct['passed']}/{r_direct['total']})")

    # Test 2: Reasoning prompt
    print("\n" + "=" * 60)
    print("TEST 2: REASONING PROMPT")
    print("=" * 60)
    reasoning = []
    for p in tqdm(dataset, desc="Reasoning"):
        try:
            c = generate_reasoning(model, tokenizer, p["prompt"])
        except:
            c = "# error"
        reasoning.append({"task_id": p["task_id"], "completion": c})

    r_reason = evaluate(reasoning, dataset)
    print(f"Reasoning: {r_reason['pass@1']*100:.1f}% ({r_reason['passed']}/{r_reason['total']})")

    # Summary
    print("\n" + "=" * 60)
    print("RESULTS SUMMARY")
    print("=" * 60)
    print(f"\n{'Prompt':<20} {'pass@1':>10}")
    print("-" * 35)
    print(f"{'Direct Code':<20} {r_direct['pass@1']*100:>9.1f}%")
    print(f"{'Reasoning':<20} {r_reason['pass@1']*100:>9.1f}%")

    diff = (r_direct['pass@1'] - r_reason['pass@1']) * 100
    print(f"\n{'Improvement:':<20} {'+' if diff >= 0 else ''}{diff:.1f}%")

    # Save
    results = {
        "experiment": "Prompt Comparison",
        "samples": NUM_SAMPLES,
        "direct": r_direct,
        "reasoning": r_reason,
        "improvement": diff
    }

    with open("prompt_comparison.json", "w") as f:
        json.dump(results, f, indent=2)

    try:
        api = HfApi()
        api.upload_file(
            path_or_fileobj="prompt_comparison.json",
            path_in_repo="prompt_comparison.json",
            repo_id=OUTPUT_REPO,
            repo_type="model",
        )
        print(f"\nUploaded to {OUTPUT_REPO}")
    except Exception as e:
        print(f"Upload failed: {e}")

    print("\nDONE")

if __name__ == "__main__":
    main()