midah commited on
Commit
3ace488
·
verified ·
1 Parent(s): dd7abff

Remove flat: scripts/embed_modal.py

Browse files
Files changed (1) hide show
  1. scripts/embed_modal.py +0 -167
scripts/embed_modal.py DELETED
@@ -1,167 +0,0 @@
1
- """Modal GPU job for CLIP embedding — ~10 min on A10G, no local storage.
2
-
3
- Mounts IMPACT from HF, runs CLIP ViT-L/14 on GPU, pushes parquet to HF Hub.
4
-
5
- Setup (one time):
6
- pip install modal
7
- modal setup # authenticate
8
- modal secret create hf-secret HF_TOKEN=hf_...
9
-
10
- Run:
11
- modal run scripts/cloud/embed_modal.py
12
-
13
- Output: hf://datasets/midah/patent-wireframes/embeddings_2022_vitl14.parquet
14
- """
15
-
16
- import io
17
- import os
18
-
19
- import modal
20
-
21
- # ── Modal image with all dependencies ────────────────────────────────────────
22
-
23
- image = (
24
- modal.Image.debian_slim(python_version="3.11")
25
- .pip_install(
26
- "open_clip_torch",
27
- "huggingface_hub",
28
- "datasets",
29
- "Pillow",
30
- "pandas",
31
- "numpy",
32
- "tqdm",
33
- )
34
- )
35
-
36
- app = modal.App("patent-clip-embed", image=image)
37
-
38
- # Secret holds HF_TOKEN
39
- hf_secret = modal.Secret.from_name("hf-secret")
40
-
41
-
42
- @app.function(
43
- gpu="A10G",
44
- timeout=3600,
45
- secrets=[hf_secret],
46
- memory=16384,
47
- )
48
- def embed_year(year: str = "2022", model_name: str = "ViT-L-14", pretrained: str = "openai"):
49
- import ast
50
- import csv
51
- import zipfile
52
-
53
- import numpy as np
54
- import open_clip
55
- import pandas as pd
56
- import torch
57
- from huggingface_hub import HfApi, hf_hub_download
58
- from PIL import Image
59
- from tqdm import tqdm
60
-
61
- token = os.environ["HF_TOKEN"]
62
- device = "cuda"
63
-
64
- # Load CLIP model
65
- print(f"Loading {model_name} ({pretrained}) on {device}...")
66
- model, _, preprocess = open_clip.create_model_and_transforms(
67
- model_name, pretrained=pretrained
68
- )
69
- model = model.to(device).eval()
70
-
71
- # Download IMPACT CSV (small — just metadata)
72
- csv_path = hf_hub_download(
73
- repo_id="AI4Patents/IMPACT",
74
- filename=f"{year}.csv",
75
- repo_type="dataset",
76
- token=token,
77
- )
78
-
79
- # Build list of (patent_id, figure_num, image_filename)
80
- figures = []
81
- with open(csv_path) as f:
82
- for row in csv.DictReader(f):
83
- try:
84
- fnames = ast.literal_eval(row["file_names"])
85
- pid = row["id"]
86
- for i, fn in enumerate(fnames):
87
- figures.append({"patent_id": pid, "figure_num": i, "filename": fn})
88
- except Exception:
89
- pass
90
-
91
- print(f"Total figures: {len(figures):,}")
92
-
93
- # Download the zip (4.4GB — into Modal's /tmp, ephemeral)
94
- print("Downloading IMPACT zip...")
95
- zip_path = hf_hub_download(
96
- repo_id="AI4Patents/IMPACT",
97
- filename=f"{year}.zip",
98
- repo_type="dataset",
99
- token=token,
100
- local_dir="/tmp/impact",
101
- )
102
-
103
- # Embed in batches
104
- BATCH = 64
105
- all_ids, all_vecs = [], []
106
-
107
- def load_image(fn: str) -> Image.Image | None:
108
- parts = fn.split("-D0")
109
- if len(parts) < 2:
110
- return None
111
- inner_path = f"{year}/{parts[0]}/{fn}"
112
- try:
113
- with zipfile.ZipFile(zip_path) as z:
114
- with z.open(inner_path) as f:
115
- return Image.open(io.BytesIO(f.read())).convert("RGB")
116
- except Exception:
117
- return None
118
-
119
- batch_imgs, batch_ids = [], []
120
-
121
- def flush_batch():
122
- if not batch_imgs:
123
- return
124
- tensors = torch.stack([preprocess(im) for im in batch_imgs]).to(device)
125
- with torch.no_grad():
126
- feats = model.encode_image(tensors)
127
- feats = feats / feats.norm(dim=-1, keepdim=True)
128
- all_vecs.append(feats.cpu().numpy())
129
- all_ids.extend(batch_ids)
130
- batch_imgs.clear()
131
- batch_ids.clear()
132
-
133
- for fig in tqdm(figures, desc="Embedding"):
134
- img = load_image(fig["filename"])
135
- if img is None:
136
- continue
137
- batch_imgs.append(img)
138
- pid = fig["patent_id"].lstrip("D").zfill(7)
139
- batch_ids.append(f"D{pid}_{fig['figure_num']}")
140
- if len(batch_imgs) >= BATCH:
141
- flush_batch()
142
- flush_batch()
143
-
144
- vecs = np.vstack(all_vecs).astype(np.float32)
145
- print(f"Embedded {len(all_ids):,} figures, shape {vecs.shape}")
146
-
147
- # Save parquet and push to Hub
148
- df = pd.DataFrame({"figure_id": all_ids, "embedding": list(vecs)})
149
- out = f"/tmp/embeddings_{year}_{model_name.lower().replace('-','')}.parquet"
150
- df.to_parquet(out, index=False)
151
-
152
- out_file = f"embeddings_{year}_vitl14.parquet"
153
- api = HfApi(token=token)
154
- api.upload_file(
155
- path_or_fileobj=out,
156
- path_in_repo=out_file,
157
- repo_id="midah/patent-wireframes",
158
- repo_type="dataset",
159
- )
160
- print(f"Pushed → hf://datasets/midah/patent-wireframes/{out_file}")
161
- return {"n_embedded": len(all_ids), "shape": list(vecs.shape)}
162
-
163
-
164
- @app.local_entrypoint()
165
- def main():
166
- result = embed_year.remote("2022")
167
- print("Done:", result)