File size: 4,546 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
"""Encode original query image+text and product image+title with Qwen3-VL-Embedding.

Writes query_ids.json, candidate_ids.json and matching *_embeds.npy arrays.
The chat format and pooling follow the Qwen reference implementation:
https://github.com/QwenLM/Qwen3-VL-Embedding
This entry point is specific to that architecture, not a generic HF encoder.
"""
import argparse
import json
from pathlib import Path

import utils as data


def message(image, text, instruction):
    return [
        {"role": "system", "content": [{"type": "text", "text": instruction}]},
        {"role": "user", "content": [
            {"type": "image", "image": image, "min_pixels": 4 * 32 * 32,
             "max_pixels": 1800 * 32 * 32},
            {"type": "text", "text": text}]},
    ]


def build_inputs(root, corpus, instruction):
    queries = data.load_queries(root)
    q = [message(data.query_image_path(root, x['image_url']), x['query'], instruction)
         for x in queries]
    c = [message(data.product_image_path(root, x['pict_url']), x['title'], instruction)
         for x in corpus.values()]
    return q, [str(x['idx']) for x in queries], c, list(corpus)


def encode(messages, model, processor, device, batch_size, max_length):
    import numpy as np
    import torch
    from qwen_vl_utils import process_vision_info

    embeds = []
    for start in range(0, len(messages), batch_size):
        batch = messages[start:start + batch_size]
        text = processor.apply_chat_template(batch, tokenize=False, add_generation_prompt=True)
        images, _ = process_vision_info(batch, image_patch_size=16)
        inputs = processor(text=text, images=images, padding=True, do_resize=False,
                           return_tensors='pt')
        if inputs['input_ids'].shape[1] > max_length:
            raise ValueError(f"Input exceeds --max-length {max_length}; refusing silent truncation")
        inputs = inputs.to(device)
        with torch.inference_mode():
            hidden = model(**inputs).last_hidden_state
            mask = inputs['attention_mask']
            last = mask.shape[1] - 1 - mask.flip(dims=[1]).argmax(dim=1)
            pooled = hidden[torch.arange(hidden.shape[0], device=hidden.device), last]
            pooled = torch.nn.functional.normalize(pooled.float(), dim=-1)
        embeds.append(pooled.cpu().numpy())
        print(f'  [{min(start + batch_size, len(messages))}/{len(messages)}]', flush=True)
    return np.concatenate(embeds)


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--model', default='Qwen/Qwen3-VL-Embedding-8B')
    p.add_argument('--out', required=True)
    p.add_argument('--data', default=None)
    p.add_argument('--batch-size', type=int, default=8)
    p.add_argument('--device', default=None)
    p.add_argument('--max-length', type=int, default=8192)
    p.add_argument('--instruction', default="Represent the user's input.")
    args = p.parse_args()
    if args.batch_size <= 0 or args.max_length <= 0:
        p.error('batch-size and max-length must be positive')

    import numpy as np
    import torch
    from transformers import Qwen3VLModel, Qwen3VLPreTrainedModel, Qwen3VLProcessor

    # The released embedding checkpoint stores backbone weights under model.*.
    class EmbeddingModel(Qwen3VLPreTrainedModel):
        _checkpoint_conversion_mapping = {}

        def __init__(self, config):
            super().__init__(config)
            self.model = Qwen3VLModel(config)
            self.post_init()

        def forward(self, **inputs):
            return self.model(**inputs)

    device = args.device or ('cuda' if torch.cuda.is_available() else 'cpu')
    dtype = torch.bfloat16 if device.startswith('cuda') else torch.float32
    model = EmbeddingModel.from_pretrained(args.model, torch_dtype=dtype).to(device).eval()
    processor = Qwen3VLProcessor.from_pretrained(args.model, padding_side='right')
    root = data.data_root(args.data)
    q, qids, c, cids = build_inputs(root, data.load_corpus(root), args.instruction)
    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    for name, messages, ids in [('query', q, qids), ('candidate', c, cids)]:
        print(f'encoding {len(ids)} {name} items...', flush=True)
        vectors = encode(messages, model, processor, device, args.batch_size, args.max_length)
        np.save(out / f'{name}_embeds.npy', vectors)
        (out / f'{name}_ids.json').write_text(json.dumps(ids))
    print(f'saved embeddings -> {out}')


if __name__ == '__main__':
    main()