"""Modal GPU job for CLIP embedding — streams images from HF, no zip extraction. Streams images directly from AI4Patents/IMPACT using the HF datasets API (record-by-record, no zip download). Runs CLIP ViT-L/14 on GPU. Pushes embeddings parquet to HF Hub immediately — survives any /tmp cleanup. Setup (one time): modal setup modal secret create hf-secret HF_TOKEN=hf_... Run: modal run scripts/cloud/embed_modal.py --year 2022 Output: hf://datasets/midah/patent-wireframes/embeddings/{year}_vitl14.parquet """ import io import os import modal image = ( modal.Image.debian_slim(python_version="3.11") .pip_install( "open_clip_torch", "huggingface_hub", "datasets", "Pillow", "pandas", "numpy", "tqdm", "requests", ) ) import time as _time app = modal.App(f"patent-clip-{int(_time.time()) % 10000}", image=image) hf_secret = modal.Secret.from_name("hf-secret") OUT_REPO = "midah/patent-wireframes" @app.function( gpu="T4", # T4 less preempted than A10G; slower but completes timeout=21600, # 6 hours — T4 is slower, full scan ~5.5 hrs secrets=[hf_secret], memory=32768, retries=modal.Retries(max_retries=3, backoff_coefficient=2.0, initial_delay=10.0), ) def embed_year(year: str = "2022", model_name: str = "ViT-L-14", pretrained: str = "openai", batch_size: int = 64): """Stream images from IMPACT HF dataset, embed with CLIP, push to Hub.""" import ast import base64 import csv from pathlib import Path import numpy as np import open_clip import pandas as pd import requests import torch from huggingface_hub import HfApi, hf_hub_download from PIL import Image from tqdm import tqdm token = os.environ["HF_TOKEN"] device = "cuda" # ── Load CLIP ───────────────────────────────────────────────────────────── print(f"Loading {model_name} ({pretrained}) on {device}...") model, _, preprocess = open_clip.create_model_and_transforms( model_name, pretrained=pretrained ) model = model.to(device).eval() print("Model loaded.") # ── Download zip and metadata CSV ──────────────────────────────────────── print(f"Downloading IMPACT {year} zip (~4.4GB) and CSV...") zip_path = hf_hub_download( repo_id="AI4Patents/IMPACT", filename=f"{year}.zip", repo_type="dataset", token=token, local_dir="/tmp/impact", ) csv_path = hf_hub_download( repo_id="AI4Patents/IMPACT", filename=f"{year}.csv", repo_type="dataset", token=token, local_dir="/tmp/impact", ) # Build figure list from CSV to get patent IDs for output pid_map = {} # filename → (patent_id, figure_num) with open(csv_path) as f: for row in csv.DictReader(f): try: fnames = ast.literal_eval(row.get("file_names") or "[]") pid = row.get("id") or "" for i, fn in enumerate(fnames): pid_map[fn] = (pid, i) except Exception: pass print(f"Total expected figures: {len(pid_map):,}") # ── Sequential mmap scan of zip — avoids EOCD / central directory ──────── # The zip has a corrupt/non-standard Zip64 central directory that defeats # Python's zipfile and 7z extraction. Instead, scan local file headers # (PK\x03\x04) sequentially using mmap — no central directory needed. # Each TIF is decompressed in memory and fed directly to GPU. import mmap, zlib, struct SIG_LOCAL = b"PK\x03\x04" def scan_zip_and_embed(zip_path: str): """Yield (filename, PIL.Image) by scanning zip local headers.""" with open(zip_path, "rb") as f: mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) pos = 0 total_size = mm.size() while pos < total_size - 30: idx = mm.find(SIG_LOCAL, pos) if idx < 0: break header = mm[idx: idx + 30] if len(header) < 30: break flags = struct.unpack_from(" Image.Image | None: return None # unused — we use scan_zip_and_embed instead # ── Resume from existing HF checkpoint ─────────────────────────────────── # Download any existing embeddings from HF so we accumulate across preemptions # rather than restarting from zero each time. all_ids: list[str] = [] all_vecs: list[np.ndarray] = [] already_embedded: set[str] = set() existing_path = f"/tmp/{year}_existing.parquet" try: existing_hf = hf_hub_download( repo_id=OUT_REPO, filename=f"embeddings/{year}_vitl14.parquet", repo_type="dataset", token=token, local_dir="/tmp/impact", ) existing_df = pd.read_parquet(existing_hf) already_embedded = set(existing_df["figure_id"].tolist()) # Seed all_ids / all_vecs with existing embeddings all_ids = existing_df["figure_id"].tolist() # Convert object-array of 768-dim vectors to proper 2D float32 array existing_vecs = np.vstack(existing_df["embedding"].tolist()).astype(np.float32) all_vecs = [existing_vecs] print(f"Resuming from {len(already_embedded):,} existing embeddings on HF") except Exception: print("No existing checkpoint — starting fresh") batch_imgs: list[Image.Image] = [] batch_ids: list[str] = [] n_processed = 0 last_checkpoint_n = len(all_ids) // 10000 # start above existing checkpoints CHECKPOINT_EVERY = 25000 # unused field — kept for reference def flush_batch(): if not batch_imgs: return tensors = torch.stack([preprocess(im) for im in batch_imgs]).to(device) with torch.no_grad(): feats = model.encode_image(tensors) feats = feats / feats.norm(dim=-1, keepdim=True) all_vecs.append(feats.cpu().numpy()) all_ids.extend(batch_ids) batch_imgs.clear() batch_ids.clear() print(f"Scanning zip and embedding (sequential mmap, no EOCD needed)...") for basename, img in scan_zip_and_embed(zip_path): n_processed += 1 if n_processed % 5000 == 0: print(f" {n_processed:,} files scanned, {len(all_ids):,} embedded") # Map basename back to patent ID using pid_map pid_raw, fig_num = pid_map.get(basename, (None, None)) if pid_raw is None: continue pid_norm = str(pid_raw).lstrip("D").zfill(7) fig_id = f"D{pid_norm}_{fig_num}" # Skip already-embedded figures if fig_id in already_embedded: continue batch_ids.append(fig_id) batch_imgs.append(img) if len(batch_imgs) >= batch_size: flush_batch() # Checkpoint every 10k NEW embeddings to HF current_boundary = len(all_ids) // 10000 if current_boundary > last_checkpoint_n and len(all_ids) > len(already_embedded): _vecs_cp = np.vstack(all_vecs).astype(np.float32) _norms_cp = np.linalg.norm(_vecs_cp, axis=1, keepdims=True) _vecs_cp /= np.maximum(_norms_cp, 1e-8) _df_cp = pd.DataFrame({"figure_id": list(all_ids), "embedding": list(_vecs_cp)}) _out_cp = f"/tmp/{year}_cp.parquet" _df_cp.to_parquet(_out_cp, index=False) HfApi(token=token).upload_file( path_or_fileobj=_out_cp, path_in_repo=f"embeddings/{year}_vitl14.parquet", repo_id=OUT_REPO, repo_type="dataset", commit_message=f"Checkpoint {len(all_ids):,} for {year}", ) print(f" Checkpoint: {len(all_ids):,} embeddings on HF") last_checkpoint_n = current_boundary flush_batch() print(f"Scan complete: {n_processed:,} files scanned, {len(all_ids):,} embedded") print(f"Embedded: {len(all_ids):,} figures") if not all_ids: print("No figures embedded — check HF access") return {"n": 0} # ── Normalize + save + push ─────────────────────────────────────────────── vecs = np.vstack(all_vecs).astype(np.float32) norms = np.linalg.norm(vecs, axis=1, keepdims=True) vecs /= np.maximum(norms, 1e-8) df = pd.DataFrame({"figure_id": all_ids, "embedding": list(vecs)}) out_file = f"embeddings/{year}_vitl14.parquet" local_out = f"/tmp/{year}_vitl14.parquet" df.to_parquet(local_out, index=False) size_mb = Path(local_out).stat().st_size / 1e6 print(f"Parquet: {size_mb:.1f}MB — pushing to HF Hub...") api = HfApi(token=token) api.upload_file( path_or_fileobj=local_out, path_in_repo=out_file, repo_id=OUT_REPO, repo_type="dataset", commit_message=f"Add CLIP embeddings for {year}", ) print(f"Pushed → hf://datasets/{OUT_REPO}/{out_file}") return {"year": year, "n_embedded": len(all_ids), "shape": list(vecs.shape)} @app.local_entrypoint() def main(year: str = "2022"): print(f"Embedding year: {year}") result = embed_year.remote(year) print("Done:", result)