wetey commited on
Commit
78dac5f
·
1 Parent(s): 6d62685

english trained model

Browse files
config.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "distilbert-base-uncased",
3
+ "activation": "gelu",
4
+ "architectures": [
5
+ "DistilBertForSequenceClassification"
6
+ ],
7
+ "attention_dropout": 0.1,
8
+ "dim": 768,
9
+ "dropout": 0.1,
10
+ "hidden_dim": 3072,
11
+ "id2label": {
12
+ "0": "LABEL_0",
13
+ "1": "LABEL_1",
14
+ "2": "LABEL_2"
15
+ },
16
+ "initializer_range": 0.02,
17
+ "label2id": {
18
+ "LABEL_0": 0,
19
+ "LABEL_1": 1,
20
+ "LABEL_2": 2
21
+ },
22
+ "max_position_embeddings": 512,
23
+ "model_type": "distilbert",
24
+ "n_heads": 12,
25
+ "n_layers": 6,
26
+ "pad_token_id": 0,
27
+ "problem_type": "single_label_classification",
28
+ "qa_dropout": 0.1,
29
+ "seq_classif_dropout": 0.2,
30
+ "sinusoidal_pos_embds": false,
31
+ "tie_weights_": true,
32
+ "torch_dtype": "float32",
33
+ "transformers_version": "4.35.0",
34
+ "vocab_size": 30522
35
+ }
hierarchical_summarization.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from groq import Groq
2
+ import pandas as pd
3
+ import os
4
+ from scipy.cluster.hierarchy import linkage
5
+ import numpy as np
6
+ from scipy.cluster import hierarchy
7
+ from tqdm import tqdm
8
+ from sentence_transformers import SentenceTransformer
9
+ from scipy.spatial.distance import cosine
10
+
11
+ def convert_labels(dataset):
12
+ labels = dataset.label.unique()
13
+ labels_mapping = {}
14
+
15
+ for label in labels:
16
+ pred = dataset.loc[dataset['label'] == label, 'label_y'].values[0]
17
+ labels_mapping[label] = pred
18
+
19
+ for label in labels_mapping:
20
+ dataset.loc[dataset.pred == label, 'pred_label'] = labels_mapping[label]
21
+ return dataset
22
+
23
+ def add_labels(dataset, original_dataset):
24
+
25
+ original_dataset = original_dataset.rename(columns={'text':'content'})
26
+ original_dataset = original_dataset[['content', 'label_y']]
27
+ #content column to compare with original dataset
28
+ dataset_content = dataset.content
29
+ #retrieve all columns for each row in test set from original dataset
30
+ subset_original_content = original_dataset.loc[original_dataset.content.isin(dataset_content)]
31
+ #merge dataframes
32
+ dataset = pd.merge(dataset, subset_original_content, on = 'content')
33
+ dataset = convert_labels(dataset)
34
+
35
+ return dataset
36
+
37
+
38
+ def tree_depth(node):
39
+ if node is None:
40
+ return 0
41
+ else:
42
+ left_depth = tree_depth(node.get_left())
43
+ right_depth = tree_depth(node.get_right())
44
+ return max(left_depth, right_depth) + 1
45
+
46
+ def reconstruct_tree(mergings, content):
47
+ tree = {}
48
+ for i, merge in enumerate(mergings):
49
+ #these are the leaves, they'll have an index less than the number of examples
50
+ if merge[0] <= len(mergings):
51
+ a = content[int(merge[0]) - 1]
52
+ else:
53
+ #if here then that's a merged cluster
54
+ a = tree[int(merge[0])]
55
+ #these are the leaves, they'll have an index less than the number of examples
56
+ if merge[1] <= len(mergings):
57
+ b = content[int(merge[1]) - 1]
58
+ else:
59
+ #if here then that's a merged cluster
60
+ b = tree[int(merge[1])]
61
+ tree[1 + i + len(mergings)] = [a,b]
62
+ return tree
63
+
64
+ #remove nested lists in branches and put all nodes in a 1-D list
65
+ def flatten(dict_list):
66
+ flat_list = []
67
+ for item in dict_list:
68
+ if isinstance(item, list):
69
+ flat_list.extend(flatten(item))
70
+ else:
71
+ flat_list.append(item)
72
+ return flat_list
73
+
74
+ #pass prompt to llm
75
+ def get_answer(prompt, system_prompt):
76
+
77
+ chat_completion = client.chat.completions.create(
78
+ messages=[
79
+ {
80
+ "role":"system",
81
+ "content":f"{system_prompt}"
82
+ },
83
+ {
84
+ "role": "user",
85
+ "content": f"{prompt}",
86
+ }
87
+ ],
88
+ model="mixtral-8x7b-32768"
89
+ )
90
+ return chat_completion.choices[0].message.content
91
+
92
+ #pass two leaves to the llm and get a list of their similarities
93
+ #leaf will have the content, predicted label, and actual label
94
+ def merge_two_leaves(leaf_0, leaf_1):
95
+
96
+ system_prompt =f'You are given two statements from an offensive language dataset that were misclassified by an offensive language detection system. Analyze the two statements thoroughly and provide a bullet list explanation of the similarities between the two statements. Your list should have the following format: * Error_Feature: <Explanation> where Error_Feature: is a two word discription of the feature and Explanation is a one sentence explanation of the feature. Make sure to stick to the format specified. Avoid making explicit references to the examples and use layman terms for the explanations.'
97
+
98
+ prompt = f'Statement_0: {leaf_0.content}\npredicted_label_0: {leaf_0.predicted_label}\nactual_label_0: {leaf_0.actual_label}\n\nStatement_1: {leaf_1.content}\npredicted_label_1: {leaf_1.predicted_label}\nactual_label_1: {leaf_1.actual_label}\n\nList: '
99
+
100
+ #pass prompts to llm and get answer
101
+ base_list = get_answer(prompt, system_prompt)
102
+
103
+ return base_list
104
+
105
+ #case 2: pass leaf (with content, predicted label, and actual label) and the list previously generated
106
+ def applies(leaf, list, threshold = 2): #another way to do this would be to split the list and check every bullet points -> more api calls
107
+
108
+ system_prompt = f"You are given a statement from an offensive language dataset that was misclassified by an offensive language detection system. In addition, you are given a list of features generated by an LLM for other statements that were misclassified. Perform a thorough analysis of the statement and the list. If at least {threshold} points apply to the statement return YES otherwise return NO."
109
+
110
+ prompt = f"Statement: {leaf.content}\npredicted_label: {leaf.predicted_label}\nactual_label: {leaf.actual_label}\n\nList: {list}\n\nAnswer: "
111
+
112
+ #convert answer to all lower case to avoid llm inconsistency
113
+ check = get_answer(prompt, system_prompt).lower()
114
+
115
+ #if yes return true otherwise return false
116
+ return 'yes' in check
117
+
118
+ def merge_leaf(leaf, list):
119
+
120
+ system_prompt = f"You are given a statement from an offensive language dataset that was misclassified by an offensive language detection system. In addition, you are given a list of features generated by an LLM for other statements that were misclassified. Make the minimal changes so the list also applies to the given statement. Maintain the same format * Error_Feature: <Explanation> where Error_Feature: is a two word discription of the feature and Explanation is a one sentence explanation of the feature. Make sure to stick to the format specified. Avoid making explicit references to the examples and use layman terms for the explanations. "
121
+
122
+ prompt = f"Statement: {leaf.content}\npredicted_label: {leaf.predicted_label}\nactual_label: {leaf.actual_label}\n\nList: {list}\n\nUpdated list: "
123
+
124
+ if applies(leaf, list):
125
+ return 'edited', get_answer(prompt, system_prompt)
126
+ else:
127
+ return 'not edited', list
128
+
129
+ def get_bullet_points(list):
130
+ #split on new line to get the individual bullet points
131
+ return list.split('\n')
132
+
133
+ def construct_bipartite_graph(bullet_list_0, bullet_list_1):
134
+ bipartite_graph = []
135
+ for first in bullet_list_0: #o(n)
136
+ for second in bullet_list_1: #o(m)
137
+ if ((first, second) and (second, first)) not in bipartite_graph: #check pair is not already in list, order doesn't matter, o(k)
138
+ bipartite_graph.append((first,second))
139
+ return bipartite_graph
140
+
141
+ def sbert_embeddings(bipartite_graph):
142
+ sbert_bipartite_graph = []
143
+ for pair in bipartite_graph:
144
+ first = sbert_model.encode(pair[0])
145
+ second = sbert_model.encode(pair[1])
146
+ sbert_bipartite_graph.append((first, second))
147
+ return sbert_bipartite_graph
148
+
149
+ def compute_cosine_similarity(sbert_bipartite_embeddings):
150
+ cosine_similarity = []
151
+ for pair in sbert_bipartite_embeddings:
152
+ similarity = 1 - cosine(pair[0], pair[1])
153
+ cosine_similarity.append(similarity)
154
+ return cosine_similarity
155
+
156
+ def combine(cosine_similarity, bipartite_graph, similarity_threshold):
157
+ pairs_to_combine = []
158
+ for index in range(len(cosine_similarity)):
159
+ if cosine_similarity[index] > similarity_threshold: #there needs to be a different threshold/criteria
160
+ pairs_to_combine.append(bipartite_graph[index])
161
+ return pairs_to_combine
162
+
163
+ #check the overlap between the two lists
164
+ def overlap(list_0, list_1, overlap_threshold = 0.5, similarity_threshold = 0.75):
165
+ #step 0: separate the list to individual bullet points
166
+ bullet_list_0 = get_bullet_points(list_0)
167
+ bullet_list_1 = get_bullet_points(list_1)
168
+
169
+ #step 1: construct a bipartite graph
170
+ bipartite_graph = construct_bipartite_graph(bullet_list_0, bullet_list_1)
171
+
172
+ #step 2: compute the sbert embeddings
173
+ sbert_bipartite_graph = sbert_embeddings(bipartite_graph)
174
+
175
+ #step 3: calculate the cosine similarity
176
+ cosine_similarity = compute_cosine_similarity(sbert_bipartite_graph)
177
+
178
+ #step 4: if similarity above threshold -> combine otherwise leave as separate
179
+ pairs_to_combine = combine(cosine_similarity, bipartite_graph, similarity_threshold)
180
+
181
+ #step 5: increment overlap score
182
+ overlap_score = len(pairs_to_combine) / len(bipartite_graph)
183
+
184
+ #step 6: if score is more than overlap_threshold -> pair should be combined (save this pair)
185
+ return overlap_score > overlap_threshold, bipartite_graph, pairs_to_combine
186
+
187
+ def union(bipartite_graph, pairs_to_combine):
188
+
189
+ #to get the union
190
+ #step 0: remove the pairs_to_combine from bipartite_graph
191
+ bipartite_graph = [pair for pair in bipartite_graph if pair not in pairs_to_combine]
192
+
193
+ #step 1: remove all the pairs where one of the elements is also in pairs_to_combine
194
+ #step 1.1: convert pair_to_combine to a set
195
+ distinct_features = set()
196
+ for pair in pairs_to_combine:
197
+ distinct_features.add(pair[0])
198
+ distinct_features.add(pair[1])
199
+
200
+ #step 1.2: remove the any pairs that have elements in pairs_to_combine
201
+ bipartite_graph = [pair for pair in bipartite_graph if pair[0] or pair[1] not in distinct_features]
202
+
203
+ dont_combine = set()
204
+ for pair in bipartite_graph:
205
+ dont_combine.add(pair[0])
206
+ dont_combine.add(pair[1])
207
+
208
+ return dont_combine
209
+
210
+ #take the union between the lists
211
+ def list_union(bipartite_graph, pairs_to_combine):
212
+
213
+ dont_combine = union(bipartite_graph, pairs_to_combine)
214
+ union_list = '\n'.join(dont_combine)
215
+
216
+ system_prompt = f"You are given two bullet points generated to explain similarities between statements. You are tasked to combine these two bullet points into one. Make sure to maintain the same format * Error_Feature: <Explanation> where Error_Feature: is a two word discription of the feature and Explanation is a one sentence explanation of the feature. Make sure to stick to the format specified."
217
+
218
+ for pair in pairs_to_combine:
219
+ prompt = f"First point: {pair[0]}\n\nSecond point: {pair[1]}\n\nNew point: "
220
+ union_list += get_answer(prompt, system_prompt) + '\n'
221
+
222
+ return union_list
223
+
224
+ #read data
225
+ dataset = pd.read_json("improved_english/clusters/baseline_sb.json")
226
+ original_dataset = pd.read_csv('clusters/mhs_lhs_errors.csv')
227
+
228
+ #this is using one of the sbert clustering but we just want to the embeddings and content (maybe labels)
229
+ dataset.drop(['slice', 'centroid', 'cluster'], inplace=True, axis=1)
230
+ dataset = add_labels(dataset, original_dataset)
231
+ dataset = dataset.rename(columns={'label_y':'actual_label', 'pred_label':'predicted_label'})
232
+
233
+ #generate the hierarchical tree
234
+ mergings = linkage(np.array(dataset.embedding.to_list()), method='complete', metric='cosine')
235
+
236
+ #convert to a tree to traverse
237
+ root, nodelist = hierarchy.to_tree(mergings, rd = True)
238
+
239
+ #construct tree using examples
240
+ tree = reconstruct_tree(mergings, dataset.content.to_list())
241
+
242
+ client = Groq(
243
+ api_key=os.environ.get("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"),
244
+ )
245
+ #load sbert model
246
+ sbert_model = SentenceTransformer('all-distilroberta-v1')
247
+
248
+ #store the intermediate steps
249
+ intermediate_steps = []
250
+ end_summaries = []
251
+
252
+ for id, node in tqdm(enumerate(mergings)):
253
+
254
+ #first case: if both are leaves -> send to llm
255
+ if node[0] <= len(mergings) and node[1] <= len(mergings):
256
+ #pass two leaves
257
+ leaf_0 = dataset.iloc[[int(node[0])]]
258
+ leaf_1 = dataset.iloc[[int(node[1])]]
259
+ leaf_list = merge_two_leaves(leaf_0, leaf_1)
260
+ current = {'id': int(id + len(mergings) + 1), #index in mergings DS + number of clusters idk if this correct
261
+ 'examples': [[leaf_0.content,
262
+ leaf_0.predicted_label,
263
+ leaf_0.actual_label,
264
+ int(node[0])],
265
+ [leaf_1.content,
266
+ leaf_1.predicted_label,
267
+ leaf_1.actual_label,
268
+ int(node[1])]],
269
+ 'bullet_list': leaf_list,
270
+ 'edited': 'both are leaves',
271
+ 'previous_list': 'base list'}
272
+
273
+ #second case: if you're merging a leaf to a merged cluster -> send to check if it applies
274
+ elif (node[0] >= len(mergings)) ^ (node[1] >= len(mergings)):
275
+
276
+ #use the cluster id of the merged list to get the previous list
277
+ if node[0] <= len(mergings):
278
+ leaf = dataset.iloc[[int(node[0])]]
279
+ previous_list = int(node[1]) #this is the id
280
+ leaf_id = int(node[0])
281
+ else: #I don't think this will ever be executed idk
282
+ leaf = dataset.iloc[[int(node[1])]]
283
+ previous_list = int(node[0]) #this is the id
284
+ leaf_id = int(node[1])
285
+
286
+ previous_bullet_list = next(item for item in intermediate_steps if item['id'] == previous_list)
287
+ previous_bullet_list = previous_bullet_list['bullet_list']
288
+
289
+ #pass the previous list
290
+ edited, merged_leaf = merge_leaf(leaf, previous_bullet_list) #hyperparameter threshold (how many points apply to the example)
291
+
292
+ #store the list and examples and verdict so they're easy to retrieve
293
+ current = {'id':int(id + len(mergings) + 1), #index in mergings DS + number of clusters
294
+ 'examples': [leaf.content,
295
+ leaf.predicted_label,
296
+ leaf.actual_label,
297
+ leaf_id],
298
+ 'bullet_list': merged_leaf,
299
+ 'edited': edited,
300
+ 'previous_list':previous_list
301
+ }
302
+
303
+ #third case: merging to clusters
304
+ else:
305
+ #get the list generated at each node
306
+ list_0 = next(item for item in intermediate_steps if item['id'] == int(node[0]))
307
+ list_0_id = list_0['bullet_list']
308
+
309
+ list_1 = next(item for item in intermediate_steps if item['id'] == int(node[1]))
310
+ list_1_id = list_1['bullet_list']
311
+
312
+ #if there is "enough" overlap merge the cluster
313
+ enough, bipartite_graph, pairs_to_combine = overlap(list_0_id,list_1_id)
314
+
315
+ if enough:
316
+ union_list = list_union(bipartite_graph, pairs_to_combine)
317
+ current = {'id':int(id + len(mergings) + 1), #index in mergings DS + number of clusters
318
+ 'examples': [list_0['id'],
319
+ list_1['id']],
320
+ 'bullet_list': union_list,
321
+ 'edited': 'merging two clusters',
322
+ 'previous_list':'enough overlap to merge'
323
+ }
324
+
325
+ #not enough overlap, separate into two clusters
326
+ else:
327
+ print('not merging')
328
+ end_summaries.append(list_0)
329
+ end_summaries.append(list_1)
330
+
331
+ intermediate_steps.append(current)
332
+ if id == 118:
333
+ break
334
+
335
+ intermediate_steps = pd.DataFrame(intermediate_steps)
336
+ intermediate_steps.to_json('intermediate_steps.json', orient='records', indent=4)
337
+
338
+ end_summaries = pd.DataFrame(end_summaries)
339
+ end_summaries.to_json('end_summaries.json', orient='records', indent=4)
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7349f9baca3d6850992cb5c8ef7047b347d06ce95768e63e1a11ec3dd66c39fd
3
+ size 267835644
special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "mask_token": "[MASK]",
4
+ "pad_token": "[PAD]",
5
+ "sep_token": "[SEP]",
6
+ "unk_token": "[UNK]"
7
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "100": {
12
+ "content": "[UNK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "101": {
20
+ "content": "[CLS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "102": {
28
+ "content": "[SEP]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "103": {
36
+ "content": "[MASK]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": true,
45
+ "cls_token": "[CLS]",
46
+ "do_lower_case": true,
47
+ "mask_token": "[MASK]",
48
+ "model_max_length": 512,
49
+ "pad_token": "[PAD]",
50
+ "sep_token": "[SEP]",
51
+ "strip_accents": null,
52
+ "tokenize_chinese_chars": true,
53
+ "tokenizer_class": "DistilBertTokenizer",
54
+ "unk_token": "[UNK]"
55
+ }
vocab.txt ADDED
The diff for this file is too large to render. See raw diff