Datasets:

Modalities:
Tabular
Text
Formats:
arrow
Languages:
English
Libraries:
Datasets
License:
brettrenfer commited on
Commit
569f72e
·
verified ·
1 Parent(s): 7bf4c0b

Create embeddings_streaming.py

Browse files
Files changed (1) hide show
  1. embeddings_streaming.py +131 -0
embeddings_streaming.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, math, glob
2
+ import datasets
3
+ from datasets import Features, Value, Array1D
4
+ from transformers import CLIPProcessor, CLIPModel
5
+ import torch
6
+ from PIL import Image
7
+ from tqdm import tqdm
8
+ import numpy as np
9
+
10
+ # Optional (recommended for reproducibility)
11
+ torch.manual_seed(0)
12
+
13
+ # ---------- Config ----------
14
+ MODEL_NAME = "openai/clip-vit-base-patch32"
15
+ BATCH_SIZE = 32 # tune for your machine
16
+ SHARD_SIZE = 10_000 # write a parquet file every N rows
17
+ OUT_DIR = "metmuseum_embeddings_streaming" # will contain *.parquet
18
+ IMG_COL = "jpg" # adjust if column differs (sometimes 'image')
19
+ ID_COL = "Object ID"
20
+ # ----------------------------
21
+
22
+ # 1) Load streaming dataset
23
+ ds_stream = datasets.load_dataset(
24
+ "metmuseum/openaccess", split="train", streaming=True
25
+ )
26
+
27
+ # 2) Model / processor / device
28
+ model = CLIPModel.from_pretrained(MODEL_NAME)
29
+ processor = CLIPProcessor.from_pretrained(MODEL_NAME)
30
+ device = torch.device("mps" if torch.backends.mps.is_available() else "cpu")
31
+ model.to(device).eval()
32
+
33
+ # 3) L2 normalize helper
34
+ def l2_normalize(x, dim=-1, eps=1e-12):
35
+ return x / (x.norm(p=2, dim=dim, keepdim=True) + eps)
36
+
37
+ # 4) Sharded writer (Parquet via datasets.Dataset)
38
+ os.makedirs(OUT_DIR, exist_ok=True)
39
+ shard_idx = 0
40
+ rows_in_shard = 0
41
+ buffer_ids = []
42
+ buffer_vecs = []
43
+ emb_dim = None # will set after first batch
44
+
45
+ def flush_shard():
46
+ """Write current buffer to a parquet shard and clear it."""
47
+ global shard_idx, rows_in_shard, buffer_ids, buffer_vecs, emb_dim
48
+ if not buffer_ids:
49
+ return
50
+
51
+ # Ensure emb_dim is known
52
+ if emb_dim is None:
53
+ emb_dim = len(buffer_vecs[0])
54
+
55
+ # Build a small in-memory HF Dataset for this shard with explicit features
56
+ features = Features({
57
+ ID_COL: Value("int32"),
58
+ "Embedding": Array1D(emb_dim, dtype="float32"),
59
+ })
60
+ shard_ds = datasets.Dataset.from_dict(
61
+ {ID_COL: buffer_ids, "Embedding": buffer_vecs},
62
+ features=features,
63
+ )
64
+ # Write a parquet file (fast & compact)
65
+ shard_path = os.path.join(OUT_DIR, f"part-{shard_idx:05d}.parquet")
66
+ shard_ds.to_parquet(shard_path)
67
+
68
+ # Clear buffers / advance
69
+ shard_idx += 1
70
+ rows_in_shard = 0
71
+ buffer_ids = []
72
+ buffer_vecs = []
73
+
74
+ # 5) Batch inference loop
75
+ obj_ids_batch, images_batch = [], []
76
+
77
+ def flush_batch():
78
+ """Run CLIP on the current image batch and append to shard buffer."""
79
+ global emb_dim, rows_in_shard, buffer_ids, buffer_vecs
80
+ if not images_batch:
81
+ return
82
+ inputs = processor(images=images_batch, return_tensors="pt")
83
+ pixel_values = inputs["pixel_values"].to(device)
84
+
85
+ with torch.no_grad():
86
+ feats = model.get_image_features(pixel_values=pixel_values) # (B, D)
87
+ feats = l2_normalize(feats, dim=-1).cpu().numpy().astype("float32")
88
+
89
+ if emb_dim is None:
90
+ emb_dim = feats.shape[1]
91
+
92
+ # Append to shard buffer
93
+ buffer_ids.extend([int(x) for x in obj_ids_batch])
94
+ buffer_vecs.extend([feats[i] for i in range(feats.shape[0])])
95
+ rows_in_shard += feats.shape[0]
96
+
97
+ # Clear batch
98
+ obj_ids_batch.clear()
99
+ images_batch.clear()
100
+
101
+ # Iterate stream
102
+ for item in tqdm(ds_stream, desc="Embedding (streaming)"):
103
+ oid = item.get(ID_COL)
104
+ img = item.get(IMG_COL)
105
+
106
+ if oid is None or img is None:
107
+ continue
108
+
109
+ # Ensure PIL RGB
110
+ if isinstance(img, Image.Image):
111
+ pil_img = img.convert("RGB")
112
+ else:
113
+ try:
114
+ pil_img = Image.fromarray(img).convert("RGB")
115
+ except Exception:
116
+ continue
117
+
118
+ obj_ids_batch.append(oid)
119
+ images_batch.append(pil_img)
120
+
121
+ if len(images_batch) >= BATCH_SIZE:
122
+ flush_batch()
123
+
124
+ if rows_in_shard >= SHARD_SIZE:
125
+ flush_shard()
126
+
127
+ # Flush remainder
128
+ flush_batch()
129
+ flush_shard()
130
+
131
+ print(f"Wrote {shard_idx} shard(s) to {OUT_DIR}")