kingmin commited on
Commit
ff90a13
·
verified ·
1 Parent(s): 95f26d4

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +68 -28
README.md CHANGED
@@ -135,8 +135,16 @@ Load the processor and model once. The following examples share these objects an
135
 
136
  ```python
137
  import torch
 
138
  from transformers import AutoModelForImageTextToText, AutoProcessor
139
 
 
 
 
 
 
 
 
140
  model_id = "tencent/WeMM-Ecom-9B"
141
  processor = AutoProcessor.from_pretrained(model_id)
142
  model = AutoModelForImageTextToText.from_pretrained(
@@ -152,11 +160,26 @@ generation_kwargs = {
152
  "repetition_penalty": 1.0,
153
  }
154
 
 
 
 
 
 
 
 
 
 
 
 
155
  def split_output(text, thinking):
156
  if not thinking:
 
 
157
  return "", text.strip()
158
  reasoning, closed, answer = text.partition("</think>")
159
- return reasoning.removeprefix("<think>").strip(), answer.strip() if closed else ""
 
 
160
  ```
161
 
162
  The examples print the final answer. In Thinking Mode, `reasoning_text` contains the reasoning and the final answer starts after `</think>`.
@@ -169,7 +192,7 @@ Describe an image and its visible details:
169
  messages = [{
170
  "role": "user",
171
  "content": [
172
- {"type": "image", "image": "./product.jpg"},
173
  {"type": "text", "text": "Briefly describe the main subjects and their visible attributes."},
174
  ],
175
  }]
@@ -185,6 +208,7 @@ with torch.inference_mode():
185
  top_p=0.95 if enable_thinking else 0.8,
186
  )
187
  new_tokens = outputs[:, inputs["input_ids"].shape[1]:]
 
188
  decoded = processor.batch_decode(
189
  new_tokens, skip_special_tokens=True, clean_up_tokenization_spaces=False,
190
  )[0]
@@ -218,6 +242,7 @@ with torch.inference_mode():
218
  top_p=0.95 if enable_thinking else 0.8,
219
  )
220
  new_tokens = outputs[:, inputs["input_ids"].shape[1]:]
 
221
  decoded = processor.batch_decode(
222
  new_tokens, skip_special_tokens=True, clean_up_tokenization_spaces=False,
223
  )[0]
@@ -234,8 +259,8 @@ Provide multiple product views in one conversation:
234
 
235
  ```python
236
  messages = [{"role": "user", "content": [
237
- {"type": "image", "image": "./product_front.jpg"},
238
- {"type": "image", "image": "./product_back.jpg"},
239
  {"type": "text", "text": "Compare these views and extract the visible variant attributes."},
240
  ]}]
241
  inputs = processor.apply_chat_template(
@@ -250,6 +275,7 @@ with torch.inference_mode():
250
  top_p=0.95 if enable_thinking else 0.8,
251
  )
252
  new_tokens = outputs[:, inputs["input_ids"].shape[1]:]
 
253
  decoded = processor.batch_decode(
254
  new_tokens, skip_special_tokens=True, clean_up_tokenization_spaces=False,
255
  )[0]
@@ -296,6 +322,7 @@ with torch.inference_mode():
296
  top_p=0.95 if enable_thinking else 0.8,
297
  )
298
  new_tokens = outputs[:, inputs["input_ids"].shape[1]:]
 
299
  decoded = processor.batch_decode(
300
  new_tokens, skip_special_tokens=True, clean_up_tokenization_spaces=False,
301
  )[0]
@@ -316,7 +343,7 @@ Pass a list of conversations and use left padding. Crop generated tokens at the
316
  processor.tokenizer.padding_side = "left"
317
  batch_messages = [
318
  [{"role": "user", "content": [
319
- {"type": "image", "image": "./product_front.jpg"},
320
  {"type": "text", "text": "Extract the visible product attributes."},
321
  ]}],
322
  [{"role": "user", "content": [{
@@ -335,6 +362,7 @@ with torch.inference_mode():
335
  top_p=0.95 if enable_thinking else 0.8,
336
  )
337
  new_tokens = outputs[:, inputs["input_ids"].shape[1]:]
 
338
  decoded_batch = processor.batch_decode(
339
  new_tokens, skip_special_tokens=True, clean_up_tokenization_spaces=False,
340
  )
@@ -352,7 +380,7 @@ Keep the media references in the conversation history and append only the final
352
 
353
  ```python
