Yanqing0327 commited on
Commit
bb7aa95
·
verified ·
1 Parent(s): de402e7

Load without remote code; vLLM usage; the evaluated image bounds

Browse files

The chat template now writes the input format out exactly, the processor defaults to at most 8,388,608 pixels, and Sentence Transformers uses its stock modules. The model card shows plain Transformers, Sentence Transformers and vLLM usage, with how close each is to the evaluated embeddings.

1_Pooling/config.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "embedding_dimension": 1024,
3
+ "pooling_mode": "lasttoken",
4
+ "include_prompt": true
5
+ }
NOTICE CHANGED
@@ -16,15 +16,17 @@ under the Apache License, Version 2.0:
16
  2. WeMM-Embedding (Tencent), https://huggingface.co/tencent/WeMM-Embedding-2B
17
  Copyright (C) 2026 Tencent. Files taken from it:
18
  modeling_wemm_embedding.py, tokenizer.json, tokenizer_config.json,
19
- chat_template.jinja, embedding_chat_template.jinja, processor_config.json,
20
- modules.json, sentence_bert_config.json,
21
- additional_chat_templates/sentence_transformers.jinja
22
  Modified by the OpenEmbed authors:
23
- modeling_st_wemm.py (an image item without its own pixel bounds is resized
24
- within 65,536 to 8,388,608 pixels, the bounds OpenEmbed was evaluated with),
25
- config_sentence_transformers.json (the library versions it was tested with).
26
  License: third_party/LICENSE-WeMM-Embedding
27
 
 
 
 
 
 
28
  The two distillation teachers, Qwen3-VL-Embedding-8B (Qwen team) and
29
  WeMM-Embedding-9B (Tencent), are licensed under Apache-2.0. Their weights are not
30
  included in this repository.
 
16
  2. WeMM-Embedding (Tencent), https://huggingface.co/tencent/WeMM-Embedding-2B
17
  Copyright (C) 2026 Tencent. Files taken from it:
18
  modeling_wemm_embedding.py, tokenizer.json, tokenizer_config.json,
19
+ embedding_chat_template.jinja
 
 
20
  Modified by the OpenEmbed authors:
21
+ processor_config.json (the largest image lowered from 16,777,216 to
22
+ 8,388,608 pixels, the bound OpenEmbed was trained and evaluated with).
 
23
  License: third_party/LICENSE-WeMM-Embedding
24
 
