1import torch
2import torch.nn as nn
3import json
4from transformers import AutoTokenizer, AutoModel
5
6class MaximDetector(nn.Module):
7 def __init__(self, model_name="microsoft/deberta-v3-base", num_maxims=4):
8 super().__init__()
9 self.encoder = AutoModel.from_pretrained(model_name)
10 hidden = self.encoder.config.hidden_size
11 self.classifiers = nn.ModuleList([
12 nn.Sequential(
13 nn.Dropout(0.15),
14 nn.Linear(hidden, hidden // 2), nn.GELU(),
15 nn.Dropout(0.15),
16 nn.Linear(hidden // 2, hidden // 4), nn.GELU(),
17 nn.Dropout(0.15),
18 nn.Linear(hidden // 4, 1)
19 ) for _ in range(num_maxims)
20 ])
21
22 def forward(self, input_ids, attention_mask):
23 outputs = self.encoder(input_ids=input_ids, attention_mask=attention_mask)
24 cls = outputs.last_hidden_state[:, 0, :]
25 return torch.cat([head(cls) for head in self.classifiers], dim=1)
26
27tokenizer = AutoTokenizer.from_pretrained("microsoft/deberta-v3-base")
28model = MaximDetector()
29state_dict = torch.load("pytorch_model.pt", map_location="cpu")
30model.load_state_dict(state_dict)
31model.eval()
32
33with open("temperatures.json") as f:
34 temperatures = json.load(f)
35
36def detect_violations(context: str, response: str, evidence: str = "") -> dict:
37 input_text = f"Context: {context}\nEvidence: {evidence}\nResponse: {response}"
38 inputs = tokenizer(
39 input_text, return_tensors="pt",
40 max_length=512, truncation=True, padding=True
41 )
42
43 maxim_names = ["quantity", "quality", "relation", "manner"]
44 temp_values = [
45 temperatures.get("quantity", 0.9),
46 temperatures.get("quality", 0.55),
47 temperatures.get("relation", 0.75),
48 temperatures.get("manner", 0.45),
49 ]
50
51 with torch.no_grad():
52 logits = model(**inputs)
53
54 probs, violations = {}, {}
55 for i, (maxim, temp) in enumerate(zip(maxim_names, temp_values)):
56 prob = torch.sigmoid(logits[0, i] / temp).item()
57 probs[maxim] = round(prob, 4)
58 violations[maxim] = prob > 0.5
59
60 return {
61 "violations": violations,
62 "probabilities": probs,
63 "is_cooperative": not any(violations.values())
64 }
65
66result = detect_violations(
67 context="What do you think about the latest developments in AI?",
68 response="Yes.",
69 evidence="AI has seen rapid advancement in large language models during 2024-2025."
70)
71print(result)