File size: 3,148 Bytes
90964f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157d7a8
 
90964f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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)