tokenspace / generate-embedding.py
ppbrown's picture
Actually works properly
14b75c0 verified
raw
history blame contribute delete
No virus
1.85 kB
#!/bin/env python
""" Work in progress
NB: This is COMPLETELY DIFFERENT from "generate-embeddings.py"!!!
Plan:
Take input for a single word or phrase.
Generate a embedding file, "generated.safetensors"
Save it out, to "generated.safetensors"
Note that you can generate an embedding from two words, or even more
Note also that apparently there are multiple file formats for embeddings.
I only use the simplest of them, in the simplest way.
"""
import sys
import json
import torch
from safetensors.torch import save_file
from transformers import CLIPProcessor,CLIPTextModel
import logging
# Turn off stupid mesages from CLIPModel.load
logging.disable(logging.WARNING)
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 = CLIPTextModel.from_pretrained(clipsrc)
print("done",file=sys.stderr)
model = model.to(device)
def cliptextmodel_embed_calc(text):
inputs = processor(text=text, return_tensors="pt")
inputs.to(device)
with torch.no_grad():
outputs = model(**inputs)
embeddings = outputs.pooler_output
return embeddings
init()
word = input("type a phrase to generate an embedding for: ")
emb = cliptextmodel_embed_calc(word)
#embs=emb.unsqueeze(0) # stupid matrix magic to make it the required shape
embs=emb
print("Shape of result = ",embs.shape)
output = "generated.safetensors"
if all(char.isalpha() for char in word):
output=f"{word}.safetensors"
print(f"Saving to {output}...")
save_file({"emb_params": embs}, output)