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.
Files changed (258) hide show
  1. fount_vlm_nell_02-0.3.11.dist-info/METADATA +418 -0
  2. fount_vlm_nell_02-0.3.11.dist-info/RECORD +258 -0
  3. fount_vlm_nell_02-0.3.11.dist-info/WHEEL +5 -0
  4. fount_vlm_nell_02-0.3.11.dist-info/entry_points.txt +5 -0
  5. fount_vlm_nell_02-0.3.11.dist-info/licenses/LICENSE +21 -0
  6. fount_vlm_nell_02-0.3.11.dist-info/top_level.txt +1 -0
  7. mlx_vlm/__init__.py +16 -0
  8. mlx_vlm/__main__.py +24 -0
  9. mlx_vlm/chat.py +234 -0
  10. mlx_vlm/chat_ui.py +508 -0
  11. mlx_vlm/convert.py +284 -0
  12. mlx_vlm/deprecation.py +52 -0
  13. mlx_vlm/evals/__init__.py +0 -0
  14. mlx_vlm/evals/math_vista.py +565 -0
  15. mlx_vlm/evals/mmmu.py +528 -0
  16. mlx_vlm/evals/mmstar.py +343 -0
  17. mlx_vlm/evals/ocrbench.py +453 -0
  18. mlx_vlm/evals/utils.py +37 -0
  19. mlx_vlm/generate.py +1457 -0
  20. mlx_vlm/lora.py +207 -0
  21. mlx_vlm/models/__init__.py +0 -0
  22. mlx_vlm/models/aya_vision/__init__.py +2 -0
  23. mlx_vlm/models/aya_vision/aya_vision.py +188 -0
  24. mlx_vlm/models/aya_vision/config.py +52 -0
  25. mlx_vlm/models/aya_vision/language.py +202 -0
  26. mlx_vlm/models/aya_vision/vision.py +340 -0
  27. mlx_vlm/models/base.py +356 -0
  28. mlx_vlm/models/cache.py +238 -0
  29. mlx_vlm/models/deepseek_vl_v2/__init__.py +2 -0
  30. mlx_vlm/models/deepseek_vl_v2/config.py +159 -0
  31. mlx_vlm/models/deepseek_vl_v2/conversation.py +264 -0
  32. mlx_vlm/models/deepseek_vl_v2/deepseek_vl_v2.py +418 -0
  33. mlx_vlm/models/deepseek_vl_v2/language.py +539 -0
  34. mlx_vlm/models/deepseek_vl_v2/processing_deepsek_vl_v2.py +536 -0
  35. mlx_vlm/models/deepseek_vl_v2/vision.py +322 -0
  36. mlx_vlm/models/deepseekocr/__init__.py +2 -0
  37. mlx_vlm/models/deepseekocr/config.py +173 -0
  38. mlx_vlm/models/deepseekocr/conversation.py +264 -0
  39. mlx_vlm/models/deepseekocr/deepseekocr.py +371 -0
  40. mlx_vlm/models/deepseekocr/language.py +547 -0
  41. mlx_vlm/models/deepseekocr/processing_deepseekocr.py +655 -0
  42. mlx_vlm/models/deepseekocr/sam.py +489 -0
  43. mlx_vlm/models/deepseekocr/vision.py +263 -0
  44. mlx_vlm/models/deepseekocr_2/__init__.py +12 -0
  45. mlx_vlm/models/deepseekocr_2/config.py +216 -0
  46. mlx_vlm/models/deepseekocr_2/deepseekocr_2.py +297 -0
  47. mlx_vlm/models/deepseekocr_2/processing_deepseekocr.py +624 -0
  48. mlx_vlm/models/deepseekocr_2/vision.py +439 -0
  49. mlx_vlm/models/ernie4_5_moe_vl/__init__.py +5 -0
  50. mlx_vlm/models/ernie4_5_moe_vl/config.py +139 -0
  51. mlx_vlm/models/ernie4_5_moe_vl/ernie4_5_moe_vl.py +337 -0
  52. mlx_vlm/models/ernie4_5_moe_vl/language.py +770 -0
  53. mlx_vlm/models/ernie4_5_moe_vl/processor.py +686 -0
  54. mlx_vlm/models/ernie4_5_moe_vl/vision.py +322 -0
  55. mlx_vlm/models/fastvlm/__init__.py +2 -0
  56. mlx_vlm/models/fastvlm/config.py +79 -0
  57. mlx_vlm/models/fastvlm/fastvlm.py +198 -0
  58. mlx_vlm/models/fastvlm/language.py +49 -0
  59. mlx_vlm/models/fastvlm/vision.py +692 -0
  60. mlx_vlm/models/florence2/__init__.py +2 -0
  61. mlx_vlm/models/florence2/config.py +84 -0
  62. mlx_vlm/models/florence2/florence2.py +383 -0
  63. mlx_vlm/models/florence2/language.py +452 -0
  64. mlx_vlm/models/florence2/processing_florence2.py +30 -0
  65. mlx_vlm/models/florence2/vision.py +552 -0
  66. mlx_vlm/models/gemma3/__init__.py +2 -0
  67. mlx_vlm/models/gemma3/config.py +52 -0
  68. mlx_vlm/models/gemma3/gemma3.py +194 -0
  69. mlx_vlm/models/gemma3/language.py +293 -0
  70. mlx_vlm/models/gemma3/vision.py +215 -0
  71. mlx_vlm/models/gemma3n/__init__.py +2 -0
  72. mlx_vlm/models/gemma3n/audio.py +1038 -0
  73. mlx_vlm/models/gemma3n/config.py +130 -0
  74. mlx_vlm/models/gemma3n/gemma3n.py +322 -0
  75. mlx_vlm/models/gemma3n/language.py +631 -0
  76. mlx_vlm/models/gemma3n/vision.py +994 -0
  77. mlx_vlm/models/glm4v/__init__.py +3 -0
  78. mlx_vlm/models/glm4v/config.py +79 -0
  79. mlx_vlm/models/glm4v/glm4v.py +188 -0
  80. mlx_vlm/models/glm4v/language.py +574 -0
  81. mlx_vlm/models/glm4v/processing.py +220 -0
  82. mlx_vlm/models/glm4v/vision.py +406 -0
  83. mlx_vlm/models/glm4v_moe/__init__.py +3 -0
  84. mlx_vlm/models/glm4v_moe/config.py +81 -0
  85. mlx_vlm/models/glm4v_moe/glm4v_moe.py +176 -0
  86. mlx_vlm/models/glm4v_moe/language.py +674 -0
  87. mlx_vlm/models/glm4v_moe/processing.py +229 -0
  88. mlx_vlm/models/glm4v_moe/vision.py +405 -0
  89. mlx_vlm/models/glm_ocr/__init__.py +3 -0
  90. mlx_vlm/models/glm_ocr/config.py +93 -0
  91. mlx_vlm/models/glm_ocr/glm_ocr.py +180 -0
  92. mlx_vlm/models/glm_ocr/language.py +585 -0
  93. mlx_vlm/models/glm_ocr/processing.py +208 -0
  94. mlx_vlm/models/glm_ocr/vision.py +342 -0
  95. mlx_vlm/models/hunyuan_vl/__init__.py +7 -0
  96. mlx_vlm/models/hunyuan_vl/config.py +136 -0
  97. mlx_vlm/models/hunyuan_vl/hunyuan_vl.py +181 -0
  98. mlx_vlm/models/hunyuan_vl/language.py +509 -0
  99. mlx_vlm/models/hunyuan_vl/processing_hunyuan_vl.py +607 -0
  100. mlx_vlm/models/hunyuan_vl/vision.py +322 -0
  101. mlx_vlm/models/idefics2/__init__.py +2 -0
  102. mlx_vlm/models/idefics2/config.py +65 -0
  103. mlx_vlm/models/idefics2/idefics2.py +321 -0
  104. mlx_vlm/models/idefics2/language.py +161 -0
  105. mlx_vlm/models/idefics2/vision.py +244 -0
  106. mlx_vlm/models/idefics3/__init__.py +4 -0
  107. mlx_vlm/models/idefics3/config.py +54 -0
  108. mlx_vlm/models/idefics3/idefics3.py +221 -0
  109. mlx_vlm/models/idefics3/language.py +157 -0
  110. mlx_vlm/models/idefics3/vision.py +265 -0
  111. mlx_vlm/models/internvl_chat/__init__.py +3 -0
  112. mlx_vlm/models/internvl_chat/config.py +89 -0
  113. mlx_vlm/models/internvl_chat/internvl_chat.py +115 -0
  114. mlx_vlm/models/internvl_chat/language.py +187 -0
  115. mlx_vlm/models/internvl_chat/processor.py +395 -0
  116. mlx_vlm/models/internvl_chat/vision.py +265 -0
  117. mlx_vlm/models/interpolate.py +183 -0
  118. mlx_vlm/models/jina_vlm/__init__.py +3 -0
  119. mlx_vlm/models/jina_vlm/config.py +142 -0
  120. mlx_vlm/models/jina_vlm/image_processor.py +430 -0
  121. mlx_vlm/models/jina_vlm/jina_vlm.py +280 -0
  122. mlx_vlm/models/jina_vlm/language.py +272 -0
  123. mlx_vlm/models/jina_vlm/processing_jinavlm.py +266 -0
  124. mlx_vlm/models/jina_vlm/vision.py +202 -0
  125. mlx_vlm/models/kernels.py +447 -0
  126. mlx_vlm/models/kimi_vl/__init__.py +4 -0
  127. mlx_vlm/models/kimi_vl/config.py +84 -0
  128. mlx_vlm/models/kimi_vl/kimi_vl.py +127 -0
  129. mlx_vlm/models/kimi_vl/language.py +460 -0
  130. mlx_vlm/models/kimi_vl/processing_kimi_vl.py +560 -0
  131. mlx_vlm/models/kimi_vl/vision.py +485 -0
  132. mlx_vlm/models/lfm2_vl/__init__.py +2 -0
  133. mlx_vlm/models/lfm2_vl/config.py +94 -0
  134. mlx_vlm/models/lfm2_vl/language.py +49 -0
  135. mlx_vlm/models/lfm2_vl/lfm2_vl.py +223 -0
  136. mlx_vlm/models/lfm2_vl/processing_lfm2_vl.py +320 -0
  137. mlx_vlm/models/lfm2_vl/vision.py +223 -0
  138. mlx_vlm/models/llama4/__init__.py +2 -0
  139. mlx_vlm/models/llama4/config.py +83 -0
  140. mlx_vlm/models/llama4/language.py +334 -0
  141. mlx_vlm/models/llama4/llama4.py +146 -0
  142. mlx_vlm/models/llama4/vision.py +526 -0
  143. mlx_vlm/models/llava/__init__.py +2 -0
  144. mlx_vlm/models/llava/config.py +61 -0
  145. mlx_vlm/models/llava/language.py +200 -0
  146. mlx_vlm/models/llava/llava.py +132 -0
  147. mlx_vlm/models/llava/vision.py +233 -0
  148. mlx_vlm/models/llava_bunny/__init__.py +2 -0
  149. mlx_vlm/models/llava_bunny/config.py +85 -0
  150. mlx_vlm/models/llava_bunny/language.py +194 -0
  151. mlx_vlm/models/llava_bunny/llava_bunny.py +217 -0
  152. mlx_vlm/models/llava_bunny/vision.py +278 -0
  153. mlx_vlm/models/llava_next/__init__.py +2 -0
  154. mlx_vlm/models/llava_next/config.py +60 -0
  155. mlx_vlm/models/llava_next/language.py +192 -0
  156. mlx_vlm/models/llava_next/llava_next.py +138 -0
  157. mlx_vlm/models/llava_next/vision.py +217 -0
  158. mlx_vlm/models/mistral3/__init__.py +2 -0
  159. mlx_vlm/models/mistral3/config.py +59 -0
  160. mlx_vlm/models/mistral3/language.py +269 -0
  161. mlx_vlm/models/mistral3/mistral3.py +383 -0
  162. mlx_vlm/models/mllama/__init__.py +4 -0
  163. mlx_vlm/models/mllama/config.py +74 -0
  164. mlx_vlm/models/mllama/language.py +377 -0
  165. mlx_vlm/models/mllama/mllama.py +210 -0
  166. mlx_vlm/models/mllama/vision.py +458 -0
  167. mlx_vlm/models/molmo/__init__.py +5 -0
  168. mlx_vlm/models/molmo/config.py +93 -0
  169. mlx_vlm/models/molmo/language.py +208 -0
  170. mlx_vlm/models/molmo/molmo.py +108 -0
  171. mlx_vlm/models/molmo/processing_molmo.py +763 -0
  172. mlx_vlm/models/molmo/vision.py +408 -0
  173. mlx_vlm/models/molmo2/__init__.py +6 -0
  174. mlx_vlm/models/molmo2/config.py +137 -0
  175. mlx_vlm/models/molmo2/language.py +206 -0
  176. mlx_vlm/models/molmo2/molmo2.py +330 -0
  177. mlx_vlm/models/molmo2/processing.py +773 -0
  178. mlx_vlm/models/molmo2/vision.py +286 -0
  179. mlx_vlm/models/moondream2/__init__.py +11 -0
  180. mlx_vlm/models/moondream2/config.py +92 -0
  181. mlx_vlm/models/moondream2/image_crops.py +269 -0
  182. mlx_vlm/models/moondream2/language.py +267 -0
  183. mlx_vlm/models/moondream2/moondream2.py +522 -0
  184. mlx_vlm/models/moondream2/processing_moondream.py +144 -0
  185. mlx_vlm/models/moondream2/vision.py +200 -0
  186. mlx_vlm/models/multi_modality/__init__.py +4 -0
  187. mlx_vlm/models/multi_modality/config.py +108 -0
  188. mlx_vlm/models/multi_modality/language.py +191 -0
  189. mlx_vlm/models/multi_modality/multi_modality.py +338 -0
  190. mlx_vlm/models/multi_modality/sam.py +543 -0
  191. mlx_vlm/models/multi_modality/vision.py +450 -0
  192. mlx_vlm/models/paddleocr_vl/__init__.py +3 -0
  193. mlx_vlm/models/paddleocr_vl/config.py +93 -0
  194. mlx_vlm/models/paddleocr_vl/language.py +522 -0
  195. mlx_vlm/models/paddleocr_vl/paddleocr_vl.py +207 -0
  196. mlx_vlm/models/paddleocr_vl/processing_paddleocr_vl.py +425 -0
  197. mlx_vlm/models/paddleocr_vl/vision.py +358 -0
  198. mlx_vlm/models/paligemma/__init__.py +4 -0
  199. mlx_vlm/models/paligemma/config.py +50 -0
  200. mlx_vlm/models/paligemma/language.py +253 -0
  201. mlx_vlm/models/paligemma/paligemma.py +140 -0
  202. mlx_vlm/models/paligemma/vision.py +218 -0
  203. mlx_vlm/models/phi3_v/__init__.py +5 -0
  204. mlx_vlm/models/phi3_v/config.py +55 -0
  205. mlx_vlm/models/phi3_v/language.py +2 -0
  206. mlx_vlm/models/phi3_v/phi3_v.py +239 -0
  207. mlx_vlm/models/phi3_v/processing_phi3_v.py +704 -0
  208. mlx_vlm/models/phi3_v/vision.py +294 -0
  209. mlx_vlm/models/pixtral/__init__.py +4 -0
  210. mlx_vlm/models/pixtral/config.py +69 -0
  211. mlx_vlm/models/pixtral/language.py +195 -0
  212. mlx_vlm/models/pixtral/pixtral.py +208 -0
  213. mlx_vlm/models/pixtral/vision.py +293 -0
  214. mlx_vlm/models/qwen2_5_vl/__init__.py +2 -0
  215. mlx_vlm/models/qwen2_5_vl/config.py +90 -0
  216. mlx_vlm/models/qwen2_5_vl/language.py +541 -0
  217. mlx_vlm/models/qwen2_5_vl/qwen2_5_vl.py +184 -0
  218. mlx_vlm/models/qwen2_5_vl/vision.py +414 -0
  219. mlx_vlm/models/qwen2_vl/__init__.py +2 -0
  220. mlx_vlm/models/qwen2_vl/config.py +86 -0
  221. mlx_vlm/models/qwen2_vl/language.py +539 -0
  222. mlx_vlm/models/qwen2_vl/qwen2_vl.py +180 -0
  223. mlx_vlm/models/qwen2_vl/vision.py +308 -0
  224. mlx_vlm/models/qwen3_omni_moe/__init__.py +29 -0
  225. mlx_vlm/models/qwen3_omni_moe/audio.py +317 -0
  226. mlx_vlm/models/qwen3_omni_moe/code2wav.py +542 -0
  227. mlx_vlm/models/qwen3_omni_moe/config.py +264 -0
  228. mlx_vlm/models/qwen3_omni_moe/language.py +622 -0
  229. mlx_vlm/models/qwen3_omni_moe/omni_utils.py +69 -0
  230. mlx_vlm/models/qwen3_omni_moe/qwen3_omni_moe.py +706 -0
  231. mlx_vlm/models/qwen3_omni_moe/talker.py +873 -0
  232. mlx_vlm/models/qwen3_omni_moe/thinker.py +366 -0
  233. mlx_vlm/models/qwen3_omni_moe/vision.py +419 -0
  234. mlx_vlm/models/qwen3_vl/__init__.py +2 -0
  235. mlx_vlm/models/qwen3_vl/config.py +103 -0
  236. mlx_vlm/models/qwen3_vl/language.py +596 -0
  237. mlx_vlm/models/qwen3_vl/qwen3_vl.py +166 -0
  238. mlx_vlm/models/qwen3_vl/vision.py +441 -0
  239. mlx_vlm/models/qwen3_vl_moe/__init__.py +2 -0
  240. mlx_vlm/models/qwen3_vl_moe/config.py +108 -0
  241. mlx_vlm/models/qwen3_vl_moe/language.py +656 -0
  242. mlx_vlm/models/qwen3_vl_moe/qwen3_vl_moe.py +184 -0
  243. mlx_vlm/models/qwen3_vl_moe/vision.py +442 -0
  244. mlx_vlm/models/smolvlm/__init__.py +4 -0
  245. mlx_vlm/models/smolvlm/config.py +59 -0
  246. mlx_vlm/models/smolvlm/smolvlm.py +60 -0
  247. mlx_vlm/prompt_utils.py +565 -0
  248. mlx_vlm/sample_utils.py +39 -0
  249. mlx_vlm/server.py +1107 -0
  250. mlx_vlm/smolvlm_video_generate.py +109 -0
  251. mlx_vlm/tokenizer_utils.py +371 -0
  252. mlx_vlm/trainer/__init__.py +9 -0
  253. mlx_vlm/trainer/lora.py +70 -0
  254. mlx_vlm/trainer/trainer.py +299 -0
  255. mlx_vlm/trainer/utils.py +160 -0
  256. mlx_vlm/utils.py +1339 -0
  257. mlx_vlm/version.py +1 -0
  258. mlx_vlm/video_generate.py +611 -0
