1024m commited on
Commit
297efeb
1 Parent(s): f57712d

Upload modeling_molmo.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_molmo.py +2368 -0
modeling_molmo.py ADDED
@@ -0,0 +1,2368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 LayerNormFp32(nn.LayerNorm):
729
+ """Subclass torch's LayerNorm to handle fp16 (by casting to float32 and back).
730
+ Derived from https://github.com/mlfoundations/open_clip/blob/main/src/open_clip/transformer.py.
731
+ """
732
+
733
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
734
+ orig_type = x.dtype
735
+ x = F.layer_norm(x.to(torch.float32), self.normalized_shape, self.weight, self.bias, self.eps)
736
+ return x.to(orig_type)
737
+
738
+
739
+ class ViTMLP(nn.Module):
740
+ def __init__(self, config: FullMolmoConfig):
741
+ super().__init__()
742
+ self.config = config
743
+ v_cfg = config.vision_backbone
744
+
745
+ self.w1 = nn.Linear(
746
+ v_cfg.image_emb_dim,
747
+ v_cfg.image_mlp_dim,
748
+ bias=True,
749
+ device=config.init_device,
750
+ )
751
+ # Activation function.
752
+ cfg = deepcopy(config)
753
+ cfg.activation_type = v_cfg.image_mlp_activations
754
+ self.act = Activation.build(cfg)
755
+ self.w2 = nn.Linear(
756
+ v_cfg.image_mlp_dim,
757
+ v_cfg.image_emb_dim,
758
+ bias=True,
759
+ device=config.init_device,
760
+ )
761
+
762
+ def reset_parameters(self):
763
+ v_cfg = self.config.vision_backbone
764
+ nn.init.trunc_normal_(self.w1.weight, std=math.sqrt(1 / v_cfg.image_emb_dim), a=-2.0, b=2.0)
765
+ nn.init.trunc_normal_(self.w2.weight, std=math.sqrt(1 / v_cfg.image_mlp_dim), a=-2.0, b=2.0)
766
+ nn.init.zeros_(self.w1.bias)
767
+ nn.init.zeros_(self.w2.bias)
768
+
769
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
770
+ x = self.w1(x)
771
+ x = self.act(x)
772
+ x = self.w2(x)
773
+ return x
774
+
775
+
776
+
777
+ class ResidualAttentionBlock(nn.Module):
778
+
779
+ def __init__(self, config: FullMolmoConfig):
780
+ super().__init__()
781
+ self.config = config
782
+
783
+ v_cfg = config.vision_backbone
784
+ self.attention = MultiHeadDotProductAttention(config)
785
+ self.feed_forward = ViTMLP(config)
786
+ self.attention_norm = nn.LayerNorm(
787
+ v_cfg.image_emb_dim,
788
+ eps=v_cfg.image_norm_eps,
789
+ device=config.init_device,
790
+ )
791
+ self.ffn_norm = nn.LayerNorm(
792
+ v_cfg.image_emb_dim,
793
+ eps=v_cfg.image_norm_eps,
794
+ device=config.init_device,
795
+ )
796
+
797
+ def reset_parameters(self):
798
+ self.attention.reset_parameters()
799
+ self.feed_forward.reset_parameters()
800
+ self.attention_norm.reset_parameters()
801
+ self.ffn_norm.reset_parameters()
802
+
803
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
804
+ x = x + self.attention(self.attention_norm(x))
805
+ x = x + self.feed_forward(self.ffn_norm(x))
806
+ return x
807
+
808
+
809
+ class BlockCollection(nn.Module):
810
+
811
+ def __init__(self, config: FullMolmoConfig):
812
+ super().__init__()
813
+ self.config = config
814
+ self.grad_checkpointing: bool = False
815
+
816
+ v_cfg = config.vision_backbone
817
+ self.resblocks = nn.ModuleList([
818
+ ResidualAttentionBlock(config) for _ in range(v_cfg.image_num_layers)
819
+ ])
820
+
821
+ def reset_parameters(self):
822
+ for r in self.resblocks:
823
+ r.reset_parameters()
824
+
825
+ def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
826
+ hidden_states = []
827
+ for r in self.resblocks:
828
+ x = r(x)
829
+ hidden_states.append(x)
830
+ return hidden_states
831
+
832
+
833
+ class VisionTransformer(nn.Module):
834
+
835
+ def __init__(self, config: FullMolmoConfig):
836
+ super().__init__()
837
+ self.config = config
838
+
839
+ v_cfg = config.vision_backbone
840
+ # class embeddings and positional embeddings
841
+ self.scale = v_cfg.image_emb_dim ** -0.5
842
+ self.class_embedding = nn.Parameter(
843
+ torch.zeros(v_cfg.image_emb_dim, device=config.init_device),
844
+ )
845
+ self.num_prefix_tokens: int = 1
846
+ self.positional_embedding = nn.Parameter(
847
+ torch.zeros(v_cfg.image_num_pos, v_cfg.image_emb_dim, device=config.init_device),
848
+ )
849
+
850
+ image_patch_size = v_cfg.image_patch_size
851
+ self.patch_embedding = nn.Linear(
852
+ image_patch_size * image_patch_size * 3,
853
+ v_cfg.image_emb_dim,
854
+ bias=False,
855
+ device=config.init_device,
856
+ )
857
+
858
+ self.pre_ln = LayerNormFp32(
859
+ v_cfg.image_emb_dim,
860
+ eps=v_cfg.image_norm_eps,
861
+ device=config.init_device,
862
+ )
863
+
864
+ self.transformer = BlockCollection(config)
865
+
866
+ @torch.jit.ignore
867
+ def set_grad_checkpointing(self, enable=True):
868
+ self.transformer.grad_checkpointing = enable
869
+
870
+ def reset_parameters(self):
871
+ nn.init.normal_(self.class_embedding, std=self.scale)
872
+ nn.init.normal_(self.positional_embedding, std=self.scale)
873
+ nn.init.normal_(self.patch_embedding.weight, std=0.02)
874
+ self.pre_ln.reset_parameters()
875
+ self.transformer.reset_parameters()
876
+
877
+ def add_pos_emb(self, x: torch.Tensor, patch_num: int) -> torch.Tensor:
878
+ cls_emb = self.positional_embedding[0:1]
879
+ pos_emb = self.positional_embedding[1:]
880
+
881
+ pos_emb = pos_emb.reshape(
882
+ (int(math.sqrt(pos_emb.shape[0])), int(math.sqrt(pos_emb.shape[0])), pos_emb.shape[1])
883
+ )
884
+
885
+ (patch_num_0, patch_num_1) = patch_num
886
+
887
+ if pos_emb.shape[0] != patch_num_0 or pos_emb.shape[1] != patch_num_1:
888
+ # Dervied from https://github.com/facebookresearch/mae/blob/main/util/pos_embed.py
889
+ # antialias: default True in jax.image.resize
890
+ pos_emb = pos_emb.unsqueeze(0).permute(0, 3, 1, 2)
891
+ pos_emb = F.interpolate(
892
+ pos_emb, size=(patch_num_0, patch_num_1), mode="bicubic", align_corners=False, antialias=True,
893
+ )
894
+ pos_emb = pos_emb.permute(0, 2, 3, 1).squeeze(0)
895
+
896
+ pos_emb = pos_emb.reshape(-1, pos_emb.shape[-1])
897
+ x = x + torch.cat([cls_emb[None, :, :], pos_emb[None, :, :]], dim=1).to(x.dtype)
898
+ return x
899
+
900
+ def forward(self, x: torch.Tensor, patch_num: int = None) -> List[torch.Tensor]:
901
+ """
902
+ : param x: (batch_size, num_patch, n_pixels)
903
+ """
904
+ if patch_num is None:
905
+ patch_num = self.config.vision_backbone.image_num_patch
906
+ B, N, D = x.shape
907
+
908
+ x = self.patch_embedding(x)
909
+
910
+ # class embeddings and positional embeddings
911
+ x = torch.cat([_expand_token(self.class_embedding, x.shape[0]).to(x.dtype), x], dim=1)
912
+ x = self.add_pos_emb(x, patch_num)
913
+
914
+ x = self.pre_ln(x)
915
+
916
+ hidden_states = self.transformer(x)
917
+ return hidden_states
918
+
919
+
920
+ class MultiHeadDotProductAttention(nn.Module):
921
+ def __init__(self, config: FullMolmoConfig, use_bias: bool = True, is_vit_layer: Optional[bool] = True):
922
+ super().__init__()
923
+ self.config = config
924
+ self.use_bias = use_bias
925
+
926
+ v_cfg = config.vision_backbone
927
+ self.embed_dim = v_cfg.image_emb_dim
928
+ self.num_heads = v_cfg.image_num_heads
929
+ self.head_dim = v_cfg.image_head_dim
930
+ self.num_key_value_heads = v_cfg.image_num_key_value_heads
931
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
932
+ self.initializer_range = v_cfg.initializer_range
933
+ self.is_vit_layer = is_vit_layer
934
+
935
+ nlayers = 1 if (is_vit_layer or config.vit_layers is None) else len(config.vit_layers)
936
+
937
+ self.wq = nn.Linear(
938
+ nlayers * self.embed_dim,
939
+ self.num_heads * self.head_dim,
940
+ bias=use_bias,
941
+ device=config.init_device,
942
+ )
943
+ self.wk = nn.Linear(
944
+ nlayers * self.embed_dim,
945
+ self.num_key_value_heads * self.head_dim,
946
+ bias=use_bias,
947
+ device=config.init_device,
948
+ )
949
+ self.wv = nn.Linear(
950
+ nlayers * self.embed_dim,
951
+ self.num_key_value_heads * self.head_dim,
952
+ bias=use_bias,
953
+ device=config.init_device,
954
+ )
955
+ self.wo = nn.Linear(
956
+ self.num_heads * self.head_dim,
957
+ self.embed_dim,
958
+ bias=use_bias,
959
+ device=config.init_device,
960
+ )
961
+ self.attention_dropout: Optional[Dropout] = None
962
+ if v_cfg.attention_dropout > 0:
963
+ self.attention_dropout = Dropout(v_cfg.attention_dropout, broadcast_dims=(0, 1))
964
+ self.residual_dropout = Dropout(v_cfg.residual_dropout)
965
+
966
+ def reset_parameters(self):
967
+ nn.init.normal_(self.wq.weight, std=self.initializer_range)
968
+ nn.init.normal_(self.wk.weight, std=self.initializer_range)
969
+ nn.init.normal_(self.wv.weight, std=self.initializer_range)
970
+ nn.init.normal_(self.wo.weight, std=self.initializer_range)
971
+ if self.use_bias:
972
+ nn.init.constant_(self.wq.bias, 0)
973
+ nn.init.constant_(self.wk.bias, 0)
974
+ nn.init.constant_(self.wv.bias, 0)
975
+ nn.init.constant_(self.wo.bias, 0)
976
+
977
+ def _split_heads(self, hidden_states, num_heads) -> torch.Tensor:
978
+ return hidden_states.reshape(hidden_states.shape[:2] + (num_heads, self.head_dim))
979
+
980
+ def _merge_heads(self, hidden_states) -> torch.Tensor:
981
+ return hidden_states.reshape(hidden_states.shape[:2] + (self.embed_dim,))
982
+
983
+ def forward(self, inputs_q: torch.Tensor, inputs_kv: Optional[torch.Tensor] = None) -> torch.Tensor:
984
+
985
+ if inputs_kv is not None:
986
+ inputs_k = inputs_kv
987
+ inputs_v = inputs_kv
988
+ else:
989
+ inputs_k = inputs_q
990
+ inputs_v = inputs_q
991
+
992
+ xq, xk, xv = self.wq(inputs_q), self.wk(inputs_k), self.wv(inputs_v)
993
+
994
+ xq = self._split_heads(xq, self.num_heads)
995
+ xk = self._split_heads(xk, self.num_key_value_heads)
996
+ xv = self._split_heads(xv, self.num_key_value_heads)
997
+
998
+ if self.num_heads != self.num_key_value_heads:
999
+ xk = xk.repeat_interleave(self.num_key_value_groups, dim=2, output_size=self.num_heads)
1000
+ xv = xv.repeat_interleave(self.num_key_value_groups, dim=2, output_size=self.num_heads)
1001
+
1002
+ og_dtype = xq.dtype
1003
+
1004
+ if self.config.float32_attention:
1005
+ xq = xq.to(torch.float)
1006
+ xk = xk.to(torch.float)
1007
+
1008
+ if self.config.attention_type == "direct":
1009
+ attn_weights = torch.einsum("...qhd,...khd->...hqk", xq / math.sqrt(xq.size(-1)), xk)
1010
+ attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(xq.dtype)
1011
+ if self.attention_dropout is not None:
1012
+ attn_weights = self.attention_dropout(attn_weights)
1013
+ attn_output = torch.einsum("...hqk,...khd->...qhd", attn_weights.to(xv.dtype), xv)
1014
+
1015
+ elif self.config.attention_type == "sdpa":
1016
+ attn_output = F.scaled_dot_product_attention(
1017
+ xq.transpose(1, 2).contiguous(),
1018
+ xk.transpose(1, 2).contiguous(),
1019
+ xv.transpose(1, 2).contiguous(),
1020
+ is_causal=False,
1021
+ dropout_p=self.config.vision_backbone.attention_dropout
1022
+ ).transpose(1, 2)
1023
+ else:
1024
+ raise NotImplementedError(self.config.attention_type)
1025
+ attn_output = attn_output.to(og_dtype)
1026
+ attn_output = self._merge_heads(attn_output)
1027
+ attn_output = self.wo(attn_output)
1028
+ attn_output = self.residual_dropout(attn_output)
1029
+
1030
+ return attn_output
1031
+
1032
+
1033
+ class MultiHeadAttentionPool(nn.Module):
1034
+ def __init__(
1035
+ self,
1036
+ config: FullMolmoConfig,
1037
+ factor: int = 1,
1038
+ use_bias: bool = True,
1039
+ dropout: bool = True,
1040
+ output_layer: bool = True,
1041
+ mean_residual: bool = False,
1042
+ query: str = "mean",
1043
+ is_vit_layer: Optional[bool] = True
1044
+ ):
1045
+ super().__init__()
1046
+ self.config = config
1047
+ self.factor = factor
1048
+ self.use_bias = use_bias
1049
+ self.dropout = dropout
1050
+ self.output_layer = output_layer
1051
+ self.mean_residual = mean_residual
1052
+ self.query = query
1053
+
1054
+ v_cfg = config.vision_backbone
1055
+ input_dim = v_cfg.image_emb_dim
1056
+ self.embed_dim = v_cfg.image_emb_dim * factor
1057
+ self.num_heads = v_cfg.image_num_heads
1058
+ self.head_dim = v_cfg.image_head_dim * factor
1059
+ self.num_key_value_heads = v_cfg.image_num_key_value_heads
1060
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
1061
+ self.initializer_range = v_cfg.initializer_range
1062
+
1063
+ nlayers = 1 if (is_vit_layer or config.vit_layers is None) else len(config.vit_layers)
1064
+
1065
+ if query != "vector":
1066
+ self.wq = nn.Linear(
1067
+ nlayers * input_dim,
1068
+ self.num_heads * self.head_dim,
1069
+ bias=use_bias,
1070
+ device=config.init_device,
1071
+ )
1072
+ self.wk = nn.Linear(
1073
+ nlayers * input_dim,
1074
+ self.num_key_value_heads * self.head_dim,
1075
+ bias=use_bias,
1076
+ device=config.init_device,
1077
+ )
1078
+ self.wv = nn.Linear(
1079
+ nlayers * input_dim,
1080
+ self.num_key_value_heads * self.head_dim,
1081
+ bias=use_bias,
1082
+ device=config.init_device,
1083
+ )
1084
+
1085
+ if query == "vector":
1086
+ self.attention_query = nn.Parameter(
1087
+ torch.zeros(
1088
+ 1, self.num_key_value_heads * self.head_dim, device=config.init_device,
1089
+ ),
1090
+ )
1091
+
1092
+ if output_layer:
1093
+ self.wo = nn.Linear(
1094
+ self.num_heads * self.head_dim,
1095
+ self.embed_dim,
1096
+ bias=use_bias,
1097
+ device=config.init_device,
1098
+ )
1099
+ self.attention_dropout = Dropout(v_cfg.attention_dropout, broadcast_dims=(0, 1))
1100
+ if dropout:
1101
+ self.residual_dropout = Dropout(v_cfg.residual_dropout)
1102
+
1103
+ def reset_parameters(self):
1104
+ if self.query != "vector":
1105
+ nn.init.normal_(self.wq.weight, std=self.initializer_range)
1106
+ nn.init.normal_(self.wk.weight, std=self.initializer_range)
1107
+ nn.init.normal_(self.wv.weight, std=self.initializer_range)
1108
+ if self.output_layer:
1109
+ nn.init.normal_(self.wo.weight, std=self.initializer_range)
1110
+ if self.use_bias:
1111
+ if self.query != "vector":
1112
+ nn.init.constant_(self.wq.bias, 0)
1113
+ nn.init.constant_(self.wk.bias, 0)
1114
+ nn.init.constant_(self.wv.bias, 0)
1115
+ if self.output_layer:
1116
+ nn.init.constant_(self.wo.bias, 0)
1117
+ if self.query == "vector":
1118
+ nn.init.normal_(self.attention_query, std=self.initializer_range)
1119
+
1120
+ def _split_heads(self, hidden_states, num_heads):
1121
+ return hidden_states.reshape(hidden_states.shape[:2] + (num_heads, self.head_dim))
1122
+
1123
+ def _merge_heads(self, hidden_states):
1124
+ return hidden_states.reshape(hidden_states.shape[:2] + (self.embed_dim,))
1125
+
1126
+ def forward(self, inputs_kv: torch.Tensor) -> torch.Tensor:
1127
+
1128
+ xk, xv = self.wk(inputs_kv), self.wv(inputs_kv)
1129
+
1130
+ if self.query == "mean":
1131
+ inputs_q = inputs_kv.mean(dim=1, keepdim=True)
1132
+ xq = self.wq(inputs_q)
1133
+ elif self.query == "first":
1134
+ inputs_q = inputs_kv[:, :1]
1135
+ xq = self.wq(inputs_q)
1136
+ elif self.query == "vector":
1137
+ xq = self.attention_query.expand(inputs_kv.size(0), -1, -1)
1138
+ elif self.query == "constant":
1139
+ inputs_q = torch.ones_like(inputs_kv[:, :1]) / math.sqrt(inputs_kv.shape[-1])
1140
+ xq = self.wq(inputs_q)
1141
+ else:
1142
+ raise ValueError(f"Unknown query type: {self.query}")
1143
+
1144
+ xq = self._split_heads(xq, self.num_heads)
1145
+ xk = self._split_heads(xk, self.num_key_value_heads)
1146
+ xv = self._split_heads(xv, self.num_key_value_heads)
1147
+
1148
+ if self.num_heads != self.num_key_value_heads:
1149
+ xk = xk.repeat_interleave(self.num_key_value_groups, dim=2, output_size=self.num_heads)
1150
+ xv = xv.repeat_interleave(self.num_key_value_groups, dim=2, output_size=self.num_heads)
1151
+
1152
+ xq = xq.to(torch.float)
1153
+ xk = xk.to(torch.float)
1154
+
1155
+ xq = xq / math.sqrt(xq.size(-1))
1156
+ attn_weights = torch.einsum("...qhd,...khd->...hqk", xq, xk)
1157
+
1158
+ attn_weights = F.softmax(attn_weights, dim=-1).to(xq.dtype)
1159
+
1160
+ attn_weights = self.attention_dropout(attn_weights).to(xv.dtype)
1161
+
1162
+ attn_output = torch.einsum("...hqk,...khd->...qhd", attn_weights, xv)
1163
+ attn_output = self._merge_heads(attn_output)
1164
+ if self.output_layer:
1165
+ attn_output = self.wo(attn_output)
1166
+ if self.dropout:
1167
+ attn_output = self.residual_dropout(attn_output)
1168
+ if self.mean_residual:
1169
+ attn_output += inputs_kv.mean(dim=1, keepdim=True)
1170
+
1171
+ return attn_output
1172
+
1173
+
1174
+ class MLP(nn.Module):
1175
+ def __init__(self, config: FullMolmoConfig, input_dim: int, dropout: float = 0.0):
1176
+ super().__init__()
1177
+ self.config = config
1178
+ self.hidden_size = (
1179
+ config.mlp_hidden_size if config.mlp_hidden_size is not None else config.mlp_ratio * config.d_model
1180
+ )
1181
+ self.initializer_range = config.initializer_range
1182
+
1183
+ self.w1 = nn.Linear(
1184
+ input_dim,
1185
+ self.hidden_size // 2,
1186
+ bias=False,
1187
+ device=config.init_device,
1188
+ )
1189
+ self.w2 = nn.Linear(
1190
+ self.hidden_size // 2,
1191
+ config.d_model,
1192
+ bias=False,
1193
+ device=config.init_device,
1194
+ )
1195
+ self.w3 = nn.Linear(
1196
+ input_dim,
1197
+ self.hidden_size // 2,
1198
+ bias=False,
1199
+ device=config.init_device,
1200
+ )
1201
+ # Activation function.
1202
+ self.act = Activation.build(config)
1203
+ self.dropout = Dropout(dropout)
1204
+
1205
+ def reset_parameters(self):
1206
+ nn.init.normal_(self.w1.weight, std=self.initializer_range)
1207
+ nn.init.normal_(self.w2.weight, std=self.initializer_range)
1208
+ nn.init.normal_(self.w3.weight, std=self.initializer_range)
1209
+
1210
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
1211
+ x = self.w2(self.act(self.w1(x), self.w3(x)))
1212
+ x = self.dropout(x)
1213
+ return x
1214
+
1215
+
1216
+ class Residual(nn.Module):
1217
+ def __init__(self, submodule: nn.Module):
1218
+ super().__init__()
1219
+ self.submodule = submodule
1220
+
1221
+ def reset_parameters(self):
1222
+ self.submodule.reset_parameters()
1223
+
1224
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
1225
+ return x + self.submodule(x)
1226
+
1227
+
1228
+ class OLMoVisionBackbone(nn.Module):
1229
+ def __init__(self, config: FullMolmoConfig):
1230
+ super().__init__()
1231
+ self.config = config
1232
+ self.image_vit = VisionTransformer(config)
1233
+
1234
+ input_dim: int = None
1235
+ self.image_pooling_2d: nn.Module = None
1236
+ if config.image_pooling_2d in {ImagePooling2DType.attention, ImagePooling2DType.attention_meanq}:
1237
+ self.image_pooling_2d = MultiHeadDotProductAttention(config, is_vit_layer=False)
1238
+ input_dim = config.vision_backbone.image_emb_dim
1239
+ elif config.image_pooling_2d == ImagePooling2DType.attention_2wide:
1240
+ cfg = deepcopy(config)
1241
+ cfg.vision_backbone.image_emb_dim *= 2
1242
+ cfg.vision_backbone.image_head_dim *= 2
1243
+ self.image_pooling_2d = MultiHeadDotProductAttention(cfg, is_vit_layer=False)
1244
+ input_dim = cfg.vision_backbone.image_emb_dim
1245
+ elif config.image_pooling_2d == ImagePooling2DType.attention_v2:
1246
+ assert config.vit_layers is not None
1247
+ use_bias = True
1248
+ dropout = True
1249
+ output_layer = True
1250
+ query = "mean"
1251
+ mean_residual = False
1252
+ factor = len(config.vit_layers)
1253
+ self.image_pooling_2d = MultiHeadAttentionPool(
1254
+ config,
1255
+ factor=factor,
1256
+ use_bias=use_bias,
1257
+ dropout=dropout,
1258
+ output_layer=output_layer,
1259
+ mean_residual=mean_residual,
1260
+ query=query,
1261
+ is_vit_layer=False,
1262
+ )
1263
+ input_dim = config.vision_backbone.image_emb_dim * factor
1264
+ elif config.image_pooling_2d in [ImagePooling2DType.none, ImagePooling2DType.stack]:
1265
+ self.image_pooling_2d = None
1266
+ nlayers = 1 if config.vit_layers is None else len(config.vit_layers)
1267
+ input_dim = nlayers * config.vision_backbone.image_emb_dim
1268
+ else:
1269
+ raise NotImplementedError(f"Unknown image pooling 2D method: {config.image_pooling_2d}")
1270
+
1271
+ self.input_dim = input_dim
1272
+
1273
+ # `MLP` assume the activation takes two inputs, so it must be a 'llama' version
1274
+ if config.activation_type == ActivationType.swiglu:
1275
+ mlp_config = replace(config, activation_type=ActivationType.llama_swiglu)
1276
+ elif config.activation_type == ActivationType.gelu:
1277
+ mlp_config = replace(config, activation_type=ActivationType.llama_geglu)
1278
+ else:
1279
+ mlp_config = config
1280
+ if config.image_projector == ImageProjectType.mlpx2:
1281
+ self.image_projector = nn.ModuleList(
1282
+ [MLP(mlp_config, input_dim), Residual(MLP(config, input_dim))]
1283
+ )
1284
+ elif config.image_projector == ImageProjectType.mlp:
1285
+ self.image_projector = MLP(mlp_config, input_dim)
1286
+ elif config.image_projector == ImageProjectType.linear:
1287
+ self.image_projector = nn.Linear(
1288
+ input_dim,
1289
+ config.d_model,
1290
+ bias=False,
1291
+ device=config.init_device,
1292
+ )
1293
+ else:
1294
+ raise NotImplementedError(f"Unknown image projector: {config.image_projector}")
1295
+
1296
+ self.image_feature_dropout = Dropout(config.image_feature_dropout)
1297
+
1298
+ def reset_parameters(self):
1299
+ if self.image_pooling_2d is not None:
1300
+ self.image_pooling_2d.reset_parameters()
1301
+ if self.config.image_projector == "2mlp":
1302
+ for module in self.image_projector:
1303
+ module.reset_parameters()
1304
+ elif self.config.image_projector == "linear":
1305
+ nn.init.xavier_uniform_(self.image_projector.weight)
1306
+ else:
1307
+ self.image_projector.reset_parameters()
1308
+
1309
+ def forward(self, images: torch.Tensor, image_masks: torch.Tensor) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
1310
+ raise NotImplementedError
1311
+
1312
+
1313
+ class OLMoPretrainedVisionBackbone(OLMoVisionBackbone):
1314
+ def __init__(self, config: FullMolmoConfig):
1315
+ super().__init__(config)
1316
+ v_cfg = self.config.vision_backbone
1317
+ self.grad_checkpointing = False
1318
+
1319
+ self.num_prefix_tokens = self.image_vit.num_prefix_tokens
1320
+ assert self.num_prefix_tokens in {0, 1}, "Only 0 or 1 prefix tokens are supported"
1321
+
1322
+ self.pad_embed = None
1323
+ if config.image_padding_embed:
1324
+ image_dim = v_cfg.image_emb_dim*len(self.config.vit_layers)
1325
+ if config.image_padding_embed in ["pad_embed", "regress"]:
1326
+ self.pad_embed = nn.Parameter(
1327
+ torch.zeros((image_dim,), device=config.init_device))
1328
+ elif config.image_padding_embed == "pad_and_partial_pad":
1329
+ self.pad_embed = nn.Parameter(
1330
+ torch.zeros((2, image_dim), device=config.init_device))
1331
+ else:
1332
+ raise ValueError(config.image_padding_embed)
1333
+
1334
+ def reset_parameters(self):
1335
+ super().reset_parameters()
1336
+ self.image_vit.reset_parameters()
1337
+
1338
+ def encode_image(self, images: torch.Tensor) -> torch.Tensor:
1339
+ """
1340
+ : param images: (batch_size, num_crops, num_patch, n_pixels)
1341
+ """
1342
+ cfg = self.config
1343
+ v_cfg = self.config.vision_backbone
1344
+ B, T, N, D = images.shape
1345
+
1346
+ mask = ~torch.all(images.view(B * T, N, D) == -1, dim=(1, 2), keepdim=True)
1347
+
1348
+ # Output all hidden states
1349
+ # n_layers x (batch_num_crops, (1+)n_tokens, image_emb_dim)
1350
+ images = images.view(B * T, N, D)
1351
+ image_features = self.image_vit(images)
1352
+
1353
+ if cfg.vit_layers is not None:
1354
+ features = []
1355
+ for layer in cfg.vit_layers:
1356
+ features.append(image_features[layer])
1357
+ image_features = torch.cat(features, dim=-1)
1358
+ else:
1359
+ image_features = image_features[-1]
1360
+
1361
+ cls_embed: torch.Tensor = None
1362
+ if self.num_prefix_tokens > 0:
1363
+ cls_embed = image_features[:, 0]
1364
+ image_features = image_features[:, 1:]
1365
+
1366
+ image_features = image_features * mask
1367
+ image_features = image_features.view(B, T, N, -1)
1368
+
1369
+ cls_embed = cls_embed.view(B, T, -1) if cls_embed is not None else None
1370
+
1371
+ return image_features, cls_embed
1372
+
1373
+ def forward(self, images: torch.Tensor, image_masks: torch.Tensor) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
1374
+ cfg = self.config
1375
+
1376
+ # image_features: (batch_size, num_crops(=num_image), num_patch, nximage_emb_dim)
1377
+ batch_size, num_image = images.shape[:2]
1378
+ image_features, cls_embed = self.encode_image(images)
1379
+
1380
+ if cfg.image_padding_embed:
1381
+ assert image_masks is not None
1382
+ if cfg.image_padding_embed == "pad_embed":
1383
+ all_pad = (image_masks == 0).to(dtype=torch.float32)
1384
+ pad_embed = self.pad_embed[None, None, None, :]
1385
+ image_features = image_features + pad_embed * torch.unsqueeze(all_pad, -1)
1386
+ elif cfg.image_padding_embed == "regress":
1387
+ pad_embed = self.pad_embed[None, None, None, :]
1388
+ image_features = image_features + pad_embed * torch.unsqueeze(torch.maximum(image_masks, torch.zeros_like(image_masks)), -1)
1389
+ elif cfg.image_padding_embed == "pad_and_partial_pad":
1390
+ pad_embed = self.pad_embed[:, None, None, None, :]
1391
+ all_pad = image_masks == 0
1392
+ partial_pad = torch.logical_and(image_masks < 1, torch.logical_not(all_pad)).to(dtype=torch.float32)
1393
+ all_pad = all_pad.to(dtype=torch.float32)
1394
+ image_features = image_features + pad_embed[0] * torch.unsqueeze(all_pad, -1)
1395
+ image_features = image_features + pad_embed[1] * torch.unsqueeze(partial_pad, -1)
1396
+ else:
1397
+ raise ValueError(cfg.image_padding_embed)
1398
+
1399
+ image_features = self.image_feature_dropout(image_features)
1400
+ if cls_embed is not None:
1401
+ cls_embed = self.image_feature_dropout(cls_embed)
1402
+
1403
+ image_features = image_features.reshape(
1404
+ (batch_size, num_image) + cfg.image_num_patch + (-1,),
1405
+ )
1406
+
1407
+ if cfg.image_num_patch[0] % cfg.image_pooling_h == 1:
1408
+ # Pad so we can still pool 2x2 patches
1409
+ image_features = F.pad(
1410
+ image_features,
1411
+ (0, 0, 0, 1, 0, 1, 0, 0, 0, 0),
1412
+ )
1413
+
1414
+ # image pooling
1415
+ image_features = einops.rearrange(
1416
+ image_features,
1417
+ 'b n (h dh) (w dw) c -> (b n h w) (dh dw) c',
1418
+ dh=cfg.image_pooling_h,
1419
+ dw=cfg.image_pooling_w,
1420
+ )
1421
+
1422
+ if cfg.image_pooling_2d == ImagePooling2DType.attention_meanq:
1423
+ query = image_features.mean(-2, keepdim=True)
1424
+ image_features = self.image_pooling_2d(query, image_features)
1425
+ elif cfg.image_pooling_2d not in {ImagePooling2DType.none, ImagePooling2DType.stack}:
1426
+ if self.grad_checkpointing:
1427
+ from torch.utils.checkpoint import checkpoint
1428
+ image_features = checkpoint(self.image_pooling_2d, image_features[:, :1, :], image_features, use_reentrant=False)
1429
+ else:
1430
+ image_features = self.image_pooling_2d(image_features[:, :1, :], image_features)
1431
+
1432
+ h, w = cfg.llm_patches_per_crop()
1433
+ image_features = image_features.reshape(batch_size, num_image, h * w, -1)
1434
+
1435
+ # MLP layer to map the feature.
1436
+ if self.grad_checkpointing:
1437
+ from torch.utils.checkpoint import checkpoint
1438
+ image_features = checkpoint(self.image_projector, image_features, use_reentrant=False)
1439
+ else:
1440
+ image_features = self.image_projector(image_features)
1441
+
1442
+ # image_features: (batch_size, num_image, num_patch, d_model)
1443
+ # cls_embed: (batch_size, num_image, d_model)
1444
+ return image_features, cls_embed
1445
+
1446
+
1447
+ class ModuleType(str, Enum):
1448
+ in_module = "in"
1449
+ out_module = "out"
1450
+ emb = "emb"
1451
+ final_out = "final_out"
1452
+
1453
+
1454
+ def init_weights(
1455
+ config: FullMolmoConfig,
1456
+ module: Union[nn.Linear, nn.Embedding],
1457
+ d: Optional[int] = None,
1458
+ layer_id: Optional[int] = None,
1459
+ std_factor: float = 1.0,
1460
+ type_of_module: Optional[ModuleType] = None,
1461
+ ) -> None:
1462
+ d = d if d is not None else config.d_model
1463
+ std = config.init_std * std_factor
1464
+ if config.init_cutoff_factor is not None:
1465
+ cutoff_value = config.init_cutoff_factor * std
1466
+ nn.init.trunc_normal_(module.weight, mean=0.0, std=std, a=-cutoff_value, b=cutoff_value)
1467
+ else:
1468
+ nn.init.normal_(module.weight, mean=0.0, std=std)
1469
+
1470
+
1471
+ class LlamaSwiGLU(nn.Module):
1472
+ def forward(self, x1: torch.Tensor, x2: torch.Tensor) -> torch.Tensor:
1473
+ return F.silu(x1) * x2
1474
+
1475
+ @property
1476
+ def output_multiplier(self) -> float:
1477
+ return 0.5
1478
+
1479
+
1480
+ class SwiGLU(nn.Module):
1481
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
1482
+ x, gate = x.chunk(2, dim=-1)
1483
+ return F.silu(gate) * x
1484
+
1485
+ @property
1486
+ def output_multiplier(self) -> float:
1487
+ return 0.5
1488
+
1489
+
1490
+ class Activation(nn.Module):
1491
+ def __init__(self, config: FullMolmoConfig):
1492
+ super().__init__()
1493
+ self.config = config
1494
+
1495
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
1496
+ raise NotImplementedError
1497
+
1498
+ @property
1499
+ def output_multiplier(self) -> float:
1500
+ raise NotImplementedError
1501
+
1502
+ @classmethod
1503
+ def build(cls, config: FullMolmoConfig) -> 'Activation':
1504
+ if config.activation_type == "quick_gelu":
1505
+ return QuickGELU(config)
1506
+ elif config.activation_type == "gelu":
1507
+ return cast(Activation, GELU(approximate="none"))
1508
+ elif config.activation_type == "gelu_tanh":
1509
+ return cast(Activation, GELU(approximate="tanh"))
1510
+ elif config.activation_type == "relu":
1511
+ return cast(Activation, ReLU(inplace=False))
1512
+ elif config.activation_type == "silu":
1513
+ return cast(Activation, SiLU(inplace=False))
1514
+ # elif config.activation_type == "llama_geglu":
1515
+ # return LlamaGEGLU(config)
1516
+ # elif config.activation_type == "llama_geglu_tanh":
1517
+ # return LlamaGEGLUTanh(config)
1518
+ elif config.activation_type == "llama_swiglu":
1519
+ return LlamaSwiGLU()
1520
+ elif config.activation_type == "swiglu":
1521
+ return SwiGLU()
1522
+ else:
1523
+ raise NotImplementedError(f"Unknown activation: '{config.activation_type}'")
1524
+
1525
+
1526
+ class QuickGELU(Activation):
1527
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
1528
+ return x * torch.sigmoid(1.702 * x)
1529
+
1530
+ @property
1531
+ def output_multiplier(self) -> float:
1532
+ return 1.0
1533
+
1534
+
1535
+ class GELU(nn.GELU):
1536
+ @property
1537
+ def output_multiplier(self) -> float:
1538
+ return 1.0
1539
+
1540
+
1541
+ class ReLU(nn.ReLU):
1542
+ @property
1543
+ def output_multiplier(self) -> float:
1544
+ return 1.0
1545
+
1546
+
1547
+ class SiLU(nn.SiLU):
1548
+ @property
1549
+ def output_multiplier(self) -> float:
1550
+ return 1.0
1551
+
1552
+
1553
+ def causal_attention_bias(seq_len: int, device: torch.device) -> torch.FloatTensor:
1554
+ att_bias = torch.triu(
1555
+ torch.ones(seq_len, seq_len, device=device, dtype=torch.float),
1556
+ diagonal=1,
1557
+ )
1558
+ att_bias.masked_fill_(att_bias == 1, torch.finfo(att_bias.dtype).min)
1559
+ return att_bias.view(1, 1, seq_len, seq_len) # type: ignore
1560
+
1561
+
1562
+ def get_causal_attention_bias(cache: BufferCache, seq_len: int, device: torch.device) -> torch.Tensor:
1563
+ if (causal_bias := cache.get("causal_attention_bias")) is not None and causal_bias.shape[-1] >= seq_len:
1564
+ if causal_bias.device != device:
1565
+ causal_bias = causal_bias.to(device)
1566
+ cache["causal_attention_bias"] = causal_bias
1567
+ return causal_bias
1568
+ with torch.autocast(device.type, enabled=False):
1569
+ causal_bias = causal_attention_bias(seq_len, device)
1570
+ cache["causal_attention_bias"] = causal_bias
1571
+ return causal_bias
1572
+
1573
+
1574
+ class LayerNormBase(nn.Module):
1575
+ def __init__(
1576
+ self,
1577
+ config: MolmoConfig,
1578
+ *,
1579
+ size: Optional[int] = None,
1580
+ elementwise_affine: Optional[bool] = True,
1581
+ eps: float = 1e-05,
1582
+ weight_initializer: Optional[Callable] = torch.ones,
1583
+ bias_initializer: Optional[Callable] = torch.zeros,
1584
+ ):
1585
+ super().__init__()
1586
+ self.config = config
1587
+ self.eps = self.config.layer_norm_eps or eps
1588
+ self.normalized_shape = (size or config.d_model,)
1589
+ if elementwise_affine or (elementwise_affine is None and self.config.layer_norm_with_affine):
1590
+ self.weight = nn.Parameter(weight_initializer(self.normalized_shape, device=config.init_device))
1591
+ use_bias = self.config.bias_for_layer_norm
1592
+ if use_bias is None:
1593
+ use_bias = self.config.include_bias
1594
+ if use_bias:
1595
+ self.bias = nn.Parameter(bias_initializer(self.normalized_shape, device=config.init_device))
1596
+ else:
1597
+ self.register_parameter("bias", None)
1598
+ else:
1599
+ self.register_parameter("bias", None)
1600
+ self.register_parameter("weight", None)
1601
+
1602
+ @classmethod
1603
+ def build(cls, config: FullMolmoConfig, size: Optional[int] = None, **kwargs):
1604
+ if config.layer_norm_type == "default":
1605
+ return LayerNorm(config, size=size, low_precision=False, **kwargs)
1606
+ elif config.layer_norm_type == "low_precision":
1607
+ return LayerNorm(config, size=size, low_precision=True, **kwargs)
1608
+ elif config.layer_norm_type == "rms":
1609
+ return RMSLayerNorm(config, size=size, **kwargs)
1610
+ else:
1611
+ raise NotImplementedError(f"Unknown LayerNorm type: '{config.layer_norm_type}'")
1612
+
1613
+
1614
+ class RMSLayerNorm(LayerNormBase):
1615
+ """
1616
+ RMS layer norm, a simplified :class:`LayerNorm` implementation
1617
+ """
1618
+
1619
+ def __init__(
1620
+ self,
1621
+ config: FullMolmoConfig,
1622
+ size: Optional[int] = None,
1623
+ elementwise_affine: Optional[bool] = None,
1624
+ eps: float = 1e-5,
1625
+ ):
1626
+ super().__init__(config, size=size, elementwise_affine=elementwise_affine, eps=eps)
1627
+
1628
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
1629
+ with torch.autocast(enabled=False, device_type=x.device.type):
1630
+ og_dtype = x.dtype
1631
+ x = x.to(torch.float32)
1632
+ variance = x.pow(2).mean(-1, keepdim=True)
1633
+ x = x * torch.rsqrt(variance + self.eps)
1634
+ x = x.to(og_dtype)
1635
+
1636
+ if self.weight is not None:
1637
+ if self.bias is not None:
1638
+ return self.weight * x + self.bias
1639
+ else:
1640
+ return self.weight * x
1641
+ else:
1642
+ return x
1643
+
1644
+
1645
+ class LayerNorm(LayerNormBase):
1646
+ """
1647
+ The default :class:`LayerNorm` implementation which can optionally run in low precision.
1648
+ """
1649
+
1650
+ def __init__(
1651
+ self,
1652
+ config: FullMolmoConfig,
1653
+ size: Optional[int] = None,
1654
+ low_precision: bool = False,
1655
+ elementwise_affine: Optional[bool] = None,
1656
+ eps: float = 1e-05,
1657
+ ):
1658
+ super().__init__(config, size=size, elementwise_affine=elementwise_affine, eps=eps)
1659
+ self.low_precision = low_precision
1660
+
1661
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
1662
+ if self.low_precision:
1663
+ module_device = x.device
1664
+ downcast_x = self._cast_if_autocast_enabled(x)
1665
+ downcast_weight = (
1666
+ self._cast_if_autocast_enabled(self.weight) if self.weight is not None else self.weight
1667
+ )
1668
+ downcast_bias = self._cast_if_autocast_enabled(self.bias) if self.bias is not None else self.bias
1669
+ with torch.autocast(enabled=False, device_type=module_device.type):
1670
+ return F.layer_norm(
1671
+ downcast_x, self.normalized_shape, weight=downcast_weight, bias=downcast_bias, eps=self.eps
1672
+ )
1673
+ else:
1674
+ return F.layer_norm(x, self.normalized_shape, weight=self.weight, bias=self.bias, eps=self.eps)
1675
+
1676
+
1677
+ class Molmo(nn.Module):
1678
+ def __init__(self, config: FullMolmoConfig, init_params: bool = True):
1679
+ super().__init__()
1680
+ self.config = config
1681
+ self.__cache = BufferCache()
1682
+
1683
+ # Validate config.
1684
+ if self.config.embedding_size is not None and self.config.embedding_size != self.config.vocab_size:
1685
+ if self.config.embedding_size < self.config.vocab_size:
1686
+ raise MolmoConfigurationError("embedding size should be at least as big as vocab size")
1687
+ elif self.config.embedding_size % 128 != 0:
1688
+ import warnings
1689
+
1690
+ warnings.warn(
1691
+ "Embedding size is not a multiple of 128! This could hurt throughput performance.", UserWarning
1692
+ )
1693
+ torch.backends.cuda.enable_flash_sdp(True)
1694
+ torch.backends.cuda.enable_mem_efficient_sdp(False) # this is super slow so make sure torch won't use it
1695
+
1696
+ wte = None
1697
+ if self.config.additional_vocab_size is not None:
1698
+ wte = Embedding(
1699
+ config.embedding_size or config.vocab_size,
1700
+ config.additional_vocab_size,
1701
+ config.d_model,
1702
+ device=config.init_device,
1703
+ initializer_range=config.initializer_range,
1704
+ new_embed_initializer_range=config.new_embedding_init_range
1705
+ )
1706
+ else:
1707
+ wte=nn.Embedding(
1708
+ config.embedding_size or config.vocab_size, config.d_model, device=config.init_device
1709
+ )
1710
+
1711
+ self.transformer = nn.ModuleDict(
1712
+ dict(
1713
+ wte=wte,
1714
+ emb_drop=Dropout(config.embedding_dropout),
1715
+ ln_f=LayerNorm.build(config),
1716
+ )
1717
+ )
1718
+
1719
+ blocks = [MolmoBlock.build(i, config, self.__cache) for i in range(config.n_layers)]
1720
+ if self.config.block_group_size > 1:
1721
+ raise NotImplementedError()
1722
+ else:
1723
+ self.transformer.update({"blocks": nn.ModuleList(blocks)})
1724
+
1725
+ if not self.config.rope:
1726
+ self.transformer.update(
1727
+ {"wpe": nn.Embedding(config.max_sequence_length, config.d_model, device=config.init_device)}
1728
+ )
1729
+ if not config.weight_tying:
1730
+ self.transformer.update(
1731
+ {
1732
+ "ff_out": nn.Linear(
1733
+ config.d_model,
1734
+ config.embedding_size or config.vocab_size,
1735
+ bias=config.include_bias,
1736
+ device=config.init_device,
1737
+ )
1738
+ }
1739
+ )
1740
+
1741
+ self.vision_backbone: Optional[OLMoVisionBackbone] = None
1742
+ if config.vision_backbone is not None:
1743
+ self.vision_backbone = OLMoPretrainedVisionBackbone(config)
1744
+
1745
+ self.__num_fwd_flops: Optional[int] = None
1746
+
1747
+ def reset_parameters(self):
1748
+ if self.vision_backbone is not None:
1749
+ self.vision_backbone.reset_parameters()
1750
+ self.reset_non_vision_parameters()
1751
+
1752
+ def reset_non_vision_parameters(self):
1753
+ self.transformer.wte.reset_parameters()
1754
+ if hasattr(self.transformer.wte, "new_embedding"):
1755
+ nn.init.normal_(self.transformer.wte.new_embedding, std=self.config.new_embedding_init_range)
1756
+
1757
+ if hasattr(self.transformer, "wpe"):
1758
+ nn.init.normal_(self.transformer.wpe, mean=0.0, std=1.0)
1759
+
1760
+ self.transformer.ln_f.reset_parameters() # type: ignore
1761
+
1762
+ if hasattr(self.transformer, "ff_out"):
1763
+ nn.init.normal_(self.transformer.ff_out, mean=0.0, std=0.02)
1764
+
1765
+ if self.config.block_group_size == 1:
1766
+ for block in self.transformer.blocks:
1767
+ block.reset_parameters()
1768
+ else:
1769
+ for block_group in self.transformer.block_groups:
1770
+ block_group.reset_parameters()
1771
+
1772
+ def forward(
1773
+ self,
1774
+ input_ids: torch.LongTensor,
1775
+ input_embeddings: Optional[torch.FloatTensor] = None,
1776
+ attention_mask: Optional[torch.Tensor] = None,
1777
+ attention_bias: Optional[torch.Tensor] = None,
1778
+ response_mask: Optional[torch.Tensor] = None,
1779
+ images: Optional[torch.Tensor] = None,
1780
+ image_masks: Optional[torch.Tensor] = None,
1781
+ image_input_idx: Optional[torch.Tensor] = None,
1782
+ subsegment_ids: Optional[torch.Tensor] = None,
1783
+ position_ids: Optional[torch.Tensor] = None,
1784
+ past_key_values: Optional[Sequence[Tuple[torch.Tensor, torch.Tensor]]] = None,
1785
+ use_cache: bool = False,
1786
+ last_logits_only: bool = False,
1787
+ output_hidden_states: Optional[bool] = None,
1788
+ append_last_valid_logits: Optional[torch.Tensor] = None,
1789
+ ) -> ModelOutput:
1790
+ """
1791
+ :param input_ids: A tensor of shape `(batch_size, seq_len)`.
1792
+ :param input_embeddings: A tensor of shape `(batch_size, seq_len, d_model)` with input
1793
+ embeddings. When provided, it is treated as the output of the input embedding layer.
1794
+ :param attention_mask: A tensor of shape `(batch_size, seq_len)` that indicates
1795
+ which input IDs are masked. A `1` value in the mask means that
1796
+ the corresponding input ID should *not* be ignored. A `0` means
1797
+ that the corresponding input ID is masked.
1798
+
1799
+ This has the same meaning as the `attention_mask` in HuggingFace's `transformers`
1800
+ library.
1801
+ :param attention_bias: A tensor of shape `(batch_size, 1, seq_len, seq_len)`,
1802
+ `(1, 1, seq_len, seq_len)`, or `(seq_len, seq_len)`. This is used
1803
+ to introduce causal or other biases.
1804
+
1805
+ If the tensor is a bool or byte tensor, a `True` or `1` at `attention_bias[:, :, i, j]`
1806
+ indicates that the i-th element in the sequence is allowed to attend to the j-th
1807
+ element in the sequence.
1808
+
1809
+ If the tensor is a float tensor, it will just be added to the attention
1810
+ scores before the softmax.
1811
+
1812
+ The default is causal, which corresponds to a lower-diagonal byte matrix of ones.
1813
+ :param response_mask: A tensor of shape `(batch_size, seq_len)` that indicates
1814
+ the response mask. A `1` value in the mask means that the corresponding token
1815
+ is a response token. A `0` means that the corresponding token is not
1816
+ a response token.
1817
+ :param past_key_values: Pre-computed keys and values for each attention block.
1818
+ Can be used to speed up sequential decoding. The `input_ids` which have
1819
+ their past given to this model should not be passed as `input_ids` as they have already been computed.
1820
+ :param use_cache: If `True`, return key and value tensors for each block.
1821
+ :param last_logits_only: If `True`, only compute the logits for the last token of each sequence.
1822
+ This can speed up decoding when you only care about the next token.
1823
+ """
1824
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else False
1825
+
1826
+ if past_key_values:
1827
+ assert len(past_key_values) == self.config.n_layers
1828
+
1829
+ has_image = images is not None
1830
+
1831
+ assert not (has_image and input_embeddings is not None), "Cannot provide both images and input embeddings."
1832
+ assert not (has_image and past_key_values is not None), "Cached key and values should not be used with images."
1833
+
1834
+ batch_size, seq_len = input_ids.size() if input_embeddings is None else input_embeddings.size()[:2]
1835
+ if past_key_values is None:
1836
+ past_length = 0
1837
+ else:
1838
+ past_length = past_key_values[0][0].size(-2)
1839
+
1840
+ if self.config.use_position_ids and attention_mask is None:
1841
+ attention_mask = input_ids != -1
1842
+
1843
+ if subsegment_ids is not None:
1844
+ assert not use_cache, "Subsegment_ids cannot be used with cache."
1845
+ subsegment_mask = subsegment_ids.unsqueeze(2) <= subsegment_ids.unsqueeze(1)
1846
+ attention_mask = (
1847
+ subsegment_mask.to(attention_mask.dtype) *
1848
+ attention_mask.unsqueeze(2) *
1849
+ attention_mask.unsqueeze(1))
1850
+ if position_ids is None:
1851
+ raise ValueError(f"Positioned ids must be given if using subsegment_ids")
1852
+ else:
1853
+ if self.config.use_position_ids and position_ids is None:
1854
+ position_ids = torch.clamp(
1855
+ torch.cumsum(attention_mask.to(torch.int32), dim=-1) - 1,
1856
+ min=0,
1857
+ ).broadcast_to((batch_size, attention_mask.shape[-1]))
1858
+
1859
+ # Get embeddings of input.
1860
+ # shape: (batch_size, seq_len, d_model)
1861
+ if input_ids is not None:
1862
+ input_ids = input_ids * (input_ids != -1).to(input_ids.dtype)
1863
+ x = self.transformer.wte(input_ids) if input_embeddings is None else input_embeddings # type: ignore
1864
+
1865
+ num_image: Optional[int] = None
1866
+ if images is not None:
1867
+ # shape: (batch_size, num_image, num_patch, d_model)
1868
+ # cls_embed: (batch_size, num_image, d_model)
1869
+ image_features, cls_embed = self.vision_backbone(images, image_masks)
1870
+ num_image, num_patch = image_features.shape[1:3]
1871
+ assert image_input_idx.shape == (batch_size, num_image, num_patch)
1872
+
1873
+ # inster the image feature into the embedding.
1874
+ image_features = image_features.view(batch_size, num_image * num_patch, -1)
1875
+ image_input_idx = image_input_idx.view(batch_size, num_image * num_patch)
1876
+
1877
+ valid = image_input_idx >= 0
1878
+ batch_idx = torch.arange(batch_size, device=x.device)
1879
+ batch_idx = torch.tile(batch_idx[:, None], [1, image_features.shape[1]])
1880
+
1881
+ # For hf demo/endpoint
1882
+ image_features = image_features.to(x.device)
1883
+
1884
+ x[batch_idx[valid], image_input_idx[valid]] += image_features[valid]
1885
+
1886
+ if not self.config.rope:
1887
+ # Get positional embeddings.
1888
+ # shape: (1, seq_len)
1889
+ pos = torch.arange(past_length, past_length + seq_len, dtype=torch.long, device=x.device).unsqueeze(0)
1890
+ # shape: (1, seq_len, d_model)
1891
+ pos_emb = self.transformer.wpe(pos) # type: ignore
1892
+ x = pos_emb + x
1893
+
1894
+ # Add input + positional embeddings and apply dropout.
1895
+ # shape: (batch_size, seq_len, d_model)
1896
+ x = self.transformer.emb_drop(x) # type: ignore
1897
+
1898
+ # normalized
1899
+ if self.config.normalize_input_embeds:
1900
+ x = x * (self.config.d_model ** 0.5)
1901
+
1902
+ # Transform the attention mask into what the blocks expect.
1903
+ if attention_mask is not None:
1904
+ # shape: (batch_size, 1, 1, seq_len)
1905
+ if len(attention_mask.shape) == 2:
1906
+ attention_mask = attention_mask[:, :past_length + seq_len]
1907
+ attention_mask = attention_mask.to(dtype=torch.float).view(batch_size, -1)[:, None, None, :]
1908
+ else:
1909
+ attention_mask = attention_mask.unsqueeze(1).to(dtype=torch.float)
1910
+ attention_mask = (1.0 - attention_mask) * torch.finfo(attention_mask.dtype).min
1911
+
1912
+ # Merge attention mask with attention bias.
1913
+ if (
1914
+ attention_bias is not None
1915
+ or attention_mask is not None
1916
+ # NOTE (epwalsh): we need to initialize the attn bias in order for attn to work properly
1917
+ # with key+value cache. Otherwise `F.scaled_dot_product_attention()` doesn't seem to compute
1918
+ # scores correctly.
1919
+ or past_key_values is not None
1920
+ ):
1921
+ if attention_bias is None:
1922
+ attention_bias = get_causal_attention_bias(self.__cache, past_length + seq_len, x.device)
1923
+ elif attention_bias.dtype in (torch.int8, torch.bool):
1924
+ attention_bias = attention_bias.to(dtype=torch.float)
1925
+ attention_bias.masked_fill_(attention_bias == 0.0, torch.finfo(attention_bias.dtype).min)
1926
+
1927
+ # Transform to the right shape and data type.
1928
+ mask_len = seq_len
1929
+ if attention_mask is not None:
1930
+ mask_len = attention_mask.shape[-1]
1931
+ elif past_key_values is not None:
1932
+ mask_len = past_key_values[0][0].shape[-2] + seq_len
1933
+ attention_bias = attention_bias[:, :, :mask_len, :mask_len].to(dtype=torch.float)
1934
+
1935
+ # Add in the masking bias.
1936
+ if attention_mask is not None:
1937
+ attention_bias = attention_bias + attention_mask
1938
+ # Might get -infs after adding attention mask, since dtype.min + dtype.min = -inf.
1939
+ # `F.scaled_dot_product_attention()` doesn't handle -inf like you'd expect, instead
1940
+ # it can produce NaNs.
1941
+ ensure_finite_(attention_bias, check_neg_inf=True, check_pos_inf=False)
1942
+
1943
+ attn_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = [] if use_cache else None
1944
+
1945
+ # decoder layers
1946
+ all_hidden_states = []
1947
+
1948
+ # Apply blocks one-by-one.
1949
+ if self.config.block_group_size == 1:
1950
+ for block_idx, block in enumerate(self.transformer.blocks):
1951
+ if output_hidden_states:
1952
+ # add hidden states
1953
+ all_hidden_states.append(x)
1954
+
1955
+ layer_past = None if past_key_values is None else past_key_values[block_idx]
1956
+ x, cache = block(x, attention_bias=attention_bias, position_ids=position_ids, layer_past=layer_past, use_cache=use_cache)
1957
+
1958
+ if attn_key_values is not None:
1959
+ assert cache is not None
1960
+ attn_key_values.append(cache)
1961
+ else:
1962
+ for group_idx, block_group in enumerate(self.transformer.block_groups):
1963
+ if output_hidden_states:
1964
+ # add hidden states
1965
+ all_hidden_states.append(x)
1966
+
1967
+ layers_past = (
1968
+ None
1969
+ if past_key_values is None
1970
+ else past_key_values[
1971
+ group_idx * self.config.block_group_size : (group_idx + 1) * self.config.block_group_size
1972
+ ]
1973
+ )
1974
+ x, cache = block_group(
1975
+ x, attention_bias=attention_bias, position_ids=position_ids, layers_past=layers_past, use_cache=use_cache
1976
+ )
1977
+ if attn_key_values is not None:
1978
+ assert cache is not None
1979
+ attn_key_values.extend(cache)
1980
+
1981
+ if last_logits_only:
1982
+ # shape: (batch_size, 1, d_model)
1983
+ if append_last_valid_logits is not None:
1984
+ last_valid_output = x[
1985
+ torch.arange(x.shape[0], device=x.device), append_last_valid_logits.to(x.device)]
1986
+ x = last_valid_output.unsqueeze(1)
1987
+ else:
1988
+ x = x[:, -1, :].unsqueeze(1)
1989
+
1990
+ # Apply final layer norm.
1991
+ # shape: (batch_size, seq_len or 1, d_model)
1992
+ x = self.transformer.ln_f(x) # type: ignore
1993
+ if output_hidden_states:
1994
+ # add final hidden state post-final-layernorm, following HuggingFace's convention
1995
+ all_hidden_states.append(x)
1996
+
1997
+ # Get logits.
1998
+ # shape: (batch_size, seq_len or 1, vocab_size)
1999
+ if self.config.weight_tying:
2000
+ logits = F.linear(x, self.transformer.wte.weight, None) # type: ignore
2001
+ else:
2002
+ logits = self.transformer.ff_out(x) # type: ignore
2003
+ if self.config.scale_logits:
2004
+ logits.mul_(1 / math.sqrt(self.config.d_model))
2005
+
2006
+ if not last_logits_only and append_last_valid_logits is not None:
2007
+ last_valid_logit = logits[
2008
+ torch.arange(logits.shape[0], device=logits.device), append_last_valid_logits]
2009
+ logits = torch.cat([logits[:, :-1], last_valid_logit[:, None]], dim=1)
2010
+
2011
+ 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]
2012
+
2013
+
2014
+ class MolmoForCausalLM(PreTrainedModel):
2015
+ config_class = MolmoConfig
2016
+ base_model_prefix = "model"
2017
+ _no_split_modules = ["MolmoBlock"]
2018
+
2019
+ def __init__(self, config: MolmoConfig, model: Optional[Molmo] = None, init_params: bool = False):
2020
+ super().__init__(config)
2021
+
2022
+ if not model:
2023
+ full_config = FullMolmoConfig(
2024
+ image_padding_embed="pad_and_partial_pad",
2025
+ image_pooling_2d="attention-meanq",
2026
+ attention_layer_norm=config.attention_layer_norm,
2027
+ rope_impl="llama",
2028
+ vocab_size=config.vocab_size,
2029
+ max_sequence_length=config.max_position_embeddings,
2030
+ qkv_bias=config.qkv_bias,
2031
+ norm_after=config.norm_after,
2032
+ embedding_size=config.embedding_size,
2033
+ attention_type="sdpa",
2034
+ embedding_dropout=0,
2035
+ attention_dropout=0,
2036
+ residual_dropout=0,
2037
+ rope=True,
2038
+ weight_tying=False,
2039
+ include_bias=False,
2040
+ d_model=config.hidden_size,
2041
+ mlp_hidden_size=config.intermediate_size,
2042
+ n_layers=config.num_hidden_layers,
2043
+ additional_vocab_size=128,
2044
+ n_heads=config.num_attention_heads,
2045
+ n_kv_heads=config.num_key_value_heads,
2046
+ rope_theta=config.rope_theta,
2047
+ layer_norm_eps=config.layer_norm_eps,
2048
+ layer_norm_type=config.layer_norm_type,
2049
+ vit_layers=[-2, -9],
2050
+ vision_backbone=VisionBackboneConfig(
2051
+ image_default_input_size=(336, 336),
2052
+ image_patch_size=14,
2053
+ image_pos_patch_size=14,
2054
+ image_emb_dim=1024,
2055
+ image_num_heads=16,
2056
+ image_num_key_value_heads=16,
2057
+ image_num_layers=23,
2058
+ image_head_dim=64,
2059
+ image_mlp_dim=4096,
2060
+ image_mlp_activations="quick_gelu",
2061
+ image_dropout_rate=0.0,
2062
+ image_num_pos=577,
2063
+ image_norm_eps=1e-5,
2064
+ attention_dropout=0.0,
2065
+ residual_dropout=0.0,
2066
+ initializer_range=0.02,
2067
+ )
2068
+ )
2069
+ self.model = Molmo(full_config, init_params=init_params)
2070
+ else:
2071
+ self.model = model
2072
+
2073
+ def forward(
2074
+ self,
2075
+ input_ids: torch.LongTensor = None,
2076
+ inputs_embeds: Optional[torch.FloatTensor] = None,
2077
+ attention_mask: Optional[torch.Tensor] = None,
2078
+ attention_bias: Optional[torch.Tensor] = None,
2079
+ response_mask: Optional[torch.Tensor] = None,
2080
+ images: Optional[torch.Tensor] = None,
2081
+ image_masks: Optional[torch.Tensor] = None,
2082
+ image_input_idx: Optional[torch.Tensor] = None,
2083
+ subsegment_ids: Optional[torch.Tensor] = None,
2084
+ position_ids: Optional[torch.Tensor] = None,
2085
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
2086
+ labels: Optional[torch.LongTensor] = None,
2087
+ loss_masks: Optional[torch.Tensor] = None,
2088
+ use_cache: Optional[bool] = None,
2089
+ last_logits_only: Optional[bool] = None,
2090
+ output_attentions: Optional[bool] = None,
2091
+ output_hidden_states: Optional[bool] = None,
2092
+ append_last_valid_logits: Optional[torch.Tensor] = None,
2093
+ return_dict: Optional[bool] = None,
2094
+ cache_position: Optional[
2095
+ Cache
2096
+ ] = None, # This is a hack mitigation of an issue in transformers `4.39.x` https://github.com/huggingface/transformers/issues/29426
2097
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
2098
+ if use_cache is None:
2099
+ use_cache = self.config.use_cache
2100
+
2101
+ if output_attentions:
2102
+ raise ValueError("output_attentions is not yet supported in Molmo")
2103
+
2104
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
2105
+
2106
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
2107
+ outputs = self.model.forward(
2108
+ input_ids=input_ids,
2109
+ input_embeddings=inputs_embeds,
2110
+ attention_mask=attention_mask,
2111
+ attention_bias=attention_bias,
2112
+ response_mask=response_mask,
2113
+ images=images,
2114
+ image_masks=image_masks,
2115
+ image_input_idx=image_input_idx,
2116
+ subsegment_ids=subsegment_ids,
2117
+ position_ids=position_ids,
2118
+ past_key_values=past_key_values,
2119
+ use_cache=use_cache,
2120
+ last_logits_only=last_logits_only,
2121
+ output_hidden_states=output_hidden_states,
2122
+ append_last_valid_logits=append_last_valid_logits,
2123
+ )
2124
+
2125
+ logits = outputs.logits
2126
+ hidden_states = outputs.hidden_states
2127
+
2128
+ loss = None
2129
+ if labels is not None:
2130
+ if loss_masks is not None:
2131
+ loss_masks = loss_masks * (loss_masks > 0)
2132
+ batch_size_in_tokens = max(loss_masks.sum().item(), 1)
2133
+ labels = labels.long()
2134
+ labels.masked_fill_(~(loss_masks > 0), -100)
2135
+ labels = labels.view(-1)
2136
+ logits_for_loss = logits.to(torch.float32).view(-1, logits.size(-1))
2137
+ loss_fct = torch.nn.CrossEntropyLoss(ignore_index=-100, reduction='none')
2138
+ loss = loss_fct(logits_for_loss, labels)
2139
+ loss = loss.view(input_ids.shape[0], -1)
2140
+ loss = loss * loss_masks
2141
+ loss = loss.sum() / batch_size_in_tokens
2142
+ use_zloss = getattr(self.config, "softmax_auxiliary_loss", False)
2143
+ if use_zloss:
2144
+ z_squared = logits_for_loss.logsumexp(-1).pow(2)
2145
+ z_loss = self.config.softmax_auxiliary_loss_scale * z_squared
2146
+ z_loss = z_loss.view(input_ids.shape[0], -1)
2147
+ z_loss = z_loss * loss_masks
2148
+ z_loss = z_loss.sum() / batch_size_in_tokens
2149
+ loss += z_loss
2150
+ else:
2151
+ # Shift so that tokens < n predict n
2152
+ shift_logits = logits[..., :-1, :].contiguous()
2153
+ shift_labels = labels[..., 1:].contiguous()
2154
+ # Flatten the tokens
2155
+ loss_fct = torch.nn.CrossEntropyLoss()
2156
+ shift_logits = shift_logits.view(-1, self.config.embedding_size)
2157
+ shift_labels = shift_labels.view(-1)
2158
+ # Enable model parallelism
2159
+ shift_labels = shift_labels.to(shift_logits.device)
2160
+ loss = loss_fct(shift_logits, shift_labels)
2161
+
2162
+ if not return_dict:
2163
+ output = (logits,) + outputs[1:]
2164
+ return (loss,) + output if loss is not None else output
2165
+
2166
+ return CausalLMOutputWithPast(
2167
+ loss=loss,
2168
+ logits=logits,
2169
+ past_key_values=outputs.attn_key_values,
2170
+ hidden_states=hidden_states,
2171
+ )
2172
+
2173
+ def can_generate(self) -> bool:
2174
+ return True
2175
+
2176
+ @torch.no_grad()
2177
+ def generate_from_batch(
2178
+ self,
2179
+ batch: Dict[str, Any],
2180
+ generation_config: Optional[GenerationConfig] = None,
2181
+ **kwargs,
2182
+ ):
2183
+ if generation_config is not None:
2184
+ assert generation_config.use_cache
2185
+
2186
+ images = batch.get("images")
2187
+ image_masks = batch.get("image_masks")
2188
+ image_input_idx = batch.get("image_input_idx")
2189
+
2190
+ # Validate inputs.
2191
+ input_ids = batch["input_ids"]
2192
+ batch_size, seq_len = input_ids.shape
2193
+ attention_mask = batch.get("attention_mask", None)
2194
+ max_new_tokens = generation_config.max_new_tokens
2195
+ assert max_new_tokens is not None
2196
+ mask_len = seq_len + max_new_tokens if self.config.use_position_ids else seq_len
2197
+ position_ids: Optional[torch.Tensor] = None
2198
+ append_last_valid_logits: Optional[torch.Tensor] = None
2199
+ if self.config.use_position_ids and attention_mask is None:
2200
+ attention_mask = input_ids != -1
2201
+ position_ids = torch.clamp(
2202
+ torch.cumsum(attention_mask.to(torch.int32), dim=-1) - 1,
2203
+ min=0
2204
+ )
2205
+ append_last_valid_logits = attention_mask.long().sum(dim=-1) - 1
2206
+ attention_mask = torch.cat(
2207
+ [attention_mask, attention_mask.new_ones((batch_size, max_new_tokens))],
2208
+ dim=1,
2209
+ )
2210
+ if attention_mask is not None:
2211
+ assert attention_mask.shape == (batch_size, mask_len)
2212
+
2213
+ out = super().generate(
2214
+ batch["input_ids"],
2215
+ generation_config,
2216
+ attention_mask=attention_mask,
2217
+ images=images,
2218
+ image_masks=image_masks,
2219
+ image_input_idx=image_input_idx,
2220
+ position_ids=position_ids,
2221
+ append_last_valid_logits=append_last_valid_logits,
2222
+ **kwargs,
2223
+ )
2224
+
2225
+ return out
2226
+
2227
+ def prepare_inputs_for_generation(
2228
+ self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple]] = None, **kwargs
2229
+ ):
2230
+ if past_key_values:
2231
+ # This is because we want the model to only process the last generated token.
2232
+ input_ids = input_ids[:, -1:]
2233
+
2234
+ if self.config.use_position_ids:
2235
+ attention_mask = kwargs.get("attention_mask")
2236
+ images = kwargs.get("images")
2237
+ image_masks = kwargs.get("image_masks")
2238
+ image_input_idx = kwargs.get("image_input_idx")
2239
+ position_ids = kwargs.get("position_ids")
2240
+ append_last_valid_logits = kwargs.get("append_last_valid_logits")
2241
+ model_inputs = {
2242
+ "input_ids": input_ids,
2243
+ "attention_mask": attention_mask,
2244
+ "position_ids": position_ids,
2245
+ "past_key_values": past_key_values,
2246
+ "use_cache": True,
2247
+ "last_logits_only": True,
2248
+ }
2249
+ if past_key_values is None:
2250
+ model_inputs["images"] = images
2251
+ model_inputs["image_masks"] = image_masks
2252
+ model_inputs["image_input_idx"] = image_input_idx
2253
+ model_inputs["append_last_valid_logits"] = append_last_valid_logits
2254
+ else:
2255
+ model_inputs = {"input_ids": input_ids, "past_key_values": past_key_values}
2256
+
2257
+ model_inputs.update(kwargs)
2258
+ model_inputs["use_cache"] = kwargs.pop("use_cache", self.config.use_cache)
2259
+ return model_inputs
2260
+
2261
+ def _update_model_kwargs_for_generation(
2262
+ self,
2263
+ outputs: ModelOutput,
2264
+ model_kwargs: Dict[str, Any],
2265
+ is_encoder_decoder: bool = False,
2266
+ num_new_tokens: int = 1,
2267
+ ) -> Dict[str, Any]:
2268
+ if self.config.use_position_ids:
2269
+ model_kwargs["position_ids"] = model_kwargs["position_ids"][:, -1:] + 1
2270
+ if "append_last_valid_logits" in model_kwargs:
2271
+ del model_kwargs["append_last_valid_logits"]
2272
+ if "images" in model_kwargs:
2273
+ del model_kwargs["images"]
2274
+ del model_kwargs["image_masks"]
2275
+ del model_kwargs["image_input_idx"]
2276
+ cache_name, cache = super()._extract_past_from_model_output(outputs)
2277
+ model_kwargs[cache_name] = cache
2278
+ model_kwargs["cache_position"] = model_kwargs["cache_position"][-1:] + num_new_tokens
2279
+ return model_kwargs
2280
+
2281
+ def get_input_embeddings(self) -> torch.nn.Module:
2282
+ return self.model.transformer.wte
2283
+
2284
+ def set_input_embeddings(self, value: torch.nn.Module):
2285
+ self.model.transformer.wte = value
2286
+
2287
+ def get_output_embeddings(self):
2288
+ if self.config.weight_tying:
2289
+ return self.model.transformer.wte
2290
+ else:
2291
+ return self.model.transformer.ff_out
2292
+
2293
+ def set_output_embeddings(self, value: torch.nn.Module):
2294
+ if self.config.weight_tying:
2295
+ self.model.transformer.wte = value
2296
+ else:
2297
+ self.model.transformer.ff_out = value
2298
+
2299
+ def tie_weights(self):
2300
+ """
2301
+ This function is intentionally left as a no-op.
2302
+
2303
+ Weight tying is handled as follows:
2304
+ - When the model is initialized, the `ff_out` layer is conditionally defined based on the `weight_tying` configuration.
2305
+ See: `if not config.weight_tying: self.transformer.update(...)` in `olmo/model.py`.
2306
+ - When computing logits, the `wte` weights are used directly if `weight_tying` is enabled.
2307
+ See: `if self.config.weight_tying: logits = F.linear(x, self.transformer.wte.weight, None)` in the `forward` method.
2308
+
2309
+ Therefore, there is no need to explicitly tie the weights in this function.
2310
+ """
2311
+ pass
2312
+
2313
+ def resize_token_embeddings(
2314
+ self, new_num_tokens: Optional[int] = None, pad_to_multiple_of: Optional[int] = None
2315
+ ) -> torch.nn.Embedding:
2316
+ """
2317
+ Resizes input token embeddings matrix of the model if `new_num_tokens != config.embedding_size`.
2318
+
2319
+ Takes care of tying weights embeddings afterwards if the model class has a `tie_weights()` method.
2320
+
2321
+ Arguments:
2322
+ new_num_tokens (`int`, *optional*):
2323
+ The new number of tokens in the embedding matrix. Increasing the size will add newly initialized
2324
+ vectors at the end. Reducing the size will remove vectors from the end. If not provided or `None`, just
2325
+ returns a pointer to the input tokens `torch.nn.Embedding` module of the model without doing anything.
2326
+ pad_to_multiple_of (`int`, *optional*):
2327
+ If set will pad the embedding matrix to a multiple of the provided value. If `new_num_tokens` is set to
2328
+ `None` will just pad the embedding to a multiple of `pad_to_multiple_of`.
2329
+
2330
+ This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
2331
+ `>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128. For more
2332
+ details about this, or help on choosing the correct value for resizing, refer to this guide:
2333
+ https://docs.nvidia.com/deeplearning/performance/dl-performance-matrix-multiplication/index.html#requirements-tc
2334
+
2335
+ Return:
2336
+ `torch.nn.Embedding`: Pointer to the input tokens Embeddings Module of the model.
2337
+
2338
+ Note:
2339
+ This method differs from the base class implementation by resizing the `embedding_size` attribute of the
2340
+ model configuration instead of the `vocab_size`. It also includes a warning if the resized `embedding_size`
2341
+ is less than the `vocab_size`. In OLMo, `embedding_size` refers to the dimensionality of the model's token
2342
+ embeddings, while `vocab_size` refers to the number of unique tokens in the vocabulary.
2343
+ """
2344
+ model_embeds = self._resize_token_embeddings(new_num_tokens, pad_to_multiple_of)
2345
+ if new_num_tokens is None and pad_to_multiple_of is None:
2346
+ return model_embeds
2347
+
2348
+ # Update base model and current model config
2349
+ self.config.embedding_size = model_embeds.weight.shape[0]
2350
+ self.model.config.embedding_size = model_embeds.weight.shape[0]
2351
+
2352
+ # Check if the embedding size is less than the vocab size
2353
+ if self.config.embedding_size < self.config.vocab_size:
2354
+ warning_message = (
2355
+ f"Resizing token embeddings to size {self.config.embedding_size}, which is less than the vocab size "
2356
+ f"{self.config.vocab_size} defined in the model configuration. Make sure your tokenizer's vocabulary "
2357
+ "size is less than or equal to the new token embedding size."
2358
+ )
2359
+ log.warning(warning_message)
2360
+
2361
+ # Tie weights again if needed
2362
+ self.tie_weights()
2363
+
2364
+ return model_embeds
2365
+
2366
+
2367
+ # Always register for multi-modal features
2368
+ AutoModelForCausalLM.register(MolmoConfig, MolmoForCausalLM)