Upload T5/generate-dict-embeddingsT5.py with huggingface_hub
Browse files
T5/generate-dict-embeddingsT5.py
ADDED
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/env python
|
2 |
+
|
3 |
+
"""
|
4 |
+
(T5 counterpart of "generate-dict-embeddingsXL.py".
|
5 |
+
"""
|
6 |
+
|
7 |
+
outputfile="embeddingsT5.temp.safetensors"
|
8 |
+
|
9 |
+
import sys
|
10 |
+
import torch
|
11 |
+
from safetensors.torch import save_file
|
12 |
+
from transformers import T5Tokenizer,T5EncoderModel
|
13 |
+
|
14 |
+
processor=None
|
15 |
+
tmodel=None
|
16 |
+
|
17 |
+
device=torch.device("cuda")
|
18 |
+
|
19 |
+
def initT5model():
|
20 |
+
global processor,tmodel
|
21 |
+
T="mcmonkey/google_t5-v1_1-xxl_encoderonly"
|
22 |
+
processor = T5Tokenizer.from_pretrained(T)
|
23 |
+
tmodel = T5EncoderModel.from_pretrained(T).to(device)
|
24 |
+
|
25 |
+
|
26 |
+
def embed_from_text(text):
|
27 |
+
global processor,tmodel
|
28 |
+
#print("Word:"+text)
|
29 |
+
tokens = processor(text, return_tensors="pt")
|
30 |
+
tokens.to(device)
|
31 |
+
|
32 |
+
if len(tokens.input_ids) >2:
|
33 |
+
print("ERROR: expected single token per word")
|
34 |
+
print(text)
|
35 |
+
exit(1)
|
36 |
+
|
37 |
+
with torch.no_grad():
|
38 |
+
outputs = tmodel(tokens.input_ids)
|
39 |
+
|
40 |
+
embedding = outputs.last_hidden_state[0][0]
|
41 |
+
#print(encoding.shape)
|
42 |
+
# Shape of this is (1,2,4096)
|
43 |
+
|
44 |
+
return embedding
|
45 |
+
|
46 |
+
initT5model()
|
47 |
+
|
48 |
+
print("Reading in 'dictionary'")
|
49 |
+
with open("dictionary","r") as f:
|
50 |
+
tokendict = f.readlines()
|
51 |
+
tokendict = [token.strip() for token in tokendict] # Remove trailing newlines
|
52 |
+
|
53 |
+
|
54 |
+
count=1
|
55 |
+
all_embeddings = []
|
56 |
+
|
57 |
+
for word in tokendict:
|
58 |
+
emb = embed_from_text(word)
|
59 |
+
#emb=emb.unsqueeze(0) # stupid matrix magic to make torch.cat work
|
60 |
+
all_embeddings.append(emb)
|
61 |
+
count+=1
|
62 |
+
if (count %100) ==0:
|
63 |
+
print(count)
|
64 |
+
|
65 |
+
|
66 |
+
embs = torch.cat(all_embeddings,dim=0)
|
67 |
+
print("Shape of result = ",embs.shape)
|
68 |
+
|
69 |
+
if len(embs.shape) != 2:
|
70 |
+
print("Sanity check: result is wrong shape: it wont work")
|
71 |
+
|
72 |
+
print(f"Saving the calculatiuons to {outputfile}...")
|
73 |
+
save_file({"embeddings": embs}, outputfile)
|
74 |
+
|