Views
No views yet
1from transformers import AutoTokenizer, AutoModelForSequenceClassification
2import torch
3
4# Load model and tokenizer
5tokenizer = AutoTokenizer.from_pretrained("Akashpaul123/modernbert-crisis-detection")
6model = AutoModelForSequenceClassification.from_pretrained(
7 "Akashpaul123/modernbert-crisis-detection",
8 torch_dtype=torch.bfloat16,
9 attn_implementation="eager" # For compatibility
10)
11
12# Example usage
13def detect_crisis(text):
14 inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=8192)
15
16 # Remove token_type_ids (ModernBERT doesn't use them)
17 if 'token_type_ids' in inputs:
18 del inputs['token_type_ids']
19
20 with torch.no_grad():
21 outputs = model(**inputs)
22 probs = torch.softmax(outputs.logits, dim=-1)
23 crisis_prob = probs[0][1].item()
24
25 return {
26 'crisis_detected': crisis_prob > 0.5,
27 'confidence': crisis_prob,
28 'classification': 'CRISIS' if crisis_prob > 0.5 else 'SAFE'
29 }
30
31# Test examples
32examples = [
33 "I'm feeling great today and looking forward to the weekend!",
34 "I feel hopeless and don't see any point in continuing.",
35 "Just had a good conversation with my therapist."
36]
37
38for text in examples:
39 result = detect_crisis(text)
40 print(f"Text: {text}")
41 print(f"Result: {result['classification']} (confidence: {result['confidence']:.3f})")
42 print("---")1@model{modernbert-crisis-detection,
2 author = {Akash Paul},
3 title = {ModernBERT Crisis Detection: Fine-tuned Mental Health Crisis Detection},
4 year = {2024},
5 url = {https://huggingface.co/akashpaul123/modernbert-crisis-detection},
6 note = {Fine-tuned from answerdotai/ModernBERT-base}
7}