354
  turns = [
355
- [{"type": "image", "image": "./product.jpg"},
356
  {"type": "text", "text": "Describe this product's visible attributes."}],
357
  [{"type": "text", "text": "Which attributes should be included in the product title?"}],
358
  ]
@@ -371,6 +399,7 @@ for content in turns:
371
  top_p=0.95 if enable_thinking else 0.8,
372
  )
373
  new_tokens = outputs[:, inputs["input_ids"].shape[1]:]
 
374
  decoded = processor.batch_decode(
375
  new_tokens, skip_special_tokens=True, clean_up_tokenization_spaces=False,
376
  )[0]
@@ -391,7 +420,7 @@ The image processor accepts pixel-area bounds through `images_kwargs`. This exam
391
  ```python
392
  spatial_factor = processor.image_processor.patch_size * processor.image_processor.merge_size
393
  messages = [{"role": "user", "content": [
394
- {"type": "image", "image": "./product.jpg"},
395
  {"type": "text", "text": "Describe the visible objects and their attributes. Report only text that is clearly legible."},
396
  ]}]
397
  inputs = processor.apply_chat_template(
@@ -410,6 +439,7 @@ with torch.inference_mode():
410
  top_p=0.95 if enable_thinking else 0.8,
411
  )
412
  new_tokens = outputs[:, inputs["input_ids"].shape[1]:]
 
413
  decoded = processor.batch_decode(
414
  new_tokens, skip_special_tokens=True, clean_up_tokenization_spaces=False,
415
  )[0]
@@ -479,33 +509,21 @@ python -m sglang.launch_server \
479
  --port 8000
480
  ```
481
 
