File size: 5,838 Bytes
8487231 | 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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import AutoTokenizer, AutoModel
class SharedEncoder(nn.Module):
def __init__(self, model_name):
super().__init__()
self.encoder = AutoModel.from_pretrained(model_name)
def mean_pool(self, hidden, mask):
mask = mask.unsqueeze(-1).expand(hidden.size()).float()
masked = hidden * mask
summed = masked.sum(1)
counts = mask.sum(1).clamp(min=1e-9)
return summed / counts
def forward(self, input_ids, attention_mask):
outputs = self.encoder(
input_ids=input_ids,
attention_mask=attention_mask
)
pooled = self.mean_pool(outputs.last_hidden_state, attention_mask)
pooled = F.normalize(pooled, p=2, dim=-1)
return pooled
class ClassifierHead(nn.Module):
def __init__(self, dim=768):
super().__init__()
self.net = nn.Sequential(
nn.Linear(dim, 256),
nn.ReLU(),
nn.Dropout(0.2),
nn.Linear(256, 1)
)
def forward(self, x):
return self.net(x).squeeze(-1)
def load_models():
device = "cuda" if torch.cuda.is_available() else "cpu"
model_name = "dbmdz/bert-base-turkish-cased"
encoder_path = "HomayShield_v5/homayshield_encoder.pt"
classifier_path = "HomayShield_v5/homayshield_classifier.pt"
attack_bank_path = "HomayShield_v5/homayshield_attack_bank.npy"
tokenizer = AutoTokenizer.from_pretrained(model_name)
encoder = SharedEncoder(model_name).to(device)
encoder.load_state_dict(torch.load(encoder_path, map_location=device))
encoder.eval()
classifier = ClassifierHead().to(device)
classifier.load_state_dict(torch.load(classifier_path, map_location=device))
classifier.eval()
attack_bank = np.load(attack_bank_path)
return tokenizer, encoder, classifier, attack_bank, device
def encode_text(text, tokenizer, encoder, device):
batch = tokenizer(
text,
truncation=True,
max_length=256,
padding="max_length",
return_tensors="pt"
)
batch = {k: v.to(device) for k, v in batch.items()}
with torch.no_grad():
emb = encoder(batch["input_ids"], batch["attention_mask"])
return emb[0].cpu().numpy()
def semantic_score(emb, attack_bank):
return float(np.max(attack_bank @ emb))
def predict(text, mode, config, tokenizer, encoder, classifier, attack_bank, device):
emb = encode_text(text, tokenizer, encoder, device)
attack_score = semantic_score(emb, attack_bank)
with torch.no_grad():
x = torch.tensor(emb).float().unsqueeze(0).to(device)
logits = classifier(x)
classifier_score = torch.sigmoid(logits).item()
if mode == "or":
label = "ATTACK" if (
attack_score >= config["semantic_threshold"] or
classifier_score >= config["classifier_threshold"]
) else "NORMAL"
elif mode == "fusion":
fusion_score = (
config["semantic_weight"] * attack_score +
config["classifier_weight"] * classifier_score
)
label = "ATTACK" if fusion_score >= config["fusion_threshold"] else "NORMAL"
elif mode == "semantic_only":
label = "ATTACK" if attack_score >= config["semantic_threshold"] else "NORMAL"
elif mode == "classifier_only":
label = "ATTACK" if classifier_score >= config["classifier_threshold"] else "NORMAL"
else:
raise ValueError("Invalid mode")
return {
"label": label,
"semantic_score": attack_score,
"classifier_score": classifier_score
}
def ask_mode():
print("\nSelect Mode:")
print("1 -> OR")
print("2 -> Fusion")
print("3 -> Semantic Only")
print("4 -> Classifier Only")
choice = input("Enter choice: ").strip()
mapping = {
"1": "or",
"2": "fusion",
"3": "semantic_only",
"4": "classifier_only"
}
if choice not in mapping:
raise ValueError("Invalid choice")
return mapping[choice]
def ask_thresholds(mode):
config = {}
if mode in ["or", "semantic_only"]:
config["semantic_threshold"] = float(
input("Semantic threshold (default 0.92): ") or 0.92
)
if mode in ["or", "classifier_only"]:
config["classifier_threshold"] = float(
input("Classifier threshold (default 0.80): ") or 0.80
)
if mode == "fusion":
config["semantic_weight"] = float(
input("Semantic weight (default 0.3): ") or 0.3
)
config["classifier_weight"] = float(
input("Classifier weight (default 0.7): ") or 0.7
)
config["fusion_threshold"] = float(
input("Fusion threshold (default 0.75): ") or 0.75
)
return config
def main():
tokenizer, encoder, classifier, attack_bank, device = load_models()
while True:
try:
mode = ask_mode()
config = ask_thresholds(mode)
text = input("\nEnter text to analyze:\n")
result = predict(
text,
mode,
config,
tokenizer,
encoder,
classifier,
attack_bank,
device
)
print("\n========== RESULT ==========")
print("Label:", result["label"])
print("Semantic Score:", result["semantic_score"])
print("Classifier Score:", result["classifier_score"])
again = input("\nAnalyze another? (y/n): ").strip().lower()
if again != "y":
break
except Exception as e:
print("Error:", e)
if __name__ == "__main__":
main()
|