fount-vlm-nell-02 0.3.11__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fount_vlm_nell_02-0.3.11.dist-info/METADATA +418 -0
- fount_vlm_nell_02-0.3.11.dist-info/RECORD +258 -0
- fount_vlm_nell_02-0.3.11.dist-info/WHEEL +5 -0
- fount_vlm_nell_02-0.3.11.dist-info/entry_points.txt +5 -0
- fount_vlm_nell_02-0.3.11.dist-info/licenses/LICENSE +21 -0
- fount_vlm_nell_02-0.3.11.dist-info/top_level.txt +1 -0
- mlx_vlm/__init__.py +16 -0
- mlx_vlm/__main__.py +24 -0
- mlx_vlm/chat.py +234 -0
- mlx_vlm/chat_ui.py +508 -0
- mlx_vlm/convert.py +284 -0
- mlx_vlm/deprecation.py +52 -0
- mlx_vlm/evals/__init__.py +0 -0
- mlx_vlm/evals/math_vista.py +565 -0
- mlx_vlm/evals/mmmu.py +528 -0
- mlx_vlm/evals/mmstar.py +343 -0
- mlx_vlm/evals/ocrbench.py +453 -0
- mlx_vlm/evals/utils.py +37 -0
- mlx_vlm/generate.py +1457 -0
- mlx_vlm/lora.py +207 -0
- mlx_vlm/models/__init__.py +0 -0
- mlx_vlm/models/aya_vision/__init__.py +2 -0
- mlx_vlm/models/aya_vision/aya_vision.py +188 -0
- mlx_vlm/models/aya_vision/config.py +52 -0
- mlx_vlm/models/aya_vision/language.py +202 -0
- mlx_vlm/models/aya_vision/vision.py +340 -0
- mlx_vlm/models/base.py +356 -0
- mlx_vlm/models/cache.py +238 -0
- mlx_vlm/models/deepseek_vl_v2/__init__.py +2 -0
- mlx_vlm/models/deepseek_vl_v2/config.py +159 -0
- mlx_vlm/models/deepseek_vl_v2/conversation.py +264 -0
- mlx_vlm/models/deepseek_vl_v2/deepseek_vl_v2.py +418 -0
- mlx_vlm/models/deepseek_vl_v2/language.py +539 -0
- mlx_vlm/models/deepseek_vl_v2/processing_deepsek_vl_v2.py +536 -0
- mlx_vlm/models/deepseek_vl_v2/vision.py +322 -0
- mlx_vlm/models/deepseekocr/__init__.py +2 -0
- mlx_vlm/models/deepseekocr/config.py +173 -0
- mlx_vlm/models/deepseekocr/conversation.py +264 -0
- mlx_vlm/models/deepseekocr/deepseekocr.py +371 -0
- mlx_vlm/models/deepseekocr/language.py +547 -0
- mlx_vlm/models/deepseekocr/processing_deepseekocr.py +655 -0
- mlx_vlm/models/deepseekocr/sam.py +489 -0
- mlx_vlm/models/deepseekocr/vision.py +263 -0
- mlx_vlm/models/deepseekocr_2/__init__.py +12 -0
- mlx_vlm/models/deepseekocr_2/config.py +216 -0
- mlx_vlm/models/deepseekocr_2/deepseekocr_2.py +297 -0
- mlx_vlm/models/deepseekocr_2/processing_deepseekocr.py +624 -0
- mlx_vlm/models/deepseekocr_2/vision.py +439 -0
- mlx_vlm/models/ernie4_5_moe_vl/__init__.py +5 -0
- mlx_vlm/models/ernie4_5_moe_vl/config.py +139 -0
- mlx_vlm/models/ernie4_5_moe_vl/ernie4_5_moe_vl.py +337 -0
- mlx_vlm/models/ernie4_5_moe_vl/language.py +770 -0
- mlx_vlm/models/ernie4_5_moe_vl/processor.py +686 -0
- mlx_vlm/models/ernie4_5_moe_vl/vision.py +322 -0
- mlx_vlm/models/fastvlm/__init__.py +2 -0
- mlx_vlm/models/fastvlm/config.py +79 -0
- mlx_vlm/models/fastvlm/fastvlm.py +198 -0
- mlx_vlm/models/fastvlm/language.py +49 -0
- mlx_vlm/models/fastvlm/vision.py +692 -0
- mlx_vlm/models/florence2/__init__.py +2 -0
- mlx_vlm/models/florence2/config.py +84 -0
- mlx_vlm/models/florence2/florence2.py +383 -0
- mlx_vlm/models/florence2/language.py +452 -0
- mlx_vlm/models/florence2/processing_florence2.py +30 -0
- mlx_vlm/models/florence2/vision.py +552 -0
- mlx_vlm/models/gemma3/__init__.py +2 -0
- mlx_vlm/models/gemma3/config.py +52 -0
- mlx_vlm/models/gemma3/gemma3.py +194 -0
- mlx_vlm/models/gemma3/language.py +293 -0
- mlx_vlm/models/gemma3/vision.py +215 -0
- mlx_vlm/models/gemma3n/__init__.py +2 -0
- mlx_vlm/models/gemma3n/audio.py +1038 -0
- mlx_vlm/models/gemma3n/config.py +130 -0
- mlx_vlm/models/gemma3n/gemma3n.py +322 -0
- mlx_vlm/models/gemma3n/language.py +631 -0
- mlx_vlm/models/gemma3n/vision.py +994 -0
- mlx_vlm/models/glm4v/__init__.py +3 -0
- mlx_vlm/models/glm4v/config.py +79 -0
- mlx_vlm/models/glm4v/glm4v.py +188 -0
- mlx_vlm/models/glm4v/language.py +574 -0
- mlx_vlm/models/glm4v/processing.py +220 -0
- mlx_vlm/models/glm4v/vision.py +406 -0
- mlx_vlm/models/glm4v_moe/__init__.py +3 -0
- mlx_vlm/models/glm4v_moe/config.py +81 -0
- mlx_vlm/models/glm4v_moe/glm4v_moe.py +176 -0
- mlx_vlm/models/glm4v_moe/language.py +674 -0
- mlx_vlm/models/glm4v_moe/processing.py +229 -0
- mlx_vlm/models/glm4v_moe/vision.py +405 -0
- mlx_vlm/models/glm_ocr/__init__.py +3 -0
- mlx_vlm/models/glm_ocr/config.py +93 -0
- mlx_vlm/models/glm_ocr/glm_ocr.py +180 -0
- mlx_vlm/models/glm_ocr/language.py +585 -0
- mlx_vlm/models/glm_ocr/processing.py +208 -0
- mlx_vlm/models/glm_ocr/vision.py +342 -0
- mlx_vlm/models/hunyuan_vl/__init__.py +7 -0
- mlx_vlm/models/hunyuan_vl/config.py +136 -0
- mlx_vlm/models/hunyuan_vl/hunyuan_vl.py +181 -0
- mlx_vlm/models/hunyuan_vl/language.py +509 -0
- mlx_vlm/models/hunyuan_vl/processing_hunyuan_vl.py +607 -0
- mlx_vlm/models/hunyuan_vl/vision.py +322 -0
- mlx_vlm/models/idefics2/__init__.py +2 -0
- mlx_vlm/models/idefics2/config.py +65 -0
- mlx_vlm/models/idefics2/idefics2.py +321 -0
- mlx_vlm/models/idefics2/language.py +161 -0
- mlx_vlm/models/idefics2/vision.py +244 -0
- mlx_vlm/models/idefics3/__init__.py +4 -0
- mlx_vlm/models/idefics3/config.py +54 -0
- mlx_vlm/models/idefics3/idefics3.py +221 -0
- mlx_vlm/models/idefics3/language.py +157 -0
- mlx_vlm/models/idefics3/vision.py +265 -0
- mlx_vlm/models/internvl_chat/__init__.py +3 -0
- mlx_vlm/models/internvl_chat/config.py +89 -0
- mlx_vlm/models/internvl_chat/internvl_chat.py +115 -0
- mlx_vlm/models/internvl_chat/language.py +187 -0
- mlx_vlm/models/internvl_chat/processor.py +395 -0
- mlx_vlm/models/internvl_chat/vision.py +265 -0
- mlx_vlm/models/interpolate.py +183 -0
- mlx_vlm/models/jina_vlm/__init__.py +3 -0
- mlx_vlm/models/jina_vlm/config.py +142 -0
- mlx_vlm/models/jina_vlm/image_processor.py +430 -0
- mlx_vlm/models/jina_vlm/jina_vlm.py +280 -0
- mlx_vlm/models/jina_vlm/language.py +272 -0
- mlx_vlm/models/jina_vlm/processing_jinavlm.py +266 -0
- mlx_vlm/models/jina_vlm/vision.py +202 -0
- mlx_vlm/models/kernels.py +447 -0
- mlx_vlm/models/kimi_vl/__init__.py +4 -0
- mlx_vlm/models/kimi_vl/config.py +84 -0
- mlx_vlm/models/kimi_vl/kimi_vl.py +127 -0
- mlx_vlm/models/kimi_vl/language.py +460 -0
- mlx_vlm/models/kimi_vl/processing_kimi_vl.py +560 -0
- mlx_vlm/models/kimi_vl/vision.py +485 -0
- mlx_vlm/models/lfm2_vl/__init__.py +2 -0
- mlx_vlm/models/lfm2_vl/config.py +94 -0
- mlx_vlm/models/lfm2_vl/language.py +49 -0
- mlx_vlm/models/lfm2_vl/lfm2_vl.py +223 -0
- mlx_vlm/models/lfm2_vl/processing_lfm2_vl.py +320 -0
- mlx_vlm/models/lfm2_vl/vision.py +223 -0
- mlx_vlm/models/llama4/__init__.py +2 -0
- mlx_vlm/models/llama4/config.py +83 -0
- mlx_vlm/models/llama4/language.py +334 -0
- mlx_vlm/models/llama4/llama4.py +146 -0
- mlx_vlm/models/llama4/vision.py +526 -0
- mlx_vlm/models/llava/__init__.py +2 -0
- mlx_vlm/models/llava/config.py +61 -0
- mlx_vlm/models/llava/language.py +200 -0
- mlx_vlm/models/llava/llava.py +132 -0
- mlx_vlm/models/llava/vision.py +233 -0
- mlx_vlm/models/llava_bunny/__init__.py +2 -0
- mlx_vlm/models/llava_bunny/config.py +85 -0
- mlx_vlm/models/llava_bunny/language.py +194 -0
- mlx_vlm/models/llava_bunny/llava_bunny.py +217 -0
- mlx_vlm/models/llava_bunny/vision.py +278 -0
- mlx_vlm/models/llava_next/__init__.py +2 -0
- mlx_vlm/models/llava_next/config.py +60 -0
- mlx_vlm/models/llava_next/language.py +192 -0
- mlx_vlm/models/llava_next/llava_next.py +138 -0
- mlx_vlm/models/llava_next/vision.py +217 -0
- mlx_vlm/models/mistral3/__init__.py +2 -0
- mlx_vlm/models/mistral3/config.py +59 -0
- mlx_vlm/models/mistral3/language.py +269 -0
- mlx_vlm/models/mistral3/mistral3.py +383 -0
- mlx_vlm/models/mllama/__init__.py +4 -0
- mlx_vlm/models/mllama/config.py +74 -0
- mlx_vlm/models/mllama/language.py +377 -0
- mlx_vlm/models/mllama/mllama.py +210 -0
- mlx_vlm/models/mllama/vision.py +458 -0
- mlx_vlm/models/molmo/__init__.py +5 -0
- mlx_vlm/models/molmo/config.py +93 -0
- mlx_vlm/models/molmo/language.py +208 -0
- mlx_vlm/models/molmo/molmo.py +108 -0
- mlx_vlm/models/molmo/processing_molmo.py +763 -0
- mlx_vlm/models/molmo/vision.py +408 -0
- mlx_vlm/models/molmo2/__init__.py +6 -0
- mlx_vlm/models/molmo2/config.py +137 -0
- mlx_vlm/models/molmo2/language.py +206 -0
- mlx_vlm/models/molmo2/molmo2.py +330 -0
- mlx_vlm/models/molmo2/processing.py +773 -0
- mlx_vlm/models/molmo2/vision.py +286 -0
- mlx_vlm/models/moondream2/__init__.py +11 -0
- mlx_vlm/models/moondream2/config.py +92 -0
- mlx_vlm/models/moondream2/image_crops.py +269 -0
- mlx_vlm/models/moondream2/language.py +267 -0
- mlx_vlm/models/moondream2/moondream2.py +522 -0
- mlx_vlm/models/moondream2/processing_moondream.py +144 -0
- mlx_vlm/models/moondream2/vision.py +200 -0
- mlx_vlm/models/multi_modality/__init__.py +4 -0
- mlx_vlm/models/multi_modality/config.py +108 -0
- mlx_vlm/models/multi_modality/language.py +191 -0
- mlx_vlm/models/multi_modality/multi_modality.py +338 -0
- mlx_vlm/models/multi_modality/sam.py +543 -0
- mlx_vlm/models/multi_modality/vision.py +450 -0
- mlx_vlm/models/paddleocr_vl/__init__.py +3 -0
- mlx_vlm/models/paddleocr_vl/config.py +93 -0
- mlx_vlm/models/paddleocr_vl/language.py +522 -0
- mlx_vlm/models/paddleocr_vl/paddleocr_vl.py +207 -0
- mlx_vlm/models/paddleocr_vl/processing_paddleocr_vl.py +425 -0
- mlx_vlm/models/paddleocr_vl/vision.py +358 -0
- mlx_vlm/models/paligemma/__init__.py +4 -0
- mlx_vlm/models/paligemma/config.py +50 -0
- mlx_vlm/models/paligemma/language.py +253 -0
- mlx_vlm/models/paligemma/paligemma.py +140 -0
- mlx_vlm/models/paligemma/vision.py +218 -0
- mlx_vlm/models/phi3_v/__init__.py +5 -0
- mlx_vlm/models/phi3_v/config.py +55 -0
- mlx_vlm/models/phi3_v/language.py +2 -0
- mlx_vlm/models/phi3_v/phi3_v.py +239 -0
- mlx_vlm/models/phi3_v/processing_phi3_v.py +704 -0
- mlx_vlm/models/phi3_v/vision.py +294 -0
- mlx_vlm/models/pixtral/__init__.py +4 -0
- mlx_vlm/models/pixtral/config.py +69 -0
- mlx_vlm/models/pixtral/language.py +195 -0
- mlx_vlm/models/pixtral/pixtral.py +208 -0
- mlx_vlm/models/pixtral/vision.py +293 -0
- mlx_vlm/models/qwen2_5_vl/__init__.py +2 -0
- mlx_vlm/models/qwen2_5_vl/config.py +90 -0
- mlx_vlm/models/qwen2_5_vl/language.py +541 -0
- mlx_vlm/models/qwen2_5_vl/qwen2_5_vl.py +184 -0
- mlx_vlm/models/qwen2_5_vl/vision.py +414 -0
- mlx_vlm/models/qwen2_vl/__init__.py +2 -0
- mlx_vlm/models/qwen2_vl/config.py +86 -0
- mlx_vlm/models/qwen2_vl/language.py +539 -0
- mlx_vlm/models/qwen2_vl/qwen2_vl.py +180 -0
- mlx_vlm/models/qwen2_vl/vision.py +308 -0
- mlx_vlm/models/qwen3_omni_moe/__init__.py +29 -0
- mlx_vlm/models/qwen3_omni_moe/audio.py +317 -0
- mlx_vlm/models/qwen3_omni_moe/code2wav.py +542 -0
- mlx_vlm/models/qwen3_omni_moe/config.py +264 -0
- mlx_vlm/models/qwen3_omni_moe/language.py +622 -0
- mlx_vlm/models/qwen3_omni_moe/omni_utils.py +69 -0
- mlx_vlm/models/qwen3_omni_moe/qwen3_omni_moe.py +706 -0
- mlx_vlm/models/qwen3_omni_moe/talker.py +873 -0
- mlx_vlm/models/qwen3_omni_moe/thinker.py +366 -0
- mlx_vlm/models/qwen3_omni_moe/vision.py +419 -0
- mlx_vlm/models/qwen3_vl/__init__.py +2 -0
- mlx_vlm/models/qwen3_vl/config.py +103 -0
- mlx_vlm/models/qwen3_vl/language.py +596 -0
- mlx_vlm/models/qwen3_vl/qwen3_vl.py +166 -0
- mlx_vlm/models/qwen3_vl/vision.py +441 -0
- mlx_vlm/models/qwen3_vl_moe/__init__.py +2 -0
- mlx_vlm/models/qwen3_vl_moe/config.py +108 -0
- mlx_vlm/models/qwen3_vl_moe/language.py +656 -0
- mlx_vlm/models/qwen3_vl_moe/qwen3_vl_moe.py +184 -0
- mlx_vlm/models/qwen3_vl_moe/vision.py +442 -0
- mlx_vlm/models/smolvlm/__init__.py +4 -0
- mlx_vlm/models/smolvlm/config.py +59 -0
- mlx_vlm/models/smolvlm/smolvlm.py +60 -0
- mlx_vlm/prompt_utils.py +565 -0
- mlx_vlm/sample_utils.py +39 -0
- mlx_vlm/server.py +1107 -0
- mlx_vlm/smolvlm_video_generate.py +109 -0
- mlx_vlm/tokenizer_utils.py +371 -0
- mlx_vlm/trainer/__init__.py +9 -0
- mlx_vlm/trainer/lora.py +70 -0
- mlx_vlm/trainer/trainer.py +299 -0
- mlx_vlm/trainer/utils.py +160 -0
- mlx_vlm/utils.py +1339 -0
- mlx_vlm/version.py +1 -0
- mlx_vlm/video_generate.py +611 -0
|
@@ -0,0 +1,536 @@
|
|
|
1
|
+
"""
|
|
2
|
+
From https://github.com/deepseek-ai/DeepSeek-VL2
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Dict, List, Literal, Optional, Tuple
|
|
8
|
+
|
|
9
|
+
import mlx.core as mx
|
|
10
|
+
import numpy as np
|
|
11
|
+
from PIL import Image, ImageOps
|
|
12
|
+
from transformers import LlamaTokenizerFast
|
|
13
|
+
from transformers.processing_utils import ProcessorMixin
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def select_best_resolution(image_size, candidate_resolutions):
|
|
17
|
+
# used for cropping
|
|
18
|
+
original_width, original_height = image_size
|
|
19
|
+
best_fit = None
|
|
20
|
+
max_effective_resolution = 0
|
|
21
|
+
min_wasted_resolution = float("inf")
|
|
22
|
+
|
|
23
|
+
for width, height in candidate_resolutions:
|
|
24
|
+
scale = min(width / original_width, height / original_height)
|
|
25
|
+
downscaled_width, downscaled_height = int(original_width * scale), int(
|
|
26
|
+
original_height * scale
|
|
27
|
+
)
|
|
28
|
+
effective_resolution = min(
|
|
29
|
+
downscaled_width * downscaled_height, original_width * original_height
|
|
30
|
+
)
|
|
31
|
+
wasted_resolution = (width * height) - effective_resolution
|
|
32
|
+
|
|
33
|
+
if effective_resolution > max_effective_resolution or (
|
|
34
|
+
effective_resolution == max_effective_resolution
|
|
35
|
+
and wasted_resolution < min_wasted_resolution
|
|
36
|
+
):
|
|
37
|
+
max_effective_resolution = effective_resolution
|
|
38
|
+
min_wasted_resolution = wasted_resolution
|
|
39
|
+
best_fit = (width, height)
|
|
40
|
+
|
|
41
|
+
return best_fit
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class DictOutput(object):
|
|
45
|
+
def keys(self):
|
|
46
|
+
return self.__dict__.keys()
|
|
47
|
+
|
|
48
|
+
def __getitem__(self, item):
|
|
49
|
+
if isinstance(item, int):
|
|
50
|
+
return list(self.__dict__.values())[item]
|
|
51
|
+
if item not in self.__dict__:
|
|
52
|
+
raise KeyError(item)
|
|
53
|
+
return self.__dict__[item]
|
|
54
|
+
|
|
55
|
+
def __setitem__(self, key, value):
|
|
56
|
+
self.__dict__[key] = value
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass
|
|
60
|
+
class VLChatProcessorOutput(DictOutput):
|
|
61
|
+
sft_format: str
|
|
62
|
+
input_ids: mx.array
|
|
63
|
+
target_ids: mx.array
|
|
64
|
+
images: mx.array
|
|
65
|
+
images_seq_mask: mx.array
|
|
66
|
+
images_spatial_crop: mx.array
|
|
67
|
+
num_image_tokens: List[int]
|
|
68
|
+
|
|
69
|
+
def __len__(self):
|
|
70
|
+
return len(self.input_ids)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass
|
|
74
|
+
class BatchCollateOutput(DictOutput):
|
|
75
|
+
sft_format: List[str]
|
|
76
|
+
input_ids: mx.array
|
|
77
|
+
labels: mx.array
|
|
78
|
+
images: mx.array
|
|
79
|
+
attention_mask: mx.array
|
|
80
|
+
images_seq_mask: mx.array
|
|
81
|
+
images_spatial_crop: mx.array
|
|
82
|
+
seq_lens: List[int]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class ImageTransform:
|
|
86
|
+
def __init__(
|
|
87
|
+
self,
|
|
88
|
+
mean: Optional[Tuple[float, float, float]] = (0.5, 0.5, 0.5),
|
|
89
|
+
std: Optional[Tuple[float, float, float]] = (0.5, 0.5, 0.5),
|
|
90
|
+
normalize: bool = True,
|
|
91
|
+
):
|
|
92
|
+
self.mean = mean
|
|
93
|
+
self.std = std
|
|
94
|
+
self.normalize = normalize
|
|
95
|
+
|
|
96
|
+
def __call__(self, pil_img: Image.Image):
|
|
97
|
+
# Convert PIL image to numpy array and normalize
|
|
98
|
+
|
|
99
|
+
img = mx.array(np.array(pil_img)) / 255.0
|
|
100
|
+
|
|
101
|
+
# Transpose from HWC to CHW format
|
|
102
|
+
img = mx.transpose(img, [2, 0, 1])
|
|
103
|
+
|
|
104
|
+
if self.normalize:
|
|
105
|
+
mean = mx.array(self.mean).reshape(-1, 1, 1)
|
|
106
|
+
std = mx.array(self.std).reshape(-1, 1, 1)
|
|
107
|
+
img = (img - mean) / std
|
|
108
|
+
|
|
109
|
+
return img
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class DeepseekVLV2Processor(ProcessorMixin):
|
|
113
|
+
tokenizer_class = ("LlamaTokenizer", "LlamaTokenizerFast")
|
|
114
|
+
attributes = ["tokenizer"]
|
|
115
|
+
|
|
116
|
+
def __init__(
|
|
117
|
+
self,
|
|
118
|
+
tokenizer: LlamaTokenizerFast,
|
|
119
|
+
candidate_resolutions: Tuple[Tuple[int, int]],
|
|
120
|
+
patch_size: int,
|
|
121
|
+
downsample_ratio: int,
|
|
122
|
+
image_mean: Tuple[float, float, float] = (0.5, 0.5, 0.5),
|
|
123
|
+
image_std: Tuple[float, float, float] = (0.5, 0.5, 0.5),
|
|
124
|
+
normalize: bool = True,
|
|
125
|
+
image_token: str = "<image>",
|
|
126
|
+
pad_token: str = "<|▁pad▁|>",
|
|
127
|
+
add_special_token: bool = False,
|
|
128
|
+
sft_format: str = "deepseek",
|
|
129
|
+
mask_prompt: bool = True,
|
|
130
|
+
ignore_id: int = -100,
|
|
131
|
+
**kwargs,
|
|
132
|
+
):
|
|
133
|
+
self.candidate_resolutions = candidate_resolutions
|
|
134
|
+
self.image_size = candidate_resolutions[0][0]
|
|
135
|
+
self.patch_size = patch_size
|
|
136
|
+
self.image_mean = image_mean
|
|
137
|
+
self.image_std = image_std
|
|
138
|
+
self.normalize = normalize
|
|
139
|
+
self.downsample_ratio = downsample_ratio
|
|
140
|
+
|
|
141
|
+
self.image_transform = ImageTransform(
|
|
142
|
+
mean=image_mean, std=image_std, normalize=normalize
|
|
143
|
+
)
|
|
144
|
+
self.tokenizer = tokenizer
|
|
145
|
+
self.tokenizer.padding_side = "left"
|
|
146
|
+
|
|
147
|
+
# Add special tokens
|
|
148
|
+
if tokenizer.pad_token is None:
|
|
149
|
+
self.tokenizer.add_special_tokens({"pad_token": pad_token})
|
|
150
|
+
print(
|
|
151
|
+
f"Add pad token = ['{pad_token}'] to the tokenizer\n"
|
|
152
|
+
f"{pad_token}:{tokenizer.encode(pad_token, add_special_tokens=False)[0]}"
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
image_token_id = self.tokenizer.vocab.get(image_token)
|
|
156
|
+
if image_token_id is None:
|
|
157
|
+
special_tokens = [image_token]
|
|
158
|
+
special_tokens_dict = {"additional_special_tokens": special_tokens}
|
|
159
|
+
self.tokenizer.add_special_tokens(special_tokens_dict)
|
|
160
|
+
self.image_token_id = self.tokenizer.vocab.get(image_token)
|
|
161
|
+
print(
|
|
162
|
+
f"Add image token = ['{image_token}'] to the tokenizer\n"
|
|
163
|
+
f"{image_token}:{tokenizer.encode(image_token, add_special_tokens=False)[0]}"
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
# Add grounding-related tokens
|
|
167
|
+
special_tokens = ["<|ref|>", "<|/ref|>", "<|det|>", "<|/det|>", "<|grounding|>"]
|
|
168
|
+
special_tokens_dict = {"additional_special_tokens": special_tokens}
|
|
169
|
+
self.tokenizer.add_special_tokens(special_tokens_dict)
|
|
170
|
+
print("Added grounding-related tokens")
|
|
171
|
+
|
|
172
|
+
# Add chat tokens
|
|
173
|
+
special_tokens = ["<|User|>", "<|Assistant|>"]
|
|
174
|
+
special_tokens_dict = {"additional_special_tokens": special_tokens}
|
|
175
|
+
self.tokenizer.add_special_tokens(special_tokens_dict)
|
|
176
|
+
print("Added chat tokens")
|
|
177
|
+
|
|
178
|
+
self.image_token = image_token
|
|
179
|
+
self.pad_token = pad_token
|
|
180
|
+
self.add_special_token = add_special_token
|
|
181
|
+
self.sft_format = sft_format
|
|
182
|
+
self.mask_prompt = mask_prompt
|
|
183
|
+
self.ignore_id = ignore_id
|
|
184
|
+
super().__init__(tokenizer, **kwargs)
|
|
185
|
+
|
|
186
|
+
# Add chat template
|
|
187
|
+
self.chat_template = kwargs.pop("chat_template", self.default_chat_template)
|
|
188
|
+
|
|
189
|
+
@property
|
|
190
|
+
def default_chat_template(self):
|
|
191
|
+
return (
|
|
192
|
+
"{% for message in messages %}"
|
|
193
|
+
"{% if message['role'] == 'user' %}<|User|>:"
|
|
194
|
+
"{% elif message['role'] == 'assistant' %}<|Assistant|>{% endif %} "
|
|
195
|
+
"{{message['content']}}\n\n"
|
|
196
|
+
"{% endfor %}"
|
|
197
|
+
"{% if add_generation_prompt %}<|Assistant|>:{% endif %}"
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
@property
|
|
201
|
+
def bos_id(self):
|
|
202
|
+
return self.tokenizer.bos_token_id
|
|
203
|
+
|
|
204
|
+
@property
|
|
205
|
+
def eos_id(self):
|
|
206
|
+
return self.tokenizer.eos_token_id
|
|
207
|
+
|
|
208
|
+
@property
|
|
209
|
+
def pad_id(self):
|
|
210
|
+
return self.tokenizer.pad_token_id
|
|
211
|
+
|
|
212
|
+
def encode(self, text: str, bos: bool = True, eos: bool = False):
|
|
213
|
+
t = self.tokenizer.encode(text, add_special_tokens=False)
|
|
214
|
+
|
|
215
|
+
if bos:
|
|
216
|
+
t = [self.bos_id] + t
|
|
217
|
+
if eos:
|
|
218
|
+
t = t + [self.eos_id]
|
|
219
|
+
|
|
220
|
+
return t
|
|
221
|
+
|
|
222
|
+
def decode(self, t: List[int], **kwargs) -> str:
|
|
223
|
+
return self.tokenizer.decode(t, **kwargs)
|
|
224
|
+
|
|
225
|
+
def process_one(
|
|
226
|
+
self,
|
|
227
|
+
prompt: str = None,
|
|
228
|
+
conversations: List[Dict[str, str]] = None,
|
|
229
|
+
images: List[Image.Image] = None,
|
|
230
|
+
apply_sft_format: bool = False,
|
|
231
|
+
inference_mode: bool = True,
|
|
232
|
+
system_prompt: str = "",
|
|
233
|
+
**kwargs,
|
|
234
|
+
):
|
|
235
|
+
assert (
|
|
236
|
+
prompt is None or conversations is None
|
|
237
|
+
), "prompt and conversations cannot be used at the same time."
|
|
238
|
+
|
|
239
|
+
if apply_sft_format:
|
|
240
|
+
sft_format = self.format_prompts(
|
|
241
|
+
prompts=prompt, sft_format=self.sft_format, system_prompt=system_prompt
|
|
242
|
+
)
|
|
243
|
+
else:
|
|
244
|
+
sft_format = prompt
|
|
245
|
+
(
|
|
246
|
+
tokenized_str,
|
|
247
|
+
images_list,
|
|
248
|
+
images_seq_mask,
|
|
249
|
+
images_spatial_crop,
|
|
250
|
+
num_image_tokens,
|
|
251
|
+
) = self.tokenize_with_images(
|
|
252
|
+
sft_format, images, bos=True, eos=True, cropping=len(images) <= 2
|
|
253
|
+
)
|
|
254
|
+
masked_tokenized_str = []
|
|
255
|
+
for token_index in tokenized_str:
|
|
256
|
+
if token_index != self.image_token_id:
|
|
257
|
+
masked_tokenized_str.append(token_index)
|
|
258
|
+
else:
|
|
259
|
+
masked_tokenized_str.append(self.ignore_id)
|
|
260
|
+
|
|
261
|
+
input_ids = mx.array(tokenized_str)
|
|
262
|
+
target_ids = mx.array(masked_tokenized_str)
|
|
263
|
+
images_seq_mask = mx.array(images_seq_mask)
|
|
264
|
+
|
|
265
|
+
# Set ignored indices
|
|
266
|
+
target_ids = mx.where(
|
|
267
|
+
(input_ids < 0) | (input_ids == self.image_token_id),
|
|
268
|
+
self.ignore_id,
|
|
269
|
+
target_ids,
|
|
270
|
+
)
|
|
271
|
+
input_ids = mx.where(input_ids < 0, self.pad_id, input_ids)
|
|
272
|
+
|
|
273
|
+
if inference_mode:
|
|
274
|
+
input_ids = input_ids[:-1]
|
|
275
|
+
target_ids = target_ids[:-1]
|
|
276
|
+
images_seq_mask = images_seq_mask[:-1]
|
|
277
|
+
|
|
278
|
+
if len(images_list) == 0:
|
|
279
|
+
images = mx.zeros((1, 3, self.image_size, self.image_size))
|
|
280
|
+
images_spatial_crop = mx.zeros((1, 2))
|
|
281
|
+
else:
|
|
282
|
+
images = mx.stack(images_list)
|
|
283
|
+
images_spatial_crop = mx.array(images_spatial_crop)
|
|
284
|
+
|
|
285
|
+
return VLChatProcessorOutput(
|
|
286
|
+
sft_format=sft_format,
|
|
287
|
+
input_ids=input_ids,
|
|
288
|
+
target_ids=target_ids,
|
|
289
|
+
images=images,
|
|
290
|
+
images_seq_mask=images_seq_mask,
|
|
291
|
+
images_spatial_crop=images_spatial_crop,
|
|
292
|
+
num_image_tokens=num_image_tokens,
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
def pad_sequence(self, sequences, padding_value):
|
|
296
|
+
# Get max length of sequences
|
|
297
|
+
max_len = max(len(seq) for seq in sequences)
|
|
298
|
+
|
|
299
|
+
# Pad each sequence to max length
|
|
300
|
+
padded_seqs = []
|
|
301
|
+
for seq in sequences:
|
|
302
|
+
pad_length = max_len - len(seq)
|
|
303
|
+
if pad_length > 0:
|
|
304
|
+
padding = mx.full((pad_length,), padding_value)
|
|
305
|
+
padded_seq = mx.concatenate([seq, padding])
|
|
306
|
+
else:
|
|
307
|
+
padded_seq = seq
|
|
308
|
+
padded_seqs.append(padded_seq)
|
|
309
|
+
|
|
310
|
+
return mx.stack(padded_seqs)
|
|
311
|
+
|
|
312
|
+
def tokenize_with_images(
|
|
313
|
+
self,
|
|
314
|
+
conversation: str,
|
|
315
|
+
images: List[Image.Image],
|
|
316
|
+
bos: bool = True,
|
|
317
|
+
eos: bool = True,
|
|
318
|
+
cropping: bool = True,
|
|
319
|
+
):
|
|
320
|
+
"""Tokenize text with <image> tags."""
|
|
321
|
+
assert conversation.count(self.image_token) == len(images)
|
|
322
|
+
text_splits = conversation.split(self.image_token)
|
|
323
|
+
images_list, images_seq_mask, images_spatial_crop = [], [], []
|
|
324
|
+
num_image_tokens = []
|
|
325
|
+
tokenized_str = []
|
|
326
|
+
for text_sep, image in zip(text_splits, images):
|
|
327
|
+
"""encode text_sep"""
|
|
328
|
+
tokenized_sep = self.encode(text_sep, bos=False, eos=False)
|
|
329
|
+
tokenized_str += tokenized_sep
|
|
330
|
+
images_seq_mask += [False] * len(tokenized_sep)
|
|
331
|
+
|
|
332
|
+
"""select best resolution for anyres"""
|
|
333
|
+
if cropping:
|
|
334
|
+
best_width, best_height = select_best_resolution(
|
|
335
|
+
image.size, self.candidate_resolutions
|
|
336
|
+
)
|
|
337
|
+
else:
|
|
338
|
+
best_width, best_height = self.image_size, self.image_size
|
|
339
|
+
|
|
340
|
+
"""process the global view"""
|
|
341
|
+
global_view = ImageOps.pad(
|
|
342
|
+
image,
|
|
343
|
+
(self.image_size, self.image_size),
|
|
344
|
+
color=tuple(int(x * 255) for x in self.image_transform.mean),
|
|
345
|
+
)
|
|
346
|
+
images_list.append(self.image_transform(global_view))
|
|
347
|
+
|
|
348
|
+
"""process the local views"""
|
|
349
|
+
local_view = ImageOps.pad(
|
|
350
|
+
image,
|
|
351
|
+
(best_width, best_height),
|
|
352
|
+
color=tuple(int(x * 255) for x in self.image_transform.mean),
|
|
353
|
+
)
|
|
354
|
+
for i in range(0, best_height, self.image_size):
|
|
355
|
+
for j in range(0, best_width, self.image_size):
|
|
356
|
+
images_list.append(
|
|
357
|
+
self.image_transform(
|
|
358
|
+
local_view.crop(
|
|
359
|
+
(j, i, j + self.image_size, i + self.image_size)
|
|
360
|
+
)
|
|
361
|
+
)
|
|
362
|
+
)
|
|
363
|
+
|
|
364
|
+
"""record height / width crop num"""
|
|
365
|
+
num_width_tiles, num_height_tiles = (
|
|
366
|
+
best_width // self.image_size,
|
|
367
|
+
best_height // self.image_size,
|
|
368
|
+
)
|
|
369
|
+
images_spatial_crop.append([num_width_tiles, num_height_tiles])
|
|
370
|
+
|
|
371
|
+
"""add image tokens"""
|
|
372
|
+
h = w = math.ceil(
|
|
373
|
+
(self.image_size // self.patch_size) / self.downsample_ratio
|
|
374
|
+
)
|
|
375
|
+
# global views tokens h * (w + 1), 1 is for line seperator
|
|
376
|
+
tokenized_image = [self.image_token_id] * h * (w + 1)
|
|
377
|
+
# add a seperator between global and local views
|
|
378
|
+
tokenized_image += [self.image_token_id]
|
|
379
|
+
# local views tokens, (num_height_tiles * h) * (num_width_tiles * w + 1)
|
|
380
|
+
tokenized_image += (
|
|
381
|
+
[self.image_token_id]
|
|
382
|
+
* (num_height_tiles * h)
|
|
383
|
+
* (num_width_tiles * w + 1)
|
|
384
|
+
)
|
|
385
|
+
|
|
386
|
+
tokenized_str += tokenized_image
|
|
387
|
+
images_seq_mask += [True] * len(tokenized_image)
|
|
388
|
+
num_image_tokens.append(len(tokenized_image))
|
|
389
|
+
|
|
390
|
+
"""process the last text split"""
|
|
391
|
+
tokenized_sep = self.encode(text_splits[-1], bos=False, eos=False)
|
|
392
|
+
tokenized_str += tokenized_sep
|
|
393
|
+
images_seq_mask += [False] * len(tokenized_sep)
|
|
394
|
+
|
|
395
|
+
"""add the bos and eos tokens"""
|
|
396
|
+
if bos:
|
|
397
|
+
tokenized_str = [self.bos_id] + tokenized_str
|
|
398
|
+
images_seq_mask = [False] + images_seq_mask
|
|
399
|
+
if eos:
|
|
400
|
+
tokenized_str = tokenized_str + [self.eos_id]
|
|
401
|
+
images_seq_mask = images_seq_mask + [False]
|
|
402
|
+
|
|
403
|
+
assert len(tokenized_str) == len(
|
|
404
|
+
images_seq_mask
|
|
405
|
+
), f"tokenize_with_images func: tokenized_str's length {len(tokenized_str)} is not equal to imags_seq_mask's length {len(images_seq_mask)}"
|
|
406
|
+
|
|
407
|
+
return (
|
|
408
|
+
tokenized_str,
|
|
409
|
+
images_list,
|
|
410
|
+
images_seq_mask,
|
|
411
|
+
images_spatial_crop,
|
|
412
|
+
num_image_tokens,
|
|
413
|
+
)
|
|
414
|
+
|
|
415
|
+
def batchify(
|
|
416
|
+
self,
|
|
417
|
+
sample_list: List[VLChatProcessorOutput],
|
|
418
|
+
padding: Literal["left", "right"] = "left",
|
|
419
|
+
) -> BatchCollateOutput:
|
|
420
|
+
batched_sft_format = [sample.sft_format for sample in sample_list]
|
|
421
|
+
batched_input_ids = [sample.input_ids for sample in sample_list]
|
|
422
|
+
batched_labels = [sample.target_ids for sample in sample_list]
|
|
423
|
+
batched_images_seq_mask = [sample.images_seq_mask for sample in sample_list]
|
|
424
|
+
seq_lens = [len(sample) for sample in sample_list]
|
|
425
|
+
|
|
426
|
+
# Padding
|
|
427
|
+
if padding == "left":
|
|
428
|
+
# MLX implementation of padding
|
|
429
|
+
max_len = max(len(ids) for ids in batched_input_ids)
|
|
430
|
+
|
|
431
|
+
def pad_left(sequence, pad_val):
|
|
432
|
+
pad_len = max_len - len(sequence)
|
|
433
|
+
if pad_len > 0:
|
|
434
|
+
padding = mx.full((pad_len,), pad_val)
|
|
435
|
+
return mx.concatenate([padding, sequence])
|
|
436
|
+
return sequence
|
|
437
|
+
|
|
438
|
+
batched_input_ids = mx.stack(
|
|
439
|
+
[pad_left(ids, self.pad_id) for ids in batched_input_ids]
|
|
440
|
+
)
|
|
441
|
+
batched_labels = mx.stack(
|
|
442
|
+
[pad_left(ids, self.ignore_id) for ids in batched_labels]
|
|
443
|
+
)
|
|
444
|
+
batched_images_seq_mask = mx.stack(
|
|
445
|
+
[pad_left(mask, False) for mask in batched_images_seq_mask]
|
|
446
|
+
)
|
|
447
|
+
batched_attention_mask = batched_input_ids != self.pad_id
|
|
448
|
+
|
|
449
|
+
else:
|
|
450
|
+
batched_input_ids = self.pad_sequence(batched_input_ids, self.pad_id)
|
|
451
|
+
batched_labels = self.pad_sequence(batched_labels, self.ignore_id)
|
|
452
|
+
batched_images_seq_mask = self.pad_sequence(batched_images_seq_mask, False)
|
|
453
|
+
batched_attention_mask = batched_input_ids != self.pad_id
|
|
454
|
+
|
|
455
|
+
# Padding images
|
|
456
|
+
max_n_patches = max(sample.images.shape[0] for sample in sample_list)
|
|
457
|
+
batched_images = []
|
|
458
|
+
for sample in sample_list:
|
|
459
|
+
images = sample.images
|
|
460
|
+
n_pads = max_n_patches - images.shape[0]
|
|
461
|
+
if n_pads > 0:
|
|
462
|
+
pad_shape = (n_pads,) + images.shape[1:]
|
|
463
|
+
pad_images = mx.zeros(pad_shape)
|
|
464
|
+
images = mx.concatenate([images, pad_images])
|
|
465
|
+
batched_images.append(images)
|
|
466
|
+
batched_images = mx.stack(batched_images)
|
|
467
|
+
|
|
468
|
+
# Padding spatial crop info
|
|
469
|
+
max_n_images = max(
|
|
470
|
+
sample.images_spatial_crop.shape[0] for sample in sample_list
|
|
471
|
+
)
|
|
472
|
+
batched_images_spatial_crop = []
|
|
473
|
+
for sample in sample_list:
|
|
474
|
+
spatial_crop = sample.images_spatial_crop
|
|
475
|
+
n_pads = max_n_images - spatial_crop.shape[0]
|
|
476
|
+
if n_pads > 0:
|
|
477
|
+
pad_spatial = mx.zeros((n_pads, 2))
|
|
478
|
+
spatial_crop = mx.concatenate([spatial_crop, pad_spatial])
|
|
479
|
+
batched_images_spatial_crop.append(spatial_crop)
|
|
480
|
+
batched_images_spatial_crop = mx.stack(batched_images_spatial_crop)
|
|
481
|
+
|
|
482
|
+
return {
|
|
483
|
+
"input_ids": batched_input_ids,
|
|
484
|
+
"attention_mask": batched_attention_mask,
|
|
485
|
+
"labels": batched_labels,
|
|
486
|
+
"images": batched_images,
|
|
487
|
+
"images_seq_mask": batched_images_seq_mask,
|
|
488
|
+
"images_spatial_crop": batched_images_spatial_crop,
|
|
489
|
+
"sft_format": batched_sft_format,
|
|
490
|
+
"seq_lens": seq_lens,
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
def __call__(
|
|
494
|
+
self,
|
|
495
|
+
*,
|
|
496
|
+
text: str = None,
|
|
497
|
+
images: List[Image.Image] = None,
|
|
498
|
+
apply_sft_format: bool = False,
|
|
499
|
+
force_batchify: bool = True,
|
|
500
|
+
inference_mode: bool = True,
|
|
501
|
+
system_prompt: str = "",
|
|
502
|
+
**kwargs,
|
|
503
|
+
):
|
|
504
|
+
"""
|
|
505
|
+
|
|
506
|
+
Args:
|
|
507
|
+
prompt (str): the formatted prompt;
|
|
508
|
+
conversations (List[Dict]): conversations with a list of messages;
|
|
509
|
+
images (List[ImageType]): the list of images;
|
|
510
|
+
apply_sft_format (bool): if prompt is not None, then apply the SFT format to prompt;
|
|
511
|
+
if conversations is not None, then it will always apply the SFT format to conversations;
|
|
512
|
+
force_batchify (bool): force batchify the inputs;
|
|
513
|
+
inference_mode (bool): if True, then remove the last eos token;
|
|
514
|
+
system_prompt (str): the system prompt;
|
|
515
|
+
**kwargs:
|
|
516
|
+
|
|
517
|
+
Returns:
|
|
518
|
+
outputs (BaseProcessorOutput): the output of the processor,
|
|
519
|
+
- input_ids (torch.LongTensor): [N + image tokens]
|
|
520
|
+
- images (torch.FloatTensor): [n_images, 3, H, W]
|
|
521
|
+
- image_id (int): the id of the image token
|
|
522
|
+
- num_image_tokens (List[int]): the number of image tokens
|
|
523
|
+
"""
|
|
524
|
+
|
|
525
|
+
prepare = self.process_one(
|
|
526
|
+
prompt=text,
|
|
527
|
+
images=images,
|
|
528
|
+
apply_sft_format=apply_sft_format,
|
|
529
|
+
inference_mode=inference_mode,
|
|
530
|
+
system_prompt=system_prompt,
|
|
531
|
+
)
|
|
532
|
+
|
|
533
|
+
if force_batchify:
|
|
534
|
+
prepare = self.batchify([prepare])
|
|
535
|
+
|
|
536
|
+
return prepare
|