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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import torch
|
| 3 |
+
from torch import nn
|
| 4 |
+
from torch.utils.data import DataLoader
|
| 5 |
+
from tqdm import tqdm
|
| 6 |
+
from PIL import Image
|
| 7 |
+
import numpy as np
|
| 8 |
+
import io
|
| 9 |
+
|
| 10 |
+
from transformers import AutoProcessor
|
| 11 |
+
from transformers.models.paligemma.modeling_paligemma import (
|
| 12 |
+
PaliGemmaConfig,
|
| 13 |
+
PaliGemmaForConditionalGeneration,
|
| 14 |
+
PaliGemmaPreTrainedModel,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
from transformers.models.qwen2_vl import (
|
| 18 |
+
Qwen2VLForConditionalGeneration,
|
| 19 |
+
Qwen2VLConfig,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
class ColPali(PaliGemmaPreTrainedModel):
|
| 23 |
+
"""
|
| 24 |
+
ColPali model implementation from the "ColPali: Efficient Document Retrieval with Vision Language Models" paper.
|
| 25 |
+
"""
|
| 26 |
+
def __init__(self, config: PaliGemmaConfig):
|
| 27 |
+
super().__init__(config=config)
|
| 28 |
+
model = PaliGemmaForConditionalGeneration(config=config)
|
| 29 |
+
if model.language_model._tied_weights_keys is not None:
|
| 30 |
+
self._tied_weights_keys = [f"model.language_model.{k}" for k in model.language_model._tied_weights_keys]
|
| 31 |
+
self.model = model
|
| 32 |
+
self.dim = 128
|
| 33 |
+
self.custom_text_proj = nn.Linear(self.model.config.text_config.hidden_size, self.dim)
|
| 34 |
+
self.post_init()
|
| 35 |
+
|
| 36 |
+
def forward(self, *args, **kwargs) -> torch.Tensor:
|
| 37 |
+
# Delete output_hidden_states from kwargs
|
| 38 |
+
kwargs.pop("output_hidden_states", None)
|
| 39 |
+
outputs = self.model(*args, output_hidden_states=True, **kwargs) # (batch_size, sequence_length, hidden_size)
|
| 40 |
+
last_hidden_states = outputs.hidden_states[-1] # (batch_size, sequence_length, hidden_size)
|
| 41 |
+
proj = self.custom_text_proj(last_hidden_states) # (batch_size, sequence_length, dim)
|
| 42 |
+
# L2 normalization
|
| 43 |
+
proj = proj / proj.norm(dim=-1, keepdim=True) # (batch_size, sequence_length, dim)
|
| 44 |
+
proj = proj * kwargs["attention_mask"].unsqueeze(-1) # (batch_size, sequence_length, dim)
|
| 45 |
+
return proj
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class ColPaliRetriever():
|
| 49 |
+
def __init__(self, bs=4, use_gpu=True):
|
| 50 |
+
self.bs = bs
|
| 51 |
+
self.bs_query = 64
|
| 52 |
+
self.model_name = "checkpoint/colpali-v1.1"
|
| 53 |
+
self.base_ckpt = "checkpoint/colpaligemma-3b-mix-448-base"
|
| 54 |
+
# Load model on cuda:0 by default!
|
| 55 |
+
device = "cuda:0" if (torch.cuda.is_available() and use_gpu) else "cpu"
|
| 56 |
+
self.model = ColPali.from_pretrained(
|
| 57 |
+
self.base_ckpt, torch_dtype=torch.bfloat16, device_map=None # <-- NONE: Don't use device_map
|
| 58 |
+
)
|
| 59 |
+
self.model.load_adapter(self.model_name)
|
| 60 |
+
self.model = self.model.to(device)
|
| 61 |
+
self.model.eval()
|
| 62 |
+
# Multi-GPU with DataParallel
|
| 63 |
+
if torch.cuda.device_count() > 1 and use_gpu:
|
| 64 |
+
print(f"[ColPaliRetriever] Using DataParallel on {torch.cuda.device_count()} GPUs")
|
| 65 |
+
self.model = torch.nn.DataParallel(self.model)
|
| 66 |
+
self.device = torch.device("cuda:0")
|
| 67 |
+
else:
|
| 68 |
+
self.device = torch.device(device)
|
| 69 |
+
print(f"[ColPaliRetriever - init] ColPali loaded from '{self.base_ckpt}' (Adapter '{self.model_name}')...")
|
| 70 |
+
# Load processor
|
| 71 |
+
self.processor = AutoProcessor.from_pretrained(self.model_name)
|
| 72 |
+
self.mock_image = Image.new("RGB", (16, 16), color="black")
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def embed_queries(self, queries, pad=False):
|
| 76 |
+
if isinstance(queries, str):
|
| 77 |
+
queries = [queries]
|
| 78 |
+
embeddings = []
|
| 79 |
+
dataloader = DataLoader(queries, batch_size=self.bs_query, shuffle=False,
|
| 80 |
+
collate_fn=lambda x: self.process_queries(x))
|
| 81 |
+
with torch.no_grad():
|
| 82 |
+
for batch in tqdm(dataloader, desc="[ColPaliRetriever] Embedding queries"):
|
| 83 |
+
batch = {k: v.to(self.device) for k, v in batch.items()}
|
| 84 |
+
outputs = self.model(**batch)
|
| 85 |
+
attention_mask = batch["attention_mask"]
|
| 86 |
+
if isinstance(outputs, (tuple, list)): outputs = outputs[0]
|
| 87 |
+
for emb, mask in zip(outputs, attention_mask):
|
| 88 |
+
if pad:
|
| 89 |
+
embeddings.append(emb.cpu().float().numpy())
|
| 90 |
+
else:
|
| 91 |
+
emb_nonpad = emb[mask.bool()]
|
| 92 |
+
embeddings.append(emb_nonpad.cpu().float().numpy())
|
| 93 |
+
return embeddings
|
| 94 |
+
|
| 95 |
+
def embed_quotes(self, images):
|
| 96 |
+
if isinstance(images, Image.Image):
|
| 97 |
+
images = [images]
|
| 98 |
+
embeddings = []
|
| 99 |
+
dataloader = DataLoader(images, batch_size=self.bs, shuffle=False,
|
| 100 |
+
collate_fn=lambda x: self.process_images(x))
|
| 101 |
+
with torch.no_grad():
|
| 102 |
+
for batch in tqdm(dataloader, desc="[ColPaliRetriever] Embedding images"):
|
| 103 |
+
batch = {k: v.to(self.device) for k, v in batch.items()}
|
| 104 |
+
outputs = self.model(**batch)
|
| 105 |
+
for emb in torch.unbind(outputs):
|
| 106 |
+
embeddings.append(emb.cpu().float().numpy())
|
| 107 |
+
return embeddings
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def process_queries(self, queries, max_length=512):
|
| 111 |
+
texts_query = [f"Question: {q}" + "<pad>" * 10 for q in queries]
|
| 112 |
+
sl = getattr(self.processor, "image_seq_length", 32) # 1024
|
| 113 |
+
batch_query = self.processor(
|
| 114 |
+
images=[self.mock_image] * len(texts_query),
|
| 115 |
+
text=texts_query,
|
| 116 |
+
return_tensors="pt",
|
| 117 |
+
padding="longest",
|
| 118 |
+
max_length=max_length + sl # fallback seq len
|
| 119 |
+
)
|
| 120 |
+
if "pixel_values" in batch_query: del batch_query["pixel_values"]
|
| 121 |
+
|
| 122 |
+
batch_query["input_ids"] = batch_query["input_ids"][..., sl :]
|
| 123 |
+
batch_query["attention_mask"] = batch_query["attention_mask"][..., sl :]
|
| 124 |
+
return batch_query
|
| 125 |
+
|
| 126 |
+
def process_images(self, images):
|
| 127 |
+
pil_images = []
|
| 128 |
+
for img in images:
|
| 129 |
+
if isinstance(img, Image.Image): # Already a PIL Image
|
| 130 |
+
pil_img = img
|
| 131 |
+
elif isinstance(img, (bytes, bytearray)): # Binary image (e.g., from buffered.getvalue())
|
| 132 |
+
pil_img = Image.open(io.BytesIO(img))
|
| 133 |
+
else:
|
| 134 |
+
raise ValueError("Each image must be a PIL.Image.Image or bytes.")
|
| 135 |
+
pil_images.append(pil_img.convert("RGB"))
|
| 136 |
+
|
| 137 |
+
texts = ["Describe the image."] * len(pil_images)
|
| 138 |
+
batch_docs = self.processor(
|
| 139 |
+
text=texts,
|
| 140 |
+
images=pil_images,
|
| 141 |
+
return_tensors="pt",
|
| 142 |
+
padding="longest"
|
| 143 |
+
)
|
| 144 |
+
return batch_docs
|
| 145 |
+
|
| 146 |
+
def score(self, query_embs, image_embs):
|
| 147 |
+
"""
|
| 148 |
+
Computes (batch) similarity scores MaxSim style.
|
| 149 |
+
Inputs:
|
| 150 |
+
query_embs: [Nq, seq, dim]
|
| 151 |
+
image_embs: [Ni, seq, dim]
|
| 152 |
+
Returns:
|
| 153 |
+
scores: [Nq, Ni] max similarity per query-image (like ColBERT)
|
| 154 |
+
"""
|
| 155 |
+
qs = [torch.from_numpy(e) for e in query_embs]
|
| 156 |
+
ds = [torch.from_numpy(e) for e in image_embs]
|
| 157 |
+
# MaxSim/colbert scoring: max dot product over sequence dimension
|
| 158 |
+
# shape: [Q, D]
|
| 159 |
+
scores = np.zeros((len(qs), len(ds)), dtype=np.float32)
|
| 160 |
+
for i, q in enumerate(qs):
|
| 161 |
+
q = q.float() # [Lq, d]
|
| 162 |
+
for j, d in enumerate(ds):
|
| 163 |
+
d = d.float() # [Ld, d]
|
| 164 |
+
# score = max_{q_token, d_token} q_token @ d_token.T
|
| 165 |
+
sim = torch.matmul(q, d.T) # [Lq, Ld]
|
| 166 |
+
maxsim = torch.max(sim, dim=1)[0].sum().item() # colbert-style batch: sum-of-max over query tokens
|
| 167 |
+
scores[i, j] = maxsim
|
| 168 |
+
return scores
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
class ColQwen2(Qwen2VLForConditionalGeneration):
|
| 173 |
+
"""
|
| 174 |
+
ColQwen2 model implementation.
|
| 175 |
+
"""
|
| 176 |
+
def __init__(self, config: Qwen2VLConfig):
|
| 177 |
+
super().__init__(config)
|
| 178 |
+
self.dim = 128
|
| 179 |
+
self.custom_text_proj = torch.nn.Linear(self.model.config.hidden_size, self.dim)
|
| 180 |
+
self.padding_side = "left"
|
| 181 |
+
self.post_init()
|
| 182 |
+
|
| 183 |
+
def forward(self, *args, **kwargs) -> torch.Tensor:
|
| 184 |
+
kwargs.pop("output_hidden_states", None)
|
| 185 |
+
# scatter hack for DDP, see original code if needed
|
| 186 |
+
if "pixel_values" in kwargs and "image_grid_thw" in kwargs:
|
| 187 |
+
offsets = kwargs["image_grid_thw"][:, 1] * kwargs["image_grid_thw"][:, 2]
|
| 188 |
+
kwargs["pixel_values"] = torch.cat([pv[:o] for pv, o in zip(kwargs["pixel_values"], offsets)], dim=0)
|
| 189 |
+
|
| 190 |
+
position_ids, rope_deltas = self.get_rope_index(
|
| 191 |
+
input_ids=kwargs["input_ids"],
|
| 192 |
+
image_grid_thw=kwargs.get("image_grid_thw", None),
|
| 193 |
+
video_grid_thw=None,
|
| 194 |
+
attention_mask=kwargs.get("attention_mask", None),
|
| 195 |
+
)
|
| 196 |
+
outputs = super().forward(*args,
|
| 197 |
+
**kwargs,
|
| 198 |
+
position_ids=position_ids,
|
| 199 |
+
rope_deltas=rope_deltas,
|
| 200 |
+
use_cache=False,
|
| 201 |
+
output_hidden_states=True)
|
| 202 |
+
last_hidden_states = outputs.hidden_states[-1]
|
| 203 |
+
proj = self.custom_text_proj(last_hidden_states)
|
| 204 |
+
proj = proj / proj.norm(dim=-1, keepdim=True)
|
| 205 |
+
proj = proj * kwargs["attention_mask"].unsqueeze(-1)
|
| 206 |
+
return proj
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
class ColQwen2Retriever:
|
| 210 |
+
def __init__(self, bs=4, use_gpu=True):
|
| 211 |
+
self.bs = bs
|
| 212 |
+
self.bs_query = 64
|
| 213 |
+
self.model_name = "checkpoint/colqwen2-v1.0"
|
| 214 |
+
self.base_ckpt = "checkpoint/colqwen2-base"
|
| 215 |
+
self.device = "cuda" if torch.cuda.is_available() and use_gpu else "cpu"
|
| 216 |
+
|
| 217 |
+
self.model = ColQwen2.from_pretrained(
|
| 218 |
+
self.base_ckpt,
|
| 219 |
+
torch_dtype=torch.bfloat16,
|
| 220 |
+
device_map=self.device
|
| 221 |
+
)
|
| 222 |
+
self.model.load_adapter(self.model_name)
|
| 223 |
+
self.model.eval()
|
| 224 |
+
|
| 225 |
+
# DataParallel:
|
| 226 |
+
self.is_parallel = False
|
| 227 |
+
if torch.cuda.device_count() > 1:
|
| 228 |
+
print(f"Using {torch.cuda.device_count()} GPUs with DataParallel")
|
| 229 |
+
self.model = torch.nn.DataParallel(self.model)
|
| 230 |
+
self.is_parallel = True
|
| 231 |
+
|
| 232 |
+
self.processor = AutoProcessor.from_pretrained(self.model_name)
|
| 233 |
+
self.min_pixels = 4 * 28 * 28
|
| 234 |
+
self.max_pixels = 768 * 28 * 28
|
| 235 |
+
self.factor = 28
|
| 236 |
+
self.max_ratio = 200
|
| 237 |
+
|
| 238 |
+
# ---------- Image Processing Utilities ----------
|
| 239 |
+
@staticmethod
|
| 240 |
+
def round_by_factor(number, factor):
|
| 241 |
+
return round(number / factor) * factor
|
| 242 |
+
|
| 243 |
+
@staticmethod
|
| 244 |
+
def ceil_by_factor(number, factor):
|
| 245 |
+
return math.ceil(number / factor) * factor
|
| 246 |
+
|
| 247 |
+
@staticmethod
|
| 248 |
+
def floor_by_factor(number, factor):
|
| 249 |
+
return math.floor(number / factor) * factor
|
| 250 |
+
|
| 251 |
+
def smart_resize(self, height: int, width: int) -> tuple:
|
| 252 |
+
if max(height, width) / min(height, width) > self.max_ratio:
|
| 253 |
+
raise ValueError(
|
| 254 |
+
f"absolute aspect ratio must be smaller than {self.max_ratio}, "
|
| 255 |
+
f"got {max(height, width) / min(height, width)}"
|
| 256 |
+
)
|
| 257 |
+
h_bar = max(self.factor, self.round_by_factor(height, self.factor))
|
| 258 |
+
w_bar = max(self.factor, self.round_by_factor(width, self.factor))
|
| 259 |
+
if h_bar * w_bar > self.max_pixels:
|
| 260 |
+
beta = math.sqrt((height * width) / self.max_pixels)
|
| 261 |
+
h_bar = self.floor_by_factor(height / beta, self.factor)
|
| 262 |
+
w_bar = self.floor_by_factor(width / beta, self.factor)
|
| 263 |
+
elif h_bar * w_bar < self.min_pixels:
|
| 264 |
+
beta = math.sqrt(self.min_pixels / (height * width))
|
| 265 |
+
h_bar = self.ceil_by_factor(height * beta, self.factor)
|
| 266 |
+
w_bar = self.ceil_by_factor(width * beta, self.factor)
|
| 267 |
+
return h_bar, w_bar
|
| 268 |
+
|
| 269 |
+
def process_images(self, images):
|
| 270 |
+
pil_images = []
|
| 271 |
+
for img in images:
|
| 272 |
+
if isinstance(img, Image.Image):
|
| 273 |
+
pil_img = img
|
| 274 |
+
elif isinstance(img, (bytes, bytearray)):
|
| 275 |
+
pil_img = Image.open(io.BytesIO(img))
|
| 276 |
+
else:
|
| 277 |
+
raise ValueError("Each image must be a PIL.Image.Image or bytes.")
|
| 278 |
+
pil_images.append(pil_img.convert("RGB"))
|
| 279 |
+
|
| 280 |
+
# Resize and convert
|
| 281 |
+
resized_images = []
|
| 282 |
+
for image in pil_images:
|
| 283 |
+
orig_size = image.size
|
| 284 |
+
resized_height, resized_width = self.smart_resize(orig_size[1], orig_size[0])
|
| 285 |
+
out_img = image.resize((resized_width,resized_height)).convert('RGB')
|
| 286 |
+
resized_images.append(out_img)
|
| 287 |
+
|
| 288 |
+
texts_doc = [
|
| 289 |
+
"<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>Describe the image.<|im_end|>\n"
|
| 290 |
+
] * len(resized_images)
|
| 291 |
+
|
| 292 |
+
batch_doc = self.processor(
|
| 293 |
+
text=texts_doc,
|
| 294 |
+
images=resized_images,
|
| 295 |
+
padding="longest",
|
| 296 |
+
return_tensors="pt"
|
| 297 |
+
)
|
| 298 |
+
# The following hack can be skipped during inference unless you run into shape mismatch
|
| 299 |
+
offsets = batch_doc["image_grid_thw"][:, 1] * batch_doc["image_grid_thw"][:, 2]
|
| 300 |
+
pixel_values = torch.split(batch_doc["pixel_values"], offsets.tolist())
|
| 301 |
+
max_length = max([len(pv) for pv in pixel_values])
|
| 302 |
+
pixel_values = [torch.cat([pv,
|
| 303 |
+
torch.zeros((max_length - len(pv), pv.shape[1]),
|
| 304 |
+
dtype=pv.dtype, device=pv.device)]) for pv in pixel_values]
|
| 305 |
+
batch_doc["pixel_values"] = torch.stack(pixel_values)
|
| 306 |
+
return batch_doc
|
| 307 |
+
|
| 308 |
+
def process_queries(self, queries, max_length=50, suffix=None):
|
| 309 |
+
if suffix is None:
|
| 310 |
+
suffix = "<pad>" * 10
|
| 311 |
+
texts_query = []
|
| 312 |
+
for q in queries:
|
| 313 |
+
q_ = f"Query: {q}{suffix}"
|
| 314 |
+
texts_query.append(q_)
|
| 315 |
+
batch_query = self.processor(
|
| 316 |
+
text=texts_query,
|
| 317 |
+
return_tensors="pt",
|
| 318 |
+
padding="longest",
|
| 319 |
+
)
|
| 320 |
+
return batch_query
|
| 321 |
+
|
| 322 |
+
def embed_queries(self, queries, pad=False):
|
| 323 |
+
if isinstance(queries, str):
|
| 324 |
+
queries = [queries]
|
| 325 |
+
embeddings = []
|
| 326 |
+
dataloader = DataLoader(
|
| 327 |
+
queries, batch_size=self.bs_query, shuffle=False,
|
| 328 |
+
collate_fn=lambda x: self.process_queries(x)
|
| 329 |
+
)
|
| 330 |
+
with torch.no_grad():
|
| 331 |
+
# Use main device for DataParallel
|
| 332 |
+
dev = self.model.device_ids[0] if self.is_parallel else self.model.device
|
| 333 |
+
for batch in tqdm(dataloader, desc="[ColQwen2Retriever] Embedding queries"):
|
| 334 |
+
batch = {k: v.to(dev) for k, v in batch.items()}
|
| 335 |
+
outputs = self.model(**batch)
|
| 336 |
+
attention_mask = batch["attention_mask"]
|
| 337 |
+
if isinstance(outputs, (tuple, list)):
|
| 338 |
+
outputs = outputs[0]
|
| 339 |
+
for emb, mask in zip(outputs, attention_mask):
|
| 340 |
+
if pad:
|
| 341 |
+
embeddings.append(emb.cpu().float().numpy())
|
| 342 |
+
else:
|
| 343 |
+
emb_nonpad = emb[mask.bool()]
|
| 344 |
+
embeddings.append(emb_nonpad.cpu().float().numpy())
|
| 345 |
+
return embeddings
|
| 346 |
+
|
| 347 |
+
def embed_quotes(self, images):
|
| 348 |
+
if isinstance(images, Image.Image):
|
| 349 |
+
images = [images]
|
| 350 |
+
embeddings = []
|
| 351 |
+
dataloader = DataLoader(
|
| 352 |
+
images, batch_size=self.bs, shuffle=False,
|
| 353 |
+
collate_fn=lambda x: self.process_images(x)
|
| 354 |
+
)
|
| 355 |
+
with torch.no_grad():
|
| 356 |
+
dev = self.model.device_ids[0] if self.is_parallel else self.model.device
|
| 357 |
+
for batch in tqdm(dataloader, desc="[ColQwen2Retriever] Embedding images"):
|
| 358 |
+
batch = {k: v.to(dev) for k, v in batch.items()}
|
| 359 |
+
outputs = self.model(**batch)
|
| 360 |
+
for emb in torch.unbind(outputs):
|
| 361 |
+
embeddings.append(emb.cpu().float().numpy())
|
| 362 |
+
return embeddings
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def score(self, query_embs, image_embs):
|
| 366 |
+
qs = [torch.from_numpy(e) for e in query_embs]
|
| 367 |
+
ds = [torch.from_numpy(e) for e in image_embs]
|
| 368 |
+
scores = np.zeros((len(qs), len(ds)), dtype=np.float32)
|
| 369 |
+
for i, q in enumerate(qs):
|
| 370 |
+
q = q.float()
|
| 371 |
+
for j, d in enumerate(ds):
|
| 372 |
+
d = d.float()
|
| 373 |
+
sim = torch.matmul(q, d.T)
|
| 374 |
+
maxsim = torch.max(sim, dim=1)[0].sum().item()
|
| 375 |
+
scores[i, j] = maxsim
|
| 376 |
+
return scores
|