nexaai 1.0.19rc7__cp310-cp310-macosx_14_0_universal2.whl → 1.0.19rc9__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 (200) 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/mlx_backend/vlm/generate_qwen3_vl.py +14 -31
  5. nexaai/mlx_backend/vlm/generate_qwen3_vl_moe.py +15 -32
  6. nexaai/mlx_backend/vlm/modeling/models/qwen3_vl/qwen3vl.py +7 -23
  7. nexaai/mlx_backend/vlm/modeling/models/qwen3vl_moe/qwen3vl_moe.py +8 -24
  8. {nexaai-1.0.19rc7.dist-info → nexaai-1.0.19rc9.dist-info}/METADATA +1 -1
  9. {nexaai-1.0.19rc7.dist-info → nexaai-1.0.19rc9.dist-info}/RECORD +11 -200
  10. nexaai/binds/nexa_mlx/py-lib/asr/__init__.py +0 -12
  11. nexaai/binds/nexa_mlx/py-lib/asr/interface.py +0 -122
  12. nexaai/binds/nexa_mlx/py-lib/common/__init__.py +0 -0
  13. nexaai/binds/nexa_mlx/py-lib/common/utils.py +0 -25
  14. nexaai/binds/nexa_mlx/py-lib/cv/__init__.py +0 -0
  15. nexaai/binds/nexa_mlx/py-lib/cv/generate.py +0 -195
  16. nexaai/binds/nexa_mlx/py-lib/cv/interface.py +0 -151
  17. nexaai/binds/nexa_mlx/py-lib/cv/main.py +0 -81
  18. nexaai/binds/nexa_mlx/py-lib/cv/modeling/pp_ocr_v4.py +0 -1736
  19. nexaai/binds/nexa_mlx/py-lib/embedding/__init__.py +0 -0
  20. nexaai/binds/nexa_mlx/py-lib/embedding/generate.py +0 -333
  21. nexaai/binds/nexa_mlx/py-lib/embedding/interface.py +0 -617
  22. nexaai/binds/nexa_mlx/py-lib/embedding/main.py +0 -173
  23. nexaai/binds/nexa_mlx/py-lib/embedding/modeling/__init__.py +0 -0
  24. nexaai/binds/nexa_mlx/py-lib/embedding/modeling/nexa_jina_v2.py +0 -399
  25. nexaai/binds/nexa_mlx/py-lib/image_gen/__init__.py +0 -1
  26. nexaai/binds/nexa_mlx/py-lib/image_gen/generate_sd.py +0 -244
  27. nexaai/binds/nexa_mlx/py-lib/image_gen/interface.py +0 -82
  28. nexaai/binds/nexa_mlx/py-lib/image_gen/main.py +0 -281
  29. nexaai/binds/nexa_mlx/py-lib/image_gen/stable_diffusion/__init__.py +0 -306
  30. nexaai/binds/nexa_mlx/py-lib/image_gen/stable_diffusion/clip.py +0 -116
  31. nexaai/binds/nexa_mlx/py-lib/image_gen/stable_diffusion/config.py +0 -65
  32. nexaai/binds/nexa_mlx/py-lib/image_gen/stable_diffusion/model_io.py +0 -386
  33. nexaai/binds/nexa_mlx/py-lib/image_gen/stable_diffusion/sampler.py +0 -105
  34. nexaai/binds/nexa_mlx/py-lib/image_gen/stable_diffusion/tokenizer.py +0 -100
  35. nexaai/binds/nexa_mlx/py-lib/image_gen/stable_diffusion/unet.py +0 -460
  36. nexaai/binds/nexa_mlx/py-lib/image_gen/stable_diffusion/vae.py +0 -274
  37. nexaai/binds/nexa_mlx/py-lib/llm/__init__.py +0 -0
  38. nexaai/binds/nexa_mlx/py-lib/llm/generate.py +0 -149
  39. nexaai/binds/nexa_mlx/py-lib/llm/interface.py +0 -764
  40. nexaai/binds/nexa_mlx/py-lib/llm/main.py +0 -68
  41. nexaai/binds/nexa_mlx/py-lib/rerank/__init__.py +0 -0
  42. nexaai/binds/nexa_mlx/py-lib/rerank/generate.py +0 -174
  43. nexaai/binds/nexa_mlx/py-lib/rerank/interface.py +0 -287
  44. nexaai/binds/nexa_mlx/py-lib/rerank/main.py +0 -127
  45. nexaai/binds/nexa_mlx/py-lib/rerank/modeling/__init__.py +0 -0
  46. nexaai/binds/nexa_mlx/py-lib/rerank/modeling/nexa_jina_rerank.py +0 -330
  47. nexaai/binds/nexa_mlx/py-lib/sd/__init__.py +0 -1
  48. nexaai/binds/nexa_mlx/py-lib/sd/interface.py +0 -362
  49. nexaai/binds/nexa_mlx/py-lib/sd/main.py +0 -286
  50. nexaai/binds/nexa_mlx/py-lib/sd/modeling/__init__.py +0 -306
  51. nexaai/binds/nexa_mlx/py-lib/sd/modeling/clip.py +0 -116
  52. nexaai/binds/nexa_mlx/py-lib/sd/modeling/config.py +0 -65
  53. nexaai/binds/nexa_mlx/py-lib/sd/modeling/model_io.py +0 -385
  54. nexaai/binds/nexa_mlx/py-lib/sd/modeling/sampler.py +0 -105
  55. nexaai/binds/nexa_mlx/py-lib/sd/modeling/tokenizer.py +0 -100
  56. nexaai/binds/nexa_mlx/py-lib/sd/modeling/unet.py +0 -460
  57. nexaai/binds/nexa_mlx/py-lib/sd/modeling/vae.py +0 -274
  58. nexaai/binds/nexa_mlx/py-lib/tts/__init__.py +0 -12
  59. nexaai/binds/nexa_mlx/py-lib/tts/interface.py +0 -276
  60. nexaai/binds/nexa_mlx/py-lib/vlm/__init__.py +0 -3
  61. nexaai/binds/nexa_mlx/py-lib/vlm/generate.py +0 -572
  62. nexaai/binds/nexa_mlx/py-lib/vlm/generate_qwen3_vl.py +0 -294
  63. nexaai/binds/nexa_mlx/py-lib/vlm/generate_qwen3_vl_moe.py +0 -276
  64. nexaai/binds/nexa_mlx/py-lib/vlm/interface.py +0 -504
  65. nexaai/binds/nexa_mlx/py-lib/vlm/main.py +0 -320
  66. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/__init__.py +0 -0
  67. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/convert.py +0 -68
  68. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/__init__.py +0 -0
  69. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/aya_vision/__init__.py +0 -8
  70. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/aya_vision/aya_vision.py +0 -193
  71. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/aya_vision/interpolate.py +0 -186
  72. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/aya_vision/language.py +0 -233
  73. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/aya_vision/vision.py +0 -503
  74. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/base.py +0 -202
  75. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/cache.py +0 -230
  76. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/deepseek_vl_v2/__init__.py +0 -10
  77. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/deepseek_vl_v2/conversation.py +0 -264
  78. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/deepseek_vl_v2/deepseek_vl_v2.py +0 -472
  79. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/deepseek_vl_v2/language.py +0 -591
  80. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/deepseek_vl_v2/processing_deepsek_vl_v2.py +0 -526
  81. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/deepseek_vl_v2/vision.py +0 -356
  82. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/florence2/__init__.py +0 -8
  83. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/florence2/florence2.py +0 -366
  84. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/florence2/language.py +0 -488
  85. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/florence2/vision.py +0 -591
  86. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3/__init__.py +0 -8
  87. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3/gemma3.py +0 -213
  88. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3/language.py +0 -315
  89. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3/vision.py +0 -238
  90. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3n/__init__.py +0 -2
  91. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3n/audio.py +0 -1038
  92. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3n/config.py +0 -139
  93. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3n/gemma3n.py +0 -322
  94. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3n/language.py +0 -629
  95. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3n/vision.py +0 -1022
  96. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/idefics2/__init__.py +0 -9
  97. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/idefics2/idefics2.py +0 -294
  98. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/idefics2/language.py +0 -191
  99. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/idefics2/vision.py +0 -267
  100. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/idefics3/__init__.py +0 -8
  101. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/idefics3/idefics3.py +0 -175
  102. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/idefics3/language.py +0 -192
  103. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/idefics3/vision.py +0 -233
  104. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/internvl_chat/__init__.py +0 -9
  105. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/internvl_chat/internvl_chat.py +0 -140
  106. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/internvl_chat/language.py +0 -220
  107. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/internvl_chat/processor.py +0 -393
  108. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/internvl_chat/vision.py +0 -293
  109. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/kernels.py +0 -307
  110. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/kimi_vl/__init__.py +0 -8
  111. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/kimi_vl/kimi_vl.py +0 -143
  112. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/kimi_vl/language.py +0 -509
  113. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/kimi_vl/vision.py +0 -522
  114. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llama4/__init__.py +0 -8
  115. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llama4/language.py +0 -386
  116. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llama4/llama4.py +0 -138
  117. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llama4/vision.py +0 -560
  118. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava/__init__.py +0 -8
  119. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava/language.py +0 -240
  120. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava/llava.py +0 -153
  121. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava/vision.py +0 -259
  122. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava_bunny/__init__.py +0 -9
  123. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava_bunny/language.py +0 -236
  124. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava_bunny/llava_bunny.py +0 -256
  125. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava_bunny/vision.py +0 -303
  126. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava_next/__init__.py +0 -8
  127. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava_next/language.py +0 -230
  128. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava_next/llava_next.py +0 -160
  129. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava_next/vision.py +0 -243
  130. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/mistral3/__init__.py +0 -8
  131. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/mistral3/mistral3.py +0 -283
  132. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/mllama/__init__.py +0 -8
  133. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/mllama/language.py +0 -416
  134. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/mllama/mllama.py +0 -172
  135. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/mllama/vision.py +0 -499
  136. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/molmo/__init__.py +0 -8
  137. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/molmo/language.py +0 -243
  138. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/molmo/molmo.py +0 -133
  139. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/molmo/vision.py +0 -465
  140. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/multi_modality/__init__.py +0 -10
  141. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/multi_modality/language.py +0 -230
  142. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/multi_modality/multi_modality.py +0 -385
  143. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/multi_modality/sam.py +0 -557
  144. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/multi_modality/vision.py +0 -526
  145. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/paligemma/__init__.py +0 -8
  146. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/paligemma/language.py +0 -282
  147. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/paligemma/paligemma.py +0 -160
  148. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/paligemma/vision.py +0 -242
  149. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/phi3_v/__init__.py +0 -8
  150. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/phi3_v/language.py +0 -21
  151. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/phi3_v/phi3_v.py +0 -243
  152. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/phi3_v/su_rope.py +0 -71
  153. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/phi3_v/vision.py +0 -324
  154. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/pixtral/__init__.py +0 -8
  155. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/pixtral/language.py +0 -229
  156. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/pixtral/pixtral.py +0 -161
  157. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/pixtral/vision.py +0 -320
  158. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_5_vl/__init__.py +0 -2
  159. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_5_vl/config.py +0 -108
  160. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_5_vl/language.py +0 -490
  161. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_5_vl/qwen2_5_vl.py +0 -168
  162. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_5_vl/vision.py +0 -414
  163. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_vl/__init__.py +0 -2
  164. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_vl/config.py +0 -104
  165. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_vl/language.py +0 -490
  166. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_vl/qwen2_vl.py +0 -167
  167. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_vl/vision.py +0 -312
  168. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/llm_common/__init__.py +0 -0
  169. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/llm_common/base.py +0 -117
  170. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/llm_common/cache.py +0 -531
  171. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/llm_common/generate.py +0 -701
  172. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/llm_common/rope_utils.py +0 -255
  173. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/llm_common/sample_utils.py +0 -303
  174. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/llm_common/tokenizer_utils.py +0 -407
  175. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/processor.py +0 -476
  176. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/qwen3vl.py +0 -1223
  177. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/llm_common/__init__.py +0 -0
  178. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/llm_common/base.py +0 -117
  179. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/llm_common/cache.py +0 -531
  180. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/llm_common/generate.py +0 -701
  181. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/llm_common/rope_utils.py +0 -255
  182. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/llm_common/sample_utils.py +0 -303
  183. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/llm_common/tokenizer_utils.py +0 -407
  184. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/processor.py +0 -476
  185. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/qwen3vl_moe.py +0 -1309
  186. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/switch_layers.py +0 -210
  187. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/smolvlm/__init__.py +0 -8
  188. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/smolvlm/smolvlm.py +0 -62
  189. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/processing_qwen2_5_vl.py +0 -209
  190. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/processing_qwen2_vl.py +0 -215
  191. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/prompt_utils.py +0 -474
  192. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/sample_utils.py +0 -39
  193. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/tokenizer_utils.py +0 -344
  194. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/trainer/__init__.py +0 -9
  195. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/trainer/lora.py +0 -70
  196. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/trainer/trainer.py +0 -296
  197. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/trainer/utils.py +0 -160
  198. nexaai/binds/nexa_mlx/py-lib/vlm/modeling/utils.py +0 -928
  199. {nexaai-1.0.19rc7.dist-info → nexaai-1.0.19rc9.dist-info}/WHEEL +0 -0
  200. {nexaai-1.0.19rc7.dist-info → nexaai-1.0.19rc9.dist-info}/top_level.txt +0 -0
