Skip to content

Add object detection, tracking, mobile notifications, and search to any security camera.

Cleanclip (#143)

Rory Clearf7cffa4d8f1d
diff --git a/clearcam.py b/clearcam.py
index 9e81b93..3419fe9 100644
--- a/clearcam.py
+++ b/clearcam.py
@@ -636,20 +636,20 @@ def point_not_in_polygon(coords, poly):
return False
return True
-def run_encode_text(return_q, searcher, text):
- res = searcher._encode_text(text, realize=True)
+def run_encode_text(return_q, clip, text):
+ res = clip.model._encode_text(text, realize=True)
return_q.put(res)
return res
-def run_search(return_q, searcher, image_text, top_k, cam_name, selected_dir):
- res = searcher.search(image_text, top_k, cam_name, selected_dir)
+def run_search(return_q, clip, image_text, top_k, cam_name, selected_dir):
+ res = clip.search(image_text, top_k, cam_name, selected_dir)
return_q.put(res)
-def run_clip(return_q, clip, searcher, im, top_k, cam_name, selected_dir, is_face):
+def run_clip(return_q, clip, im, top_k, cam_name, selected_dir, is_face):
im = clip.preprocess_face(im) if is_face else clip.preprocess_clip(im)
if im is not None:
embedding = clip.precompute_face_embedding_bs1_np(im) if is_face else clip.precompute_embedding_bs1_np(im)
- res = searcher.search(None, top_k, cam_name, selected_dir, embedding, is_face)
+ res = clip.search(None, top_k, cam_name, selected_dir, embedding, is_face)
else:
res = []
return_q.put(res)
@@ -657,7 +657,6 @@ def run_clip(return_q, clip, searcher, im, top_k, cam_name, selected_dir, is_fac
class HLSRequestHandler(BaseHTTPRequestHandler):
def __init__(self, *args, **kwargs):
self.clip = kwargs.pop('clip_instance', None)
- self.searcher = kwargs.pop('searcher_instance', None)
super().__init__(*args, **kwargs)
def log_message(self, format, *args): pass # don't print stuff
@@ -1075,21 +1074,21 @@ class HLSRequestHandler(BaseHTTPRequestHandler):
})
selected_dirs.append("video")
- if image_text and use_clip: self.searcher._load_all_embeddings()
- if (uploaded_image or similar_img) and use_clip: self.searcher._load_all_embeddings(face=is_face)
+ if image_text and use_clip: self.clip._load_all_embeddings()
+ if (uploaded_image or similar_img) and use_clip: self.clip._load_all_embeddings(face=is_face)
if uploaded_image and use_clip:
- results = self.server.process_with_clip_lock(run_clip, self.clip, self.searcher, uploaded_image, start+count, cam_name, selected_dir, is_face)
+ results = self.server.process_with_clip_lock(run_clip, self.clip, uploaded_image, start+count, cam_name, selected_dir, is_face)
self.send_results(results, start, count)
return
if similar_img and use_clip:
- results = self.server.process_with_clip_lock(run_clip, self.clip, self.searcher, similar_img, start+count, cam_name, selected_dir, is_face) # todo one with above
+ results = self.server.process_with_clip_lock(run_clip, self.clip, similar_img, start+count, cam_name, selected_dir, is_face) # todo one with above
self.send_results(results, start, count)
return
if image_text and use_clip:
- results = self.server.process_with_clip_lock(run_search, self.searcher, image_text, start+count, cam_name, selected_dir)
+ results = self.server.process_with_clip_lock(run_search, self.clip, image_text, start+count, cam_name, selected_dir)
self.send_results(results, start, count)
return
@@ -1242,8 +1241,7 @@ class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
database.run_put("max_storage", "all", 256)
max_gb = database.run_get("max_storage", None)
self.max_gb = max_gb["all"]
- self.clip = CachedCLIPSearch() if use_clip else None
- self.searcher = CLIPSearch() if use_clip else None
+ self.clip = CachedCLIPSearch(prewarm=True) if use_clip else None
self.clip_stop_event = threading.Event()
self.clip_thread = None
self._setup_cleanup_and_clip_thread()
@@ -1264,7 +1262,7 @@ class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
self.clip_lock.release()
def finish_request(self, request, client_address):
- self.RequestHandlerClass(request, client_address, self, clip_instance=self.clip, searcher_instance=self.searcher)
+ self.RequestHandlerClass(request, client_address, self, clip_instance=self.clip)
def _setup_cleanup_and_clip_thread(self):
if self.cleanup_thread is None or not self.cleanup_thread.is_alive():
@@ -1314,7 +1312,7 @@ class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
# todo, move to own loop
for k, alert in alerts.items():
if alert.desc is not None and alert.desc_emb is None:
- alert.desc_emb = self.process_with_clip_lock(run_encode_text, self.searcher, alert.desc)
+ alert.desc_emb = self.process_with_clip_lock(run_encode_text, self.clip, alert.desc)
database.run_put("alerts", name, alert, id=k)
except Exception as e:
@@ -1411,7 +1409,6 @@ if __name__ == "__main__":
sys.exit(1)
if use_clip:
- from clip_search import CLIPSearch
from clip import CachedCLIPSearch
cam_name = next((arg.split("=", 1)[1] for arg in sys.argv[1:] if arg.startswith("--cam_name=")), "my_camera")
diff --git a/clip.py b/clip.py
index 8eb6681..c0304a9 100644
--- a/clip.py
+++ b/clip.py
@@ -11,11 +11,42 @@ from utils.helpers import send_notif, export_and_upload, BASE_DIR
from blazeface import BlazeFace
from adaface import ADAFACE
from tinygrad.nn.state import safe_save, safe_load, get_state_dict, load_state_dict
+from utils.clip_tokenizer import SimpleTokenizer
+import math
+from clearcam import event_img_info
+from utils.clip_tokenizer import SimpleTokenizer
class Blank: pass
class OpenCLIP:
- def __init__(self):
+ def __init__(self, base_path="data/cameras"):
+ self.base_path = base_path
+ self.image_embeddings = {}
+ self.face_embeddings = {}
+ self.image_paths = {}
+ self.face_paths = {}
+ self.tokenizer = SimpleTokenizer()
+ self.text_projection = Tensor.empty(768, 768)
+ self.positional_embedding_text = Tensor.empty(77, 768)
+ self.token_embedding = nn.Embedding(49408, 768)
+
+ self.ln_final = nn.LayerNorm(768, eps=1e-5, elementwise_affine=True)
+ self.attn_mask = Tensor.ones(77, 77).tril().where(0.0, -math.inf).cast("float32")
+ self.resblocks = []
+
+ for i in range(12):
+ resblock = Blank()
+ resblock.ln_1 = nn.LayerNorm(768, 1e-5, elementwise_affine=True)
+ resblock.ln_2 = nn.LayerNorm(768, 1e-5, elementwise_affine=True)
+ resblock.attn_out_proj_weight = Tensor.empty(768, 768)
+ resblock.attn_out_proj_bias = Tensor.empty(768)
+ resblock.mlp_c_fc = nn.Linear(768, 3072)
+ resblock.mlp_c_proj = nn.Linear(3072, 768)
+ resblock.in_proj_weight = Tensor.empty(2304, 768)
+ resblock.in_proj_bias = Tensor.empty(2304)
+ self.resblocks.append(resblock)
+
+
self.visual_conv1 = nn.Conv2d(3, 1024, (14, 14), (14, 14), (0, 0), (1, 1), 1, bias=False)
self.class_embedding = Tensor.empty(1024)
self.positional_embedding = Tensor.empty(257, 1024)
@@ -24,7 +55,7 @@ class OpenCLIP:
self.ln_post = nn.LayerNorm(1024)
self.proj = Tensor.empty(1024, 768)
- self.resblocks = []
+ self.resblocks_img = []
for i in range(24):
resblock = Blank()
resblock.ln_1 = nn.LayerNorm(1024, 1e-05, elementwise_affine=True)
@@ -35,29 +66,104 @@ class OpenCLIP:
resblock.out_proj_bias = Tensor.empty(1024)
resblock.mlp_c_fc = nn.Linear(1024, 4096)
resblock.mlp_c_proj = nn.Linear(4096, 1024)
- self.resblocks.append(resblock)
+ self.resblocks_img.append(resblock)
+
+ self.text_projection = Tensor.empty(768, 768)
+ self.positional_embedding_text = Tensor.empty(77, 768)
+ self.token_embedding = nn.Embedding(49408, 768)
+
+ self.ln_final = nn.LayerNorm(768, eps=1e-5, elementwise_affine=True)
+ self.attn_mask = Tensor.ones(77, 77).tril().where(0.0, -math.inf).cast("float32")
+ self.resblocks = []
+ for i in range(12):
+ resblock = Blank()
+ resblock.ln_1 = nn.LayerNorm(768, 1e-5, elementwise_affine=True)
+ resblock.ln_2 = nn.LayerNorm(768, 1e-5, elementwise_affine=True)
+ resblock.attn_out_proj_weight = Tensor.empty(768, 768)
+ resblock.attn_out_proj_bias = Tensor.empty(768)
+ resblock.mlp_c_fc = nn.Linear(768, 3072)
+ resblock.mlp_c_proj = nn.Linear(3072, 768)
+ resblock.in_proj_weight = Tensor.empty(2304, 768)
+ resblock.in_proj_bias = Tensor.empty(2304)
+ self.resblocks.append(resblock)
+
state_dict = safe_load(fetch("https://huggingface.co/roryclear/CLIP-ViT-L-14-laion2B-s32B-b82K/resolve/main/CLIP-ViT-L-14-laion2B-s32B-b82K.safetensors"))
load_state_dict(self, state_dict)
+ def _encode_text(self, query, realize=False):
+ tokens = [49406]
+ tokens += self.tokenizer.encode(query)
+ tokens.append(49407)
+ if len(tokens) < 77: tokens += [0] * (77 - len(tokens))
+ tokens = Tensor([tokens])
+ text_emb = encode_text(self, tokens)
+ if realize: return text_emb.numpy()
+ return text_emb
+
+@TinyJit
+def encode_text(model, text):
+ x = text
+ x = model.token_embedding(x)
+ x = x + model.positional_embedding_text
+
+ for i in range(len(model.resblocks)):
+ residual = x
+ x = model.resblocks[i].ln_1(x)
+
+ B, L, D = x.shape
+ H = 12 #resblock.attn.num_heads
+ d_head = D // H
+
+ qkv = x.matmul(model.resblocks[i].in_proj_weight.T) + model.resblocks[i].in_proj_bias
+ q, k, v = qkv.split(D, dim=-1)
+ q = q.view(B, L, H, d_head).transpose(1, 2)
+ k = k.view(B, L, H, d_head).transpose(1, 2)
+ v = v.view(B, L, H, d_head).transpose(1, 2)
+
+ scale = 1.0 / (d_head ** 0.5)
+ attn_scores = q.matmul(k.transpose(-2, -1)) * scale # (B,H,L,L)
+ bool_mask = model.attn_mask < 0
+ attn_scores = attn_scores.masked_fill(bool_mask, float("-inf"))
+ attn_probs = Tensor.softmax(attn_scores)
+ context = attn_probs.matmul(v)
+ context = context.transpose(1, 2).contiguous().view(B, L, D)
+ x = context.matmul(model.resblocks[i].attn_out_proj_weight.T) + model.resblocks[i].attn_out_proj_bias
+
+ x += residual
+ residual = x
+ x = model.resblocks[i].ln_2(x)
+ x = model.resblocks[i].mlp_c_fc(x)
+ x = x.gelu()
+ x = model.resblocks[i].mlp_c_proj(x)
+ x += residual
+
+ x = model.ln_final(x) # [batch_size, n_ctx, transformer.width]
+ argmax = text.argmax()
+ x = x[0][argmax]
+ x = x @ model.text_projection
+ return x / (x * x).sum(axis=-1, keepdim=True).sqrt()
+
class CachedCLIPSearch:
- def __init__(self, prewarm=True):
+ def __init__(self, prewarm=False, base_path="data/cameras"):
+ self.base_path = base_path
self.image_embeddings = {}
+ self.face_embeddings = {}
self.image_paths = {}
+ self.face_paths = {}
self.model = OpenCLIP()
- self.blazeface = BlazeFace()
- self.adaface = ADAFACE()
+ #self.blazeface = BlazeFace()
+ #self.adaface = ADAFACE()
# prewarm
if prewarm:
- blazeface_jit(self.blazeface, Tensor.rand((640, 640, 3)).cast(dtype=dtypes.uchar))
- adaface_jit(self.adaface, Tensor.rand((112, 112, 3)).cast(dtype=dtypes.uchar))
+ #blazeface_jit(self.blazeface, Tensor.rand((640, 640, 3)).cast(dtype=dtypes.uchar))
+ #adaface_jit(self.adaface, Tensor.rand((112, 112, 3)).cast(dtype=dtypes.uchar))
precompute_embeddings_jit(self.model, Tensor.rand((1, 3, 224, 224), dtype=dtypes.float32))
precompute_embeddings_jit(self.model, Tensor.rand((16, 3, 224, 224), dtype=dtypes.float32))
-
def find_object_folders(self, base_path="data/cameras"):
object_folders = []
if not os.path.exists(base_path): return object_folders
@@ -209,6 +315,98 @@ class CachedCLIPSearch:
return ret_paths, ret_embeddings
+ def search(self, query=None, top_k=10, cam_name=None, timestamp=None, text_embedding=None, is_face=False):
+ embeddings = self.face_embeddings if is_face else self.image_embeddings
+ if not embeddings:
+ print("No embeddings available.")
+ return []
+ if text_embedding is None:
+ text_embedding = self.model._encode_text(query)
+ text_embedding = text_embedding.numpy()
+ all_similarities = []
+ for path, img_embedding in embeddings.items():
+ normalized_path = path.replace("\\", "/")
+ if cam_name and f"/cameras/{cam_name}/" not in normalized_path:
+ continue
+ if timestamp and f"/objects/{timestamp}/" not in normalized_path and "/objects/video/" not in normalized_path:
+ continue
+ similarity = (img_embedding @ text_embedding.T).item()
+ filename = os.path.basename(path)
+ if filename.lower().endswith((".jpg", ".jpeg", ".png")):
+ object_id = event_img_info(filename.split(".")[0])["object_id"] if "_" in filename else None
+ all_similarities.append((path, similarity, object_id))
+
+ if any(item[2] for item in all_similarities):
+ best_per_id = {}
+ for path, score, object_id in all_similarities:
+ if object_id is not None:
+ if object_id not in best_per_id or score > best_per_id[object_id][1]:
+ best_per_id[object_id] = (path, score)
+
+ items_without_id = [(path, score) for path, score, object_id in all_similarities if object_id is None]
+ results = list(best_per_id.values()) + items_without_id
+ else:
+ results = [(path, score) for path, score, _ in all_similarities]
+ results.sort(key=lambda x: x[1], reverse=True)
+ return results[:top_k]
+
+
+ def _load_single_embeddings_file(self, cache_file):
+ try:
+ with open(cache_file, "rb") as f:
+ cache = pickle.load(f)
+
+ folder_embeddings = cache.get("embeddings", {})
+ folder_paths = cache.get("paths", {})
+
+ self.image_embeddings.update(folder_embeddings)
+ self.image_paths.update(folder_paths)
+
+ loaded_count = len(folder_embeddings)
+ print(f"Loaded {loaded_count} embeddings from {cache_file}")
+ return loaded_count
+
+ except Exception as e:
+ print(f"Error loading {cache_file}: {e}")
+ return 0
+
+ def _load_all_embeddings(self, face=False):
+ total_loaded = 0
+ valid_paths = set()
+ cache_filename = "embeddings.pkl"
+ target_embeddings = self.face_embeddings if face else self.image_embeddings
+ target_paths = self.face_paths if face else self.image_paths
+
+ for camera_folder in os.listdir(self.base_path):
+ camera_path = os.path.join(self.base_path, camera_folder)
+ if not os.path.isdir(camera_path): continue
+ objects_path = os.path.join(camera_path, "faces" if face else "objects")
+ if not os.path.isdir(objects_path): continue
+ for date_folder in os.listdir(objects_path):
+ date_path = os.path.join(objects_path, date_folder)
+ if not os.path.isdir(date_path): continue
+ cache_file = os.path.join(date_path, cache_filename)
+ if not os.path.exists(cache_file): continue
+ with open(cache_file, "rb") as f:
+ cache = pickle.load(f)
+ folder_embeddings = cache.get("embeddings", {})
+ folder_paths = cache.get("paths", {})
+ valid_paths.update(folder_embeddings.keys())
+ target_embeddings.update(folder_embeddings)
+ target_paths.update(folder_paths)
+ total_loaded += len(folder_embeddings)
+ stale_keys = set(target_embeddings.keys()) - valid_paths
+ for k in stale_keys:
+ del target_embeddings[k]
+ target_paths.pop(k, None)
+
+ if face:
+ self.face_embeddings = target_embeddings
+ else:
+ self.image_embeddings = target_embeddings
+
+ print(f"\nTotal {'face' if face else 'image'} embeddings loaded: {total_loaded}")
+
def get_embeddings(path, filename):
cache_file = os.path.join(path, filename)
folder_embeddings = {}
@@ -247,12 +445,12 @@ def precompute_embedding(model, x):
x = x + model.positional_embedding
x = model.ln_pre(x)
# https://github.com/pytorch/pytorch/blob/v2.9.1/torch/nn/modules/activation.py#L1252
- for i in range(len(model.resblocks)):
- x_ln1 = model.resblocks[i].ln_1(x)
+ for i in range(len(model.resblocks_img)):
+ x_ln1 = model.resblocks_img[i].ln_1(x)
B, L, D = x_ln1.shape
H = 16 #block.attn.num_heads
d_head = D // H
- qkv = x_ln1 @ model.resblocks[i].in_proj_weight.T + model.resblocks[i].in_proj_bias
+ qkv = x_ln1 @ model.resblocks_img[i].in_proj_weight.T + model.resblocks_img[i].in_proj_bias
q, k, v = qkv.split(D, dim=-1)
def shape(x): return x.view(B, L, H, d_head).transpose(1, 2)
q = shape(q)
@@ -263,13 +461,13 @@ def precompute_embedding(model, x):
attn_probs = Tensor.softmax(attn_scores)
context = attn_probs.matmul(v)
context = context.transpose(1, 2).contiguous().view(B, L, D)
- attn_out = context @ model.resblocks[i].out_proj_weight.T + model.resblocks[i].out_proj_bias
+ attn_out = context @ model.resblocks_img[i].out_proj_weight.T + model.resblocks_img[i].out_proj_bias
attn_scaled = attn_out
x = x + attn_scaled
- x_ln2 = model.resblocks[i].ln_2(x)
- ff = model.resblocks[i].mlp_c_fc(x_ln2)
+ x_ln2 = model.resblocks_img[i].ln_2(x)
+ ff = model.resblocks_img[i].mlp_c_fc(x_ln2)
ff = ff.gelu()
- ff = model.resblocks[i].mlp_c_proj(ff)
+ ff = model.resblocks_img[i].mlp_c_proj(ff)
x = x + ff
x = model.ln_post(x)
diff --git a/clip_search.py b/clip_search.py
deleted file mode 100644
index da0cf88..0000000
--- a/clip_search.py
+++ /dev/null
@@ -1,188 +0,0 @@
-import os
-import pickle
-from tinygrad import nn, Tensor, TinyJit, Device
-from tinygrad.helpers import fetch
-from clearcam import event_img_info
-from utils.clip_tokenizer import SimpleTokenizer
-import numpy as np
-import math
-from tinygrad.nn.state import safe_save, safe_load, get_state_dict, load_state_dict
-
-class Blank: pass
-
-class CLIPSearch:
- def __init__(self, base_path="data/cameras"):
- self.base_path = base_path
- self.image_embeddings = {}
- self.face_embeddings = {}
- self.image_paths = {}
- self.face_paths = {}
- self.tokenizer = SimpleTokenizer()
- self.text_projection = Tensor.empty(768, 768)
- self.positional_embedding = Tensor.empty(77, 768)
- self.token_embedding = nn.Embedding(49408, 768)
-
- self.ln_final = nn.LayerNorm(768, eps=1e-5, elementwise_affine=True)
- self.attn_mask = Tensor.ones(77, 77).tril().where(0.0, -math.inf).cast("float32")
- self.resblocks = []
-
- for i in range(12):
- resblock = Blank()
- resblock.ln_1 = nn.LayerNorm(768, 1e-5, elementwise_affine=True)
- resblock.ln_2 = nn.LayerNorm(768, 1e-5, elementwise_affine=True)
- resblock.attn_out_proj_weight = Tensor.empty(768, 768)
- resblock.attn_out_proj_bias = Tensor.empty(768)
- resblock.mlp_c_fc = nn.Linear(768, 3072)
- resblock.mlp_c_proj = nn.Linear(3072, 768)
- resblock.in_proj_weight = Tensor.empty(2304, 768)
- resblock.in_proj_bias = Tensor.empty(2304)
- self.resblocks.append(resblock)
-
- state_dict = safe_load(fetch("https://huggingface.co/roryclear/CLIP-ViT-L-14-laion2B-s32B-b82K/resolve/main/CLIP-ViT-L-14-laion2B-s32B-b82K_2.safetensors"))
- load_state_dict(self, state_dict)
-
-
-
- def _load_single_embeddings_file(self, cache_file):
- try:
- with open(cache_file, "rb") as f:
- cache = pickle.load(f)
-
- folder_embeddings = cache.get("embeddings", {})
- folder_paths = cache.get("paths", {})
-
- self.image_embeddings.update(folder_embeddings)
- self.image_paths.update(folder_paths)
-
- loaded_count = len(folder_embeddings)
- print(f"Loaded {loaded_count} embeddings from {cache_file}")
- return loaded_count
-
- except Exception as e:
- print(f"Error loading {cache_file}: {e}")
- return 0
-
- def _load_all_embeddings(self, face=False):
- total_loaded = 0
- valid_paths = set()
- cache_filename = "embeddings.pkl"
- target_embeddings = self.face_embeddings if face else self.image_embeddings
- target_paths = self.face_paths if face else self.image_paths
-
- for camera_folder in os.listdir(self.base_path):
- camera_path = os.path.join(self.base_path, camera_folder)
- if not os.path.isdir(camera_path): continue
- objects_path = os.path.join(camera_path, "faces" if face else "objects")
- if not os.path.isdir(objects_path): continue
- for date_folder in os.listdir(objects_path):
- date_path = os.path.join(objects_path, date_folder)
- if not os.path.isdir(date_path): continue
- cache_file = os.path.join(date_path, cache_filename)
- if not os.path.exists(cache_file): continue
- with open(cache_file, "rb") as f:
- cache = pickle.load(f)
- folder_embeddings = cache.get("embeddings", {})
- folder_paths = cache.get("paths", {})
- valid_paths.update(folder_embeddings.keys())
- target_embeddings.update(folder_embeddings)
- target_paths.update(folder_paths)
- total_loaded += len(folder_embeddings)
- stale_keys = set(target_embeddings.keys()) - valid_paths
- for k in stale_keys:
- del target_embeddings[k]
- target_paths.pop(k, None)
-
- if face:
- self.face_embeddings = target_embeddings
- else:
- self.image_embeddings = target_embeddings
-
- print(f"\nTotal {'face' if face else 'image'} embeddings loaded: {total_loaded}")
-
- def _encode_text(self, query, realize=False):
- tokens = [49406]
- tokens += self.tokenizer.encode(query)
- tokens.append(49407)
- if len(tokens) < 77: tokens += [0] * (77 - len(tokens))
- tokens = Tensor([tokens])
- text_emb = encode_text(self, tokens)
- if realize: return text_emb.numpy()
- return text_emb
-
- def search(self, query=None, top_k=10, cam_name=None, timestamp=None, text_embedding=None, is_face=False):
- embeddings = self.face_embeddings if is_face else self.image_embeddings
- if not embeddings:
- print("No embeddings available.")
- return []
- if text_embedding is None:
- text_embedding = self._encode_text(query)
- text_embedding = text_embedding.numpy()
- all_similarities = []
- for path, img_embedding in embeddings.items():
- normalized_path = path.replace("\\", "/")
- if cam_name and f"/cameras/{cam_name}/" not in normalized_path:
- continue
- if timestamp and f"/objects/{timestamp}/" not in normalized_path and "/objects/video/" not in normalized_path:
- continue
- similarity = (img_embedding @ text_embedding.T).item()
- filename = os.path.basename(path)
- if filename.lower().endswith((".jpg", ".jpeg", ".png")):
- object_id = event_img_info(filename.split(".")[0])["object_id"] if "_" in filename else None
- all_similarities.append((path, similarity, object_id))
-
- if any(item[2] for item in all_similarities):
- best_per_id = {}
- for path, score, object_id in all_similarities:
- if object_id is not None:
- if object_id not in best_per_id or score > best_per_id[object_id][1]:
- best_per_id[object_id] = (path, score)
-
- items_without_id = [(path, score) for path, score, object_id in all_similarities if object_id is None]
- results = list(best_per_id.values()) + items_without_id
- else:
- results = [(path, score) for path, score, _ in all_similarities]
- results.sort(key=lambda x: x[1], reverse=True)
- return results[:top_k]
-
-@TinyJit
-def encode_text(model, text):
- x = text
- x = model.token_embedding(x)
- x = x + model.positional_embedding
-
- for i in range(len(model.resblocks)):
- residual = x
- x = model.resblocks[i].ln_1(x)
-
- B, L, D = x.shape
- H = 12 #resblock.attn.num_heads
- d_head = D // H
-
- qkv = x.matmul(model.resblocks[i].in_proj_weight.T) + model.resblocks[i].in_proj_bias
- q, k, v = qkv.split(D, dim=-1)
- q = q.view(B, L, H, d_head).transpose(1, 2)
- k = k.view(B, L, H, d_head).transpose(1, 2)
- v = v.view(B, L, H, d_head).transpose(1, 2)
-
- scale = 1.0 / (d_head ** 0.5)
- attn_scores = q.matmul(k.transpose(-2, -1)) * scale # (B,H,L,L)
- bool_mask = model.attn_mask < 0
- attn_scores = attn_scores.masked_fill(bool_mask, float("-inf"))
- attn_probs = Tensor.softmax(attn_scores)
- context = attn_probs.matmul(v)
- context = context.transpose(1, 2).contiguous().view(B, L, D)
- x = context.matmul(model.resblocks[i].attn_out_proj_weight.T) + model.resblocks[i].attn_out_proj_bias
-
- x += residual
- residual = x
- x = model.resblocks[i].ln_2(x)
- x = model.resblocks[i].mlp_c_fc(x)
- x = x.gelu()
- x = model.resblocks[i].mlp_c_proj(x)
- x += residual
-
- x = model.ln_final(x) # [batch_size, n_ctx, transformer.width]
- argmax = text.argmax()
- x = x[0][argmax]
- x = x @ model.text_projection
- return x / (x * x).sum(axis=-1, keepdim=True).sqrt()
diff --git a/requirements.txt b/requirements.txt
index f49c613..8981735 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,3 +1,3 @@
-git+https://github.com/tinygrad/tinygrad.git@b45edeb9653d5e7adbf0fcd3cd14c48e8bfd2b6c
+git+https://github.com/tinygrad/tinygrad.git@74ecf6d3e676f02d16b58f54366a13df6918d4f7
numpy==2.0.0
opencv-python-headless==4.10.0.84
\ No newline at end of file
diff --git a/test/test_clip.py b/test/test_clip.py
index 80eeba5..18031cc 100644
--- a/test/test_clip.py
+++ b/test/test_clip.py
@@ -1,36 +1,35 @@
from clip import CachedCLIPSearch as CachedCLIPSearch
-from clip_search import CLIPSearch as ClipSearch
import numpy as np
import os
def setup_clip_test():
if os.path.exists("test/clip_images/embeddings.pkl"): os.remove("test/clip_images/embeddings.pkl")
- scanner = CachedCLIPSearch(prewarm=False)
- scanner.precompute_embeddings("test/clip_images")
+ clip = CachedCLIPSearch(prewarm=False)
+ clip.precompute_embeddings("test/clip_images")
def test_clip_search():
- searcher = ClipSearch()
- searcher._load_single_embeddings_file("test/clip_images/embeddings.pkl")
- res = searcher.search("ferrari f40")
+ clip = CachedCLIPSearch()
+ clip._load_single_embeddings_file("test/clip_images/embeddings.pkl")
+ res = clip.search("ferrari f40")
np.testing.assert_allclose(res[0][1], 0.3566271960735321, rtol=1e-03)
np.testing.assert_allclose(res[1][1], 0.0718243420124054, rtol=1e-02) # careful now
assert res[0][0] == "test/clip_images/f40.jpg"
assert res[1][0] == "test/clip_images/micra.jpg"
- res = searcher.search("nissan micra")
+ res = clip.search("nissan micra")
np.testing.assert_allclose(res[0][1], 0.3218580484390259, rtol=1e-03)
np.testing.assert_allclose(res[1][1], 0.07153752446174622, rtol=1e-02)
assert res[1][0] == "test/clip_images/f40.jpg"
assert res[0][0] == "test/clip_images/micra.jpg"
def test_clip_search_jit():
- searcher = ClipSearch()
- searcher._load_single_embeddings_file("test/clip_images/embeddings.pkl")
- for _ in range(5): res = searcher.search("ferrari f40")
+ clip = CachedCLIPSearch()
+ clip._load_single_embeddings_file("test/clip_images/embeddings.pkl")
+ for _ in range(5): res = clip.search("ferrari f40")
np.testing.assert_allclose(res[0][1], 0.3566271960735321, rtol=1e-03)
np.testing.assert_allclose(res[1][1], 0.0718243420124054, rtol=1e-02) # careful now
assert res[0][0] == "test/clip_images/f40.jpg"
assert res[1][0] == "test/clip_images/micra.jpg"
- for _ in range(5): res = searcher.search("nissan micra")
+ for _ in range(5): res = clip.search("nissan micra")
np.testing.assert_allclose(res[0][1], 0.3218580484390259, rtol=1e-03)
np.testing.assert_allclose(res[1][1], 0.07153752446174622, rtol=1e-02)
assert res[1][0] == "test/clip_images/f40.jpg"