Upload 2 files
Browse files- handler.py +140 -0
- requirements.txt +2 -0
handler.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Custom inference handler for Hugging Face Inference Endpoints.
|
| 3 |
+
|
| 4 |
+
Serves the Marqo GCL ViT-L-14 open_clip checkpoint as a pure encoder:
|
| 5 |
+
given text and/or image(s), it returns L2-normalized embeddings, exactly
|
| 6 |
+
matching the notebook's encode_text / encode_image + normalize steps.
|
| 7 |
+
|
| 8 |
+
Request (JSON):
|
| 9 |
+
{ "inputs": { "text": ["a red dress", ...], # optional
|
| 10 |
+
"image": ["<base64-encoded-image>", ...] } } # optional
|
| 11 |
+
|
| 12 |
+
Response (JSON):
|
| 13 |
+
{ "text_embeddings": [[... 768 floats ...], ...], # if text sent
|
| 14 |
+
"image_embeddings": [[... 768 floats ...], ...] } # if image sent
|
| 15 |
+
|
| 16 |
+
Fusion (alpha*img + (1-alpha)*txt) is intentionally NOT done here — that
|
| 17 |
+
happens in the n8n Code node, so this endpoint stays a clean encoder.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import os
|
| 21 |
+
import io
|
| 22 |
+
import glob
|
| 23 |
+
import base64
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import open_clip
|
| 27 |
+
from PIL import Image
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class EndpointHandler:
|
| 31 |
+
def __init__(self, path: str = ""):
|
| 32 |
+
# `path` is the local directory where the repo (including the .pt) is mounted.
|
| 33 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 34 |
+
|
| 35 |
+
# Architecture of the checkpoint. ViT-L-14 for the Marqo GCL model.
|
| 36 |
+
arch = os.environ.get("OPEN_CLIP_ARCH", "ViT-L-14")
|
| 37 |
+
|
| 38 |
+
# Build the architecture WITHOUT pretrained weights, then load the GCL checkpoint.
|
| 39 |
+
self.model, _, self.preprocess = open_clip.create_model_and_transforms(
|
| 40 |
+
arch, pretrained=None
|
| 41 |
+
)
|
| 42 |
+
self.tokenizer = open_clip.get_tokenizer(arch)
|
| 43 |
+
|
| 44 |
+
ckpt_path = self._find_checkpoint(path)
|
| 45 |
+
self._load_weights(ckpt_path)
|
| 46 |
+
|
| 47 |
+
self.model = self.model.to(self.device).eval()
|
| 48 |
+
|
| 49 |
+
# ---- locate the checkpoint file inside the repo ----
|
| 50 |
+
def _find_checkpoint(self, path: str) -> str:
|
| 51 |
+
# Allow an explicit override via env var (filename or absolute path).
|
| 52 |
+
env = os.environ.get("CHECKPOINT_FILE")
|
| 53 |
+
if env:
|
| 54 |
+
return env if os.path.isabs(env) else os.path.join(path, env)
|
| 55 |
+
|
| 56 |
+
candidates = (
|
| 57 |
+
glob.glob(os.path.join(path, "*.pt"))
|
| 58 |
+
+ glob.glob(os.path.join(path, "*.bin"))
|
| 59 |
+
+ glob.glob(os.path.join(path, "*.safetensors"))
|
| 60 |
+
)
|
| 61 |
+
if not candidates:
|
| 62 |
+
raise FileNotFoundError(
|
| 63 |
+
f"No .pt/.bin/.safetensors checkpoint found in '{path}'. "
|
| 64 |
+
"Set CHECKPOINT_FILE env var to the filename."
|
| 65 |
+
)
|
| 66 |
+
# If several exist, prefer the largest (the model weights, not a config shard).
|
| 67 |
+
return max(candidates, key=os.path.getsize)
|
| 68 |
+
|
| 69 |
+
# ---- load weights, tolerating the 'full_states' training-checkpoint layout ----
|
| 70 |
+
def _load_weights(self, ckpt_path: str) -> None:
|
| 71 |
+
# The Marqo file is named "...full_states.pt": a full training state that
|
| 72 |
+
# wraps the model weights under a 'state_dict' key and may prefix keys with
|
| 73 |
+
# 'module.' (from DDP training). open_clip.load_checkpoint normalizes both.
|
| 74 |
+
try:
|
| 75 |
+
open_clip.load_checkpoint(self.model, ckpt_path, strict=False)
|
| 76 |
+
return
|
| 77 |
+
except Exception as e:
|
| 78 |
+
print(f"[handler] open_clip.load_checkpoint fallback triggered: {e}")
|
| 79 |
+
|
| 80 |
+
# Manual fallback. weights_only=False is required because a full training
|
| 81 |
+
# state contains non-tensor objects (optimizer state, epoch, etc.).
|
| 82 |
+
ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)
|
| 83 |
+
|
| 84 |
+
if isinstance(ckpt, dict):
|
| 85 |
+
state_dict = ckpt.get("state_dict", ckpt.get("model", ckpt))
|
| 86 |
+
else:
|
| 87 |
+
state_dict = ckpt
|
| 88 |
+
|
| 89 |
+
# Strip a leading 'module.' from DDP-saved keys.
|
| 90 |
+
state_dict = {
|
| 91 |
+
(k[len("module."):] if k.startswith("module.") else k): v
|
| 92 |
+
for k, v in state_dict.items()
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
missing, unexpected = self.model.load_state_dict(state_dict, strict=False)
|
| 96 |
+
if missing:
|
| 97 |
+
print(f"[handler] missing keys (first 5): {list(missing)[:5]}")
|
| 98 |
+
if unexpected:
|
| 99 |
+
print(f"[handler] unexpected keys (first 5): {list(unexpected)[:5]}")
|
| 100 |
+
|
| 101 |
+
@torch.no_grad()
|
| 102 |
+
def __call__(self, data: dict) -> dict:
|
| 103 |
+
# HF passes {"inputs": ..., "parameters": ...}; be lenient about shape.
|
| 104 |
+
inputs = data.get("inputs", data) or {}
|
| 105 |
+
if not isinstance(inputs, dict):
|
| 106 |
+
return {"error": "Send an object under 'inputs' with 'text' and/or 'image'."}
|
| 107 |
+
|
| 108 |
+
out = {}
|
| 109 |
+
|
| 110 |
+
# ---- text embeddings ----
|
| 111 |
+
texts = inputs.get("text")
|
| 112 |
+
if texts:
|
| 113 |
+
if isinstance(texts, str):
|
| 114 |
+
texts = [texts]
|
| 115 |
+
tokens = self.tokenizer(texts).to(self.device)
|
| 116 |
+
feats = self.model.encode_text(tokens)
|
| 117 |
+
feats = feats / feats.norm(dim=-1, keepdim=True)
|
| 118 |
+
out["text_embeddings"] = feats.cpu().tolist()
|
| 119 |
+
|
| 120 |
+
# ---- image embeddings (base64-encoded bytes) ----
|
| 121 |
+
images = inputs.get("image")
|
| 122 |
+
if images:
|
| 123 |
+
if isinstance(images, str):
|
| 124 |
+
images = [images]
|
| 125 |
+
tensors = []
|
| 126 |
+
for b64 in images:
|
| 127 |
+
raw = base64.b64decode(b64)
|
| 128 |
+
img = Image.open(io.BytesIO(raw)).convert("RGB")
|
| 129 |
+
tensors.append(self.preprocess(img))
|
| 130 |
+
batch = torch.stack(tensors).to(self.device)
|
| 131 |
+
feats = self.model.encode_image(batch)
|
| 132 |
+
feats = feats / feats.norm(dim=-1, keepdim=True)
|
| 133 |
+
out["image_embeddings"] = feats.cpu().tolist()
|
| 134 |
+
|
| 135 |
+
if not out:
|
| 136 |
+
return {
|
| 137 |
+
"error": "Provide 'text' and/or 'image' (base64) under 'inputs'.",
|
| 138 |
+
"example": {"inputs": {"text": ["a red dress"]}},
|
| 139 |
+
}
|
| 140 |
+
return out
|
requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
open_clip_torch>=2.24.0
|
| 2 |
+
pillow
|