25
+ Written by the OpenEmbed authors: chat_template.jinja (renders the input format
26
+ of training exactly, so the tokens do not depend on the tokenizer's normalizer),
27
+ and the Sentence Transformers files modules.json, sentence_bert_config.json,
28
+ 1_Pooling/config.json and config_sentence_transformers.json (stock modules).
29
+
30
  The two distillation teachers, Qwen3-VL-Embedding-8B (Qwen team) and
31
  WeMM-Embedding-9B (Tencent), are licensed under Apache-2.0. Their weights are not
32
  included in this repository.
README.md CHANGED
@@ -37,20 +37,19 @@ MMEB-V2: 36 image tasks (Hit@1; CLS: classification, VQA: visual question answer
37
 
38
  ## Usage
39
 
40
- Tested with torch 2.8.0, torchvision 0.23.0, transformers 5.2.0, qwen-vl-utils 0.0.14, and sentence-transformers 5.7.0. qwen-vl-utils needs torchvision, which it does not install by itself.
41
 
42
  ```bash
43
- pip install torch torchvision transformers==5.2.0 qwen-vl-utils==0.0.14 "sentence-transformers>=5.7.0"
44
  ```
45
 
46
  ### Input format
47
 
48
- OpenEmbed was trained and evaluated with WeMM-Embedding's input format:
49
 
50
  - Each input is one user turn with no system turn. Images come first, followed by one text item that holds the instruction and the text, joined by a space.
51
- - The chat template is applied with `add_generation_prompt=False`. The tokenizer appends the `<embedding>` token.
52
- - Images are resized to between 65,536 and 8,388,608 pixels (`min_pixels`, `max_pixels`), the bounds used in evaluation.
53
- - Keep the tokenizer's default right padding: the embedding is read at the last non-padding position.
54
 
55
  Instructions used in training and in MMEB-V2:
56
 
@@ -67,34 +66,32 @@ Instructions used in training and in MMEB-V2:
67
 
68
  ```python
69
  import torch
70
- from qwen_vl_utils import process_vision_info
 
71
  from transformers import AutoModel, AutoProcessor
72
 
73
  model_id = "UCSC-VLAA/OpenEmbed-0.8B"
74
- processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
75
- model = AutoModel.from_pretrained(model_id, trust_remote_code=True, dtype=torch.bfloat16).cuda().eval()
76
-
77
- MIN_PIXELS, MAX_PIXELS = 65536, 8388608
78
 
79
 
80
  def embed(inputs):
81
- """inputs: dicts with an optional "image" (path, URL, or PIL.Image) and an optional "text"."""
82
- conversations = []
83
  for x in inputs:
84
- content = []
85
- if x.get("image") is not None:
86
- content.append({"type": "image", "image": x["image"],
87
- "min_pixels": MIN_PIXELS, "max_pixels": MAX_PIXELS})
88
  if x.get("text") or not content:
89
  content.append({"type": "text", "text": x.get("text", "")})
90
- conversations.append([{"role": "user", "content": content}])
91
- texts = [processor.apply_chat_template(c, tokenize=False, add_generation_prompt=False)
92
- for c in conversations]
93
- images, _ = process_vision_info(conversations, image_patch_size=16)
94
- batch = processor(text=texts, images=images, padding=True, do_resize=False,
95
- return_tensors="pt").to(model.device)
96
  with torch.inference_mode():
97
- return model.embedding(**batch) # shape (len(inputs), 1024), L2-normalized
 
 
 
98
 
99
 
100
  queries = embed([
@@ -102,29 +99,81 @@ queries = embed([
102
  {"text": "Find a document image that matches the given query. What was the revenue in 2023?"},
103
  ])
104
  candidates = embed([
105
- {"image": "dog.jpg", "text": "Represent the given image."},
106
- {"image": "annual_report_page.png"},
107
  ])
108
  print(queries @ candidates.T)
109
  ```
110
 
 
 
111
  ### Sentence Transformers
112
 
113
  ```python
 
 
114
  from sentence_transformers import SentenceTransformer
115
 
116
- model = SentenceTransformer("UCSC-VLAA/OpenEmbed-0.8B", trust_remote_code=True)
117
  queries = model.encode([
118
  "Find me an everyday image that matches the given caption: A brown dog running on a beach.",
119
  "Find a document image that matches the given query. What was the revenue in 2023?",
120
  ])
121
  candidates = model.encode([
122
- {"image": "dog.jpg", "text": "Represent the given image."},
123
- {"image": "annual_report_page.png"},
124
  ])
125
  print(model.similarity(queries, candidates))
126
  ```
127
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  ## Training
129
 
130
  | | |
 
37
 
38
  ## Usage
39
 
40
+ No remote code is needed. Tested with transformers 5.2.0 and 5.23.0, sentence-transformers 5.7.0 and 6.3.0 (torch 2.8.0), and vLLM 0.34.0.
41
 
42
  ```bash
43
+ pip install torch torchvision "transformers>=5.2.0" "sentence-transformers>=5.7.0"
44
  ```
45
 
46
  ### Input format
47
 
48
+ OpenEmbed was trained and evaluated with WeMM-Embedding's input format, which the repository's chat template renders:
49
 
50
  - Each input is one user turn with no system turn. Images come first, followed by one text item that holds the instruction and the text, joined by a space.
51
+ - The tokenizer appends the `<embedding>` token. The embedding is the L2-normalized last hidden state at that token, the last non-padding position (keep the default right padding).
52
+ - Images are resized to between 65,536 and 8,388,608 pixels, the bounds of training and evaluation and the processor's defaults. Scores move with the image budget, so keep them.
 
53
 
54
  Instructions used in training and in MMEB-V2:
55
 
 
66
 
67
  ```python
68
  import torch
69
+ import torch.nn.functional as F
70
+ from PIL import Image
71
  from transformers import AutoModel, AutoProcessor
72
 
73
  model_id = "UCSC-VLAA/OpenEmbed-0.8B"
74
+ processor = AutoProcessor.from_pretrained(model_id, use_fast=False)
75
+ model = AutoModel.from_pretrained(model_id, dtype=torch.bfloat16).cuda().eval()
 
 
76
 
77
 
78
  def embed(inputs):
79
+ """inputs: dicts with an optional "image" (a PIL.Image) and an optional "text"."""
80
+ texts, images = [], []
81
  for x in inputs:
82
+ content = [{"type": "image"}] if x.get("image") is not None else []
 
 
 
83
  if x.get("text") or not content:
84
  content.append({"type": "text", "text": x.get("text", "")})
85
+ texts.append(processor.apply_chat_template([{"role": "user", "content": content}], tokenize=False))
86
+ if x.get("image") is not None:
87
+ images.append(x["image"])
88
+ batch = processor(text=texts, images=images or None, padding=True, return_tensors="pt").to(model.device)
89
+ model.rope_deltas = None # transformers < 5.15 would reuse the last image batch's value
 
90
  with torch.inference_mode():
91
+ hidden = model(**batch).last_hidden_state
92
+ last = batch["attention_mask"].sum(dim=1) - 1 # the <embedding> token
93
+ rows = torch.arange(hidden.size(0), device=hidden.device)
94
+ return F.normalize(hidden[rows, last].float(), dim=-1) # shape (len(inputs), 1024)
95
 
96
 
97
  queries = embed([
 
99
  {"text": "Find a document image that matches the given query. What was the revenue in 2023?"},
100
  ])
101
  candidates = embed([
102
+ {"image": Image.open("dog.jpg"), "text": "Represent the given image."},
103
+ {"image": Image.open("annual_report_page.png")},
104
  ])
105
  print(queries @ candidates.T)
106
  ```
107
 
108
+ `use_fast=False` resizes images with PIL, as our evaluation did. The default (torchvision) processor works too and gives embeddings within a cosine of 0.999 of these.
109
+
110
  ### Sentence Transformers
111
 
112
  ```python
113
+ import torch
114
+ from PIL import Image
115
  from sentence_transformers import SentenceTransformer
116
 
117
+ model = SentenceTransformer("UCSC-VLAA/OpenEmbed-0.8B", model_kwargs={"dtype": torch.bfloat16})
118
  queries = model.encode([
119
  "Find me an everyday image that matches the given caption: A brown dog running on a beach.",
120
  "Find a document image that matches the given query. What was the revenue in 2023?",
121
  ])
122
  candidates = model.encode([
123
+ {"image": Image.open("dog.jpg"), "text": "Represent the given image."},
124
+ {"image": Image.open("annual_report_page.png")},
125
  ])
126
  print(model.similarity(queries, candidates))
127
  ```
128
 
129
+ Add `processor_kwargs={"use_fast": False}` to resize images exactly as our evaluation did.
130
+
131
+ ### vLLM
132
+
133
+ ```bash
134
+ hf download UCSC-VLAA/OpenEmbed-0.8B --local-dir OpenEmbed-0.8B
135
+ vllm serve OpenEmbed-0.8B --runner pooling --chat-template OpenEmbed-0.8B/embedding_chat_template.jinja \
136
+ --limit-mm-per-prompt.video=0
137
+ ```
138
+
139
+ ```python
140
+ import base64
141
+ import requests
142
+
143
+
144
+ def image_url(path):
145
+ return "data:image/jpeg;base64," + base64.b64encode(open(path, "rb").read()).decode()
146
+
147
+
148
+ response = requests.post("http://localhost:8000/v1/embeddings", json={
149
+ "model": "OpenEmbed-0.8B",
150
+ "messages": [{"role": "user", "content": [
151
+ {"type": "image_url", "image_url": {"url": image_url("dog.jpg")}},
152
+ {"type": "text", "text": "Represent the given image."},
153
+ ]}],
154
+ "encoding_format": "float",
155
+ })
156
+ embedding = response.json()["data"][0]["embedding"]
157
+ ```
158
+
159
+ We ran it on a 24 GB card with `--max-model-len 16384` added. `--limit-mm-per-prompt.video=0` leaves out video inputs, which OpenEmbed was not trained on, and the memory vLLM would set aside for them.
160
+
161
+ ### How close each path is to our evaluation
162
+
163
+ We compared each path with the embeddings of our evaluation (the official evaluation code, transformers 5.2.0) on nine inputs: three texts, three images with text, a document page, and an image above and one below the pixel bounds. The Transformers code above produced the evaluation's token ids and image grids for every input. Lowest cosine similarity per path:
164
+
165
+ | Path | Lowest cosine |
166
+ |---|---:|
167
+ | Transformers code above, transformers 5.2.0 | 0.999998 |
168
+ | Transformers code above, transformers 5.23.0 | 0.9992 |
169
+ | Sentence Transformers 5.7.0 (transformers 5.2.0) | 0.9997 |
170
+ | Sentence Transformers 6.3.0 (transformers 5.23.0) | 0.9990 |
171
+ | vLLM 0.34.0 | 0.9996 |
172
+
173
+ The rest comes from the numerics of later library versions and from the default image processor's resizing.
174
+
175
+ `trust_remote_code=True` still loads WeMM-Embedding's class (`modeling_wemm_embedding.py`, which the evaluation code reads); its `embedding` method computes the same embedding.
176
+
177
  ## Training
178
 
179
  | | |
additional_chat_templates/sentence_transformers.jinja DELETED
@@ -1,32 +0,0 @@
1
- {#- Embedding template used by Sentence Transformers.
2
-
3
- Renders the same surface form as chat_template.jinja for text and images. Video
4
- is the exception: it renders as a bare <|video_pad|>, because the processor
5
- expands that token into one <seconds><|vision_start|>...<|vision_end|> block per
6
- frame and, from transformers 5.3, no longer consumes a surrounding pair. The
7
- wrapped form therefore gains a second, unwanted pair of vision boundaries there.
8
- This matches embedding_chat_template.jinja, which is bare for the same reason.
9
-
10
- The tokenizer normalizer drops the role newline before a leading image and the
11
- newline after the final <|im_end|>, then the post-processor appends <embedding>. #}
12
- {%- for message in messages %}
13
- {{- '<|im_start|>' + message.role + '\n' }}
14
- {%- if message.content is string %}
15
- {{- message.content }}
16
- {%- elif message.content is iterable and message.content is not mapping %}
17
- {%- for item in message.content %}
18
- {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
19
- {{- '<|vision_start|><|image_pad|><|vision_end|>' }}
20
- {%- elif 'video' in item or item.type == 'video' %}
21
- {{- '<|video_pad|>' }}
22
- {%- elif 'text' in item %}
23
- {{- item.text }}
24
- {%- else %}
25
- {{- raise_exception('Unexpected item type in content.') }}
26
- {%- endif %}
27
- {%- endfor %}
28
- {%- elif message.content is not none %}
29
- {{- raise_exception('Unexpected content type.') }}
30
- {%- endif %}
31
- {{- '<|im_end|>\n' }}
32
- {%- endfor %}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
chat_template.jinja CHANGED
@@ -1,154 +1,26 @@
1
- {%- set image_count = namespace(value=0) %}
2
- {%- set video_count = namespace(value=0) %}
3
- {%- macro render_content(content, do_vision_count, is_system_content=false) %}
4
- {%- if content is string %}
5
- {{- content }}
6
- {%- elif content is iterable and content is not mapping %}
7
- {%- for item in content %}
8
- {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
9
- {%- if is_system_content %}
10
- {{- raise_exception('System message cannot contain images.') }}
11
- {%- endif %}
12
- {%- if do_vision_count %}
13
- {%- set image_count.value = image_count.value + 1 %}
14
- {%- endif %}
15
- {%- if add_vision_id %}
16
- {{- 'Picture ' ~ image_count.value ~ ': ' }}
17
- {%- endif %}
18
- {{- '<|vision_start|><|image_pad|><|vision_end|>' }}
19
- {%- elif 'video' in item or item.type == 'video' %}
20
- {%- if is_system_content %}
21
- {{- raise_exception('System message cannot contain videos.') }}
22
- {%- endif %}
23
- {%- if do_vision_count %}
24
- {%- set video_count.value = video_count.value + 1 %}
25
- {%- endif %}
26
- {%- if add_vision_id %}
27
- {{- 'Video ' ~ video_count.value ~ ': ' }}
28
- {%- endif %}
29
- {{- '<|vision_start|><|video_pad|><|vision_end|>' }}
30
- {%- elif 'text' in item %}
31
- {{- item.text }}
32
- {%- else %}
33
- {{- raise_exception('Unexpected item type in content.') }}
34
- {%- endif %}
35
- {%- endfor %}
36
- {%- elif content is none or content is undefined %}
37
- {{- '' }}
38
- {%- else %}
39
- {{- raise_exception('Unexpected content type.') }}
40
- {%- endif %}
41
- {%- endmacro %}
42
- {%- if not messages %}
43
- {{- raise_exception('No messages provided.') }}
44
- {%- endif %}
45
- {%- if tools and tools is iterable and tools is not mapping %}
46
- {{- '<|im_start|>system\n' }}
47
- {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
48
- {%- for tool in tools %}
49
- {{- "\n" }}
50
- {{- tool | tojson }}
51
- {%- endfor %}
52
- {{- "\n</tools>" }}
53
- {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
54
- {%- if messages[0].role == 'system' %}
55
- {%- set content = render_content(messages[0].content, false, true)|trim %}
56
- {%- if content %}
57
- {{- '\n\n' + content }}
58
- {%- endif %}
59
- {%- endif %}
60
- {{- '<|im_end|>\n' }}
61
  {%- else %}
62
- {%- if messages[0].role == 'system' %}
63
- {%- set content = render_content(messages[0].content, false, true)|trim %}
64
- {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
65
- {%- endif %}
66
  {%- endif %}
67
- {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
68
- {%- for message in messages[::-1] %}
69
- {%- set index = (messages|length - 1) - loop.index0 %}
70
- {%- if ns.multi_step_tool and message.role == "user" %}
71
- {%- set content = render_content(message.content, false)|trim %}
72
- {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
73
- {%- set ns.multi_step_tool = false %}
74
- {%- set ns.last_query_index = index %}
75
- {%- endif %}
76
- {%- endif %}
77
  {%- endfor %}
78
- {%- if ns.multi_step_tool %}
79
- {{- raise_exception('No user query found in messages.') }}
80
  {%- endif %}
81
- {%- for message in messages %}
82
- {%- set content = render_content(message.content, true)|trim %}
83
- {%- if message.role == "system" %}
84
- {%- if not loop.first %}
85
- {{- raise_exception('System message must be at the beginning.') }}
86
- {%- endif %}
87
- {%- elif message.role == "user" %}
88
- {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
89
- {%- elif message.role == "assistant" %}
90
- {%- set reasoning_content = '' %}
91
- {%- if message.reasoning_content is string %}
92
- {%- set reasoning_content = message.reasoning_content %}
93
- {%- else %}
94
- {%- if '</think>' in content %}
95
- {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
96
- {%- set content = content.split('</think>')[-1].lstrip('\n') %}
97
- {%- endif %}
98
- {%- endif %}
99
- {%- set reasoning_content = reasoning_content|trim %}
100
- {%- if loop.index0 > ns.last_query_index %}
101
- {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
102
- {%- else %}
103
- {{- '<|im_start|>' + message.role + '\n' + content }}
104
- {%- endif %}
105
- {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
106
- {%- for tool_call in message.tool_calls %}
107
- {%- if tool_call.function is defined %}
108
- {%- set tool_call = tool_call.function %}
109
- {%- endif %}
110
- {%- if loop.first %}
111
- {%- if content|trim %}
112
- {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
113
- {%- else %}
114
- {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
115
- {%- endif %}
116
- {%- else %}
117
- {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
118
- {%- endif %}
119
- {%- if tool_call.arguments is defined %}
120
- {%- for args_name, args_value in tool_call.arguments|items %}
121
- {{- '<parameter=' + args_name + '>\n' }}
122
- {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
123
- {{- args_value }}
124
- {{- '\n</parameter>\n' }}
125
- {%- endfor %}
126
- {%- endif %}
127
- {{- '</function>\n</tool_call>' }}
128
- {%- endfor %}
129
- {%- endif %}
130
- {{- '<|im_end|>\n' }}
131
- {%- elif message.role == "tool" %}
132
- {%- if loop.previtem and loop.previtem.role != "tool" %}
133
- {{- '<|im_start|>user' }}
134
- {%- endif %}
135
- {{- '\n<tool_response>\n' }}
136
- {{- content }}
137
- {{- '\n</tool_response>' }}
138
- {%- if not loop.last and loop.nextitem.role != "tool" %}
139
- {{- '<|im_end|>\n' }}
140
- {%- elif loop.last %}
141
- {{- '<|im_end|>\n' }}
142
- {%- endif %}
143
- {%- else %}
144
- {{- raise_exception('Unexpected message role.') }}
145
- {%- endif %}
146
  {%- endfor %}
147
- {%- if add_generation_prompt %}
148
- {{- '<|im_start|>assistant\n' }}
149
- {%- if enable_thinking is defined and enable_thinking is true %}
150
- {{- '<think>\n' }}
151
- {%- else %}
152
- {{- '<think>\n\n</think>\n\n' }}
153
- {%- endif %}
154
- {%- endif %}
 
1
+ {#- OpenEmbed input format: one user turn with no system turn; images first, then one text item.
2
+ The surface form is written out exactly as in training (no newline between the role and a leading image,
3
+ none after the final <|im_end|>), so the tokens do not depend on the tokenizer's normalizer, which
4
+ transformers stopped applying in later 5.x releases. The tokenizer's post-processor appends <embedding>. -#}
5
+ {%- for message in messages %}
6
+ {{- '<|im_start|>' + message.role }}
7
+ {%- if message.content is string %}
8
+ {{- '\n' + message.content }}
9
+ {%- else %}
10
+ {%- for item in message.content %}
11
+ {%- if item.type in ['image', 'image_url'] or 'image' in item or 'image_url' in item %}
12
+ {{- '<|vision_start|><|image_pad|><|vision_end|>' }}
13
+ {%- elif item.type in ['video', 'video_url'] or 'video' in item or 'video_url' in item %}
14
+ {{- '\n<|video_pad|>' }}
15
+ {%- elif item.type == 'text' or 'text' in item %}
16
+ {{- ('\n' if loop.first else '') + item.text }}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  {%- else %}
18
+ {{- raise_exception('Unsupported content type') }}
 
 
 
19
  {%- endif %}
 
 
 
 
 
 
 
 
 
 
20
  {%- endfor %}
 
 
21
  {%- endif %}
22
+ {{- '<|im_end|>' }}
23
+ {%- if not loop.last %}
24
+ {{- '\n' }}
25
+ {%- endif %}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  {%- endfor %}
 
 
 
 
 
 
 
 
config_sentence_transformers.json CHANGED
@@ -1,8 +1,8 @@
1
  {
2
  "__version__": {
3
  "pytorch": "2.8.0",
4
- "sentence_transformers": "5.7.0",
5
- "transformers": "5.2.0"
6
  },
7
  "default_prompt_name": null,
8
  "model_type": "SentenceTransformer",
 
1
  {
2
  "__version__": {
3
  "pytorch": "2.8.0",
4
+ "sentence_transformers": "6.3.0",
5
+ "transformers": "5.23.0"
6
  },
7
  "default_prompt_name": null,
8
  "model_type": "SentenceTransformer",
modeling_st_wemm.py DELETED
@@ -1,93 +0,0 @@
1
- """Sentence Transformers module for WeMM-Embedding.
2
-
3
- Reproduces the `transformers` usage from the model card inside a Sentence Transformers
4
- pipeline: vision inputs are prepared with `qwen_vl_utils.process_vision_info` and the
5
- embedding is read from `WeMMEmbedding.embedding`, which pools the `<embedding>` position and
6
- L2-normalizes. Everything else (batching, prompts, truncation, `encode_query` /
7
- `encode_document`, similarity) comes from the stock `Transformer` module.
8
-
9
- Modified by the OpenEmbed authors (2026-11-18) from tencent/WeMM-Embedding-2B (Apache-2.0):
10
- an image item without its own `min_pixels` / `max_pixels` is resized within 65,536 to
11
- 8,388,608 pixels, the image budget OpenEmbed was evaluated with. Nothing else changes.
12
- """
13
-
14
- from __future__ import annotations
15
-
16
- import inspect
17
- from typing import Any
18
-
19
- from sentence_transformers.models import Transformer
20
-
21
- OPENEMBED_MIN_PIXELS = 65536
22
- OPENEMBED_MAX_PIXELS = 8388608
23
-
24
-
25
- def _with_pixel_budget(conversation):
26
- """A copy of one conversation whose image items carry the OpenEmbed pixel bounds."""
27
- out = []
28
- for message in conversation:
29
- content = message.get("content") if isinstance(message, dict) else None
30
- if isinstance(content, (list, tuple)):
31
- items = []
32
- for item in content:
33
- if isinstance(item, dict) and ("image" in item or "image_url" in item or item.get("type") == "image"):
34
- item = {"min_pixels": OPENEMBED_MIN_PIXELS, "max_pixels": OPENEMBED_MAX_PIXELS, **item}
35
- items.append(item)
36
- message = {**message, "content": items}
37
- out.append(message)
38
- return out
39
-
40
-
41
- class WeMMTransformer(Transformer):
42
- """`Transformer` that prepares images and videos the way the model card's snippet does."""
43
-
44
- def __init__(self, model_name_or_path: str, **kwargs: Any) -> None:
45
- super().__init__(model_name_or_path, **kwargs)
46
- vision_config = getattr(self.config, "vision_config", None)
47
- self.image_patch_size = int(getattr(vision_config, "patch_size", 16))
48
-
49
- # `embedding` hands its **kwargs to the inner model, so filtering on its own signature
50
- # would drop `pixel_values`. Filter on the inner model's parameters instead, plus the
51
- # processor's input names for anything the model only accepts as **kwargs.
52
- inner_model = getattr(self.model, "model", self.model)
53
- signature = set(inspect.signature(inner_model.forward).parameters)
54
- signature |= set(getattr(self.processor, "model_input_names", ()))
55
- for modality_params in self.modality_config.values():
56
- method_name = modality_params["method"]
57
- if method_name != "forward":
58
- self._method_signature_cache.setdefault(method_name, signature)
59
-
60
- def _apply_chat_template(
61
- self,
62
- messages: list[list[dict[str, Any]]],
63
- modality_kwargs: dict[str, dict[str, Any]],
64
- common_kwargs: dict[str, Any],
65
- chat_template_kwargs: dict[str, Any],
66
- ) -> dict[str, Any]:
67
- """Render the chat template and prepare images / videos exactly as the model card does."""
68
- from qwen_vl_utils import process_vision_info
69
-
70
- chat_template_kwargs = {"add_generation_prompt": False, **chat_template_kwargs}
71
- texts = [
72
- self.processor.apply_chat_template(conversation, tokenize=False, **chat_template_kwargs)
73
- for conversation in messages
74
- ]
75
- images, videos, video_kwargs = process_vision_info(
76
- [_with_pixel_budget(list(conversation)) for conversation in messages],
77
- image_patch_size=self.image_patch_size,
78
- return_video_kwargs=True,
79
- return_video_metadata=True,
80
- )
81
- if videos is not None:
82
- videos, video_metadata = (list(part) for part in zip(*videos))
83
- video_kwargs = {**video_kwargs, "video_metadata": video_metadata}
84
-
85
- return self.processor(
86
- text=texts,
87
- images=images,
88
- videos=videos,
89
- text_kwargs=modality_kwargs["text"],
90
- images_kwargs=modality_kwargs["image"],
91
- videos_kwargs={**modality_kwargs["video"], **video_kwargs},
92
- common_kwargs=common_kwargs,
93
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
modules.json CHANGED
@@ -3,6 +3,18 @@
3
  "idx": 0,
4
  "name": "0",
5
  "path": "",
6
- "type": "modeling_st_wemm.WeMMTransformer"
 
 
 
 
 
 
 
 
 
 
 
 
7
  }
8
  ]
 
3
  "idx": 0,
4
  "name": "0",
5
  "path": "",
6
+ "type": "sentence_transformers.base.modules.transformer.Transformer"
7
+ },
8
+ {
9
+ "idx": 1,
10
+ "name": "1",
11
+ "path": "1_Pooling",
12
+ "type": "sentence_transformers.sentence_transformer.modules.pooling.Pooling"
13
+ },
14
+ {
15
+ "idx": 2,
16
+ "name": "2",
17
+ "path": "2_Normalize",
18
+ "type": "sentence_transformers.sentence_transformer.modules.normalize.Normalize"
19
  }
20
  ]
processor_config.json CHANGED
@@ -20,7 +20,7 @@
20
  "resample": 3,
21
  "rescale_factor": 0.00392156862745098,
22
  "size": {
23
- "longest_edge": 16777216,
24
  "shortest_edge": 65536
25
  },
26
  "temporal_patch_size": 2
 
20
  "resample": 3,
21
  "rescale_factor": 0.00392156862745098,
22
  "size": {
23
+ "longest_edge": 8388608,
24
  "shortest_edge": 65536
25
  },
26
  "temporal_patch_size": 2
sentence_bert_config.json CHANGED
@@ -1,37 +1,29 @@
1
  {
2
- "transformer_task": "feature-extraction",
3
- "modality_config": {
4
- "text": {
5
- "method": "embedding",
6
- "method_output_name": null
7
- },
8
- "image": {
9
- "method": "embedding",
10
- "method_output_name": null
11
- },
12
- "video": {
13
- "method": "embedding",
14
- "method_output_name": null
15
- },
16
- "image+text": {
17
- "method": "embedding",
18
- "method_output_name": null
19
- },
20
- "text+video": {
21
- "method": "embedding",
22
- "method_output_name": null
23
- },
24
- "message": {
25
- "method": "embedding",
26
- "method_output_name": null,
27
- "format": "structured"
28
- }
29
  },
30
- "module_output_name": "sentence_embedding",
31
- "processing_kwargs": {
32
- "chat_template": {
33
- "chat_template": "sentence_transformers"
34
- }
35
  },
36
- "unpad_inputs": false
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  }
 
1
  {
2
+ "transformer_task": "feature-extraction",
3
+ "modality_config": {
4
+ "text": {
5
+ "method": "forward",
6
+ "method_output_name": "last_hidden_state"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  },
8
+ "image": {
9
+ "method": "forward",
10
+ "method_output_name": "last_hidden_state"
 
 
11
  },
12
+ "image+text": {
13
+ "method": "forward",
14
+ "method_output_name": "last_hidden_state"
15
+ },
16
+ "message": {
17
+ "method": "forward",
18
+ "method_output_name": "last_hidden_state",
19
+ "format": "structured"
20
+ }
21
+ },
22
+ "module_output_name": "token_embeddings",
23
+ "processing_kwargs": {
24
+ "chat_template": {
25
+ "add_generation_prompt": false
26
+ }
27
+ },
28
+ "unpad_inputs": false
29
  }