482
- <details>
483
- <summary>CUDA 12.9 environment setup</summary>
484
-
485
- For **Linux x86_64 with SGLang 0.5.15 and PyTorch 2.11.0+cu129**, follow the [CUDA 12.9 override in SGLang's Dockerfile](https://github.com/sgl-project/sglang/blob/v0.5.15/docker/Dockerfile#L228-L234). If an incompatible DeepGEMM build produces an import error mentioning `libcudart.so.13`, install the matching CUDA 12.9 wheel in the activated environment:
486
-
487
- ```bash
488
- python -m pip install --no-deps --force-reinstall \
489
- "https://github.com/sgl-project/whl/releases/download/v0.1.4/sgl_deep_gemm-0.1.4+cu129-py3-none-manylinux2014_x86_64.whl"
490
- ```
491
-
492
- For other SGLang, PyTorch, or CUDA versions, select the corresponding builds from the [official installation guide](https://docs.sglang.io/docs/get-started/install.md).
493
-
494
- </details>
495
-
496
  ### OpenAI-compatible API
497
 
498
  Install the client where you send requests:
499
 
500
  ```bash
501
- pip install -U openai
502
  ```
503
 
504
  Set `enable_thinking` before constructing the shared request settings; rerun this setup when changing modes. Local media are encoded in the client so the server does not need access to their file paths.
505
 
506
  ```python
507
  import base64
 
508
  from pathlib import Path
 
509
  from openai import OpenAI
510
 
511
  client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
@@ -523,11 +541,25 @@ request_kwargs = {
523
  }
524
 
525
  def media_url(path, mime_type):
526
- data = base64.b64encode(Path(path).read_bytes()).decode("ascii")
527
- return f"data:{mime_type};base64,{data}"
 
 
 
 
 
 
 
 
 
 
 
528
 
529
  def show_response(response):
530
- message = response.choices[0].message
 
 
 
531
  reasoning = getattr(message, "reasoning", None) or getattr(message, "reasoning_content", None)
532
  if reasoning:
533
  print("Reasoning:\n" + reasoning)
@@ -622,10 +654,16 @@ messages = [{"role": "user", "content": [
622
  ]}]
623
  stream = client.chat.completions.create(messages=messages, stream=True, **request_kwargs)
624
  channel = None
 
 
625
  for chunk in stream:
626
  if not chunk.choices:
627
  continue
628
- delta = chunk.choices[0].delta
 
 
 
 
629
  reasoning = getattr(delta, "reasoning", None) or getattr(delta, "reasoning_content", None)
630
  for label, text in [("Reasoning", reasoning), ("Answer", delta.content)]:
631
  if not text:
@@ -635,6 +673,8 @@ for chunk in stream:
635
  channel = label
636
  print(text, end="", flush=True)
637
  print()
 
 
638
  ```
639
 
640
  </details>
@@ -643,7 +683,7 @@ print()
643
 
644
  ### Sampling Parameters
645
 
646
- Choose a profile by mode and task. The following settings are starting points drawn from our evaluation configurations.
647
 
648
  - **Instruct Mode — general tasks:** `temperature=0.7`, `top_p=0.8`, `top_k=20`, `min_p=0.0`, `presence_penalty=1.5`, `repetition_penalty=1.0`.
649
  - **Instruct Mode — structured outputs, such as attribute selection, product detection, and SKU matching:** `temperature=0.7`, `top_p=0.8`, `top_k=20`, `min_p=0.0`, `presence_penalty=0.0`, `repetition_penalty=1.0`.
@@ -656,7 +696,7 @@ Use the OpenAI-compatible examples to apply all listed parameters. Pass `tempera
656
  ### Mode and Output Settings
657
 
658
  - **Select the mode explicitly:** use `enable_thinking=False` for Instruct Mode and `enable_thinking=True` for Thinking Mode. In the serving API, pass this switch through `chat_template_kwargs` in `extra_body`.
659
- - **Allow enough output tokens:** our evaluations use a maximum generation budget of **65,536 tokens**. The Quick Start uses **4,096 tokens** for a compact example; increase this budget for longer reasoning. Set `max_new_tokens` in Transformers or `max_completion_tokens` in the serving API. The serving context limit must accommodate both the input and the generated output.
660
  - **Specify the output format:** for extraction, matching, and grounding, state the required fields, labels, and coordinate format. For multiple-choice tasks, request a clear final answer. In multi-turn conversations, append the assistant's final answer to the history.
661
 
662
  ## Citation
 
135
 
136
  ```python
137
  import torch
138
+ from PIL import Image, ImageOps
139
  from transformers import AutoModelForImageTextToText, AutoProcessor
140
 
141
+ # Apply camera orientation and use white behind transparent image regions.
142
+ def load_image(path):
143
+ with Image.open(path) as source:
144
+ image = ImageOps.exif_transpose(source).convert("RGBA")
145
+ background = Image.new("RGBA", image.size, (255, 255, 255, 255))
146
+ return Image.alpha_composite(background, image).convert("RGB")
147
+
148
  model_id = "tencent/WeMM-Ecom-9B"
149
  processor = AutoProcessor.from_pretrained(model_id)
150
  model = AutoModelForImageTextToText.from_pretrained(
 
160
  "repetition_penalty": 1.0,
161
  }
162
 
163
+ def check_output_stopped(token_ids, eos_token_id):
164
+ if type(eos_token_id) is int:
165
+ eos_ids = {eos_token_id}
166
+ elif isinstance(eos_token_id, list) and all(type(value) is int for value in eos_token_id):
167
+ eos_ids = set(eos_token_id)
168
+ else:
169
+ raise RuntimeError("No valid EOS token IDs are configured.")
170
+ rows = token_ids.tolist()
171
+ if not eos_ids or not rows or any(not any(token_id in eos_ids for token_id in row) for row in rows):
172
+ raise RuntimeError("Generation ended without an EOS token. Review max_new_tokens and generation settings.")
173
+
174
  def split_output(text, thinking):
175
  if not thinking:
176
+ if not text.strip():
177
+ raise RuntimeError("No final answer. Review the output budget and generation settings.")
178
  return "", text.strip()
179
  reasoning, closed, answer = text.partition("</think>")
180
+ if not closed or not answer.strip():
181
+ raise RuntimeError("No complete final answer. Review max_new_tokens and generation settings.")
182
+ return reasoning.removeprefix("<think>").strip(), answer.strip()
183
  ```
184
 
185
  The examples print the final answer. In Thinking Mode, `reasoning_text` contains the reasoning and the final answer starts after `</think>`.
 
192
  messages = [{
193
  "role": "user",
194
  "content": [
195
+ {"type": "image", "image": load_image("./product.jpg")},
196
  {"type": "text", "text": "Briefly describe the main subjects and their visible attributes."},
197
  ],
198
  }]
 
208
  top_p=0.95 if enable_thinking else 0.8,
209
  )
210
  new_tokens = outputs[:, inputs["input_ids"].shape[1]:]
211
+ check_output_stopped(new_tokens, model.generation_config.eos_token_id)
212
  decoded = processor.batch_decode(
213
  new_tokens, skip_special_tokens=True, clean_up_tokenization_spaces=False,
214
  )[0]
 
242
  top_p=0.95 if enable_thinking else 0.8,
243
  )
244
  new_tokens = outputs[:, inputs["input_ids"].shape[1]:]
245
+ check_output_stopped(new_tokens, model.generation_config.eos_token_id)
246
  decoded = processor.batch_decode(
247
  new_tokens, skip_special_tokens=True, clean_up_tokenization_spaces=False,
248
  )[0]
 
259
 
260
  ```python
261
  messages = [{"role": "user", "content": [
262
+ {"type": "image", "image": load_image("./product_front.jpg")},
263
+ {"type": "image", "image": load_image("./product_back.jpg")},
264
  {"type": "text", "text": "Compare these views and extract the visible variant attributes."},
265
  ]}]
266
  inputs = processor.apply_chat_template(
 
275
  top_p=0.95 if enable_thinking else 0.8,
276
  )
277
  new_tokens = outputs[:, inputs["input_ids"].shape[1]:]
278
+ check_output_stopped(new_tokens, model.generation_config.eos_token_id)
279
  decoded = processor.batch_decode(
280
  new_tokens, skip_special_tokens=True, clean_up_tokenization_spaces=False,
281
  )[0]
 
322
  top_p=0.95 if enable_thinking else 0.8,
323
  )
324
  new_tokens = outputs[:, inputs["input_ids"].shape[1]:]
325
+ check_output_stopped(new_tokens, model.generation_config.eos_token_id)
326
  decoded = processor.batch_decode(
327
  new_tokens, skip_special_tokens=True, clean_up_tokenization_spaces=False,
328
  )[0]
 
343
  processor.tokenizer.padding_side = "left"
344
  batch_messages = [
345
  [{"role": "user", "content": [
346
+ {"type": "image", "image": load_image("./product_front.jpg")},
347
  {"type": "text", "text": "Extract the visible product attributes."},
348
  ]}],
349
  [{"role": "user", "content": [{
 
362
  top_p=0.95 if enable_thinking else 0.8,
363
  )
364
  new_tokens = outputs[:, inputs["input_ids"].shape[1]:]
365
+ check_output_stopped(new_tokens, model.generation_config.eos_token_id)
366
  decoded_batch = processor.batch_decode(
367
  new_tokens, skip_special_tokens=True, clean_up_tokenization_spaces=False,
368
  )
 
380
 
381
  ```python
382
  turns = [
383
+ [{"type": "image", "image": load_image("./product.jpg")},
384
  {"type": "text", "text": "Describe this product's visible attributes."}],
385
  [{"type": "text", "text": "Which attributes should be included in the product title?"}],
386
  ]
 
399
  top_p=0.95 if enable_thinking else 0.8,
400
  )
401
  new_tokens = outputs[:, inputs["input_ids"].shape[1]:]
402
+ check_output_stopped(new_tokens, model.generation_config.eos_token_id)
403
  decoded = processor.batch_decode(
404
  new_tokens, skip_special_tokens=True, clean_up_tokenization_spaces=False,
405
  )[0]
 
420
  ```python
421
  spatial_factor = processor.image_processor.patch_size * processor.image_processor.merge_size
422
  messages = [{"role": "user", "content": [
423
+ {"type": "image", "image": load_image("./product.jpg")},
424
  {"type": "text", "text": "Describe the visible objects and their attributes. Report only text that is clearly legible."},
425
  ]}]
426
  inputs = processor.apply_chat_template(
 
439
  top_p=0.95 if enable_thinking else 0.8,
440
  )
441
  new_tokens = outputs[:, inputs["input_ids"].shape[1]:]
442
+ check_output_stopped(new_tokens, model.generation_config.eos_token_id)
443
  decoded = processor.batch_decode(
444
  new_tokens, skip_special_tokens=True, clean_up_tokenization_spaces=False,
445
  )[0]
 
509
  --port 8000
510
  ```
511
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
512
  ### OpenAI-compatible API
513
 
514
  Install the client where you send requests:
515
 
516
  ```bash
517
+ pip install -U openai pillow
518
  ```
519
 
520
  Set `enable_thinking` before constructing the shared request settings; rerun this setup when changing modes. Local media are encoded in the client so the server does not need access to their file paths.
521
 
522
  ```python
523
  import base64
524
+ import io
525
  from pathlib import Path
526
+ from PIL import Image, ImageOps
527
  from openai import OpenAI
528
 
529
  client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
 
541
  }
542
 
543
  def media_url(path, mime_type):
544
+ if mime_type.startswith("image/"):
545
+ with Image.open(path) as source:
546
+ image = ImageOps.exif_transpose(source).convert("RGBA")
547
+ background = Image.new("RGBA", image.size, (255, 255, 255, 255))
548
+ image = Image.alpha_composite(background, image).convert("RGB")
549
+ buffer = io.BytesIO()
550
+ image.save(buffer, format="PNG")
551
+ data = buffer.getvalue()
552
+ mime_type = "image/png"
553
+ else:
554
+ data = Path(path).read_bytes()
555
+ encoded = base64.b64encode(data).decode("ascii")
556
+ return f"data:{mime_type};base64,{encoded}"
557
 
558
  def show_response(response):
559
+ choice = response.choices[0]
560
+ message = choice.message
561
+ if choice.finish_reason == "length" or not (message.content or "").strip():
562
+ raise RuntimeError("No complete final answer. Review max_completion_tokens and generation settings.")
563
  reasoning = getattr(message, "reasoning", None) or getattr(message, "reasoning_content", None)
564
  if reasoning:
565
  print("Reasoning:\n" + reasoning)
 
654
  ]}]
655
  stream = client.chat.completions.create(messages=messages, stream=True, **request_kwargs)
656
  channel = None
657
+ finish_reason = None
658
+ answer_parts = []
659
  for chunk in stream:
660
  if not chunk.choices:
661
  continue
662
+ choice = chunk.choices[0]
663
+ finish_reason = choice.finish_reason or finish_reason
664
+ delta = choice.delta
665
+ if delta.content:
666
+ answer_parts.append(delta.content)
667
  reasoning = getattr(delta, "reasoning", None) or getattr(delta, "reasoning_content", None)
668
  for label, text in [("Reasoning", reasoning), ("Answer", delta.content)]:
669
  if not text:
 
673
  channel = label
674
  print(text, end="", flush=True)
675
  print()
676
+ if finish_reason == "length" or not "".join(answer_parts).strip():
677
+ raise RuntimeError("No complete final answer. Review max_completion_tokens and generation settings.")
678
  ```
679
 
680
  </details>
 
683
 
684
  ### Sampling Parameters
685
 
686
+ Use the following sampling profiles according to the mode and task.
687
 
688
  - **Instruct Mode — general tasks:** `temperature=0.7`, `top_p=0.8`, `top_k=20`, `min_p=0.0`, `presence_penalty=1.5`, `repetition_penalty=1.0`.
689
  - **Instruct Mode — structured outputs, such as attribute selection, product detection, and SKU matching:** `temperature=0.7`, `top_p=0.8`, `top_k=20`, `min_p=0.0`, `presence_penalty=0.0`, `repetition_penalty=1.0`.
 
696
  ### Mode and Output Settings
697
 
698
  - **Select the mode explicitly:** use `enable_thinking=False` for Instruct Mode and `enable_thinking=True` for Thinking Mode. In the serving API, pass this switch through `chat_template_kwargs` in `extra_body`.
699
+ - **Allow enough output tokens:** the Quick Start uses **4,096 tokens** for a compact example. Allow a larger budget for longer reasoning; in Thinking Mode, this budget covers both reasoning and the final answer. Set `max_new_tokens` in Transformers or `max_completion_tokens` in the serving API. The serving context limit must accommodate both the input and the generated output.
700
  - **Specify the output format:** for extraction, matching, and grounding, state the required fields, labels, and coordinate format. For multiple-choice tasks, request a clear final answer. In multi-turn conversations, append the assistant's final answer to the history.
701
 
702
  ## Citation