| 1 | import glob |
| 2 | import inspect |
| 3 | import json |
| 4 | from dataclasses import dataclass |
| 5 | from pathlib import Path |
| 6 | from typing import Optional |
| 7 | |
| 8 | import mlx.core as mx |
| 9 | import mlx.nn as nn |
| 10 | import numpy as np |
| 11 | from huggingface_hub import snapshot_download |
| 12 | |
| 13 | from .language import LanguageModel, TextConfig |
| 14 | from .vision import VisionConfig, VisionModel |
| 15 | |
| 16 | |
| 17 | @dataclass |
| 18 | class ModelConfig: |
| 19 | text_config: TextConfig |
| 20 | vision_config: VisionConfig |
| 21 | model_type: str |
| 22 | ignore_index: int = -100 |
| 23 | image_token_index: int = 32000 |
| 24 | vision_feature_select_strategy: str = "default" |
| 25 | vision_feature_layer: int = -2 |
| 26 | vocab_size: int = 32000 |
| 27 | |
| 28 | @classmethod |
| 29 | def from_dict(cls, params): |
| 30 | return cls( |
| 31 | **{ |
| 32 | k: v |
| 33 | for k, v in params.items() |
| 34 | if k in inspect.signature(cls).parameters |
| 35 | } |
| 36 | ) |
| 37 | |
| 38 | |
| 39 | class LlavaMultiModalProjector(nn.Module): |
| 40 | def __init__(self, config: ModelConfig): |
| 41 | super().__init__() |
| 42 | self.linear_1 = nn.Linear( |
| 43 | config.vision_config.hidden_size, config.text_config.hidden_size, bias=True |
| 44 | ) |
| 45 | self.gelu = nn.GELU() |
| 46 | self.linear_2 = nn.Linear( |
| 47 | config.text_config.hidden_size, config.text_config.hidden_size, bias=True |
| 48 | ) |
| 49 | |
| 50 | def __call__(self, x: mx.array) -> mx.array: |
| 51 | x = self.linear_1(x) |
| 52 | x = self.gelu(x) |
| 53 | x = self.linear_2(x) |
| 54 | return x |
| 55 | |
| 56 | |
| 57 | class Model(nn.Module): |
| 58 | def __init__(self, config: ModelConfig): |
| 59 | super().__init__() |
| 60 | self.config = config |
| 61 | self.vision_tower = VisionModel(config.vision_config) |
| 62 | self.language_model = LanguageModel(config.text_config) |
| 63 | embed_std = 1 / mx.sqrt(config.text_config.hidden_size) |
| 64 | self.image_newline = ( |
| 65 | mx.random.normal((config.text_config.hidden_size,)) * embed_std |
| 66 | ) |
| 67 | |
| 68 | self.multi_modal_projector = LlavaMultiModalProjector(config) |
| 69 | self.vision_feature_layer = config.vision_feature_layer |
| 70 | self.vision_feature_select_strategy = config.vision_feature_select_strategy |
| 71 | |
| 72 | def get_input_embeddings( |
| 73 | self, |
| 74 | input_ids: Optional[mx.array] = None, |
| 75 | pixel_values: Optional[mx.array] = None, |
| 76 | ): |
| 77 | if pixel_values is None: |
| 78 | return self.language_model(input_ids) |
| 79 | |
| 80 | # Get the input embeddings from the language model |
| 81 | inputs_embeds = self.language_model.model.embed_tokens(input_ids) |
| 82 | |
| 83 | # Get the ouptut hidden states from the vision model |
| 84 | *_, hidden_states = self.vision_tower( |
| 85 | pixel_values[0].transpose(0, 2, 3, 1), output_hidden_states=True |
| 86 | ) |
| 87 | |
| 88 | # Select the hidden states from the desired layer |
| 89 | selected_image_feature = hidden_states[self.vision_feature_layer] |
| 90 | |
| 91 | if self.vision_feature_select_strategy == "default": |
| 92 | selected_image_feature = selected_image_feature[:, 1:] |
| 93 | elif self.vision_feature_select_strategy == "full": |
| 94 | selected_image_feature = selected_image_feature |
| 95 | else: |
| 96 | raise ValueError( |
| 97 | "Unexpected feature selection strategy: " |
| 98 | f"{self.vision_feature_select_strategy}" |
| 99 | ) |
| 100 | |
| 101 | # Pass image features through the multi-modal projector |
| 102 | image_features = self.multi_modal_projector(selected_image_feature) |
| 103 | if self.image_newline is not None: |
| 104 | self.image_newline = np.array(self.image_newline)[None, None, :] |
| 105 | self.image_newline = np.broadcast_to( |
| 106 | self.image_newline, image_features.shape |
| 107 | ) |
| 108 | image_newline = mx.array(self.image_newline) |
| 109 | image_features = mx.concatenate([image_features, image_newline], axis=0) |
| 110 | |
| 111 | # Insert special image tokens in the input_ids |
| 112 | final_inputs_embeds = self._merge_input_ids_with_image_features( |
| 113 | image_features, inputs_embeds, input_ids |
| 114 | ) |
| 115 | return final_inputs_embeds |
| 116 | |
| 117 | def _merge_input_ids_with_image_features( |
| 118 | self, image_features, inputs_embeds, input_ids |
| 119 | ): |
| 120 | image_token_index = self.config.image_token_index |
| 121 | |
| 122 | # Positions of <image> tokens in input_ids, assuming batch size is 1 |
| 123 | image_positions = np.where(input_ids[0] == image_token_index)[0].tolist() |
| 124 | text_segments = [] |
| 125 | start_idx = 0 |
| 126 | |
| 127 | for position in image_positions: |
| 128 | text_segments.append(inputs_embeds[:, start_idx:position]) |
| 129 | start_idx = position + 1 |
| 130 | |
| 131 | image_embeddings = mx.split(image_features, image_features.shape[0]) |
| 132 | final_embeddings = [v for p in zip(text_segments, image_embeddings) for v in p] |
| 133 | final_embeddings += [inputs_embeds[:, start_idx:]] |
| 134 | |
| 135 | # Create a final embedding of shape |
| 136 | # (1, num_image_patches*num_images + sequence_len, embed_dim) |
| 137 | return mx.concatenate(final_embeddings, axis=1) |
| 138 | |
| 139 | def __call__( |
| 140 | self, |
| 141 | input_ids: mx.array, |
| 142 | pixel_values: mx.array, |
| 143 | mask: mx.array, |
| 144 | cache=None, |
| 145 | **kwargs, |
| 146 | ): |
| 147 | |
| 148 | input_embddings = self.get_input_embeddings(input_ids, pixel_values) |
| 149 | logits = self.language_model( |
| 150 | input_ids, cache=cache, inputs_embeds=input_embddings |
| 151 | ) |
| 152 | return logits |
| 153 | |
| 154 | @staticmethod |
| 155 | def from_pretrained(path_or_hf_repo: str): |
| 156 | path = Path(path_or_hf_repo) |
| 157 | if not path.exists(): |
| 158 | path = Path( |
| 159 | snapshot_download( |
| 160 | repo_id=path_or_hf_repo, |
| 161 | allow_patterns=[ |
| 162 | "*.json", |
| 163 | "*.safetensors", |
| 164 | "*.py", |
| 165 | "tokenizer.model", |
| 166 | "*.tiktoken", |
| 167 | ], |
| 168 | ) |
| 169 | ) |
| 170 | |
| 171 | with open(path / "config.json", "r") as f: |
| 172 | model_config = json.load(f) |
| 173 | |
| 174 | model_config = ModelConfig.from_dict(model_config) |
| 175 | |
| 176 | model_config.vision_config = VisionConfig.from_dict(model_config.vision_config) |
| 177 | model_config.text_config = TextConfig.from_dict(model_config.text_config) |
| 178 | |
| 179 | model = Model(model_config) |
| 180 | weight_files = glob.glob(str(path / "*.safetensors")) |
| 181 | if not weight_files: |
| 182 | raise FileNotFoundError(f"No safetensors found in {path}") |
| 183 | |
| 184 | weights = {} |
| 185 | for wf in weight_files: |
| 186 | weights.update(mx.load(wf)) |
| 187 | |
| 188 | weights = VisionModel.sanitize(weights) |
| 189 | weights = LanguageModel.sanitize(weights) |
| 190 | |
| 191 | model.load_weights(list(weights.items())) |
| 192 | return model |