Add object detection, tracking, mobile notifications, and search to any security camera.
Clean jit (#155)
Rory Clear459469e25a73
diff --git a/adaface.py b/adaface.pyindex 582be83..ddad303 100644--- a/adaface.py+++ b/adaface.py@@ -1,4 +1,4 @@-from tinygrad import Tensor, nn+from tinygrad import Tensor, nn, TinyJitfrom tinygrad.nn.state import safe_save, safe_load, get_state_dict, load_state_dictfrom tinygrad.helpers import fetchclass MaxPool2d:@@ -76,7 +76,7 @@ class ADAFACE():state_dict = safe_load(fetch("https://huggingface.co/roryclear/AdaFace/resolve/main/adaface_ir50_ms1mv2.safetensors"))load_state_dict(self, state_dict)-+ @TinyJitdef __call__(self, x):x = ((x[:,:,::-1] / 255.) - 0.5) / 0.5x = x.permute(2,0,1).unsqueeze(0)diff --git a/blazeface.py b/blazeface.pyindex 84722b8..d57eae0 100644--- a/blazeface.py+++ b/blazeface.py@@ -1,4 +1,4 @@-from tinygrad import Tensor, nn+from tinygrad import Tensor, nn, TinyJitfrom tinygrad.nn.state import safe_save, safe_load, get_state_dict, load_state_dictfrom utils.helpers import resize@@ -164,6 +164,7 @@ class BlazeFace():r = Tensor.cat(r1, r2, dim=1)return [r, c]+ @TinyJitdef __call__(self, img):h0, w0 = img.shape[:2]diff --git a/clearcam.py b/clearcam.pyindex 648c470..b93f162 100644--- a/clearcam.py+++ b/clearcam.py@@ -662,7 +662,7 @@ def run_search(clip, image_text, top_k, cam_name, selected_dir): return clip.seadef run_clip(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)+ embedding = clip.adaface(Tensor(im)).numpy() if is_face else jit_infer(clip.model.precompute_embedding, Tensor(im), jit_cache=jit_cache).numpy()res = clip.search(None, top_k, cam_name, selected_dir, embedding, is_face)else:res = []@@ -1222,7 +1222,7 @@ def process_latest_face(img):cv2.imwrite(str(object_queue[0]).replace("/objects/", "/faces/"), face_img)date = object_queue[0].parent.namepkl_path = object_queue[0].parent.parent.parent / "faces" / date / "embeddings.pkl"- face_emb = adaface_jit(object_finder.adaface, Tensor(face_img).contiguous()).numpy()+ face_emb = object_finder.adaface(Tensor(face_img).contiguous()).numpy()data = pickle.load(open(pkl_path, "rb")) if pkl_path.exists() else {}if "embeddings" not in data: data["embeddings"] = {}data["embeddings"][str(object_queue[0])] = face_emb@@ -1234,7 +1234,7 @@ def clip_latest_img(img):img = object_finder.preprocess(img)data = pickle.load(open(object_queue[0].parent / 'embeddings.pkl', 'rb')) if os.path.exists(object_queue[0].parent / 'embeddings.pkl') else {}if "embeddings" not in data: data["embeddings"] = {}- emb = precompute_embedding_jit_bs1(object_finder.model, Tensor(img).unsqueeze(0)).numpy()+ emb = jit_infer(object_finder.model.precompute_embedding, Tensor(img).unsqueeze(0), jit_cache).numpy()data["embeddings"][str(object_queue[0])] = embwith open(object_queue[0].parent / 'embeddings.pkl', "wb") as f: pickle.dump(data, f)@@ -1385,7 +1385,7 @@ if __name__ == "__main__":sys.exit(1)if use_clip or use_face:- from objects import ObjectFinder, precompute_embedding_jit_bs1, adaface_jit+ from objects import ObjectFinderobject_queue = []cam_name = next((arg.split("=", 1)[1] for arg in sys.argv[1:] if arg.startswith("--cam_name=")), "my_camera")diff --git a/detection/rfdetr.py b/detection/rfdetr.pyindex 881ca10..56f7534 100644--- a/detection/rfdetr.py+++ b/detection/rfdetr.py@@ -603,15 +603,6 @@ class RFDETR():state_dict = safe_load(fetch(f'https://huggingface.co/roryclear/rf-detr/resolve/main/{name}.safetensors'))load_state_dict(self, state_dict)- # todo, this should be more generic and not in both here and yolo- def jit_infer(self, frame):- shape = tuple(frame.shape)- if shape not in self.jit_cache:- @TinyJit- def fn(im, model): return model(im)- self.jit_cache[shape] = fn- return self.jit_cache[shape](frame, self)-def __call__(self, frame):pre = self.preprocess(frame)predictions = self.predict(pre)diff --git a/objects.py b/objects.pyindex 43b6d93..67c0ef9 100644--- a/objects.py+++ b/objects.py@@ -90,6 +90,47 @@ class OpenCLIP: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 precompute_embedding(self, x):+ x = self.visual_conv1(x)+ x = x.reshape(x.shape[0], x.shape[1], -1)+ x = x.permute(0, 2, 1)+ cls_emb = self.class_embedding+ cls_emb = cls_emb.unsqueeze(0).expand(x.shape[0], -1, -1)+ x = Tensor.cat(cls_emb, x, dim=1)+ x = x + self.positional_embedding+ x = self.ln_pre(x)+ # https://github.com/pytorch/pytorch/blob/v2.9.1/torch/nn/modules/activation.py#L1252+ for i in range(len(self.resblocks_img)):+ x_ln1 = self.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 @ self.resblocks_img[i].in_proj_weight.T + self.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)+ k = shape(k)+ v = shape(v)+ scale = 1.0 / (d_head ** 0.5)+ attn_scores = q.matmul(k.transpose(-2, -1)) * scale+ attn_probs = Tensor.softmax(attn_scores)+ context = attn_probs.matmul(v)+ context = context.transpose(1, 2).contiguous().view(B, L, D)+ attn_out = context @ self.resblocks_img[i].out_proj_weight.T + self.resblocks_img[i].out_proj_bias+ attn_scaled = attn_out+ x = x + attn_scaled+ x_ln2 = self.resblocks_img[i].ln_2(x)+ ff = self.resblocks_img[i].mlp_c_fc(x_ln2)+ ff = ff.gelu()+ ff = self.resblocks_img[i].mlp_c_proj(ff)+ x = x + ff++ x = self.ln_post(x)+ image_embeds = x[:, 0, :]+ embeddings = image_embeds @ self.proj+ embeddings = embeddings / (embeddings.pow(2).sum(axis=-1, keepdim=True).sqrt() + 1e-8)+ return embeddingsdef _encode_text(self, query, realize=False):tokens = [49406]@@ -174,10 +215,6 @@ class ObjectFinder:object_folders.append(date_path)return object_folders- def precompute_embedding_bs1_np(self, img): return precompute_embedding_jit_bs1(self.model, Tensor(img)).numpy() # todo remove-- def precompute_face_embedding_bs1_np(self, img): return adaface_jit(self.adaface, Tensor(img)).numpy() # todo remove-def preprocess(self, img):img = cv2.resize(img, (224, 224), interpolation=cv2.INTER_CUBIC)img = img.astype(np.float32) / 255.0@@ -213,7 +250,7 @@ class ObjectFinder:top, bottom = delta_h // 2, delta_h - (delta_h // 2)left, right = delta_w // 2, delta_w - (delta_w // 2)orig = cv2.copyMakeBorder(resized, top, bottom, left, right, cv2.BORDER_CONSTANT, value=[0,0,0])- detections = blazeface_jit(self.blazeface, Tensor(orig)).numpy()+ detections = self.blazeface(Tensor(orig)).numpy()detections = detections[detections[:, 0] != 0]# one face per person for nowif detections.shape[0] > 0:@@ -363,57 +400,4 @@ class ObjectFinder:else:self.image_embeddings = target_embeddings- print(f"\nTotal {'face' if face else 'image'} embeddings loaded: {total_loaded}")--@TinyJit-def precompute_embeddings_jit(model, x): return precompute_embedding(model, x)--@TinyJit-def precompute_embedding_jit_bs1(model, x): return precompute_embedding(model, x)--@TinyJit-def blazeface_jit(model, x): return model(x)--@TinyJit-def adaface_jit(model, x): return model(x)--def precompute_embedding(model, x):- x = model.visual_conv1(x)- x = x.reshape(x.shape[0], x.shape[1], -1)- x = x.permute(0, 2, 1)- cls_emb = model.class_embedding- cls_emb = cls_emb.unsqueeze(0).expand(x.shape[0], -1, -1)- x = Tensor.cat(cls_emb, x, dim=1)- 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_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_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)- k = shape(k)- v = shape(v)- scale = 1.0 / (d_head ** 0.5)- attn_scores = q.matmul(k.transpose(-2, -1)) * scale- 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_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_img[i].ln_2(x)- ff = model.resblocks_img[i].mlp_c_fc(x_ln2)- ff = ff.gelu()- ff = model.resblocks_img[i].mlp_c_proj(ff)- x = x + ff-- x = model.ln_post(x)- image_embeds = x[:, 0, :]- embeddings = image_embeds @ model.proj- embeddings = embeddings / (embeddings.pow(2).sum(axis=-1, keepdim=True).sqrt() + 1e-8)- return embeddings\ No newline at end of file+ print(f"\nTotal {'face' if face else 'image'} embeddings loaded: {total_loaded}")\ No newline at end of filediff --git a/test/run_clip.py b/test/run_clip.pydeleted file mode 100644index ad89624..0000000--- a/test/run_clip.py+++ /dev/null@@ -1,18 +0,0 @@-from tinygrad import Tensor, TinyJit-from objects import ObjectFinder, precompute_embeddings_jit, precompute_embedding_jit_bs1-import time-import numpy as np-import sys--def teset_clip_jit(bs=1):- input1 = np.random.rand(bs, 3, 224, 224).astype(np.float32)- fun = precompute_embedding_jit_bs1 if bs == 1 else precompute_embeddings_jit- for _ in range(3): _ = fun(clip.model, Tensor(input1)).numpy()- ts = time.time()- _ = fun(clip.model, Tensor(input1)).numpy()- print(f"time (bs={bs}) =",round((time.time() - ts) / bs, 2), "seconds")--if __name__ == "__main__":- clip = ObjectFinder(clip=True)- bs = int(sys.argv[1])- teset_clip_jit(bs=bs)\ No newline at end of filediff --git a/test/test_clip.py b/test/test_clip.pyindex dd5a9e2..f7b130b 100644--- a/test/test_clip.py+++ b/test/test_clip.py@@ -6,7 +6,7 @@ import cv2def test_clip_outputs():img1 = cv2.imread("test/clip_images/f40.jpg")img1 = clip.preprocess(img1)- emb1 = precompute_embedding_jit_bs1(clip.model, Tensor(img1).unsqueeze(0))+ emb1 = clip.model.precompute_embedding(Tensor(img1).unsqueeze(0))emb1_text = clip.model._encode_text("ferrari f40")sim = (emb1_text @ emb1.T).numpy()[0]np.testing.assert_allclose(0.330654, sim, rtol=1e-6, atol=1e-6)diff --git a/test/test_clip_jit.py b/test/test_clip_jit.pydeleted file mode 100644index e8b2220..0000000--- a/test/test_clip_jit.py+++ /dev/null@@ -1,3 +0,0 @@-import subprocess-import sys-for i in range(8): subprocess.run([sys.executable, "test/run_clip.py", str(2**i)], check=True)\ No newline at end of filediff --git a/test/test_clip_speed.py b/test/test_clip_speed.pynew file mode 100644index 0000000..ffc7a81--- /dev/null+++ b/test/test_clip_speed.py@@ -0,0 +1,20 @@+from tinygrad import Tensor, TinyJit+from objects import ObjectFinder+from utils.helpers import jit_infer+import time+import numpy as np+import sys++def teset_clip_jit():+ for i in range(8):+ bs = 2**i+ input1 = np.random.rand(bs, 3, 224, 224).astype(np.float32)+ for _ in range(3): _ = jit_infer(clip.model.precompute_embedding, Tensor(input1), jit_cache=jit_cache).numpy()+ ts = time.time()+ _ = jit_infer(clip.model.precompute_embedding, Tensor(input1), jit_cache=jit_cache).numpy()+ print(f"time (bs={bs}) =",round((time.time() - ts) / bs, 2), "seconds")++if __name__ == "__main__":+ jit_cache = {}+ clip = ObjectFinder(clip=True)+ teset_clip_jit()\ No newline at end of filediff --git a/utils/helpers.py b/utils/helpers.pyindex 2eb153c..edd9d7a 100644--- a/utils/helpers.py+++ b/utils/helpers.py@@ -204,13 +204,14 @@ def export_and_upload(cam_name, thumbnail, userID, key, start=None, end=0, lengtupload_file(Path(f"{mp4_filename}.aes"), userID)os.unlink(mp4_filename)-def jit_infer(model, x, jit_cache):+def jit_infer(fn, x, jit_cache):shape = tuple(x.shape)if shape not in jit_cache:@TinyJit- def fn(x, model): return model(x)- jit_cache[shape] = fn- return jit_cache[shape](x, model)+ def compiled(x, fn):+ return fn(x)+ jit_cache[shape] = compiled+ return jit_cache[shape](x, fn)def find_ffmpeg():ffmpeg_path = shutil.which('ffmpeg')