Views
No views yet
vit_huge_patch14_clip_224.laion2b quantized to 2-bit via Half-Quadratic Quantization (HQQ): https://mobiusml.github.io/hqq_blog/1from hqq.engine.timm import HQQtimm
2model = HQQtimm.from_quantized("mobiuslabsgmbh/CLIP-ViT-H-14-laion2B-2bit_g16_s128-HQQ")1!pip install open_clip_torch
2!pip install Pillow
3
4import torch
5import numpy as np
6
7import open_clip
8orig_model, _ , preprocess = open_clip.create_model_and_transforms('ViT-H-14', pretrained='laion2B-s32B-b79K')
9tokenizer = open_clip.get_tokenizer('ViT-H-14')
10model_text = orig_model.encode_text
11
12from hqq.engine.timm import HQQtimm
13model_visual = HQQtimm.from_quantized("mobiuslabsgmbh/CLIP-ViT-H-14-laion2B-2bit_g16_s128-HQQ")
14
15###############################################################
16#Add your own templates here, we provide simple ones below.
17#https://github.com/openai/CLIP/blob/main/data/prompts.md for the complete list
18TEMPLATES = (
19 lambda c: f'itap of a {c}.',
20 lambda c: f'a origami {c}.',
21 lambda c: f'a bad photo of the {c}.',
22 lambda c: f'a photo of the large {c}.',
23 lambda c: f'a photo of the small {c}.',
24 lambda c: f'a {c} in a video game.',
25 lambda c: f'art of the {c}.',
26)
27
28@torch.no_grad()
29def forward_image(img):
30 x = preprocess(img).unsqueeze(0)
31 f = model_visual(x.half().cuda())
32 f /= torch.norm(f, p=2, dim=-1, keepdim=True)
33 return f
34
35@torch.no_grad()
36def forward_text(text_batch_list, normalize=True):
37 inputs = tokenizer(text_batch_list)
38 f = model_text(inputs)
39 if(normalize):
40 f /= torch.norm(f, p=2, dim=-1, keepdim=True)
41 del inputs
42 return f.half().to('cuda')
43
44def forward_text_with_templates(text, templates=TEMPLATES, normalize=True):
45 f = forward_text([t(text) for t in templates], normalize=False).mean(axis=0)
46 if(normalize):
47 f /= torch.norm(f, p=2, dim=-1, keepdim=True)
48 return f
49
50def classifier_zero_shot_with_pil(img, classes):
51 classifiers = torch.cat([forward_text_with_templates(c).reshape([1, -1]) for c in classes], axis=0)
52 img_features = forward_image(img)
53 scores = torch.matmul(img_features, classifiers.T)[0].detach().cpu().numpy()
54 out = classes[np.argmax(scores)]
55 return out
56###############################################################
57from PIL import Image
58import requests
59img_path_or_url = "https://images.pexels.com/photos/45201/kitty-cat-kitten-pet-45201.jpeg" #Cat
60
61img = Image.open(requests.get(img_path_or_url, stream=True).raw)
62classes = ['cat', 'dog', 'car', 'tiger', 'bag of chips']
63out = classifier_zero_shot_with_pil(img, classes)
64print("It's a picture of a " + out) #It's a picture of a cat