asahi417 commited on
Commit
efb026f
·
1 Parent(s): 070cd41
experiments/huggingface_ops.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from huggingface_hub import HfApi, ModelFilter
2
+ from pprint import pprint
3
+
4
+ api = HfApi()
5
+ models = api.list_models(filter=ModelFilter(author='tweettemposhift'))
6
+ models_filtered = [i.modelId for i in models if 'topic-' in i.modelId]
7
+
8
+ pprint(sorted([i for i in models_filtered if i.endswith('twitter-roberta-base-2019-90m')]))
9
+ pprint(sorted([i for i in models_filtered if i.endswith('twitter-roberta-base-dec2020')]))
experiments/main.sh CHANGED
@@ -1,22 +1,21 @@
1
  # MAIN EXPERIMENT
2
  MODEL="roberta-base"
3
  MODEL="vinai/bertweet-base"
4
- MODEL="cardiffnlp/twitter-roberta-base-2022-154m"
5
  MODEL="jhu-clsp/bernice"
6
- MODEL="cardiffnlp/twitter-roberta-base-2021-124m"
7
  MODEL="roberta-large"
8
-
9
- # topic, ner, nerd[hk], sentiment[ukri]
10
  MODEL="vinai/bertweet-large"
11
- # topic, ner, nerd[hk], sentiment[ukri]
 
 
 
12
  MODEL="cardiffnlp/twitter-roberta-large-2022-154m"
13
 
14
  # ABLATION (TimeLMs)
15
  ## Topic & NER
16
- MODEL="twitter-roberta-base-jun2020"
17
- MODEL="twitter-roberta-base-sep2021"
18
  ## NERD
19
- MODEL="twitter-roberta-base-jun2021"
20
 
21
  # SENTIMENT
22
  python model_finetuning_sentiment.py -m "${MODEL}" -d "sentiment_small_temporal"
 
1
  # MAIN EXPERIMENT
2
  MODEL="roberta-base"
3
  MODEL="vinai/bertweet-base"
 
4
  MODEL="jhu-clsp/bernice"
 
5
  MODEL="roberta-large"
 
 
6
  MODEL="vinai/bertweet-large"
7
+ MODEL="cardiffnlp/twitter-roberta-base-2019-90m"
8
+ MODEL="cardiffnlp/twitter-roberta-base-dec2020"
9
+ MODEL="cardiffnlp/twitter-roberta-base-2021-124m"
10
+ MODEL="cardiffnlp/twitter-roberta-base-2022-154m"
11
  MODEL="cardiffnlp/twitter-roberta-large-2022-154m"
12
 
13
  # ABLATION (TimeLMs)
14
  ## Topic & NER
15
+ MODEL="cardiffnlp/twitter-roberta-base-jun2020"
16
+ MODEL="cardiffnlp/twitter-roberta-base-sep2021"
17
  ## NERD
18
+ MODEL="cardiffnlp/twitter-roberta-base-jun2021"
19
 
20
  # SENTIMENT
21
  python model_finetuning_sentiment.py -m "${MODEL}" -d "sentiment_small_temporal"
