|
|
|
|
|
""" 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 |
|
|
|
logging.disable(logging.WARNING) |
|
|
|
clipsrc="openai/clip-vit-large-patch14" |
|
processor=None |
|
model=None |
|
|
|
device=torch.device("cuda") |
|
|
|
|
|
def init(): |
|
global processor |
|
global 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 |
|
|
|
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) |
|
|
|
|
|
|
|
|
|
|