CLIP-ViT-B-32-recovered / cpu /application.py
ztripez's picture
Publish recovered FP32 CLIP program and exact operand image
da2d9e2 verified
Raw History Blame Contribute Delete
2.71 kB
"""Detached CLIP application with NumPy storage and compiled numerical kernels."""
# @locus component: cge.compiler_guided_extraction
import argparse
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import json
import numpy as np
from PIL import Image
import clip_ops
from mapped_coefficients import load_coefficients
import recovered
from clip_frontends import Tokenizer, preprocess
class Application:
"""Load the original learned operands and execute the recovered graph."""
def __init__(self, path):
clip_ops.configure(path)
self.executor = ThreadPoolExecutor(max_workers=1)
self.data = load_coefficients(path / "coefficients.json")
self.tokenizer = Tokenizer(path / "bpe_simple_vocab_16e6.txt.gz")
def call(self, name, *args):
return getattr(recovered, name)(self.data[name], *args)
def state(self, lane, inputs, write=None):
state = self.call(lane + "_frontend", inputs)
if lane == "text" and write is None:
length = min(77, (int(inputs.argmax(axis=1).max()) + 8) // 8 * 8)
state = state[:length]
for index in range(12):
if write is not None:
state = write(index, state)
state = self.call(f"{lane}_{index:02}", state)
return state
def tensors(self, pixels, tokens, visual_write=None, text_write=None):
if visual_write is None and text_write is None:
text_state = self.executor.submit(self.state, "text", tokens)
image = self.call("image", self.state("image", pixels))
text = self.call("text", text_state.result(), tokens)
else:
image = self.call("image", self.state("image", pixels, visual_write))
text = self.call("text", self.state("text", tokens, text_write), tokens)
return image, text, *self.call("score", image, text)
def raw(self, images, texts, visual_write=None, text_write=None):
return self.tensors(np.stack([preprocess(image) for image in images]),
self.tokenizer.tokenize(texts), visual_write, text_write)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--image", action="append", required=True, type=Path)
parser.add_argument("--text", action="append", required=True)
args = parser.parse_args()
images = []
for path in args.image:
with Image.open(path) as image:
images.append(image.copy())
application = Application(Path(__file__).resolve().parent)
print(json.dumps([tensor.tolist() for tensor in application.raw(images, args.text)]))
if __name__ == "__main__":
main()