system HF Staff commited on
Commit
56749a4
·
verified ·
1 Parent(s): 83f3ec5

deploy: sync encoder from 736c3e5

Browse files
Files changed (8) hide show
  1. .dockerignore +5 -0
  2. .gitignore +2 -0
  3. Dockerfile +28 -0
  4. README.md +16 -5
  5. app.py +63 -0
  6. pytest.ini +3 -0
  7. requirements.txt +10 -0
  8. text_encoder.py +99 -0
.dockerignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ .venv/
2
+ __pycache__/
3
+ tests/
4
+ scripts/
5
+ .gitignore
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ .venv/
2
+ __pycache__/
Dockerfile ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.12-slim
2
+
3
+ # HF Spaces runs containers as a non-root user; create one and give it a writable
4
+ # HF cache so the baked-in model is readable at runtime.
5
+ RUN useradd -m -u 1000 user
6
+ ENV HF_HOME=/home/user/.cache/huggingface \
7
+ PYTHONUNBUFFERED=1
8
+ WORKDIR /home/user/app
9
+
10
+ COPY requirements.txt .
11
+ RUN pip install --no-cache-dir -r requirements.txt
12
+
13
+ ARG SIGLIP_MODEL_ID=onnx-community/siglip2-base-patch16-256-ONNX
14
+ ENV SIGLIP_MODEL_ID=${SIGLIP_MODEL_ID}
15
+ COPY text_encoder.py app.py ./
16
+
17
+ USER user
18
+ # Bake the 283 MB text tower + tokenizer into the image so a post-sleep wake
19
+ # never re-downloads from HuggingFace.
20
+ RUN python -c "import os; \
21
+ from huggingface_hub import hf_hub_download; \
22
+ from transformers import AutoTokenizer; \
23
+ m = os.environ['SIGLIP_MODEL_ID']; \
24
+ hf_hub_download(m, 'onnx/text_model_quantized.onnx'); \
25
+ AutoTokenizer.from_pretrained(m)"
26
+
27
+ EXPOSE 7860
28
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
README.md CHANGED
@@ -1,10 +1,21 @@
1
  ---
2
- title: Reflections Encoder
3
- emoji: 🐢
4
- colorFrom: gray
5
- colorTo: indigo
6
  sdk: docker
 
7
  pinned: false
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Reflections SigLIP Encoder
3
+ emoji: 🔎
4
+ colorFrom: indigo
5
+ colorTo: blue
6
  sdk: docker
7
+ app_port: 7860
8
  pinned: false
9
  ---
10
 
