Download adapters/securebert.py from perchscan/benchmark-results: direct link, hf CLI and curl.
- Browser
- Download file 3.15 kB
-
https://huggingface.co/datasets/perchscan/benchmark-results/resolve/main/adapters/securebert.py
- Command line
-
hf download hf://datasets/perchscan/benchmark-results/adapters/securebert.py
-
curl -L -o securebert.py https://huggingface.co/datasets/perchscan/benchmark-results/resolve/main/adapters/securebert.py
3.15 kB
| #!/usr/bin/env python3 | |
| """Persistent benchmark.py adapter for Cisco's released SecureBERT detection head. | |
| The original benchmark run did not record the exact Hub snapshot revision. | |
| Set SECUREBERT_MODEL to that snapshot when reproducing a specific run. | |
| """ | |
| import json | |
| import math | |
| import os | |
| import sys | |
| from huggingface_hub import snapshot_download | |
| import torch | |
| from transformers import AutoModelForSequenceClassification, AutoTokenizer | |
| CAPS = (("method", 2800), ("edges", 120), ("callers", 520), | |
| ("callees", 520), ("module", 240), ("imports", 120)) | |
| path = os.getenv("SECUREBERT_MODEL") or snapshot_download( | |
| "cisco-ai/SecureBERT2.0-code-vuln-detection") | |
| tokenizer = AutoTokenizer.from_pretrained(path) | |
| model = AutoModelForSequenceClassification.from_pretrained(path, attn_implementation="sdpa") | |
| device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu" | |
| model.to(device).eval() | |
| def sections(row): | |
| state = row["state"] | |
| method = state["method"] | |
| def neighbors(key): | |
| return "\n".join(f"{item.get('name', '')} ({item.get('path', '')})\n{item.get('source', '')}" | |
| for item in state.get(key, [])) | |
| return { | |
| "method": f"LANGUAGE: {row['language']}\nPATH: {method.get('path', '')}" | |
| f"\nMETHOD: {method.get('name', '')}\n{method.get('source', '')}", | |
| "edges": "CALL GRAPH EDGES:\n" + "\n".join(state.get("call_graph", [])), | |
| "callers": "CALLERS:\n" + neighbors("called_by"), | |
| "callees": "CALLEES:\n" + neighbors("calls"), | |
| "module": "MODULE SCOPE:\n" + str(state.get("module_scope", "")), | |
| "imports": "IMPORTS:\n" + "\n".join(map(str, state.get("imports", []))), | |
| } | |
| with torch.inference_mode(): | |
| for line in sys.stdin: | |
| row = json.loads(line) | |
| if row["domain"] != "security": | |
| raise ValueError("SecureBERT adapter supports security only") | |
| if "question_name" in row: | |
| raise ValueError("SecureBERT does not accept CWE questions; use its native protocol ID") | |
| parts = sections(row) | |
| ids = [tokenizer.cls_token_id] | |
| for name, cap in CAPS: | |
| ids.extend(tokenizer.encode(parts[name], add_special_tokens=False)[:cap]) | |
| ids.append(tokenizer.sep_token_id) | |
| if len(ids) > 4096: | |
| ids = ids[:4095] + [tokenizer.sep_token_id] | |
| length = math.ceil(len(ids) / 64) * 64 | |
| tokens = torch.full((1, length), tokenizer.pad_token_id, dtype=torch.long, device=device) | |
| mask = torch.zeros_like(tokens) | |
| tokens[0, :len(ids)] = torch.tensor(ids, dtype=torch.long, device=device) | |
| mask[0, :len(ids)] = 1 | |
| hidden = model.model(input_ids=tokens, attention_mask=mask)[0] | |
| if model.config.classifier_pooling == "mean": | |
| m = mask.unsqueeze(-1) | |
| pooled = (hidden * m).sum(1) / m.sum(1).clamp(min=1) | |
| else: | |
| pooled = hidden[:, 0] | |
| logits = model.classifier(model.drop(model.head(pooled)))[0].float() | |
| score = torch.sigmoid(logits[1] - logits[0]).item() | |
| print(json.dumps({"score": score}), flush=True) | |