nexaai 1.0.19rc7__cp310-cp310-macosx_14_0_universal2.whl → 1.0.19rc8__cp310-cp310-macosx_14_0_universal2.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.

Potentially problematic release.


This version of nexaai might be problematic. Click here for more details.

Files changed (196) hide show
  1. nexaai/_stub.cpython-310-darwin.so +0 -0
  2. nexaai/_version.py +1 -1
  3. nexaai/binds/libnexa_bridge.dylib +0 -0
  4. {nexaai-1.0.19rc7.dist-info → nexaai-1.0.19rc8.dist-info}/METADATA +1 -1
  5. {nexaai-1.0.19rc7.dist-info → nexaai-1.0.19rc8.dist-info}/RECORD +7 -196
  6. nexaai/binds/nexa_mlx/py-lib/asr/__init__.py +0 -12
  7. nexaai/binds/nexa_mlx/py-lib/asr/interface.py +0 -122
  8. nexaai/binds/nexa_mlx/py-lib/common/__init__.py +0 -0
  9. nexaai/binds/nexa_mlx/py-lib/common/utils.py +0 -25
  10. nexaai/binds/nexa_mlx/py-lib/cv/__init__.py +0 -0
  11. nexaai/binds/nexa_mlx/py-lib/cv/generate.py +0 -195
  12. nexaai/binds/nexa_mlx/py-lib/cv/interface.py +0 -151
  13. nexaai/binds/nexa_mlx/py-lib/cv/main.py +0 -81
  14. nexaai/binds/nexa_mlx/py-lib/cv/modeling/pp_ocr_v4.py +0 -1736
  15. nexaai/binds/nexa_mlx/py-lib/embedding/__init__.py +0 -0
  16. nexaai/binds/nexa_mlx/py-lib/embedding/generate.py +0 -333
  17. nexaai/binds/nexa_mlx/py-lib/embedding/interface.py +0 -617
  18. nexaai/binds/nexa_mlx/py-lib/embedding/main.py +0 -173
  19. nexaai/binds/nexa_mlx/py-lib/embedding/modeling/__init__.py +0 -0
  20. nexaai/binds/nexa_mlx/py-lib/embedding/modeling/nexa_jina_v2.py +0 -399
  21. nexaai/binds/nexa_mlx/py-lib/image_gen/__init__.py +0 -1
  22. nexaai/binds/nexa_mlx/py-lib/image_gen/generate_sd.py +0 -244
  23. nexaai/binds/nexa_mlx/py-lib/image_gen/interface.py +0 -82
  24. nexaai/binds/nexa_mlx/py-lib/image_gen/main.py +0 -281
  25. nexaai/binds/nexa_mlx/py-lib/image_gen/stable_diffusion/__init__.py +0 -306
  26. nexaai/binds/nexa_mlx/py-lib/image_gen/stable_diffusion/clip.py +0 -116
  27. nexaai/binds/nexa_mlx/py-lib/image_gen/stable_diffusion/config.py +0 -65
  28. nexaai/binds/nexa_mlx/py-lib/image_gen/stable_diffusion/model_io.py +0 -386
  29. nexaai/binds/nexa_mlx/py-lib/image_gen/stable_diffusion/sampler.py +0 -105
  30. nexaai/binds/nexa_mlx/py-lib/image_gen/stable_diffusion/tokenizer.py +0 -100
  31. nexaai/binds/nexa_mlx/py-lib/image_gen/stable_diffusion/unet.py +0 -460
  32. nexaai/binds/nexa_mlx/py-lib/image_gen/stable_diffusion/vae.py +0 -274
  33. nexaai/binds/nexa_mlx/py-lib/llm/__init__.py +0 -0
  34. nexaai/binds/nexa_mlx/py-lib/llm/generate.py +0 -149
  35. nexaai/binds/nexa_mlx/py-lib/llm/interface.py +0 -764
  36. nexaai/binds/nexa_mlx/py-lib/llm/main.py +0 -68
  37. nexaai/binds/nexa_mlx/py-lib/rerank/__init__.py +0 -0
  38. nexaai/binds/nexa_mlx/py-lib/rerank/generate.py +0 -174
  39. nexaai/binds/nexa_mlx/py-lib/rerank/interface.py +0 -287
  40. nexaai/binds/nexa_mlx/py-lib/rerank/main.py +0 -127
  41. nexaai/binds/nexa_mlx/py-lib/rerank/modeling/__init__.py +0 -0
  42. nexaai/binds/nexa_mlx/py-lib/rerank/modeling/nexa_jina_rerank.py +0 -330
  43. nexaai/binds/nexa_mlx/py-lib/sd/__init__.py +0 -1
  44. nexaai/binds/nexa_mlx/py-lib/sd/interface.py +0 -362
  45. nexaai/binds/nexa_mlx/py-lib/sd/main.py +0 -286
  46. nexaai/binds/nexa_mlx/py-lib/sd/modeling/__init__.py +0 -306
  47. nexaai/binds/nexa_mlx/py-lib/sd/modeling/clip.py +0 -116
  48. nexaai/binds/nexa_mlx/py-lib/sd/modeling/config.py +0 -65
  49. nexaai/binds/nexa_mlx/py-lib/sd/modeling/model_io.py +0 -385
  50. nexaai/binds/nexa_mlx/py-lib/sd/modeling/sampler.py +0 -105
  51. nexaai/binds/nexa_mlx/py-lib/sd/modeling/tokenizer.py +0 -100
  52. nexaai/binds/nexa_mlx/py-lib/sd/modeling/unet.py +0 -460
  53. nexaai/binds/nexa_mlx/py-lib/sd/modeling/vae.py +0 -274
  54. nexaai/binds/nexa_mlx/py-lib/tts/__init__.py +0 -12
  55. nexaai/binds/nexa_mlx/py-lib/tts/interface.py +0 -276
  56. nexaai/binds/nexa_mlx/py-lib/vlm/__init__.py +0 -3
  57. nexaai/binds/nexa_mlx/py-lib/vlm/generate.py +0 -572
  58. nexaai/binds/nexa_mlx/py-lib/vlm/generate_qwen3_vl.py +0 -294
  59. nexaai/binds/nexa_mlx/py-lib/vlm/generate_qwen3_vl_moe.py +0 -276
  60. nexaai/binds/nexa_mlx/py-lib/vlm/interface.py +0 -504
  61. nexaai/binds/nexa_mlx/py-lib/vlm/main.py +0 -320
  62. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/__init__.py +0 -0
  63. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/convert.py +0 -68
  64. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/__init__.py +0 -0
  65. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/aya_vision/__init__.py +0 -8
  66. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/aya_vision/aya_vision.py +0 -193
  67. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/aya_vision/interpolate.py +0 -186
  68. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/aya_vision/language.py +0 -233
  69. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/aya_vision/vision.py +0 -503
  70. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/base.py +0 -202
  71. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/cache.py +0 -230
  72. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/deepseek_vl_v2/__init__.py +0 -10
  73. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/deepseek_vl_v2/conversation.py +0 -264
  74. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/deepseek_vl_v2/deepseek_vl_v2.py +0 -472
  75. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/deepseek_vl_v2/language.py +0 -591
  76. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/deepseek_vl_v2/processing_deepsek_vl_v2.py +0 -526
  77. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/deepseek_vl_v2/vision.py +0 -356
  78. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/florence2/__init__.py +0 -8
  79. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/florence2/florence2.py +0 -366
  80. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/florence2/language.py +0 -488
  81. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/florence2/vision.py +0 -591
  82. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3/__init__.py +0 -8
  83. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3/gemma3.py +0 -213
  84. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3/language.py +0 -315
  85. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3/vision.py +0 -238
  86. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3n/__init__.py +0 -2
  87. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3n/audio.py +0 -1038
  88. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3n/config.py +0 -139
  89. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3n/gemma3n.py +0 -322
  90. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3n/language.py +0 -629
  91. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3n/vision.py +0 -1022
  92. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/idefics2/__init__.py +0 -9
  93. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/idefics2/idefics2.py +0 -294
  94. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/idefics2/language.py +0 -191
  95. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/idefics2/vision.py +0 -267
  96. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/idefics3/__init__.py +0 -8
  97. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/idefics3/idefics3.py +0 -175
  98. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/idefics3/language.py +0 -192
  99. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/idefics3/vision.py +0 -233
  100. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/internvl_chat/__init__.py +0 -9
  101. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/internvl_chat/internvl_chat.py +0 -140
  102. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/internvl_chat/language.py +0 -220
  103. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/internvl_chat/processor.py +0 -393
  104. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/internvl_chat/vision.py +0 -293
  105. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/kernels.py +0 -307
  106. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/kimi_vl/__init__.py +0 -8
  107. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/kimi_vl/kimi_vl.py +0 -143
  108. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/kimi_vl/language.py +0 -509
  109. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/kimi_vl/vision.py +0 -522
  110. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llama4/__init__.py +0 -8
  111. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llama4/language.py +0 -386
  112. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llama4/llama4.py +0 -138
  113. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llama4/vision.py +0 -560
  114. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava/__init__.py +0 -8
  115. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava/language.py +0 -240
  116. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava/llava.py +0 -153
  117. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava/vision.py +0 -259
  118. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava_bunny/__init__.py +0 -9
  119. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava_bunny/language.py +0 -236
  120. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava_bunny/llava_bunny.py +0 -256
  121. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava_bunny/vision.py +0 -303
  122. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava_next/__init__.py +0 -8
  123. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava_next/language.py +0 -230
  124. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava_next/llava_next.py +0 -160
  125. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava_next/vision.py +0 -243
  126. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/mistral3/__init__.py +0 -8
  127. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/mistral3/mistral3.py +0 -283
  128. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/mllama/__init__.py +0 -8
  129. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/mllama/language.py +0 -416
  130. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/mllama/mllama.py +0 -172
  131. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/mllama/vision.py +0 -499
  132. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/molmo/__init__.py +0 -8
  133. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/molmo/language.py +0 -243
  134. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/molmo/molmo.py +0 -133
  135. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/molmo/vision.py +0 -465
  136. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/multi_modality/__init__.py +0 -10
  137. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/multi_modality/language.py +0 -230
  138. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/multi_modality/multi_modality.py +0 -385
  139. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/multi_modality/sam.py +0 -557
  140. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/multi_modality/vision.py +0 -526
  141. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/paligemma/__init__.py +0 -8
  142. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/paligemma/language.py +0 -282
  143. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/paligemma/paligemma.py +0 -160
  144. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/paligemma/vision.py +0 -242
  145. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/phi3_v/__init__.py +0 -8
  146. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/phi3_v/language.py +0 -21
  147. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/phi3_v/phi3_v.py +0 -243
  148. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/phi3_v/su_rope.py +0 -71
  149. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/phi3_v/vision.py +0 -324
  150. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/pixtral/__init__.py +0 -8
  151. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/pixtral/language.py +0 -229
  152. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/pixtral/pixtral.py +0 -161
  153. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/pixtral/vision.py +0 -320
  154. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_5_vl/__init__.py +0 -2
  155. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_5_vl/config.py +0 -108
  156. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_5_vl/language.py +0 -490
  157. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_5_vl/qwen2_5_vl.py +0 -168
  158. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_5_vl/vision.py +0 -414
  159. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_vl/__init__.py +0 -2
  160. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_vl/config.py +0 -104
  161. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_vl/language.py +0 -490
  162. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_vl/qwen2_vl.py +0 -167
  163. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_vl/vision.py +0 -312
  164. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/llm_common/__init__.py +0 -0
  165. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/llm_common/base.py +0 -117
  166. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/llm_common/cache.py +0 -531
  167. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/llm_common/generate.py +0 -701
  168. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/llm_common/rope_utils.py +0 -255
  169. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/llm_common/sample_utils.py +0 -303
  170. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/llm_common/tokenizer_utils.py +0 -407
  171. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/processor.py +0 -476
  172. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/qwen3vl.py +0 -1223
  173. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/llm_common/__init__.py +0 -0
  174. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/llm_common/base.py +0 -117
  175. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/llm_common/cache.py +0 -531
  176. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/llm_common/generate.py +0 -701
  177. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/llm_common/rope_utils.py +0 -255
  178. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/llm_common/sample_utils.py +0 -303
  179. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/llm_common/tokenizer_utils.py +0 -407
  180. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/processor.py +0 -476
  181. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/qwen3vl_moe.py +0 -1309
  182. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/switch_layers.py +0 -210
  183. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/smolvlm/__init__.py +0 -8
  184. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/smolvlm/smolvlm.py +0 -62
  185. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/processing_qwen2_5_vl.py +0 -209
  186. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/processing_qwen2_vl.py +0 -215
  187. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/prompt_utils.py +0 -474
  188. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/sample_utils.py +0 -39
  189. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/tokenizer_utils.py +0 -344
  190. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/trainer/__init__.py +0 -9
  191. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/trainer/lora.py +0 -70
  192. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/trainer/trainer.py +0 -296
  193. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/trainer/utils.py +0 -160
  194. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/utils.py +0 -928
  195. {nexaai-1.0.19rc7.dist-info → nexaai-1.0.19rc8.dist-info}/WHEEL +0 -0
  196. {nexaai-1.0.19rc7.dist-info → nexaai-1.0.19rc8.dist-info}/top_level.txt +0 -0