@@ -0,0 +1,418 @@
1
+ import math
2
+ from typing import Optional
3
+
4
+ import mlx.core as mx
5
+ import mlx.nn as nn
6
+ import numpy as np
7
+ from transformers import AutoProcessor
8
+
9
+ from ..base import InputEmbeddingsFeatures
10
+ from .config import ModelConfig, ProjectorConfig
11
+ from .language import LanguageModel
12
+ from .processing_deepsek_vl_v2 import DeepseekVLV2Processor
13
+ from .vision import VisionModel
14
+
15
+ AutoProcessor.register("deepseek_vl_v2", DeepseekVLV2Processor)
16
+
17
+
18
+ class MlpProjector(nn.Module):
19
+ def __init__(self, config: ProjectorConfig):
20
+ super().__init__()
21
+ self.config = config
22
+ if config.projector_config.projector_type == "identity":
23
+ modules = nn.Identity()
24
+ elif config.projector_config.projector_type == "linear":
25
+ modules = nn.Linear(
26
+ config.projector_config.input_dim, config.projector_config.n_embed
27
+ )
28
+ elif config.projector_config.projector_type == "mlp_gelu":
29
+ mlp_depth = config.projector_config.depth
30
+ modules = [
31
+ nn.Linear(
32
+ config.projector_config.input_dim, config.projector_config.n_embed
33
+ )
34
+ ]
35
+ for _ in range(1, mlp_depth):
36
+ modules.append(nn.GELU())
37
+ modules.append(
38
+ nn.Linear(
39
+ config.projector_config.n_embed, config.projector_config.n_embed
40
+ )
41
+ )
42
+ elif config.projector_config.projector_type == "downsample_mlp_gelu":
43
+ mlp_depth = config.projector_config.depth
44
+ mlp_ratio = config.projector_config.mlp_ratio
45
+ modules = [
46
+ nn.Linear(
47
+ config.projector_config.input_dim
48
+ * config.projector_config.downsample_ratio
49
+ * config.projector_config.downsample_ratio,
50
+ config.projector_config.n_embed * mlp_ratio,
51
+ )
52
+ ]
53
+ for _ in range(1, mlp_depth - 1):
54
+ modules.append(nn.GELU())
55
+ modules.append(
56
+ nn.Linear(
57
+ config.projector_config.n_embed * mlp_ratio,
58
+ config.projector_config.n_embed * mlp_ratio,
59
+ )
60
+ )
61
+ modules.append(nn.GELU())
62
+ modules.append(
63
+ nn.Linear(
64
+ config.projector_config.n_embed * mlp_ratio,
65
+ config.projector_config.n_embed,
66
+ )
67
+ )
68
+ else:
69
+ raise ValueError(
70
+ f"Unknown projector type: {config.projector_config.projector_type}"
71
+ )
72
+
73
+ if config.projector_config.token_pooling:
74
+ self.token_pooling_layer = nn.Linear(
75
+ config.projector_config.input_dim * 4, config.projector_config.input_dim
76
+ )
77
+ self.layers = modules
78
+
79
+ def __call__(self, x):
80
+ if self.config.projector_config.token_pooling:
81
+ batch_size, wxh, channels = x.shape
82
+ w = h = int(math.sqrt(wxh))
83
+ x = mx.reshape(x, (batch_size, w, h, channels))
84
+ x = mx.transpose(x, (0, 3, 1, 2)) # B, C, H, W
85
+
86
+ # Implement unfold operation manually since MLX doesn't have unfold
87
+ patches = []
88
+ for i in range(0, h - 1, 2):
89
+ for j in range(0, w - 1, 2):
90
+ patch = x[:, :, i : i + 2, j : j + 2]
91
+ patches.append(patch)
92
+
93
+ patches = mx.stack(patches, axis=2) # B, C, N_patches, 2, 2
94
+ batch_size, channels, n_patches, _, _ = patches.shape
95
+
96
+ # Reshape and concatenate
97
+ patches = mx.reshape(patches, (batch_size, channels, n_patches, -1))
98
+ patches = mx.transpose(patches, (0, 2, 1, 3))
99
+ patches = mx.reshape(patches, (batch_size, n_patches, channels * 4))
100
+ x = self.token_pooling_layer(patches)
101
+
102
+ elif self.config.projector_config.projector_type == "downsample_mlp_gelu":
103
+ bs, hw, input_dim = x.shape
104
+ h = w = int(math.sqrt(hw))
105
+
106
+ # Compute padding
107
+ pad = (
108
+ 0
109
+ if h % self.config.projector_config.downsample_ratio == 0
110
+ else self.config.projector_config.downsample_ratio
111
+ - h % self.config.projector_config.downsample_ratio
112
+ )
113
+
114
+ x = mx.reshape(x, (bs, h, w, input_dim))
115
+ if pad > 0:
116
+ x = mx.pad(x, [(0, 0), (0, pad), (0, pad), (0, 0)], constant_values=0)
117
+
118
+ x = mx.transpose(x, (0, 3, 1, 2)) # B, C, H, W
119
+
120
+ # Manual implementation of unfold for downsampling
121
+ h_pad, w_pad = x.shape[2], x.shape[3]
122
+ ds = self.config.projector_config.downsample_ratio
123
+ patches = []
124
+
125
+ for i in range(0, h_pad - ds + 1, ds):
126
+ for j in range(0, w_pad - ds + 1, ds):
127
+ patch = x[:, :, i : i + ds, j : j + ds]
128
+ patches.append(mx.reshape(patch, (bs, -1)))
129
+
130
+ x = mx.stack(patches, axis=1) # B, N_patches, C*ds*ds
131
+
132
+ for layer in self.layers:
133
+ x = layer(x)
134
+ return x
135
+
136
+
137
+ class Model(nn.Module):
138
+ def __init__(self, config: ModelConfig):
139
+ super().__init__()
140
+ self.config = config
141
+ self.vision = VisionModel(config.vision_config)
142
+ self.language_model = LanguageModel(config.text_config)
143
+ self.projector = MlpProjector(config)
144
+ self.vision_feature_layer = config.select_layer
145
+ self.vision_feature_select_strategy = config.vision_feature_select_strategy
146
+
147
+ self.tile_tag = config.tile_tag
148
+ self.global_view_pos = config.global_view_pos
149
+
150
+ # 用于format image token sequence的特殊token
151
+ embed_std = 1 / mx.sqrt(
152
+ mx.array(config.projector_config.n_embed, dtype=mx.float32)
153
+ )
154
+ if self.tile_tag == "2D":
155
+ # <|view_separator|>, <|\n|>
156
+ self.image_newline = mx.array(
157
+ mx.random.normal((config.projector_config.n_embed,)) * embed_std
158
+ )
159
+ # fix the typo: view_seperater
160
+ self.view_separator = mx.array(
161
+ mx.random.normal((config.projector_config.n_embed,)) * embed_std
162
+ )
163
+ elif self.tile_tag == "1D":
164
+ # <|tile_x|>, <|tile_global|>
165
+ candidate_resolutions = config.candidate_resolutions
166
+ if len(candidate_resolutions) == 0:
167
+ raise ValueError(
168
+ f"len(candidate_resolutions) should be larger than 0, but got {len(candidate_resolutions)}"
169
+ )
170
+ tile_variants_num = len(candidate_resolutions)
171
+ self.tile_indicators = mx.array(
172
+ mx.random.normal(
173
+ (tile_variants_num + 1, config.projector_config.n_embed)
174
+ )
175
+ * embed_std
176
+ )
177
+ else:
178
+ raise ValueError(
179
+ f"tile tag should be either 1D or 2D, but got {self.tile_tag}"
180
+ )
181
+
182
+ def process_image_features(
183
+ self,
184
+ input_embeds,
185
+ images_embeds,
186
+ images_spatial_crop,
187
+ images_seq_mask,
188
+ h,
189
+ w,
190
+ n_dim,
191
+ ):
192
+ tile_index = 0
193
+ all_batch_features = []
194
+
195
+ for idx in range(images_spatial_crop.shape[0]):
196
+ images_in_this_batch = []
197
+ for jdx in range(images_spatial_crop.shape[1]):
198
+ # Extract global & local features
199
+ num_width_tiles, num_height_tiles = images_spatial_crop[idx, jdx]
200
+ if num_width_tiles == 0 or num_height_tiles == 0:
201
+ break
202
+
203
+ num_tiles_in_image = (num_width_tiles * num_height_tiles).tolist()
204
+
205
+ # Get global features [hw, D]
206
+ global_features = images_embeds[tile_index]
207
+
208
+ # Get local features [num_height_tiles * num_width_tiles, hw, D]
209
+ local_features = images_embeds[
210
+ tile_index + 1 : tile_index + 1 + num_tiles_in_image
211
+ ]
212
+
213
+ tile_index += num_tiles_in_image + 1
214
+
215
+ # Format global and local features
216
+ if self.tile_tag == "2D":
217
+ # ----------------- global view add newline -----------------
218
+ # [hw, D] -> [h, w, D]
219
+ global_features = mx.reshape(global_features, (h, w, n_dim))
220
+
221
+ # [D] -> [h, 1, D]
222
+ new_lines_in_global = mx.expand_dims(self.image_newline, axis=0)
223
+ new_lines_in_global = mx.repeat(
224
+ new_lines_in_global, repeats=h, axis=0
225
+ )
226
+ new_lines_in_global = mx.expand_dims(new_lines_in_global, axis=1)
227
+
228
+ # cat([h, w, D], [h, 1, D], dim=1) -> [h, w + 1, D]
229
+ global_features = mx.concatenate(
230
+ [global_features, new_lines_in_global], axis=1
231
+ )
232
+
233
+ # [h, w + 1, D] -> [h * (w + 1), D]
234
+ global_features = mx.reshape(global_features, (-1, n_dim))
235
+
236
+ # ----------------- local view add newline -----------------
237
+ # Rearrange local features
238
+ # [num_height_tiles * num_width_tiles, h * w, D] -> [num_height_tiles * h, num_width_tiles * w, D]
239
+ local_features = mx.reshape(
240
+ local_features, (num_height_tiles, num_width_tiles, h, w, n_dim)
241
+ )
242
+ local_features = mx.transpose(local_features, (0, 2, 1, 3, 4))
243
+ local_features = mx.reshape(
244
+ local_features,
245
+ (num_height_tiles * h, num_width_tiles * w, n_dim),
246
+ )
247
+
248
+ # Create newlines for local features
249
+ # [D] -> [num_height_tiles * h, 1, D]
250
+ new_lines_in_local = mx.repeat(
251
+ mx.expand_dims(self.image_newline, axis=0),
252
+ repeats=num_height_tiles * h,
253
+ axis=0,
254
+ )
255
+ new_lines_in_local = mx.expand_dims(new_lines_in_local, axis=1)
256
+
257
+ # [num_height_tiles * h, num_width_tiles * w + 1, D]
258
+ local_features = mx.concatenate(
259
+ [local_features, new_lines_in_local], axis=1
260
+ )
261
+
262
+ # [(num_height_tiles * h) * (num_width_tiles * w + 1), D]
263
+ local_features = mx.reshape(local_features, (-1, n_dim))
264
+
265
+ # ----------------- merge global and local tiles -----------------
266
+ view_separator = mx.expand_dims(self.view_separator, axis=0)
267
+
268
+ if self.global_view_pos == "head":
269
+ global_local_features = mx.concatenate(
270
+ [global_features, view_separator, local_features], axis=0
271
+ )
272
+ else:
273
+ global_local_features = mx.concatenate(
274
+ [local_features, view_separator, global_features], axis=0
275
+ )
276
+
277
+ else:
278
+ # 1D processing (legacy path)
279
+ global_features = mx.concatenate(
280
+ [
281
+ mx.expand_dims(self.tile_indicators[0], axis=0),
282
+ global_features,
283
+ ],
284
+ axis=0,
285
+ )
286
+
287
+ local_indicators = mx.expand_dims(
288
+ self.tile_indicators[1 : num_tiles_in_image + 1], axis=1
289
+ )
290
+ local_features = mx.concatenate(
291
+ [local_indicators, local_features], axis=1
292
+ )
293
+ local_features = mx.reshape(local_features, (-1, n_dim))
294
+
295
+ if self.global_view_pos == "head":
296
+ global_local_features = mx.concatenate(
297
+ [global_features, local_features], axis=0
298
+ )
299
+ else:
300
+ global_local_features = mx.concatenate(
301
+ [local_features, global_features], axis=0
302
+ )
303
+
304
+ images_in_this_batch.append(global_local_features)
305
+
306
+ if images_in_this_batch:
307
+ images_in_this_batch = mx.concatenate(images_in_this_batch, axis=0)
308
+ # Find positions where images should be placed
309
+ image_indices = np.where(images_seq_mask[idx])[0].tolist()
310
+ # Directly assign the image features to those positions
311
+ input_embeds[idx, image_indices] = images_in_this_batch
312
+
313
+ return input_embeds
314
+
315
+ def get_input_embeddings(
316
+ self,
317
+ input_ids: Optional[mx.array] = None,
318
+ pixel_values: Optional[mx.array] = None,
319
+ images_spatial_crop: Optional[mx.array] = None,
320
+ images_seq_mask: Optional[mx.array] = None,
321
+ **kwargs,
322
+ ):
323
+ if pixel_values is None:
324
+ return InputEmbeddingsFeatures(
325
+ inputs_embeds=self.language_model.model.embed_tokens(input_ids)
326
+ )
327
+
328
+ bs = pixel_values.shape[0]
329
+ max_n_images = pixel_values.shape[1]
330
+
331
+ batch_num_tiles = [0 for _ in range(bs)]
332
+ total_tiles = []
333
+
334
+ # Total number of tiles in each batch
335
+ for idx in range(bs):
336
+ for jdx in range(max_n_images):
337
+ num_width_tiles, num_height_tiles = images_spatial_crop[idx][jdx]
338
+ if num_width_tiles == 0 or num_height_tiles == 0:
339
+ break
340
+ batch_num_tiles[idx] += int(
341
+ (1 + num_width_tiles * num_height_tiles).item()
342
+ )
343
+
344
+ total_tiles.append(pixel_values[idx, : batch_num_tiles[idx]])
345
+
346
+ total_tiles = mx.concatenate(total_tiles, axis=0)
347
+
348
+ if total_tiles.shape[0] == 0:
349
+ return InputEmbeddingsFeatures(
350
+ inputs_embeds=self.language_model.model.embed_tokens(input_ids)
351
+ )
352
+
353
+ # Get the input embeddings from the language model
354
+ input_embeds = self.language_model.model.embed_tokens(input_ids)
355
+
356
+ # Get the ouptut hidden states from the vision model
357
+ hidden_states, *_ = self.vision(
358
+ total_tiles.transpose(0, 2, 3, 1), output_hidden_states=True
359
+ )
360
+
361
+ # Pass image features through the multi-modal projector
362
+ image_features = self.projector(hidden_states)
363
+
364
+ _, hw, n_dim = image_features.shape
365
+ h = w = int(hw**0.5)
366
+
367
+ image_features = self.process_image_features(
368
+ input_embeds,
369
+ image_features,
370
+ images_spatial_crop,
371
+ images_seq_mask,
372
+ h,
373
+ w,
374
+ n_dim,
375
+ )
376
+
377
+ return InputEmbeddingsFeatures(inputs_embeds=image_features)
378
+
379
+ @property
380
+ def layers(self):
381
+ return self.language_model.model.layers
382
+
383
+ def __call__(
384
+ self,
385
+ input_ids: mx.array,
386
+ pixel_values: Optional[mx.array] = None,
387
+ mask: Optional[mx.array] = None,
388
+ cache=None,
389
+ **kwargs,
390
+ ):
391
+
392
+ images_spatial_crop = kwargs.get("images_spatial_crop", None)
393
+ images_seq_mask = kwargs.get("images_seq_mask", None)
394
+ input_embeddings_features = self.get_input_embeddings(
395
+ input_ids, pixel_values, images_spatial_crop, images_seq_mask
396
+ )
397
+ logits = self.language_model(
398
+ input_ids,
399
+ cache=cache,
400
+ inputs_embeds=input_embeddings_features.inputs_embeds,
401
+ )
402
+ return logits
403
+
404
+ @staticmethod
405
+ def sanitize(weights):
406
+ def transform_key(key):
407
+ if "language" in key and "language_model" not in key:
408
+ if ".model" in key:
409
+ key = key.replace("language.model", "language_model.model")
410
+ if ".lm_head" in key:
411
+ key = key.replace("language", "language_model")
412
+ if "vision" in key and "vision_tower" not in key:
413
+ key = key.replace("vision", "vision.vision_tower")
414
+ if "view_seperator" in key:
415
+ key = key.replace("view_seperator", "view_separator")
416
+ return key
417
+
418
+ return {transform_key(k): v for k, v in weights.items()}