Datasets:
Sync evaluate.py with repo (reasoning-model + stratified easy/hard fixes)
Browse files- evaluate.py +58 -38
evaluate.py
CHANGED
|
@@ -5,13 +5,16 @@ 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 |
-
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
| 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:
|
| 15 |
"""
|
| 16 |
|
| 17 |
from __future__ import annotations
|
|
@@ -21,11 +24,14 @@ import re
|
|
| 21 |
|
| 22 |
import torch
|
| 23 |
from datasets import load_dataset
|
|
|
|
| 24 |
|
| 25 |
CWE_RE = re.compile(r"CWE-\d+")
|
| 26 |
|
| 27 |
-
#
|
| 28 |
-
#
|
|
|
|
|
|
|
| 29 |
EASY_KW = [
|
| 30 |
"sql injection",
|
| 31 |
"cross-site scripting",
|
|
@@ -50,12 +56,16 @@ EASY_KW = [
|
|
| 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 |
-
|
| 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]:
|
|
@@ -66,17 +76,29 @@ def prf(tp: int, fp: int, fn: int) -> tuple[float, float, float]:
|
|
| 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 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
|
| 82 |
def score(truths: list[set[str]], preds: list[set[str]], easies: list[bool]) -> None:
|
|
@@ -126,38 +148,36 @@ def score(truths: list[set[str]], preds: list[set[str]], easies: list[bool]) ->
|
|
| 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="
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 154 |
-
except
|
| 155 |
-
|
| 156 |
-
|
|
|
|
| 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 =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
|
| 162 |
ds = load_dataset(args.dataset, split=args.split)
|
| 163 |
if args.limit:
|
|
|
|
| 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 |
+
Loads with plain transformers. Newer architectures (e.g. model_type ``gemma4``,
|
| 9 |
+
used by gemma-4-E4B) need **transformers >= 5.5** -- older versions raise
|
| 10 |
+
``KeyError: 'gemma4'``. Note: do NOT load gemma4 through unsloth in a Studio env
|
| 11 |
+
whose transformers was upgraded -- the upgrade pulls ``huggingface_hub`` 1.x,
|
| 12 |
+
which breaks ``unsloth_zoo``'s config lookup. Plain transformers is the clean path.
|
| 13 |
|
| 14 |
+
python evaluate.py --model "C:\\path\\to\\exported\\merged_model" --limit 500
|
| 15 |
python evaluate.py --model "C:\\path\\to\\exported\\merged_model"
|
|
|
|
| 16 |
|
| 17 |
+
Needs: transformers>=5.5, torch, datasets, accelerate.
|
| 18 |
"""
|
| 19 |
|
| 20 |
from __future__ import annotations
|
|
|
|
| 24 |
|
| 25 |
import torch
|
| 26 |
from datasets import load_dataset
|
| 27 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 28 |
|
| 29 |
CWE_RE = re.compile(r"CWE-\d+")
|
| 30 |
|
| 31 |
+
# A row is "easy" if the description literally names the weakness (the model can
|
| 32 |
+
# keyword-match); "hard" rows require inferring the CWE from the prose.
|
| 33 |
+
# NOTE: kept identical to eip_hf.normalize.EASY_KW (the cap uses it to retain hard
|
| 34 |
+
# rows). If you change one, change the other -- tests/test_export.py guards this.
|
| 35 |
EASY_KW = [
|
| 36 |
"sql injection",
|
| 37 |
"cross-site scripting",
|
|
|
|
| 56 |
|
| 57 |
|
| 58 |
def parse_cwes(text: str) -> set[str]:
|
| 59 |
+
# If a reasoning block leaked through (model ignored enable_thinking=False),
|
| 60 |
+
# keep only the text after the final </think> so CWEs mused about mid-thought
|
| 61 |
+
# don't count as predictions.
|
| 62 |
+
if "</think>" in text:
|
| 63 |
+
text = text.rsplit("</think>", 1)[1]
|
| 64 |
return set(CWE_RE.findall(text))
|
| 65 |
|
| 66 |
|
| 67 |
def is_easy(description: str) -> bool:
|
| 68 |
+
return any(k in description.lower() for k in EASY_KW)
|
|
|
|
| 69 |
|
| 70 |
|
| 71 |
def prf(tp: int, fp: int, fn: int) -> tuple[float, float, float]:
|
|
|
|
| 76 |
|
| 77 |
|
| 78 |
def build_prompt(tok, messages: list[dict]) -> str:
|
| 79 |
+
"""Prompt = everything up to (but not including) the assistant answer.
|
| 80 |
+
|
| 81 |
+
For reasoning models (Qwen3.x, etc.) we pass ``enable_thinking=False``: this
|
| 82 |
+
is a single-label classification task, so the chain-of-thought only burns the
|
| 83 |
+
generation budget before the answer and pollutes parsing with CWEs mentioned
|
| 84 |
+
mid-reasoning. Templates that don't accept the kwarg ignore it via the retry.
|
| 85 |
+
"""
|
| 86 |
convo = messages[:-1]
|
| 87 |
+
for kwargs in ({"enable_thinking": False}, {}):
|
| 88 |
+
try:
|
| 89 |
+
return tok.apply_chat_template(
|
| 90 |
+
convo, tokenize=False, add_generation_prompt=True, **kwargs
|
| 91 |
+
)
|
| 92 |
+
except TypeError:
|
| 93 |
+
continue # template rejects enable_thinking -> retry without it
|
| 94 |
+
except Exception:
|
| 95 |
+
break # some other template issue (e.g. no system role) -> fold below
|
| 96 |
+
# Some chat templates (e.g. Gemma) reject a separate "system" role;
|
| 97 |
+
# fold the system text into the user turn instead.
|
| 98 |
+
sys_txt = next((m["content"] for m in convo if m["role"] == "system"), "")
|
| 99 |
+
usr_txt = next((m["content"] for m in convo if m["role"] == "user"), "")
|
| 100 |
+
folded = [{"role": "user", "content": f"{sys_txt}\n\n{usr_txt}".strip()}]
|
| 101 |
+
return tok.apply_chat_template(folded, tokenize=False, add_generation_prompt=True)
|
| 102 |
|
| 103 |
|
| 104 |
def score(truths: list[set[str]], preds: list[set[str]], easies: list[bool]) -> None:
|
|
|
|
| 148 |
def main() -> None:
|
| 149 |
ap = argparse.ArgumentParser(description="Evaluate a CVE->CWE model on the test split.")
|
| 150 |
ap.add_argument("--model", required=True, help="path or HF id of the fine-tuned (merged) model")
|
| 151 |
+
ap.add_argument("--dataset", default="exploitintel/cve-cwe-consensus")
|
| 152 |
ap.add_argument("--split", default="test")
|
| 153 |
ap.add_argument(
|
| 154 |
"--limit", type=int, default=None, help="evaluate only the first N rows (quick check)"
|
| 155 |
)
|
| 156 |
ap.add_argument("--batch-size", type=int, default=16)
|
| 157 |
+
# 256, not 32: reasoning models (Qwen3.x) may emit <think>...</think> even with
|
| 158 |
+
# enable_thinking=False if they were fine-tuned to reason. Greedy generation stops
|
| 159 |
+
# at EOS as soon as a bare answer finishes, so this only costs time on rows that
|
| 160 |
+
# actually think; the </think> strip in parse_cwes then recovers the answer.
|
| 161 |
+
ap.add_argument("--max-new-tokens", type=int, default=256)
|
| 162 |
args = ap.parse_args()
|
| 163 |
|
| 164 |
print(f"loading model: {args.model}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
try:
|
| 166 |
+
tok = AutoTokenizer.from_pretrained(args.model)
|
| 167 |
+
except (AttributeError, TypeError):
|
| 168 |
+
# Some Gemma tokenizer configs store `extra_special_tokens` as a list, which
|
| 169 |
+
# trips a transformers bug ('list' object has no attribute 'keys').
|
| 170 |
+
tok = AutoTokenizer.from_pretrained(args.model, extra_special_tokens={})
|
| 171 |
tok.padding_side = "left" # decoder-only batched generation needs left padding
|
| 172 |
if tok.pad_token is None:
|
| 173 |
tok.pad_token = tok.eos_token
|
| 174 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 175 |
+
try:
|
| 176 |
+
model = AutoModelForCausalLM.from_pretrained(args.model, dtype="auto").to(device)
|
| 177 |
+
except TypeError:
|
| 178 |
+
# `dtype` is the transformers 5.x name; older releases use `torch_dtype`.
|
| 179 |
+
model = AutoModelForCausalLM.from_pretrained(args.model, torch_dtype="auto").to(device)
|
| 180 |
+
model.eval()
|
| 181 |
|
| 182 |
ds = load_dataset(args.dataset, split=args.split)
|
| 183 |
if args.limit:
|