tokenspace / subtracted-distances.py
ppbrown's picture
Upload subtracted-distances.py
c6a81ec verified
raw
history blame
No virus
2.23 kB
#!/usr/bin/python3
""" Work in progress
Plan:
Kinda a "temp" hack (maybe)
Prompt for TWO things. Subtract the second embed from the first.
Then see what is near
"""
import sys
import json
import torch
from safetensors import safe_open
from transformers import CLIPProcessor,CLIPModel
clipsrc="openai/clip-vit-large-patch14"
processor=None
model=None
device=torch.device("cuda")
def init():
global processor
global model
# Load the processor and model
print("loading processor from "+clipsrc,file=sys.stderr)
processor = CLIPProcessor.from_pretrained(clipsrc)
print("done",file=sys.stderr)
print("loading model from "+clipsrc,file=sys.stderr)
model = CLIPModel.from_pretrained(clipsrc)
print("done",file=sys.stderr)
model = model.to(device)
embed_file="embeddings.safetensors"
device=torch.device("cuda")
print("reading words from dictionary now",file=sys.stderr)
with open("dictionary","r") as f:
tokendict = f.readlines()
wordlist = [token.strip() for token in tokendict] # Remove trailing newlines
print(len(wordlist),"lines read")
print("reading embeddings now",file=sys.stderr)
model = safe_open(embed_file,framework="pt",device="cuda")
embs=model.get_tensor("embeddings")
embs.to(device)
print("Shape of loaded embeds =",embs.shape)
def standard_embed_calc(text):
if processor == None:
init()
inputs = processor(text=text, return_tensors="pt")
inputs.to(device)
with torch.no_grad():
text_features = model.get_text_features(**inputs)
embedding = text_features[0]
return embedding
def print_distances(targetemb):
targetdistances = torch.cdist( targetemb.unsqueeze(0), embs, p=2)
print("shape of distances...",targetdistances.shape)
smallest_distances, smallest_indices = torch.topk(targetdistances[0], 20, largest=False)
smallest_distances=smallest_distances.tolist()
smallest_indices=smallest_indices.tolist()
for d,i in zip(smallest_distances,smallest_indices):
print(wordlist[i],"(",d,")")
text1=input("First text? ")
text2=input("Second text? ")
emb1=standard_embed_calc(text1)
emb2=standard_embed_calc(text2)
result=torch.sub(emb1,emb2)
print_distances(result)