@@ -1,1223 +0,0 @@
1
- # Copyright © 2023-2024 Apple Inc.
2
-
3
- from dataclasses import dataclass
4
- from typing import Any, Dict, List, Optional, Tuple, Union
5
-
6
- import mlx.core as mx
7
- import mlx.nn as nn
8
- import math
9
- import numpy as np
10
-
11
- import os
12
- import sys
13
-
14
- curr_dir = os.path.dirname(os.path.abspath(__file__))
15
- llm_common_dir = os.path.join(curr_dir, "..", "..")
16
- sys.path.append(llm_common_dir)
17
-
18
- # Try relative imports first, fallback to sys.path approach for Nuitka compatibility
19
- try:
20
- from .llm_common.base import (
21
- BaseModelArgs,
22
- create_attention_mask,
23
- scaled_dot_product_attention,
24
- )
25
- from .llm_common.rope_utils import initialize_rope
26
- except ImportError:
27
- # Fallback for Nuitka compiled environment
28
- from llm_common.base import (
29
- BaseModelArgs,
30
- create_attention_mask,
31
- scaled_dot_product_attention,
32
- )
33
- from llm_common.rope_utils import initialize_rope
34
-
35
-
36
- @dataclass
37
- class VisionConfig:
38
- hidden_size: int = 1024
39
- intermediate_size: int = 4096
40
- num_heads: int = 16
41
- num_hidden_layers: int = 24
42
- patch_size: int = 16
43
- temporal_patch_size: int = 2
44
- in_channels: int = 3
45
- hidden_act: str = "gelu"
46
- spatial_merge_size: int = 2
47
- out_hidden_size: int = 2560
48
- num_position_embeddings: int = 2304
49
- deepstack_visual_indexes: List[int] = None
50
-
51
- def __post_init__(self):
52
- if self.deepstack_visual_indexes is None:
53
- self.deepstack_visual_indexes = [3, 7, 11]
54
-
55
-
56
- @dataclass
57
- class TextConfig(BaseModelArgs):
58
- model_type: str = "qwen3vl"
59
- hidden_size: int = 2560
60
- num_hidden_layers: int = 36
61
- intermediate_size: int = 9728
62
- num_attention_heads: int = 32
63
- num_key_value_heads: int = 8
64
- rms_norm_eps: float = 1e-6
65
- vocab_size: int = 151936
66
- max_position_embeddings: int = 32768
67
- rope_theta: float = 10000.0
68
- head_dim: int = 128
69
- tie_word_embeddings: bool = True
70
- attention_bias: bool = False
71
- attention_dropout: float = 0.0
72
- rope_scaling: Optional[Dict[str, Union[float, str]]] = None
73
-
74
- def __post_init__(self):
75
- if self.rope_scaling is None:
76
- # Use default RoPE for now since MRoPE is not implemented in rope_utils
77
- self.rope_scaling = None
78
-
79
-
80
- @dataclass
81
- class ModelArgs(BaseModelArgs):
82
- vision_config: VisionConfig = None
83
- text_config: TextConfig = None
84
- image_token_id: int = 151655
85
- vision_start_token_id: int = 151652
86
- vision_end_token_id: int = 151653
87
-
88
- def __post_init__(self):
89
- if self.vision_config is None:
90
- self.vision_config = VisionConfig()
91
- if self.text_config is None:
92
- self.text_config = TextConfig()
93
-
94
-
95
- def rotate_half(x):
96
- x1 = x[..., : x.shape[-1] // 2]
97
- x2 = x[..., x.shape[-1] // 2 :]
98
- return mx.concatenate([-x2, x1], axis=-1)
99
-
100
-
101
- def apply_rotary_pos_emb_vision(q, k, cos, sin):
102
- cos = mx.expand_dims(cos, axis=-2)
103
- sin = mx.expand_dims(sin, axis=-2)
104
- q_embed = (q * cos) + (rotate_half(q) * sin)
105
- k_embed = (k * cos) + (rotate_half(k) * sin)
106
- return q_embed, k_embed
107
-
108
-
109
- def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
110
- cos = mx.expand_dims(cos, axis=unsqueeze_dim)
111
- sin = mx.expand_dims(sin, axis=unsqueeze_dim)
112
- q_embed = (q * cos) + (rotate_half(q) * sin)
113
- k_embed = (k * cos) + (rotate_half(k) * sin)
114
- return q_embed, k_embed
115
-
116
-
117
- class VisionMLP(nn.Module):
118
- def __init__(self, config: VisionConfig):
119
- super().__init__()
120
- self.hidden_size = config.hidden_size
121
- self.intermediate_size = config.intermediate_size
122
- self.linear_fc1 = nn.Linear(self.hidden_size, self.intermediate_size, bias=True)
123
- self.linear_fc2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=True)
124
-
125
- def __call__(self, hidden_state):
126
- return self.linear_fc2(nn.gelu(self.linear_fc1(hidden_state)))
127
-
128
-
129
- class VisionPatchEmbed(nn.Module):
130
- def __init__(self, config: VisionConfig):
131
- super().__init__()
132
- self.patch_size = config.patch_size
133
- self.temporal_patch_size = config.temporal_patch_size
134
- self.in_channels = config.in_channels
135
- self.embed_dim = config.hidden_size
136
-
137
- kernel_size = [self.temporal_patch_size, self.patch_size, self.patch_size]
138
- self.proj = nn.Conv3d(
139
- self.in_channels,
140
- self.embed_dim,
141
- kernel_size=kernel_size,
142
- stride=kernel_size,
143
- bias=True
144
- )
145
-
146
- def __call__(self, hidden_states: mx.array) -> mx.array:
147
- target_dtype = self.proj.weight.dtype
148
-
149
- # Reshape to 5D: [batch, channels, temporal, height, width] (PyTorch format)
150
- # This matches the PyTorch ground truth exactly
151
- hidden_states = hidden_states.reshape(
152
- -1, self.in_channels, self.temporal_patch_size, self.patch_size, self.patch_size
153
- )
154
-
155
- # Convert to MLX format: [batch, temporal, height, width, channels]
156
- hidden_states = hidden_states.transpose(0, 2, 3, 4, 1)
157
-
158
- # Apply conv3d with target dtype and reshape to match PyTorch output
159
- hidden_states = self.proj(hidden_states.astype(target_dtype)).reshape(-1, self.embed_dim)
160
-
161
- return hidden_states
162
-
163
-
164
- class VisionRotaryEmbedding(nn.Module):
165
- def __init__(self, dim: int, theta: float = 10000.0):
166
- super().__init__()
167
- # Don't store inv_freq as a parameter since it causes loading issues
168
- self.dim = dim
169
- self.theta = theta
170
-
171
- def __call__(self, seqlen: int) -> mx.array:
172
- # Compute inv_freq on the fly
173
- inv_freq = 1.0 / (self.theta ** (mx.arange(0, self.dim, 2, dtype=mx.float32) / self.dim))
174
- seq = mx.arange(seqlen, dtype=inv_freq.dtype)
175
- freqs = mx.outer(seq, inv_freq)
176
- return freqs
177
-
178
-
179
- class VisionPatchMerger(nn.Module):
180
- def __init__(self, config: VisionConfig, use_postshuffle_norm=False):
181
- super().__init__()
182
- self.hidden_size = config.hidden_size * (config.spatial_merge_size ** 2)
183
- self.use_postshuffle_norm = use_postshuffle_norm
184
-
185
- norm_size = self.hidden_size if use_postshuffle_norm else config.hidden_size
186
- self.ln_q = nn.LayerNorm(norm_size, eps=1e-6)
187
- self.linear_fc1 = nn.Linear(self.hidden_size, self.hidden_size)
188
- self.linear_fc2 = nn.Linear(self.hidden_size, config.out_hidden_size)
189
-
190
- def __call__(self, x: mx.array) -> mx.array:
191
- if self.use_postshuffle_norm:
192
- x = self.ln_q(x.reshape(-1, self.hidden_size)).reshape(-1, self.hidden_size)
193
- else:
194
- x = self.ln_q(x).reshape(-1, self.hidden_size)
195
-
196
- x = self.linear_fc2(nn.gelu(self.linear_fc1(x)))
197
- return x
198
-
199
-
200
- class VisionAttention(nn.Module):
201
- def __init__(self, config: VisionConfig):
202
- super().__init__()
203
- self.dim = config.hidden_size
204
- self.num_heads = config.num_heads
205
- self.head_dim = self.dim // self.num_heads
206
- self.scaling = self.head_dim ** -0.5
207
-
208
- self.qkv = nn.Linear(self.dim, self.dim * 3, bias=True)
209
- self.proj = nn.Linear(self.dim, self.dim)
210
-
211
- def __call__(
212
- self,
213
- hidden_states: mx.array,
214
- cu_seqlens: mx.array,
215
- rotary_pos_emb: Optional[mx.array] = None,
216
- position_embeddings: Optional[Tuple[mx.array, mx.array]] = None,
217
- **kwargs,
218
- ) -> mx.array:
219
- seq_length = hidden_states.shape[0]
220
- qkv = self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1)
221
- qkv = qkv.transpose(1, 0, 2, 3)
222
- query_states, key_states, value_states = qkv[0], qkv[1], qkv[2]
223
-
224
- cos, sin = position_embeddings
225
- query_states, key_states = apply_rotary_pos_emb_vision(
226
- query_states, key_states, cos, sin
227
- )
228
-
229
- query_states = query_states.transpose(1, 0, 2)
230
- key_states = key_states.transpose(1, 0, 2)
231
- value_states = value_states.transpose(1, 0, 2)
232
-
233
- query_states = mx.expand_dims(query_states, axis=0)
234
- key_states = mx.expand_dims(key_states, axis=0)
235
- value_states = mx.expand_dims(value_states, axis=0)
236
-
237
- lengths = cu_seqlens[1:] - cu_seqlens[:-1]
238
-
239
- split_indices = []
240
- cumsum = 0
241
- for length in lengths[:-1]:
242
- cumsum += int(length)
243
- split_indices.append(cumsum)
244
-
245
- if split_indices:
246
- q_splits = mx.split(query_states, split_indices, axis=1)
247
- k_splits = mx.split(key_states, split_indices, axis=1)
248
- v_splits = mx.split(value_states, split_indices, axis=1)
249
- else:
250
- q_splits = [query_states]
251
- k_splits = [key_states]
252
- v_splits = [value_states]
253
-
254
- attn_outputs = []
255
- for q, k, v in zip(q_splits, k_splits, v_splits):
256
- attn_out = scaled_dot_product_attention(
257
- q, k, v,
258
- scale=self.scaling, mask=None, cache=None
259
- )
260
- attn_outputs.append(attn_out)
261
-
262
- attn_output = mx.concatenate(attn_outputs, axis=1)
263
-
264
- attn_output = attn_output[0].transpose(1, 0, 2)
265
- attn_output = attn_output.reshape(seq_length, -1)
266
- attn_output = self.proj(attn_output)
267
-
268
- return attn_output
269
-
270
-
271
- class VisionBlock(nn.Module):
272
- def __init__(self, config: VisionConfig):
273
- super().__init__()
274
- self.norm1 = nn.LayerNorm(config.hidden_size, eps=1e-6)
275
- self.norm2 = nn.LayerNorm(config.hidden_size, eps=1e-6)
276
- self.attn = VisionAttention(config)
277
- self.mlp = VisionMLP(config)
278
-
279
- def __call__(
280
- self,
281
- hidden_states: mx.array,
282
- cu_seqlens: mx.array,
283
- position_embeddings: Tuple[mx.array, mx.array],
284
- ) -> mx.array:
285
- hidden_states = hidden_states + self.attn(
286
- self.norm1(hidden_states),
287
- cu_seqlens=cu_seqlens,
288
- position_embeddings=position_embeddings,
289
- )
290
- hidden_states = hidden_states + self.mlp(self.norm2(hidden_states))
291
- return hidden_states
292
-
293
-
294
- class VisionModel(nn.Module):
295
- def __init__(self, config: VisionConfig):
296
- super().__init__()
297
- self.config = config
298
- self.spatial_merge_size = config.spatial_merge_size
299
- self.patch_size = config.patch_size
300
-
301
- self.patch_embed = VisionPatchEmbed(config)
302
- self.pos_embed = nn.Embedding(config.num_position_embeddings, config.hidden_size)
303
- self.num_grid_per_side = int(config.num_position_embeddings ** 0.5)
304
-
305
- head_dim = config.hidden_size // config.num_heads
306
- self.rotary_pos_emb = VisionRotaryEmbedding(head_dim // 2)
307
-
308
- self.blocks = [VisionBlock(config) for _ in range(config.num_hidden_layers)]
309
- self.merger = VisionPatchMerger(config, use_postshuffle_norm=False)
310
-
311
- self.deepstack_visual_indexes = config.deepstack_visual_indexes
312
- self.deepstack_merger_list = [
313
- VisionPatchMerger(config, use_postshuffle_norm=True)
314
- for _ in range(len(config.deepstack_visual_indexes))
315
- ]
316
-
317
- def rot_pos_emb(self, grid_thw: mx.array) -> mx.array:
318
- merge_size = self.spatial_merge_size
319
-
320
- max_hw = int(grid_thw[:, 1:].max().item())
321
- freq_table = self.rotary_pos_emb(max_hw) # (max_hw, dim // 2)
322
-
323
- pos_ids_parts = []
324
-
325
- for i in range(grid_thw.shape[0]):
326
- num_frames = int(grid_thw[i, 0].item())
327
- height = int(grid_thw[i, 1].item())
328
- width = int(grid_thw[i, 2].item())
329
-
330
- merged_h, merged_w = height // merge_size, width // merge_size
331
-
332
- block_rows = mx.arange(merged_h) # block row indices
333
- block_cols = mx.arange(merged_w) # block col indices
334
- intra_row = mx.arange(merge_size) # intra-block row offsets
335
- intra_col = mx.arange(merge_size) # intra-block col offsets
336
-
337
- # Compute full-resolution positions using broadcasting
338
- row_idx = block_rows[:, None, None, None] * merge_size + intra_row[None, None, :, None]
339
- col_idx = block_cols[None, :, None, None] * merge_size + intra_col[None, None, None, :]
340
-
341
- row_idx = mx.broadcast_to(row_idx, (merged_h, merged_w, merge_size, merge_size)).reshape(-1)
342
- col_idx = mx.broadcast_to(col_idx, (merged_h, merged_w, merge_size, merge_size)).reshape(-1)
343
-
344
- coords = mx.stack([row_idx, col_idx], axis=-1)
345
-
346
- if num_frames > 1:
347
- coords = mx.tile(coords, (num_frames, 1))
348
-
349
- pos_ids_parts.append(coords)
350
-
351
- # Concatenate all coordinate parts
352
- pos_ids = mx.concatenate(pos_ids_parts, axis=0)
353
-
354
- embeddings = freq_table[pos_ids] # lookup rotary embeddings
355
- embeddings = embeddings.reshape(embeddings.shape[0], -1)
356
- return embeddings
357
-
358
- def fast_pos_embed_interpolate(self, grid_thw: mx.array):
359
- patch_pos_embeds = []
360
-
361
- for i in range(grid_thw.shape[0]):
362
- t = int(grid_thw[i, 0].item())
363
- h = int(grid_thw[i, 1].item())
364
- w = int(grid_thw[i, 2].item())
365
-
366
- # Simple position embedding interpolation
367
- h_idxs = mx.linspace(0, self.num_grid_per_side - 1, h)
368
- w_idxs = mx.linspace(0, self.num_grid_per_side - 1, w)
369
-
370
- h_idxs_floor = mx.floor(h_idxs).astype(mx.int32)
371
- w_idxs_floor = mx.floor(w_idxs).astype(mx.int32)
372
- h_idxs_ceil = mx.minimum(h_idxs_floor + 1, self.num_grid_per_side - 1)
373
- w_idxs_ceil = mx.minimum(w_idxs_floor + 1, self.num_grid_per_side - 1)
374
-
375
- dh = h_idxs - h_idxs_floor.astype(mx.float32)
376
- dw = w_idxs - w_idxs_floor.astype(mx.float32)
377
-
378
- base_h = h_idxs_floor * self.num_grid_per_side
379
- base_h_ceil = h_idxs_ceil * self.num_grid_per_side
380
-
381
- # Compute bilinear interpolation indices and weights
382
- indices_tl = (base_h[:, None] + w_idxs_floor[None, :]).reshape(-1)
383
- indices_tr = (base_h[:, None] + w_idxs_ceil[None, :]).reshape(-1)
384
- indices_bl = (base_h_ceil[:, None] + w_idxs_floor[None, :]).reshape(-1)
385
- indices_br = (base_h_ceil[:, None] + w_idxs_ceil[None, :]).reshape(-1)
386
-
387
- weights_tl = ((1 - dh)[:, None] * (1 - dw)[None, :]).reshape(-1)
388
- weights_tr = ((1 - dh)[:, None] * dw[None, :]).reshape(-1)
389
- weights_bl = (dh[:, None] * (1 - dw)[None, :]).reshape(-1)
390
- weights_br = (dh[:, None] * dw[None, :]).reshape(-1)
391
-
392
- # Get embeddings and interpolate
393
- pos_embed_tl = self.pos_embed(indices_tl) * weights_tl[:, None]
394
- pos_embed_tr = self.pos_embed(indices_tr) * weights_tr[:, None]
395
- pos_embed_bl = self.pos_embed(indices_bl) * weights_bl[:, None]
396
- pos_embed_br = self.pos_embed(indices_br) * weights_br[:, None]
397
-
398
- pos_embed = pos_embed_tl + pos_embed_tr + pos_embed_bl + pos_embed_br
399
-
400
- # Repeat for temporal dimension and apply spatial merging
401
- pos_embed = mx.tile(pos_embed, (t, 1))
402
-
403
- # Apply spatial merging pattern
404
- merge_size = self.config.spatial_merge_size
405
- pos_embed = pos_embed.reshape(t, h // merge_size, merge_size, w // merge_size, merge_size, -1)
406
- pos_embed = mx.transpose(pos_embed, (0, 1, 3, 2, 4, 5))
407
- pos_embed = pos_embed.reshape(-1, pos_embed.shape[-1])
408
-
409
- patch_pos_embeds.append(pos_embed)
410
-
411
- return mx.concatenate(patch_pos_embeds, axis=0)
412
-
413
- def __call__(self, hidden_states: mx.array, grid_thw: mx.array) -> Tuple[mx.array, List[mx.array]]:
414
- hidden_states = self.patch_embed(hidden_states)
415
-
416
- pos_embeds = self.fast_pos_embed_interpolate(grid_thw)
417
- hidden_states = hidden_states + pos_embeds
418
-
419
- rotary_pos_emb = self.rot_pos_emb(grid_thw)
420
- seq_len = hidden_states.shape[0]
421
-
422
- emb = mx.concatenate([rotary_pos_emb, rotary_pos_emb], axis=-1)
423
- position_embeddings = (mx.cos(emb), mx.sin(emb))
424
-
425
- # Create cumulative sequence lengths (following HuggingFace implementation)
426
- # torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0])
427
- seq_lens_per_image = grid_thw[:, 1] * grid_thw[:, 2] # h * w for each image
428
- seq_lens = []
429
- for i, (seq_len, repeats) in enumerate(zip(seq_lens_per_image, grid_thw[:, 0])):
430
- seq_lens.extend([seq_len] * int(repeats))
431
- seq_lens = mx.array(seq_lens)
432
-
433
- # Then compute cumulative sum
434
- cu_seqlens = mx.cumsum(seq_lens)
435
- # Pad with 0 at the beginning
436
- cu_seqlens = mx.concatenate([mx.array([0]), cu_seqlens])
437
-
438
- deepstack_feature_lists = []
439
- for layer_num, blk in enumerate(self.blocks):
440
- hidden_states = blk(
441
- hidden_states,
442
- cu_seqlens=cu_seqlens,
443
- position_embeddings=position_embeddings,
444
- )
445
- if layer_num in self.deepstack_visual_indexes:
446
- idx = self.deepstack_visual_indexes.index(layer_num)
447
- deepstack_feature = self.deepstack_merger_list[idx](hidden_states)
448
- deepstack_feature_lists.append(deepstack_feature)
449
-
450
- hidden_states = self.merger(hidden_states)
451
- return hidden_states, deepstack_feature_lists
452
-
453
-
454
- class TextRotaryEmbedding(nn.Module):
455
- def __init__(self, config: TextConfig):
456
- super().__init__()
457
- self.config = config
458
- self.max_seq_len_cached = config.max_position_embeddings
459
- self.original_max_seq_len = config.max_position_embeddings
460
-
461
- # MRoPE configuration
462
- if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
463
- self.rope_type = config.rope_scaling.get("rope_type", "default")
464
- self.mrope_section = config.rope_scaling.get("mrope_section", [24, 20, 20])
465
- else:
466
- self.rope_type = "default"
467
- self.mrope_section = [24, 20, 20]
468
-
469
- # Store parameters for computing inv_freq on the fly
470
- self.head_dim = config.head_dim
471
- self.theta = config.rope_theta
472
-
473
- # Attention scaling (simplified - may need adjustment based on actual config)
474
- self.attention_scaling = 1.0
475
-
476
- def _get_inv_freq(self):
477
- """Compute inverse frequencies on the fly"""
478
- inv_freq = 1.0 / (self.theta ** (mx.arange(0, self.head_dim, 2).astype(mx.float32) / self.head_dim))
479
- # Expand for 3 dimensions (T, H, W)
480
- return mx.broadcast_to(inv_freq[None, :], (3, len(inv_freq)))
481
-
482
- def apply_interleaved_mrope(self, freqs, mrope_section):
483
- """Apply interleaved MRoPE to 3D rotary embeddings.
484
- Reorganizes frequency layout from chunked [TTT...HHH...WWW] to
485
- interleaved [THTHWHTHW...TT], preserving frequency continuity.
486
- args:
487
- x: (3, bs, seq_len, head_dim // 2)
488
- mrope_section: (3,)
489
- returns:
490
- x_t: (bs, seq_len, head_dim // 2)
491
- """
492
- freqs_t = freqs[0] # just overwrite the first dimension T
493
- for dim, offset in enumerate((1, 2), start=1): # H, W
494
- length = mrope_section[dim] * 3
495
- idx = slice(offset, length, 3)
496
- freqs_t[..., idx] = freqs[dim, ..., idx]
497
- return freqs_t
498
-
499
- def __call__(self, x: mx.array, position_ids: mx.array) -> mx.array:
500
- """
501
- Args:
502
- x: Input tensor for dtype reference
503
- position_ids: Position indices, shape (3, batch_size, seq_len) for MRoPE
504
-
505
- Returns:
506
- cos, sin: Cosine and sine embeddings
507
- """
508
- # Handle 2D position_ids by expanding to 3D for MRoPE
509
- if position_ids.ndim == 2:
510
- position_ids = mx.broadcast_to(position_ids[None, ...], (3, position_ids.shape[0], position_ids.shape[1]))
511
-
512
- batch_size, seq_len = position_ids.shape[1], position_ids.shape[2]
513
-
514
- # Expand inverse frequencies: (3, 1, 1, dim//2) -> (3, batch_size, 1, dim//2)
515
- inv_freq_expanded = mx.broadcast_to(
516
- self._get_inv_freq()[:, None, None, :],
517
- (3, batch_size, 1, self._get_inv_freq().shape[-1])
518
- )
519
-
520
- # Expand position ids: (3, batch_size, seq_len) -> (3, batch_size, seq_len, 1)
521
- position_ids_expanded = position_ids[..., None].astype(mx.float32)
522
-
523
- # Compute frequencies: (3, batch_size, seq_len, dim//2)
524
- freqs = inv_freq_expanded * position_ids_expanded
525
-
526
- # Apply interleaved MRoPE
527
- freqs = self.apply_interleaved_mrope(freqs, self.mrope_section)
528
-
529
- # Create embeddings
530
- emb = mx.concatenate([freqs, freqs], axis=-1) # (batch_size, seq_len, head_dim)
531
- cos = mx.cos(emb) * self.attention_scaling
532
- sin = mx.sin(emb) * self.attention_scaling
533
-
534
- return cos.astype(x.dtype), sin.astype(x.dtype)
535
-
536
-
537
- class TextAttention(nn.Module):
538
- def __init__(self, config: TextConfig, layer_idx: int):
539
- super().__init__()
540
- self.config = config
541
- self.layer_idx = layer_idx
542
-
543
- dim = config.hidden_size
544
- self.n_heads = config.num_attention_heads
545
- self.n_kv_heads = config.num_key_value_heads
546
- self.head_dim = config.head_dim
547
- self.scale = self.head_dim ** -0.5
548
-
549
- self.q_proj = nn.Linear(dim, self.n_heads * self.head_dim, bias=config.attention_bias)
550
- self.k_proj = nn.Linear(dim, self.n_kv_heads * self.head_dim, bias=config.attention_bias)
551
- self.v_proj = nn.Linear(dim, self.n_kv_heads * self.head_dim, bias=config.attention_bias)
552
- self.o_proj = nn.Linear(self.n_heads * self.head_dim, dim, bias=config.attention_bias)
553
-
554
- self.q_norm = nn.RMSNorm(self.head_dim, eps=config.rms_norm_eps)
555
- self.k_norm = nn.RMSNorm(self.head_dim, eps=config.rms_norm_eps)
556
-
557
- # Initialize rope directly
558
- self.rope = initialize_rope(
559
- config.head_dim,
560
- base=config.rope_theta,
561
- traditional=False,
562
- scaling_config=config.rope_scaling,
563
- max_position_embeddings=config.max_position_embeddings,
564
- )
565
-
566
- def __call__(
567
- self,
568
- hidden_states: mx.array,
569
- attention_mask: Optional[mx.array] = None,
570
- cache: Optional[Any] = None,
571
- cos: Optional[mx.array] = None,
572
- sin: Optional[mx.array] = None,
573
- rope_deltas: Optional[mx.array] = None,
574
- ) -> Tuple[mx.array, Optional[mx.array]]:
575
- B, L, D = hidden_states.shape
576
-
577
- queries = self.q_proj(hidden_states).reshape(B, L, self.n_heads, -1)
578
- keys = self.k_proj(hidden_states).reshape(B, L, self.n_kv_heads, -1)
579
- values = self.v_proj(hidden_states).reshape(B, L, self.n_kv_heads, -1)
580
-
581
- queries = self.q_norm(queries).transpose(0, 2, 1, 3)
582
- keys = self.k_norm(keys).transpose(0, 2, 1, 3)
583
- values = values.transpose(0, 2, 1, 3)
584
-
585
- # Apply rope directly to queries and keys
586
- if cos is not None and sin is not None:
587
- queries, keys = apply_rotary_pos_emb(queries, keys, cos, sin)
588
- if cache is not None:
589
- keys, values = cache.update_and_fetch(keys, values)
590
- else:
591
- if cache is not None:
592
- queries = self.rope(queries, offset=cache.offset+rope_deltas)
593
- keys = self.rope(keys, offset=cache.offset+rope_deltas)
594
- keys, values = cache.update_and_fetch(keys, values)
595
- else:
596
- queries = self.rope(queries)
597
- keys = self.rope(keys)
598
-
599
- output = scaled_dot_product_attention(
600
- queries, keys, values, cache=cache, scale=self.scale, mask=attention_mask
601
- )
602
- output = output.transpose(0, 2, 1, 3).reshape(B, L, -1)
603
- return self.o_proj(output), None
604
-
605
-
606
- class TextMLP(nn.Module):
607
- def __init__(self, config: TextConfig):
608
- super().__init__()
609
- self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
610
- self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
611
- self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
612
-
613
- def __call__(self, x):
614
- return self.down_proj(nn.silu(self.gate_proj(x)) * self.up_proj(x))
615
-
616
-
617
- class TextDecoderLayer(nn.Module):
618
- def __init__(self, config: TextConfig, layer_idx: int):
619
- super().__init__()
620
- self.hidden_size = config.hidden_size
621
- self.self_attn = TextAttention(config, layer_idx)
622
- self.mlp = TextMLP(config)
623
- self.input_layernorm = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
624
- self.post_attention_layernorm = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
625
-
626
- def __call__(
627
- self,
628
- hidden_states: mx.array,
629
- attention_mask: Optional[mx.array] = None,
630
- cache: Optional[Any] = None,
631
- cos: Optional[mx.array] = None,
632
- sin: Optional[mx.array] = None,
633
- rope_deltas: Optional[mx.array] = None,
634
- ) -> mx.array:
635
- residual = hidden_states
636
- hidden_states = self.input_layernorm(hidden_states)
637
-
638
- hidden_states, _ = self.self_attn(
639
- hidden_states=hidden_states,
640
- attention_mask=attention_mask,
641
- cache=cache,
642
- cos=cos,
643
- sin=sin,
644
- rope_deltas=rope_deltas,
645
- )
646
- hidden_states = residual + hidden_states
647
- residual = hidden_states
648
- hidden_states = self.post_attention_layernorm(hidden_states)
649
- hidden_states = self.mlp(hidden_states)
650
- hidden_states = residual + hidden_states
651
- return hidden_states
652
-
653
-
654
- class TextModel(nn.Module):
655
- def __init__(self, config: TextConfig):
656
- super().__init__()
657
- self.config = config
658
- self.vocab_size = config.vocab_size
659
-
660
- self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
661
- self.layers = [
662
- TextDecoderLayer(config, layer_idx)
663
- for layer_idx in range(config.num_hidden_layers)
664
- ]
665
- self.norm = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
666
- self.rotary_emb = TextRotaryEmbedding(config)
667
-
668
- def _deepstack_process(
669
- self,
670
- hidden_states: mx.array,
671
- visual_pos_masks: mx.array,
672
- deepstack_visual_embeds: mx.array,
673
- ) -> mx.array:
674
- if visual_pos_masks is None or deepstack_visual_embeds is None:
675
- return hidden_states
676
- B, L, D = hidden_states.shape
677
- mask_flat = visual_pos_masks.astype(mx.int32).reshape(-1)
678
- idx_flat = mx.cumsum(mask_flat, axis=0) - 1
679
- N = deepstack_visual_embeds.shape[0]
680
- idx_flat = mx.maximum(idx_flat, 0)
681
- eq = (idx_flat[:, None] == mx.arange(N)[None, :]).astype(hidden_states.dtype)
682
- add_flat = eq @ deepstack_visual_embeds.astype(hidden_states.dtype)
683
- add_flat = add_flat * mask_flat[:, None].astype(hidden_states.dtype)
684
- add = add_flat.reshape(B, L, D)
685
- return hidden_states + add
686
-
687
- def __call__(
688
- self,
689
- input_ids: Optional[mx.array] = None,
690
- inputs_embeds: Optional[mx.array] = None,
691
- attention_mask: Optional[mx.array] = None,
692
- cache=None,
693
- visual_pos_masks: Optional[mx.array] = None,
694
- deepstack_visual_embeds: Optional[List[mx.array]] = None,
695
- cos: Optional[mx.array] = None,
696
- sin: Optional[mx.array] = None,
697
- rope_deltas: Optional[mx.array] = None,
698
- ):
699
- if inputs_embeds is None:
700
- inputs_embeds = self.embed_tokens(input_ids)
701
-
702
- hidden_states = inputs_embeds
703
-
704
- if attention_mask is None:
705
- attention_mask = create_attention_mask(hidden_states, cache, return_array=True)
706
-
707
- if cache is None:
708
- cache = [None] * len(self.layers)
709
-
710
- for layer_idx, (decoder_layer, c) in enumerate(zip(self.layers, cache)):
711
- hidden_states = decoder_layer(
712
- hidden_states,
713
- attention_mask=attention_mask,
714
- cache=c,
715
- cos=cos,
716
- sin=sin,
717
- rope_deltas=rope_deltas,
718
- )
719
- if deepstack_visual_embeds is not None and layer_idx < len(deepstack_visual_embeds):
720
- hidden_states = self._deepstack_process(hidden_states, visual_pos_masks, deepstack_visual_embeds[layer_idx])
721
- hidden_states = self.norm(hidden_states)
722
- return hidden_states
723
-
724
-
725
- # Standalone Vision Model
726
- class VEGModel(nn.Module):
727
- def __init__(self, vision_config: VisionConfig):
728
- super().__init__()
729
- self.config = vision_config
730
- self.visual = VisionModel(vision_config)
731
-
732
- def __call__(self, pixel_values: mx.array, image_grid_thw: mx.array):
733
- return self.visual(pixel_values, image_grid_thw)
734
-
735
- def sanitize(self, weights):
736
- sanitized = {}
737
- for k, v in weights.items():
738
- if 'visual.' in k:
739
- # Remove prefixes to match our model structure
740
- clean_key = k.replace('model.visual.', '').replace('visual.', '')
741
- sanitized[f'visual.{clean_key}'] = v
742
- return sanitized
743
-
744
-
745
- # Pure LLM Model (no vision components)
746
- class LLMModel(nn.Module):
747
- def __init__(self, text_config: TextConfig):
748
- super().__init__()
749
- self.args = text_config
750
- self.config = text_config
751
- self.language_model = TextModel(text_config)
752
- if not text_config.tie_word_embeddings:
753
- self.lm_head = nn.Linear(text_config.hidden_size, text_config.vocab_size, bias=False)
754
-
755
- def get_rope_index(
756
- self,
757
- input_ids: Optional[mx.array] = None,
758
- image_grid_thw: Optional[mx.array] = None,
759
- attention_mask: Optional[mx.array] = None,
760
- ) -> Tuple[mx.array, mx.array]:
761
- """Simplified version for images only (no video support)."""
762
-
763
- spatial_merge_size = 2
764
- image_token_id = 151655
765
- vision_start_token_id = 151652
766
- mrope_position_deltas = []
767
-
768
- if input_ids is not None and image_grid_thw is not None:
769
- total_input_ids = input_ids
770
- if attention_mask is None:
771
- attention_mask = mx.ones_like(total_input_ids)
772
-
773
- batch_size, seq_len = input_ids.shape
774
- position_ids_list = []
775
- image_index = 0
776
-
777
- for i in range(batch_size):
778
- input_ids_seq = total_input_ids[i]
779
- mask_seq = attention_mask[i]
780
-
781
- # Use mask to get valid length
782
- valid_length = int(mx.sum(mask_seq).item())
783
- input_ids_seq = input_ids_seq[:valid_length]
784
-
785
- image_nums = 0
786
- # Find vision start tokens by iterating through the sequence
787
- vision_start_positions = []
788
- for pos in range(input_ids_seq.shape[0]):
789
- if input_ids_seq[pos].item() == vision_start_token_id:
790
- vision_start_positions.append(pos)
791
-
792
- if len(vision_start_positions) > 0:
793
- for pos in vision_start_positions:
794
- if pos + 1 < input_ids_seq.shape[0]:
795
- if input_ids_seq[pos + 1].item() == image_token_id:
796
- image_nums += 1
797
-
798
- input_tokens = input_ids_seq.tolist()
799
- llm_pos_ids_list = []
800
- st = 0
801
- remain_images = image_nums
802
-
803
- for _ in range(image_nums):
804
- ed_image = input_tokens.index(image_token_id, st)
805
-
806
- t = image_grid_thw[image_index, 0].item()
807
- h = image_grid_thw[image_index, 1].item()
808
- w = image_grid_thw[image_index, 2].item()
809
- image_index += 1
810
- remain_images -= 1
811
- ed = ed_image
812
-
813
- llm_grid_t = int(t)
814
- llm_grid_h = int(h) // spatial_merge_size
815
- llm_grid_w = int(w) // spatial_merge_size
816
- text_len = ed - st
817
-
818
- st_idx = llm_pos_ids_list[-1].max().item() + 1 if len(llm_pos_ids_list) > 0 else 0
819
- text_pos = mx.arange(text_len).reshape(1, -1)
820
- text_pos = mx.broadcast_to(text_pos, (3, text_len)) + st_idx
821
- llm_pos_ids_list.append(text_pos)
822
-
823
- # t_index is always 0 because llm_grid_t is always 1 for images
824
- t_index = mx.arange(llm_grid_t).reshape(-1, 1)
825
- t_index = mx.broadcast_to(t_index, (llm_grid_t, llm_grid_h * llm_grid_w)).reshape(-1)
826
-
827
- h_index = mx.arange(llm_grid_h).reshape(1, -1, 1)
828
- h_index = mx.broadcast_to(h_index, (llm_grid_t, llm_grid_h, llm_grid_w)).reshape(-1)
829
-
830
- w_index = mx.arange(llm_grid_w).reshape(1, 1, -1)
831
- w_index = mx.broadcast_to(w_index, (llm_grid_t, llm_grid_h, llm_grid_w)).reshape(-1)
832
-
833
- vision_pos = mx.stack([t_index, h_index, w_index]) + text_len + st_idx
834
- llm_pos_ids_list.append(vision_pos)
835
- st = ed + llm_grid_t * llm_grid_h * llm_grid_w
836
-
837
- if st < len(input_tokens):
838
- st_idx = llm_pos_ids_list[-1].max().item() + 1 if len(llm_pos_ids_list) > 0 else 0
839
- text_len = len(input_tokens) - st
840
- text_pos = mx.arange(text_len).reshape(1, -1)
841
- text_pos = mx.broadcast_to(text_pos, (3, text_len)) + st_idx
842
- llm_pos_ids_list.append(text_pos)
843
-
844
- llm_positions = mx.concatenate(llm_pos_ids_list, axis=1).reshape(3, -1)
845
-
846
- # Create position_ids for this batch item, pad to seq_len
847
- batch_position_ids = mx.ones((3, seq_len), dtype=input_ids.dtype)
848
- valid_length = min(seq_len, llm_positions.shape[1])
849
-
850
- # Create new arrays for each dimension
851
- pos_dim0 = mx.concatenate([llm_positions[0, :valid_length],
852
- mx.ones(seq_len - valid_length, dtype=input_ids.dtype)])
853
- pos_dim1 = mx.concatenate([llm_positions[1, :valid_length],
854
- mx.ones(seq_len - valid_length, dtype=input_ids.dtype)])
855
- pos_dim2 = mx.concatenate([llm_positions[2, :valid_length],
856
- mx.ones(seq_len - valid_length, dtype=input_ids.dtype)])
857
-
858
- batch_position_ids = mx.stack([pos_dim0, pos_dim1, pos_dim2])
859
- position_ids_list.append(batch_position_ids)
860
-
861
- mrope_position_deltas.append(llm_positions.max().item() + 1 - len(total_input_ids[i]))
862
-
863
- # Stack all batch position_ids
864
- position_ids = mx.stack(position_ids_list, axis=1) # Shape: (3, batch_size, seq_len)
865
- # Ensure rope deltas are 1D: (batch,)
866
- mrope_position_deltas = mx.array(mrope_position_deltas).reshape(-1)
867
- return position_ids, mrope_position_deltas
868
- else:
869
- if attention_mask is not None:
870
- position_ids = mx.cumsum(attention_mask.astype(mx.int32), axis=-1) - 1
871
- position_ids = mx.where(attention_mask == 0, 1, position_ids)
872
- position_ids = mx.expand_dims(position_ids, axis=0)
873
- position_ids = mx.broadcast_to(position_ids, (3, position_ids.shape[1], position_ids.shape[2]))
874
- # Compute max position per batch, ensure 1D shape (batch,)
875
- max_position_ids = mx.max(mx.max(position_ids, axis=0, keepdims=False), axis=-1, keepdims=False)
876
- mrope_position_deltas = max_position_ids + 1 - attention_mask.shape[-1]
877
- mrope_position_deltas = mx.reshape(mrope_position_deltas, (-1,))
878
- else:
879
- seq_len = input_ids.shape[1]
880
- batch_size = input_ids.shape[0]
881
- position_ids = mx.arange(seq_len).reshape(1, 1, -1)
882
- position_ids = mx.broadcast_to(position_ids, (3, batch_size, seq_len))
883
- # 1D zeros for rope deltas
884
- mrope_position_deltas = mx.zeros((batch_size,), dtype=input_ids.dtype)
885
-
886
- return position_ids, mrope_position_deltas
887
-
888
- def __call__(
889
- self,
890
- inputs: mx.array = None,
891
- mask: mx.array = None,
892
- cache=None,
893
- inputs_embeds: Optional[mx.array] = None,
894
- visual_pos_masks: Optional[mx.array] = None,
895
- deepstack_visual_embeds: Optional[List[mx.array]] = None,
896
- cos: Optional[mx.array] = None,
897
- sin: Optional[mx.array] = None,
898
- rope_deltas: Optional[mx.array] = None,
899
- ):
900
- out = self.language_model(
901
- input_ids=inputs,
902
- inputs_embeds=inputs_embeds,
903
- attention_mask=mask,
904
- cache=cache,
905
- visual_pos_masks=visual_pos_masks,
906
- deepstack_visual_embeds=deepstack_visual_embeds,
907
- cos=cos,
908
- sin=sin,
909
- rope_deltas=rope_deltas,
910
- )
911
- if self.args.tie_word_embeddings:
912
- return self.language_model.embed_tokens.as_linear(out)
913
- else:
914
- return self.lm_head(out)
915
-
916
- def sanitize(self, weights):
917
- sanitized = {}
918
- for k, v in weights.items():
919
- if not ('visual.' in k):
920
- # Handle key mapping from combined model to LLM-only model
921
- clean_key = k
922
-
923
- # Remove model. prefix if present
924
- if clean_key.startswith('model.'):
925
- clean_key = clean_key[6:] # Remove 'model.'
926
-
927
- # Map language_ prefixed keys to language_model structure
928
- if clean_key.startswith('language_'):
929
- if clean_key.startswith('language_layers.'):
930
- clean_key = 'language_model.layers.' + clean_key[16:] # Map to language_model.layers.
931
- elif clean_key.startswith('language_embed_tokens.'):
932
- clean_key = 'language_model.embed_tokens.' + clean_key[22:] # Map to language_model.embed_tokens.
933
- elif clean_key.startswith('language_norm.'):
934
- clean_key = 'language_model.norm.' + clean_key[14:] # Map to language_model.norm.
935
-
936
- sanitized[clean_key] = v
937
-
938
- # Handle tied embeddings - remove lm_head if using tied embeddings
939
- if self.args.tie_word_embeddings:
940
- sanitized.pop("lm_head.weight", None)
941
-
942
- return sanitized
943
-
944
- @property
945
- def layers(self):
946
- return self.language_model.layers
947
-
948
-
949
- # Combined Model (for compatibility and utility functions)
950
- class Qwen3VLModel(nn.Module):
951
- def __init__(self, args: ModelArgs):
952
- super().__init__()
953
- self.args = args
954
- self.config = args
955
- self.visual = VisionModel(args.vision_config)
956
- self.language_model = TextModel(args.text_config)
957
-
958
- def sanitize(self, weights):
959
- # Map weights to match the combined model structure
960
- sanitized = {}
961
- for k, v in weights.items():
962
- # Remove 'model.' prefix if present to match our structure
963
- clean_key = k.replace('model.', '') if k.startswith('model.') else k
964
- sanitized[clean_key] = v
965
- return sanitized
966
-
967
- def get_image_features(
968
- self,
969
- pixel_values: mx.array,
970
- image_grid_thw: Optional[mx.array] = None
971
- ):
972
- image_embeds, deepstack_visual_embeds = self.visual(pixel_values, image_grid_thw)
973
- # Split based on grid dimensions
974
- if image_grid_thw is not None:
975
- split_sizes = (mx.prod(image_grid_thw, axis=-1) // (self.visual.spatial_merge_size ** 2)).tolist()
976
- # Convert sizes to indices for mx.split (cumulative sum, excluding the last)
977
- split_indices = []
978
- cumsum = 0
979
- for size in split_sizes[:-1]: # Exclude last element
980
- cumsum += size
981
- split_indices.append(cumsum)
982
-
983
- if split_indices: # Only split if we have indices
984
- image_embeds = mx.split(image_embeds, split_indices)
985
- else:
986
- image_embeds = [image_embeds] # Single image case
987
- return image_embeds, deepstack_visual_embeds
988
-
989
-
990
- def __call__(
991
- self,
992
- input_ids: mx.array = None,
993
- attention_mask: Optional[mx.array] = None,
994
- inputs_embeds: Optional[mx.array] = None,
995
- pixel_values: Optional[mx.array] = None,
996
- image_grid_thw: Optional[mx.array] = None,
997
- cache=None,
998
- visual_pos_masks: Optional[mx.array] = None,
999
- deepstack_visual_embeds: Optional[List[mx.array]] = None,
1000
- cos: Optional[mx.array] = None,
1001
- sin: Optional[mx.array] = None,
1002
- rope_deltas: Optional[mx.array] = None,
1003
- ):
1004
- if inputs_embeds is None:
1005
- inputs_embeds = self.language_model.embed_tokens(input_ids)
1006
-
1007
- # Process images
1008
-
1009
- if pixel_values is not None:
1010
- image_embeds, deepstack_visual_embeds = self.get_image_features(
1011
- pixel_values, image_grid_thw
1012
- )
1013
-
1014
- # Create masks and embed visual features
1015
- if isinstance(image_embeds, list):
1016
- image_embeds = mx.concatenate(image_embeds, axis=0)
1017
-
1018
- # Find image token positions and replace with visual embeddings
1019
- image_mask = (input_ids == self.args.image_token_id)
1020
- visual_pos_masks = image_mask
1021
-
1022
- # Replace image tokens with visual embeddings
1023
- inputs_embeds = inputs_embeds.at[image_mask].set(
1024
- image_embeds.astype(inputs_embeds.dtype)
1025
- )
1026
-
1027
-
1028
- outputs = self.language_model(
1029
- inputs_embeds=inputs_embeds,
1030
- attention_mask=attention_mask,
1031
- cache=cache,
1032
- visual_pos_masks=visual_pos_masks,
1033
- deepstack_visual_embeds=deepstack_visual_embeds,
1034
- cos=cos,
1035
- sin=sin,
1036
- rope_deltas=rope_deltas,
1037
- )
1038
-
1039
- return outputs
1040
-
1041
-
1042
- def handle_multimodal_embeds(vision_model, llm_model, input_ids, pixel_values, image_grid_thw):
1043
- """
1044
- Handle the processing of multimodal embeddings including image features and position encoding.
1045
-
1046
- This function processes vision and text inputs to create unified embeddings that can be fed
1047
- into the language model. It handles:
1048
- - Vision feature extraction from pixel values
1049
- - Deepstack visual embedding collection
1050
- - Image token replacement in text embeddings
1051
- - Position encoding setup for MRoPE (Multi-dimensional RoPE)
1052
-
1053
- Args:
1054
- vision_model: The vision encoder model (VEGModel instance)
1055
- llm_model: The language model (LLMModel instance)
1056
- input_ids: Tokenized text input with image token placeholders [batch_size, seq_len]
1057
- pixel_values: Preprocessed image pixel data [num_patches, feature_dim]
1058
- image_grid_thw: Grid dimensions for each image [num_images, 3] (time, height, width)
1059
-
1060
- Returns:
1061
- tuple: (inputs_embeds, deepstack_visual_embeds, visual_pos_masks, cos, sin, rope_deltas)
1062
- - inputs_embeds: Combined text and image embeddings [batch_size, seq_len, hidden_size]
1063
- - deepstack_visual_embeds: Multi-layer visual features for deepstack processing
1064
- - visual_pos_masks: Boolean mask indicating image token positions
1065
- - cos: Cosine values for rotary position encoding
1066
- - sin: Sine values for rotary position encoding
1067
- - rope_deltas: Position offset deltas for rope computation
1068
- """
1069
- inputs_embeds = llm_model.language_model.embed_tokens(input_ids.squeeze(0))
1070
- deepstack_visual_embeds = None
1071
- visual_pos_masks = None
1072
- cos = None
1073
- sin = None
1074
- rope_deltas = 0
1075
-
1076
- if pixel_values is not None:
1077
- if pixel_values.ndim == 4:
1078
- pixel_values = mx.expand_dims(pixel_values, axis=2)
1079
-
1080
- # Process each image individually to prevent feature mixing
1081
- image_embeds_list = []
1082
- all_deepstack_embeds = []
1083
-
1084
- # Calculate cumulative indices for each image
1085
- cumulative_patches = 0
1086
-
1087
- for i in range(image_grid_thw.shape[0]):
1088
- # Calculate number of patches for current image
1089
- current_patches = int(image_grid_thw[i, 1] * image_grid_thw[i, 2])
1090
- start_idx = cumulative_patches
1091
- end_idx = cumulative_patches + current_patches
1092
- cumulative_patches += current_patches
1093
-
1094
- single_pixel_values = pixel_values[start_idx:end_idx]
1095
- single_grid_thw = image_grid_thw[i:i+1]
1096
-
1097
- # Use vision model directly
1098
- single_embeds, single_deepstack = vision_model(single_pixel_values, single_grid_thw)
1099
-
1100
- # Split based on grid dimensions
1101
- if single_grid_thw is not None:
1102
- split_sizes = (mx.prod(single_grid_thw, axis=-1) // (vision_model.visual.spatial_merge_size ** 2)).tolist()
1103
- split_indices = []
1104
- cumsum = 0
1105
- for size in split_sizes[:-1]:
1106
- cumsum += size
1107
- split_indices.append(cumsum)
1108
-
1109
- if split_indices:
1110
- single_embeds = mx.split(single_embeds, split_indices)
1111
- else:
1112
- single_embeds = [single_embeds]
1113
-
1114
- image_embeds_list.extend(single_embeds)
1115
-
1116
- # Collect deepstack embeddings
1117
- if i == 0:
1118
- all_deepstack_embeds = single_deepstack
1119
- else:
1120
- # Concatenate deepstack embeddings from different images
1121
- for j in range(len(all_deepstack_embeds)):
1122
- all_deepstack_embeds[j] = mx.concatenate([all_deepstack_embeds[j], single_deepstack[j]], axis=0)
1123
-
1124
- deepstack_visual_embeds = all_deepstack_embeds
1125
-
1126
- # Concatenate all image embeddings for processing
1127
- image_embeds = mx.concatenate(image_embeds_list, axis=0)
1128
-
1129
- # Find all image token positions
1130
- image_token_id = 151655 # Default image token ID
1131
- image_mask = (input_ids.squeeze(0) == image_token_id)
1132
- image_mask_np = np.array(image_mask)
1133
- image_token_positions = np.where(image_mask_np)[0]
1134
-
1135
- # Verify we have the correct number of image tokens
1136
- expected_total_tokens = sum(embed.shape[0] for embed in image_embeds_list)
1137
- assert len(image_token_positions) == expected_total_tokens, f"Expected {expected_total_tokens} image tokens, got {len(image_token_positions)}"
1138
-
1139
- # Replace image tokens with image embeddings
1140
- seq_len = inputs_embeds.shape[0]
1141
- result = inputs_embeds
1142
-
1143
- # Replace image tokens with image embeddings sequentially
1144
- embed_idx = 0
1145
- for img_embed in image_embeds_list:
1146
- for patch_idx in range(img_embed.shape[0]):
1147
- token_pos = image_token_positions[embed_idx]
1148
- pos_mask = mx.arange(seq_len) == token_pos
1149
- result = mx.where(
1150
- mx.expand_dims(pos_mask, axis=-1),
1151
- mx.expand_dims(img_embed[patch_idx], axis=0).astype(inputs_embeds.dtype),
1152
- result
1153
- )
1154
- embed_idx += 1
1155
-
1156
- inputs_embeds = result
1157
- position_ids, rope_deltas = llm_model.get_rope_index(input_ids, image_grid_thw)
1158
- cos, sin = llm_model.language_model.rotary_emb(inputs_embeds, position_ids)
1159
- if inputs_embeds.ndim == 2:
1160
- inputs_embeds = mx.expand_dims(inputs_embeds, axis=0)
1161
-
1162
- if image_mask is not None:
1163
- visual_pos_masks = image_mask
1164
-
1165
- return inputs_embeds, deepstack_visual_embeds, visual_pos_masks, cos, sin, rope_deltas
1166
-
1167
-
1168
- # Legacy Model wrapper (for backward compatibility)
1169
- class Model(nn.Module):
1170
- def __init__(self, args: ModelArgs):
1171
- super().__init__()
1172
- self.args = args
1173
- self.model = Qwen3VLModel(args)
1174
- if not args.text_config.tie_word_embeddings:
1175
- self.lm_head = nn.Linear(args.text_config.hidden_size, args.text_config.vocab_size, bias=False)
1176
-
1177
- def __call__(
1178
- self,
1179
- inputs: mx.array = None,
1180
- mask: mx.array = None,
1181
- cache=None,
1182
- inputs_embeds: Optional[mx.array] = None,
1183
- pixel_values: Optional[mx.array] = None,
1184
- image_grid_thw: Optional[mx.array] = None,
1185
- visual_pos_masks: Optional[mx.array] = None,
1186
- deepstack_visual_embeds: Optional[List[mx.array]] = None,
1187
- cos: Optional[mx.array] = None,
1188
- sin: Optional[mx.array] = None,
1189
- rope_deltas: Optional[mx.array] = None,
1190
- ):
1191
- out = self.model(
1192
- input_ids=inputs,
1193
- inputs_embeds=inputs_embeds,
1194
- attention_mask=mask,
1195
- cache=cache,
1196
- pixel_values=pixel_values,
1197
- image_grid_thw=image_grid_thw,
1198
- visual_pos_masks=visual_pos_masks,
1199
- deepstack_visual_embeds=deepstack_visual_embeds,
1200
- cos=cos,
1201
- sin=sin,
1202
- rope_deltas=rope_deltas,
1203
- )
1204
- if self.args.text_config.tie_word_embeddings:
1205
- return self.model.language_model.embed_tokens.as_linear(out)
1206
- else:
1207
- return self.lm_head(out)
1208
-
1209
- def sanitize(self, weights):
1210
- # Remove any unnecessary weights
1211
- sanitized = {}
1212
- for k, v in weights.items():
1213
- sanitized[k] = v
1214
-
1215
- # Handle tied embeddings - remove lm_head if using tied embeddings
1216
- if self.args.text_config.tie_word_embeddings:
1217
- sanitized.pop("lm_head.weight", None)
1218
-
1219
- return sanitized
1220
-
1221
- @property
1222
- def layers(self):
1223
- return self.model.language_model.layers