| 1 | import inspect |
| 2 | import math |
| 3 | from dataclasses import dataclass |
| 4 | from typing import Optional, Tuple |
| 5 | |
| 6 | import mlx.core as mx |
| 7 | import mlx.nn as nn |
| 8 | |
| 9 | from ..base import KVCache, LanguageModelOutput, SimpleKVCache, create_attention_mask |
| 10 | |
| 11 | |
| 12 | @dataclass |
| 13 | class TextConfig: |
| 14 | d_model: int = 768 |
| 15 | model_type: str = "florence2" |
| 16 | encoder_attention_heads: int = 8 |
| 17 | decoder_attention_heads: int = 8 |
| 18 | encoder_ffn_dim: int = 3072 |
| 19 | decoder_ffn_dim: int = 3072 |
| 20 | dropout: float = 0.1 |
| 21 | attention_dropout: float = 0.0 |
| 22 | activation_dropout: float = 0.0 |
| 23 | activation_function: str = "gelu" |
| 24 | init_std: float = 0.02 |
| 25 | encoder_layerdrop: float = 0.0 |
| 26 | decoder_layerdrop: float = 0.0 |
| 27 | scale_embedding: bool = False |
| 28 | use_cache: bool = True |
| 29 | max_position_embeddings: int = 1024 |
| 30 | vocab_size: int = 51289 |
| 31 | pad_token_id: int = 1 |
| 32 | bos_token_id: int = 0 |
| 33 | eos_token_id: int = 2 |
| 34 | encoder_layers: int = 6 |
| 35 | decoder_layers: int = 6 |
| 36 | |
| 37 | @classmethod |
| 38 | def from_dict(cls, params): |
| 39 | return cls( |
| 40 | **{ |
| 41 | k: v |
| 42 | for k, v in params.items() |
| 43 | if k in inspect.signature(cls).parameters |
| 44 | } |
| 45 | ) |
| 46 | |
| 47 | |
| 48 | class Florence2Attention(nn.Module): |
| 49 | def __init__( |
| 50 | self, config: TextConfig, is_decoder: bool = False, is_causal: bool = False |
| 51 | ): |
| 52 | super().__init__() |
| 53 | self.embed_dim = config.d_model |
| 54 | self.num_heads = ( |
| 55 | config.decoder_attention_heads |
| 56 | if is_decoder |
| 57 | else config.encoder_attention_heads |
| 58 | ) |
| 59 | self.is_decoder = is_decoder |
| 60 | self.is_causal = is_causal |
| 61 | self.head_dim = self.embed_dim // self.num_heads |
| 62 | self.scaling = self.head_dim**-0.5 |
| 63 | |
| 64 | self.k_proj = nn.Linear(self.embed_dim, self.embed_dim) |
| 65 | self.v_proj = nn.Linear(self.embed_dim, self.embed_dim) |
| 66 | self.q_proj = nn.Linear(self.embed_dim, self.embed_dim) |
| 67 | self.out_proj = nn.Linear(self.embed_dim, self.embed_dim) |
| 68 | |
| 69 | def __call__( |
| 70 | self, |
| 71 | hidden_states, |
| 72 | key_value_states=None, |
| 73 | # cache: Optional[Tuple[mx.array, mx.array]] = None, |
| 74 | cache: Optional[KVCache] = None, |
| 75 | attention_mask=None, |
| 76 | layer_head_mask=None, |
| 77 | ): |
| 78 | batch_size, tgt_len, _ = hidden_states.shape |
| 79 | |
| 80 | q = ( |
| 81 | self.q_proj(hidden_states) |
| 82 | .reshape(batch_size, tgt_len, self.num_heads, self.head_dim) |
| 83 | .transpose(0, 2, 1, 3) |
| 84 | ) |
| 85 | |
| 86 | is_cross_attention = key_value_states is not None |
| 87 | |
| 88 | batch_size, tgt_len, _ = hidden_states.shape |
| 89 | src_len = ( |
| 90 | key_value_states.shape[1] |
| 91 | if key_value_states is not None |
| 92 | else hidden_states.shape[1] |
| 93 | ) |
| 94 | |
| 95 | if ( |
| 96 | is_cross_attention |
| 97 | and cache.cache_length > 0 |
| 98 | and cache.keys.shape[2] == key_value_states.shape[1] |
| 99 | ): |
| 100 | # k = cache[0] |
| 101 | # v = cache[1] |
| 102 | k = cache.keys |
| 103 | v = cache.values |
| 104 | |
| 105 | elif is_cross_attention: |
| 106 | # Cross attention |
| 107 | k = ( |
| 108 | self.k_proj(key_value_states) |
| 109 | .reshape(batch_size, src_len, self.num_heads, self.head_dim) |
| 110 | .transpose(0, 2, 1, 3) |
| 111 | ) |
| 112 | v = ( |
| 113 | self.v_proj(key_value_states) |
| 114 | .reshape(batch_size, src_len, self.num_heads, self.head_dim) |
| 115 | .transpose(0, 2, 1, 3) |
| 116 | ) |
| 117 | elif cache is not None: |
| 118 | # reuse k, v, self_attention |
| 119 | k = ( |
| 120 | self.k_proj(hidden_states) |
| 121 | .reshape(batch_size, src_len, self.num_heads, -1) |
| 122 | .transpose(0, 2, 1, 3) |
| 123 | ) |
| 124 | v = ( |
| 125 | self.v_proj(hidden_states) |
| 126 | .reshape(batch_size, src_len, self.num_heads, -1) |
| 127 | .transpose(0, 2, 1, 3) |
| 128 | ) |
| 129 | |
| 130 | k, v = cache.update_and_fetch(k, v) |
| 131 | else: |
| 132 | # Self attention |
| 133 | k = ( |
| 134 | self.k_proj(hidden_states) |
| 135 | .reshape(batch_size, src_len, self.num_heads, self.head_dim) |
| 136 | .transpose(0, 2, 1, 3) |
| 137 | ) |
| 138 | v = ( |
| 139 | self.v_proj(hidden_states) |
| 140 | .reshape(batch_size, src_len, self.num_heads, self.head_dim) |
| 141 | .transpose(0, 2, 1, 3) |
| 142 | ) |
| 143 | |
| 144 | if self.is_decoder: |
| 145 | cache.update(k, v) |
| 146 | |
| 147 | if self.is_causal and self.is_decoder: |
| 148 | causal_mask = create_attention_mask(hidden_states) |
| 149 | attention_mask = causal_mask |
| 150 | |
| 151 | attn_output = ( |
| 152 | mx.fast.scaled_dot_product_attention( |
| 153 | q, k, v, scale=self.scaling, mask=attention_mask |
| 154 | ) |
| 155 | .transpose(0, 2, 1, 3) |
| 156 | .reshape(batch_size, tgt_len, -1) |
| 157 | ) |
| 158 | |
| 159 | attn_output = self.out_proj(attn_output) |
| 160 | |
| 161 | return attn_output |
| 162 | |
| 163 | |
| 164 | class Florence2EncoderLayer(nn.Module): |
| 165 | def __init__(self, config: TextConfig): |
| 166 | super().__init__() |
| 167 | self.embed_dim = config.d_model |
| 168 | self.self_attn = Florence2Attention(config, is_decoder=False, is_causal=False) |
| 169 | self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim) |
| 170 | self.activation_fn = nn.GELU() |
| 171 | self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim) |
| 172 | self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim) |
| 173 | self.final_layer_norm = nn.LayerNorm(self.embed_dim) |
| 174 | |
| 175 | def __call__(self, hidden_states, attention_mask=None): |
| 176 | residual = hidden_states |
| 177 | hidden_states = self.self_attn(hidden_states, attention_mask=attention_mask) |
| 178 | hidden_states = residual + hidden_states |
| 179 | hidden_states = self.self_attn_layer_norm(hidden_states) |
| 180 | |
| 181 | residual = hidden_states |
| 182 | hidden_states = self.activation_fn(self.fc1(hidden_states)) |
| 183 | hidden_states = self.fc2(hidden_states) |
| 184 | hidden_states = residual + hidden_states |
| 185 | hidden_states = self.final_layer_norm(hidden_states) |
| 186 | |
| 187 | return hidden_states |
| 188 | |
| 189 | |
| 190 | class Florence2DecoderLayer(nn.Module): |
| 191 | def __init__(self, config: TextConfig): |
| 192 | super().__init__() |
| 193 | self.embed_dim = config.d_model |
| 194 | self.self_attn = Florence2Attention(config, is_decoder=True, is_causal=True) |
| 195 | self.dropout = config.dropout |
| 196 | self.activation_fn = nn.GELU() |
| 197 | self.activation_dropout = config.activation_dropout |
| 198 | |
| 199 | self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim) |
| 200 | self.encoder_attn = Florence2Attention(config, is_decoder=True) |
| 201 | self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim) |
| 202 | self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim) |
| 203 | self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim) |
| 204 | self.final_layer_norm = nn.LayerNorm(self.embed_dim) |
| 205 | |
| 206 | def __call__( |
| 207 | self, |
| 208 | hidden_states, |
| 209 | encoder_hidden_states, |
| 210 | attention_mask=None, |
| 211 | encoder_attention_mask=None, |
| 212 | cache: Optional[Tuple[KVCache, KVCache]] = None, |
| 213 | ): |
| 214 | residual = hidden_states |
| 215 | |
| 216 | # decoder uni-directional self-attention cached key/values tuple is at positions 1,2 |
| 217 | self_attn_cache = cache[0] if cache[0] is not None else None |
| 218 | |
| 219 | hidden_states = self.self_attn( |
| 220 | hidden_states, attention_mask=attention_mask, cache=self_attn_cache |
| 221 | ) |
| 222 | |
| 223 | hidden_states = residual + hidden_states |
| 224 | hidden_states = self.self_attn_layer_norm(hidden_states) |
| 225 | |
| 226 | if encoder_hidden_states is not None: |
| 227 | residual = hidden_states |
| 228 | |
| 229 | mask = create_attention_mask(hidden_states) |
| 230 | |
| 231 | # cross_attn cached key/values tuple is at positions 3,4 of cache tuple |
| 232 | cross_attn_cache = cache[-1] if cache[-1] is not None else None |
| 233 | |
| 234 | hidden_states = self.encoder_attn( |
| 235 | hidden_states, |
| 236 | key_value_states=encoder_hidden_states, |
| 237 | attention_mask=mask, |
| 238 | cache=cross_attn_cache, |
| 239 | ) |
| 240 | hidden_states = residual + hidden_states |
| 241 | hidden_states = self.encoder_attn_layer_norm(hidden_states) |
| 242 | |
| 243 | # Fully Connected |
| 244 | residual = hidden_states |
| 245 | hidden_states = self.activation_fn(self.fc1(hidden_states)) |
| 246 | hidden_states = self.fc2(hidden_states) |
| 247 | hidden_states = residual + hidden_states |
| 248 | hidden_states = self.final_layer_norm(hidden_states) |
| 249 | |
| 250 | return hidden_states |
| 251 | |
| 252 | |
| 253 | class Florence2Encoder(nn.Module): |
| 254 | def __init__(self, config: TextConfig): |
| 255 | super().__init__() |
| 256 | self.config = config |
| 257 | self.dropout = config.dropout |
| 258 | self.layerdrop = config.encoder_layerdrop |
| 259 | |
| 260 | embed_dim = config.d_model |
| 261 | self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0 |
| 262 | self.offset = 2 |
| 263 | self.embed_positions = nn.Embedding( |
| 264 | config.max_position_embeddings + self.offset, embed_dim |
| 265 | ) |
| 266 | self.layers = [ |
| 267 | Florence2EncoderLayer(config) for _ in range(config.encoder_layers) |
| 268 | ] |
| 269 | self.layernorm_embedding = nn.LayerNorm(embed_dim) |
| 270 | |
| 271 | def __call__(self, input_ids=None, inputs_embeds=None, attention_mask=None): |
| 272 | |
| 273 | if inputs_embeds is None: |
| 274 | inputs_embeds = self.embed_tokens(input_ids) |
| 275 | input_shape = inputs_embeds.shape |
| 276 | else: |
| 277 | input_shape = inputs_embeds.shape |
| 278 | |
| 279 | positions = mx.arange(input_shape[1]) |
| 280 | |
| 281 | if positions.ndim == 1: |
| 282 | positions = mx.expand_dims(positions, axis=0) |
| 283 | |
| 284 | embed_pos = self.embed_positions(positions + self.offset) |
| 285 | |
| 286 | hidden_states = inputs_embeds + embed_pos |
| 287 | hidden_states = self.layernorm_embedding(hidden_states) |
| 288 | |
| 289 | for encoder_layer in self.layers: |
| 290 | # Add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) |
| 291 | dropout_probability = mx.random.uniform() |
| 292 | if self.training and (dropout_probability < self.layerdrop): |
| 293 | continue |
| 294 | hidden_states = encoder_layer(hidden_states, attention_mask) |
| 295 | |
| 296 | return hidden_states |
| 297 | |
| 298 | |
| 299 | class Florence2Decoder(nn.Module): |
| 300 | def __init__(self, config: TextConfig): |
| 301 | super().__init__() |
| 302 | self.config = config |
| 303 | self.dropout = config.dropout |
| 304 | self.layerdrop = config.decoder_layerdrop |
| 305 | self.padding_idx = config.pad_token_id |
| 306 | self.max_target_positions = config.max_position_embeddings |
| 307 | self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0 |
| 308 | self.offset = 2 |
| 309 | self.embed_positions = nn.Embedding( |
| 310 | config.max_position_embeddings + self.offset, config.d_model |
| 311 | ) |
| 312 | self.layers = [ |
| 313 | Florence2DecoderLayer(config) for _ in range(config.decoder_layers) |
| 314 | ] |
| 315 | self.layernorm_embedding = nn.LayerNorm(config.d_model) |
| 316 | |
| 317 | def __call__( |
| 318 | self, |
| 319 | input_ids=None, |
| 320 | attention_mask=None, |
| 321 | encoder_hidden_states=None, |
| 322 | encoder_attention_mask=None, |
| 323 | head_mask=None, |
| 324 | cross_attn_head_mask=None, |
| 325 | inputs_embeds=None, |
| 326 | cache=None, |
| 327 | ): |
| 328 | if input_ids is not None and inputs_embeds is not None: |
| 329 | raise ValueError( |
| 330 | "You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time" |
| 331 | ) |
| 332 | elif input_ids is not None: |
| 333 | inputs_embeds = self.embed_tokens(input_ids) |
| 334 | input_shape = inputs_embeds.shape # for 2d masks |
| 335 | positions = input_ids |
| 336 | elif inputs_embeds is not None: |
| 337 | input_shape = inputs_embeds.shape[:-1] # for 4d masks |
| 338 | positions = inputs_embeds[:, :, -1] |
| 339 | else: |
| 340 | raise ValueError( |
| 341 | "You have to specify either decoder_input_ids or decoder_inputs_embeds" |
| 342 | ) |
| 343 | |
| 344 | if positions.ndim == 1: |
| 345 | positions = mx.expand_dims(positions, axis=0) |
| 346 | |
| 347 | cache_length = cache[0][0].keys.shape[2] if cache[0][0].cache_length > 0 else 0 |
| 348 | |
| 349 | bsz, seq_len = inputs_embeds.shape[:2] |
| 350 | positions = mx.arange( |
| 351 | cache_length, |
| 352 | cache_length + seq_len, |
| 353 | dtype=mx.int64, |
| 354 | ) |
| 355 | positions = mx.expand_dims(positions, axis=0) |
| 356 | |
| 357 | embed_pos = self.embed_positions(positions + self.offset) |
| 358 | |
| 359 | hidden_states = inputs_embeds + embed_pos |
| 360 | hidden_states = self.layernorm_embedding(hidden_states) |
| 361 | |
| 362 | for decoder_layer, c in zip(self.layers, cache): |
| 363 | # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) |
| 364 | dropout_probability = mx.random.uniform() |
| 365 | if self.training and (dropout_probability < self.layerdrop): |
| 366 | continue |
| 367 | hidden_states = decoder_layer( |
| 368 | hidden_states=hidden_states, |
| 369 | encoder_hidden_states=encoder_hidden_states, |
| 370 | attention_mask=attention_mask, |
| 371 | encoder_attention_mask=encoder_attention_mask, |
| 372 | cache=c, |
| 373 | ) |
| 374 | |
| 375 | return hidden_states |
| 376 | |
| 377 | |
| 378 | class Florence2LanguageModel(nn.Module): |
| 379 | def __init__(self, config: TextConfig): |
| 380 | super().__init__() |
| 381 | self.config = config |
| 382 | self.shared = nn.Embedding(config.vocab_size, config.d_model) |
| 383 | self.encoder = Florence2Encoder(config) |
| 384 | self.decoder = Florence2Decoder(config) |
| 385 | if config.scale_embedding: |
| 386 | self.embed_scale = math.sqrt(config.d_model) |
| 387 | else: |
| 388 | self.embed_scale = 1.0 |
| 389 | |
| 390 | def __call__( |
| 391 | self, |
| 392 | input_ids=None, |
| 393 | inputs_embeds=None, |
| 394 | decoder_input_ids=None, |
| 395 | decoder_inputs_embeds=None, |
| 396 | attention_mask=None, |
| 397 | decoder_attention_mask=None, |
| 398 | encoder_outputs=None, |
| 399 | cache=None, |
| 400 | ): |
| 401 | self.encoder.embed_tokens = self.shared |
| 402 | self.decoder.embed_tokens = self.shared |
| 403 | |
| 404 | if decoder_input_ids is None and decoder_inputs_embeds is None: |
| 405 | if input_ids is None: |
| 406 | raise ValueError( |
| 407 | "If no `decoder_input_ids` or `decoder_inputs_embeds` are " |
| 408 | "passed, `input_ids` cannot be `None`. Please pass either " |
| 409 | "`input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`." |
| 410 | ) |
| 411 | |
| 412 | decoder_input_ids = mx.zeros_like(input_ids) |
| 413 | decoder_input_ids[:, 1:] = input_ids[:, :-1] |
| 414 | decoder_input_ids[:, 0] = self.config.bos_token_id |
| 415 | |
| 416 | if inputs_embeds is not None: |
| 417 | inputs_embeds = inputs_embeds * self.embed_scale |
| 418 | |
| 419 | if cache is None: |
| 420 | cache = [(SimpleKVCache(), SimpleKVCache())] * len(self.decoder.layers) |
| 421 | |
| 422 | if encoder_outputs is None: |
| 423 | encoder_outputs = self.encoder( |
| 424 | input_ids=input_ids, |
| 425 | inputs_embeds=inputs_embeds, |
| 426 | attention_mask=attention_mask, |
| 427 | ) |
| 428 | |
| 429 | decoder_outputs = self.decoder( |
| 430 | input_ids=decoder_input_ids, |
| 431 | attention_mask=decoder_attention_mask, |
| 432 | encoder_hidden_states=encoder_outputs, |
| 433 | encoder_attention_mask=attention_mask, |
| 434 | inputs_embeds=decoder_inputs_embeds, |
| 435 | cache=cache, |
| 436 | ) |
| 437 | return decoder_outputs, encoder_outputs |
| 438 | |
| 439 | |
| 440 | class LanguageModel(nn.Module): |
| 441 | def __init__(self, config: TextConfig): |
| 442 | super().__init__() |
| 443 | self.config = config |
| 444 | self.model = Florence2LanguageModel(config) |
| 445 | self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False) |
| 446 | |
| 447 | def __call__( |
| 448 | self, |
| 449 | input_ids=None, |
| 450 | inputs_embeds=None, |
| 451 | decoder_input_ids=None, |
| 452 | decoder_inputs_embeds=None, |
| 453 | attention_mask=None, |
| 454 | decoder_attention_mask=None, |
| 455 | encoder_outputs=None, |
| 456 | cache=None, |
| 457 | ): |
| 458 | decoder_outputs, encoder_outputs = self.model( |
| 459 | input_ids, |
| 460 | inputs_embeds, |
| 461 | decoder_input_ids, |
| 462 | decoder_inputs_embeds, |
| 463 | attention_mask, |
| 464 | decoder_attention_mask, |
| 465 | encoder_outputs, |
| 466 | cache, |
| 467 | ) |
| 468 | out = self.lm_head(decoder_outputs) |
| 469 | return LanguageModelOutput(logits=out, encoder_outputs=encoder_outputs) |
| 470 | |
| 471 | @property |
| 472 | def layers(self): |
| 473 | return range(self.model.config.decoder_layers) |
| 474 | |
| 475 | @property |
| 476 | def head_dim(self): |
| 477 | return self.config.d_model // self.config.decoder_attention_heads |
| 478 | |
| 479 | @property |
| 480 | def n_kv_heads(self): |
| 481 | return self.config.decoder_attention_heads |