File size: 5,592 Bytes
25dab88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
"""Handicate vision: identify anything, and learn new concepts on the fly.

Two parts:
  1. VisionPerceiver  -- a VLM (Qwen2.5-VL) that identifies/describes an image, plus an
     image embedder (SigLIP) for the concept memory.
  2. ConceptMemory    -- a growing vector store of (image_embedding -> label). Teaching a
     new thing is instant (learn); recognizing it later is a nearest-neighbour lookup
     (no retraining). This is the "learn on the fly" mechanism.

How it ties into the improving system: the concept memory is periodically DISTILLED into
the VLM's weights (vision SFT on the accumulated (image, label) pairs) and then the raw
entries are DISCARDED -- on-the-fly knowledge becomes permanent, weighted knowledge.

Honest scope: a VLM identifies a broad range, not literally everything. The memory +
distillation is how Handicate expands to new/unusual/just-shown things over time.
"""
import json
from pathlib import Path

import numpy as np


class ConceptMemory:
    """Instant on-the-fly visual learning via an embedding store (pure numpy, testable)."""

    def __init__(self, path=None):
        self.labels = []
        self.embs = []          # list of unit-norm np.float32 vectors
        self.path = path
        if path and Path(path).exists():
            self.load()

    @staticmethod
    def _unit(v):
        v = np.asarray(v, dtype=np.float32)
        return v / (np.linalg.norm(v) + 1e-8)

    def learn(self, embedding, label):
        """Teach a new concept instantly -- no training step."""
        self.embs.append(self._unit(embedding))
        self.labels.append(label)

    def recognize(self, embedding):
        """Return (label, similarity) of the closest learned concept, or (None, 0)."""
        if not self.embs:
            return None, 0.0
        e = self._unit(embedding)
        sims = np.array([float(e @ m) for m in self.embs])
        i = int(sims.argmax())
        return self.labels[i], float(sims[i])

    def export_for_distill(self):
        """The (label, embedding) pairs to fold into the VLM, after which raw is discarded."""
        return [{"label": l, "embedding": e.tolist()} for l, e in zip(self.labels, self.embs)]

    def clear(self):
        self.labels, self.embs = [], []

    def save(self):
        if not self.path:
            return
        Path(self.path).parent.mkdir(parents=True, exist_ok=True)
        np.savez(self.path, embs=np.array(self.embs) if self.embs else np.zeros((0,)),
                 labels=np.array(self.labels, dtype=object))

    def load(self):
        d = np.load(self.path, allow_pickle=True)
        self.embs = [self._unit(e) for e in d["embs"]] if len(d["embs"]) else []
        self.labels = list(d["labels"])


class VisionPerceiver:
    """Eyes: VLM identification + image embedding. Lazy-loaded (GPU)."""

    def __init__(self, vlm="Qwen/Qwen2.5-VL-3B-Instruct",
                 embedder="google/siglip-base-patch16-224", device="cuda"):
        self.vlm_name, self.emb_name, self.device = vlm, embedder, device
        self._vlm = self._proc = self._emb = self._emb_proc = None

    def _ensure_vlm(self):
        if self._vlm is None:
            import torch
            from transformers import AutoModelForImageTextToText, AutoProcessor
            self._proc = AutoProcessor.from_pretrained(self.vlm_name)
            self._vlm = AutoModelForImageTextToText.from_pretrained(
                self.vlm_name, torch_dtype=torch.bfloat16, device_map=self.device)

    def _ensure_emb(self):
        if self._emb is None:
            import torch
            from transformers import AutoModel, AutoProcessor
            self._emb_proc = AutoProcessor.from_pretrained(self.emb_name)
            self._emb = AutoModel.from_pretrained(
                self.emb_name, torch_dtype=torch.float32, device_map=self.device)

    def identify(self, image, question="What is in this image? Identify it specifically."):
        self._ensure_vlm()
        import torch
        msgs = [{"role": "user", "content": [{"type": "image", "image": image},
                                             {"type": "text", "text": question}]}]
        inputs = self._proc.apply_chat_template(msgs, add_generation_prompt=True,
                                                tokenize=True, return_dict=True, return_tensors="pt")
        inputs = {k: v.to(self._vlm.device) for k, v in inputs.items()}
        with torch.no_grad():
            out = self._vlm.generate(**inputs, max_new_tokens=120, do_sample=False)
        return self._proc.decode(out[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True).strip()

    def embed(self, image):
        self._ensure_emb()
        import torch
        from PIL import Image
        img = Image.open(image).convert("RGB") if isinstance(image, str) else image
        inp = self._emb_proc(images=img, return_tensors="pt").to(self._emb.device)
        with torch.no_grad():
            feats = self._emb.get_image_features(**inp)
        return feats[0].float().cpu().numpy()

    def see(self, image, memory, threshold=0.85, label=None):
        """The on-the-fly loop: teach if a label is given, else recognize-or-identify."""
        emb = self.embed(image)
        if label is not None:
            memory.learn(emb, label)
            return f"learned '{label}' on the fly"
        known, sim = memory.recognize(emb)
        if known and sim >= threshold:
            return f"{known}  (recognized from memory, sim {sim:.2f})"
        desc = self.identify(image)
        return f"{desc}  (identified by VLM; teach me with a label to remember it)"