""" Simple interface for CardiffNLP twitter models. """ import os import torch import re import json from typing import List, Dict from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoConfig from datasets import load_dataset URL_RE = re.compile(r"https?:\/\/[\w\.\/\?\=\d&#%_:/-]+") HANDLE_RE = re.compile(r"@\w+") def preprocess_bernice(text): text = HANDLE_RE.sub("@USER", text) text = URL_RE.sub("HTTPURL", text) return text def preprocess_timelm(text): text = HANDLE_RE.sub("@user", text) text = URL_RE.sub("http", text) return text def preprocess(model_name, text): if model_name == "jhu-clsp/bernice": return preprocess_bernice(text) if "twitter-roberta-base" in model_name: return preprocess_timelm(text) return text class Classifier: def __init__(self, model_name: str, max_length: int, multi_label: bool, id_to_label: Dict[str, str]): self.model_name = model_name self.config = AutoConfig.from_pretrained(self.model_name) self.tokenizer = AutoTokenizer.from_pretrained(self.model_name) self.model = AutoModelForSequenceClassification.from_pretrained(self.model_name, config=self.config) self.max_length = max_length self.multi_label = multi_label self.id_to_label = id_to_label # GPU setup (https://github.com/cardiffnlp/tweetnlp/issues/15) if torch.cuda.is_available() and torch.cuda.device_count() > 0: self.device = torch.device("cuda") elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available() and torch.backends.mps.is_built(): self.device = torch.device("mps") else: self.device = torch.device("cpu") self.parallel = torch.cuda.device_count() > 1 if self.parallel: self.model = torch.nn.DataParallel(self.model) self.model.to(self.device) self.model.eval() def predict(self, text: List[str], batch_size: int): text = [preprocess(self.model_name, t) for t in text] indices = list(range(0, len(text), batch_size)) + [len(text) + 1] probs = [] with torch.no_grad(): for i in range(len(indices) - 1): encoded_input = self.tokenizer.batch_encode_plus( text[indices[i]: indices[i+1]], max_length=self.max_length, return_tensors="pt", padding=True, truncation=True) output = self.model(**{k: v.to(self.device) for k, v in encoded_input.items()}) if self.multi_label: probs += torch.sigmoid(output.logits).cpu().tolist() else: probs += torch.softmax(output.logits, -1).cpu().tolist() if self.multi_label: return [{"label": [self.id_to_label[str(n)] for n, p in enumerate(_pr) if p > 0.5]} for _pr in probs] return [{"label": self.id_to_label[str(p.index(max(p)))]} for p in probs] class TopicClassification(Classifier): id_to_label = { '0': 'arts_&_culture', '1': 'business_&_entrepreneurs', '2': 'celebrity_&_pop_culture', '3': 'diaries_&_daily_life', '4': 'family', '5': 'fashion_&_style', '6': 'film_tv_&_video', '7': 'fitness_&_health', '8': 'food_&_dining', '9': 'gaming', '10': 'learning_&_educational', '11': 'music', '12': 'news_&_social_concern', '13': 'other_hobbies', '14': 'relationships', '15': 'science_&_technology', '16': 'sports', '17': 'travel_&_adventure', '18': 'youth_&_student_life' } def __init__(self, model_name: str): super().__init__(model_name, max_length=128, multi_label=True, id_to_label=self.id_to_label) self.dataset = load_dataset("tweettemposhift/tweet_temporal_shift", "topic_temporal") def get_prediction(self, export_dir: str, batch_size: int): os.makedirs(export_dir, exist_ok=True) for test_split in ["test_1", "test_2", "test_3", "test_4"]: if os.path.exists(f"{export_dir}/{test_split}.jsonl"): continue data = self.dataset[test_split] predictions = self.predict(data["text"], batch_size) with open(f"{export_dir}/{test_split}.jsonl", "w") as f: f.write("\n".join([json.dumps(i) for i in predictions])) class SentimentClassification(Classifier): id_to_label = {'0': '0', '1': '1'} def __init__(self, model_name: str): super().__init__(model_name, max_length=128, multi_label=False, id_to_label=self.id_to_label) self.dataset = load_dataset("tweettemposhift/tweet_temporal_shift", "sentiment_temporal") def get_prediction(self, export_dir: str, batch_size: int): os.makedirs(export_dir, exist_ok=True) for test_split in ["test_1", "test_2", "test_3", "test_4"]: if os.path.exists(f"{export_dir}/{test_split}.jsonl"): continue data = self.dataset[test_split] predictions = self.predict(data["text"], batch_size) with open(f"{export_dir}/{test_split}.jsonl", "w") as f: f.write("\n".join([json.dumps(i) for i in predictions])) class HateClassification(Classifier): id_to_label = {'0': '0', '1': '1'} def __init__(self, model_name: str): super().__init__(model_name, max_length=128, multi_label=False, id_to_label=self.id_to_label) self.dataset = load_dataset("tweettemposhift/tweet_temporal_shift", "hate_temporal") def get_prediction(self, export_dir: str, batch_size: int): os.makedirs(export_dir, exist_ok=True) for test_split in ["test_1", "test_2", "test_3", "test_4"]: if os.path.exists(f"{export_dir}/{test_split}.jsonl"): continue data = self.dataset[test_split] predictions = self.predict(data["text"], batch_size) with open(f"{export_dir}/{test_split}.jsonl", "w") as f: f.write("\n".join([json.dumps(i) for i in predictions])) class EmojiClassification(Classifier): def __init__(self, model_name: str): self.dataset = load_dataset("tweettemposhift/tweet_temporal_shift", "hate_temporal") id_to_label = {str(k): v for k, v in enumerate(self.dataset["test"].features["gold_label"].names)} super().__init__(model_name, max_length=128, multi_label=False, id_to_label=id_to_label) def get_prediction(self, export_dir: str, batch_size: int): os.makedirs(export_dir, exist_ok=True) for test_split in ["test_1", "test_2", "test_3", "test_4"]: if os.path.exists(f"{export_dir}/{test_split}.jsonl"): continue data = self.dataset[test_split] predictions = self.predict(data["text"], batch_size) with open(f"{export_dir}/{test_split}.jsonl", "w") as f: f.write("\n".join([json.dumps(i) for i in predictions])) class NERDClassification(Classifier): id_to_label = {'0': '0', '1': '1'} def __init__(self, model_name: str): super().__init__(model_name, max_length=128, multi_label=False, id_to_label=self.id_to_label) self.dataset = load_dataset("tweettemposhift/tweet_temporal_shift", "nerd_temporal") def get_prediction(self, export_dir: str, batch_size: int): os.makedirs(export_dir, exist_ok=True) for test_split in ["test_1", "test_2", "test_3", "test_4"]: if os.path.exists(f"{export_dir}/{test_split}.jsonl"): continue data = self.dataset[test_split] text = [ f"{d['target']} {self.tokenizer.sep_token} {d['definition']} {self.tokenizer.sep_token} {d['text']}" for d in data ] predictions = self.predict(text, batch_size) with open(f"{export_dir}/{test_split}.jsonl", "w") as f: f.write("\n".join([json.dumps(i) for i in predictions])) if __name__ == '__main__': model_list = [ "roberta-base", "bertweet-base", "bernice", "roberta-large", "bertweet-large", "twitter-roberta-base-2019-90m", "twitter-roberta-base-dec2020", "twitter-roberta-base-2021-124m", "twitter-roberta-base-2022-154m", "twitter-roberta-large-2022-154m" ] for model_m in model_list: alias = f"tweettemposhift/hate-hate_temporal-{model_m}" HateClassification(alias).get_prediction(export_dir=f"prediction_files/{os.path.basename(alias)}", batch_size=512) torch.cuda.empty_cache() for random_r in range(4): for seed_s in range(3): alias = f"tweettemposhift/hate-hate_random{random_r}_seed{seed_s}-{model_m}" HateClassification(alias).get_prediction(export_dir=f"prediction_files/{os.path.basename(alias)}", batch_size=512) torch.cuda.empty_cache() # for model_m in model_list: # alias = f"tweettemposhift/topic-topic_temporal-{model_m}" # TopicClassification(alias).get_prediction(export_dir=f"prediction_files/{os.path.basename(alias)}", batch_size=512) # torch.cuda.empty_cache() # for random_r in range(4): # for seed_s in range(3): # alias = f"tweettemposhift/topic-topic_random{random_r}_seed{seed_s}-{model_m}" # TopicClassification(alias).get_prediction(export_dir=f"prediction_files/{os.path.basename(alias)}", batch_size=512) # torch.cuda.empty_cache() # # for model_m in model_list: # alias = f"tweettemposhift/sentiment-sentiment_small_temporal-{model_m}" # SentimentClassification(alias).get_prediction(export_dir=f"prediction_files/{os.path.basename(alias)}", batch_size=512) # torch.cuda.empty_cache() # for random_r in range(4): # for seed_s in range(3): # alias = f"tweettemposhift/sentiment-sentiment_small_random{random_r}_seed{seed_s}-{model_m}" # SentimentClassification(alias).get_prediction(export_dir=f"prediction_files/{os.path.basename(alias)}", batch_size=512) # torch.cuda.empty_cache() # # for model_m in model_list: # alias = f"tweettemposhift/nerd-nerd_temporal-{model_m}" # NERDClassification(alias).get_prediction(export_dir=f"prediction_files/{os.path.basename(alias)}", batch_size=512) # torch.cuda.empty_cache() # for random_r in range(4): # for seed_s in range(3): # alias = f"tweettemposhift/nerd-nerd_random{random_r}_seed{seed_s}-{model_m}" # NERDClassification(alias).get_prediction(export_dir=f"prediction_files/{os.path.basename(alias)}", batch_size=512) # torch.cuda.empty_cache()