| 1 | import glob |
| 2 | import inspect |
| 3 | import json |
| 4 | from dataclasses import dataclass, field |
| 5 | from pathlib import Path |
| 6 | from typing import Dict, List, Tuple, Union |
| 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 = field(default_factory=TextConfig) |
| 20 | vision_config: VisionConfig = field(default_factory=VisionConfig) |
| 21 | model_type: str = "molmo" |
| 22 | image_feature_dropout: float = 0.0 |
| 23 | image_pooling_h: int = 2 |
| 24 | image_pooling_w: int = 2 |
| 25 | image_pooling_2d: str = "attention" |
| 26 | image_projector: str = "mlp" |
| 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 Model(nn.Module): |
| 40 | def __init__(self, config: ModelConfig): |
| 41 | super().__init__() |
| 42 | self.config = config |
| 43 | self.language_model = LanguageModel(config.text_config) |
| 44 | self.vision_tower = VisionModel(config.vision_config) |
| 45 | |
| 46 | def __call__( |
| 47 | self, |
| 48 | input_ids: mx.array, |
| 49 | pixel_values: mx.array, |
| 50 | mask: mx.array, |
| 51 | cache=None, |
| 52 | **kwargs, |
| 53 | ) -> Dict[str, Union[mx.array, List[Tuple[mx.array, mx.array]]]]: |
| 54 | if input_ids.ndim == 1: |
| 55 | input_ids = input_ids[None, :] |
| 56 | |
| 57 | batch_size, seq_len = input_ids.shape |
| 58 | |
| 59 | image_input_idx = kwargs.get("image_input_idx", None) |
| 60 | image_masks = kwargs.get("image_masks", None) |
| 61 | |
| 62 | if pixel_values is not None: |
| 63 | assert ( |
| 64 | image_masks is not None and image_input_idx is not None |
| 65 | ), "image_masks and image_input_idx must be provided when images are given" |
| 66 | |
| 67 | dtype = self.vision_tower.image_vit.patch_embedding.weight.dtype |
| 68 | pixel_values = pixel_values.astype(dtype) |
| 69 | |
| 70 | # Process images |
| 71 | if pixel_values.ndim == 3: |
| 72 | pixel_values = mx.expand_dims(pixel_values, 0) |
| 73 | image_masks = ( |
| 74 | mx.expand_dims(image_masks, 0) if image_masks is not None else None |
| 75 | ) |
| 76 | image_input_idx = ( |
| 77 | mx.expand_dims(image_input_idx, 0) |
| 78 | if image_input_idx is not None |
| 79 | else None |
| 80 | ) |
| 81 | |
| 82 | image_features, cls_embed = self.vision_tower(pixel_values, image_masks) |
| 83 | |
| 84 | # Insert image features into the input embeddings |
| 85 | num_image, num_patch = image_features.shape[1:3] |
| 86 | |
| 87 | assert image_input_idx.shape == ( |
| 88 | batch_size, |
| 89 | num_image, |
| 90 | num_patch, |
| 91 | ), f"image_input_idx.shape: {image_input_idx.shape}, expected: {(batch_size, num_image, num_patch)}" |
| 92 | |
| 93 | # Insert image features into the input embeddings |
| 94 | image_features = image_features.reshape( |
| 95 | batch_size, num_image * num_patch, -1 |
| 96 | ) |
| 97 | image_input_idx = image_input_idx.reshape(batch_size, num_image * num_patch) |
| 98 | |
| 99 | valid = np.where(image_input_idx >= 0)[0].tolist() |
| 100 | batch_idx = mx.arange(batch_size) |
| 101 | batch_idx = mx.tile(batch_idx[:, None], [1, image_features.shape[1]]) |
| 102 | |
| 103 | input_embeddings = self.language_model.model.wte(input_ids) |
| 104 | input_embeddings[ |
| 105 | batch_idx[valid], image_input_idx[valid] |
| 106 | ] += image_features[valid] |
| 107 | else: |
| 108 | input_embeddings = None |
| 109 | |
| 110 | # Forward pass through the language model |
| 111 | logits = self.language_model( |
| 112 | input_ids, |
| 113 | inputs_embeds=input_embeddings, |
| 114 | mask=mask, |
| 115 | cache=cache, |
| 116 | ) |
| 117 | |
| 118 | return logits |
| 119 | |
| 120 | @staticmethod |
| 121 | def from_pretrained(path_or_hf_repo: str): |
| 122 | path = Path(path_or_hf_repo) |
| 123 | if not path.exists(): |
| 124 | path = Path( |
| 125 | snapshot_download( |
| 126 | repo_id=path_or_hf_repo, |
| 127 | allow_patterns=[ |
| 128 | "*.json", |
| 129 | "*.safetensors", |
| 130 | "*.py", |
| 131 | "tokenizer.model", |
| 132 | "*.tiktoken", |
| 133 | ], |
| 134 | ) |
| 135 | ) |
| 136 | |
| 137 | with open(path / "config.json", "r") as f: |
| 138 | model_config = json.load(f) |
| 139 | |
| 140 | model_config = ModelConfig.from_dict(model_config) |
| 141 | |
| 142 | model_config.vision_config = VisionConfig.from_dict(model_config.vision_config) |
| 143 | model_config.text_config = TextConfig.from_dict(model_config.text_config) |
| 144 | |
| 145 | model = Model(model_config) |
| 146 | weight_files = glob.glob(str(path / "*.safetensors")) |
| 147 | if not weight_files: |
| 148 | raise FileNotFoundError(f"No safetensors found in {path}") |
| 149 | |
| 150 | weights = {} |
| 151 | for wf in weight_files: |
| 152 | weights.update(mx.load(wf)) |
| 153 | |
| 154 | weights = VisionModel.sanitize(weights) |
| 155 | weights = LanguageModel.sanitize(weights) |
| 156 | |
| 157 | model.load_weights(list(weights.items())) |
| 158 | return model |
| 159 | |
| 160 | def sanitize(self, weights): |
| 161 | def transform_key(key): |
| 162 | if "model.transformer" in key: |
| 163 | key = key.replace("model.transformer", "language_model.model") |
| 164 | if "model.vision_backbone" in key: |
| 165 | key = key.replace("model.vision_backbone", "vision_tower") |
| 166 | return key |
| 167 | |
| 168 | return {transform_key(k): v for k, v in weights.items()} |