chrisc36 commited on
Commit
68e0611
1 Parent(s): 3cfd449

Delete modeling_molmo.py

Browse files
Files changed (1) hide show
  1. modeling_molmo.py +0 -2360
modeling_molmo.py DELETED
@@ -1,2360 +0,0 @@
1
- import logging
2
- import math
3
- from copy import deepcopy
4
- from dataclasses import fields, dataclass, replace
5
- from enum import Enum
6
- from typing import List, Optional, Tuple, Union, Dict, Any, Sequence, Callable, cast, MutableMapping
7
-
8
- import torch
9
- from einops import einsum, einops
10
- from transformers import PreTrainedModel, GenerationConfig
11
- from transformers.cache_utils import Cache
12
- from transformers.modeling_outputs import CausalLMOutputWithPast, ModelOutput
13
- from transformers.models.auto import AutoModelForCausalLM
14
- from torch import nn
15
-
16
- from .config_molmo import MolmoConfig
17
- from torch.nn import functional as F
18
-
19
-
20
- log = logging.getLogger(__name__)
21
-
22
-
23
- class BufferCache(dict, MutableMapping[str, torch.Tensor]):
24
- """
25
- Cache for attention biases and other things that would normally be stored as buffers.
26
- We avoid using buffers because we've run into various issues doing so with FSDP.
27
- In general it appears the way FSDP handles buffers is not well-defined.
28
- It doesn't shard them but apparently it does synchronize them across processes, which we want to avoid
29
- since (A) it isn't necessary, and (B) we sometimes have `-inf` in these biases which might get turned into
30
- NaNs when they're synchronized due to casting or some other issue.
31
- """
32
-
33
-
34
- class StrEnum(str, Enum):
35
- def __str__(self) -> str:
36
- return self.value
37
-
38
- def __repr__(self) -> str:
39
- return f"'{str(self)}'"
40
-
41
-
42
- class ImageProjectType(StrEnum):
43
- mlp = "mlp"
44
- mlpx2 = "2mlp"
45
- linear = "linear"
46
-
47
-
48
- class ImagePooling2DType(StrEnum):
49
- attention = "attention"
50
- attention_meanq = "attention-meanq"
51
- attention_2wide = "attention_2wide"
52
- attention_v2 = "attention-v2"
53
- none = "none"
54
- stack = "stack"
55
-
56
-
57
- class ActivationType(StrEnum):
58
- quick_gelu = "quick_gelu"
59
- gelu = "gelu"
60
- gelu_tanh = "gelu_tanh"
61
- relu = "relu"
62
- silu = "silu"
63
- llama_geglu = "llama_geglu"
64
- llama_geglu_tanh = "llama_geglu_tanh"
65
- llama_swiglu = "llama_swiglu"
66
- swiglu = "swiglu"
67
-
68
-
69
- def ensure_finite_(x: torch.Tensor, check_neg_inf: bool = True, check_pos_inf: bool = False):
70
- """
71
- Modify ``x`` in place to replace ``float("-inf")`` with the minimum value of the dtype when ``check_neg_inf``
72
- is ``True`` and to replace ``float("inf")`` with the maximum value of the dtype when ``check_pos_inf`` is ``True``.
73
- """
74
- if check_neg_inf:
75
- x.masked_fill_(x == float("-inf"), torch.finfo(x.dtype).min)
76
- if check_pos_inf:
77
- x.masked_fill_(x == float("inf"), torch.finfo(x.dtype).max)
78
-
79
-
80
- class MolmoConfigurationError(Exception):
81
- pass
82
-
83
-
84
- def _non_meta_init_device(config) -> torch.device:
85
- if config.init_device is not None and config.init_device != "meta":
86
- return torch.device(config.init_device)
87
- else:
88
- return torch.device("cuda" if torch.cuda.is_available() else "cpu")
89
-
90
-
91
- class RotaryEmbedding(nn.Module):
92
- """
93
- [Rotary positional embeddings (RoPE)](https://arxiv.org/abs/2104.09864).
94
- """
95
-
96
- def __init__(self, config: MolmoConfig, cache: BufferCache):
97
- super().__init__()
98
- self.config = config
99
- self.__cache = cache
100
- # Warm up cache.
101
- self.get_rotary_embedding(
102
- config.max_position_embeddings or config.max_sequence_length,
103
- _non_meta_init_device(config)
104
- )
105
-
106
- def get_rotary_embedding(self, seq_len: int, device: torch.device) -> Tuple[torch.Tensor, torch.Tensor]:
107
- if (
108
- (pos_sin := self.__cache.get("rope_pos_sin")) is not None
109
- and (pos_cos := self.__cache.get("rope_pos_cos")) is not None
110
- and pos_sin.shape[-2] >= seq_len
111
- and pos_cos.shape[-2] >= seq_len
112
- ):
113
- if pos_sin.device != device:
114
- pos_sin = pos_sin.to(device)
115
- self.__cache["rope_pos_sin"] = pos_sin
116
- if pos_cos.device != device:
117
- pos_cos = pos_cos.to(device)
118
- self.__cache["rope_pos_cos"] = pos_cos
119
- return pos_sin[:, :, :seq_len, :], pos_cos[:, :, :seq_len, :]
120
-
121
- with torch.autocast(device.type, enabled=False):
122
- dim = self.config.d_model // self.config.n_heads
123
- inv_freq = 1.0 / (self.config.rope_theta ** (torch.arange(0, dim, 2, device=device, dtype=torch.float) / dim))
124
- seq = torch.arange(seq_len, device=device, dtype=torch.float)
125
- freqs = torch.einsum("i , j -> i j", seq, inv_freq)
126
- if self.config.rope_impl == "interleave":
127
- positions = freqs.repeat_interleave(2, dim=-1)
128
- else:
129
- positions = torch.cat((freqs, freqs), dim=-1)
130
- pos_sin, pos_cos = positions.sin()[None, None, :, :], positions.cos()[None, None, :, :]
131
- self.__cache["rope_pos_sin"] = pos_sin
132
- self.__cache["rope_pos_cos"] = pos_cos
133
- return pos_sin, pos_cos
134
-
135
- def rotate_half(self, x: torch.Tensor) -> torch.Tensor:
136
- B, nh, T, hs = x.size()
137
- x = x.view(B, nh, T, 2, hs // 2)
138
- x1, x2 = x.unbind(dim=-2)
139
- return torch.cat((-x2, x1), dim=-1)
140
-
141
- def rotate_every_two(self, x: torch.Tensor) -> torch.Tensor:
142
- B, nh, T, hs = x.size()
143
- x = x.view(B, nh, T, hs // 2, 2)
144
- x1, x2 = x.unbind(dim=-1)
145
- x = torch.stack((-x2, x1), dim=-1)
146
- return x.view(B, nh, T, hs)
147
-
148
- def apply_rotary_pos_emb(self, pos_sin: torch.Tensor, pos_cos: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
149
- if self.config.rope_impl == "interleave":
150
- return ((t * pos_cos) + (self.rotate_every_two(t) * pos_sin)).to(t.dtype)
151
- else:
152
- return ((t * pos_cos) + (self.rotate_half(t) * pos_sin)).to(t.dtype)
153
-
154
- def forward(
155
- self,
156
- q: torch.Tensor,
157
- k: torch.Tensor,
158
- position_ids: Optional[torch.Tensor] = None
159
- ) -> Tuple[torch.Tensor, torch.Tensor]:
160
- if self.config.rope_full_precision:
161
- q_, k_ = q.float(), k.float()
162
- else:
163
- q_, k_ = q, k
164
-
165
- with torch.autocast(q.device.type, enabled=False):
166
- batch_size = q_.shape[0]
167
- query_len, key_len = q_.shape[-2], k_.shape[-2] # could be different if layer_past not None
168
- if position_ids is not None:
169
- freqs_cis_len = (self.config.max_position_embeddings or self.config.max_sequence_length)
170
- else:
171
- freqs_cis_len = key_len
172
- pos_sin, pos_cos = self.get_rotary_embedding(freqs_cis_len, q_.device)
173
- pos_sin = pos_sin.type_as(q_)
174
- pos_cos = pos_cos.type_as(q_)
175
- if position_ids is not None:
176
- assert query_len == key_len, "Query and key lengths must be equal when using position IDs."
177
- pos_sin = pos_sin[0, 0][position_ids].view(
178
- (batch_size, 1, key_len, pos_sin.shape[-1])
179
- )
180
- pos_cos = pos_cos[0, 0][position_ids].view(
181
- (batch_size, 1, key_len, pos_cos.shape[-1])
182
- )
183
- q_ = self.apply_rotary_pos_emb(
184
- pos_sin[:, :, key_len - query_len : key_len, :],
185
- pos_cos[:, :, key_len - query_len : key_len, :],
186
- q_,
187
- )
188
- k_ = self.apply_rotary_pos_emb(pos_sin, pos_cos, k_)
189
- return q_.type_as(q), k_.type_as(k)
190
-
191
-
192
- class MolmoBlock(nn.Module):
193
- """
194
- A base class for transformer block implementations.
195
- """
196
-
197
- def __init__(self, layer_id: int, config: MolmoConfig, cache: BufferCache):
198
- super().__init__()
199
- self.layer_id = layer_id
200
- self.config = config
201
- self.hidden_size = (
202
- config.mlp_hidden_size if config.mlp_hidden_size is not None else config.mlp_ratio * config.d_model
203
- )
204
- self.__cache = cache
205
- self._activation_checkpoint_fn = None
206
-
207
- # Dropout.
208
- self.dropout = Dropout(config.residual_dropout)
209
-
210
- # Layer norms.
211
- self.k_norm: Optional[LayerNormBase] = None
212
- self.q_norm: Optional[LayerNormBase] = None
213
- if config.attention_layer_norm:
214
- assert config.effective_n_kv_heads is not None
215
- self.k_norm = LayerNormBase.build(
216
- config,
217
- size=(config.d_model // config.n_heads) * config.effective_n_kv_heads,
218
- elementwise_affine=config.attention_layer_norm_with_affine,
219
- )
220
- self.q_norm = LayerNormBase.build(config, elementwise_affine=config.attention_layer_norm_with_affine)
221
-
222
- # Make sure QKV clip coefficient is positive, otherwise it's not well-defined.
223
- if config.clip_qkv is not None:
224
- assert config.clip_qkv > 0
225
-
226
- # Activation function.
227
- self.act = Activation.build(config)
228
- assert (self.act.output_multiplier * self.hidden_size) % 1 == 0
229
-
230
- # Attention output projection.
231
- input_dim = config.d_model
232
- self.attn_out = nn.Linear(
233
- input_dim, config.d_model,
234
- bias=config.include_bias,
235
- device=config.init_device
236
- )
237
-
238
- # Feed-forward output projection.
239
- self.ff_out = nn.Linear(
240
- int(self.act.output_multiplier * self.hidden_size),
241
- config.d_model,
242
- bias=config.include_bias,
243
- device=config.init_device,
244
- )
245
- self.ff_out._is_residual = True # type: ignore
246
-
247
- # Rotary embeddings.
248
- if self.config.rope:
249
- self.rotary_emb = RotaryEmbedding(config, self.__cache)
250
-
251
- self.flash_attn_func = None
252
- if config.attention_type == "flash":
253
- try:
254
- from flash_attn import flash_attn_func # type: ignore
255
-
256
- self.flash_attn_func = flash_attn_func
257
- except ModuleNotFoundError:
258
- pass
259
-
260
- def reset_parameters(self):
261
- if self.k_norm is not None:
262
- self.k_norm.reset_parameters()
263
- if self.q_norm is not None:
264
- self.q_norm.reset_parameters()
265
- init_weights(
266
- self.config,
267
- self.attn_out,
268
- d=self.config.d_model,
269
- layer_id=self.layer_id,
270
- type_of_module=ModuleType.out_module,
271
- )
272
- init_weights(
273
- self.config,
274
- self.ff_out,
275
- d=self.ff_out.in_features,
276
- layer_id=self.layer_id,
277
- type_of_module=ModuleType.out_module,
278
- )
279
-
280
- @classmethod
281
- def _cast_attn_bias(cls, bias: torch.Tensor, input_dtype: torch.dtype) -> torch.Tensor:
282
- target_dtype = input_dtype
283
- # NOTE: `is_autocast_enabled()` only checks for CUDA autocast, so we use the separate function
284
- # `is_autocast_cpu_enabled()` for CPU autocast.
285
- # See https://github.com/pytorch/pytorch/issues/110966.
286
- if bias.device.type == "cuda" and torch.is_autocast_enabled():
287
- target_dtype = torch.get_autocast_gpu_dtype()
288
- elif bias.device.type == "cpu" and torch.is_autocast_cpu_enabled():
289
- target_dtype = torch.get_autocast_cpu_dtype()
290
- if bias.dtype != target_dtype:
291
- bias = bias.to(target_dtype)
292
- ensure_finite_(bias, check_neg_inf=True, check_pos_inf=False)
293
- return bias
294
-
295
- def _scaled_dot_product_attention(
296
- self,
297
- q: torch.Tensor,
298
- k: torch.Tensor,
299
- v: torch.Tensor,
300
- attn_mask: Optional[torch.Tensor] = None,
301
- dropout_p: float = 0.0,
302
- response_dropout_p: float = 0.0,
303
- is_causal: bool = False,
304
- ) -> torch.Tensor:
305
- """
306
- Computes scaled dot product attention on query, key and value tensors, using an optional
307
- attention mask if passed, and applying dropout if a probability greater than 0.0 is specified.
308
- """
309
- if attn_mask is not None:
310
- attn_mask = attn_mask.to(q.device)
311
-
312
- if self.flash_attn_func is not None and attn_mask is None:
313
- r = self.flash_attn_func(
314
- q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), dropout_p=dropout_p, causal=is_causal
315
- )
316
- return r.transpose(1, 2)
317
- else:
318
- # torch's sdpa doesn't support GQA, so we're doing this
319
- assert k.size(1) == v.size(1)
320
- num_kv_heads = k.size(1)
321
- num_q_heads = q.size(1)
322
- if num_q_heads != num_kv_heads:
323
- assert num_q_heads % num_kv_heads == 0
324
- k = k.repeat_interleave(num_q_heads // num_kv_heads, dim=1, output_size=num_q_heads)
325
- v = v.repeat_interleave(num_q_heads // num_kv_heads, dim=1, output_size=num_q_heads)
326
-
327
- return F.scaled_dot_product_attention(
328
- q,
329
- k,
330
- v,
331
- attn_mask=attn_mask,
332
- dropout_p=dropout_p,
333
- is_causal=is_causal,
334
- )
335
-
336
- def attention(
337
- self,
338
- q: torch.Tensor,
339
- k: torch.Tensor,
340
- v: torch.Tensor,
341
- attention_bias: Optional[torch.Tensor] = None,
342
- position_ids: Optional[torch.Tensor] = None,
343
- layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
344
- use_cache: bool = False,
345
- ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
346
- B, T, C = q.size() # batch size, sequence length, d_model
347
- dtype = k.dtype
348
-
349
- # Optionally apply layer norm to keys and queries.
350
- if self.q_norm is not None and self.k_norm is not None:
351
- q = self.q_norm(q).to(dtype=dtype)
352
- k = self.k_norm(k).to(dtype=dtype)
353
-
354
- # Move head forward to be next to the batch dim.
355
- # shape: (B, nh, T, hs)
356
- q = q.view(B, T, self.config.n_heads, C // self.config.n_heads).transpose(1, 2)
357
- # shape: (B, n_kv_h, T, hs)
358
- k = k.view(B, T, self.config.effective_n_kv_heads, C // self.config.n_heads).transpose(1, 2)
359
- # shape: (B, n_kv_h, T, hs)
360
- v = v.view(B, T, self.config.effective_n_kv_heads, C // self.config.n_heads).transpose(1, 2)
361
-
362
- if self.config.use_position_ids and self.config.rope:
363
- # Apply rotary embeddings
364
- q, k = self.rotary_emb(q, k, position_ids=position_ids)
365
-
366
- if layer_past is not None:
367
- past_key, past_value = layer_past
368
- k = torch.cat((past_key.to(k.device), k), dim=-2)
369
- v = torch.cat((past_value.to(v.device), v), dim=-2)
370
-
371
- present = (k, v) if use_cache else None
372
- query_len, key_len = q.shape[-2], k.shape[-2] # could be different if layer_past not None
373
-
374
- if not self.config.use_position_ids and self.config.rope:
375
- # Apply rotary embeddings
376
- q, k = self.rotary_emb(q, k)
377
-
378
- if attention_bias is not None:
379
- # Resize and cast attention bias.
380
- # The current dtype of the attention bias might not match the dtype that the SDP attn function will
381
- # run in if AMP is enabled, and this can be a problem if some tokens are masked out due to padding
382
- # as down-casting the attention bias to the autocast precision will result in -infs, which will
383
- # cause the SDP attn function to produce NaNs.
384
- attention_bias = self._cast_attn_bias(
385
- attention_bias[:, :, key_len - query_len : key_len, :key_len], dtype
386
- )
387
-
388
- # Get the attention scores.
389
- # shape: (B, nh, T, hs)
390
- att = self._scaled_dot_product_attention(
391
- q,
392
- k,
393
- v,
394
- attn_mask=attention_bias,
395
- dropout_p=0.0 if not self.training else self.config.attention_dropout,
396
- response_dropout_p=0.0 if not self.training else self.config.response_attention_dropout,
397
- is_causal=attention_bias is None,
398
- )
399
-
400
- # Re-assemble all head outputs side-by-side.
401
- att = att.transpose(1, 2).contiguous().view(B, T, C)
402
-
403
- # Apply output projection.
404
- return self.attn_out(att), present
405
-
406
- def forward(
407
- self,
408
- x: torch.Tensor,
409
- attention_bias: Optional[torch.FloatTensor] = None,
410
- position_ids: Optional[torch.Tensor] = None,
411
- layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
412
- use_cache: bool = False,
413
- ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
414
- raise NotImplementedError
415
-
416
- @classmethod
417
- def build(cls, layer_id: int, config: MolmoConfig, cache: BufferCache):
418
- return MolmoSequentialBlock(layer_id, config, cache)
419
-
420
-
421
- class MolmoSequentialBlock(MolmoBlock):
422
- """
423
- This is a typical transformer block where the output is computed as ``MLP(LN(x + Attention(LN(x))))``
424
- (plus another skip connection).
425
- """
426
-
427
- def __init__(self, layer_id: int, config: MolmoConfig, cache: BufferCache):
428
- super().__init__(layer_id, config, cache)
429
- # Layer norms.
430
- self.attn_norm = LayerNorm.build(config)
431
- self.ff_norm = LayerNorm.build(config)
432
- # Attention input projection. Projects x -> (q, k, v)
433
-
434
- head_dim = config.d_model // config.n_heads
435
- self.fused_dims = (
436
- config.d_model,
437
- config.effective_n_kv_heads * head_dim,
438
- config.effective_n_kv_heads * head_dim,
439
- )
440
- self.att_proj = nn.Linear(
441
- config.d_model, sum(self.fused_dims),
442
- bias=config.include_bias or config.qkv_bias,
443
- device=config.init_device
444
- )
445
- # Feed-forward input projection.
446
- self.ff_proj = nn.Linear(
447
- config.d_model, self.hidden_size, bias=config.include_bias, device=config.init_device
448
- )
449
-
450
- def reset_parameters(self):
451
- super().reset_parameters()
452
- self.attn_norm.reset_parameters()
453
- self.ff_norm.reset_parameters()
454
- # NOTE: the standard deviation for these weights does not depend on the layer.
455
- init_weights(
456
- self.config, self.att_proj, d=self.config.d_model, layer_id=None, type_of_module=ModuleType.in_module
457
- )
458
- init_weights(
459
- self.config, self.ff_proj, d=self.config.d_model, layer_id=None, type_of_module=ModuleType.in_module
460
- )
461
-
462
- def forward(
463
- self,
464
- x: torch.Tensor,
465
- attention_bias: Optional[torch.Tensor] = None,
466
- position_ids: Optional[torch.Tensor] = None,
467
- layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
468
- use_cache: bool = False,
469
- ) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
470
- # Get query, key, value projections.
471
- # shape:
472
- # - for regular attn q, k, v: (batch_size, seq_len, d_model)
473
- # - for multi-query attn q: (batch_size, seq_len, d_model)
474
- # k, v: (batch_size, seq_len, d_model // n_heads)
475
- # - for group query attn q: (batch_size, seq_len, d_model)
476
- # k, v: (batch_size, seq_len, d_model // n_kv_heads)
477
-
478
- if not self.config.norm_after:
479
- if self._activation_checkpoint_fn is not None:
480
- atten_in = self._activation_checkpoint_fn(self.attn_norm, x)
481
- else:
482
- atten_in = self.attn_norm(x)
483
- else:
484
- atten_in = x
485
- qkv = self.att_proj(atten_in)
486
-
487
- if self.config.clip_qkv is not None:
488
- qkv.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
489
-
490
- q, k, v = qkv.split(self.fused_dims, dim=-1)
491
-
492
- # Get attention scores.
493
- if self._activation_checkpoint_fn is not None:
494
- att, cache = self._activation_checkpoint_fn( # type: ignore
495
- self.attention, q, k, v, attention_bias, position_ids=position_ids, layer_past=layer_past, use_cache=use_cache
496
- )
497
- else:
498
- att, cache = self.attention(q, k, v, attention_bias, position_ids=position_ids, layer_past=layer_past, use_cache=use_cache)
499
-
500
- if self.config.norm_after:
501
- if self._activation_checkpoint_fn is not None:
502
- att = self._activation_checkpoint_fn(self.attn_norm, att)
503
- else:
504
- att = self.attn_norm(att)
505
-
506
- # Add attention scores.
507
- # shape: (B, T, C)
508
- x = x + self.dropout(att)
509
-
510
- # Add feed-forward projection.
511
- # shape: (batch_size, seq_len, d_model)
512
- og_x = x
513
-
514
- if not self.config.norm_after:
515
- if self._activation_checkpoint_fn is not None:
516
- x = self._activation_checkpoint_fn(self.ff_norm, x) # type: ignore
517
- else:
518
- x = self.ff_norm(x)
519
-
520
- x = self.ff_proj(x)
521
- if self._activation_checkpoint_fn is not None:
522
- x = self._activation_checkpoint_fn(self.act, x) # type: ignore
523
- else:
524
- x = self.act(x)
525
- x = self.ff_out(x)
526
-
527
- if self.config.norm_after:
528
- if self._activation_checkpoint_fn is not None:
529
- x = self._activation_checkpoint_fn(self.ff_norm, x) # type: ignore
530
- else:
531
- x = self.ff_norm(x)
532
-
533
- x = self.dropout(x)
534
- x = og_x + x
535
-
536
- return x, cache
537
-
538
-
539
- class Embedding(nn.Module):
540
- def __init__(
541
- self,
542
- num_embeddings: int,
543
- num_new_embeddings: int,
544
- features: int,
545
- device: Union[str, torch.device],
546
- initializer_range: float = 0.02,
547
- new_embed_initializer_range: float = 0.02,
548
- ):
549
- super().__init__()
550
- self.initializer_range = initializer_range
551
- self.new_embed_initializer_range = new_embed_initializer_range
552
- self.embedding = nn.Parameter(
553
- torch.zeros(num_embeddings, features, device=device),
554
- )
555
- self.new_embedding = nn.Parameter(
556
- torch.zeros(num_new_embeddings, features, device=device),
557
- )
558
-
559
- def reset_parameters(self):
560
- nn.init.normal_(self.embedding, std=self.initializer_range)
561
- nn.init.normal_(self.new_embedding, std=self.new_embed_initializer_range)
562
-
563
- def forward(self, x: torch.Tensor) -> torch.Tensor:
564
- return F.embedding(x, torch.cat([self.embedding, self.new_embedding], dim=0))
565
-
566
-
567
- class Dropout(nn.Dropout):
568
- def __init__(
569
- self,
570
- p: float = 0.5,
571
- inplace: bool = False,
572
- mask_p: float = 0,
573
- broadcast_dims: Sequence[int] = (),
574
- ):
575
- super().__init__(p, inplace)
576
- self.mask_p = mask_p
577
- self.broadcast_dims = broadcast_dims
578
-
579
- def forward(self, input: torch.Tensor) -> torch.Tensor:
580
- """
581
- :param input: A tensor of shape `(batch_size, seq_len, embed_dim)`
582
- """
583
- if self.p == 0.0 and (self.mask_p is None or self.mask_p == 0.0):
584
- return input
585
- else:
586
- if self.p > 0. and len(self.broadcast_dims) > 0 and self.training:
587
- keep_prob = 1.0 - self.p
588
- dropout_shape = list(input.shape)
589
- for dim in self.broadcast_dims:
590
- dropout_shape[dim] = 1
591
- keep = input.new_empty(dropout_shape).bernoulli_(keep_prob)
592
- multiplier = keep.broadcast_to(input.shape)
593
- multiplier.div_(keep_prob)
594
- input = input * multiplier
595
- else:
596
- return F.dropout(input, self.p, self.training, self.inplace)
597
-
598
-
599
- @dataclass
600
- class VisionBackboneConfig:
601
- image_default_input_size: Tuple[int, int] = (336, 336)
602
- image_patch_size: int = 14
603
- image_pos_patch_size: int = 14
604
- image_emb_dim: int = 1024
605
- image_num_heads: int = 16
606
- image_num_key_value_heads: int = 16
607
- image_num_layers: int = 24
608
- image_head_dim: int = 64
609
- image_mlp_dim: int = 4096
610
- image_mlp_activations: str = "gelu"
611
- image_dropout_rate: float = 0.0
612
- image_num_pos: int = 577
613
- image_norm_eps: float = 1e-5
614
- attention_dropout: float = 0.0
615
- residual_dropout: float = 0.0
616
- initializer_range: float = 0.02
617
- fsdp_wrap: bool = False
618
- resize_mode: str = "default"
619
-
620
- def __post_init__(self):
621
- self.image_default_input_size = tuple(self.image_default_input_size) # type: ignore[assignment]
622
-
623
- @property
624
- def image_num_patch(self):
625
- h, w = self.image_default_input_size
626
- return h // self.image_patch_size, w // self.image_patch_size
627
-
628
-
629
- @dataclass
630
- class FullMolmoConfig:
631
- d_model: int = 768
632
- n_heads: int = 12
633
- n_kv_heads: Optional[int] = None
634
- qkv_bias: bool = False
635
- clip_qkv: Optional[float] = None
636
- n_layers: int = 12
637
- mlp_ratio: int = 4
638
- mlp_hidden_size: Optional[int] = None
639
- activation_type: str = "swiglu"
640
- block_group_size: int = 1
641
- rope: bool = True
642
- rope_full_precision: bool = True
643
- rope_theta: float = 10000.
644
- rope_impl: str = "interleave"
645
- vision_backbone: Optional[VisionBackboneConfig] = None
646
- attention_type: str = "sdpa"
647
- float32_attention: bool = True
648
- attention_dropout: float = 0.1
649
- response_attention_dropout: float = 0.0
650
- multi_query_attention: Optional[bool] = None
651
- attention_layer_norm: bool = False
652
- residual_dropout: float = 0.1
653
- embedding_dropout: float = 0.1
654
- layer_norm_type: str = "default"
655
- layer_norm_with_affine: bool = True
656
- layer_norm_eps: Optional[float] = None
657
- attention_layer_norm_with_affine: bool = True
658
- max_sequence_length: int = 1024
659
- max_position_embeddings: Optional[int] = None
660
- include_bias: bool = True
661
- bias_for_layer_norm: Optional[bool] = None
662
- scale_logits: bool = False
663
- vocab_size: int = 50257
664
- embedding_size: Optional[int] = 50304
665
- additional_vocab_size: Optional[int] = None
666
- new_embedding_init_range: float = 0.02
667
- weight_tying: bool = True
668
- pad_token_id: int = -1
669
- init_device: Optional[str] = None
670
- init_std: float = 0.02
671
- init_cutoff_factor: Optional[float] = None
672
- norm_after: bool = False
673
- precision: Optional[str] = None
674
- image_padding_embed: Optional[str] = None
675
- vit_layers: Tuple = (-1,)
676
- image_pooling_h: int = 2
677
- image_pooling_w: int = 2
678
- image_pooling_2d: str = "attention"
679
- image_projector: str = "mlp"
680
- image_feature_dropout: float = 0.0
681
- initializer_range: float = 0.02
682
- normalize_input_embeds: bool = False
683
- use_position_ids: bool = True
684
-
685
- @property
686
- def effective_n_kv_heads(self) -> int:
687
- if self.n_kv_heads is None:
688
- if self.multi_query_attention is True:
689
- return 1
690
- else:
691
- return self.n_heads
692
- else:
693
- if self.multi_query_attention is None:
694
- return self.n_kv_heads
695
- if self.multi_query_attention:
696
- n_kv_heads_should_be = 1
697
- else:
698
- n_kv_heads_should_be = self.n_heads
699
- if self.n_kv_heads == n_kv_heads_should_be:
700
- return n_kv_heads_should_be
701
- else:
702
- raise MolmoConfigurationError(
703
- "You can't set `multi_query_attention` and `n_kv_heads` at the same time."
704
- )
705
-
706
- @property
707
- def image_num_patch(self):
708
- assert self.vision_backbone is not None
709
- return self.vision_backbone.image_num_patch
710
-
711
- @property
712
- def image_patch_size(self):
713
- assert self.vision_backbone is not None
714
- return self.visoin_backbone.image_patch_size
715
-
716
- def llm_patches_per_crop(self):
717
- h, w = self.image_num_patch
718
- # Round up in case we need to pad the image features for pooling
719
- h = (h + self.image_pooling_h - 1) // self.image_pooling_h
720
- w = (w + self.image_pooling_w - 1) // self.image_pooling_w
721
- return h, w
722
-
723
-
724
- def _expand_token(token, batch_size: int):
725
- return token.view(1, 1, -1).expand(batch_size, -1, -1)
726
-
727
-
728
- class ViTMLP(nn.Module):
729
- def __init__(self, config: FullMolmoConfig):
730
- super().__init__()
731
- self.config = config
732
- v_cfg = config.vision_backbone
733
-
734
- self.w1 = nn.Linear(
735
- v_cfg.image_emb_dim,
736
- v_cfg.image_mlp_dim,
737
- bias=True,
738
- device=config.init_device,
739
- )
740
- # Activation function.
741
- cfg = deepcopy(config)
742
- cfg.activation_type = v_cfg.image_mlp_activations
743
- self.act = Activation.build(cfg)
744
- self.w2 = nn.Linear(
745
- v_cfg.image_mlp_dim,
746
- v_cfg.image_emb_dim,
747
- bias=True,
748
- device=config.init_device,
749
- )
750
-
751
- def reset_parameters(self):
752
- v_cfg = self.config.vision_backbone
753
- nn.init.trunc_normal_(self.w1.weight, std=math.sqrt(1 / v_cfg.image_emb_dim), a=-2.0, b=2.0)
754
- nn.init.trunc_normal_(self.w2.weight, std=math.sqrt(1 / v_cfg.image_mlp_dim), a=-2.0, b=2.0)
755
- nn.init.zeros_(self.w1.bias)
756
- nn.init.zeros_(self.w2.bias)
757
-
758
- def forward(self, x: torch.Tensor) -> torch.Tensor:
759
- x = self.w1(x)
760
- x = self.act(x)
761
- x = self.w2(x)
762
- return x
763
-
764
-
765
-
766
- class ResidualAttentionBlock(nn.Module):
767
-
768
- def __init__(self, config: FullMolmoConfig):
769
- super().__init__()
770
- self.config = config
771
-
772
- v_cfg = config.vision_backbone
773
- self.attention = MultiHeadDotProductAttention(config)
774
- self.feed_forward = ViTMLP(config)
775
- self.attention_norm = nn.LayerNorm(
776
- v_cfg.image_emb_dim,
777
- eps=v_cfg.image_norm_eps,
778
- device=config.init_device,
779
- )
780
- self.ffn_norm = nn.LayerNorm(
781
- v_cfg.image_emb_dim,
782
- eps=v_cfg.image_norm_eps,
783
- device=config.init_device,
784
- )
785
-
786
- def reset_parameters(self):
787
- self.attention.reset_parameters()
788
- self.feed_forward.reset_parameters()
789
- self.attention_norm.reset_parameters()
790
- self.ffn_norm.reset_parameters()
791
-
792
- def forward(self, x: torch.Tensor) -> torch.Tensor:
793
- x = x + self.attention(self.attention_norm(x))
794
- x = x + self.feed_forward(self.ffn_norm(x))
795
- return x
796
-
797
-
798
- class BlockCollection(nn.Module):
799
-
800
- def __init__(self, config: FullMolmoConfig):
801
- super().__init__()
802
- self.config = config
803
- self.grad_checkpointing: bool = False
804
-
805
- v_cfg = config.vision_backbone
806
- self.resblocks = nn.ModuleList([
807
- ResidualAttentionBlock(config) for _ in range(v_cfg.image_num_layers)
808
- ])
809
-
810
- def reset_parameters(self):
811
- for r in self.resblocks:
812
- r.reset_parameters()
813
-
814
- def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
815
- hidden_states = []
816
- for r in self.resblocks:
817
- x = r(x)
818
- hidden_states.append(x)
819
- return hidden_states
820
-
821
-
822
- class VisionTransformer(nn.Module):
823
-
824
- def __init__(self, config: FullMolmoConfig):
825
- super().__init__()
826
- self.config = config
827
-
828
- v_cfg = config.vision_backbone
829
- # class embeddings and positional embeddings
830
- self.scale = v_cfg.image_emb_dim ** -0.5
831
- self.class_embedding = nn.Parameter(
832
- torch.zeros(v_cfg.image_emb_dim, device=config.init_device),
833
- )
834
- self.num_prefix_tokens: int = 1
835
- self.positional_embedding = nn.Parameter(
836
- torch.zeros(v_cfg.image_num_pos, v_cfg.image_emb_dim, device=config.init_device),
837
- )
838
-
839
- image_patch_size = v_cfg.image_patch_size
840
- self.patch_embedding = nn.Linear(
841
- image_patch_size * image_patch_size * 3,
842
- v_cfg.image_emb_dim,
843
- bias=False,
844
- device=config.init_device,
845
- )
846
-
847
- self.pre_ln = nn.LayerNorm(
848
- v_cfg.image_emb_dim,
849
- eps=v_cfg.image_norm_eps,
850
- )
851
-
852
- self.transformer = BlockCollection(config)
853
-
854
- @torch.jit.ignore
855
- def set_grad_checkpointing(self, enable=True):
856
- self.transformer.grad_checkpointing = enable
857
-
858
- def reset_parameters(self):
859
- nn.init.normal_(self.class_embedding, std=self.scale)
860
- nn.init.normal_(self.positional_embedding, std=self.scale)
861
- nn.init.normal_(self.patch_embedding.weight, std=0.02)
862
- self.pre_ln.reset_parameters()
863
- self.transformer.reset_parameters()
864
-
865
- def add_pos_emb(self, x: torch.Tensor, patch_num: int) -> torch.Tensor:
866
- cls_emb = self.positional_embedding[0:1]
867
- pos_emb = self.positional_embedding[1:]
868
-
869
- pos_emb = pos_emb.reshape(
870
- (int(math.sqrt(pos_emb.shape[0])), int(math.sqrt(pos_emb.shape[0])), pos_emb.shape[1])
871
- )
872
-
873
- (patch_num_0, patch_num_1) = patch_num
874
-
875
- if pos_emb.shape[0] != patch_num_0 or pos_emb.shape[1] != patch_num_1:
876
- # Dervied from https://github.com/facebookresearch/mae/blob/main/util/pos_embed.py
877
- # antialias: default True in jax.image.resize
878
- pos_emb = pos_emb.unsqueeze(0).permute(0, 3, 1, 2)
879
- pos_emb = F.interpolate(
880
- pos_emb, size=(patch_num_0, patch_num_1), mode="bicubic", align_corners=False, antialias=True,
881
- )
882
- pos_emb = pos_emb.permute(0, 2, 3, 1).squeeze(0)
883
-
884
- pos_emb = pos_emb.reshape(-1, pos_emb.shape[-1])
885
- x = x + torch.cat([cls_emb[None, :, :], pos_emb[None, :, :]], dim=1).to(x.dtype)
886
- return x
887
-
888
- def forward(self, x: torch.Tensor, patch_num: int = None) -> List[torch.Tensor]:
889
- """
890
- : param x: (batch_size, num_patch, n_pixels)
891
- """
892
- if patch_num is None:
893
- patch_num = self.config.vision_backbone.image_num_patch
894
- B, N, D = x.shape
895
-
896
- x = self.patch_embedding(x)
897
-
898
- # class embeddings and positional embeddings
899
- x = torch.cat([_expand_token(self.class_embedding, x.shape[0]).to(x.dtype), x], dim=1)
900
- x = self.add_pos_emb(x, patch_num)
901
-
902
- x = self.pre_ln(x)
903
-
904
- hidden_states = self.transformer(x)
905
- return hidden_states
906
-
907
-
908
- class MultiHeadDotProductAttention(nn.Module):
909
- def __init__(self, config: FullMolmoConfig, use_bias: bool = True, is_vit_layer: Optional[bool] = True):
910
- super().__init__()
911
- self.config = config
912
- self.use_bias = use_bias
913
-
914
- v_cfg = config.vision_backbone
915
- self.embed_dim = v_cfg.image_emb_dim
916
- self.num_heads = v_cfg.image_num_heads
917
- self.head_dim = v_cfg.image_head_dim
918
- self.num_key_value_heads = v_cfg.image_num_key_value_heads
919
- self.num_key_value_groups = self.num_heads // self.num_key_value_heads
920
- self.initializer_range = v_cfg.initializer_range
921
- self.is_vit_layer = is_vit_layer
922
-
923
- nlayers = 1 if (is_vit_layer or config.vit_layers is None) else len(config.vit_layers)
924
-
925
- self.wq = nn.Linear(
926
- nlayers * self.embed_dim,
927
- self.num_heads * self.head_dim,
928
- bias=use_bias,
929
- device=config.init_device,
930
- )
931
- self.wk = nn.Linear(
932
- nlayers * self.embed_dim,
933
- self.num_key_value_heads * self.head_dim,
934
- bias=use_bias,
935
- device=config.init_device,
936
- )
937
- self.wv = nn.Linear(
938
- nlayers * self.embed_dim,
939
- self.num_key_value_heads * self.head_dim,
940
- bias=use_bias,
941
- device=config.init_device,
942
- )
943
- self.wo = nn.Linear(
944
- self.num_heads * self.head_dim,
945
- self.embed_dim,
946
- bias=use_bias,
947
- device=config.init_device,
948
- )
949
- self.attention_dropout: Optional[Dropout] = None
950
- if v_cfg.attention_dropout > 0:
951
- self.attention_dropout = Dropout(v_cfg.attention_dropout, broadcast_dims=(0, 1))
952
- self.residual_dropout = Dropout(v_cfg.residual_dropout)
953
-
954
- def reset_parameters(self):
955
- nn.init.normal_(self.wq.weight, std=self.initializer_range)
956
- nn.init.normal_(self.wk.weight, std=self.initializer_range)
957
- nn.init.normal_(self.wv.weight, std=self.initializer_range)
958
- nn.init.normal_(self.wo.weight, std=self.initializer_range)
959
- if self.use_bias:
960
- nn.init.constant_(self.wq.bias, 0)
961
- nn.init.constant_(self.wk.bias, 0)
962
- nn.init.constant_(self.wv.bias, 0)
963
- nn.init.constant_(self.wo.bias, 0)
964
-
965
- def _split_heads(self, hidden_states, num_heads) -> torch.Tensor:
966
- return hidden_states.reshape(hidden_states.shape[:2] + (num_heads, self.head_dim))
967
-
968
- def _merge_heads(self, hidden_states) -> torch.Tensor:
969
- return hidden_states.reshape(hidden_states.shape[:2] + (self.embed_dim,))
970
-
971
- def forward(self, inputs_q: torch.Tensor, inputs_kv: Optional[torch.Tensor] = None) -> torch.Tensor:
972
-
973
- if inputs_kv is not None:
974
- inputs_k = inputs_kv
975
- inputs_v = inputs_kv
976
- else:
977
- inputs_k = inputs_q
978
- inputs_v = inputs_q
979
-
980
- xq, xk, xv = self.wq(inputs_q), self.wk(inputs_k), self.wv(inputs_v)
981
-
982
- xq = self._split_heads(xq, self.num_heads)
983
- xk = self._split_heads(xk, self.num_key_value_heads)
984
- xv = self._split_heads(xv, self.num_key_value_heads)
985
-
986
- if self.num_heads != self.num_key_value_heads:
987
- xk = xk.repeat_interleave(self.num_key_value_groups, dim=2, output_size=self.num_heads)
988
- xv = xv.repeat_interleave(self.num_key_value_groups, dim=2, output_size=self.num_heads)
989
-
990
- og_dtype = xq.dtype
991
-
992
- if self.config.float32_attention:
993
- xq = xq.to(torch.float)
994
- xk = xk.to(torch.float)
995
-
996
- if self.config.attention_type == "direct":
997
- attn_weights = torch.einsum("...qhd,...khd->...hqk", xq / math.sqrt(xq.size(-1)), xk)
998
- attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(xq.dtype)
999
- if self.attention_dropout is not None:
1000
- attn_weights = self.attention_dropout(attn_weights)
1001
- attn_output = torch.einsum("...hqk,...khd->...qhd", attn_weights.to(xv.dtype), xv)
1002
-
1003
- elif self.config.attention_type == "sdpa":
1004
- if self.config.float32_attention and not torch.is_autocast_enabled():
1005
- xv = xv.to(torch.float32)
1006
- attn_output = F.scaled_dot_product_attention(
1007
- xq.transpose(1, 2).contiguous(),
1008
- xk.transpose(1, 2).contiguous(),
1009
- xv.transpose(1, 2).contiguous(),
1010
- is_causal=False,
1011
- dropout_p=self.config.vision_backbone.attention_dropout
1012
- ).transpose(1, 2)
1013
- else:
1014
- raise NotImplementedError(self.config.attention_type)
1015
- attn_output = attn_output.to(og_dtype)
1016
- attn_output = self._merge_heads(attn_output)
1017
- attn_output = self.wo(attn_output)
1018
- attn_output = self.residual_dropout(attn_output)
1019
-
1020
- return attn_output
1021
-
1022
-
1023
- class MultiHeadAttentionPool(nn.Module):
1024
- def __init__(
1025
- self,
1026
- config: FullMolmoConfig,
1027
- factor: int = 1,
1028
- use_bias: bool = True,
1029
- dropout: bool = True,
1030
- output_layer: bool = True,
1031
- mean_residual: bool = False,
1032
- query: str = "mean",
1033
- is_vit_layer: Optional[bool] = True
1034
- ):
1035
- super().__init__()
1036
- self.config = config
1037
- self.factor = factor
1038
- self.use_bias = use_bias
1039
- self.dropout = dropout
1040
- self.output_layer = output_layer
1041
- self.mean_residual = mean_residual
1042
- self.query = query
1043
-
1044
- v_cfg = config.vision_backbone
1045
- input_dim = v_cfg.image_emb_dim
1046
- self.embed_dim = v_cfg.image_emb_dim * factor
1047
- self.num_heads = v_cfg.image_num_heads
1048
- self.head_dim = v_cfg.image_head_dim * factor
1049
- self.num_key_value_heads = v_cfg.image_num_key_value_heads
1050
- self.num_key_value_groups = self.num_heads // self.num_key_value_heads
1051
- self.initializer_range = v_cfg.initializer_range
1052
-
1053
- nlayers = 1 if (is_vit_layer or config.vit_layers is None) else len(config.vit_layers)
1054
-
1055
- if query != "vector":
1056
- self.wq = nn.Linear(
1057
- nlayers * input_dim,
1058
- self.num_heads * self.head_dim,
1059
- bias=use_bias,
1060
- device=config.init_device,
1061
- )
1062
- self.wk = nn.Linear(
1063
- nlayers * input_dim,
1064
- self.num_key_value_heads * self.head_dim,
1065
- bias=use_bias,
1066
- device=config.init_device,
1067
- )
1068
- self.wv = nn.Linear(
1069
- nlayers * input_dim,
1070
- self.num_key_value_heads * self.head_dim,
1071
- bias=use_bias,
1072
- device=config.init_device,
1073
- )
1074
-
1075
- if query == "vector":
1076
- self.attention_query = nn.Parameter(
1077
- torch.zeros(
1078
- 1, self.num_key_value_heads * self.head_dim, device=config.init_device,
1079
- ),
1080
- )
1081
-
1082
- if output_layer:
1083
- self.wo = nn.Linear(
1084
- self.num_heads * self.head_dim,
1085
- self.embed_dim,
1086
- bias=use_bias,
1087
- device=config.init_device,
1088
- )
1089
- self.attention_dropout = Dropout(v_cfg.attention_dropout, broadcast_dims=(0, 1))
1090
- if dropout:
1091
- self.residual_dropout = Dropout(v_cfg.residual_dropout)
1092
-
1093
- def reset_parameters(self):
1094
- if self.query != "vector":
1095
- nn.init.normal_(self.wq.weight, std=self.initializer_range)
1096
- nn.init.normal_(self.wk.weight, std=self.initializer_range)
1097
- nn.init.normal_(self.wv.weight, std=self.initializer_range)
1098
- if self.output_layer:
1099
- nn.init.normal_(self.wo.weight, std=self.initializer_range)
1100
- if self.use_bias:
1101
- if self.query != "vector":
1102
- nn.init.constant_(self.wq.bias, 0)
1103
- nn.init.constant_(self.wk.bias, 0)
1104
- nn.init.constant_(self.wv.bias, 0)
1105
- if self.output_layer:
1106
- nn.init.constant_(self.wo.bias, 0)
1107
- if self.query == "vector":
1108
- nn.init.normal_(self.attention_query, std=self.initializer_range)
1109
-
1110
- def _split_heads(self, hidden_states, num_heads):
1111
- return hidden_states.reshape(hidden_states.shape[:2] + (num_heads, self.head_dim))
1112
-
1113
- def _merge_heads(self, hidden_states):
1114
- return hidden_states.reshape(hidden_states.shape[:2] + (self.embed_dim,))
1115
-
1116
- def forward(self, inputs_kv: torch.Tensor) -> torch.Tensor:
1117
-
1118
- xk, xv = self.wk(inputs_kv), self.wv(inputs_kv)
1119
-
1120
- if self.query == "mean":
1121
- inputs_q = inputs_kv.mean(dim=1, keepdim=True)
1122
- xq = self.wq(inputs_q)
1123
- elif self.query == "first":
1124
- inputs_q = inputs_kv[:, :1]
1125
- xq = self.wq(inputs_q)
1126
- elif self.query == "vector":
1127
- xq = self.attention_query.expand(inputs_kv.size(0), -1, -1)
1128
- elif self.query == "constant":
1129
- inputs_q = torch.ones_like(inputs_kv[:, :1]) / math.sqrt(inputs_kv.shape[-1])
1130
- xq = self.wq(inputs_q)
1131
- else:
1132
- raise ValueError(f"Unknown query type: {self.query}")
1133
-
1134
- xq = self._split_heads(xq, self.num_heads)
1135
- xk = self._split_heads(xk, self.num_key_value_heads)
1136
- xv = self._split_heads(xv, self.num_key_value_heads)
1137
-
1138
- if self.num_heads != self.num_key_value_heads:
1139
- xk = xk.repeat_interleave(self.num_key_value_groups, dim=2, output_size=self.num_heads)
1140
- xv = xv.repeat_interleave(self.num_key_value_groups, dim=2, output_size=self.num_heads)
1141
-
1142
- xq = xq.to(torch.float)
1143
- xk = xk.to(torch.float)
1144
-
1145
- xq = xq / math.sqrt(xq.size(-1))
1146
- attn_weights = torch.einsum("...qhd,...khd->...hqk", xq, xk)
1147
-
1148
- attn_weights = F.softmax(attn_weights, dim=-1).to(xq.dtype)
1149
-
1150
- attn_weights = self.attention_dropout(attn_weights).to(xv.dtype)
1151
-
1152
- attn_output = torch.einsum("...hqk,...khd->...qhd", attn_weights, xv)
1153
- attn_output = self._merge_heads(attn_output)
1154
- if self.output_layer:
1155
- attn_output = self.wo(attn_output)
1156
- if self.dropout:
1157
- attn_output = self.residual_dropout(attn_output)
1158
- if self.mean_residual:
1159
- attn_output += inputs_kv.mean(dim=1, keepdim=True)
1160
-
1161
- return attn_output
1162
-
1163
-
1164
- class MLP(nn.Module):
1165
- def __init__(self, config: FullMolmoConfig, input_dim: int, dropout: float = 0.0):
1166
- super().__init__()
1167
- self.config = config
1168
- self.hidden_size = (
1169
- config.mlp_hidden_size if config.mlp_hidden_size is not None else config.mlp_ratio * config.d_model
1170
- )
1171
- self.initializer_range = config.initializer_range
1172
-
1173
- self.w1 = nn.Linear(
1174
- input_dim,
1175
- self.hidden_size // 2,
1176
- bias=False,
1177
- device=config.init_device,
1178
- )
1179
- self.w2 = nn.Linear(
1180
- self.hidden_size // 2,
1181
- config.d_model,
1182
- bias=False,
1183
- device=config.init_device,
1184
- )
1185
- self.w3 = nn.Linear(
1186
- input_dim,
1187
- self.hidden_size // 2,
1188
- bias=False,
1189
- device=config.init_device,
1190
- )
1191
- # Activation function.
1192
- self.act = Activation.build(config)
1193
- self.dropout = Dropout(dropout)
1194
-
1195
- def reset_parameters(self):
1196
- nn.init.normal_(self.w1.weight, std=self.initializer_range)
1197
- nn.init.normal_(self.w2.weight, std=self.initializer_range)
1198
- nn.init.normal_(self.w3.weight, std=self.initializer_range)
1199
-
1200
- def forward(self, x: torch.Tensor) -> torch.Tensor:
1201
- x = self.w2(self.act(self.w1(x), self.w3(x)))
1202
- x = self.dropout(x)
1203
- return x
1204
-
1205
-
1206
- class Residual(nn.Module):
1207
- def __init__(self, submodule: nn.Module):
1208
- super().__init__()
1209
- self.submodule = submodule
1210
-
1211
- def reset_parameters(self):
1212
- self.submodule.reset_parameters()
1213
-
1214
- def forward(self, x: torch.Tensor) -> torch.Tensor:
1215
- return x + self.submodule(x)
1216
-
1217
-
1218
- class OLMoVisionBackbone(nn.Module):
1219
- def __init__(self, config: FullMolmoConfig):
1220
- super().__init__()
1221
- self.config = config
1222
- self.image_vit = VisionTransformer(config)
1223
-
1224
- input_dim: int = None
1225
- self.image_pooling_2d: nn.Module = None
1226
- if config.image_pooling_2d in {ImagePooling2DType.attention, ImagePooling2DType.attention_meanq}:
1227
- self.image_pooling_2d = MultiHeadDotProductAttention(config, is_vit_layer=False)
1228
- input_dim = config.vision_backbone.image_emb_dim
1229
- elif config.image_pooling_2d == ImagePooling2DType.attention_2wide:
1230
- cfg = deepcopy(config)
1231
- cfg.vision_backbone.image_emb_dim *= 2
1232
- cfg.vision_backbone.image_head_dim *= 2
1233
- self.image_pooling_2d = MultiHeadDotProductAttention(cfg, is_vit_layer=False)
1234
- input_dim = cfg.vision_backbone.image_emb_dim
1235
- elif config.image_pooling_2d == ImagePooling2DType.attention_v2:
1236
- assert config.vit_layers is not None
1237
- use_bias = True
1238
- dropout = True
1239
- output_layer = True
1240
- query = "mean"
1241
- mean_residual = False
1242
- factor = len(config.vit_layers)
1243
- self.image_pooling_2d = MultiHeadAttentionPool(
1244
- config,
1245
- factor=factor,
1246
- use_bias=use_bias,
1247
- dropout=dropout,
1248
- output_layer=output_layer,
1249
- mean_residual=mean_residual,
1250
- query=query,
1251
- is_vit_layer=False,
1252
- )
1253
- input_dim = config.vision_backbone.image_emb_dim * factor
1254
- elif config.image_pooling_2d in [ImagePooling2DType.none, ImagePooling2DType.stack]:
1255
- self.image_pooling_2d = None
1256
- nlayers = 1 if config.vit_layers is None else len(config.vit_layers)
1257
- input_dim = nlayers * config.vision_backbone.image_emb_dim
1258
- else:
1259
- raise NotImplementedError(f"Unknown image pooling 2D method: {config.image_pooling_2d}")
1260
-
1261
- self.input_dim = input_dim
1262
-
1263
- # `MLP` assume the activation takes two inputs, so it must be a 'llama' version
1264
- if config.activation_type == ActivationType.swiglu:
1265
- mlp_config = replace(config, activation_type=ActivationType.llama_swiglu)
1266
- elif config.activation_type == ActivationType.gelu:
1267
- mlp_config = replace(config, activation_type=ActivationType.llama_geglu)
1268
- else:
1269
- mlp_config = config
1270
- if config.image_projector == ImageProjectType.mlpx2:
1271
- self.image_projector = nn.ModuleList(
1272
- [MLP(mlp_config, input_dim), Residual(MLP(config, input_dim))]
1273
- )
1274
- elif config.image_projector == ImageProjectType.mlp:
1275
- self.image_projector = MLP(mlp_config, input_dim)
1276
- elif config.image_projector == ImageProjectType.linear:
1277
- self.image_projector = nn.Linear(
1278
- input_dim,
1279
- config.d_model,
1280
- bias=False,
1281
- device=config.init_device,
1282
- )
1283
- else:
1284
- raise NotImplementedError(f"Unknown image projector: {config.image_projector}")
1285
-
1286
- self.image_feature_dropout = Dropout(config.image_feature_dropout)
1287
-
1288
- def reset_parameters(self):
1289
- if self.image_pooling_2d is not None:
1290
- self.image_pooling_2d.reset_parameters()
1291
- if self.config.image_projector == "2mlp":
1292
- for module in self.image_projector:
1293
- module.reset_parameters()
1294
- elif self.config.image_projector == "linear":
1295
- nn.init.xavier_uniform_(self.image_projector.weight)
1296
- else:
1297
- self.image_projector.reset_parameters()
1298
-
1299
- def forward(self, images: torch.Tensor, image_masks: torch.Tensor) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
1300
- raise NotImplementedError
1301
-
1302
-
1303
- class OLMoPretrainedVisionBackbone(OLMoVisionBackbone):
1304
- def __init__(self, config: FullMolmoConfig):
1305
- super().__init__(config)
1306
- v_cfg = self.config.vision_backbone
1307
- self.grad_checkpointing = False
1308
-
1309
- self.num_prefix_tokens = self.image_vit.num_prefix_tokens
1310
- assert self.num_prefix_tokens in {0, 1}, "Only 0 or 1 prefix tokens are supported"
1311
-
1312
- self.pad_embed = None
1313
- if config.image_padding_embed:
1314
- image_dim = v_cfg.image_emb_dim*len(self.config.vit_layers)
1315
- if config.image_padding_embed in ["pad_embed", "regress"]:
1316
- self.pad_embed = nn.Parameter(
1317
- torch.zeros((image_dim,), device=config.init_device))
1318
- elif config.image_padding_embed == "pad_and_partial_pad":
1319
- self.pad_embed = nn.Parameter(
1320
- torch.zeros((2, image_dim), device=config.init_device))
1321
- else:
1322
- raise ValueError(config.image_padding_embed)
1323
-
1324
- def reset_parameters(self):
1325
- super().reset_parameters()
1326
- self.image_vit.reset_parameters()
1327
-
1328
- def encode_image(self, images: torch.Tensor) -> torch.Tensor:
1329
- """
1330
- : param images: (batch_size, num_crops, num_patch, n_pixels)
1331
- """
1332
- cfg = self.config
1333
- v_cfg = self.config.vision_backbone
1334
- B, T, N, D = images.shape
1335
-
1336
- mask = ~torch.all(images.view(B * T, N, D) == -1, dim=(1, 2), keepdim=True)
1337
-
1338
- # Output all hidden states
1339
- # n_layers x (batch_num_crops, (1+)n_tokens, image_emb_dim)
1340
- images = images.view(B * T, N, D)
1341
- image_features = self.image_vit(images)
1342
-
1343
- if cfg.vit_layers is not None:
1344
- features = []
1345
- for layer in cfg.vit_layers:
1346
- features.append(image_features[layer])
1347
- image_features = torch.cat(features, dim=-1)
1348
- else:
1349
- image_features = image_features[-1]
1350
-
1351
- cls_embed: torch.Tensor = None
1352
- if self.num_prefix_tokens > 0:
1353
- cls_embed = image_features[:, 0]
1354
- image_features = image_features[:, 1:]
1355
-
1356
- image_features = image_features * mask
1357
- image_features = image_features.view(B, T, N, -1)
1358
-
1359
- cls_embed = cls_embed.view(B, T, -1) if cls_embed is not None else None
1360
-
1361
- return image_features, cls_embed
1362
-
1363
- def forward(self, images: torch.Tensor, image_masks: torch.Tensor) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
1364
- cfg = self.config
1365
-
1366
- # image_features: (batch_size, num_crops(=num_image), num_patch, nximage_emb_dim)
1367
- batch_size, num_image = images.shape[:2]
1368
- image_features, cls_embed = self.encode_image(images)
1369
-
1370
- if cfg.image_padding_embed:
1371
- assert image_masks is not None
1372
- if cfg.image_padding_embed == "pad_embed":
1373
- all_pad = (image_masks == 0).to(dtype=torch.float32)
1374
- pad_embed = self.pad_embed[None, None, None, :]
1375
- image_features = image_features + pad_embed * torch.unsqueeze(all_pad, -1)
1376
- elif cfg.image_padding_embed == "regress":
1377
- pad_embed = self.pad_embed[None, None, None, :]
1378
- image_features = image_features + pad_embed * torch.unsqueeze(torch.maximum(image_masks, torch.zeros_like(image_masks)), -1)
1379
- elif cfg.image_padding_embed == "pad_and_partial_pad":
1380
- pad_embed = self.pad_embed[:, None, None, None, :]
1381
- all_pad = image_masks == 0
1382
- partial_pad = torch.logical_and(image_masks < 1, torch.logical_not(all_pad)).to(dtype=image_features.dtype)
1383
- all_pad = all_pad.to(dtype=image_features.dtype)
1384
- image_features = image_features + pad_embed[0] * torch.unsqueeze(all_pad, -1)
1385
- image_features = image_features + pad_embed[1] * torch.unsqueeze(partial_pad, -1)
1386
- else:
1387
- raise ValueError(cfg.image_padding_embed)
1388
-
1389
- image_features = self.image_feature_dropout(image_features)
1390
- if cls_embed is not None:
1391
- cls_embed = self.image_feature_dropout(cls_embed)
1392
-
1393
- image_features = image_features.reshape(
1394
- (batch_size, num_image) + cfg.image_num_patch + (-1,),
1395
- )
1396
-
1397
- if cfg.image_num_patch[0] % cfg.image_pooling_h == 1:
1398
- # Pad so we can still pool 2x2 patches
1399
- image_features = F.pad(
1400
- image_features,
1401
- (0, 0, 0, 1, 0, 1, 0, 0, 0, 0),
1402
- )
1403
-
1404
- # image pooling
1405
- image_features = einops.rearrange(
1406
- image_features,
1407
- 'b n (h dh) (w dw) c -> (b n h w) (dh dw) c',
1408
- dh=cfg.image_pooling_h,
1409
- dw=cfg.image_pooling_w,
1410
- )
1411
-
1412
- if cfg.image_pooling_2d == ImagePooling2DType.attention_meanq:
1413
- query = image_features.mean(-2, keepdim=True)
1414
- image_features = self.image_pooling_2d(query, image_features)
1415
- elif cfg.image_pooling_2d not in {ImagePooling2DType.none, ImagePooling2DType.stack}:
1416
- if self.grad_checkpointing:
1417
- from torch.utils.checkpoint import checkpoint
1418
- image_features = checkpoint(self.image_pooling_2d, image_features[:, :1, :], image_features, use_reentrant=False)
1419
- else:
1420
- image_features = self.image_pooling_2d(image_features[:, :1, :], image_features)
1421
-
1422
- h, w = cfg.llm_patches_per_crop()
1423
- image_features = image_features.reshape(batch_size, num_image, h * w, -1)
1424
-
1425
- # MLP layer to map the feature.
1426
- if self.grad_checkpointing:
1427
- from torch.utils.checkpoint import checkpoint
1428
- image_features = checkpoint(self.image_projector, image_features, use_reentrant=False)
1429
- else:
1430
- image_features = self.image_projector(image_features)
1431
-
1432
- # image_features: (batch_size, num_image, num_patch, d_model)
1433
- # cls_embed: (batch_size, num_image, d_model)
1434
- return image_features, cls_embed
1435
-
1436
-
1437
- class ModuleType(str, Enum):
1438
- in_module = "in"
1439
- out_module = "out"
1440
- emb = "emb"
1441
- final_out = "final_out"
1442
-
1443
-
1444
- def init_weights(
1445
- config: FullMolmoConfig,
1446
- module: Union[nn.Linear, nn.Embedding],
1447
- d: Optional[int] = None,
1448
- layer_id: Optional[int] = None,
1449
- std_factor: float = 1.0,
1450
- type_of_module: Optional[ModuleType] = None,
1451
- ) -> None:
1452
- d = d if d is not None else config.d_model
1453
- std = config.init_std * std_factor
1454
- if config.init_cutoff_factor is not None:
1455
- cutoff_value = config.init_cutoff_factor * std
1456
- nn.init.trunc_normal_(module.weight, mean=0.0, std=std, a=-cutoff_value, b=cutoff_value)
1457
- else:
1458
- nn.init.normal_(module.weight, mean=0.0, std=std)
1459
-
1460
-
1461
- class LlamaSwiGLU(nn.Module):
1462
- def forward(self, x1: torch.Tensor, x2: torch.Tensor) -> torch.Tensor:
1463
- return F.silu(x1) * x2
1464
-
1465
- @property
1466
- def output_multiplier(self) -> float:
1467
- return 0.5
1468
-
1469
-
1470
- class SwiGLU(nn.Module):
1471
- def forward(self, x: torch.Tensor) -> torch.Tensor:
1472
- x, gate = x.chunk(2, dim=-1)
1473
- return F.silu(gate) * x
1474
-
1475
- @property
1476
- def output_multiplier(self) -> float:
1477
- return 0.5
1478
-
1479
-
1480
- class Activation(nn.Module):
1481
- def __init__(self, config: FullMolmoConfig):
1482
- super().__init__()
1483
- self.config = config
1484
-
1485
- def forward(self, x: torch.Tensor) -> torch.Tensor:
1486
- raise NotImplementedError
1487
-
1488
- @property
1489
- def output_multiplier(self) -> float:
1490
- raise NotImplementedError
1491
-
1492
- @classmethod
1493
- def build(cls, config: FullMolmoConfig) -> 'Activation':
1494
- if config.activation_type == "quick_gelu":
1495
- return QuickGELU(config)
1496
- elif config.activation_type == "gelu":
1497
- return cast(Activation, GELU(approximate="none"))
1498
- elif config.activation_type == "gelu_tanh":
1499
- return cast(Activation, GELU(approximate="tanh"))
1500
- elif config.activation_type == "relu":
1501
- return cast(Activation, ReLU(inplace=False))
1502
- elif config.activation_type == "silu":
1503
- return cast(Activation, SiLU(inplace=False))
1504
- # elif config.activation_type == "llama_geglu":
1505
- # return LlamaGEGLU(config)
1506
- # elif config.activation_type == "llama_geglu_tanh":
1507
- # return LlamaGEGLUTanh(config)
1508
- elif config.activation_type == "llama_swiglu":
1509
- return LlamaSwiGLU()
1510
- elif config.activation_type == "swiglu":
1511
- return SwiGLU()
1512
- else:
1513
- raise NotImplementedError(f"Unknown activation: '{config.activation_type}'")
1514
-
1515
-
1516
- class QuickGELU(Activation):
1517
- def forward(self, x: torch.Tensor) -> torch.Tensor:
1518
- return x * torch.sigmoid(1.702 * x)
1519
-
1520
- @property
1521
- def output_multiplier(self) -> float:
1522
- return 1.0
1523
-
1524
-
1525
- class GELU(nn.GELU):
1526
- @property
1527
- def output_multiplier(self) -> float:
1528
- return 1.0
1529
-
1530
-
1531
- class ReLU(nn.ReLU):
1532
- @property
1533
- def output_multiplier(self) -> float:
1534
- return 1.0
1535
-
1536
-
1537
- class SiLU(nn.SiLU):
1538
- @property
1539
- def output_multiplier(self) -> float:
1540
- return 1.0
1541
-
1542
-
1543
- def causal_attention_bias(seq_len: int, device: torch.device) -> torch.FloatTensor:
1544
- att_bias = torch.triu(
1545
- torch.ones(seq_len, seq_len, device=device, dtype=torch.float),
1546
- diagonal=1,
1547
- )
1548
- att_bias.masked_fill_(att_bias == 1, torch.finfo(att_bias.dtype).min)
1549
- return att_bias.view(1, 1, seq_len, seq_len) # type: ignore
1550
-
1551
-
1552
- def get_causal_attention_bias(cache: BufferCache, seq_len: int, device: torch.device) -> torch.Tensor:
1553
- if (causal_bias := cache.get("causal_attention_bias")) is not None and causal_bias.shape[-1] >= seq_len:
1554
- if causal_bias.device != device:
1555
- causal_bias = causal_bias.to(device)
1556
- cache["causal_attention_bias"] = causal_bias
1557
- return causal_bias
1558
- with torch.autocast(device.type, enabled=False):
1559
- causal_bias = causal_attention_bias(seq_len, device)
1560
- cache["causal_attention_bias"] = causal_bias
1561
- return causal_bias
1562
-
1563
-
1564
- class LayerNormBase(nn.Module):
1565
- def __init__(
1566
- self,
1567
- config: MolmoConfig,
1568
- *,
1569
- size: Optional[int] = None,
1570
- elementwise_affine: Optional[bool] = True,
1571
- eps: float = 1e-05,
1572
- weight_initializer: Optional[Callable] = torch.ones,
1573
- bias_initializer: Optional[Callable] = torch.zeros,
1574
- ):
1575
- super().__init__()
1576
- self.config = config
1577
- self.eps = self.config.layer_norm_eps or eps
1578
- self.normalized_shape = (size or config.d_model,)
1579
- if elementwise_affine or (elementwise_affine is None and self.config.layer_norm_with_affine):
1580
- self.weight = nn.Parameter(weight_initializer(self.normalized_shape, device=config.init_device))
1581
- use_bias = self.config.bias_for_layer_norm
1582
- if use_bias is None:
1583
- use_bias = self.config.include_bias
1584
- if use_bias:
1585
- self.bias = nn.Parameter(bias_initializer(self.normalized_shape, device=config.init_device))
1586
- else:
1587
- self.register_parameter("bias", None)
1588
- else:
1589
- self.register_parameter("bias", None)
1590
- self.register_parameter("weight", None)
1591
-
1592
- @classmethod
1593
- def build(cls, config: FullMolmoConfig, size: Optional[int] = None, **kwargs):
1594
- if config.layer_norm_type == "default":
1595
- return LayerNorm(config, size=size, low_precision=False, **kwargs)
1596
- elif config.layer_norm_type == "low_precision":
1597
- return LayerNorm(config, size=size, low_precision=True, **kwargs)
1598
- elif config.layer_norm_type == "rms":
1599
- return RMSLayerNorm(config, size=size, **kwargs)
1600
- else:
1601
- raise NotImplementedError(f"Unknown LayerNorm type: '{config.layer_norm_type}'")
1602
-
1603
-
1604
- class RMSLayerNorm(LayerNormBase):
1605
- """
1606
- RMS layer norm, a simplified :class:`LayerNorm` implementation
1607
- """
1608
-
1609
- def __init__(
1610
- self,
1611
- config: FullMolmoConfig,
1612
- size: Optional[int] = None,
1613
- elementwise_affine: Optional[bool] = None,
1614
- eps: float = 1e-5,
1615
- ):
1616
- super().__init__(config, size=size, elementwise_affine=elementwise_affine, eps=eps)
1617
-
1618
- def forward(self, x: torch.Tensor) -> torch.Tensor:
1619
- with torch.autocast(enabled=False, device_type=x.device.type):
1620
- og_dtype = x.dtype
1621
- x = x.to(torch.float32)
1622
- variance = x.pow(2).mean(-1, keepdim=True)
1623
- x = x * torch.rsqrt(variance + self.eps)
1624
- x = x.to(og_dtype)
1625
-
1626
- if self.weight is not None:
1627
- if self.bias is not None:
1628
- return self.weight * x + self.bias
1629
- else:
1630
- return self.weight * x
1631
- else:
1632
- return x
1633
-
1634
-
1635
- class LayerNorm(LayerNormBase):
1636
- """
1637
- The default :class:`LayerNorm` implementation which can optionally run in low precision.
1638
- """
1639
-
1640
- def __init__(
1641
- self,
1642
- config: FullMolmoConfig,
1643
- size: Optional[int] = None,
1644
- low_precision: bool = False,
1645
- elementwise_affine: Optional[bool] = None,
1646
- eps: float = 1e-05,
1647
- ):
1648
- super().__init__(config, size=size, elementwise_affine=elementwise_affine, eps=eps)
1649
- self.low_precision = low_precision
1650
-
1651
- def forward(self, x: torch.Tensor) -> torch.Tensor:
1652
- if self.low_precision:
1653
- module_device = x.device
1654
- downcast_x = self._cast_if_autocast_enabled(x)
1655
- downcast_weight = (
1656
- self._cast_if_autocast_enabled(self.weight) if self.weight is not None else self.weight
1657
- )
1658
- downcast_bias = self._cast_if_autocast_enabled(self.bias) if self.bias is not None else self.bias
1659
- with torch.autocast(enabled=False, device_type=module_device.type):
1660
- return F.layer_norm(
1661
- downcast_x, self.normalized_shape, weight=downcast_weight, bias=downcast_bias, eps=self.eps
1662
- )
1663
- else:
1664
- return F.layer_norm(x, self.normalized_shape, weight=self.weight, bias=self.bias, eps=self.eps)
1665
-
1666
-
1667
- class Molmo(nn.Module):
1668
- def __init__(self, config: FullMolmoConfig, init_params: bool = True):
1669
- super().__init__()
1670
- self.config = config
1671
- self.__cache = BufferCache()
1672
-
1673
- # Validate config.
1674
- if self.config.embedding_size is not None and self.config.embedding_size != self.config.vocab_size:
1675
- if self.config.embedding_size < self.config.vocab_size:
1676
- raise MolmoConfigurationError("embedding size should be at least as big as vocab size")
1677
- elif self.config.embedding_size % 128 != 0:
1678
- import warnings
1679
-
1680
- warnings.warn(
1681
- "Embedding size is not a multiple of 128! This could hurt throughput performance.", UserWarning
1682
- )
1683
- torch.backends.cuda.enable_flash_sdp(True)
1684
- torch.backends.cuda.enable_mem_efficient_sdp(False) # this is super slow so make sure torch won't use it
1685
-
1686
- wte = None
1687
- if self.config.additional_vocab_size is not None:
1688
- wte = Embedding(
1689
- config.embedding_size or config.vocab_size,
1690
- config.additional_vocab_size,
1691
- config.d_model,
1692
- device=config.init_device,
1693
- initializer_range=config.initializer_range,
1694
- new_embed_initializer_range=config.new_embedding_init_range
1695
- )
1696
- else:
1697
- wte=nn.Embedding(
1698
- config.embedding_size or config.vocab_size, config.d_model, device=config.init_device
1699
- )
1700
-
1701
- self.transformer = nn.ModuleDict(
1702
- dict(
1703
- wte=wte,
1704
- emb_drop=Dropout(config.embedding_dropout),
1705
- ln_f=LayerNorm.build(config),
1706
- )
1707
- )
1708
-
1709
- blocks = [MolmoBlock.build(i, config, self.__cache) for i in range(config.n_layers)]
1710
- if self.config.block_group_size > 1:
1711
- raise NotImplementedError()
1712
- else:
1713
- self.transformer.update({"blocks": nn.ModuleList(blocks)})
1714
-
1715
- if not self.config.rope:
1716
- self.transformer.update(
1717
- {"wpe": nn.Embedding(config.max_sequence_length, config.d_model, device=config.init_device)}
1718
- )
1719
- if not config.weight_tying:
1720
- self.transformer.update(
1721
- {
1722
- "ff_out": nn.Linear(
1723
- config.d_model,
1724
- config.embedding_size or config.vocab_size,
1725
- bias=config.include_bias,
1726
- device=config.init_device,
1727
- )
1728
- }
1729
- )
1730
-
1731
- self.vision_backbone: Optional[OLMoVisionBackbone] = None
1732
- if config.vision_backbone is not None:
1733
- self.vision_backbone = OLMoPretrainedVisionBackbone(config)
1734
-
1735
- self.__num_fwd_flops: Optional[int] = None
1736
-
1737
- def reset_parameters(self):
1738
- if self.vision_backbone is not None:
1739
- self.vision_backbone.reset_parameters()
1740
- self.reset_non_vision_parameters()
1741
-
1742
- def reset_non_vision_parameters(self):
1743
- self.transformer.wte.reset_parameters()
1744
- if hasattr(self.transformer.wte, "new_embedding"):
1745
- nn.init.normal_(self.transformer.wte.new_embedding, std=self.config.new_embedding_init_range)
1746
-
1747
- if hasattr(self.transformer, "wpe"):
1748
- nn.init.normal_(self.transformer.wpe, mean=0.0, std=1.0)
1749
-
1750
- self.transformer.ln_f.reset_parameters() # type: ignore
1751
-
1752
- if hasattr(self.transformer, "ff_out"):
1753
- nn.init.normal_(self.transformer.ff_out, mean=0.0, std=0.02)
1754
-
1755
- if self.config.block_group_size == 1:
1756
- for block in self.transformer.blocks:
1757
- block.reset_parameters()
1758
- else:
1759
- for block_group in self.transformer.block_groups:
1760
- block_group.reset_parameters()
1761
-
1762
-
1763
- def forward(
1764
- self,
1765
- input_ids: torch.LongTensor,
1766
- input_embeddings: Optional[torch.FloatTensor] = None,
1767
- attention_mask: Optional[torch.Tensor] = None,
1768
- attention_bias: Optional[torch.Tensor] = None,
1769
- response_mask: Optional[torch.Tensor] = None,
1770
- images: Optional[torch.Tensor] = None,
1771
- image_masks: Optional[torch.Tensor] = None,
1772
- image_input_idx: Optional[torch.Tensor] = None,
1773
- subsegment_ids: Optional[torch.Tensor] = None,
1774
- position_ids: Optional[torch.Tensor] = None,
1775
- past_key_values: Optional[Sequence[Tuple[torch.Tensor, torch.Tensor]]] = None,
1776
- use_cache: bool = False,
1777
- last_logits_only: bool = False,
1778
- output_hidden_states: Optional[bool] = None,
1779
- append_last_valid_logits: Optional[torch.Tensor] = None,
1780
- ) -> ModelOutput:
1781
- """
1782
- :param input_ids: A tensor of shape `(batch_size, seq_len)`.
1783
- :param input_embeddings: A tensor of shape `(batch_size, seq_len, d_model)` with input
1784
- embeddings. When provided, it is treated as the output of the input embedding layer.
1785
- :param attention_mask: A tensor of shape `(batch_size, seq_len)` that indicates
1786
- which input IDs are masked. A `1` value in the mask means that
1787
- the corresponding input ID should *not* be ignored. A `0` means
1788
- that the corresponding input ID is masked.
1789
-
1790
- This has the same meaning as the `attention_mask` in HuggingFace's `transformers`
1791
- library.
1792
- :param attention_bias: A tensor of shape `(batch_size, 1, seq_len, seq_len)`,
1793
- `(1, 1, seq_len, seq_len)`, or `(seq_len, seq_len)`. This is used
1794
- to introduce causal or other biases.
1795
-
1796
- If the tensor is a bool or byte tensor, a `True` or `1` at `attention_bias[:, :, i, j]`
1797
- indicates that the i-th element in the sequence is allowed to attend to the j-th
1798
- element in the sequence.
1799
-
1800
- If the tensor is a float tensor, it will just be added to the attention
1801
- scores before the softmax.
1802
-
1803
- The default is causal, which corresponds to a lower-diagonal byte matrix of ones.
1804
- :param response_mask: A tensor of shape `(batch_size, seq_len)` that indicates
1805
- the response mask. A `1` value in the mask means that the corresponding token
1806
- is a response token. A `0` means that the corresponding token is not
1807
- a response token.
1808
- :param past_key_values: Pre-computed keys and values for each attention block.
1809
- Can be used to speed up sequential decoding. The `input_ids` which have
1810
- their past given to this model should not be passed as `input_ids` as they have already been computed.
1811
- :param use_cache: If `True`, return key and value tensors for each block.
1812
- :param last_logits_only: If `True`, only compute the logits for the last token of each sequence.
1813
- This can speed up decoding when you only care about the next token.
1814
- """
1815
- output_hidden_states = output_hidden_states if output_hidden_states is not None else False
1816
-
1817
- if past_key_values:
1818
- assert len(past_key_values) == self.config.n_layers
1819
-
1820
- has_image = images is not None
1821
-
1822
- assert not (has_image and input_embeddings is not None), "Cannot provide both images and input embeddings."
1823
- assert not (has_image and past_key_values is not None), "Cached key and values should not be used with images."
1824
-
1825
- batch_size, seq_len = input_ids.size() if input_embeddings is None else input_embeddings.size()[:2]
1826
- if past_key_values is None:
1827
- past_length = 0
1828
- else:
1829
- past_length = past_key_values[0][0].size(-2)
1830
-
1831
- if self.config.use_position_ids and attention_mask is None:
1832
- attention_mask = input_ids != -1
1833
-
1834
- if subsegment_ids is not None:
1835
- assert not use_cache, "Subsegment_ids cannot be used with cache."
1836
- subsegment_mask = subsegment_ids.unsqueeze(2) <= subsegment_ids.unsqueeze(1)
1837
- attention_mask = (
1838
- subsegment_mask.to(attention_mask.dtype) *
1839
- attention_mask.unsqueeze(2) *
1840
- attention_mask.unsqueeze(1))
1841
- if position_ids is None:
1842
- raise ValueError(f"Positioned ids must be given if using subsegment_ids")
1843
- else:
1844
- if self.config.use_position_ids and position_ids is None:
1845
- position_ids = torch.clamp(
1846
- torch.cumsum(attention_mask.to(torch.int32), dim=-1) - 1,
1847
- min=0,
1848
- ).broadcast_to((batch_size, attention_mask.shape[-1]))
1849
-
1850
- # Get embeddings of input.
1851
- # shape: (batch_size, seq_len, d_model)
1852
- if input_ids is not None:
1853
- input_ids = input_ids * (input_ids != -1).to(input_ids.dtype)
1854
- x = self.transformer.wte(input_ids) if input_embeddings is None else input_embeddings # type: ignore
1855
-
1856
- num_image: Optional[int] = None
1857
- if images is not None:
1858
- # shape: (batch_size, num_image, num_patch, d_model)
1859
- # cls_embed: (batch_size, num_image, d_model)
1860
- image_features, cls_embed = self.vision_backbone(images, image_masks)
1861
- num_image, num_patch = image_features.shape[1:3]
1862
- assert image_input_idx.shape == (batch_size, num_image, num_patch)
1863
-
1864
- # inster the image feature into the embedding.
1865
- image_features = image_features.view(batch_size, num_image * num_patch, -1)
1866
- image_input_idx = image_input_idx.view(batch_size, num_image * num_patch)
1867
-
1868
- valid = image_input_idx >= 0
1869
- batch_idx = torch.arange(batch_size, device=x.device)
1870
- batch_idx = torch.tile(batch_idx[:, None], [1, image_features.shape[1]])
1871
-
1872
- # For hf demo/endpoint
1873
- image_features = image_features.to(x.device)
1874
-
1875
- x[batch_idx[valid], image_input_idx[valid]] += image_features[valid]
1876
-
1877
- if not self.config.rope:
1878
- # Get positional embeddings.
1879
- # shape: (1, seq_len)
1880
- pos = torch.arange(past_length, past_length + seq_len, dtype=torch.long, device=x.device).unsqueeze(0)
1881
- # shape: (1, seq_len, d_model)
1882
- pos_emb = self.transformer.wpe(pos) # type: ignore
1883
- x = pos_emb + x
1884
-
1885
- # Add input + positional embeddings and apply dropout.
1886
- # shape: (batch_size, seq_len, d_model)
1887
- x = self.transformer.emb_drop(x) # type: ignore
1888
-
1889
- # normalized
1890
- if self.config.normalize_input_embeds:
1891
- x = x * (self.config.d_model ** 0.5)
1892
-
1893
- # Transform the attention mask into what the blocks expect.
1894
- if attention_mask is not None:
1895
- # shape: (batch_size, 1, 1, seq_len)
1896
- if len(attention_mask.shape) == 2:
1897
- attention_mask = attention_mask[:, :past_length + seq_len]
1898
- attention_mask = attention_mask.to(dtype=torch.float).view(batch_size, -1)[:, None, None, :]
1899
- else:
1900
- attention_mask = attention_mask.unsqueeze(1).to(dtype=torch.float)
1901
- attention_mask = (1.0 - attention_mask) * torch.finfo(attention_mask.dtype).min
1902
-
1903
- # Merge attention mask with attention bias.
1904
- if (
1905
- attention_bias is not None
1906
- or attention_mask is not None
1907
- # NOTE (epwalsh): we need to initialize the attn bias in order for attn to work properly
1908
- # with key+value cache. Otherwise `F.scaled_dot_product_attention()` doesn't seem to compute
1909
- # scores correctly.
1910
- or past_key_values is not None
1911
- ):
1912
- if attention_bias is None:
1913
- attention_bias = get_causal_attention_bias(self.__cache, past_length + seq_len, x.device)
1914
- elif attention_bias.dtype in (torch.int8, torch.bool):
1915
- attention_bias = attention_bias.to(dtype=torch.float)
1916
- attention_bias.masked_fill_(attention_bias == 0.0, torch.finfo(attention_bias.dtype).min)
1917
-
1918
- # Transform to the right shape and data type.
1919
- mask_len = seq_len
1920
- if attention_mask is not None:
1921
- mask_len = attention_mask.shape[-1]
1922
- elif past_key_values is not None:
1923
- mask_len = past_key_values[0][0].shape[-2] + seq_len
1924
- attention_bias = attention_bias[:, :, :mask_len, :mask_len].to(dtype=torch.float)
1925
-
1926
- # Add in the masking bias.
1927
- if attention_mask is not None:
1928
- attention_bias = attention_bias + attention_mask
1929
- # Might get -infs after adding attention mask, since dtype.min + dtype.min = -inf.
1930
- # `F.scaled_dot_product_attention()` doesn't handle -inf like you'd expect, instead
1931
- # it can produce NaNs.
1932
- ensure_finite_(attention_bias, check_neg_inf=True, check_pos_inf=False)
1933
-
1934
- attn_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = [] if use_cache else None
1935
-
1936
- # decoder layers
1937
- all_hidden_states = []
1938
-
1939
- # Apply blocks one-by-one.
1940
- if self.config.block_group_size == 1:
1941
- for block_idx, block in enumerate(self.transformer.blocks):
1942
- if output_hidden_states:
1943
- # add hidden states
1944
- all_hidden_states.append(x)
1945
-
1946
- layer_past = None if past_key_values is None else past_key_values[block_idx]
1947
- x, cache = block(x, attention_bias=attention_bias, position_ids=position_ids, layer_past=layer_past, use_cache=use_cache)
1948
-
1949
- if attn_key_values is not None:
1950
- assert cache is not None
1951
- attn_key_values.append(cache)
1952
- else:
1953
- for group_idx, block_group in enumerate(self.transformer.block_groups):
1954
- if output_hidden_states:
1955
- # add hidden states
1956
- all_hidden_states.append(x)
1957
-
1958
- layers_past = (
1959
- None
1960
- if past_key_values is None
1961
- else past_key_values[
1962
- group_idx * self.config.block_group_size : (group_idx + 1) * self.config.block_group_size
1963
- ]
1964
- )
1965
- x, cache = block_group(
1966
- x, attention_bias=attention_bias, position_ids=position_ids, layers_past=layers_past, use_cache=use_cache
1967
- )
1968
- if attn_key_values is not None:
1969
- assert cache is not None
1970
- attn_key_values.extend(cache)
1971
-
1972
- if last_logits_only:
1973
- # shape: (batch_size, 1, d_model)
1974
- if append_last_valid_logits is not None:
1975
- last_valid_output = x[
1976
- torch.arange(x.shape[0], device=x.device), append_last_valid_logits.to(x.device)]
1977
- x = last_valid_output.unsqueeze(1)
1978
- else:
1979
- x = x[:, -1, :].unsqueeze(1)
1980
-
1981
- # Apply final layer norm.
1982
- # shape: (batch_size, seq_len or 1, d_model)
1983
- x = self.transformer.ln_f(x) # type: ignore
1984
- if output_hidden_states:
1985
- # add final hidden state post-final-layernorm, following HuggingFace's convention
1986
- all_hidden_states.append(x)
1987
-
1988
- # Get logits.
1989
- # shape: (batch_size, seq_len or 1, vocab_size)
1990
- if self.config.weight_tying:
1991
- logits = F.linear(x, self.transformer.wte.weight, None) # type: ignore
1992
- else:
1993
- logits = self.transformer.ff_out(x) # type: ignore
1994
- if self.config.scale_logits:
1995
- logits.mul_(1 / math.sqrt(self.config.d_model))
1996
-
1997
- if not last_logits_only and append_last_valid_logits is not None:
1998
- last_valid_logit = logits[
1999
- torch.arange(logits.shape[0], device=logits.device), append_last_valid_logits]
2000
- logits = torch.cat([logits[:, :-1], last_valid_logit[:, None]], dim=1)
2001
-
2002
- return ModelOutput(logits=logits, attn_key_values=attn_key_values, hidden_states=tuple(all_hidden_states) if output_hidden_states else None) # type: ignore[arg-type]
2003
-
2004
-
2005
- class MolmoForCausalLM(PreTrainedModel):
2006
- config_class = MolmoConfig
2007
- base_model_prefix = "model"
2008
- _no_split_modules = ["MolmoBlock"]
2009
-
2010
- def __init__(self, config: MolmoConfig, model: Optional[Molmo] = None, init_params: bool = False):
2011
- super().__init__(config)
2012
-
2013
- if not model:
2014
- full_config = FullMolmoConfig(
2015
- image_padding_embed="pad_and_partial_pad",
2016
- image_pooling_2d="attention-meanq",
2017
- attention_layer_norm=config.attention_layer_norm,
2018
- rope_impl="llama",
2019
- vocab_size=config.vocab_size,
2020
- max_sequence_length=config.max_position_embeddings,
2021
- qkv_bias=config.qkv_bias,
2022
- norm_after=config.norm_after,
2023
- embedding_size=config.embedding_size,
2024
- attention_type="sdpa",
2025
- embedding_dropout=0,
2026
- attention_dropout=0,
2027
- residual_dropout=0,
2028
- rope=True,
2029
- weight_tying=False,
2030
- include_bias=False,
2031
- d_model=config.hidden_size,
2032
- mlp_hidden_size=config.intermediate_size,
2033
- n_layers=config.num_hidden_layers,
2034
- additional_vocab_size=128,
2035
- n_heads=config.num_attention_heads,
2036
- n_kv_heads=config.num_key_value_heads,
2037
- rope_theta=config.rope_theta,
2038
- layer_norm_eps=config.layer_norm_eps,
2039
- layer_norm_type=config.layer_norm_type,
2040
- vit_layers=[-2, -9],
2041
- vision_backbone=VisionBackboneConfig(
2042
- image_default_input_size=(336, 336),
2043
- image_patch_size=14,
2044
- image_pos_patch_size=14,
2045
- image_emb_dim=1024,
2046
- image_num_heads=16,
2047
- image_num_key_value_heads=16,
2048
- image_num_layers=23,
2049
- image_head_dim=64,
2050
- image_mlp_dim=4096,
2051
- image_mlp_activations="quick_gelu",
2052
- image_dropout_rate=0.0,
2053
- image_num_pos=577,
2054
- image_norm_eps=1e-5,
2055
- attention_dropout=0.0,
2056
- residual_dropout=0.0,
2057
- initializer_range=0.02,
2058
- )
2059
- )
2060
- self.model = Molmo(full_config, init_params=init_params)
2061
- else:
2062
- self.model = model
2063
-
2064
-
2065
- def forward(
2066
- self,
2067
- input_ids: torch.LongTensor = None,
2068
- inputs_embeds: Optional[torch.FloatTensor] = None,
2069
- attention_mask: Optional[torch.Tensor] = None,
2070
- attention_bias: Optional[torch.Tensor] = None,
2071
- response_mask: Optional[torch.Tensor] = None,
2072
- images: Optional[torch.Tensor] = None,
2073
- image_masks: Optional[torch.Tensor] = None,
2074
- image_input_idx: Optional[torch.Tensor] = None,
2075
- subsegment_ids: Optional[torch.Tensor] = None,
2076
- position_ids: Optional[torch.Tensor] = None,
2077
- past_key_values: Optional[List[torch.FloatTensor]] = None,
2078
- labels: Optional[torch.LongTensor] = None,
2079
- loss_masks: Optional[torch.Tensor] = None,
2080
- use_cache: Optional[bool] = None,
2081
- last_logits_only: Optional[bool] = None,
2082
- output_attentions: Optional[bool] = None,
2083
- output_hidden_states: Optional[bool] = None,
2084
- append_last_valid_logits: Optional[torch.Tensor] = None,
2085
- return_dict: Optional[bool] = None,
2086
- cache_position: Optional[
2087
- Cache
2088
- ] = None, # This is a hack mitigation of an issue in transformers `4.39.x` https://github.com/huggingface/transformers/issues/29426
2089
- ) -> Union[Tuple, CausalLMOutputWithPast]:
2090
- if use_cache is None:
2091
- use_cache = self.config.use_cache
2092
-
2093
- if output_attentions:
2094
- raise ValueError("output_attentions is not yet supported in Molmo")
2095
-
2096
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
2097
-
2098
- # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
2099
- outputs = self.model.forward(
2100
- input_ids=input_ids,
2101
- input_embeddings=inputs_embeds,
2102
- attention_mask=attention_mask,
2103
- attention_bias=attention_bias,
2104
- response_mask=response_mask,
2105
- images=images,
2106
- image_masks=image_masks,
2107
- image_input_idx=image_input_idx,
2108
- subsegment_ids=subsegment_ids,
2109
- position_ids=position_ids,
2110
- past_key_values=past_key_values,
2111
- use_cache=use_cache,
2112
- last_logits_only=last_logits_only,
2113
- output_hidden_states=output_hidden_states,
2114
- append_last_valid_logits=append_last_valid_logits,
2115
- )
2116
-
2117
- logits = outputs.logits
2118
- hidden_states = outputs.hidden_states
2119
-
2120
- loss = None
2121
- if labels is not None:
2122
- if loss_masks is not None:
2123
- loss_masks = loss_masks * (loss_masks > 0)
2124
- batch_size_in_tokens = max(loss_masks.sum().item(), 1)
2125
- labels = labels.long()
2126
- labels.masked_fill_(~(loss_masks > 0), -100)
2127
- labels = labels.view(-1)
2128
- logits_for_loss = logits.to(torch.float32).view(-1, logits.size(-1))
2129
- loss_fct = torch.nn.CrossEntropyLoss(ignore_index=-100, reduction='none')
2130
- loss = loss_fct(logits_for_loss, labels)
2131
- loss = loss.view(input_ids.shape[0], -1)
2132
- loss = loss * loss_masks
2133
- loss = loss.sum() / batch_size_in_tokens
2134
- use_zloss = getattr(self.config, "softmax_auxiliary_loss", False)
2135
- if use_zloss:
2136
- z_squared = logits_for_loss.logsumexp(-1).pow(2)
2137
- z_loss = self.config.softmax_auxiliary_loss_scale * z_squared
2138
- z_loss = z_loss.view(input_ids.shape[0], -1)
2139
- z_loss = z_loss * loss_masks
2140
- z_loss = z_loss.sum() / batch_size_in_tokens
2141
- loss += z_loss
2142
- else:
2143
- # Shift so that tokens < n predict n
2144
- shift_logits = logits[..., :-1, :].contiguous()
2145
- shift_labels = labels[..., 1:].contiguous()
2146
- # Flatten the tokens
2147
- loss_fct = torch.nn.CrossEntropyLoss()
2148
- shift_logits = shift_logits.view(-1, self.config.embedding_size)
2149
- shift_labels = shift_labels.view(-1)
2150
- # Enable model parallelism
2151
- shift_labels = shift_labels.to(shift_logits.device)
2152
- loss = loss_fct(shift_logits, shift_labels)
2153
-
2154
- if not return_dict:
2155
- output = (logits,) + outputs[1:]
2156
- return (loss,) + output if loss is not None else output
2157
-
2158
- return CausalLMOutputWithPast(
2159
- loss=loss,
2160
- logits=logits,
2161
- past_key_values=outputs.attn_key_values,
2162
- hidden_states=hidden_states,
2163
- )
2164
-
2165
- def can_generate(self) -> bool:
2166
- return True
2167
-
2168
- @torch.no_grad()
2169
- def generate_from_batch(
2170
- self,
2171
- batch: Dict[str, Any],
2172
- generation_config: Optional[GenerationConfig] = None,
2173
- **kwargs,
2174
- ):
2175
- if generation_config is not None:
2176
- assert generation_config.use_cache
2177
-
2178
- images = batch.get("images")
2179
- image_masks = batch.get("image_masks")
2180
- image_input_idx = batch.get("image_input_idx")
2181
-
2182
- # Validate inputs.
2183
- input_ids = batch["input_ids"]
2184
- batch_size, seq_len = input_ids.shape
2185
- attention_mask = batch.get("attention_mask", None)
2186
- max_new_tokens = generation_config.max_new_tokens
2187
- assert max_new_tokens is not None
2188
- mask_len = seq_len + max_new_tokens if self.config.use_position_ids else seq_len
2189
- position_ids: Optional[torch.Tensor] = None
2190
- append_last_valid_logits: Optional[torch.Tensor] = None
2191
- if self.config.use_position_ids and attention_mask is None:
2192
- attention_mask = input_ids != -1
2193
- position_ids = torch.clamp(
2194
- torch.cumsum(attention_mask.to(torch.int32), dim=-1) - 1,
2195
- min=0
2196
- )
2197
- append_last_valid_logits = attention_mask.long().sum(dim=-1) - 1
2198
- attention_mask = torch.cat(
2199
- [attention_mask, attention_mask.new_ones((batch_size, max_new_tokens))],
2200
- dim=1,
2201
- )
2202
- if attention_mask is not None:
2203
- assert attention_mask.shape == (batch_size, mask_len)
2204
-
2205
- out = super().generate(
2206
- batch["input_ids"],
2207
- generation_config,
2208
- attention_mask=attention_mask,
2209
- images=images,
2210
- image_masks=image_masks,
2211
- image_input_idx=image_input_idx,
2212
- position_ids=position_ids,
2213
- append_last_valid_logits=append_last_valid_logits,
2214
- **kwargs,
2215
- )
2216
-
2217
- return out
2218
-
2219
- def prepare_inputs_for_generation(
2220
- self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple]] = None, **kwargs
2221
- ):
2222
- if past_key_values:
2223
- # This is because we want the model to only process the last generated token.
2224
- input_ids = input_ids[:, -1:]
2225
-
2226
- if self.config.use_position_ids:
2227
- attention_mask = kwargs.get("attention_mask")
2228
- images = kwargs.get("images")
2229
- image_masks = kwargs.get("image_masks")
2230
- image_input_idx = kwargs.get("image_input_idx")
2231
- position_ids = kwargs.get("position_ids")
2232
- append_last_valid_logits = kwargs.get("append_last_valid_logits")
2233
- model_inputs = {
2234
- "input_ids": input_ids,
2235
- "attention_mask": attention_mask,
2236
- "position_ids": position_ids,
2237
- "past_key_values": past_key_values,
2238
- "use_cache": True,
2239
- "last_logits_only": True,
2240
- }
2241
- if past_key_values is None:
2242
- model_inputs["images"] = images
2243
- model_inputs["image_masks"] = image_masks
2244
- model_inputs["image_input_idx"] = image_input_idx
2245
- model_inputs["append_last_valid_logits"] = append_last_valid_logits
2246
- else:
2247
- model_inputs = {"input_ids": input_ids, "past_key_values": past_key_values}
2248
-
2249
- model_inputs.update(kwargs)
2250
- model_inputs["use_cache"] = kwargs.pop("use_cache", self.config.use_cache)
2251
- return model_inputs
2252
-
2253
- def _update_model_kwargs_for_generation(
2254
- self,
2255
- outputs: ModelOutput,
2256
- model_kwargs: Dict[str, Any],
2257
- is_encoder_decoder: bool = False,
2258
- num_new_tokens: int = 1,
2259
- ) -> Dict[str, Any]:
2260
- if self.config.use_position_ids:
2261
- model_kwargs["position_ids"] = model_kwargs["position_ids"][:, -1:] + 1
2262
- if "append_last_valid_logits" in model_kwargs:
2263
- del model_kwargs["append_last_valid_logits"]
2264
- if "images" in model_kwargs:
2265
- del model_kwargs["images"]
2266
- del model_kwargs["image_masks"]
2267
- del model_kwargs["image_input_idx"]
2268
- cache_name, cache = super()._extract_past_from_model_output(outputs)
2269
- model_kwargs[cache_name] = cache
2270
- model_kwargs["cache_position"] = model_kwargs["cache_position"][-1:] + num_new_tokens
2271
- return model_kwargs
2272
-
2273
- def get_input_embeddings(self) -> torch.nn.Module:
2274
- return self.model.transformer.wte
2275
-
2276
- def set_input_embeddings(self, value: torch.nn.Module):
2277
- self.model.transformer.wte = value
2278
-
2279
- def get_output_embeddings(self):
2280
- if self.config.weight_tying:
2281
- return self.model.transformer.wte
2282
- else:
2283
- return self.model.transformer.ff_out
2284
-
2285
- def set_output_embeddings(self, value: torch.nn.Module):
2286
- if self.config.weight_tying:
2287
- self.model.transformer.wte = value
2288
- else:
2289
- self.model.transformer.ff_out = value
2290
-
2291
- def tie_weights(self):
2292
- """
2293
- This function is intentionally left as a no-op.
2294
-
2295
- Weight tying is handled as follows:
2296
- - When the model is initialized, the `ff_out` layer is conditionally defined based on the `weight_tying` configuration.
2297
- See: `if not config.weight_tying: self.transformer.update(...)` in `olmo/model.py`.
2298
- - When computing logits, the `wte` weights are used directly if `weight_tying` is enabled.
2299
- See: `if self.config.weight_tying: logits = F.linear(x, self.transformer.wte.weight, None)` in the `forward` method.
2300
-
2301
- Therefore, there is no need to explicitly tie the weights in this function.
2302
- """
2303
- pass
2304
-
2305
- def resize_token_embeddings(
2306
- self, new_num_tokens: Optional[int] = None, pad_to_multiple_of: Optional[int] = None
2307
- ) -> torch.nn.Embedding:
2308
- """
2309
- Resizes input token embeddings matrix of the model if `new_num_tokens != config.embedding_size`.
2310
-
2311
- Takes care of tying weights embeddings afterwards if the model class has a `tie_weights()` method.
2312
-
2313
- Arguments:
2314
- new_num_tokens (`int`, *optional*):
2315
- The new number of tokens in the embedding matrix. Increasing the size will add newly initialized
2316
- vectors at the end. Reducing the size will remove vectors from the end. If not provided or `None`, just
2317
- returns a pointer to the input tokens `torch.nn.Embedding` module of the model without doing anything.
2318
- pad_to_multiple_of (`int`, *optional*):
2319
- If set will pad the embedding matrix to a multiple of the provided value. If `new_num_tokens` is set to
2320
- `None` will just pad the embedding to a multiple of `pad_to_multiple_of`.
2321
-
2322
- This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
2323
- `>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128. For more
2324
- details about this, or help on choosing the correct value for resizing, refer to this guide:
2325
- https://docs.nvidia.com/deeplearning/performance/dl-performance-matrix-multiplication/index.html#requirements-tc
2326
-
2327
- Return:
2328
- `torch.nn.Embedding`: Pointer to the input tokens Embeddings Module of the model.
2329
-
2330
- Note:
2331
- This method differs from the base class implementation by resizing the `embedding_size` attribute of the
2332
- model configuration instead of the `vocab_size`. It also includes a warning if the resized `embedding_size`
2333
- is less than the `vocab_size`. In OLMo, `embedding_size` refers to the dimensionality of the model's token
2334
- embeddings, while `vocab_size` refers to the number of unique tokens in the vocabulary.
2335
- """
2336
- model_embeds = self._resize_token_embeddings(new_num_tokens, pad_to_multiple_of)
2337
- if new_num_tokens is None and pad_to_multiple_of is None:
2338
- return model_embeds
2339
-
2340
- # Update base model and current model config
2341
- self.config.embedding_size = model_embeds.weight.shape[0]
2342
- self.model.config.embedding_size = model_embeds.weight.shape[0]
2343
-
2344
- # Check if the embedding size is less than the vocab size
2345
- if self.config.embedding_size < self.config.vocab_size:
2346
- warning_message = (
2347
- f"Resizing token embeddings to size {self.config.embedding_size}, which is less than the vocab size "
2348
- f"{self.config.vocab_size} defined in the model configuration. Make sure your tokenizer's vocabulary "
2349
- "size is less than or equal to the new token embedding size."
2350
- )
2351
- log.warning(warning_message)
2352
-
2353
- # Tie weights again if needed
2354
- self.tie_weights()
2355
-
2356
- return model_embeds
2357
-
2358
-
2359
- # Always register for multi-modal features
2360
- AutoModelForCausalLM.register(MolmoConfig, MolmoForCausalLM)