File size: 2,718 Bytes
ed6b901
 
 
 
 
 
 
 
 
 
 
15eb8ca
ed6b901
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
from datasets import load_dataset
from tqdm import tqdm
import json
import csv
import os
import evaluate

# ==== CONFIG ====
MODEL_PATH = "../train/output/qlora-codellama-bugfix"
EVAL_FILE = "test_samples.jsonl"
OUTPUT_JSON = "./output/eval_results.json"
OUTPUT_CSV = "./output/eval_results.csv"
MAX_INPUT_LEN = 1024
MAX_NEW_TOKENS = 256
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"

# ==== Ensure output folder exists ====
os.makedirs(os.path.dirname(OUTPUT_JSON), exist_ok=True)

# ==== Load model ====
print("πŸ”„ Loading model...")
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
model = AutoModelForCausalLM.from_pretrained(
    MODEL_PATH,
    torch_dtype=torch.bfloat16,
    device_map="auto"
)
model.eval()

# ==== Load eval data ====
print("πŸ“‚ Loading evaluation data...")
eval_data = load_dataset("json", data_files=EVAL_FILE, split="train")

# ==== Inference ====
results = []
print("βš™οΈ Running inference...")
for example in tqdm(eval_data):
    prompt = example["prompt"]
    reference = example["completion"]

    inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=MAX_INPUT_LEN).to(DEVICE)

    with torch.no_grad():
        outputs = model.generate(
            **inputs,
            max_new_tokens=MAX_NEW_TOKENS,
            do_sample=False,
            num_beams=4,
            pad_token_id=tokenizer.pad_token_id,
            eos_token_id=tokenizer.eos_token_id
        )

    prediction = tokenizer.decode(outputs[0], skip_special_tokens=True)

    results.append({
        "prompt": prompt,
        "reference": reference.strip(),
        "prediction": prediction.strip()
    })

# ==== Save results ====
with open(OUTPUT_JSON, "w", encoding="utf-8") as f:
    json.dump(results, f, indent=2)
print(f"βœ… Saved JSON to {OUTPUT_JSON}")

with open(OUTPUT_CSV, "w", encoding="utf-8", newline='') as f:
    writer = csv.DictWriter(f, fieldnames=["prompt", "reference", "prediction"])
    writer.writeheader()
    writer.writerows(results)
print(f"βœ… Saved CSV to {OUTPUT_CSV}")

# ==== Compute Metrics ====
print("πŸ“Š Computing BLEU and ROUGE...")
bleu = evaluate.load("bleu")
rouge = evaluate.load("rouge")

predictions = [r["prediction"] for r in results]
references = [r["reference"] for r in results]

bleu_score = bleu.compute(predictions=predictions, references=[[ref] for ref in references])
rouge_score = rouge.compute(predictions=predictions, references=references)

print("\nπŸ“ˆ Evaluation Results:")
print("BLEU:", bleu_score)
print("ROUGE:", json.dumps(rouge_score, indent=2))