midah commited on
Commit
40e498d
·
verified ·
1 Parent(s): 41af2b1

Fix embed_modal: stream from HF instead of zip extraction

Browse files
Files changed (1) hide show
  1. scripts/cloud/embed_modal.py +87 -55
scripts/cloud/embed_modal.py CHANGED
@@ -1,16 +1,17 @@
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
@@ -18,8 +19,6 @@ 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(
@@ -30,29 +29,34 @@ image = (
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
@@ -61,14 +65,16 @@ def embed_year(year: str = "2022", model_name: str = "ViT-L-14", pretrained: str
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 (smalljust metadata)
 
72
  csv_path = hf_hub_download(
73
  repo_id="AI4Patents/IMPACT",
74
  filename=f"{year}.csv",
@@ -76,47 +82,60 @@ def embed_year(year: str = "2022", model_name: str = "ViT-L-14", pretrained: str
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:
@@ -130,38 +149,51 @@ def embed_year(year: str = "2022", model_name: str = "ViT-L-14", pretrained: str
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)
 
1
+ """Modal GPU job for CLIP embedding — streams images from HF, no zip extraction.
2
 
3
+ Streams images directly from AI4Patents/IMPACT using the HF datasets API
4
+ (record-by-record, no zip download). Runs CLIP ViT-L/14 on GPU.
5
+ Pushes embeddings parquet to HF Hub immediately — survives any /tmp cleanup.
6
 
7
  Setup (one time):
8
+ modal setup
 
9
  modal secret create hf-secret HF_TOKEN=hf_...
10
 
11
  Run:
12
+ modal run scripts/cloud/embed_modal.py --year 2022
13
 
14
+ Output: hf://datasets/midah/patent-wireframes/embeddings/{year}_vitl14.parquet
15
  """
16
 
17
  import io
 
19
 
20
  import modal
21
 
 
 
22
  image = (
23
  modal.Image.debian_slim(python_version="3.11")
24
  .pip_install(
 
29
  "pandas",
30
  "numpy",
31
  "tqdm",
32
+ "requests",
33
  )
34
  )
35
 
36
  app = modal.App("patent-clip-embed", image=image)
 
 
37
  hf_secret = modal.Secret.from_name("hf-secret")
38
 
39
+ OUT_REPO = "midah/patent-wireframes"
40
+
41
 
42
  @app.function(
43
  gpu="A10G",
44
+ timeout=7200,
45
  secrets=[hf_secret],
46
+ memory=32768,
47
  )
48
+ def embed_year(year: str = "2022", model_name: str = "ViT-L-14",
49
+ pretrained: str = "openai", batch_size: int = 64):
50
+ """Stream images from IMPACT HF dataset, embed with CLIP, push to Hub."""
51
  import ast
52
+ import base64
53
  import csv
54
+ from pathlib import Path
55
 
56
  import numpy as np
57
  import open_clip
58
  import pandas as pd
59
+ import requests
60
  import torch
61
  from huggingface_hub import HfApi, hf_hub_download
62
  from PIL import Image
 
65
  token = os.environ["HF_TOKEN"]
66
  device = "cuda"
67
 
68
+ # ── Load CLIP ─────────────────────────────────────────────────────────────
69
  print(f"Loading {model_name} ({pretrained}) on {device}...")
70
  model, _, preprocess = open_clip.create_model_and_transforms(
71
  model_name, pretrained=pretrained
72
  )
73
  model = model.to(device).eval()
74
+ print("Model loaded.")
75
 
76
+ # ── Download metadata CSV (55MBfast, no zip) ───────────────────────────
77
+ print(f"Downloading IMPACT {year} metadata CSV...")
78
  csv_path = hf_hub_download(
79
  repo_id="AI4Patents/IMPACT",
80
  filename=f"{year}.csv",
 
82
  token=token,
83
  )
84
 
85
+ # Build figure list from CSV
86
  figures = []
87
  with open(csv_path) as f:
88
  for row in csv.DictReader(f):
89
  try:
90
+ fnames = ast.literal_eval(row.get("file_names") or "[]")
91
+ pid = row.get("id") or row.get("patent_id") or ""
92
+ date = row.get("date") or ""
93
  for i, fn in enumerate(fnames):
94
+ figures.append({
95
+ "patent_id": pid,
96
+ "figure_num": i,
97
+ "filename": fn,
98
+ "date": date,
99
+ })
100
  except Exception:
101
  pass
102
 
103
+ total = len(figures)
104
+ print(f"Total figures: {total:,}")
105
 
106
+ # ── Stream images from HF and embed in GPU batches ────────────────────────
107
+ # Use the HF raw file URL to download individual TIFs on demand.
108
+ # Format: hf://datasets/AI4Patents/IMPACT/{year}/{dir}/{filename}
109
+ # Accessed via: hf_hub_download per file (cached in /root/.cache)
110
+ # This avoids the 4.4GB zip entirely.
 
 
 
 
111
 
112
+ HF_IMPACT = "AI4Patents/IMPACT"
113
+ CACHE_DIR = "/tmp/impact_cache"
114
+ Path(CACHE_DIR).mkdir(exist_ok=True)
115
 
116
+ def fetch_image(fig: dict) -> Image.Image | None:
117
+ fn = fig["filename"]
118
  parts = fn.split("-D0")
119
  if len(parts) < 2:
120
  return None
121
+ dir_name = parts[0]
122
+ hf_path = f"{year}/{dir_name}/{fn}"
123
  try:
124
+ local = hf_hub_download(
125
+ repo_id=HF_IMPACT,
126
+ filename=hf_path,
127
+ repo_type="dataset",
128
+ token=token,
129
+ cache_dir=CACHE_DIR,
130
+ )
131
+ return Image.open(local).convert("RGB")
132
  except Exception:
133
  return None
134
 
135
+ all_ids: list[str] = []
136
+ all_vecs: list[np.ndarray] = []
137
+ batch_imgs: list[Image.Image] = []
138
+ batch_ids: list[str] = []
139
 
140
  def flush_batch():
141
  if not batch_imgs:
 
149
  batch_imgs.clear()
150
  batch_ids.clear()
151
 
152
+ print("Streaming and embedding...")
153
+ for fig in tqdm(figures, desc=f"Embedding {year}"):
154
+ img = fetch_image(fig)
155
  if img is None:
156
  continue
157
+ pid_norm = fig["patent_id"].lstrip("D").zfill(7)
158
+ batch_ids.append(f"D{pid_norm}_{fig['figure_num']}")
159
  batch_imgs.append(img)
160
+ if len(batch_imgs) >= batch_size:
 
 
161
  flush_batch()
162
  flush_batch()
163
 
164
+ print(f"Embedded: {len(all_ids):,} figures")
165
+ if not all_ids:
166
+ print("No figures embedded — check HF access")
167
+ return {"n": 0}
168
+
169
+ # ── Normalize + save + push ───────────────────────────────────────────────
170
  vecs = np.vstack(all_vecs).astype(np.float32)
171
+ norms = np.linalg.norm(vecs, axis=1, keepdims=True)
172
+ vecs /= np.maximum(norms, 1e-8)
173
 
 
174
  df = pd.DataFrame({"figure_id": all_ids, "embedding": list(vecs)})
 
 
175
 
176
+ out_file = f"embeddings/{year}_vitl14.parquet"
177
+ local_out = f"/tmp/{year}_vitl14.parquet"
178
+ df.to_parquet(local_out, index=False)
179
+ size_mb = Path(local_out).stat().st_size / 1e6
180
+ print(f"Parquet: {size_mb:.1f}MB — pushing to HF Hub...")
181
+
182
  api = HfApi(token=token)
183
  api.upload_file(
184
+ path_or_fileobj=local_out,
185
  path_in_repo=out_file,
186
+ repo_id=OUT_REPO,
187
  repo_type="dataset",
188
+ commit_message=f"Add CLIP embeddings for {year}",
189
  )
190
+ print(f"Pushed → hf://datasets/{OUT_REPO}/{out_file}")
191
+
192
+ return {"year": year, "n_embedded": len(all_ids), "shape": list(vecs.shape)}
193
 
194
 
195
  @app.local_entrypoint()
196
+ def main(year: str = "2022"):
197
+ print(f"Embedding year: {year}")
198
+ result = embed_year.remote(year)
199
  print("Done:", result)