experiments/model_predict_classifier.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Simple interface for CardiffNLP twitter models. """
2
+ import os
3
+ import torch
4
+ import re
5
+ import json
6
+ from typing import List, Dict
7
+
8
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoConfig
9
+ from datasets import load_dataset
10
+
11
+ URL_RE = re.compile(r"https?:\/\/[\w\.\/\?\=\d&#%_:/-]+")
12
+ HANDLE_RE = re.compile(r"@\w+")
13
+
14
+
15
+ def preprocess_bernice(text):
16
+ text = HANDLE_RE.sub("@USER", text)
17
+ text = URL_RE.sub("HTTPURL", text)
18
+ return text
19
+
20
+
21
+ def preprocess_timelm(text):
22
+ text = HANDLE_RE.sub("@user", text)
23
+ text = URL_RE.sub("http", text)
24
+ return text
25
+
26
+
27
+ def preprocess(model_name, text):
28
+ if model_name == "jhu-clsp/bernice":
29
+ return preprocess_bernice(text)
30
+ if "twitter-roberta-base" in model_name:
31
+ return preprocess_timelm(text)
32
+ return text
33
+
34
+
35
+ class Classifier:
36
+
37
+ def __init__(self,
38
+ model_name: str,
39
+ max_length: int,
40
+ multi_label: bool,
41
+ id_to_label: Dict[str, str]):
42
+
43
+ self.model_name = model_name
44
+ self.config = AutoConfig.from_pretrained(self.model_name)
45
+ self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
46
+ self.model = AutoModelForSequenceClassification.from_pretrained(self.model_name, config=self.config)
47
+ self.max_length = max_length
48
+ self.multi_label = multi_label
49
+ self.id_to_label = id_to_label
50
+ # GPU setup (https://github.com/cardiffnlp/tweetnlp/issues/15)
51
+ if torch.cuda.is_available() and torch.cuda.device_count() > 0:
52
+ self.device = torch.device("cuda")
53
+ elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available() and torch.backends.mps.is_built():
54
+ self.device = torch.device("mps")
55
+ else:
56
+ self.device = torch.device("cpu")
57
+ self.parallel = torch.cuda.device_count() > 1
58
+ if self.parallel:
59
+ self.model = torch.nn.DataParallel(self.model)
60
+ self.model.to(self.device)
61
+ self.model.eval()
62
+
63
+ def predict(self, text: List[str], batch_size: int):
64
+ text = [preprocess(self.model_name, t) for t in text]
65
+ indices = list(range(0, len(text), batch_size)) + [len(text) + 1]
66
+ probs = []
67
+ with torch.no_grad():
68
+ for i in range(len(indices) - 1):
69
+ encoded_input = self.tokenizer.batch_encode_plus(
70
+ text[indices[i]: indices[i+1]],
71
+ max_length=self.max_length,
72
+ return_tensors="pt",
73
+ padding=True,
74
+ truncation=True)
75
+ output = self.model(**{k: v.to(self.device) for k, v in encoded_input.items()})
76
+ if self.multi_label:
77
+ probs += torch.sigmoid(output.logits).cpu().tolist()
78
+ else:
79
+ probs += torch.softmax(output.logits, -1).cpu().tolist()
80
+ if self.multi_label:
81
+ return [{"label": [self.id_to_label[str(n)] for n, p in enumerate(_pr) if p > 0.5]} for _pr in probs]
82
+ return [{"label": self.id_to_label[str(p.index(max(p)))]} for p in probs]
83
+
84
+
85
+ class TopicClassification(Classifier):
86
+
87
+ id_to_label = {
88
+ '0': 'arts_&_culture',
89
+ '1': 'business_&_entrepreneurs',
90
+ '2': 'celebrity_&_pop_culture',
91
+ '3': 'diaries_&_daily_life',
92
+ '4': 'family',
93
+ '5': 'fashion_&_style',
94
+ '6': 'film_tv_&_video',
95
+ '7': 'fitness_&_health',
96
+ '8': 'food_&_dining',
97
+ '9': 'gaming',
98
+ '10': 'learning_&_educational',
99
+ '11': 'music',
100
+ '12': 'news_&_social_concern',
101
+ '13': 'other_hobbies',
102
+ '14': 'relationships',
103
+ '15': 'science_&_technology',
104
+ '16': 'sports',
105
+ '17': 'travel_&_adventure',
106
+ '18': 'youth_&_student_life'
107
+ }
108
+
109
+ def __init__(self, model_name: str):
110
+ super().__init__(model_name, max_length=128, multi_label=True, id_to_label=self.id_to_label)
111
+ self.dataset = load_dataset("tweettemposhift/tweet_temporal_shift", "topic_temporal")
112
+
113
+ def get_prediction(self, export_dir: str, batch_size: int):
114
+ os.makedirs(export_dir, exist_ok=True)
115
+ for test_split in ["test_1", "test_2", "test_3", "test_4"]:
116
+ data = self.dataset[test_split]
117
+ predictions = self.predict(data["text"], batch_size)
118
+ with open(f"{export_dir}/{test_split}.jsonl", "w") as f:
119
+ f.write("\n".join([json.dumps(i) for i in predictions]))
120
+
121
+
122
+ class SentimentClassification(Classifier):
123
+
124
+ id_to_label = {'0': '0', '1': '1'}
125
+
126
+ def __init__(self, model_name: str):
127
+ super().__init__(model_name, max_length=128, multi_label=False, id_to_label=self.id_to_label)
128
+ self.dataset = load_dataset("tweettemposhift/tweet_temporal_shift", "sentiment_temporal")
129
+
130
+ def get_prediction(self, export_dir: str, batch_size: int):
131
+ os.makedirs(export_dir, exist_ok=True)
132
+ for test_split in ["test_1", "test_2", "test_3", "test_4"]:
133
+ data = self.dataset[test_split]
134
+ predictions = self.predict(data["text"], batch_size)
135
+ with open(f"{export_dir}/{test_split}.jsonl", "w") as f:
136
+ f.write("\n".join([json.dumps(i) for i in predictions]))
137
+
138
+
139
+ class NERDClassification(Classifier):
140
+
141
+ id_to_label = {'0': '0', '1': '1'}
142
+
143
+ def __init__(self, model_name: str):
144
+ super().__init__(model_name, max_length=128, multi_label=False, id_to_label=self.id_to_label)
145
+ self.dataset = load_dataset("tweettemposhift/tweet_temporal_shift", "nerd_temporal")
146
+
147
+ def get_prediction(self, export_dir: str, batch_size: int):
148
+ os.makedirs(export_dir, exist_ok=True)
149
+ for test_split in ["test_1", "test_2", "test_3", "test_4"]:
150
+ data = self.dataset[test_split]
151
+ text = [
152
+ f"{d['target']} {self.tokenizer.sep_token} {d['definition']} {self.tokenizer.sep_token} {d['text']}"
153
+ for d in data
154
+ ]
155
+ predictions = self.predict(text, batch_size)
156
+ with open(f"{export_dir}/{test_split}.jsonl", "w") as f:
157
+ f.write("\n".join([json.dumps(i) for i in predictions]))
158
+
159
+
160
+ if __name__ == '__main__':
161
+ model_list = [
162
+ "roberta-base",
163
+ "bertweet-base",
164
+ "bernice",
165
+ "roberta-large",
166
+ "bertweet-large",
167
+ "twitter-roberta-base-2019-90m",
168
+ "twitter-roberta-base-dec2020",
169
+ "twitter-roberta-base-2021-124m",
170
+ "twitter-roberta-base-2022-154m",
171
+ "twitter-roberta-large-2022-154m"
172
+ ]
173
+ for model_m in model_list:
174
+ alias = f"tweettemposhift/topic-topic_temporal-{model_m}"
175
+ TopicClassification(alias).get_prediction(export_dir=f"prediction_files/{os.path.basename(alias)}", batch_size=512)
176
+ torch.cuda.empty_cache()
177
+ for random_r in range(4):
178
+ for seed_s in range(3):
179
+ alias = f"tweettemposhift/topic-topic_random{random_r}_seed{seed_s}-{model_m}"
180
+ TopicClassification(alias).get_prediction(export_dir=f"prediction_files/{os.path.basename(alias)}", batch_size=512)
181
+ torch.cuda.empty_cache()
182
+
183
+ for model_m in model_list:
184
+ alias = f"tweettemposhift/sentiment-sentiment_small_temporal-{model_m}"
185
+ SentimentClassification(alias).get_prediction(export_dir=f"prediction_files/{os.path.basename(alias)}", batch_size=512)
186
+ torch.cuda.empty_cache()
187
+ for random_r in range(4):
188
+ for seed_s in range(3):
189
+ alias = f"tweettemposhift/sentiment-sentiment_small_random{random_r}_seed{seed_s}-{model_m}"
190
+ SentimentClassification(alias).get_prediction(export_dir=f"prediction_files/{os.path.basename(alias)}", batch_size=512)
191
+ torch.cuda.empty_cache()
192
+
193
+ for model_m in model_list:
194
+ alias = f"tweettemposhift/nerd-nerd_temporal-{model_m}"
195
+ NERDClassification(alias).get_prediction(export_dir=f"prediction_files/{os.path.basename(alias)}", batch_size=512)
196
+ torch.cuda.empty_cache()
197
+ for random_r in range(4):
198
+ for seed_s in range(3):
199
+ alias = f"tweettemposhift/nerd-nerd_random{random_r}_seed{seed_s}-{model_m}"
200
+ NERDClassification(alias).get_prediction(export_dir=f"prediction_files/{os.path.basename(alias)}", batch_size=512)
201
+ torch.cuda.empty_cache()
experiments/model_predict_ner.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import os
3
+ import torch
4
+ import json
5
+ from typing import Dict, List
6
+ from transformers import AutoTokenizer, AutoModelForTokenClassification, AutoConfig
7
+ from datasets import load_dataset
8
+
9
+ URL_RE = re.compile(r"https?:\/\/[\w\.\/\?\=\d&#%_:/-]+")
10
+ HANDLE_RE = re.compile(r"@\w+")
11
+
12
+
13
+ def preprocess_bernice(text):
14
+ text = HANDLE_RE.sub("@USER", text)
15
+ text = URL_RE.sub("HTTPURL", text)
16
+ return text
17
+
18
+
19
+ def preprocess_timelm(text):
20
+ text = HANDLE_RE.sub("@user", text)
21
+ text = URL_RE.sub("http", text)
22
+ return text
23
+
24
+
25
+ def preprocess(model_name, text):
26
+ if model_name == "jhu-clsp/bernice":
27
+ return preprocess_bernice(text)
28
+ if "twitter-roberta-base" in model_name:
29
+ return preprocess_timelm(text)
30
+ return text
31
+
32
+
33
+ class NER:
34
+
35
+ def __init__(self, model_name: str, max_length: int, id_to_label: Dict[str, str]):
36
+ self.model_name = model_name
37
+ self.config = AutoConfig.from_pretrained(self.model_name)
38
+ self.model = AutoModelForTokenClassification.from_pretrained(self.model_name, config=self.config)
39
+ self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
40
+ self.max_length = max_length
41
+ self.id_to_label = id_to_label
42
+ # GPU setup (https://github.com/cardiffnlp/tweetnlp/issues/15)
43
+ if torch.cuda.is_available() and torch.cuda.device_count() > 0:
44
+ self.device = torch.device('cuda')
45
+ elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available() and torch.backends.mps.is_built():
46
+ self.device = torch.device("mps")
47
+ else:
48
+ self.device = torch.device('cpu')
49
+ self.parallel = torch.cuda.device_count() > 1
50
+ if self.parallel:
51
+ self.model = torch.nn.DataParallel(self.model)
52
+ self.model.to(self.device)
53
+ self.model.eval()
54
+ self.dataset = load_dataset("tweettemposhift/tweet_temporal_shift", "ner_temporal")
55
+
56
+ def get_prediction(self, export_dir: str, batch_size: int):
57
+ os.makedirs(export_dir, exist_ok=True)
58
+ for test_split in ["test_1", "test_2", "test_3", "test_4"]:
59
+ data = self.dataset[test_split]
60
+ predictions = self.predict(data["text"], batch_size)
61
+ with open(f"{export_dir}/{test_split}.jsonl", "w") as f:
62
+ f.write("\n".join([json.dumps(i) for i in predictions]))
63
+
64
+ with open(export_dir, "w") as f:
65
+ predictions = self.predict(self.dataset[], batch_size)
66
+ for i in :
67
+ f.write(json.dumps(i) + "\n")
68
+
69
+ def predict(self, text: List[str], batch_size: int):
70
+ text = [[preprocess(self.model_name, t) for t in i] for i in text]
71
+ indices = list(range(0, len(text), batch_size)) + [len(text) + 1]
72
+ inputs = []
73
+ preds = []
74
+ with torch.no_grad():
75
+ for i in range(len(indices) - 1):
76
+ encoded_input = self.tokenizer.batch_encode_plus(
77
+ text[indices[i]: indices[i + 1]],
78
+ max_length=self.max_length,
79
+ return_tensors='pt',
80
+ padding=True,
81
+ truncation=True)
82
+ inputs += encoded_input['input_ids'].cpu().detach().int().tolist()
83
+ output = self.model(**{k: v.to(self.device) for k, v in encoded_input.items()})
84
+ prob = torch.softmax(output['logits'], dim=-1).cpu().detach().float().tolist()
85
+ pred = torch.max(prob, dim=-1)[1].cpu().detach().int().tolist()
86
+ preds += [[self.id_to_label[_p] for _p in p] for p in pred]
87
+ return [{"label": p, "input_id": i} for p, i in zip(preds, inputs)]
88
+
89
+
90
+ if __name__ == '__main__':
91
+ model_list = [
92
+ "roberta-base",
93
+ "bertweet-base",
94
+ "bernice",
95
+ "roberta-large",
96
+ "bertweet-large",
97
+ "twitter-roberta-base-2019-90m",
98
+ "twitter-roberta-base-dec2020",
99
+ "twitter-roberta-base-2021-124m",
100
+ "twitter-roberta-base-2022-154m",
101
+ "twitter-roberta-large-2022-154m"
102
+ ]
103
+ for model_m in model_list:
104
+ alias = f"tweettemposhift/ner-ner_temporal-{model_m}"
105
+ NER(alias).get_prediction(export_dir=f"prediction_files/{os.path.basename(alias)}", batch_size=32)
106
+ for random_r in range(4):
107
+ for seed_s in range(3):
108
+ alias = f"tweettemposhift/ner-ner_random{random_r}_seed{seed_s}-{model_m}"
109
+ TopicClassification(alias).get_prediction(export_dir=f"prediction_files/{os.path.basename(alias)}", batch_size=32)
experiments/prediction.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import pipeline
2
+
3
+ pipe = pipeline(model="tweettemposhift/nerd-nerd_random1_seed2-twitter-roberta-base-2019-90m")
4
+ out = pipe("This restaurant is awesome")
5
+
6
+ pipe = pipeline(model="tweettemposhift/sentiment-sentiment_small_random3_seed2-twitter-roberta-base-dec2020")
7
+ pipe("This restaurant is awesome")
8
+
9
+ pipe = pipeline(model="tweettemposhift/topic-topic_random3_seed2-twitter-roberta-base-dec2020")
10
+ pipe("This restaurant is awesome")
11
+
12
+ pipe = pipeline(model="tweettemposhift/ner-ner_random1_seed2-twitter-roberta-base-2019-90m")
13
+ pipe("This restaurant is awesome")