Upload generate-distances.py
Browse files- generate-distances.py +19 -3
generate-distances.py
CHANGED
|
@@ -21,24 +21,40 @@ device=torch.device("cuda")
|
|
| 21 |
print("read in words from json now",file=sys.stderr)
|
| 22 |
with open("fullword.json","r") as f:
|
| 23 |
tokendict = json.load(f)
|
|
|
|
| 24 |
|
| 25 |
print("read in embeddingsnow",file=sys.stderr)
|
| 26 |
|
| 27 |
|
| 28 |
model = safe_open(embed_file,framework="pt",device="cuda")
|
| 29 |
embs=model.get_tensor("embeddings")
|
| 30 |
-
|
| 31 |
embs.to(device)
|
| 32 |
|
| 33 |
|
| 34 |
print("Shape of loaded embeds =",embs.shape)
|
| 35 |
-
|
| 36 |
-
|
| 37 |
print("calculate distances now")
|
| 38 |
|
| 39 |
distances = torch.cdist(embs, embs, p=2)
|
| 40 |
print("distances shape is",distances.shape)
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
"""
|
| 43 |
import torch.nn.functional as F
|
| 44 |
pos=0
|
|
|
|
| 21 |
print("read in words from json now",file=sys.stderr)
|
| 22 |
with open("fullword.json","r") as f:
|
| 23 |
tokendict = json.load(f)
|
| 24 |
+
wordlist = list(tokendict.keys())
|
| 25 |
|
| 26 |
print("read in embeddingsnow",file=sys.stderr)
|
| 27 |
|
| 28 |
|
| 29 |
model = safe_open(embed_file,framework="pt",device="cuda")
|
| 30 |
embs=model.get_tensor("embeddings")
|
|
|
|
| 31 |
embs.to(device)
|
| 32 |
|
| 33 |
|
| 34 |
print("Shape of loaded embeds =",embs.shape)
|
|
|
|
|
|
|
| 35 |
print("calculate distances now")
|
| 36 |
|
| 37 |
distances = torch.cdist(embs, embs, p=2)
|
| 38 |
print("distances shape is",distances.shape)
|
| 39 |
|
| 40 |
+
targetword="cat"
|
| 41 |
+
targetindex=wordlist.index(targetword)
|
| 42 |
+
print("index of cat is",targetindex)
|
| 43 |
+
targetdistances=distances[targetindex]
|
| 44 |
+
|
| 45 |
+
smallest_distances, smallest_indices = torch.topk(targetdistances, 5, largest=False)
|
| 46 |
+
|
| 47 |
+
smallest_distances=smallest_distances.tolist()
|
| 48 |
+
smallest_indices=smallest_indices.tolist()
|
| 49 |
+
|
| 50 |
+
print("The smallest distance values are",smallest_distances)
|
| 51 |
+
print("The smallest index values are",smallest_indices)
|
| 52 |
+
|
| 53 |
+
for t in smallest_indices:
|
| 54 |
+
print(wordlist[t])
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
|
| 58 |
"""
|
| 59 |
import torch.nn.functional as F
|
| 60 |
pos=0
|