11
+ # Reflections SigLIP text-query encoder
12
+
13
+ Embeds a natural-language query into a 768-d L2-normalized vector using the
14
+ SigLIP2 text tower (`onnx-community/siglip2-base-patch16-256-ONNX`), in the same
15
+ cosine space as the photo image embeddings.
16
+
17
+ - `POST /encode` — `{ "query": "..." }` → `{ "vector": [768 floats] }`. Requires
18
+ `Authorization: Bearer $SIGLIP_ENCODER_TOKEN`.
19
+ - `GET /health` — liveness for the keep-warm cron.
20
+
21
+ Set the Space secret `SIGLIP_ENCODER_TOKEN`. The model is baked into the image.
app.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FastAPI wrapper around the SigLIP text encoder for HuggingFace Spaces.
3
+
4
+ POST /encode {query} -> {vector:[768]} (bearer-token auth)
5
+ GET /health -> {status:"ok"} (open, for the keep-warm ping)
6
+
7
+ The model + tokenizer load once at startup (lifespan) and stay resident, so every
8
+ request after wake is warm. The 283 MB model is baked into the Docker image, so a
9
+ post-sleep restart doesn't re-download.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ import secrets
15
+ from contextlib import asynccontextmanager
16
+
17
+ from fastapi import Depends, FastAPI, Header, HTTPException
18
+ from pydantic import BaseModel
19
+
20
+ from text_encoder import EMBED_DIM, encode, warmup
21
+
22
+ ENCODER_TOKEN = os.environ.get("SIGLIP_ENCODER_TOKEN", "")
23
+
24
+
25
+ @asynccontextmanager
26
+ async def lifespan(_app: FastAPI):
27
+ warmup()
28
+ yield
29
+
30
+
31
+ app = FastAPI(lifespan=lifespan)
32
+
33
+
34
+ class EncodeRequest(BaseModel):
35
+ query: str
36
+
37
+
38
+ class EncodeResponse(BaseModel):
39
+ vector: list[float]
40
+
41
+
42
+ def require_token(authorization: str = Header(default="")) -> None:
43
+ if not ENCODER_TOKEN:
44
+ raise HTTPException(status_code=500, detail="encoder token not configured")
45
+ # Constant-time compare so the endpoint isn't a timing oracle for the token.
46
+ if not secrets.compare_digest(authorization, f"Bearer {ENCODER_TOKEN}"):
47
+ raise HTTPException(status_code=401, detail="unauthorized")
48
+
49
+
50
+ @app.get("/health")
51
+ def health() -> dict[str, str]:
52
+ return {"status": "ok"}
53
+
54
+
55
+ @app.post("/encode", response_model=EncodeResponse, dependencies=[Depends(require_token)])
56
+ def encode_query(body: EncodeRequest) -> EncodeResponse:
57
+ query = body.query.strip()
58
+ if not query:
59
+ raise HTTPException(status_code=422, detail="empty query")
60
+ vec = encode(query)
61
+ if len(vec) != EMBED_DIM:
62
+ raise HTTPException(status_code=500, detail=f"expected {EMBED_DIM} dims, got {len(vec)}")
63
+ return EncodeResponse(vector=vec)
pytest.ini ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [pytest]
2
+ testpaths = tests
3
+ python_files = test_*.py
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi==0.115.5
2
+ uvicorn[standard]==0.32.1
3
+ onnxruntime==1.20.1
4
+ numpy==2.1.3
5
+ huggingface_hub==0.26.2
6
+ transformers==4.46.3
7
+ sentencepiece==0.2.0
8
+ protobuf==5.28.3
9
+ pytest==8.3.3
10
+ httpx==0.27.2
text_encoder.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SigLIP text-tower query encoder via ONNX Runtime (CPU, no torch).
3
+
4
+ Mirrors ingest/embedder.py's image tower — same checkpoint, same `pooler_output`
5
+ head, same L2-normalization — so a query vector and a stored image vector share
6
+ one cosine space. The only differences: the text tower instead of the vision
7
+ tower, and a tokenizer instead of pixel preprocessing.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import functools
12
+ import os
13
+
14
+ import numpy as np
15
+ import onnxruntime as ort
16
+ from huggingface_hub import hf_hub_download
17
+ from transformers import AutoTokenizer
18
+
19
+ # Same checkpoint the image pipeline embeds with (ingest/embedder.py) and the web
20
+ # app references (env.server.ts SIGLIP_MODEL_ID). Must stay in lockstep or text
21
+ # and image vectors stop sharing a cosine space.
22
+ MODEL_REPO = os.environ.get("SIGLIP_MODEL_ID", "onnx-community/siglip2-base-patch16-256-ONNX")
23
+ # int8 text tower (283 MB) — matches the web app's q8 dtype.
24
+ ONNX_FILE = "onnx/text_model_quantized.onnx"
25
+ EMBED_DIM = 768
26
+ # SigLIP2's GemmaTokenizer has a sentinel model_max_length; the real training pad
27
+ # length lives in tokenizer_config.json (64). Must match the web tokenizer call.
28
+ MAX_LENGTH = 64
29
+ CACHE_SIZE = 512
30
+
31
+ _TEXT_EMBED_OUTPUT = "pooler_output"
32
+ _INPUT_IDS = "input_ids"
33
+
34
+ _SESSION: ort.InferenceSession | None = None
35
+ _TOKENIZER = None
36
+
37
+
38
+ def load_session() -> ort.InferenceSession:
39
+ """Download (HF-hub-cached) the text ONNX and build a CPU session once."""
40
+ global _SESSION
41
+ if _SESSION is None:
42
+ path = hf_hub_download(MODEL_REPO, ONNX_FILE)
43
+ _SESSION = ort.InferenceSession(path, providers=["CPUExecutionProvider"])
44
+ return _SESSION
45
+
46
+
47
+ def load_tokenizer():
48
+ """Load the GemmaTokenizer for the checkpoint once."""
49
+ global _TOKENIZER
50
+ if _TOKENIZER is None:
51
+ _TOKENIZER = AutoTokenizer.from_pretrained(MODEL_REPO)
52
+ return _TOKENIZER
53
+
54
+
55
+ def warmup() -> None:
56
+ """Load both heavy objects so the first real request doesn't pay for it."""
57
+ load_session()
58
+ load_tokenizer()
59
+
60
+
61
+ @functools.lru_cache(maxsize=CACHE_SIZE)
62
+ def _encode_cached(query: str) -> tuple[float, ...]:
63
+ session = load_session()
64
+ tokenizer = load_tokenizer()
65
+ enc = tokenizer(
66
+ [query],
67
+ padding="max_length",
68
+ truncation=True,
69
+ max_length=MAX_LENGTH,
70
+ return_tensors="np",
71
+ )
72
+ output_names = [o.name for o in session.get_outputs()]
73
+ # Fail loudly rather than embedding from the wrong head if a future export
74
+ # drops/renames pooler_output (matches ingest/embedder.py's guard).
75
+ if _TEXT_EMBED_OUTPUT not in output_names:
76
+ raise ValueError(
77
+ f"ONNX model does not expose '{_TEXT_EMBED_OUTPUT}'; available: {output_names}"
78
+ )
79
+ # Feed only the inputs the model declares (SigLIP text uses input_ids; some
80
+ # exports also take attention_mask). int64 is what ONNX expects for ids.
81
+ input_names = {i.name for i in session.get_inputs()}
82
+ feed = {name: enc[name].astype(np.int64) for name in input_names if name in enc}
83
+ if _INPUT_IDS not in feed:
84
+ raise ValueError(
85
+ f"ONNX model does not accept '{_INPUT_IDS}'; inputs: {sorted(input_names)}"
86
+ )
87
+ out = session.run([_TEXT_EMBED_OUTPUT], feed)[0]
88
+ vec = np.asarray(out, dtype=np.float32).reshape(EMBED_DIM)
89
+ norm = float(np.linalg.norm(vec))
90
+ vec = vec / max(norm, 1e-12)
91
+ return tuple(float(x) for x in vec)
92
+
93
+
94
+ def encode(query: str) -> list[float]:
95
+ """Encode a query into a 768-d L2-normalized vector, cosine-comparable to
96
+ photos.embedding. Cached by exact query string."""
97
+ if not query or not query.strip():
98
+ raise ValueError("encode: empty query")
99
+ return list(_encode_cached(query))