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.
- nexaai/_stub.cpython-310-darwin.so +0 -0
- nexaai/_version.py +1 -1
- nexaai/binds/libnexa_bridge.dylib +0 -0
- {nexaai-1.0.19rc7.dist-info → nexaai-1.0.19rc8.dist-info}/METADATA +1 -1
- {nexaai-1.0.19rc7.dist-info → nexaai-1.0.19rc8.dist-info}/RECORD +7 -196
- nexaai/binds/nexa_mlx/py-lib/asr/__init__.py +0 -12
- nexaai/binds/nexa_mlx/py-lib/asr/interface.py +0 -122
- nexaai/binds/nexa_mlx/py-lib/common/__init__.py +0 -0
- nexaai/binds/nexa_mlx/py-lib/common/utils.py +0 -25
- nexaai/binds/nexa_mlx/py-lib/cv/__init__.py +0 -0
- nexaai/binds/nexa_mlx/py-lib/cv/generate.py +0 -195
- nexaai/binds/nexa_mlx/py-lib/cv/interface.py +0 -151
- nexaai/binds/nexa_mlx/py-lib/cv/main.py +0 -81
- nexaai/binds/nexa_mlx/py-lib/cv/modeling/pp_ocr_v4.py +0 -1736
- nexaai/binds/nexa_mlx/py-lib/embedding/__init__.py +0 -0
- nexaai/binds/nexa_mlx/py-lib/embedding/generate.py +0 -333
- nexaai/binds/nexa_mlx/py-lib/embedding/interface.py +0 -617
- nexaai/binds/nexa_mlx/py-lib/embedding/main.py +0 -173
- nexaai/binds/nexa_mlx/py-lib/embedding/modeling/__init__.py +0 -0
- nexaai/binds/nexa_mlx/py-lib/embedding/modeling/nexa_jina_v2.py +0 -399
- nexaai/binds/nexa_mlx/py-lib/image_gen/__init__.py +0 -1
- nexaai/binds/nexa_mlx/py-lib/image_gen/generate_sd.py +0 -244
- nexaai/binds/nexa_mlx/py-lib/image_gen/interface.py +0 -82
- nexaai/binds/nexa_mlx/py-lib/image_gen/main.py +0 -281
- nexaai/binds/nexa_mlx/py-lib/image_gen/stable_diffusion/__init__.py +0 -306
- nexaai/binds/nexa_mlx/py-lib/image_gen/stable_diffusion/clip.py +0 -116
- nexaai/binds/nexa_mlx/py-lib/image_gen/stable_diffusion/config.py +0 -65
- nexaai/binds/nexa_mlx/py-lib/image_gen/stable_diffusion/model_io.py +0 -386
- nexaai/binds/nexa_mlx/py-lib/image_gen/stable_diffusion/sampler.py +0 -105
- nexaai/binds/nexa_mlx/py-lib/image_gen/stable_diffusion/tokenizer.py +0 -100
- nexaai/binds/nexa_mlx/py-lib/image_gen/stable_diffusion/unet.py +0 -460
- nexaai/binds/nexa_mlx/py-lib/image_gen/stable_diffusion/vae.py +0 -274
- nexaai/binds/nexa_mlx/py-lib/llm/__init__.py +0 -0
- nexaai/binds/nexa_mlx/py-lib/llm/generate.py +0 -149
- nexaai/binds/nexa_mlx/py-lib/llm/interface.py +0 -764
- nexaai/binds/nexa_mlx/py-lib/llm/main.py +0 -68
- nexaai/binds/nexa_mlx/py-lib/rerank/__init__.py +0 -0
- nexaai/binds/nexa_mlx/py-lib/rerank/generate.py +0 -174
- nexaai/binds/nexa_mlx/py-lib/rerank/interface.py +0 -287
- nexaai/binds/nexa_mlx/py-lib/rerank/main.py +0 -127
- nexaai/binds/nexa_mlx/py-lib/rerank/modeling/__init__.py +0 -0
- nexaai/binds/nexa_mlx/py-lib/rerank/modeling/nexa_jina_rerank.py +0 -330
- nexaai/binds/nexa_mlx/py-lib/sd/__init__.py +0 -1
- nexaai/binds/nexa_mlx/py-lib/sd/interface.py +0 -362
- nexaai/binds/nexa_mlx/py-lib/sd/main.py +0 -286
- nexaai/binds/nexa_mlx/py-lib/sd/modeling/__init__.py +0 -306
- nexaai/binds/nexa_mlx/py-lib/sd/modeling/clip.py +0 -116
- nexaai/binds/nexa_mlx/py-lib/sd/modeling/config.py +0 -65
- nexaai/binds/nexa_mlx/py-lib/sd/modeling/model_io.py +0 -385
- nexaai/binds/nexa_mlx/py-lib/sd/modeling/sampler.py +0 -105
- nexaai/binds/nexa_mlx/py-lib/sd/modeling/tokenizer.py +0 -100
- nexaai/binds/nexa_mlx/py-lib/sd/modeling/unet.py +0 -460
- nexaai/binds/nexa_mlx/py-lib/sd/modeling/vae.py +0 -274
- nexaai/binds/nexa_mlx/py-lib/tts/__init__.py +0 -12
- nexaai/binds/nexa_mlx/py-lib/tts/interface.py +0 -276
- nexaai/binds/nexa_mlx/py-lib/vlm/__init__.py +0 -3
- nexaai/binds/nexa_mlx/py-lib/vlm/generate.py +0 -572
- nexaai/binds/nexa_mlx/py-lib/vlm/generate_qwen3_vl.py +0 -294
- nexaai/binds/nexa_mlx/py-lib/vlm/generate_qwen3_vl_moe.py +0 -276
- nexaai/binds/nexa_mlx/py-lib/vlm/interface.py +0 -504
- nexaai/binds/nexa_mlx/py-lib/vlm/main.py +0 -320
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/__init__.py +0 -0
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/convert.py +0 -68
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/__init__.py +0 -0
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/aya_vision/__init__.py +0 -8
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/aya_vision/aya_vision.py +0 -193
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/aya_vision/interpolate.py +0 -186
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/aya_vision/language.py +0 -233
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/aya_vision/vision.py +0 -503
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/base.py +0 -202
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/cache.py +0 -230
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/deepseek_vl_v2/__init__.py +0 -10
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/deepseek_vl_v2/conversation.py +0 -264
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/deepseek_vl_v2/deepseek_vl_v2.py +0 -472
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/deepseek_vl_v2/language.py +0 -591
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/deepseek_vl_v2/processing_deepsek_vl_v2.py +0 -526
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/deepseek_vl_v2/vision.py +0 -356
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/florence2/__init__.py +0 -8
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/florence2/florence2.py +0 -366
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/florence2/language.py +0 -488
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/florence2/vision.py +0 -591
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3/__init__.py +0 -8
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3/gemma3.py +0 -213
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3/language.py +0 -315
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3/vision.py +0 -238
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3n/__init__.py +0 -2
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3n/audio.py +0 -1038
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3n/config.py +0 -139
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3n/gemma3n.py +0 -322
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3n/language.py +0 -629
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/gemma3n/vision.py +0 -1022
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/idefics2/__init__.py +0 -9
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/idefics2/idefics2.py +0 -294
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/idefics2/language.py +0 -191
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/idefics2/vision.py +0 -267
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/idefics3/__init__.py +0 -8
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/idefics3/idefics3.py +0 -175
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/idefics3/language.py +0 -192
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/idefics3/vision.py +0 -233
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/internvl_chat/__init__.py +0 -9
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/internvl_chat/internvl_chat.py +0 -140
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/internvl_chat/language.py +0 -220
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/internvl_chat/processor.py +0 -393
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/internvl_chat/vision.py +0 -293
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/kernels.py +0 -307
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/kimi_vl/__init__.py +0 -8
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/kimi_vl/kimi_vl.py +0 -143
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/kimi_vl/language.py +0 -509
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/kimi_vl/vision.py +0 -522
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llama4/__init__.py +0 -8
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llama4/language.py +0 -386
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llama4/llama4.py +0 -138
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llama4/vision.py +0 -560
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava/__init__.py +0 -8
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava/language.py +0 -240
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava/llava.py +0 -153
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava/vision.py +0 -259
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava_bunny/__init__.py +0 -9
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava_bunny/language.py +0 -236
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava_bunny/llava_bunny.py +0 -256
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava_bunny/vision.py +0 -303
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava_next/__init__.py +0 -8
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava_next/language.py +0 -230
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava_next/llava_next.py +0 -160
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/llava_next/vision.py +0 -243
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/mistral3/__init__.py +0 -8
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/mistral3/mistral3.py +0 -283
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/mllama/__init__.py +0 -8
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/mllama/language.py +0 -416
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/mllama/mllama.py +0 -172
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/mllama/vision.py +0 -499
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/molmo/__init__.py +0 -8
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/molmo/language.py +0 -243
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/molmo/molmo.py +0 -133
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/molmo/vision.py +0 -465
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/multi_modality/__init__.py +0 -10
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/multi_modality/language.py +0 -230
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/multi_modality/multi_modality.py +0 -385
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/multi_modality/sam.py +0 -557
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/multi_modality/vision.py +0 -526
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/paligemma/__init__.py +0 -8
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/paligemma/language.py +0 -282
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/paligemma/paligemma.py +0 -160
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/paligemma/vision.py +0 -242
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/phi3_v/__init__.py +0 -8
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/phi3_v/language.py +0 -21
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/phi3_v/phi3_v.py +0 -243
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/phi3_v/su_rope.py +0 -71
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/phi3_v/vision.py +0 -324
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/pixtral/__init__.py +0 -8
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/pixtral/language.py +0 -229
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/pixtral/pixtral.py +0 -161
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/pixtral/vision.py +0 -320
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_5_vl/__init__.py +0 -2
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_5_vl/config.py +0 -108
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_5_vl/language.py +0 -490
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_5_vl/qwen2_5_vl.py +0 -168
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_5_vl/vision.py +0 -414
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_vl/__init__.py +0 -2
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_vl/config.py +0 -104
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_vl/language.py +0 -490
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_vl/qwen2_vl.py +0 -167
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen2_vl/vision.py +0 -312
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/llm_common/__init__.py +0 -0
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/llm_common/base.py +0 -117
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/llm_common/cache.py +0 -531
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/llm_common/generate.py +0 -701
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/llm_common/rope_utils.py +0 -255
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/llm_common/sample_utils.py +0 -303
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/llm_common/tokenizer_utils.py +0 -407
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/processor.py +0 -476
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3_vl/qwen3vl.py +0 -1223
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/llm_common/__init__.py +0 -0
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/llm_common/base.py +0 -117
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/llm_common/cache.py +0 -531
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/llm_common/generate.py +0 -701
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/llm_common/rope_utils.py +0 -255
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/llm_common/sample_utils.py +0 -303
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/llm_common/tokenizer_utils.py +0 -407
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/processor.py +0 -476
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/qwen3vl_moe.py +0 -1309
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/qwen3vl_moe/switch_layers.py +0 -210
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/smolvlm/__init__.py +0 -8
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/models/smolvlm/smolvlm.py +0 -62
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/processing_qwen2_5_vl.py +0 -209
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/processing_qwen2_vl.py +0 -215
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/prompt_utils.py +0 -474
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/sample_utils.py +0 -39
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/tokenizer_utils.py +0 -344
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/trainer/__init__.py +0 -9
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/trainer/lora.py +0 -70
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/trainer/trainer.py +0 -296
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/trainer/utils.py +0 -160
- nexaai/binds/nexa_mlx/py-lib/vlm/modeling/utils.py +0 -928
- {nexaai-1.0.19rc7.dist-info → nexaai-1.0.19rc8.dist-info}/WHEEL +0 -0
- {nexaai-1.0.19rc7.dist-info → nexaai-1.0.19rc8.dist-info}/top_level.txt +0 -0
|
@@ -1,465 +0,0 @@
|
|
|
1
|
-
import inspect
|
|
2
|
-
from dataclasses import dataclass, field
|
|
3
|
-
from typing import List, Optional, Tuple
|
|
4
|
-
|
|
5
|
-
import mlx.core as mx
|
|
6
|
-
import mlx.nn as nn
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
@dataclass
|
|
10
|
-
class VisionConfig:
|
|
11
|
-
model_type: str = "molmo"
|
|
12
|
-
num_channels: int = 3
|
|
13
|
-
image_default_input_size: Tuple[int, int] = (336, 336)
|
|
14
|
-
image_patch_size: int = 14
|
|
15
|
-
image_pos_patch_size: int = 14
|
|
16
|
-
hidden_size: int = 18944
|
|
17
|
-
image_emb_dim: int = 1024
|
|
18
|
-
image_num_heads: int = 16
|
|
19
|
-
image_num_key_value_heads: int = 16
|
|
20
|
-
image_num_layers: int = 23
|
|
21
|
-
image_head_dim: int = 64
|
|
22
|
-
image_mlp_dim: int = 4096
|
|
23
|
-
image_mlp_activations: str = "gelu"
|
|
24
|
-
image_dropout_rate: float = 0.0
|
|
25
|
-
image_num_pos: int = 577
|
|
26
|
-
image_norm_eps: float = 1e-5
|
|
27
|
-
attention_dropout: float = 0.0
|
|
28
|
-
residual_dropout: float = 0.0
|
|
29
|
-
initializer_range: float = 0.02
|
|
30
|
-
d_model: int = 3584
|
|
31
|
-
image_pooling_h: int = 2
|
|
32
|
-
image_pooling_w: int = 2
|
|
33
|
-
vit_layers: Optional[List[int]] = field(default_factory=lambda: [-2, -9])
|
|
34
|
-
image_pooling_2d: str = "attention-meanq"
|
|
35
|
-
image_padding_embed: str = "pad_and_partial_pad"
|
|
36
|
-
intermediate_size: Optional[int] = None
|
|
37
|
-
|
|
38
|
-
def __post_init__(self):
|
|
39
|
-
if self.intermediate_size is None:
|
|
40
|
-
self.intermediate_size = self.image_patch_size * self.image_patch_size * 3
|
|
41
|
-
|
|
42
|
-
@property
|
|
43
|
-
def image_num_patch(self):
|
|
44
|
-
h, w = self.image_default_input_size
|
|
45
|
-
return h // self.image_patch_size, w // self.image_patch_size
|
|
46
|
-
|
|
47
|
-
@property
|
|
48
|
-
def llm_patches_per_crop(self):
|
|
49
|
-
h, w = self.image_num_patch
|
|
50
|
-
# Round up in case we need to pad the image features for pooling
|
|
51
|
-
h = (h + self.image_pooling_h - 1) // self.image_pooling_h
|
|
52
|
-
w = (w + self.image_pooling_w - 1) // self.image_pooling_w
|
|
53
|
-
return h, w
|
|
54
|
-
|
|
55
|
-
@classmethod
|
|
56
|
-
def from_dict(cls, params):
|
|
57
|
-
return cls(
|
|
58
|
-
**{
|
|
59
|
-
k: v
|
|
60
|
-
for k, v in params.items()
|
|
61
|
-
if k in inspect.signature(cls).parameters
|
|
62
|
-
}
|
|
63
|
-
)
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
class MLP(nn.Module):
|
|
67
|
-
def __init__(self, config: VisionConfig, input_dim: int):
|
|
68
|
-
super().__init__()
|
|
69
|
-
self.config = config
|
|
70
|
-
self.hidden_size = config.hidden_size
|
|
71
|
-
self.w1 = nn.Linear(
|
|
72
|
-
input_dim,
|
|
73
|
-
self.hidden_size,
|
|
74
|
-
bias=False,
|
|
75
|
-
)
|
|
76
|
-
self.w2 = nn.Linear(
|
|
77
|
-
self.hidden_size,
|
|
78
|
-
config.d_model,
|
|
79
|
-
bias=False,
|
|
80
|
-
)
|
|
81
|
-
self.w3 = nn.Linear(
|
|
82
|
-
input_dim,
|
|
83
|
-
self.hidden_size,
|
|
84
|
-
bias=False,
|
|
85
|
-
)
|
|
86
|
-
|
|
87
|
-
def __call__(self, x: mx.array) -> mx.array:
|
|
88
|
-
x = self.w2(nn.silu(self.w1(x)) * self.w3(x))
|
|
89
|
-
return x
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
class ViTMLP(nn.Module):
|
|
93
|
-
def __init__(self, config: VisionConfig):
|
|
94
|
-
super().__init__()
|
|
95
|
-
self.config = config
|
|
96
|
-
self.w1 = nn.Linear(config.image_emb_dim, config.image_mlp_dim, bias=True)
|
|
97
|
-
self.w2 = nn.Linear(config.image_mlp_dim, config.image_emb_dim, bias=True)
|
|
98
|
-
self.act = nn.GELU(approx="fast")
|
|
99
|
-
|
|
100
|
-
def __call__(self, x: mx.array) -> mx.array:
|
|
101
|
-
x = self.w1(x)
|
|
102
|
-
x = self.act(x)
|
|
103
|
-
x = self.w2(x)
|
|
104
|
-
return x
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
class MultiHeadDotProductAttention(nn.Module):
|
|
108
|
-
def __init__(self, config: VisionConfig, is_vit_layer: Optional[bool] = True):
|
|
109
|
-
super().__init__()
|
|
110
|
-
self.config = config
|
|
111
|
-
self.embed_dim = config.image_emb_dim
|
|
112
|
-
self.num_heads = config.image_num_heads
|
|
113
|
-
self.head_dim = config.image_head_dim
|
|
114
|
-
self.num_key_value_heads = config.image_num_key_value_heads
|
|
115
|
-
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
|
116
|
-
self.scale = self.head_dim**-0.5
|
|
117
|
-
self.is_vit_layer = is_vit_layer
|
|
118
|
-
|
|
119
|
-
n_layers = (
|
|
120
|
-
1 if (is_vit_layer or config.vit_layers is None) else len(config.vit_layers)
|
|
121
|
-
)
|
|
122
|
-
|
|
123
|
-
self.wq = nn.Linear(
|
|
124
|
-
n_layers * self.embed_dim, self.num_heads * self.head_dim, bias=True
|
|
125
|
-
)
|
|
126
|
-
self.wk = nn.Linear(
|
|
127
|
-
n_layers * self.embed_dim,
|
|
128
|
-
self.num_key_value_heads * self.head_dim,
|
|
129
|
-
bias=True,
|
|
130
|
-
)
|
|
131
|
-
self.wv = nn.Linear(
|
|
132
|
-
n_layers * self.embed_dim,
|
|
133
|
-
self.num_key_value_heads * self.head_dim,
|
|
134
|
-
bias=True,
|
|
135
|
-
)
|
|
136
|
-
self.wo = nn.Linear(self.num_heads * self.head_dim, self.embed_dim, bias=True)
|
|
137
|
-
|
|
138
|
-
def _split_heads(self, hidden_states, num_heads) -> mx.array:
|
|
139
|
-
return hidden_states.reshape(
|
|
140
|
-
hidden_states.shape[:2] + (num_heads, self.head_dim)
|
|
141
|
-
)
|
|
142
|
-
|
|
143
|
-
def _merge_heads(self, hidden_states) -> mx.array:
|
|
144
|
-
return hidden_states.reshape(hidden_states.shape[:2] + (self.embed_dim,))
|
|
145
|
-
|
|
146
|
-
def __call__(self, x: mx.array, kv: mx.array = None) -> mx.array:
|
|
147
|
-
batch_size, seq_len, _ = x.shape
|
|
148
|
-
|
|
149
|
-
if kv is None:
|
|
150
|
-
k = x
|
|
151
|
-
v = x
|
|
152
|
-
else:
|
|
153
|
-
k = kv
|
|
154
|
-
v = kv
|
|
155
|
-
q = self._split_heads(self.wq(x), self.num_heads).transpose(0, 2, 1, 3)
|
|
156
|
-
|
|
157
|
-
k = self._split_heads(self.wk(k), self.num_key_value_heads).transpose(
|
|
158
|
-
0, 2, 1, 3
|
|
159
|
-
)
|
|
160
|
-
v = self._split_heads(self.wv(v), self.num_key_value_heads).transpose(
|
|
161
|
-
0, 2, 1, 3
|
|
162
|
-
)
|
|
163
|
-
|
|
164
|
-
attn = mx.fast.scaled_dot_product_attention(q, k, v, scale=self.scale)
|
|
165
|
-
out = attn.transpose(0, 2, 1, 3)
|
|
166
|
-
out = self._merge_heads(out)
|
|
167
|
-
out = self.wo(out)
|
|
168
|
-
return out
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
class ResidualAttentionBlock(nn.Module):
|
|
172
|
-
def __init__(self, config: VisionConfig):
|
|
173
|
-
super().__init__()
|
|
174
|
-
self.config = config
|
|
175
|
-
self.attention = MultiHeadDotProductAttention(config)
|
|
176
|
-
self.feed_forward = ViTMLP(config)
|
|
177
|
-
self.attention_norm = nn.LayerNorm(
|
|
178
|
-
config.image_emb_dim, eps=config.image_norm_eps
|
|
179
|
-
)
|
|
180
|
-
self.ffn_norm = nn.LayerNorm(config.image_emb_dim, eps=config.image_norm_eps)
|
|
181
|
-
|
|
182
|
-
def __call__(self, x: mx.array) -> mx.array:
|
|
183
|
-
x = x + self.attention(self.attention_norm(x))
|
|
184
|
-
x = x + self.feed_forward(self.ffn_norm(x))
|
|
185
|
-
return x
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
class ResidualAttentionBlocks(nn.Module):
|
|
189
|
-
def __init__(self, config: VisionConfig):
|
|
190
|
-
super().__init__()
|
|
191
|
-
self.resblocks = [
|
|
192
|
-
ResidualAttentionBlock(config) for _ in range(config.image_num_layers)
|
|
193
|
-
]
|
|
194
|
-
|
|
195
|
-
def __call__(self, x: mx.array) -> mx.array:
|
|
196
|
-
h = []
|
|
197
|
-
for block in self.resblocks:
|
|
198
|
-
x = block(x)
|
|
199
|
-
h.append(x)
|
|
200
|
-
return h
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
def _expand_token(token, batch_size: int):
|
|
204
|
-
return mx.broadcast_to(
|
|
205
|
-
mx.reshape(token, (1, 1, -1)), (batch_size, 1, token.shape[-1])
|
|
206
|
-
)
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
def pad_to_multiple(x, target_size, pad_mode="edge", pad_value=0):
|
|
210
|
-
"""
|
|
211
|
-
Pad the last dimension of input tensor to match target size.
|
|
212
|
-
|
|
213
|
-
Args:
|
|
214
|
-
x: Input tensor with shape [..., D]
|
|
215
|
-
target_size: Desired size for the last dimension
|
|
216
|
-
pad_mode: Padding mode ('constant', 'reflect', etc.)
|
|
217
|
-
pad_value: Value to use for constant padding
|
|
218
|
-
|
|
219
|
-
Returns:
|
|
220
|
-
Padded tensor with shape [..., target_size]
|
|
221
|
-
"""
|
|
222
|
-
current_size = x.shape[-1]
|
|
223
|
-
|
|
224
|
-
# Return early if no padding needed
|
|
225
|
-
if current_size == target_size:
|
|
226
|
-
return x
|
|
227
|
-
|
|
228
|
-
# Ensure target size is larger
|
|
229
|
-
if current_size > target_size:
|
|
230
|
-
raise ValueError(
|
|
231
|
-
f"Current size {current_size} is larger than target size {target_size}"
|
|
232
|
-
)
|
|
233
|
-
|
|
234
|
-
# Calculate padding needed
|
|
235
|
-
pad_size = target_size - current_size
|
|
236
|
-
|
|
237
|
-
# Create padding configuration
|
|
238
|
-
# No padding for batch and channel dimensions (0,0), only pad the last dim
|
|
239
|
-
pad_config = [(0, 0)] * (len(x.shape) - 1) + [(0, pad_size)]
|
|
240
|
-
|
|
241
|
-
return mx.pad(x, pad_width=pad_config, mode=pad_mode, constant_values=pad_value)
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
class VisionTransformer(nn.Module):
|
|
245
|
-
def __init__(self, config: VisionConfig):
|
|
246
|
-
super().__init__()
|
|
247
|
-
self.config = config
|
|
248
|
-
self.class_embedding = mx.zeros((config.image_emb_dim,))
|
|
249
|
-
self.positional_embedding = mx.zeros(
|
|
250
|
-
(config.image_num_pos, config.image_emb_dim)
|
|
251
|
-
)
|
|
252
|
-
self.patch_embedding = nn.Linear(
|
|
253
|
-
config.intermediate_size,
|
|
254
|
-
config.image_emb_dim,
|
|
255
|
-
bias=False,
|
|
256
|
-
)
|
|
257
|
-
self.pre_ln = nn.LayerNorm(config.image_emb_dim, eps=config.image_norm_eps)
|
|
258
|
-
self.transformer = ResidualAttentionBlocks(config)
|
|
259
|
-
|
|
260
|
-
def add_pos_emb(self, x: mx.array, patch_num: int) -> mx.array:
|
|
261
|
-
cls_emb = self.positional_embedding[0:1]
|
|
262
|
-
pos_emb = self.positional_embedding[1:]
|
|
263
|
-
|
|
264
|
-
# Reshape into 2D grid
|
|
265
|
-
pos_emb_size = int(pos_emb.shape[0] ** 0.5)
|
|
266
|
-
pos_emb = mx.reshape(pos_emb, (pos_emb_size, pos_emb_size, pos_emb.shape[1]))
|
|
267
|
-
|
|
268
|
-
(patch_num_0, patch_num_1) = patch_num
|
|
269
|
-
|
|
270
|
-
if pos_emb.shape[0] != patch_num_0 or pos_emb.shape[1] != patch_num_1:
|
|
271
|
-
# Reshape for upsampling (add batch and channel dims)
|
|
272
|
-
pos_emb = mx.expand_dims(pos_emb, 0)
|
|
273
|
-
pos_emb = mx.transpose(pos_emb, (0, 3, 1, 2))
|
|
274
|
-
|
|
275
|
-
# Create and apply upsampler
|
|
276
|
-
upsampler = nn.Upsample(
|
|
277
|
-
scale_factor=(
|
|
278
|
-
patch_num_0 / pos_emb.shape[2],
|
|
279
|
-
patch_num_1 / pos_emb.shape[3],
|
|
280
|
-
),
|
|
281
|
-
mode="linear", # MLX doesn't have bicubic, using linear as closest alternative
|
|
282
|
-
align_corners=False,
|
|
283
|
-
)
|
|
284
|
-
pos_emb = upsampler(pos_emb)
|
|
285
|
-
|
|
286
|
-
# Restore original dimensions
|
|
287
|
-
pos_emb = mx.transpose(pos_emb, (0, 2, 3, 1))
|
|
288
|
-
pos_emb = mx.squeeze(pos_emb, 0)
|
|
289
|
-
|
|
290
|
-
pos_emb = mx.reshape(pos_emb, (-1, pos_emb.shape[-1]))
|
|
291
|
-
|
|
292
|
-
# Expand cls_emb and pos_emb
|
|
293
|
-
expanded_cls = cls_emb[None, :, :]
|
|
294
|
-
expanded_pos = pos_emb[None, :, :]
|
|
295
|
-
|
|
296
|
-
# Concatenate and add to x
|
|
297
|
-
pos_embedding = mx.concatenate([expanded_cls, expanded_pos], axis=1)
|
|
298
|
-
x = x + pos_embedding
|
|
299
|
-
return x
|
|
300
|
-
|
|
301
|
-
def __call__(self, x: mx.array, patch_num: int = None) -> List[mx.array]:
|
|
302
|
-
"""
|
|
303
|
-
: param x: (batch_size, num_patch, n_pixels)
|
|
304
|
-
"""
|
|
305
|
-
if patch_num is None:
|
|
306
|
-
patch_num = self.config.image_num_patch
|
|
307
|
-
B, N, D = x.shape
|
|
308
|
-
|
|
309
|
-
# (Optional) Due to quantization, pad around the image to match intermediate_size
|
|
310
|
-
x = pad_to_multiple(x, self.config.intermediate_size)
|
|
311
|
-
|
|
312
|
-
x = self.patch_embedding(x)
|
|
313
|
-
|
|
314
|
-
# class embeddings and positional embeddings
|
|
315
|
-
expanded_class_emb = _expand_token(self.class_embedding, x.shape[0])
|
|
316
|
-
expanded_class_emb = expanded_class_emb
|
|
317
|
-
|
|
318
|
-
x = mx.concatenate([expanded_class_emb, x], axis=1)
|
|
319
|
-
x = self.add_pos_emb(x, patch_num)
|
|
320
|
-
|
|
321
|
-
x = self.pre_ln(x)
|
|
322
|
-
|
|
323
|
-
hidden_states = self.transformer(x)
|
|
324
|
-
return hidden_states
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
class VisionModel(nn.Module):
|
|
328
|
-
def __init__(self, config):
|
|
329
|
-
super().__init__()
|
|
330
|
-
self.config = config
|
|
331
|
-
self.model_type = config.model_type
|
|
332
|
-
if self.model_type != "molmo":
|
|
333
|
-
raise ValueError(
|
|
334
|
-
f"Model type {self.model_type} not supported. Currently only 'molmo' is supported"
|
|
335
|
-
)
|
|
336
|
-
self.image_vit = VisionTransformer(config)
|
|
337
|
-
self.num_prefix_tokens = 1
|
|
338
|
-
|
|
339
|
-
self.image_pooling_2d = MultiHeadDotProductAttention(config, is_vit_layer=False)
|
|
340
|
-
self.image_projector = MLP(config, config.image_emb_dim)
|
|
341
|
-
self.pad_embed = mx.zeros((2, config.image_emb_dim * 2))
|
|
342
|
-
|
|
343
|
-
def encode_image(self, images: mx.array) -> mx.array:
|
|
344
|
-
"""
|
|
345
|
-
: param images: (batch_size, num_crops, num_patch, n_pixels)
|
|
346
|
-
"""
|
|
347
|
-
cfg = self.config
|
|
348
|
-
B, T, N, D = images.shape
|
|
349
|
-
|
|
350
|
-
# Check for -1 values across dimensions 1 and 2
|
|
351
|
-
reshaped_images = mx.reshape(images, (B * T, N, D))
|
|
352
|
-
mask = ~mx.all(reshaped_images == -1, axis=(1, 2), keepdims=True)
|
|
353
|
-
|
|
354
|
-
# Output all hidden states
|
|
355
|
-
images = reshaped_images
|
|
356
|
-
image_features = self.image_vit(images)
|
|
357
|
-
|
|
358
|
-
if cfg.vit_layers is not None:
|
|
359
|
-
features = []
|
|
360
|
-
for layer in cfg.vit_layers:
|
|
361
|
-
features.append(image_features[layer])
|
|
362
|
-
image_features = mx.concatenate(features, axis=-1)
|
|
363
|
-
else:
|
|
364
|
-
image_features = image_features[-1]
|
|
365
|
-
|
|
366
|
-
cls_embed = None
|
|
367
|
-
if self.num_prefix_tokens > 0:
|
|
368
|
-
cls_embed = image_features[:, 0]
|
|
369
|
-
image_features = image_features[:, 1:]
|
|
370
|
-
|
|
371
|
-
image_features = image_features * mask
|
|
372
|
-
image_features = mx.reshape(image_features, (B, T, N, -1))
|
|
373
|
-
|
|
374
|
-
cls_embed = mx.reshape(cls_embed, (B, T, -1)) if cls_embed is not None else None
|
|
375
|
-
|
|
376
|
-
return image_features, cls_embed
|
|
377
|
-
|
|
378
|
-
def __call__(
|
|
379
|
-
self, images: mx.array, image_masks: mx.array
|
|
380
|
-
) -> Tuple[mx.array, Optional[mx.array]]:
|
|
381
|
-
cfg = self.config
|
|
382
|
-
|
|
383
|
-
batch_size, num_image = images.shape[:2]
|
|
384
|
-
image_features, cls_embed = self.encode_image(images)
|
|
385
|
-
|
|
386
|
-
if cfg.image_padding_embed:
|
|
387
|
-
assert image_masks is not None
|
|
388
|
-
if cfg.image_padding_embed == "pad_embed":
|
|
389
|
-
all_pad = image_masks == 0
|
|
390
|
-
pad_embed = mx.reshape(self.pad_embed, (1, 1, 1, -1))
|
|
391
|
-
image_features = image_features + pad_embed * mx.expand_dims(
|
|
392
|
-
all_pad, -1
|
|
393
|
-
)
|
|
394
|
-
elif cfg.image_padding_embed == "regress":
|
|
395
|
-
pad_embed = mx.reshape(self.pad_embed, (1, 1, 1, -1))
|
|
396
|
-
image_features = image_features + pad_embed * mx.expand_dims(
|
|
397
|
-
mx.maximum(image_masks, mx.zeros_like(image_masks)), -1
|
|
398
|
-
)
|
|
399
|
-
elif cfg.image_padding_embed == "pad_and_partial_pad":
|
|
400
|
-
pad_embed = mx.reshape(self.pad_embed, (2, 1, 1, 1, -1))
|
|
401
|
-
all_pad = image_masks == 0
|
|
402
|
-
partial_pad = mx.logical_and(image_masks < 1, mx.logical_not(all_pad))
|
|
403
|
-
partial_pad = partial_pad
|
|
404
|
-
all_pad = all_pad
|
|
405
|
-
image_features = image_features + pad_embed[0] * mx.expand_dims(
|
|
406
|
-
all_pad, -1
|
|
407
|
-
)
|
|
408
|
-
image_features = image_features + pad_embed[1] * mx.expand_dims(
|
|
409
|
-
partial_pad, -1
|
|
410
|
-
)
|
|
411
|
-
else:
|
|
412
|
-
raise ValueError(cfg.image_padding_embed)
|
|
413
|
-
|
|
414
|
-
image_features = mx.reshape(
|
|
415
|
-
image_features, (batch_size, num_image) + cfg.image_num_patch + (-1,)
|
|
416
|
-
)
|
|
417
|
-
|
|
418
|
-
if cfg.image_num_patch[0] % cfg.image_pooling_h == 1:
|
|
419
|
-
# Pad so we can still pool 2x2 patches
|
|
420
|
-
image_features = mx.pad(
|
|
421
|
-
image_features, [(0, 0), (0, 0), (0, 1), (0, 1), (0, 0)]
|
|
422
|
-
)
|
|
423
|
-
|
|
424
|
-
# image pooling
|
|
425
|
-
# MLX equivalent of einops rearrange
|
|
426
|
-
h_blocks = image_features.shape[2] // cfg.image_pooling_h
|
|
427
|
-
w_blocks = image_features.shape[3] // cfg.image_pooling_w
|
|
428
|
-
image_features = mx.reshape(
|
|
429
|
-
mx.transpose(
|
|
430
|
-
mx.reshape(
|
|
431
|
-
image_features,
|
|
432
|
-
(
|
|
433
|
-
batch_size,
|
|
434
|
-
num_image,
|
|
435
|
-
h_blocks,
|
|
436
|
-
cfg.image_pooling_h,
|
|
437
|
-
w_blocks,
|
|
438
|
-
cfg.image_pooling_w,
|
|
439
|
-
-1,
|
|
440
|
-
),
|
|
441
|
-
),
|
|
442
|
-
(0, 1, 2, 4, 3, 5, 6),
|
|
443
|
-
),
|
|
444
|
-
(
|
|
445
|
-
batch_size * num_image * h_blocks * w_blocks,
|
|
446
|
-
cfg.image_pooling_h * cfg.image_pooling_w,
|
|
447
|
-
-1,
|
|
448
|
-
),
|
|
449
|
-
)
|
|
450
|
-
|
|
451
|
-
if cfg.image_pooling_2d == "attention-meanq":
|
|
452
|
-
query = mx.mean(image_features, axis=-2, keepdims=True)
|
|
453
|
-
image_features = self.image_pooling_2d(query, image_features)
|
|
454
|
-
elif cfg.image_pooling_2d not in {"none", "stack"}:
|
|
455
|
-
image_features = self.image_pooling_2d(
|
|
456
|
-
image_features[:, :1, :], image_features
|
|
457
|
-
)
|
|
458
|
-
|
|
459
|
-
h, w = cfg.llm_patches_per_crop
|
|
460
|
-
image_features = mx.reshape(image_features, (batch_size, num_image, h * w, -1))
|
|
461
|
-
|
|
462
|
-
# # MLP layer to map the feature
|
|
463
|
-
image_features = self.image_projector(image_features)
|
|
464
|
-
|
|
465
|
-
return image_features, cls_embed
|
|
@@ -1,230 +0,0 @@
|
|
|
1
|
-
import inspect
|
|
2
|
-
from dataclasses import dataclass
|
|
3
|
-
from typing import Dict, Optional, Tuple, Union
|
|
4
|
-
|
|
5
|
-
import mlx.core as mx
|
|
6
|
-
import mlx.nn as nn
|
|
7
|
-
|
|
8
|
-
from ..base import (
|
|
9
|
-
LanguageModelOutput,
|
|
10
|
-
create_attention_mask,
|
|
11
|
-
scaled_dot_product_attention,
|
|
12
|
-
)
|
|
13
|
-
from ..cache import KVCache
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
@dataclass
|
|
17
|
-
class TextConfig:
|
|
18
|
-
model_type: str
|
|
19
|
-
hidden_size: int = 4096
|
|
20
|
-
num_hidden_layers: int = 32
|
|
21
|
-
intermediate_size: int = 11008
|
|
22
|
-
num_attention_heads: int = 32
|
|
23
|
-
rms_norm_eps: float = 1e-6
|
|
24
|
-
vocab_size: int = 102400
|
|
25
|
-
num_key_value_heads: int = None
|
|
26
|
-
rope_theta: float = 10000
|
|
27
|
-
rope_traditional: bool = False
|
|
28
|
-
rope_scaling: Optional[Dict[str, Union[float, str]]] = None
|
|
29
|
-
max_position_embeddings: int = 4096
|
|
30
|
-
|
|
31
|
-
@classmethod
|
|
32
|
-
def from_dict(cls, params):
|
|
33
|
-
return cls(
|
|
34
|
-
**{
|
|
35
|
-
k: v
|
|
36
|
-
for k, v in params.items()
|
|
37
|
-
if k in inspect.signature(cls).parameters
|
|
38
|
-
}
|
|
39
|
-
)
|
|
40
|
-
|
|
41
|
-
def __post_init__(self):
|
|
42
|
-
if self.num_key_value_heads is None:
|
|
43
|
-
self.num_key_value_heads = self.num_attention_heads
|
|
44
|
-
|
|
45
|
-
if self.rope_scaling:
|
|
46
|
-
required_keys = {"factor", "type"}
|
|
47
|
-
if not all(key in self.rope_scaling for key in required_keys):
|
|
48
|
-
raise ValueError(f"rope_scaling must contain keys {required_keys}")
|
|
49
|
-
|
|
50
|
-
if self.rope_scaling["type"] != "linear":
|
|
51
|
-
raise ValueError("rope_scaling 'type' currently only supports 'linear'")
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
class Attention(nn.Module):
|
|
55
|
-
def __init__(self, config: TextConfig):
|
|
56
|
-
super().__init__()
|
|
57
|
-
|
|
58
|
-
dim = config.hidden_size
|
|
59
|
-
self.n_heads = n_heads = config.num_attention_heads
|
|
60
|
-
self.n_kv_heads = n_kv_heads = config.num_key_value_heads
|
|
61
|
-
|
|
62
|
-
self.repeats = n_heads // n_kv_heads
|
|
63
|
-
|
|
64
|
-
head_dim = config.hidden_size // n_heads
|
|
65
|
-
self.scale = head_dim**-0.5
|
|
66
|
-
|
|
67
|
-
self.q_proj = nn.Linear(dim, n_heads * head_dim, bias=False)
|
|
68
|
-
self.k_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=False)
|
|
69
|
-
self.v_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=False)
|
|
70
|
-
self.o_proj = nn.Linear(n_heads * head_dim, dim, bias=False)
|
|
71
|
-
|
|
72
|
-
rope_scale = (
|
|
73
|
-
1 / config.rope_scaling["factor"]
|
|
74
|
-
if config.rope_scaling is not None
|
|
75
|
-
and config.rope_scaling["type"] == "linear"
|
|
76
|
-
else 1
|
|
77
|
-
)
|
|
78
|
-
self.rope = nn.RoPE(
|
|
79
|
-
head_dim,
|
|
80
|
-
traditional=config.rope_traditional,
|
|
81
|
-
base=config.rope_theta,
|
|
82
|
-
scale=rope_scale,
|
|
83
|
-
)
|
|
84
|
-
|
|
85
|
-
def __call__(
|
|
86
|
-
self,
|
|
87
|
-
x: mx.array,
|
|
88
|
-
mask: Optional[mx.array] = None,
|
|
89
|
-
cache: Optional[KVCache] = None,
|
|
90
|
-
) -> mx.array:
|
|
91
|
-
B, L, D = x.shape
|
|
92
|
-
|
|
93
|
-
queries, keys, values = self.q_proj(x), self.k_proj(x), self.v_proj(x)
|
|
94
|
-
|
|
95
|
-
# Prepare the queries, keys and values for the attention computation
|
|
96
|
-
queries = queries.reshape(B, L, self.n_heads, -1).transpose(0, 2, 1, 3)
|
|
97
|
-
keys = keys.reshape(B, L, self.n_kv_heads, -1).transpose(0, 2, 1, 3)
|
|
98
|
-
values = values.reshape(B, L, self.n_kv_heads, -1).transpose(0, 2, 1, 3)
|
|
99
|
-
|
|
100
|
-
if cache is not None:
|
|
101
|
-
queries = self.rope(queries, offset=cache.offset)
|
|
102
|
-
keys = self.rope(keys, offset=cache.offset)
|
|
103
|
-
keys, values = cache.update_and_fetch(keys, values)
|
|
104
|
-
else:
|
|
105
|
-
queries = self.rope(queries)
|
|
106
|
-
keys = self.rope(keys)
|
|
107
|
-
|
|
108
|
-
output = scaled_dot_product_attention(
|
|
109
|
-
queries, keys, values, cache, scale=self.scale, mask=mask
|
|
110
|
-
)
|
|
111
|
-
output = output.transpose(0, 2, 1, 3).reshape(B, L, -1)
|
|
112
|
-
return self.o_proj(output)
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
class MLP(nn.Module):
|
|
116
|
-
def __init__(self, dim, hidden_dim):
|
|
117
|
-
super().__init__()
|
|
118
|
-
self.gate_proj = nn.Linear(dim, hidden_dim, bias=False)
|
|
119
|
-
self.down_proj = nn.Linear(hidden_dim, dim, bias=False)
|
|
120
|
-
self.up_proj = nn.Linear(dim, hidden_dim, bias=False)
|
|
121
|
-
|
|
122
|
-
def __call__(self, x) -> mx.array:
|
|
123
|
-
return self.down_proj(nn.silu(self.gate_proj(x)) * self.up_proj(x))
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
class TransformerBlock(nn.Module):
|
|
127
|
-
def __init__(self, config: TextConfig):
|
|
128
|
-
super().__init__()
|
|
129
|
-
self.num_attention_heads = config.num_attention_heads
|
|
130
|
-
self.hidden_size = config.hidden_size
|
|
131
|
-
self.self_attn = Attention(config)
|
|
132
|
-
self.mlp = MLP(config.hidden_size, config.intermediate_size)
|
|
133
|
-
self.input_layernorm = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
|
134
|
-
self.post_attention_layernorm = nn.RMSNorm(
|
|
135
|
-
config.hidden_size, eps=config.rms_norm_eps
|
|
136
|
-
)
|
|
137
|
-
self.config = config
|
|
138
|
-
|
|
139
|
-
def __call__(
|
|
140
|
-
self,
|
|
141
|
-
x: mx.array,
|
|
142
|
-
mask: Optional[mx.array] = None,
|
|
143
|
-
cache: Optional[KVCache] = None,
|
|
144
|
-
) -> mx.array:
|
|
145
|
-
r = self.self_attn(self.input_layernorm(x), mask, cache)
|
|
146
|
-
h = x + r
|
|
147
|
-
r = self.mlp(self.post_attention_layernorm(h))
|
|
148
|
-
out = h + r
|
|
149
|
-
return out
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
class Llama(nn.Module):
|
|
153
|
-
def __init__(self, config: TextConfig):
|
|
154
|
-
super().__init__()
|
|
155
|
-
self.config = config
|
|
156
|
-
self.vocab_size = config.vocab_size
|
|
157
|
-
self.num_hidden_layers = config.num_hidden_layers
|
|
158
|
-
assert self.vocab_size > 0
|
|
159
|
-
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
|
|
160
|
-
self.layers = [
|
|
161
|
-
TransformerBlock(config=config) for _ in range(config.num_hidden_layers)
|
|
162
|
-
]
|
|
163
|
-
self.norm = nn.RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
|
164
|
-
|
|
165
|
-
def __call__(
|
|
166
|
-
self,
|
|
167
|
-
inputs: mx.array,
|
|
168
|
-
inputs_embeds: Optional[mx.array] = None,
|
|
169
|
-
mask: Optional[mx.array] = None,
|
|
170
|
-
cache=None,
|
|
171
|
-
):
|
|
172
|
-
# for passing merged input embeddings
|
|
173
|
-
if inputs_embeds is None:
|
|
174
|
-
h = self.embed_tokens(inputs)
|
|
175
|
-
else:
|
|
176
|
-
h = inputs_embeds
|
|
177
|
-
|
|
178
|
-
if cache is None:
|
|
179
|
-
cache = [None] * len(self.layers)
|
|
180
|
-
|
|
181
|
-
if mask is None:
|
|
182
|
-
mask = create_attention_mask(h, cache)
|
|
183
|
-
|
|
184
|
-
for layer, c in zip(self.layers, cache):
|
|
185
|
-
h = layer(h, mask, c)
|
|
186
|
-
|
|
187
|
-
return self.norm(h)
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
class LanguageModel(nn.Module):
|
|
191
|
-
def __init__(self, config: TextConfig):
|
|
192
|
-
super().__init__()
|
|
193
|
-
self.config = config
|
|
194
|
-
self.model_type = config.model_type
|
|
195
|
-
if self.model_type != "llama":
|
|
196
|
-
raise ValueError(
|
|
197
|
-
f"Model type {self.model_type} not supported. Currently only 'llama' is supported"
|
|
198
|
-
)
|
|
199
|
-
self.model = Llama(config)
|
|
200
|
-
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
|
201
|
-
|
|
202
|
-
def __call__(
|
|
203
|
-
self,
|
|
204
|
-
inputs: mx.array,
|
|
205
|
-
inputs_embeds: Optional[mx.array] = None,
|
|
206
|
-
mask: Optional[mx.array] = None,
|
|
207
|
-
cache=None,
|
|
208
|
-
):
|
|
209
|
-
out = self.model(inputs, mask=mask, cache=cache, inputs_embeds=inputs_embeds)
|
|
210
|
-
logits = self.lm_head(out)
|
|
211
|
-
return LanguageModelOutput(logits=logits)
|
|
212
|
-
|
|
213
|
-
@staticmethod
|
|
214
|
-
def sanitize(weights):
|
|
215
|
-
# Remove unused precomputed rotary freqs
|
|
216
|
-
return {
|
|
217
|
-
k: v for k, v in weights.items() if "self_attn.rotary_emb.inv_freq" not in k
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
@property
|
|
221
|
-
def layers(self):
|
|
222
|
-
return self.model.layers
|
|
223
|
-
|
|
224
|
-
@property
|
|
225
|
-
def head_dim(self):
|
|
226
|
-
return self.config.hidden_size // self.config.num_attention_heads
|
|
227
|
-
|
|
228
|
-
@property
|
|
229
|
-
def n_kv_heads(self):
|
|
230
|
-
return self.config.num_key_value_heads
|