Q-bert commited on
Commit
227a26e
1 Parent(s): 06afe08

Create modeling_mamba.py

Browse files
Files changed (1) hide show
  1. modeling_mamba.py +302 -0
modeling_mamba.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ import torch
3
+ from .configuration_mamba import MambaConfig
4
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
5
+ from transformers.modeling_utils import PreTrainedModel
6
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
7
+ import math
8
+ import json
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+ from dataclasses import dataclass
13
+ from einops import rearrange, repeat, einsum
14
+ from typing import Optional , Union ,Tuple
15
+
16
+ # Dear contributors of the https://github.com/johnma2006/mamba-minimal/tree/master repository, special thanks to Albert Gu and Tri Dao for their articles. (https://arxiv.org/abs/2312.00752)
17
+
18
+
19
+ class MambaRMSNorm(nn.Module):
20
+ def __init__(self,
21
+ d_model: int,
22
+ eps: float = 1e-5):
23
+ super().__init__()
24
+ self.eps = eps
25
+ self.weight = nn.Parameter(torch.ones(d_model))
26
+ def forward(self, x):
27
+ output = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight
28
+ return output
29
+
30
+
31
+ class MambaBlock(nn.Module):
32
+ def __init__(self, config: MambaConfig):
33
+ """A single Mamba block, as described in Figure 3 in Section 3.4 in the Mamba paper [1]."""
34
+ super().__init__()
35
+ self.config = config
36
+
37
+ self.in_proj = nn.Linear(config.d_model, config.d_inner * 2, bias=config.bias)
38
+
39
+ self.conv1d = nn.Conv1d(
40
+ in_channels=config.d_inner,
41
+ out_channels=config.d_inner,
42
+ bias=config.conv_bias,
43
+ kernel_size=config.d_conv,
44
+ groups=config.d_inner,
45
+ padding=config.d_conv - 1,
46
+ )
47
+
48
+ # x_proj takes in `x` and outputs the input-specific Δ, B, C
49
+ self.x_proj = nn.Linear(config.d_inner, config.dt_rank + config.d_state * 2, bias=False)
50
+
51
+ # dt_proj projects Δ from dt_rank to d_in
52
+ self.dt_proj = nn.Linear(config.dt_rank, config.d_inner, bias=True)
53
+
54
+ A = repeat(torch.arange(1, config.d_state + 1), 'n -> d n', d=config.d_inner)
55
+ self.A_log = nn.Parameter(torch.log(A))
56
+ self.D = nn.Parameter(torch.ones(config.d_inner))
57
+ self.out_proj = nn.Linear(config.d_inner, config.d_model, bias=config.bias)
58
+ self.norm = MambaRMSNorm(config.d_model)
59
+
60
+ def forward(self, x):
61
+ """Mamba block forward. This looks the same as Figure 3 in Section 3.4 in the Mamba paper [1].
62
+
63
+ Args:
64
+ x: shape (b, l, d) (See Glossary at top for definitions of b, l, d_in, n...)
65
+
66
+ Returns:
67
+ output: shape (b, l, d)
68
+
69
+ Official Implementation:
70
+ class Mamba, https://github.com/state-spaces/mamba/blob/main/mamba_ssm/modules/mamba_simple.py#L119
71
+ mamba_inner_ref(), https://github.com/state-spaces/mamba/blob/main/mamba_ssm/ops/selective_scan_interface.py#L311
72
+
73
+ """
74
+
75
+ (b, l, d) = x.shape
76
+ x_copy = x # There was a separate class for residual, I deleted that part and added it here.
77
+ x = self.norm(x)
78
+ x_and_res = self.in_proj(x) # shape (b, l, 2 * d_in)
79
+ (x, res) = x_and_res.split(split_size=[self.config.d_inner, self.config.d_inner], dim=-1)
80
+
81
+ x = rearrange(x, 'b l d_in -> b d_in l')
82
+ x = self.conv1d(x)[:, :, :l]
83
+ x = rearrange(x, 'b d_in l -> b l d_in')
84
+
85
+ x = F.silu(x)
86
+
87
+ y = self.ssm(x)
88
+
89
+ y = y * F.silu(res)
90
+
91
+ output = self.out_proj(y) + x_copy
92
+
93
+ return output
94
+
95
+
96
+ def ssm(self, x):
97
+ """Runs the SSM. See:
98
+ - Algorithm 2 in Section 3.2 in the Mamba paper [1]
99
+ - run_SSM(A, B, C, u) in The Annotated S4 [2]
100
+ Args:
101
+ x: shape (b, l, d_in) (See Glossary at top for definitions of b, l, d_in, n...)
102
+
103
+ Returns:
104
+ output: shape (b, l, d_in)
105
+ Official Implementation:
106
+ mamba_inner_ref(), https://github.com/state-spaces/mamba/blob/main/mamba_ssm/ops/selective_scan_interface.py#L311
107
+
108
+ """
109
+ (d_in, n) = self.A_log.shape
110
+
111
+ # Compute ∆ A B C D, the state space parameters.
112
+ # A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
113
+ # ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
114
+ # and is why Mamba is called **selective** state spaces)
115
+
116
+ A = -torch.exp(self.A_log.float()) # shape (d_in, n)
117
+ D = self.D.float()
118
+
119
+ x_dbl = self.x_proj(x) # (b, l, dt_rank + 2*n)
120
+
121
+ (delta, B, C) = x_dbl.split(split_size=[self.config.dt_rank, n, n], dim=-1) # delta: (b, l, dt_rank). B, C: (b, l, n)
122
+ delta = F.softplus(self.dt_proj(delta)) # (b, l, d_in)
123
+
124
+ y = self.selective_scan(x, delta, A, B, C, D) # This is similar to run_SSM(A, B, C, u) in The Annotated S4 [2]
125
+
126
+ return y
127
+
128
+
129
+ def selective_scan(self, u, delta, A, B, C, D):
130
+ """Does selective scan algorithm. See:
131
+ - Section 2 State Space Models in the Mamba paper [1]
132
+ - Algorithm 2 in Section 3.2 in the Mamba paper [1]
133
+ - run_SSM(A, B, C, u) in The Annotated S4 [2]
134
+ This is the classic discrete state space formula:
135
+ x(t + 1) = Ax(t) + Bu(t)
136
+ y(t) = Cx(t) + Du(t)
137
+ except B and C (and the step size delta, which is used for discretization) are dependent on the input x(t).
138
+
139
+ Args:
140
+ u: shape (b, l, d_in) (See Glossary at top for definitions of b, l, d_in, n...)
141
+ delta: shape (b, l, d_in)
142
+ A: shape (d_in, n)
143
+ B: shape (b, l, n)
144
+ C: shape (b, l, n)
145
+ D: shape (d_in,)
146
+
147
+ Returns:
148
+ output: shape (b, l, d_in)
149
+
150
+ Official Implementation:
151
+ selective_scan_ref(), https://github.com/state-spaces/mamba/blob/main/mamba_ssm/ops/selective_scan_interface.py#L86
152
+ Note: I refactored some parts out of `selective_scan_ref` out, so the functionality doesn't match exactly.
153
+
154
+ """
155
+ (b, l, d_in) = u.shape
156
+ n = A.shape[1]
157
+
158
+ # Discretize continuous parameters (A, B)
159
+ # - A is discretized using zero-order hold (ZOH) discretization (see Section 2 Equation 4 in the Mamba paper [1])
160
+ # - B is discretized using a simplified Euler discretization instead of ZOH. From a discussion with authors:
161
+ # "A is the more important term and the performance doesn't change much with the simplication on B"
162
+ deltaA = torch.exp(einsum(delta, A, 'b l d_in, d_in n -> b d_in l n'))
163
+ deltaB_u = einsum(delta, B, u, 'b l d_in, b l n, b l d_in -> b d_in l n')
164
+
165
+ # Perform selective scan (see scan_SSM() in The Annotated S4 [2])
166
+ x = torch.zeros((b, d_in, n), device=deltaA.device)
167
+ ys = []
168
+ for i in range(l):
169
+ x = deltaA[:, :, i] * x + deltaB_u[:, :, i]
170
+ y = einsum(x, C[:, i, :], 'b d_in n, b n -> b d_in')
171
+ ys.append(y)
172
+ y = torch.stack(ys, dim=1) # shape (b, l, d_in)
173
+
174
+ y = y + u * D
175
+
176
+ return y
177
+
178
+ class MambaPreTrainedModel(PreTrainedModel):
179
+ config_class = MambaConfig
180
+ base_model_prefix = "model"
181
+ supports_gradient_checkpointing = True
182
+ _no_split_modules = ["MambaBlock"]
183
+
184
+ def _init_weights(self, module):
185
+ std = 0.02
186
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
187
+ module.weight.data.normal_(mean=0.0, std=std)
188
+ if module.bias is not None:
189
+ module.bias.data.zero_()
190
+ elif isinstance(module, nn.Embedding):
191
+ module.weight.data.normal_(mean=0.0, std=std)
192
+ if module.padding_idx is not None:
193
+ module.weight.data[module.padding_idx].zero_()
194
+
195
+ class MambaModel(MambaPreTrainedModel):
196
+ def __init__(self, config: MambaConfig):
197
+ """Full Mamba model.
198
+ Mamba model decoder consisting of *config.n_layer* layers. Each layer is a [`MambaBlock`]
199
+ Args:
200
+ config: MambaConfig
201
+ """
202
+ super().__init__(config)
203
+ self.config = config
204
+
205
+ self.embedding = nn.Embedding(config.vocab_size, config.d_model)
206
+ self.layers = nn.ModuleList([MambaBlock(config) for _ in range(config.n_layer)])
207
+ self.norm_f = MambaRMSNorm(config.d_model)
208
+
209
+ self.gradient_checkpointing = False
210
+ self.post_init()
211
+
212
+ def get_input_embeddings(self):
213
+ return self.embedding
214
+
215
+ def set_input_embeddings(self, value):
216
+ self.embedding = value
217
+
218
+ def forward(self,
219
+ input_ids: torch.LongTensor = None,
220
+ return_dict: Optional[bool] = None,
221
+ )-> Union[Tuple, BaseModelOutputWithPast]:
222
+ x = self.embedding(input_ids)
223
+ all_hidden_states = list()
224
+ for layer in self.layers:
225
+ x = layer(x)
226
+ all_hidden_states.append(x)
227
+
228
+ hidden_states = self.norm_f(x)
229
+
230
+ return BaseModelOutputWithPast(
231
+ last_hidden_state=hidden_states,
232
+ hidden_states=all_hidden_states,
233
+ )
234
+ class MambaForCausalLM(MambaPreTrainedModel):
235
+ _tied_weights_keys = ["lm_head.weight"]
236
+
237
+ def __init__(self, config):
238
+ super().__init__(config)
239
+ self.model = MambaModel(config)
240
+ self.vocab_size = config.vocab_size
241
+ self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
242
+ self.lm_head.weight = self.model.embedding.weight
243
+ self.post_init()
244
+
245
+ def get_input_embeddings(self):
246
+ return self.model.embedding
247
+
248
+ def set_input_embeddings(self, value):
249
+ self.model.embedding = value
250
+
251
+ def get_output_embeddings(self):
252
+ return self.lm_head
253
+
254
+ def set_output_embeddings(self, new_embeddings):
255
+ self.lm_head = new_embeddings
256
+
257
+ def set_decoder(self, decoder):
258
+ self.model = decoder
259
+
260
+ def get_decoder(self):
261
+ return self.model
262
+
263
+ def forward(self,
264
+ input_ids: torch.LongTensor = None,
265
+ labels: Optional[torch.LongTensor] = None,
266
+ output_attentions: Optional[bool] = None,
267
+ output_hidden_states: Optional[bool] = None,
268
+ return_dict: Optional[bool] = None,
269
+ )-> Union[Tuple, CausalLMOutputWithPast]:
270
+ outputs = self.model(
271
+ input_ids=input_ids,
272
+ return_dict=return_dict,
273
+ )
274
+ hidden_states = outputs[0]
275
+ logits = self.lm_head(hidden_states)
276
+ logits = logits.float()
277
+ loss = None
278
+ if labels is not None:
279
+ shift_logits = logits[..., :-1, :].contiguous()
280
+ shift_labels = labels[..., 1:].contiguous()
281
+ loss_fct = CrossEntropyLoss()
282
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
283
+ shift_labels = shift_labels.view(-1)
284
+
285
+ shift_labels = shift_labels.to(shift_logits.device)
286
+ loss = loss_fct(shift_logits, shift_labels)
287
+
288
+ if not return_dict:
289
+ output = (logits,) + outputs[1:]
290
+ return (loss,) + output if loss is not None else output
291
+
292
+ return CausalLMOutputWithPast(
293
+ loss=loss,
294
+ logits=logits,
295
+ hidden_states=outputs.hidden_states,
296
+ )
297
+
298
+ def prepare_inputs_for_generation(
299
+ self, input_ids, **kwargs
300
+ ):
301
+ model_inputs = {"input_ids": input_ids}
302
+ return model_inputs