Views
No views yet
cisco-ai/SecureBERT2.0 utilizing a Multi-Task Learning (MTL) architecture with flat classification heads.SecureBERT2.0 backbone with 12 distinct classification heads attached to the pooled outputs:LayerNorm -> Linear -> GELU -> Dropout -> Linear -> Softmax. They use the [CLS] token embedding to predict nominal and ordinal CVSS categories.config.json. It dynamically dictates the architecture and handles label decoding.cvss_map: Contains the exact string labels for all 8 CVSS metrics (e.g., ["Network", "Adjacent", "Local", "Physical"]).cwe_labels: Contains ID-to-Name mappings for all supported CWEs across pillar, class, base, and variant levels.AutoModelForSequenceClassification. You must define the custom PyTorch class provided in the usage snippet below.1import json
2import torch
3import torch.nn as nn
4import torch.nn.functional as F
5from transformers import AutoConfig, AutoModel, AutoTokenizer
6from huggingface_hub import hf_hub_download
7
8# 1. Define the Custom Architecture
9class SecureBERTFlatClassifier(nn.Module):
10 def __init__(self, model_name, cvss_map, class_counts):
11 super().__init__()
12 config = AutoConfig.from_pretrained(model_name)
13 if hasattr(config, "reference_compile"): config.reference_compile = False
14 self.bert = AutoModel.from_pretrained(model_name, config=config)
15
16 def make_head(out_features, is_cvss=False):
17 layers =[
18 nn.LayerNorm(768), nn.Dropout(0.1),
19 nn.Linear(768, 768), nn.GELU(), nn.Dropout(0.1),
20 nn.Linear(768, 768), nn.GELU(), nn.Dropout(0.1),
21 nn.Linear(768, out_features)
22 ]
23 if is_cvss: layers.append(nn.Softmax(dim=1))
24 return nn.Sequential(*layers)
25
26 self.cvss_heads = nn.ModuleDict({k: make_head(len(v), True) for k, v in cvss_map.items()})
27 self.cwe_heads = nn.ModuleDict({k: make_head(v) for k, v in class_counts.items()})
28
29 def forward(self, input_ids, attention_mask):
30 out = self.bert(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state
31 cls_emb = out[:, 0, :]
32 mask = attention_mask.unsqueeze(-1).expand(out.size()).float()
33 mean_emb = torch.sum(out * mask, 1) / torch.clamp(mask.sum(1), min=1e-9)
34
35 res = {}
36 for k, head in self.cvss_heads.items(): res[k] = head(cls_emb)
37 for k, head in self.cwe_heads.items(): res[k] = head(mean_emb)
38 return res
39
40# 2. Inference Wrapper
41class VulnPredictor:
42 def __init__(self, repo_id):
43 self.device = "cuda" if torch.cuda.is_available() else "cpu"
44
45 conf_path = hf_hub_download(repo_id=repo_id, filename="config.json")
46 model_path = hf_hub_download(repo_id=repo_id, filename="pytorch_model.bin")
47
48 with open(conf_path, "r") as f: self.config = json.load(f)
49
50 base_model = self.config.get("base_model", "cisco-ai/SecureBERT2.0-biencoder")
51 counts = {k: len(v) for k, v in self.config.get("cwe_labels", {}).items()}
52
53 self.tokenizer = AutoTokenizer.from_pretrained(base_model)
54 self.model = SecureBERTFlatClassifier(base_model, self.config["cvss_map"], counts)
55 self.model.load_state_dict(torch.load(model_path, map_location=self.device), strict=False)
56 self.model.to(self.device).eval()
57
58 def predict(self, text, top_k=3):
59 inputs = self.tokenizer(text, return_tensors="pt", truncation=True, max_length=512).to(self.device)
60 with torch.no_grad():
61 out = self.model(inputs['input_ids'], inputs['attention_mask'])
62
63 res = {'cvss': {}, 'cwe': {}}
64 for task, labels in self.config.get("cvss_map", {}).items():
65 score, idx = torch.max(out[task], dim=1)
66 res['cvss'][task] = {"value": labels[idx.item()], "confidence": round(score.item(), 4)}
67
68 for lv, cwe_data in self.config.get("cwe_labels", {}).items():
69 if lv in out:
70 probs = F.softmax(out[lv], dim=1)
71 scores, idxs = torch.topk(probs, k=min(top_k, probs.size(1)))
72 res['cwe'][lv] =[
73 {"id": int(str(cwe_data[i.item()]['id']).replace('CWE-','')),
74 "name": cwe_data[i.item()]['name'],
75 "score": round(s.item(), 4)} for s, i in zip(scores[0], idxs[0])
76 ]
77 return res
78
79# 3. Quickstart
80if __name__ == "__main__":
81 REPO_ID = "bziemba/SecureBERT2.0-final"
82
83 predictor = VulnPredictor(REPO_ID)
84
85 sample_cve = "An issue was discovered in the login panel allowing attackers to bypass authentication via crafted SQL queries."
86 results = predictor.predict(sample_cve)
87
88 print(json.dumps(results, indent=2))
89