Spaces:
Running on Zero
Running on Zero
Download engine.py from townbox/clean-my-dataset: direct link, hf CLI and curl.
- Browser
- Download file 7.2 kB
-
https://huggingface.co/spaces/townbox/clean-my-dataset/resolve/main/engine.py
- Command line
-
hf download hf://spaces/townbox/clean-my-dataset/engine.py
-
curl -L -o engine.py https://huggingface.co/spaces/townbox/clean-my-dataset/resolve/main/engine.py
7.2 kB
| """Mistral Multimodal Embed 1B: loading, image preparation and embedding. | |
| Images are embedded on ZeroGPU. Search queries are short, so they are embedded on the CPU with a float32 copy of the | |
| text tower: no GPU queue, no GPU quota, and the same vectors as the GPU path to within bf16 rounding. | |
| """ | |
| from __future__ import annotations | |
| import copy | |
| import hashlib | |
| import io | |
| import os | |
| import time | |
| import spaces # noqa: F401 (must be imported before torch initializes CUDA) | |
| import cv2 | |
| import numpy as np | |
| import torch | |
| from PIL import Image, ImageOps | |
| from transformers import AutoModel, AutoTokenizer | |
| MODEL = "mistralai/mistral-multimodal-embed-1B" | |
| REVISION = "4d0e936674cff0439f1727058fcf98fc15066090" | |
| SIZE = 224 # the card reports stable accuracy from 224 to 1036 px; 224 keeps analysis fast | |
| GRID = 28 # patch 14 x merge 2: both sides must be multiples of 28 | |
| THUMB = 512 # sharp on phones (cards are ~200 CSS px at 3x); CC3M's own images are 512 px | |
| MEAN = (0.48145466, 0.4578275, 0.40821073) | |
| STD = (0.26862954, 0.26130258, 0.27577711) | |
| Image.MAX_IMAGE_PIXELS = 120_000_000 | |
| cv2.setNumThreads(1) | |
| def cpu_limit() -> int: | |
| """CPUs this container may use: the cgroup quota, not the host's count.""" | |
| try: | |
| quota, period = open("/sys/fs/cgroup/cpu.max").read().split() | |
| if quota != "max": | |
| return max(1, int(quota) // int(period)) | |
| except (OSError, ValueError): | |
| pass | |
| return len(os.sched_getaffinity(0)) | |
| CPUS = cpu_limit() | |
| torch.set_num_threads(max(1, min(CPUS, 8))) | |
| DEVICE = "cuda" if torch.cuda.is_available() else "cpu" | |
| _t = time.time() | |
| model = AutoModel.from_pretrained(MODEL, revision=REVISION, trust_remote_code=True, dtype=torch.bfloat16).eval() | |
| tokenizer = AutoTokenizer.from_pretrained(MODEL, revision=REVISION, trust_remote_code=True) | |
| text_cpu = copy.deepcopy(model.text_model).float().eval() | |
| EOS = model.config.eos_token_id | |
| model.to(DEVICE) | |
| print(f"model loaded in {time.time() - _t:.0f}s on {DEVICE}, {CPUS} CPUs", flush=True) | |
| # ------------------------------------------------------------------ images | |
| def trim_letterbox(a: np.ndarray, tol: int = 245) -> np.ndarray: | |
| """Remove centered white or black bars that downloaders add when they pad images to a square.""" | |
| h, w, _ = a.shape | |
| for value in (255, 0): | |
| far = (a < tol).any(2) if value == 255 else (a > 255 - tol).any(2) | |
| rows, cols = np.flatnonzero(far.any(1)), np.flatnonzero(far.any(0)) | |
| if len(rows) == 0: | |
| return a | |
| top, bottom, left, right = rows[0], h - 1 - rows[-1], cols[0], w - 1 - cols[-1] | |
| if min(top, bottom) > 0.04 * h and abs(top - bottom) <= 0.02 * h + 2 and max(left, right) <= 1: | |
| return a[top:h - bottom] | |
| if min(left, right) > 0.04 * w and abs(left - right) <= 0.02 * w + 2 and max(top, bottom) <= 1: | |
| return a[:, left:w - right] | |
| return a | |
| def decode(data: bytes) -> np.ndarray: | |
| """Full-quality decode to RGB. JPEG draft decoding is only used for photos at least 4x larger than needed: | |
| it is much faster, and the 4x area downscale that follows hides its difference (draft decoding to a size close | |
| to the target shifts this model's embeddings noticeably).""" | |
| im = Image.open(io.BytesIO(data)) | |
| if im.format == "JPEG" and min(im.size) >= 8 * SIZE: | |
| im.draft("RGB", (4 * SIZE, 4 * SIZE)) | |
| if "exif" in im.info: | |
| im = ImageOps.exif_transpose(im) | |
| if im.mode in ("RGBA", "LA", "PA", "P"): | |
| im = im.convert("RGBA") | |
| bg = Image.new("RGBA", im.size, (255, 255, 255, 255)) | |
| im = Image.alpha_composite(bg, im) | |
| return trim_letterbox(np.asarray(im.convert("RGB"))) | |
| def model_input(a: np.ndarray) -> np.ndarray: | |
| h, w = a.shape[:2] | |
| s = SIZE / max(h, w) | |
| th = ((max(round(h * s), 1) - 1) // GRID + 1) * GRID | |
| tw = ((max(round(w * s), 1) - 1) // GRID + 1) * GRID | |
| interp = cv2.INTER_AREA if th <= h and tw <= w else cv2.INTER_CUBIC | |
| return cv2.resize(a, (tw, th), interpolation=interp) | |
| def thumbnail(a: np.ndarray, path: str) -> tuple[int, int]: | |
| h, w = a.shape[:2] | |
| s = min(1.0, THUMB / max(h, w)) | |
| t = cv2.resize(a, (max(1, round(w * s)), max(1, round(h * s))), interpolation=cv2.INTER_AREA) if s < 1 else a | |
| Image.fromarray(t).save(path, "WEBP", quality=82, method=4) | |
| return t.shape[1], t.shape[0] | |
| def digest(data: bytes) -> int: | |
| return int.from_bytes(hashlib.md5(data).digest()[:8], "little", signed=True) | |
| # ------------------------------------------------------------------ embedding | |
| def _embed_images(arrays: list[np.ndarray], device: str, batch_tokens: int = 65536) -> np.ndarray: | |
| out = np.zeros((len(arrays), 1024), dtype=np.float16) | |
| mean = torch.tensor(MEAN, device=device).view(1, 3, 1, 1) | |
| std = torch.tensor(STD, device=device).view(1, 3, 1, 1) | |
| groups: dict[tuple[int, int], list[int]] = {} | |
| for i, a in enumerate(arrays): | |
| groups.setdefault(a.shape[:2], []).append(i) | |
| with torch.inference_mode(): | |
| for (h, w), idx in groups.items(): | |
| bs = max(1, batch_tokens // ((h // 14) * (w // 14))) | |
| for j in range(0, len(idx), bs): | |
| part = idx[j:j + bs] | |
| x = torch.from_numpy(np.stack([arrays[i] for i in part])).to(device) | |
| x = ((x.permute(0, 3, 1, 2).float() / 255 - mean) / std).to(torch.bfloat16) | |
| out[part] = model.vision_model(x).half().cpu().numpy() | |
| return out | |
| def _tokens(texts: list[str], max_tokens: int = 256): | |
| texts = [t if t and t.strip() else " " for t in texts] | |
| tok = tokenizer(texts, padding=True, truncation=True, max_length=max_tokens, return_tensors="pt") | |
| ids, mask = tok.input_ids, tok.attention_mask | |
| ids[torch.arange(len(ids)), mask.sum(1) - 1] = EOS # truncation can drop the end token the model pools from | |
| return ids, mask | |
| def _embed_texts(texts: list[str], device: str, batch: int = 512) -> np.ndarray: | |
| out = np.zeros((len(texts), 1024), dtype=np.float16) | |
| order = np.argsort([len(t or "") for t in texts]) | |
| with torch.inference_mode(): | |
| for j in range(0, len(order), batch): | |
| part = order[j:j + batch] | |
| ids, mask = _tokens([texts[i] for i in part]) | |
| out[part] = model.get_text_features(ids.to(device), mask.to(device)).half().cpu().numpy() | |
| return out | |
| def gpu_seconds(arrays: list[np.ndarray], texts: list[str]) -> int: | |
| # about 500 images/s on half an RTX PRO 6000 at 224 px, captions are ~6x cheaper; plus attach overhead | |
| return int(min(120, 12 + len(arrays) / 300 + len(texts) / 2000)) | |
| def embed_on_gpu(arrays: list[np.ndarray], texts: list[str]) -> tuple[np.ndarray, np.ndarray | None]: | |
| img = _embed_images(arrays, DEVICE) | |
| txt = _embed_texts(texts, DEVICE) if texts else None | |
| return img, txt | |
| def embed_query(text: str) -> np.ndarray: | |
| """One search query on the CPU, float32.""" | |
| ids, mask = _tokens([text]) | |
| with torch.inference_mode(): | |
| return text_cpu(ids, mask).float().numpy()[0] | |
| _t = time.time() | |
| embed_query("warm-up") | |
| _t = time.time() | |
| embed_query("a fox in snow") | |
| print(f"CPU query embedding: {1000 * (time.time() - _t):.0f} ms", flush=True) | |