Datasets:
File size: 19,907 Bytes
1dda194 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 | """Six multimodal reranker adapters: score and reorder the same top-50 candidate pool."""
import argparse
import json
import math
from pathlib import Path
import utils as data
from evaluate import validate_run
import torch
import torch.nn.functional as F
SYSTEM_PROMPT = (
'Judge whether the Document meets the requirements based on the Query and '
'the Instruct provided. Note that the answer can only be "yes" or "no".'
)
DEFAULT_INSTRUCTION = (
"Given a search query containing a reference product image and the user's "
"need, retrieve relevant products that can satisfy the user's need."
)
def build_qwen_messages(instruction, q_text, q_img, d_text, d_img, image_kwargs=None):
img_kw = image_kwargs or {}
content = [
{"type": "text", "text": "<Instruct>: " + instruction},
{"type": "text", "text": "<Query>:"},
]
if q_img:
content.append({"type": "image", "image": "file://" + q_img, **img_kw})
if q_text:
content.append({"type": "text", "text": q_text})
content.append({"type": "text", "text": "\n<Document>:"})
if d_img:
content.append({"type": "image", "image": "file://" + d_img, **img_kw})
if d_text:
content.append({"type": "text", "text": d_text})
return [
{"role": "system", "content": [{"type": "text", "text": SYSTEM_PROMPT}]},
{"role": "user", "content": content},
]
class BaseReranker:
def __init__(self, model_path, instruction=DEFAULT_INSTRUCTION, batch_size=4):
self.model_path = model_path
self.instruction = instruction
self.batch_size = batch_size
def score_pairs(self, pairs):
"""pairs: list of {"query_text","query_image","doc_text","doc_image"}.
Returns list of float scores, same order."""
scores = []
for s in range(0, len(pairs), self.batch_size):
scores.extend(self._score_batch(pairs[s : s + self.batch_size]))
return scores
def _score_batch(self, batch):
raise NotImplementedError
class _QwenVLYesNo(BaseReranker):
"""Qwen2-VL / Qwen2.5-VL / Qwen3-VL instruct models: P(yes) from the
last-token yes/no logits (Eq. 3 in the paper)."""
model_cls_name = None
image_patch_size = 14
pixel_factor = 28 # min/max pixels unit: patch_size * merge_size
per_image_pixels = False # True -> pass min/max pixels via content dict
def __init__(self, model_path, instruction=DEFAULT_INSTRUCTION, batch_size=4,
max_image_tokens=1280):
super().__init__(model_path, instruction, batch_size)
import transformers
from transformers import AutoProcessor
cls = getattr(transformers, self.model_cls_name)
f = self.pixel_factor
self.min_pixels = 4 * f * f
self.max_pixels = max_image_tokens * f * f
self.processor = AutoProcessor.from_pretrained(
self.model_path,
padding_side="left",
min_pixels=self.min_pixels,
max_pixels=self.max_pixels,
trust_remote_code=True,
)
self.model = cls.from_pretrained(
self.model_path,
dtype=torch.bfloat16,
attn_implementation="sdpa",
trust_remote_code=True,
).cuda().eval()
vocab = self.processor.tokenizer.get_vocab()
self.yes_id = vocab["yes"]
self.no_id = vocab["no"]
def _image_kwargs(self):
if self.per_image_pixels:
return {"min_pixels": self.min_pixels, "max_pixels": self.max_pixels}
return {}
@torch.no_grad()
def _score_batch(self, batch):
from qwen_vl_utils import process_vision_info
msgs = [
build_qwen_messages(
self.instruction,
p["query_text"], p["query_image"],
p["doc_text"], p["doc_image"],
image_kwargs=self._image_kwargs(),
)
for p in batch
]
texts = [
self.processor.apply_chat_template(m, tokenize=False, add_generation_prompt=True)
for m in msgs
]
images, _ = process_vision_info(msgs, image_patch_size=self.image_patch_size)
kwargs = {}
if self.per_image_pixels:
# images already resized by process_vision_info (official reranker flow)
kwargs["do_resize"] = False
inputs = self.processor(
text=texts, images=images, padding=True, return_tensors="pt", **kwargs
)
inputs = {k: v.cuda() if hasattr(v, "cuda") else v for k, v in inputs.items()}
logits = self.model(**inputs).logits[:, -1, :]
pair_logits = logits[:, [self.no_id, self.yes_id]].float()
return F.softmax(pair_logits, dim=-1)[:, 1].cpu().tolist()
class LycheeRerankMM(_QwenVLYesNo):
"""vec-ai/lychee-rerank-mm (Qwen2.5-VL base), official README flow."""
model_cls_name = "Qwen2_5_VLForConditionalGeneration"
image_patch_size = 14
pixel_factor = 28
per_image_pixels = False
class Qwen3VLInstruct(_QwenVLYesNo):
"""Qwen/Qwen3-VL-8B-Instruct used as a yes/no reranker."""
model_cls_name = "Qwen3VLForConditionalGeneration"
image_patch_size = 16
pixel_factor = 32
per_image_pixels = False
class Qwen2VLInstruct(_QwenVLYesNo):
"""Qwen/Qwen2-VL-7B-Instruct used as a yes/no reranker."""
model_cls_name = "Qwen2VLForConditionalGeneration"
image_patch_size = 14
pixel_factor = 28
per_image_pixels = False
class Qwen3VLReranker(_QwenVLYesNo):
"""Qwen/Qwen3-VL-Reranker-8B, official script flow (Eq. 4 in the paper):
sigmoid over the last hidden state projected by (w_yes - w_no)."""
model_cls_name = "Qwen3VLForConditionalGeneration"
image_patch_size = 16
pixel_factor = 32
per_image_pixels = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
lm_head = self.model.lm_head.weight.data
w_diff = (lm_head[self.yes_id] - lm_head[self.no_id]).float()
self.score_linear = torch.nn.Linear(w_diff.size(0), 1, bias=False)
with torch.no_grad():
self.score_linear.weight[0] = w_diff
self.score_linear = self.score_linear.cuda().to(self.model.dtype)
self.inner = self.model.model
@torch.no_grad()
def _score_batch(self, batch):
from qwen_vl_utils import process_vision_info
msgs = [
build_qwen_messages(
self.instruction,
p["query_text"], p["query_image"],
p["doc_text"], p["doc_image"],
image_kwargs=self._image_kwargs(),
)
for p in batch
]
texts = [
self.processor.apply_chat_template(m, tokenize=False, add_generation_prompt=True)
for m in msgs
]
images, _ = process_vision_info(msgs, image_patch_size=self.image_patch_size)
inputs = self.processor(
text=texts, images=images, padding=True, return_tensors="pt",
do_resize=False,
)
inputs = {k: v.cuda() if hasattr(v, "cuda") else v for k, v in inputs.items()}
hidden = self.inner(**inputs).last_hidden_state[:, -1]
scores = torch.sigmoid(self.score_linear(hidden).float().squeeze(-1))
return scores.cpu().tolist()
# ---------------- InternVL3.5 ----------------
IMAGENET_MEAN = (0.485, 0.456, 0.406)
IMAGENET_STD = (0.229, 0.224, 0.225)
INTERNVL_IMAGE_SIZE = 448
def _find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
best_ratio_diff = float("inf")
best_ratio = (1, 1)
area = width * height
for ratio in target_ratios:
target_aspect_ratio = ratio[0] / ratio[1]
ratio_diff = abs(aspect_ratio - target_aspect_ratio)
if ratio_diff < best_ratio_diff:
best_ratio_diff = ratio_diff
best_ratio = ratio
elif ratio_diff == best_ratio_diff:
if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
best_ratio = ratio
return best_ratio
def _dynamic_preprocess(image, min_num=1, max_num=6, image_size=448, use_thumbnail=True):
orig_width, orig_height = image.size
aspect_ratio = orig_width / orig_height
target_ratios = set(
(i, j)
for n in range(min_num, max_num + 1)
for i in range(1, n + 1)
for j in range(1, n + 1)
if i * j <= max_num and i * j >= min_num
)
target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
target_aspect_ratio = _find_closest_aspect_ratio(
aspect_ratio, target_ratios, orig_width, orig_height, image_size
)
target_width = image_size * target_aspect_ratio[0]
target_height = image_size * target_aspect_ratio[1]
blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
resized_img = image.resize((target_width, target_height))
processed_images = []
for i in range(blocks):
box = (
(i % (target_width // image_size)) * image_size,
(i // (target_width // image_size)) * image_size,
((i % (target_width // image_size)) + 1) * image_size,
((i // (target_width // image_size)) + 1) * image_size,
)
processed_images.append(resized_img.crop(box))
if use_thumbnail and len(processed_images) != 1:
processed_images.append(image.resize((image_size, image_size)))
return processed_images
class InternVLYesNo(BaseReranker):
"""OpenGVLab/InternVL3_5-8B-Instruct: P(yes) from last-token logits."""
def __init__(self, model_path, instruction=DEFAULT_INSTRUCTION, batch_size=4,
max_num_tiles=6):
super().__init__(model_path, instruction, batch_size)
import numpy as np
from PIL import Image
from transformers import AutoModel, AutoTokenizer
self.max_num_tiles = max_num_tiles
mean = torch.tensor(IMAGENET_MEAN).view(3, 1, 1)
std = torch.tensor(IMAGENET_STD).view(3, 1, 1)
def transform(img):
img = img.convert("RGB").resize(
(INTERNVL_IMAGE_SIZE, INTERNVL_IMAGE_SIZE), Image.BICUBIC)
arr = np.asarray(img, dtype=np.float32) / 255.0
t = torch.from_numpy(arr).permute(2, 0, 1)
return (t - mean) / std
self.transform = transform
self.tokenizer = AutoTokenizer.from_pretrained(
model_path, trust_remote_code=True)
self.tokenizer.padding_side = "left"
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
self.model = AutoModel.from_pretrained(
model_path,
torch_dtype=torch.bfloat16,
trust_remote_code=True,
use_flash_attn=False,
).cuda().eval()
self.img_context_token = "<IMG_CONTEXT>"
self.model.img_context_token_id = self.tokenizer.convert_tokens_to_ids(
self.img_context_token)
vocab = self.tokenizer.get_vocab()
self.yes_id = vocab["yes"]
self.no_id = vocab["no"]
self.num_image_token = self.model.num_image_token
def _load_tiles(self, path):
from PIL import Image
image = Image.open(path).convert("RGB")
tiles = _dynamic_preprocess(
image, min_num=1, max_num=self.max_num_tiles,
image_size=INTERNVL_IMAGE_SIZE, use_thumbnail=True,
)
return [self.transform(t) for t in tiles]
def _build_sample(self, pair):
"""Returns (input_ids, pixel_values list) for one query-doc pair."""
user_parts = ["<Instruct>: " + self.instruction, "<Query>:"]
n_q = n_d = 0
q_tiles, d_tiles = [], []
if pair["query_image"]:
q_tiles = self._load_tiles(pair["query_image"])
n_q = len(q_tiles)
user_parts.append("<image>")
if pair["query_text"]:
user_parts.append(pair["query_text"])
user_parts.append("\n<Document>:")
if pair["doc_image"]:
d_tiles = self._load_tiles(pair["doc_image"])
n_d = len(d_tiles)
user_parts.append("<image>")
if pair["doc_text"]:
user_parts.append(pair["doc_text"])
user_text = "\n".join(user_parts)
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_text},
]
prompt = self.tokenizer.apply_chat_template(
messages, tokenize=False, add_generation_prompt=True)
for n in (n_q, n_d):
if n:
image_tokens = (
"<img>" + self.img_context_token * (self.num_image_token * n)
+ "</img>"
)
prompt = prompt.replace("<image>", image_tokens, 1)
assert "<image>" not in prompt
input_ids = self.tokenizer(prompt, return_tensors="pt").input_ids[0]
return input_ids, q_tiles + d_tiles
@torch.no_grad()
def _score_batch(self, batch):
ids_list, tiles_list = [], []
for p in batch:
ids, tiles = self._build_sample(p)
ids_list.append(ids)
tiles_list.append(tiles)
enc = self.tokenizer.pad(
{"input_ids": ids_list}, padding=True, return_tensors="pt")
input_ids = enc.input_ids.cuda()
attention_mask = enc.attention_mask.cuda()
all_tiles = [t for tiles in tiles_list for t in tiles]
if all_tiles:
pixel_values = torch.stack(all_tiles).to(
dtype=torch.bfloat16, device="cuda")
image_flags = torch.ones(
pixel_values.size(0), 1, dtype=torch.long, device="cuda")
else:
pixel_values = torch.zeros(
(1, 3, INTERNVL_IMAGE_SIZE, INTERNVL_IMAGE_SIZE),
dtype=torch.bfloat16, device="cuda")
image_flags = torch.zeros(1, 1, dtype=torch.long, device="cuda")
logits = self.model(
pixel_values=pixel_values,
input_ids=input_ids,
attention_mask=attention_mask,
image_flags=image_flags,
).logits[:, -1, :]
pair_logits = logits[:, [self.no_id, self.yes_id]].float()
return F.softmax(pair_logits, dim=-1)[:, 1].cpu().tolist()
class LlavaYesNo(BaseReranker):
"""llava-hf/llava-1.5-7b-hf: P(yes) from last-token logits.
Single-image-trained model used with two images; weak-baseline contrast."""
def __init__(self, model_path, instruction=DEFAULT_INSTRUCTION, batch_size=8,
**_ignored):
super().__init__(model_path, instruction, batch_size)
from transformers import AutoProcessor, LlavaForConditionalGeneration
self.processor = AutoProcessor.from_pretrained(
model_path, padding_side="left")
self.model = LlavaForConditionalGeneration.from_pretrained(
model_path, dtype=torch.float16, attn_implementation="sdpa",
).cuda().eval()
vocab = self.processor.tokenizer.get_vocab()
# after "ASSISTANT:" the next token carries a leading space (▁)
self.yes_ids = [vocab[t] for t in ("▁yes", "▁Yes", "yes", "Yes") if t in vocab]
self.no_ids = [vocab[t] for t in ("▁no", "▁No", "no", "No") if t in vocab]
def _build_messages(self, pair, n_images):
content = [{"type": "text", "text": "<Instruct>: " + self.instruction},
{"type": "text", "text": "<Query>:"}]
if pair["query_image"]:
content.append({"type": "image"})
if pair["query_text"]:
content.append({"type": "text", "text": pair["query_text"]})
content.append({"type": "text", "text": "\n<Document>:"})
if pair["doc_image"]:
content.append({"type": "image"})
if pair["doc_text"]:
content.append({"type": "text", "text": pair["doc_text"]})
return [
{"role": "system", "content": [{"type": "text", "text": SYSTEM_PROMPT}]},
{"role": "user", "content": content},
]
@torch.no_grad()
def _score_batch(self, batch):
from PIL import Image
texts, images = [], []
for p in batch:
msgs = self._build_messages(p, 0)
texts.append(self.processor.apply_chat_template(
msgs, tokenize=False, add_generation_prompt=True))
for key in ("query_image", "doc_image"):
if p[key]:
images.append(Image.open(p[key]).convert("RGB"))
inputs = self.processor(
text=texts, images=images or None, padding=True, return_tensors="pt")
inputs = {k: v.cuda() if hasattr(v, "cuda") else v for k, v in inputs.items()}
logits = self.model(**inputs).logits[:, -1, :].float()
probs = F.softmax(logits, dim=-1)
p_yes = probs[:, self.yes_ids].sum(-1)
p_no = probs[:, self.no_ids].sum(-1)
return (p_yes / (p_yes + p_no + 1e-12)).cpu().tolist()
RERANKERS = {
"qwen3_vl_reranker_8b": ("Qwen/Qwen3-VL-Reranker-8B", Qwen3VLReranker),
"qwen3_vl_8b_instruct": ("Qwen/Qwen3-VL-8B-Instruct", Qwen3VLInstruct),
"internvl3_5_8b": ("OpenGVLab/InternVL3_5-8B-Instruct", InternVLYesNo),
"lychee_rerank_mm": ("vec-ai/lychee-rerank-mm", LycheeRerankMM),
"llava_1_5_7b": ("llava-hf/llava-1.5-7b-hf", LlavaYesNo),
"qwen2_vl_7b_instruct": ("Qwen/Qwen2-VL-7B-Instruct", Qwen2VLInstruct),
}
def get_reranker(tag, model_path=None, batch_size=4):
model_id, cls = RERANKERS[tag]
return cls(model_path or model_id, batch_size=batch_size)
def rerank(baseline, queries, corpus, root, model):
query_map = {str(row["idx"]): row for row in queries}
baseline = validate_run(baseline, query_map, corpus)
if any(len(row["ranked"]) != 50 for row in baseline):
raise ValueError("Reranking requires 50 candidates per query")
output = []
for row in baseline:
query = query_map[row["qid"]]
query_image = data.query_image_path(root, query["image_url"])
pairs = []
for hit in row["ranked"]:
product = corpus[hit["did"]]
pairs.append({"query_text": query["query"], "query_image": query_image,
"doc_text": product["title"],
"doc_image": data.product_image_path(root, product["pict_url"])})
scores = model.score_pairs(pairs)
if len(scores) != len(pairs) or not all(math.isfinite(score) for score in scores):
raise ValueError(f"Incomplete or invalid scores for {row['qid']}")
ranked = [{"did": hit["did"], "score": float(score)} for hit, score in zip(row["ranked"], scores)]
output.append({"qid": row["qid"], "ranked": sorted(ranked, key=lambda hit: -hit["score"])})
return output
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--model", required=True, choices=RERANKERS)
p.add_argument("--model-path", default=None, help="Optional local model weights")
p.add_argument("--baseline", default=None)
p.add_argument("--data", default=None)
p.add_argument("--output", required=True)
p.add_argument("--batch-size", type=int, default=4)
args = p.parse_args()
if args.batch_size <= 0:
p.error("batch-size must be positive")
root = data.data_root(args.data)
path = Path(args.baseline) if args.baseline else root / "baseline/qwen3_vl_embedding_8b_top50.json"
baseline = json.loads(path.read_text())
model = get_reranker(args.model, args.model_path, args.batch_size)
run = rerank(baseline, data.load_queries(root), data.load_corpus(root), root, model)
out = Path(args.output)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(run))
print(f"Saved {len(run)} query rankings to {out}")
if __name__ == "__main__":
main()
|