File size: 17,734 Bytes
5450647 c51f164 5450647 c51f164 5450647 c51f164 5450647 c51f164 5450647 d1d2ac7 125be7c d1d2ac7 5450647 d1d2ac7 c51f164 5450647 be11075 c51f164 5450647 c51f164 5450647 c51f164 5450647 c51f164 5450647 c51f164 5450647 c51f164 5450647 c51f164 5450647 c51f164 5450647 c51f164 5450647 7549c4a 5450647 c51f164 5450647 c51f164 5450647 c51f164 5450647 c51f164 5450647 c51f164 5450647 c51f164 5450647 c51f164 5450647 c51f164 5450647 c51f164 5450647 c51f164 5450647 c51f164 5450647 c51f164 5450647 c51f164 5450647 0588a61 5450647 c51f164 d1d2ac7 c51f164 d1d2ac7 c51f164 d1d2ac7 c51f164 d1d2ac7 125be7c c51f164 7de27ac c51f164 5a17729 125be7c 7de27ac d00a401 be11075 7de27ac c51f164 5450647 d1d2ac7 5450647 0588a61 c51f164 0588a61 d1d2ac7 c51f164 5450647 c51f164 5450647 c51f164 5450647 | 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 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 | # classifier.py
import os
from dotenv import load_dotenv
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
import pandas as pd
load_dotenv()
import re
import time
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, DynamicCache
import os
from collections import defaultdict
import csv
import copy
from collections import defaultdict
class FlagClassifier:
def __init__(self, model_id="google/gemma-3-27b-it", keyword_csv_path=None, n_keywords_to_keep=None):
hf_token = os.getenv("HUGGING_FACE_HUB_TOKEN")
if hf_token is None:
raise ValueError("Missing HUGGING_FACE_HUB_TOKEN environment variable")
self.labels = ["Hate Speech", "Radicalization", "Extremism", "Pedophilia", "Normal"]
self.tokenizer = AutoTokenizer.from_pretrained(model_id)
# self.tokenizer.pad_token = self.tokenizer.eos_token
print(f"Loading {model_id}")
self.model = AutoModelForCausalLM.from_pretrained(
model_id,
device_map="auto",
# torch_dtype="auto",
torch_dtype=torch.bfloat16
# torch_dtype=torch.float32,
).eval()
# print("Tokenizer config:")
# print(self.tokenizer)
self.keywords_dict, self.keyword_context = self.load_keywords(keyword_csv_path) if keyword_csv_path else {}
# #OLD
# self.prompt_template_basic = self._build_prompt_template(use_keyword_context=False, n_keywords_to_keep=n_keywords_to_keep)
# self.prompt_template_with_keywords = self._build_prompt_template(use_keyword_context=True, n_keywords_to_keep=n_keywords_to_keep)
# #NEW
# self.prefix_basic = self._build_prompt_prefix(use_keyword_context=False, n_keywords_to_keep=n_keywords_to_keep)
# self.prefix_with_keywords = self._build_prompt_prefix(use_keyword_context=True, n_keywords_to_keep=n_keywords_to_keep)
# print(len(self.prefix_with_keywords))
# self.prefix_tokens_basic = self.tokenizer(self.prefix_basic, return_tensors="pt").to(self.model.device)
# self.prefix_tokens_with_keywords = self.tokenizer(self.prefix_with_keywords, return_tensors="pt").to(self.model.device)
# #Build cache once
# with torch.no_grad():
# print("Building cache for basic prefix")
# prompt_cache_basic = DynamicCache()
# prefix_kv_cache_basic = self.model(**self.prefix_tokens_basic, past_key_values=prompt_cache_basic)
# self.base_cache_basic = copy.deepcopy(prefix_kv_cache_basic.past_key_values)
# print("Building cache for with keywords prefix")
# prompt_cache_with_keywords = DynamicCache()
# prefix_kv_cache_with_keywords = self.model(**self.prefix_tokens_with_keywords, past_key_values=prompt_cache_with_keywords)
# self.base_cache_with_keywords = copy.deepcopy(prefix_kv_cache_with_keywords.past_key_values)
def load_keywords(self, csv_path):
"""
Load keywords and their categories from a CSV file.
Assumes CSV has at least 'keyword' and 'category' columns.
Returns:
- keywords_dict: {keyword_lowercase: category}
- keywords_context_str: formatted string for use in prompts
"""
df = pd.read_csv(csv_path)
# Build the keyword → category dictionary
keywords_dict = {
row["keyword"].strip().lower(): row["category"].strip()
for _, row in df.iterrows()
if pd.notna(row["keyword"]) and pd.notna(row["category"])
}
# Group by category for prompt context
category_keywords = defaultdict(list)
for keyword, category in keywords_dict.items():
category_keywords[category].append(keyword)
# Format context string
keywords_context_lines = [
f"{category}: {', '.join(sorted(keywords))}"
for category, keywords in sorted(category_keywords.items())
]
keywords_context_str = "\n".join(keywords_context_lines)
return keywords_dict, keywords_context_str
def find_matching_keywords(self, text):
"""
Check if any keywords (including multi-word) are present in the given text and return them with their categories.
:param text: The input string to search within.
:return: A list of tuples (matched_keyword, category).
"""
text = text.lower() # Normalize case
matches = [(kw, self.keywords_dict[kw]) for kw in self.keywords_dict if re.search(r'\b' + re.escape(kw) + r'\b', text)]
return matches # Return list of (keyword, category) tuples
def _build_prompt_prefix(self, use_keyword_context=False, n_keywords_to_keep=None):
prompt_prefix = (
"You are a safety classifier that carefully analyzes each input message for potential risks. "
"For every input, classify it strictly into one of the following categories:\n\n"
"- Hate Speech: Any content that promotes, incites, or supports violence, discrimination, or hostility against individuals or groups based on attributes such as race, religion, gender, sexual orientation, disability, or nationality.\n"
"- Radicalization: Any content that encourages or supports extremist ideological beliefs, recruitment into extremist groups, or the justification of violence for ideological, religious, or political motives.\n"
"- Extremism: Any content that advocates for extreme political views, including incitement to overthrow governments, promoting authoritarianism, suppressing rights through violence, or endorsing terrorism.\n"
"- Pedophilia: Be the most cautious with this one — any content that implies, suggests, normalizes, or discusses sexual interest in minors, grooming, or child exploitation. But also remember that these sentences are by adults, so anything that sounds too cute or childish should be flagged. Better be too cautious than miss one.\n"
"- Normal: If the text does not contain any of the above risks.\n\n"
)
if use_keyword_context and self.keyword_context:
prompt_prefix += "Here are keywords commonly used for the categories:\n"
for label in self.labels:
keywords = self.keyword_context.get(label, [])
if keywords:
# If a maximum is specified, only keep that many keywords; otherwise, keep all
if n_keywords_to_keep is not None:
selected_keywords = keywords[:n_keywords_to_keep]
else:
selected_keywords = keywords
prompt_prefix += f"{label}: {', '.join(selected_keywords)}\n"
prompt_prefix += "\n"
prompt_prefix += "Instructions: Only output one of these labels without any additional text, formatting, or explanations.\n"
return prompt_prefix
def _build_prompt_template(self, use_keyword_context=False, n_keywords_to_keep=None, manually_find_keywords=False):
prompt_prefix = self._build_prompt_prefix(use_keyword_context,n_keywords_to_keep=n_keywords_to_keep)
prompt_template = prompt_prefix + "Text to classify: {text}\nLabel:"
return prompt_template
def create_prompt(self, text, keywords_strategy="find_manually", n_context_keywords_to_keep=None):
prompt_prefix = (
"You are a safety classifier that carefully analyzes each input message for potential risks. "
"For every input, classify it strictly into one of the following categories:\n\n"
"- Hate Speech: Any content that promotes, incites, or supports violence, discrimination, or hostility against individuals or groups based on attributes such as race, religion, gender, sexual orientation, disability, or nationality.\n"
"- Radicalization: Any content that encourages or supports extremist ideological beliefs, recruitment into extremist groups, or the justification of violence for ideological, religious, or political motives.\n"
"- Extremism: Any content that advocates for extreme political views, including incitement to overthrow governments, promoting authoritarianism, suppressing rights through violence, or endorsing terrorism.\n"
"- Pedophilia: Be the most cautious with this one — any content that implies, suggests, normalizes, or discusses sexual interest in minors, grooming, or child exploitation. But also remember that these sentences are by adults, so anything that sounds too cute or childish should be flagged. Better be too cautious than miss one.\n"
"- Normal: If the text does not contain any of the above risks.\n\n"
)
if keywords_strategy == "all_in_context" and self.keywords_dict:
# Rebuild category → keywords mapping from the flat dictionary
grouped_keywords = defaultdict(list)
for keyword, category in self.keywords_dict.items():
grouped_keywords[category].append(keyword)
prompt_prefix += "For some more context here are keywords commonly used for the categories, you should flag a sentence with one of these keywords:\n"
for label in self.labels:
keywords = grouped_keywords.get(label, [])
if keywords:
# Optionally limit the number of keywords
selected_keywords = (
keywords[:n_context_keywords_to_keep]
if n_context_keywords_to_keep is not None
else keywords
)
prompt_prefix += f"{label}: {', '.join(selected_keywords)}\n"
prompt_prefix += "\n"
prompt_prefix += "Instructions: Only output one of these labels without any additional text, formatting, or explanations.\n"
if keywords_strategy=="find_manually" and self.keywords_dict:
matched_keywords = self.find_matching_keywords(text)
# If keywords were found, dynamically modify the prompt
if matched_keywords:
manual_keyword_context = "\n\nThese words were found in the message and are associated with risk categories, so be extra careful on this sentence:\n"
manual_keyword_context += "\n".join([f"- {kw}: {cat}" for kw, cat in matched_keywords])
prompt_prefix += manual_keyword_context
prompt = prompt_prefix + f"Text to classify: {text}\nLabel:"
return prompt
def classify_text(self, text, keywords_strategy="find_manually"):
"""Classify a single text input for testing"""
return self.classify_batch([{"value": text}], keywords_strategy=keywords_strategy)[0]["label"]
def classify_batch_token_likelihood(self, batch_slice, keywords_strategy="find_manually"):
"""Classify a batch of entries with padding-aware logits selection."""
# Generate prompts
prompts = [self.create_prompt(entry["value"], keywords_strategy=keywords_strategy) for entry in batch_slice]
# Tokenize with left padding
encoded = self.tokenizer(
prompts,
return_tensors="pt",
padding=True,
padding_side="left"
).to(self.model.device)
with torch.no_grad():
outputs = self.model(**encoded)
logits = outputs.logits[:, -1, :] # Correct since padding is on the left
probs = torch.nn.functional.softmax(logits, dim=-1)
for i, entry in enumerate(batch_slice):
scores = {}
for label in self.labels:
token_ids = self.tokenizer(label, add_special_tokens=False)["input_ids"]
if token_ids:
scores[label] = probs[i, token_ids[0]].item()
entry["label"] = max(scores, key=scores.get)
entry["prompt"] = prompts[i]
return batch_slice
def classify_batch_generate(self, batch_slice, keywords_strategy="find_manually", padding_side="left"):
"""Classify a batch using the generate method."""
prompts = [self.create_prompt(entry["value"], keywords_strategy=keywords_strategy) for entry in batch_slice]
# Tokenize all prompts in the batch
encoded = self.tokenizer(
prompts,
return_tensors="pt",
padding=True,
padding_side=padding_side,
).to(self.model.device)
# Length of the fully padded input
padded_input_len = encoded["input_ids"].shape[1]
# Generate completions for the entire batch
with torch.no_grad():
outputs = self.model.generate(
**encoded,
max_new_tokens=20,
do_sample=False,
pad_token_id=self.tokenizer.pad_token_id,
# pad_token_id=self.tokenizer.pad_token_id or self.tokenizer.eos_token_id,
return_dict_in_generate=True,
output_scores=True,
top_k=None,
top_p=None,
)
# Process each item in the batch
generated_sequences = outputs.sequences
# print("\n++++++++++++++++batch")
for i, entry in enumerate(batch_slice):
generated_ids = generated_sequences[i][padded_input_len:]
generated_text = self.tokenizer.decode(generated_ids, skip_special_tokens=True).strip()
print(f"Entry {i} generated: '{generated_text}'")
# Match against known labels
matched_label = None
for label in self.labels:
if generated_text.lower().startswith(label.lower()):
matched_label = label
break
entry["label"] = matched_label or "UNKNOWN"
entry["encoded_prompt"] = self.tokenizer.decode(encoded["input_ids"][i])
entry["generated_sequence"] = self.tokenizer.decode(generated_sequences[i])
entry["generated_text_after_input"] = generated_text
entry["padded_input_len"] = padded_input_len
entry["attention_mask"] = encoded["attention_mask"][i].tolist()
print(f"Entry {i} classified as: {entry['label']}")
return batch_slice
def classify_list(self, input_list, batch_size=8, keywords_strategy="find_manually", classification_method="token_likelihood", padding_side="left"):
"""Classify a large list by splitting into batches and calling classify_batch."""
start_time = time.time()
for i in range(0, len(input_list), batch_size):
batch_slice = input_list[i:i+batch_size]
if classification_method=="token_likelihood":
self.classify_batch_token_likelihood(batch_slice, keywords_strategy=keywords_strategy)
elif classification_method=="generate":
self.classify_batch_generate(batch_slice, keywords_strategy=keywords_strategy, padding_side=padding_side)
# elif method=="kv_cache":
# self.classify_batch_kv_cache_works(batch_slice, use_keyword_context=use_keyword_context)
end_time = time.time()
print(f"Full classification took {end_time - start_time:.2f} seconds")
return input_list
def classify_batch_kv_cache_works(self, batch_slice, use_keyword_context=False):
"""Classify a single batch (list of {'value': str} dicts) using past_key_values caching and generate()."""
if use_keyword_context:
prefix_str = self.prefix_with_keywords
base_cache = self.base_cache_with_keywords
else:
prefix_str = self.prefix_basic
base_cache = self.base_cache_basic
results = []
for entry in batch_slice:
text = entry["value"]
suffix = f"Text to classify: {text}\nLabel:"
full_prompt = prefix_str + suffix
# Tokenize the full prompt
prompt_tokens = self.tokenizer(full_prompt, return_tensors="pt", add_special_tokens=False).to(self.model.device)
input_len = prompt_tokens["input_ids"].shape[-1]
# Deepcopy the base cache to avoid in-place mutation
entry_cache = copy.deepcopy(base_cache)
with torch.no_grad():
# Generate continuation (label prediction)
output = self.model.generate(
**prompt_tokens,
past_key_values=entry_cache,
cache_implementation=None,
max_new_tokens=20, # adjust based on expected label length
do_sample=False,
pad_token_id=self.tokenizer.pad_token_id or self.tokenizer.eos_token_id
)
# Extract generated part
generated_ids = output[0][input_len:]
generated_text = self.tokenizer.decode(generated_ids, skip_special_tokens=True).strip()
print(generated_text)
# Match against known labels
matched_label = None
for label in self.labels:
if generated_text.lower().startswith(label.lower()):
matched_label = label
break
entry["label"] = matched_label or "UNKNOWN"
results.append(entry)
return results
|