Views
No views yet
MLLMSeg model, a novel framework for Referring Expression Segmentation (RES) and Generalized Referring Expression Segmentation (GRES), presented in the paper Unlocking the Potential of MLLMs in Referring Expression Segmentation via a Light-weight Mask Decoder.
MLLMSeg model with the transformers library. The model takes an image and a referring expression as input and outputs a segmentation mask or coordinates. Our models accept images of any size as input. The model outputs are normalized to relative coordinates within a 0-1000 range (either a center point or a bounding box defined by top-left and bottom-right coordinates). For visualization, remember to convert these relative coordinates back to the original image dimensions.1conda create -n mllmseg python==3.10.18 -y
2conda activate mllmseg
3pip install torch==2.5.1 torchvision==0.20.1 --index-url https://download.pytorch.org/whl/cu118
4pip install -r requirements.txt
5pip install flash-attn==2.3.6 --no-build-isolation # Note: need gpu to installMLLMSeg_InternVL2_5_8B_RES model as an example.1import torch
2import torchvision.transforms as T
3from PIL import Image
4from torchvision.transforms.functional import InterpolationMode
5from transformers import AutoModel, AutoTokenizer
6import requests
7from io import BytesIO
8
9# --- Helper functions for image preprocessing (from original GitHub repo) ---
10IMAGENET_MEAN = (0.485, 0.456, 0.406)
11IMAGENET_STD = (0.229, 0.224, 0.225)
12
13def build_transform(input_size):
14 MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
15 transform = T.Compose([
16 T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
17 T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
18 T.ToTensor(),
19 T.Normalize(mean=MEAN, std=STD)
20 ])
21 return transform
22
23def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
24 best_ratio_diff = float('inf')
25 best_ratio = (1, 1)
26 area = width * height
27 for ratio in target_ratios:
28 target_aspect_ratio = ratio[0] / ratio[1]
29 ratio_diff = abs(aspect_ratio - target_aspect_ratio)
30 if ratio_diff < best_ratio_diff:
31 best_ratio_diff = ratio_diff
32 best_ratio = ratio
33 elif ratio_diff == best_ratio_diff:
34 if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
35 best_ratio = ratio
36 return best_ratio
37
38def dynamic_preprocess(image, min_num=1, max_num=6, image_size=448, use_thumbnail=True):
39 orig_width, orig_height = image.size
40 aspect_ratio = orig_width / orig_height
41
42 target_ratios = set(
43 (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
44 i * j <= max_num and i * j >= min_num)
45 target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
46
47 target_aspect_ratio = find_closest_aspect_ratio(
48 aspect_ratio, target_ratios, orig_width, orig_height, image_size)
49
50 target_width = image_size * target_aspect_ratio[0]
51 target_height = image_size * target_aspect_ratio[1]
52 blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
53
54 resized_img = image.resize((target_width, target_height))
55 processed_images = []
56 for i in range(blocks):
57 box = (
58 (i % (target_width // image_size)) * image_size,
59 (i // (target_width // image_size)) * image_size,
60 ((i % (target_width // image_size)) + 1) * image_size,
61 ((i // (target_width // image_size)) + 1) * image_size
62 )
63 split_img = resized_img.crop(box)
64 processed_images.append(split_img)
65 assert len(processed_images) == blocks
66 if use_thumbnail and len(processed_images) != 1:
67 thumbnail_img = image.resize((image_size, image_size))
68 processed_images.append(thumbnail_img)
69 return processed_images
70
71def load_image(image_file_or_url, input_size=448, max_num=6):
72 if isinstance(image_file_or_url, str) and image_file_or_url.startswith("http"):
73 response = requests.get(image_file_or_url, stream=True)
74 image = Image.open(BytesIO(response.content)).convert('RGB')
75 else:
76 image = Image.open(image_file_or_url).convert('RGB')
77
78 transform = build_transform(input_size=input_size)
79 images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
80 pixel_values = [transform(image) for image in images]
81 pixel_values = torch.stack(pixel_values)
82 return pixel_values
83# --- End of helper functions ---
84
85# Load model and tokenizer
86model_id = "jcwang0602/MLLMSeg_InternVL2_5_8B_RES"
87model = AutoModel.from_pretrained(
88 model_id,
89 torch_dtype=torch.bfloat16,
90 low_cpu_mem_usage=True,
91 trust_remote_code=True
92).eval().cuda()
93tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True, use_fast=False)
94
95# Example image and question
96# Using an example image from the MLLMSeg repository for demonstration
97image_url = "https://huggingface.co/jcwang0602/MLLMSeg_InternVL2_5_8B_RES/resolve/main/assets/res_example.png"
98question = "Please give me the segmentation mask of the dog (with [SEG])."
99
100# Preprocess image
101pixel_values = load_image(image_url, max_num=6).to(torch.bfloat16).cuda()
102generation_config = dict(max_new_tokens=1024, do_sample=True)
103
104# Generate response
105response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
106print(f'User: {question}
107Assistant: {response}')
108
109# The output `response` will contain the segmentation information (e.g., coordinates or SEG token based output).
110# You would then need to parse this string to extract the mask or coordinates for visualization.| Base Model | RES Model | GRES Model |
|---|---|---|
| InternVL2_5_1B | MLLMSeg_InternVL2_5_1B_RES | - |
| InternVL2_5_2B | MLLMSeg_InternVL2_5_2B_RES | - |
| InternVL2_5_4B | MLLMSeg_InternVL2_5_4B_RES | - |
| InternVL2_5_8B | MLLMSeg_InternVL2_5_8B_RES | MLLMSeg_InternVL2_5_8B_GRES |






1@misc{wang2025unlockingpotentialmllmsreferring,
2 title={Unlocking the Potential of MLLMs in Referring Expression Segmentation via a Light-weight Mask Decoder},
3 author={Jingchao Wang and Zhijian Wu and Dingjiang Huang and Yefeng Zheng and Hong Wang},
4 year={2025},
5 eprint={2508.04107},
6 archivePrefix={arXiv},
7 primaryClass={cs.CV},
8 url={https://arxiv.org/abs/2508.04107},
9}