Spaces:
Sleeping
Sleeping
maximuspowers
commited on
Commit
•
05dce30
1
Parent(s):
76b46b5
Create process-vocab.py
Browse files- process-vocab.py +60 -0
process-vocab.py
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import numpy as np
|
3 |
+
from transformers import BertTokenizerFast, BertForTokenClassification
|
4 |
+
from tqdm import tqdm
|
5 |
+
import json
|
6 |
+
|
7 |
+
# init
|
8 |
+
tokenizer = BertTokenizerFast.from_pretrained('bert-base-uncased')
|
9 |
+
model = BertForTokenClassification.from_pretrained('maximuspowers/bias-detection-ner', output_hidden_states=True)
|
10 |
+
model.eval()
|
11 |
+
model.to('cuda')
|
12 |
+
|
13 |
+
# get bert's entire vocab
|
14 |
+
vocab_tokens = list(tokenizer.get_vocab().keys())
|
15 |
+
print(f"Total number of tokens in vocabulary: {len(vocab_tokens)}") # 30522 tokens for bert-base-uncased
|
16 |
+
|
17 |
+
# precompute embeddings and attention scores for the entire vocabulary
|
18 |
+
def precompute_vocabulary_embeddings_and_attention():
|
19 |
+
vocab_embeddings = []
|
20 |
+
vocab_attention_scores = []
|
21 |
+
|
22 |
+
for token in tqdm(vocab_tokens, desc="Computing Embeddings and Attention Scores", unit="token"):
|
23 |
+
# no special tokens
|
24 |
+
inputs = tokenizer(token, return_tensors="pt", truncation=True, padding=True, add_special_tokens=False)
|
25 |
+
input_ids = inputs['input_ids'].to(model.device)
|
26 |
+
|
27 |
+
with torch.no_grad():
|
28 |
+
outputs = model(input_ids=input_ids)
|
29 |
+
|
30 |
+
embeddings = outputs.hidden_states[-1][0][0].cpu().numpy() # first token embedding, should only be one anyways
|
31 |
+
vocab_embeddings.append(embeddings)
|
32 |
+
|
33 |
+
logits = outputs.logits
|
34 |
+
probabilities = torch.sigmoid(logits).cpu().numpy()[0][0] # convert logits to probabilities
|
35 |
+
|
36 |
+
# store attention scores
|
37 |
+
attention_scores = {
|
38 |
+
'O': float(probabilities[0]), # O class (non-entity)
|
39 |
+
'B-GEN': float(probabilities[3]), # B-GEN
|
40 |
+
'I-GEN': float(probabilities[4]), # I-GEN
|
41 |
+
'B-UNFAIR': float(probabilities[5]), # B-UNFAIR
|
42 |
+
'I-UNFAIR': float(probabilities[6]), # I-UNFAIR
|
43 |
+
'B-STEREO': float(probabilities[1]), # B-STEREO
|
44 |
+
'I-STEREO': float(probabilities[2]) # I-STEREO
|
45 |
+
}
|
46 |
+
vocab_attention_scores.append(attention_scores)
|
47 |
+
|
48 |
+
return np.array(vocab_embeddings), vocab_attention_scores
|
49 |
+
|
50 |
+
|
51 |
+
# precompute
|
52 |
+
vocab_embeddings, vocab_attention_scores = precompute_vocabulary_embeddings_and_attention()
|
53 |
+
|
54 |
+
# save files
|
55 |
+
np.save('vocab_embeddings.npy', vocab_embeddings)
|
56 |
+
with open('vocab_attention_scores.json', 'w') as f:
|
57 |
+
json.dump(vocab_attention_scores, f)
|
58 |
+
|
59 |
+
with open('vocab_tokens.json', 'w') as f:
|
60 |
+
json.dump(vocab_tokens, f)
|