itsLu commited on
Commit
e6709f3
·
verified ·
1 Parent(s): cf9264f

Upload inference.py

Browse files
Files changed (1) hide show
  1. inference.py +120 -0
inference.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ \"\"\"
3
+ inference.py — Deep Dive v2: Self-Contained Inference Module
4
+ Model : itsLu/mentalbert-v5-deep-dive-v2
5
+ Task : Binary Depression vs Suicidal re-ranker (second-tier specialist)
6
+
7
+ ⚠️ WARNING: This model MUST NOT be used standalone.
8
+ It is invoked by Quick Vibe (itsLu/mentalbert-v5-source-aware) only when:
9
+ (a) Quick Vibe's top1 ∈ {Depression, Suicidal} AND margin < 0.20, OR
10
+ (b) Quick Vibe abstains.
11
+ It has NO coverage for: Normal, Anxiety, Stress, Bipolar,
12
+ Personality Disorder, Directed Aggression.
13
+
14
+ Usage:
15
+ from inference import DeepDiveV2
16
+ clf = DeepDiveV2.from_hub()
17
+ result = clf.predict("I don't want to be here anymore.")
18
+ # {'label': 'Suicidal', 'p_suicidal': 0.91, 'crisis_evidence_found': True,
19
+ # 'crisis_tokens_matched': ['want to die']}
20
+ \"\"\"
21
+
22
+ import json, torch, torch.nn as nn
23
+ from typing import Any, Dict, List
24
+ from transformers import BertModel, BertTokenizerFast
25
+ from huggingface_hub import hf_hub_download
26
+
27
+ HF_REPO = "itsLu/mentalbert-v5-deep-dive-v2"
28
+ CLASSES = ["Depression", "Suicidal"]
29
+
30
+
31
+ class CrisisEvidenceMentalBERT(nn.Module):
32
+ \"\"\"BertModel + crisis-evidence token max-pooling + binary head.\"\"\"
33
+ def __init__(self, model_name: str, hidden_size: int = 768):
34
+ super().__init__()
35
+ self.encoder = BertModel.from_pretrained(model_name)
36
+ self.dropout = nn.Dropout(0.2)
37
+ self.classifier = nn.Sequential(
38
+ nn.Linear(hidden_size * 2, 256),
39
+ nn.GELU(),
40
+ nn.Dropout(0.2),
41
+ nn.Linear(256, 2),
42
+ )
43
+
44
+ def forward(self, input_ids, attention_mask, crisis_mask):
45
+ h_seq = self.encoder(input_ids=input_ids,
46
+ attention_mask=attention_mask).last_hidden_state
47
+ h_cls = h_seq[:, 0, :]
48
+ masked = h_seq.masked_fill(~crisis_mask.unsqueeze(-1), float('-inf'))
49
+ any_crisis = crisis_mask.any(dim=1)
50
+ h_crisis_raw = masked.max(dim=1).values
51
+ h_crisis = torch.where(any_crisis.unsqueeze(-1), h_crisis_raw, h_cls)
52
+ return self.classifier(self.dropout(torch.cat([h_cls, h_crisis], dim=-1)))
53
+
54
+
55
+ class DeepDiveV2:
56
+ \"\"\"High-level inference wrapper — load from Hub, call .predict(text).\"\"\"
57
+
58
+ def __init__(self, model: CrisisEvidenceMentalBERT, tokenizer: BertTokenizerFast,
59
+ crisis_keywords: List[str], threshold: float, max_len: int = 256):
60
+ self.model = model.eval()
61
+ self.tokenizer = tokenizer
62
+ self.crisis_keywords = [k.lower() for k in crisis_keywords]
63
+ self.threshold = threshold
64
+ self.max_len = max_len
65
+ self.device = next(model.parameters()).device
66
+
67
+ @classmethod
68
+ def from_hub(cls, repo_id: str = HF_REPO, device: str = "cpu") -> "DeepDiveV2":
69
+ tokenizer = BertTokenizerFast.from_pretrained(repo_id)
70
+ cfg_path = hf_hub_download(repo_id=repo_id, filename="inference_config.json")
71
+ kw_path = hf_hub_download(repo_id=repo_id, filename="crisis_keywords.json")
72
+ clf_path = hf_hub_download(repo_id=repo_id, filename="classifier.pt")
73
+ with open(cfg_path) as f: cfg = json.load(f)
74
+ with open(kw_path) as f: kws = json.load(f)["crisis_keywords"]
75
+ model = CrisisEvidenceMentalBERT(model_name=repo_id)
76
+ model.classifier.load_state_dict(torch.load(clf_path, map_location=device))
77
+ model.to(device)
78
+ return cls(model=model, tokenizer=tokenizer, crisis_keywords=kws,
79
+ threshold=cfg["threshold"], max_len=cfg["max_len"])
80
+
81
+ def _crisis_mask(self, text: str, offsets: list) -> "torch.BoolTensor":
82
+ tl = text.lower()
83
+ spans = []
84
+ for kw in self.crisis_keywords:
85
+ s = 0
86
+ while (i := tl.find(kw, s)) >= 0:
87
+ spans.append((i, i + len(kw))); s = i + 1
88
+ mask = torch.zeros(self.max_len, dtype=torch.bool)
89
+ for ti, (s, e) in enumerate(offsets):
90
+ if s == e == 0: continue
91
+ for cs, ce in spans:
92
+ if s < ce and e > cs: mask[ti] = True; break
93
+ return mask
94
+
95
+ def predict(self, text: str) -> Dict[str, Any]:
96
+ \"\"\"
97
+ Returns:
98
+ label : 'Depression' | 'Suicidal'
99
+ p_suicidal : float — P(Suicidal)
100
+ crisis_evidence_found : bool — any crisis keyword matched
101
+ crisis_tokens_matched : list[str]
102
+ \"\"\"
103
+ enc = self.tokenizer(text, max_length=self.max_len, truncation=True,
104
+ padding="max_length", return_offsets_mapping=True,
105
+ return_tensors="pt")
106
+ ids = enc["input_ids"].to(self.device)
107
+ amsk = enc["attention_mask"].to(self.device)
108
+ offs = enc["offset_mapping"].squeeze(0).tolist()
109
+ cmsk = self._crisis_mask(text, offs).unsqueeze(0).to(self.device)
110
+ matched = [kw for kw in self.crisis_keywords if kw in text.lower()]
111
+ with torch.no_grad():
112
+ probs = torch.softmax(self.model(ids, amsk, cmsk), dim=-1).squeeze(0).cpu()
113
+ p = float(probs[1])
114
+ return {"label": "Suicidal" if p >= self.threshold else "Depression",
115
+ "p_suicidal": round(p, 6),
116
+ "crisis_evidence_found": bool(cmsk.any().item()),
117
+ "crisis_tokens_matched": matched}
118
+
119
+ def predict_batch(self, texts: List[str]) -> List[Dict[str, Any]]:
120
+ return [self.predict(t) for t in texts]