# 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