@@ -1,557 +0,0 @@
1
- import copy
2
- from dataclasses import dataclass
3
- from typing import List, Optional, Tuple, Type, Union
4
-
5
- import mlx.core as mx
6
- import mlx.nn as nn
7
- import numpy as np
8
- from PIL import Image
9
- from PIL.Image import Resampling
10
-
11
-
12
- @dataclass
13
- class SAMViTCfg:
14
- image_size: Union[Tuple[int, int], int] = 1024
15
- width: int = 768
16
- layers: int = 12
17
- heads: int = 12
18
- patch_size: int = 16
19
- window_size: int = 14
20
- prompt_embed_dim: int = 256
21
- global_attn_indexes: Union[List[int], Tuple[int]] = (2, 5, 8, 11)
22
- downsample_channels: Union[List[int], Tuple[int]] = (512, 1024)
23
-
24
-
25
- class MLPBlock(nn.Module):
26
- def __init__(
27
- self,
28
- embedding_dim: int,
29
- mlp_dim: int,
30
- act: Type[nn.Module] = nn.GELU,
31
- ) -> None:
32
- super().__init__()
33
- self.lin1 = nn.Linear(embedding_dim, mlp_dim)
34
- self.lin2 = nn.Linear(mlp_dim, embedding_dim)
35
- self.act = act()
36
-
37
- def __call__(self, x: mx.array):
38
- return self.lin2(self.act(self.lin1(x)))
39
-
40
-
41
- def resize_image(image_np, new_size=(96, 96), order=1):
42
- """
43
- Resize an image with multiple channels using PIL.
44
-
45
- Args:
46
- image_np (numpy.ndarray): The input image array of shape (batch, channels, height, width).
47
- new_size (tuple): The target size as (height, width).
48
- order (int): The order of interpolation (used to determine resampling method).
49
-
50
- Returns:
51
- numpy.ndarray: The resized image array in the same format as input.
52
- """
53
- # Remove batch dimension
54
- image_np = np.array(image_np[0])
55
-
56
- # Get dimensions
57
- channels, height, width = image_np.shape
58
-
59
- # Choose interpolation method based on order parameter
60
- resample_method = Resampling.BILINEAR # Default to bilinear
61
- if order == 0:
62
- resample_method = Resampling.NEAREST
63
- elif order == 2 or order == 3:
64
- resample_method = Resampling.BICUBIC
65
-
66
- # Handle different channel configurations
67
- if channels == 1:
68
- # For single-channel images (grayscale)
69
- # Reshape to 2D array (height, width)
70
- image_2d = image_np.reshape(height, width)
71
-
72
- # Create PIL image - ensure proper mode and data type conversion
73
- pil_image = Image.fromarray(image_2d.astype(np.float32))
74
-
75
- # Resize using PIL (note: PIL takes width, height order)
76
- resized_pil = pil_image.resize(
77
- (new_size[1], new_size[0]), resample=resample_method
78
- )
79
-
80
- # Convert back to numpy array, reshape to add channel dimension
81
- resized_np = np.array(resized_pil).reshape((1, new_size[0], new_size[1]))
82
- else:
83
- # For multi-channel images, process each channel individually
84
- resized_channels = []
85
-
86
- for c in range(channels):
87
- channel_data = image_np[c]
88
- pil_channel = Image.fromarray(channel_data.astype(np.float32))
89
- resized_channel = pil_channel.resize(
90
- (new_size[1], new_size[0]), resample=resample_method
91
- )
92
- resized_channels.append(np.array(resized_channel))
93
-
94
- # Stack channels back together
95
- resized_np = np.stack(resized_channels, axis=0)
96
-
97
- # Add batch dimension back and convert to mx.array
98
- return mx.array(resized_np)[None, :]
99
-
100
-
101
- class SAMEncoder(nn.Module):
102
- def __init__(
103
- self,
104
- img_size: int = 1024,
105
- patch_size: int = 16,
106
- in_chans: int = 3,
107
- embed_dim: int = 768,
108
- depth: int = 12,
109
- num_heads: int = 12,
110
- mlp_ratio: float = 4.0,
111
- out_chans: int = 256,
112
- qkv_bias: bool = True,
113
- norm_layer: Type[nn.Module] = nn.LayerNorm,
114
- act_layer: Type[nn.Module] = nn.GELU,
115
- use_abs_pos: bool = True,
116
- use_rel_pos: bool = True,
117
- rel_pos_zero_init: bool = True,
118
- window_size: int = 14,
119
- global_attn_indexes: Tuple[int, ...] = (2, 5, 8, 11),
120
- downsample_channels: Tuple[int, ...] = (512, 1024),
121
- ) -> None:
122
- """
123
- Args:
124
- img_size (int): Input image size.
125
- patch_size (int): Patch size.
126
- in_chans (int): Number of input image channels.
127
- embed_dim (int): Patch embedding dimension.
128
- depth (int): Depth of ViT.
129
- num_heads (int): Number of attention heads in each ViT block.
130
- mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
131
- qkv_bias (bool): If True, add a learnable bias to query, key, value.
132
- norm_layer (nn.Module): Normalization layer.
133
- act_layer (nn.Module): Activation layer.
134
- use_abs_pos (bool): If True, use absolute positional embeddings.
135
- use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
136
- rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
137
- window_size (int): Window size for window attention blocks.
138
- global_attn_indexes (list): Indexes for blocks using global attention.
139
- downsample_channels (list): Channels for downsampling layers.
140
- """
141
- super().__init__()
142
- self.img_size = img_size
143
-
144
- self.patch_embed = PatchEmbed(
145
- kernel_size=(patch_size, patch_size),
146
- stride=(patch_size, patch_size),
147
- in_chans=in_chans,
148
- embed_dim=embed_dim,
149
- )
150
-
151
- if use_abs_pos:
152
- # Initialize absolute positional embedding with pretrain image size.
153
- self.pos_embed = mx.zeros(
154
- (img_size // patch_size, img_size // patch_size, embed_dim)
155
- )[None, :]
156
-
157
- self.blocks = []
158
- for i in range(depth):
159
- block = Block(
160
- dim=embed_dim,
161
- num_heads=num_heads,
162
- mlp_ratio=mlp_ratio,
163
- qkv_bias=qkv_bias,
164
- norm_layer=norm_layer,
165
- act_layer=act_layer,
166
- use_rel_pos=use_rel_pos,
167
- rel_pos_zero_init=rel_pos_zero_init,
168
- window_size=window_size if i not in global_attn_indexes else 0,
169
- input_size=(img_size // patch_size, img_size // patch_size),
170
- )
171
- self.blocks.append(block)
172
-
173
- self.neck = [
174
- nn.Conv2d(
175
- embed_dim,
176
- out_chans,
177
- kernel_size=1,
178
- bias=False,
179
- ),
180
- nn.LayerNorm(out_chans),
181
- nn.Conv2d(
182
- out_chans,
183
- out_chans,
184
- kernel_size=3,
185
- padding=1,
186
- bias=False,
187
- ),
188
- nn.LayerNorm(out_chans),
189
- ]
190
-
191
- in_channels = out_chans
192
- self.downsamples = []
193
- for i in range(len(downsample_channels)):
194
- out_channels = downsample_channels[i]
195
- self.downsamples.append(
196
- nn.Conv2d(
197
- in_channels,
198
- out_channels,
199
- kernel_size=3,
200
- stride=2,
201
- padding=1,
202
- bias=False,
203
- )
204
- )
205
- in_channels = out_channels
206
-
207
- self.sam_hd = True
208
- if self.sam_hd:
209
- self.hd_alpha_downsamples = mx.zeros((1))
210
- self.neck_hd = copy.deepcopy(self.neck)
211
-
212
- def __call__(self, x: mx.array):
213
- x = self.patch_embed(x)
214
- if self.pos_embed is not None:
215
- x += self.pos_embed
216
-
217
- global_features = []
218
- for _, blk in enumerate(self.blocks):
219
- x = blk(x)
220
- if self.sam_hd and blk.window_size == 0:
221
- global_features.append(x)
222
-
223
- for _, n in enumerate(self.neck):
224
- x = n(x)
225
-
226
- x = x.transpose(0, 3, 1, 2)
227
- x = resize_image(x)
228
-
229
- x = x.transpose(0, 2, 3, 1)
230
-
231
- for _, downsample in enumerate(self.downsamples):
232
- x = downsample(x)
233
-
234
- if self.sam_hd:
235
- first_global_feature = global_features[0]
236
- for _, n_hd in enumerate(self.neck_hd):
237
- first_global_feature = n_hd(first_global_feature)
238
-
239
- first_global_feature = first_global_feature.transpose(0, 3, 1, 2)
240
-
241
- first_global_feature = resize_image(first_global_feature)
242
-
243
- first_global_feature = first_global_feature.transpose(0, 2, 3, 1)
244
- for _, downsample in enumerate(self.downsamples):
245
- first_global_feature = downsample(first_global_feature)
246
-
247
- x = x + first_global_feature * self.hd_alpha_downsamples
248
-
249
- return x
250
-
251
-
252
- class Block(nn.Module):
253
- """Transformer blocks with support of window attention and residual propagation blocks"""
254
-
255
- def __init__(
256
- self,
257
- dim: int,
258
- num_heads: int,
259
- mlp_ratio: float = 4.0,
260
- qkv_bias: bool = True,
261
- norm_layer: Type[nn.Module] = nn.LayerNorm,
262
- act_layer: Type[nn.Module] = nn.GELU,
263
- use_rel_pos: bool = False,
264
- rel_pos_zero_init: bool = True,
265
- window_size: int = 0,
266
- input_size: Optional[Tuple[int, int]] = None,
267
- ) -> None:
268
- """
269
- Args:
270
- dim (int): Number of input channels.
271
- num_heads (int): Number of attention heads in each ViT block.
272
- mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
273
- qkv_bias (bool): If True, add a learnable bias to query, key, value.
274
- norm_layer (nn.Module): Normalization layer.
275
- act_layer (nn.Module): Activation layer.
276
- use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
277
- rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
278
- window_size (int): Window size for window attention blocks. If it equals 0, then
279
- use global attention.
280
- input_size (tuple(int, int) or None): Input resolution for calculating the relative
281
- positional parameter size.
282
- """
283
- super().__init__()
284
- self.norm1 = norm_layer(dim)
285
- self.attn = Attention(
286
- dim,
287
- num_heads=num_heads,
288
- qkv_bias=qkv_bias,
289
- use_rel_pos=use_rel_pos,
290
- rel_pos_zero_init=rel_pos_zero_init,
291
- input_size=input_size if window_size == 0 else (window_size, window_size),
292
- )
293
-
294
- self.norm2 = norm_layer(dim)
295
- self.mlp = MLPBlock(
296
- embedding_dim=dim, mlp_dim=int(dim * mlp_ratio), act=act_layer
297
- )
298
-
299
- self.window_size = window_size
300
-
301
- def __call__(self, x: mx.array):
302
- shortcut = x
303
- x = self.norm1(x)
304
- # Window partition
305
- if self.window_size > 0:
306
- H, W = x.shape[1], x.shape[2]
307
- x, pad_hw = window_partition(x, self.window_size)
308
-
309
- x = self.attn(x)
310
- # Reverse window partition
311
- if self.window_size > 0:
312
- x = window_unpartition(x, self.window_size, pad_hw, (H, W))
313
-
314
- x = shortcut + x
315
- x = x + self.mlp(self.norm2(x))
316
-
317
- return x
318
-
319
-
320
- class Attention(nn.Module):
321
- """Multi-head Attention block with relative position embeddings."""
322
-
323
- def __init__(
324
- self,
325
- dim: int,
326
- num_heads: int = 8,
327
- qkv_bias: bool = True,
328
- use_rel_pos: bool = False,
329
- rel_pos_zero_init: bool = True,
330
- input_size: Optional[Tuple[int, int]] = None,
331
- ) -> None:
332
- """
333
- Args:
334
- dim (int): Number of input channels.
335
- num_heads (int): Number of attention heads.
336
- qkv_bias (bool): If True, add a learnable bias to query, key, value.
337
- rel_pos (bool): If True, add relative positional embeddings to the attention map.
338
- rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
339
- input_size (tuple(int, int) or None): Input resolution for calculating the relative
340
- positional parameter size.
341
- """
342
- super().__init__()
343
- self.num_heads = num_heads
344
- head_dim = dim // num_heads
345
- self.scale = head_dim**-0.5
346
-
347
- self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
348
- self.proj = nn.Linear(dim, dim)
349
-
350
- self.use_rel_pos = use_rel_pos
351
- if self.use_rel_pos:
352
- assert (
353
- input_size is not None
354
- ), "Input size must be provided if using relative positional encoding."
355
- # initialize relative positional embeddings
356
-
357
- self.rel_pos_h = mx.zeros((2 * input_size[0] - 1, head_dim))
358
- self.rel_pos_w = mx.zeros((2 * input_size[1] - 1, head_dim))
359
-
360
- def __call__(self, x: mx.array):
361
- B, H, W, _ = x.shape
362
- x = mx.array(x)
363
- # qkv with shape (3, B, nHead, H * W, C)
364
- qkv = (
365
- self.qkv(x)
366
- .reshape(B, H * W, 3, self.num_heads, -1)
367
- .transpose(2, 0, 3, 1, 4)
368
- )
369
- # q, k, v with shape (B * nHead, H * W, C)
370
- q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1)
371
-
372
- def do_attention(q, k, v):
373
- attn = (q * self.scale) @ k.transpose(0, -1, -2)
374
- if self.use_rel_pos:
375
- attn = add_decomposed_rel_pos(
376
- attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W)
377
- )
378
-
379
- attn = mx.softmax(attn, axis=-1)
380
- x = (
381
- (attn @ v)
382
- .reshape(B, self.num_heads, H, W, -1)
383
- .transpose(0, 2, 3, 1, 4)
384
- .reshape(B, H, W, -1)
385
- )
386
-
387
- return x
388
-
389
- x = do_attention(q, k, v)
390
- x = self.proj(x)
391
-
392
- return x
393
-
394
-
395
- def window_partition(
396
- x: np.ndarray, window_size: int
397
- ) -> Tuple[np.ndarray, Tuple[int, int]]:
398
- """
399
- Partition into non-overlapping windows with padding if needed.
400
- Args:
401
- x (ndarray): input tokens with [B, H, W, C].
402
- window_size (int): window size.
403
-
404
- Returns:
405
- windows: windows after partition with [B * num_windows, window_size, window_size, C].
406
- (Hp, Wp): padded height and width before partition
407
- """
408
- B, H, W, C = x.shape
409
-
410
- pad_h = (window_size - H % window_size) % window_size
411
- pad_w = (window_size - W % window_size) % window_size
412
- if pad_h > 0 or pad_w > 0:
413
- x = np.pad(x, ((0, 0), (0, pad_h), (0, pad_w), (0, 0)))
414
- Hp, Wp = H + pad_h, W + pad_w
415
-
416
- x = x.reshape(B, Hp // window_size, window_size, Wp // window_size, window_size, C)
417
- windows = x.transpose(0, 1, 3, 2, 4, 5).reshape(-1, window_size, window_size, C)
418
- return windows, (Hp, Wp)
419
-
420
-
421
- def window_unpartition(
422
- windows: np.ndarray,
423
- window_size: int,
424
- pad_hw: Tuple[int, int],
425
- hw: Tuple[int, int],
426
- ):
427
- """
428
- Window unpartition into original sequences and removing padding.
429
- Args:
430
- windows (ndarray): input tokens with [B * num_windows, window_size, window_size, C].
431
- window_size (int): window size.
432
- pad_hw (Tuple): padded height and width (Hp, Wp).
433
- hw (Tuple): original height and width (H, W) before padding.
434
-
435
- Returns:
436
- x: unpartitioned sequences with [B, H, W, C].
437
- """
438
- Hp, Wp = pad_hw
439
- H, W = hw
440
- B = windows.shape[0] // (Hp * Wp // window_size // window_size)
441
- x = windows.reshape(
442
- B, Hp // window_size, Wp // window_size, window_size, window_size, -1
443
- )
444
- x = x.transpose(0, 1, 3, 2, 4, 5).reshape(B, Hp, Wp, -1)
445
-
446
- if Hp > H or Wp > W:
447
- x = x[:, :H, :W, :]
448
- return x
449
-
450
-
451
- def get_rel_pos(q_size: int, k_size: int, rel_pos: np.ndarray) -> np.ndarray:
452
- """
453
- Get relative positional embeddings according to the relative positions of
454
- query and key sizes.
455
- Args:
456
- q_size (int): size of query q.
457
- k_size (int): size of key k.
458
- rel_pos (ndarray): relative position embeddings (L, C).
459
-
460
- Returns:
461
- Extracted positional embeddings according to relative positions.
462
- """
463
- rel_pos = np.array(rel_pos)
464
- max_rel_dist = int(2 * max(q_size, k_size) - 1)
465
- # Interpolate rel pos if needed.
466
- if rel_pos.shape[0] != max_rel_dist:
467
- # Interpolate rel pos.
468
- rel_pos_resized = np.expand_dims(rel_pos, axis=0)
469
- rel_pos_resized = np.transpose(rel_pos_resized, (0, 2, 1))
470
- rel_pos_resized = np.interp(
471
- np.linspace(0, max_rel_dist - 1, num=max_rel_dist),
472
- np.arange(rel_pos.shape[0]),
473
- rel_pos_resized[0],
474
- )
475
- rel_pos_resized = np.transpose(rel_pos_resized, (1, 0))
476
- else:
477
- rel_pos_resized = rel_pos
478
-
479
- # Scale the coords with short length if shapes for q and k are different.
480
- q_coords = np.arange(q_size)[:, np.newaxis] * max(k_size / q_size, 1.0)
481
- k_coords = np.arange(k_size)[np.newaxis, :] * max(q_size / k_size, 1.0)
482
- relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0)
483
- relative_coords = relative_coords.astype(np.int64)
484
- return rel_pos_resized[relative_coords]
485
-
486
-
487
- def add_decomposed_rel_pos(
488
- attn: np.ndarray,
489
- q: np.ndarray,
490
- rel_pos_h: np.ndarray,
491
- rel_pos_w: np.ndarray,
492
- q_size: Tuple[int, int],
493
- k_size: Tuple[int, int],
494
- ) -> np.ndarray:
495
- """
496
- Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`.
497
- https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py # noqa B950
498
- Args:
499
- attn (ndarray): attention map.
500
- q (ndarray): query q in the attention layer with shape (B, q_h * q_w, C).
501
- rel_pos_h (ndarray): relative position embeddings (Lh, C) for height axis.
502
- rel_pos_w (ndarray): relative position embeddings (Lw, C) for width axis.
503
- q_size (Tuple): spatial sequence size of query q with (q_h, q_w).
504
- k_size (Tuple): spatial sequence size of key k with (k_h, k_w).
505
-
506
- Returns:
507
- attn (ndarray): attention map with added relative positional embeddings.
508
- """
509
- q_h, q_w = q_size
510
- k_h, k_w = k_size
511
- Rh = get_rel_pos(q_h, k_h, rel_pos_h)
512
- Rw = get_rel_pos(q_w, k_w, rel_pos_w)
513
-
514
- B, _, dim = q.shape
515
- r_q = q.reshape(B, q_h, q_w, dim)
516
-
517
- rel_h = np.einsum("bhwc,hkc->bhwk", r_q, Rh)
518
- rel_w = np.einsum("bhwc,wkc->bhwk", r_q, Rw)
519
-
520
- attn = (
521
- attn.reshape(B, q_h, q_w, k_h, k_w)
522
- + rel_h[:, :, :, :, np.newaxis]
523
- + rel_w[:, :, :, np.newaxis, :]
524
- ).reshape(B, q_h * q_w, k_h * k_w)
525
-
526
- return attn
527
-
528
-
529
- class PatchEmbed(nn.Module):
530
- """
531
- Image to Patch Embedding.
532
- """
533
-
534
- def __init__(
535
- self,
536
- kernel_size: Tuple[int, int] = (16, 16),
537
- stride: Tuple[int, int] = (16, 16),
538
- in_chans: int = 3,
539
- embed_dim: int = 768,
540
- ) -> None:
541
- """
542
- Args:
543
- kernel_size (Tuple): kernel size of the projection layer.
544
- stride (Tuple): stride of the projection layer.
545
- padding (Tuple): padding size of the projection layer.
546
- in_chans (int): Number of input image channels.
547
- embed_dim (int): Patch embedding dimension.
548
- """
549
- super().__init__()
550
-
551
- self.proj = nn.Conv2d(
552
- in_chans, embed_dim, kernel_size=kernel_size, stride=stride
553
- )
554
-
555
- def __call__(self, x: mx.array):
556
- x = self.proj(x)
557
- return x