Add benchmark adapters for released models
#11
by jfbrown95 - opened
- README.md +1 -0
- adapters/README.md +42 -0
- adapters/clm.py +125 -0
- adapters/jev_lite.py +50 -0
- adapters/jevk5.py +25 -0
- adapters/securebert.py +72 -0
- benchmark.py +1 -0
README.md
CHANGED
|
@@ -67,6 +67,7 @@ At 0.5, SecureBERT2.0 flags nearly every security method. Its high F1 therefore
|
|
| 67 |
## Files
|
| 68 |
|
| 69 |
- [`benchmark.py`](https://huggingface.co/datasets/perchscan/benchmark-results/blob/main/benchmark.py): run a model on the public pairs and calculate the metrics in these tables.
|
|
|
|
| 70 |
- `results.jsonl`: one aggregate report per domain, track, model, and protocol.
|
| 71 |
- `split-summary.json`: split sizes and whole-file SHA-256 values. It contains no private rows or repository list.
|
| 72 |
- `predictions/`: public-pair probabilities for auditing the public scores. No private predictions are included.
|
|
|
|
| 67 |
## Files
|
| 68 |
|
| 69 |
- [`benchmark.py`](https://huggingface.co/datasets/perchscan/benchmark-results/blob/main/benchmark.py): run a model on the public pairs and calculate the metrics in these tables.
|
| 70 |
+
- [`adapters/`](https://huggingface.co/datasets/perchscan/benchmark-results/tree/main/adapters): example runners for the unmodified open-source models in the tables.
|
| 71 |
- `results.jsonl`: one aggregate report per domain, track, model, and protocol.
|
| 72 |
- `split-summary.json`: split sizes and whole-file SHA-256 values. It contains no private rows or repository list.
|
| 73 |
- `predictions/`: public-pair probabilities for auditing the public scores. No private predictions are included.
|
adapters/README.md
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Released-model benchmark adapters
|
| 2 |
+
|
| 3 |
+
These scripts connect the [Perch benchmark runner](../benchmark.py) to the unmodified, publicly released models in the results table. Each process reads one JSON request per line and writes `{"score": probability}` per line. Scores are for the supplied method side; the adapter never sees its paired repair or label.
|
| 4 |
+
|
| 5 |
+
Install the relevant model's upstream dependencies before running it. A small smoke run uses `--limit 2`; rerunning the same command resumes the prediction file. Remove `--limit` to finish and write the metric report.
|
| 6 |
+
|
| 7 |
+
## JevK5
|
| 8 |
+
|
| 9 |
+
Install the [JevK5 runtime](https://github.com/allebee/jevk5) and `huggingface_hub`. The adapter pins the v0.2 model used in the published result. If already downloaded, set `JEVK5_MODEL` to that snapshot directory.
|
| 10 |
+
|
| 11 |
+
```sh
|
| 12 |
+
python3 benchmark.py run --domain bug --scorer command --command 'python3 adapters/jevk5.py' --model-revision 'alibiserikbay/JevK5@3c673298eb7f2dc7cb98019262c55b1fac01a0bc' --protocol-id perch-broad-v1 --predictions bug-jevk5.jsonl --report bug-jevk5.json --limit 2
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
## jev-lite
|
| 16 |
+
|
| 17 |
+
Install `torch`, `transformers`, `peft`, and `huggingface_hub`. The adapter pins both the [Gemma base](https://huggingface.co/google/gemma-4-E4B-it) and [jev-lite adapter](https://huggingface.co/vagmi/jev-lite) revisions from the published run. Set `JEV_LITE_BASE` and `JEV_LITE_ADAPTER` to local snapshots to avoid downloading them again. Gemma access may require accepting its license on Hugging Face.
|
| 18 |
+
|
| 19 |
+
```sh
|
| 20 |
+
python3 benchmark.py run --domain bug --scorer command --command 'python3 adapters/jev_lite.py' --model-revision 'vagmi/jev-lite@90b23bc26c53f5a897684456893b2b7edeb90297' --protocol-id perch-broad-v1 --predictions bug-jev-lite.jsonl --report bug-jev-lite.json --limit 2
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
## SecureBERT2.0
|
| 24 |
+
|
| 25 |
+
Install `torch`, `transformers`, and `huggingface_hub`. This security-only adapter formats and truncates Perch context to the 4,096-token input used for the published run. The exact upstream snapshot revision was not recorded for that run, so set `SECUREBERT_MODEL` to a chosen local snapshot and record its revision with your result.
|
| 26 |
+
|
| 27 |
+
```sh
|
| 28 |
+
python3 benchmark.py run --domain security --scorer command --command 'python3 adapters/securebert.py' --model-revision 'cisco-ai/SecureBERT2.0-code-vuln-detection@YOUR_REVISION' --protocol-id perch-security-state-4096-v1 --predictions security-securebert.jsonl --report security-securebert.json --limit 2
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
## CLM-v0.1-8B
|
| 32 |
+
|
| 33 |
+
Clone the [CLM source](https://github.com/Contrastive-LM/CLM), set `CLM_REPO` to the checkout, and install its dependencies plus `torch`, `numpy`, and `huggingface_hub`. Run a vLLM Qwen3-8B pooling endpoint with a context length of at least 6,144 tokens. Set `CLM_EMBED_URL` if it is not `http://127.0.0.1:8090/v1/embeddings`. The adapter checks the released choice-head file hash and uses the same method formatting and 6,144-token embedding recipe as the published run.
|
| 34 |
+
|
| 35 |
+
```sh
|
| 36 |
+
export CLM_REPO=/path/to/CLM
|
| 37 |
+
vllm serve Qwen/Qwen3-8B --runner pooling --max-model-len 6144 --port 8090
|
| 38 |
+
# In another shell:
|
| 39 |
+
python3 benchmark.py run --domain bug --scorer command --command 'python3 adapters/clm.py' --model-revision 'Contrastive-LM/CLM-v0.1-8B@sha256:b2b4a8c9c2d39263eff78a351eb909a342ce9b3bf21a3f07c1d1bf15f1c4eda5' --protocol-id clm-native-choice-6144-v1 --predictions bug-clm.jsonl --report bug-clm.json --limit 2
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
The CLM adapter uses its native choice prompts, while the other adapters use the broad bug or security question where the model accepts one. Input length and model revisions affect results. These scripts contain no benchmark labels, API keys, private data, or fine-tuned weights.
|
adapters/clm.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Persistent benchmark adapter for the released CLM-v0.1-8B choice heads.
|
| 3 |
+
|
| 4 |
+
Requires the upstream CLM checkout and a Qwen3-8B vLLM pooling endpoint.
|
| 5 |
+
See adapters/README.md for setup. This is the 6,144-token benchmark protocol.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import contextlib
|
| 9 |
+
import hashlib
|
| 10 |
+
import json
|
| 11 |
+
import os
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
import sys
|
| 14 |
+
|
| 15 |
+
from huggingface_hub import hf_hub_download
|
| 16 |
+
import numpy as np
|
| 17 |
+
import torch
|
| 18 |
+
from torch.nn import functional as F
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
repo = Path(os.environ["CLM_REPO"])
|
| 22 |
+
sys.path.insert(0, str(repo / "src"))
|
| 23 |
+
sys.path.insert(0, str(repo / "train"))
|
| 24 |
+
from clm.heads import make_head # noqa: E402
|
| 25 |
+
from clm.schema import build_pairs # noqa: E402
|
| 26 |
+
from embed_utils import Recipe, ServerBackend # noqa: E402
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
QUESTIONS = {
|
| 30 |
+
"bug": {
|
| 31 |
+
"type": "noul",
|
| 32 |
+
"instructions": "Does this method contain a functional bug that can cause incorrect behavior in the current code?",
|
| 33 |
+
"criteria": {
|
| 34 |
+
"false": "The current method has no functional bug causing incorrect behavior.",
|
| 35 |
+
"true": "The current method has a functional bug causing incorrect behavior.",
|
| 36 |
+
},
|
| 37 |
+
},
|
| 38 |
+
"security": {
|
| 39 |
+
"type": "noul",
|
| 40 |
+
"instructions": "Does this method contain a security vulnerability exploitable in the current code?",
|
| 41 |
+
"criteria": {
|
| 42 |
+
"false": "The current method has no exploitable security vulnerability.",
|
| 43 |
+
"true": "The current method has an exploitable security vulnerability.",
|
| 44 |
+
},
|
| 45 |
+
},
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def context_text(row):
|
| 50 |
+
state = row["state"]
|
| 51 |
+
target = state.get("method") or {}
|
| 52 |
+
|
| 53 |
+
def neighbors(name):
|
| 54 |
+
chunks = []
|
| 55 |
+
for item in state.get(name, []):
|
| 56 |
+
if isinstance(item, str):
|
| 57 |
+
chunks.append(item)
|
| 58 |
+
else:
|
| 59 |
+
chunks.append(f"{item.get('name', '')} ({item.get('path', '')})\n{item.get('source', '')}")
|
| 60 |
+
return "\n".join(chunks)
|
| 61 |
+
|
| 62 |
+
sections = {
|
| 63 |
+
"method": f"LANGUAGE: {row.get('language') or 'unknown'}\nPATH: {target.get('path') or ''}"
|
| 64 |
+
f"\nMETHOD: {target.get('name') or ''}\n{target.get('source') or row.get('source') or ''}",
|
| 65 |
+
"edges": "CALL GRAPH EDGES:\n" + "\n".join(map(str, state.get("call_graph", []))),
|
| 66 |
+
"callers": "CALLERS:\n" + neighbors("called_by"),
|
| 67 |
+
"callees": "CALLEES:\n" + neighbors("calls"),
|
| 68 |
+
"module": "MODULE SCOPE:\n" + str(state.get("module_scope", "")),
|
| 69 |
+
"imports": "IMPORTS:\n" + "\n".join(map(str, state.get("imports", []))),
|
| 70 |
+
}
|
| 71 |
+
order = ("imports", "module", "edges", "callers", "callees", "method")
|
| 72 |
+
return "\n\n".join(sections[key] for key in order if sections[key].strip())
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
head_path = Path(os.getenv("CLM_HEAD") or hf_hub_download(
|
| 76 |
+
"Contrastive-LM/CLM-v0.1-8B", "CLM_v0.1-8B.pt"))
|
| 77 |
+
expected_hash = "b2b4a8c9c2d39263eff78a351eb909a342ce9b3bf21a3f07c1d1bf15f1c4eda5"
|
| 78 |
+
if hashlib.sha256(head_path.read_bytes()).hexdigest() != expected_hash:
|
| 79 |
+
raise RuntimeError("CLM choice head does not match the published checkpoint")
|
| 80 |
+
|
| 81 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu")
|
| 82 |
+
blob = torch.load(head_path, map_location="cpu", weights_only=True)
|
| 83 |
+
cfg = blob["cfg"]
|
| 84 |
+
kwargs = {"width": cfg["width"], "depth": cfg["depth"],
|
| 85 |
+
"proj": cfg.get("projection_dim", 512),
|
| 86 |
+
"activation": cfg.get("activation", "gelu"),
|
| 87 |
+
"layernorm": cfg.get("layernorm", False),
|
| 88 |
+
"residual": cfg.get("residual", False),
|
| 89 |
+
"hidden": cfg.get("hidden_size", 4096)}
|
| 90 |
+
state_head = make_head(**kwargs).to(device).eval()
|
| 91 |
+
action_head = make_head(**kwargs).to(device).eval()
|
| 92 |
+
state_head.load_state_dict(blob["state_head"])
|
| 93 |
+
action_head.load_state_dict(blob["action_head"])
|
| 94 |
+
scale = torch.as_tensor(blob["logit_scale"], device=device).float().exp().clamp(max=100.0)
|
| 95 |
+
|
| 96 |
+
model_name = "Qwen/Qwen3-8B"
|
| 97 |
+
recipe = Recipe(model_name, 6144)
|
| 98 |
+
backend = ServerBackend(os.getenv("CLM_EMBED_URL", "http://127.0.0.1:8090/v1/embeddings"),
|
| 99 |
+
model_name, batch=16)
|
| 100 |
+
candidate_vectors = {}
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def embed(ids):
|
| 104 |
+
# Upstream's embedding backend emits progress on stdout; reserve stdout for NDJSON.
|
| 105 |
+
with contextlib.redirect_stdout(sys.stderr):
|
| 106 |
+
vector = backend.embed([ids])[0]
|
| 107 |
+
return torch.from_numpy(np.asarray(vector, dtype=np.float16).astype(np.float32)).to(device)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
with torch.inference_mode():
|
| 111 |
+
for line in sys.stdin:
|
| 112 |
+
row = json.loads(line)
|
| 113 |
+
domain = row["domain"]
|
| 114 |
+
state_text, keys, candidates = build_pairs(context_text(row), {domain: QUESTIONS[domain]})[domain]
|
| 115 |
+
if keys != ["false", "true"] or len(candidates) != 2:
|
| 116 |
+
raise RuntimeError("CLM option order changed")
|
| 117 |
+
if domain not in candidate_vectors:
|
| 118 |
+
candidate_vectors[domain] = torch.stack([
|
| 119 |
+
embed(recipe.text_ids(text, keep="head")) for text in candidates])
|
| 120 |
+
state = embed(recipe.text_ids(state_text, keep="tail")).unsqueeze(0)
|
| 121 |
+
state_z = F.normalize(state_head(state), dim=-1)
|
| 122 |
+
action_z = F.normalize(action_head(candidate_vectors[domain]), dim=-1)
|
| 123 |
+
logits = scale * torch.einsum("bd,kd->bk", state_z, action_z)
|
| 124 |
+
score = torch.softmax(logits.float(), dim=-1)[0, 1].item()
|
| 125 |
+
print(json.dumps({"score": score}), flush=True)
|
adapters/jev_lite.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Persistent benchmark.py command adapter for the released jev-lite checkpoint."""
|
| 3 |
+
|
| 4 |
+
import importlib.util
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import sys
|
| 9 |
+
|
| 10 |
+
from huggingface_hub import snapshot_download
|
| 11 |
+
from peft import PeftModel
|
| 12 |
+
import torch
|
| 13 |
+
from transformers import AutoModelForImageTextToText, AutoTokenizer
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
base_path = os.getenv("JEV_LITE_BASE") or snapshot_download(
|
| 17 |
+
"google/gemma-4-E4B-it", revision="ee0ef6023621cff504d758262d4e04895a5af4a2")
|
| 18 |
+
adapter_path = os.getenv("JEV_LITE_ADAPTER") or snapshot_download(
|
| 19 |
+
"vagmi/jev-lite", revision="90b23bc26c53f5a897684456893b2b7edeb90297")
|
| 20 |
+
spec = importlib.util.spec_from_file_location("jev_lite_primitives", Path(adapter_path) / "primitives.py")
|
| 21 |
+
primitives = importlib.util.module_from_spec(spec)
|
| 22 |
+
spec.loader.exec_module(primitives)
|
| 23 |
+
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
|
| 24 |
+
tokenizer = AutoTokenizer.from_pretrained(adapter_path)
|
| 25 |
+
base = AutoModelForImageTextToText.from_pretrained(
|
| 26 |
+
base_path, torch_dtype=torch.bfloat16,
|
| 27 |
+
attn_implementation="sdpa" if device == "cuda" else "eager",
|
| 28 |
+
low_cpu_mem_usage=True)
|
| 29 |
+
model = PeftModel.from_pretrained(base, adapter_path).eval().to(device)
|
| 30 |
+
letters = [tokenizer.encode(" " + c, add_special_tokens=False)[0]
|
| 31 |
+
for c in primitives.LETTERS[:2]]
|
| 32 |
+
if len(set(letters)) != 2:
|
| 33 |
+
raise RuntimeError("Answer token IDs are not distinct")
|
| 34 |
+
|
| 35 |
+
with torch.inference_mode():
|
| 36 |
+
for line in sys.stdin:
|
| 37 |
+
request = json.loads(line)
|
| 38 |
+
question = request["question"]
|
| 39 |
+
item = primitives.normalize({
|
| 40 |
+
"type": "noul", "state": json.dumps(request["state"], ensure_ascii=False),
|
| 41 |
+
"question": question["instructions"], "options": ["true", "false"],
|
| 42 |
+
"criteria": question["criteria"],
|
| 43 |
+
})
|
| 44 |
+
prompt = (primitives.PREFIX + item["state"] + "\n</state>\n\n"
|
| 45 |
+
+ primitives.question_block(item) + "\nAnswer:")
|
| 46 |
+
ids = [tokenizer.bos_token_id] + tokenizer.encode(prompt, add_special_tokens=False)
|
| 47 |
+
tensor = torch.tensor([ids], dtype=torch.long, device=device)
|
| 48 |
+
logits = model(input_ids=tensor).logits[0, -1].float()
|
| 49 |
+
score = torch.softmax(logits[letters], dim=-1)[0].item()
|
| 50 |
+
print(json.dumps({"score": score}), flush=True)
|
adapters/jevk5.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Persistent benchmark.py command adapter for the pinned, unmodified JevK5 v0.2.
|
| 3 |
+
|
| 4 |
+
Install the upstream runtime from https://github.com/allebee/jevk5, then run
|
| 5 |
+
with JEVK5_MODEL pointing to a local snapshot if it is already downloaded.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
import sys
|
| 11 |
+
|
| 12 |
+
from huggingface_hub import snapshot_download
|
| 13 |
+
from jevk5.runtime import JevK5
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
REVISION = "3c673298eb7f2dc7cb98019262c55b1fac01a0bc"
|
| 17 |
+
path = os.getenv("JEVK5_MODEL") or snapshot_download("alibiserikbay/JevK5", revision=REVISION)
|
| 18 |
+
model = JevK5(path, graphs=False)
|
| 19 |
+
if model.temperature != 1.532:
|
| 20 |
+
raise RuntimeError("This adapter expects the v0.2 checkpoint used in the published result")
|
| 21 |
+
|
| 22 |
+
for line in sys.stdin:
|
| 23 |
+
row = json.loads(line)
|
| 24 |
+
probabilities, _ = model.probabilities(row["state"], row["question"])
|
| 25 |
+
print(json.dumps({"score": float(probabilities["true"])}), flush=True)
|
adapters/securebert.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Persistent benchmark.py adapter for Cisco's released SecureBERT detection head.
|
| 3 |
+
|
| 4 |
+
The original benchmark run did not record the exact Hub snapshot revision.
|
| 5 |
+
Set SECUREBERT_MODEL to that snapshot when reproducing a specific run.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
import math
|
| 10 |
+
import os
|
| 11 |
+
import sys
|
| 12 |
+
|
| 13 |
+
from huggingface_hub import snapshot_download
|
| 14 |
+
import torch
|
| 15 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
CAPS = (("method", 2800), ("edges", 120), ("callers", 520),
|
| 19 |
+
("callees", 520), ("module", 240), ("imports", 120))
|
| 20 |
+
path = os.getenv("SECUREBERT_MODEL") or snapshot_download(
|
| 21 |
+
"cisco-ai/SecureBERT2.0-code-vuln-detection")
|
| 22 |
+
tokenizer = AutoTokenizer.from_pretrained(path)
|
| 23 |
+
model = AutoModelForSequenceClassification.from_pretrained(path, attn_implementation="sdpa")
|
| 24 |
+
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
|
| 25 |
+
model.to(device).eval()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def sections(row):
|
| 29 |
+
state = row["state"]
|
| 30 |
+
method = state["method"]
|
| 31 |
+
|
| 32 |
+
def neighbors(key):
|
| 33 |
+
return "\n".join(f"{item.get('name', '')} ({item.get('path', '')})\n{item.get('source', '')}"
|
| 34 |
+
for item in state.get(key, []))
|
| 35 |
+
|
| 36 |
+
return {
|
| 37 |
+
"method": f"LANGUAGE: {row['language']}\nPATH: {method.get('path', '')}"
|
| 38 |
+
f"\nMETHOD: {method.get('name', '')}\n{method.get('source', '')}",
|
| 39 |
+
"edges": "CALL GRAPH EDGES:\n" + "\n".join(state.get("call_graph", [])),
|
| 40 |
+
"callers": "CALLERS:\n" + neighbors("called_by"),
|
| 41 |
+
"callees": "CALLEES:\n" + neighbors("calls"),
|
| 42 |
+
"module": "MODULE SCOPE:\n" + str(state.get("module_scope", "")),
|
| 43 |
+
"imports": "IMPORTS:\n" + "\n".join(map(str, state.get("imports", []))),
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
with torch.inference_mode():
|
| 48 |
+
for line in sys.stdin:
|
| 49 |
+
row = json.loads(line)
|
| 50 |
+
if row["domain"] != "security":
|
| 51 |
+
raise ValueError("SecureBERT adapter supports security only")
|
| 52 |
+
parts = sections(row)
|
| 53 |
+
ids = [tokenizer.cls_token_id]
|
| 54 |
+
for name, cap in CAPS:
|
| 55 |
+
ids.extend(tokenizer.encode(parts[name], add_special_tokens=False)[:cap])
|
| 56 |
+
ids.append(tokenizer.sep_token_id)
|
| 57 |
+
if len(ids) > 4096:
|
| 58 |
+
ids = ids[:4095] + [tokenizer.sep_token_id]
|
| 59 |
+
length = math.ceil(len(ids) / 64) * 64
|
| 60 |
+
tokens = torch.full((1, length), tokenizer.pad_token_id, dtype=torch.long, device=device)
|
| 61 |
+
mask = torch.zeros_like(tokens)
|
| 62 |
+
tokens[0, :len(ids)] = torch.tensor(ids, dtype=torch.long, device=device)
|
| 63 |
+
mask[0, :len(ids)] = 1
|
| 64 |
+
hidden = model.model(input_ids=tokens, attention_mask=mask)[0]
|
| 65 |
+
if model.config.classifier_pooling == "mean":
|
| 66 |
+
m = mask.unsqueeze(-1)
|
| 67 |
+
pooled = (hidden * m).sum(1) / m.sum(1).clamp(min=1)
|
| 68 |
+
else:
|
| 69 |
+
pooled = hidden[:, 0]
|
| 70 |
+
logits = model.classifier(model.drop(model.head(pooled)))[0].float()
|
| 71 |
+
score = torch.sigmoid(logits[1] - logits[0]).item()
|
| 72 |
+
print(json.dumps({"score": score}), flush=True)
|
benchmark.py
CHANGED
|
@@ -213,6 +213,7 @@ def run(args: argparse.Namespace) -> None:
|
|
| 213 |
score = jev_score(state, args.domain, revision, args.api_url)
|
| 214 |
else:
|
| 215 |
request = {"domain": args.domain, "pair_id": pair["pair_id"], "role": role,
|
|
|
|
| 216 |
"state": state, "question": QUESTION[args.domain]}
|
| 217 |
assert command and command.stdin and command.stdout
|
| 218 |
command.stdin.write(json.dumps(request, ensure_ascii=False) + "\n")
|
|
|
|
| 213 |
score = jev_score(state, args.domain, revision, args.api_url)
|
| 214 |
else:
|
| 215 |
request = {"domain": args.domain, "pair_id": pair["pair_id"], "role": role,
|
| 216 |
+
"language": pair.get("language"), "source": pair[role]["source"],
|
| 217 |
"state": state, "question": QUESTION[args.domain]}
|
| 218 |
assert command and command.stdin and command.stdout
|
| 219 |
command.stdin.write(json.dumps(request, ensure_ascii=False) + "\n")
|