Exploit Intel commited on
Commit
1c0bef9
·
verified ·
1 Parent(s): b484f66

Add eval script (unsloth loader for gemma4)

Browse files
Files changed (1) hide show
  1. evaluate.py +197 -0
evaluate.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Evaluate a fine-tuned CVE -> CWE model on the held-out test split.
3
+
4
+ Reports exact-match accuracy plus micro/macro multi-label F1, stratified into
5
+ "easy" (the weakness is named in the description) vs "hard" (it must be inferred),
6
+ so you see real-world performance instead of one flattered average.
7
+
8
+ Run it in an environment that has the model's deps (the Unsloth Studio venv is
9
+ easiest, since it already has a torch/transformers new enough for gemma-4-E4B):
10
+
11
+ python evaluate.py --model "C:\\path\\to\\exported\\merged_model"
12
+ python evaluate.py --model eiphuggincve/your-model-repo --limit 500 # quick check
13
+
14
+ Needs: torch, transformers, datasets, accelerate.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import re
21
+
22
+ import torch
23
+ from datasets import load_dataset
24
+
25
+ CWE_RE = re.compile(r"CWE-\d+")
26
+
27
+ # Same keyword list used to measure the dataset: a row is "easy" if the
28
+ # description literally names the weakness, so the model can keyword-match.
29
+ EASY_KW = [
30
+ "sql injection",
31
+ "cross-site scripting",
32
+ "cross site scripting",
33
+ "xss",
34
+ "buffer overflow",
35
+ "use after free",
36
+ "use-after-free",
37
+ "path traversal",
38
+ "command injection",
39
+ "out-of-bounds",
40
+ "out of bounds",
41
+ "race condition",
42
+ "deserialization",
43
+ "ssrf",
44
+ "server-side request forgery",
45
+ "csrf",
46
+ "cross-site request forgery",
47
+ "open redirect",
48
+ "integer overflow",
49
+ ]
50
+
51
+
52
+ def parse_cwes(text: str) -> set[str]:
53
+ return set(CWE_RE.findall(text))
54
+
55
+
56
+ def is_easy(description: str) -> bool:
57
+ d = description.lower()
58
+ return any(k in d for k in EASY_KW)
59
+
60
+
61
+ def prf(tp: int, fp: int, fn: int) -> tuple[float, float, float]:
62
+ p = tp / (tp + fp) if (tp + fp) else 0.0
63
+ r = tp / (tp + fn) if (tp + fn) else 0.0
64
+ f = 2 * p * r / (p + r) if (p + r) else 0.0
65
+ return p, r, f
66
+
67
+
68
+ def build_prompt(tok, messages: list[dict]) -> str:
69
+ """Prompt = everything up to (but not including) the assistant answer."""
70
+ convo = messages[:-1]
71
+ try:
72
+ return tok.apply_chat_template(convo, tokenize=False, add_generation_prompt=True)
73
+ except Exception:
74
+ # Some chat templates (e.g. Gemma) reject a separate "system" role;
75
+ # fold the system text into the user turn instead.
76
+ sys_txt = next((m["content"] for m in convo if m["role"] == "system"), "")
77
+ usr_txt = next((m["content"] for m in convo if m["role"] == "user"), "")
78
+ folded = [{"role": "user", "content": f"{sys_txt}\n\n{usr_txt}".strip()}]
79
+ return tok.apply_chat_template(folded, tokenize=False, add_generation_prompt=True)
80
+
81
+
82
+ def score(truths: list[set[str]], preds: list[set[str]], easies: list[bool]) -> None:
83
+ micro = [0, 0, 0] # tp, fp, fn
84
+ per_label: dict[str, list[int]] = {}
85
+ exact = 0
86
+ strata = {"easy": [0, 0, 0, 0, 0], "hard": [0, 0, 0, 0, 0]} # tp,fp,fn,exact,n
87
+
88
+ for true, pred, easy in zip(truths, preds, easies):
89
+ tp, fp, fn = len(pred & true), len(pred - true), len(true - pred)
90
+ micro[0] += tp
91
+ micro[1] += fp
92
+ micro[2] += fn
93
+ ex = int(pred == true)
94
+ exact += ex
95
+ for lab in true | pred:
96
+ d = per_label.setdefault(lab, [0, 0, 0])
97
+ if lab in true and lab in pred:
98
+ d[0] += 1
99
+ elif lab in pred:
100
+ d[1] += 1
101
+ else:
102
+ d[2] += 1
103
+ s = strata["easy" if easy else "hard"]
104
+ s[0] += tp
105
+ s[1] += fp
106
+ s[2] += fn
107
+ s[3] += ex
108
+ s[4] += 1
109
+
110
+ n = len(truths)
111
+ micro_f1 = prf(*micro)[2]
112
+ macro_f1 = sum(prf(*v)[2] for v in per_label.values()) / len(per_label) if per_label else 0.0
113
+
114
+ print("\n=== CVE -> CWE evaluation ===")
115
+ print(f"examples : {n}")
116
+ print(f"exact-match accuracy : {exact / n:.3f} (predicted CWE set == true set)")
117
+ print(f"micro-F1 : {micro_f1:.3f}")
118
+ print(f"macro-F1 : {macro_f1:.3f} (unweighted mean over {len(per_label)} CWEs)")
119
+ print("\n-- by difficulty --")
120
+ for name, label in (("easy", "easy (weakness named)"), ("hard", "hard (must infer) ")):
121
+ tp, fp, fn, ex, m = strata[name]
122
+ if m:
123
+ print(f" {label:22s} n={m:5d} exact={ex / m:.3f} micro-F1={prf(tp, fp, fn)[2]:.3f}")
124
+
125
+
126
+ def main() -> None:
127
+ ap = argparse.ArgumentParser(description="Evaluate a CVE->CWE model on the test split.")
128
+ ap.add_argument("--model", required=True, help="path or HF id of the fine-tuned (merged) model")
129
+ ap.add_argument("--dataset", default="eiphuggincve/cve-cwe-consensus")
130
+ ap.add_argument("--split", default="test")
131
+ ap.add_argument(
132
+ "--limit", type=int, default=None, help="evaluate only the first N rows (quick check)"
133
+ )
134
+ ap.add_argument("--batch-size", type=int, default=16)
135
+ ap.add_argument("--max-new-tokens", type=int, default=32)
136
+ args = ap.parse_args()
137
+
138
+ print(f"loading model: {args.model}")
139
+ # gemma-4-E4B has model_type 'gemma4', which stock transformers does not recognize
140
+ # (KeyError: 'gemma4') -- only unsloth's patched stack runs it, so load via unsloth.
141
+ try:
142
+ from unsloth import FastModel as Loader
143
+ except ImportError:
144
+ from unsloth import FastLanguageModel as Loader
145
+ model, tok = Loader.from_pretrained(
146
+ model_name=args.model,
147
+ max_seq_length=1024,
148
+ dtype=None,
149
+ load_in_4bit=False, # set True if you hit out-of-memory
150
+ )
151
+ tok = getattr(tok, "tokenizer", tok) # FastModel may return a processor wrapping the tokenizer
152
+ try:
153
+ Loader.for_inference(model) # 2x faster inference; no-op on some versions
154
+ except Exception:
155
+ pass
156
+ model.eval()
157
+ tok.padding_side = "left" # decoder-only batched generation needs left padding
158
+ if tok.pad_token is None:
159
+ tok.pad_token = tok.eos_token
160
+ device = model.device
161
+
162
+ ds = load_dataset(args.dataset, split=args.split)
163
+ if args.limit:
164
+ ds = ds.select(range(min(args.limit, len(ds))))
165
+
166
+ prompts, truths, easies = [], [], []
167
+ for ex in ds:
168
+ msgs = ex["messages"]
169
+ prompts.append(build_prompt(tok, msgs))
170
+ truths.append(parse_cwes(msgs[-1]["content"]))
171
+ usr = next((m["content"] for m in msgs if m["role"] == "user"), "")
172
+ easies.append(is_easy(usr))
173
+
174
+ preds: list[set[str]] = []
175
+ for i in range(0, len(prompts), args.batch_size):
176
+ batch = prompts[i : i + args.batch_size]
177
+ enc = tok(batch, return_tensors="pt", padding=True, truncation=True, max_length=1024).to(
178
+ device
179
+ )
180
+ with torch.no_grad():
181
+ out = model.generate(
182
+ **enc,
183
+ max_new_tokens=args.max_new_tokens,
184
+ do_sample=False, # greedy = deterministic
185
+ pad_token_id=tok.pad_token_id,
186
+ )
187
+ new_tokens = out[:, enc["input_ids"].shape[1] :] # drop the prompt, keep the answer
188
+ for row in new_tokens:
189
+ preds.append(parse_cwes(tok.decode(row, skip_special_tokens=True)))
190
+ print(f" {min(i + args.batch_size, len(prompts))}/{len(prompts)}", end="\r")
191
+ print()
192
+
193
+ score(truths, preds, easies)
194
+
195
+
196
+ if __name__ == "__main__":
197
+ main()