njeffrie commited on
Commit
ad11e5c
·
verified ·
1 Parent(s): e6033db

Upload model

Browse files
Files changed (5) hide show
  1. README.md +199 -0
  2. config.json +20 -0
  3. configuration_moonshine.py +32 -0
  4. model.safetensors +3 -0
  5. modeling_moonshine.py +508 -0
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "MoonshineModel"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_moonshine.MoonshineConfig",
7
+ "AutoModelForCausalLM": "modeling_moonshine.MoonshineModel"
8
+ },
9
+ "dec_depth": 6,
10
+ "dec_ff_swiglu": true,
11
+ "dec_voc_size": 32768,
12
+ "dim": 288,
13
+ "enc_depth": 6,
14
+ "enc_ff_swiglu": false,
15
+ "inner_dim": 288,
16
+ "model_type": "moonshine",
17
+ "n_head": 8,
18
+ "torch_dtype": "float32",
19
+ "transformers_version": "4.47.0.dev0"
20
+ }
configuration_moonshine.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+ from typing import List
3
+
4
+
5
+ class MoonshineConfig(PretrainedConfig):
6
+ model_type = "moonshine"
7
+
8
+ def __init__(
9
+ self,
10
+ dim: int = 288,
11
+ inner_dim: int = None,
12
+ enc_depth: int = 8,
13
+ dec_depth: int = 8,
14
+ n_head: int = 8,
15
+ dec_voc_size: int = 32768,
16
+ enc_ff_swiglu: bool = False,
17
+ dec_ff_swiglu: bool = True,
18
+ **kwargs
19
+ ):
20
+ if inner_dim is None:
21
+ inner_dim = dim
22
+ if inner_dim % n_head != 0:
23
+ raise ValueError("`inner dim` must be divisible by `n_head`")
24
+ self.dim = dim
25
+ self.inner_dim = inner_dim
26
+ self.enc_depth = enc_depth
27
+ self.dec_depth = dec_depth
28
+ self.n_head = n_head
29
+ self.dec_voc_size = dec_voc_size
30
+ self.enc_ff_swiglu = enc_ff_swiglu
31
+ self.dec_ff_swiglu = dec_ff_swiglu
32
+ super().__init__(**kwargs)
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2f46496c082ab898f5414e31bae398953aa205fb5fc614eb8be7f0d8d8ddd0aa
3
+ size 186049168
modeling_moonshine.py ADDED
@@ -0,0 +1,508 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from einops import rearrange
2
+ from einops.layers.torch import Rearrange
3
+ from torch import nn
4
+ import math
5
+ import torch
6
+
7
+
8
+ class RotaryEmbedding(nn.Module):
9
+ def __init__(self, dim, base=10000):
10
+ super().__init__()
11
+
12
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
13
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
14
+
15
+ def forward(self, t):
16
+ freqs = torch.einsum("i , j -> i j", t.type_as(self.inv_freq), self.inv_freq)
17
+ freqs = torch.stack((freqs, freqs), dim=-1)
18
+ return rearrange(freqs, "... d r -> ... (d r)")
19
+
20
+
21
+ def rotate_half(x):
22
+ x = rearrange(x, "... (d r) -> ... d r", r=2)
23
+ x1, x2 = x.unbind(dim=-1)
24
+ x = torch.stack((-x2, x1), dim=-1)
25
+ return rearrange(x, "... d r -> ... (d r)")
26
+
27
+
28
+ def apply_rotary_pos_emb(t, freqs):
29
+ rot_dim, seq_len, orig_dtype = freqs.shape[-1], t.shape[-2], t.dtype
30
+
31
+ freqs = freqs[-seq_len:, :]
32
+
33
+ # partial rotary embeddings, Wang et al. GPT-J
34
+ t, t_unrotated = t[..., :rot_dim], t[..., rot_dim:]
35
+ t = t * freqs.cos() + rotate_half(t) * freqs.sin()
36
+ out = torch.cat((t, t_unrotated), dim=-1)
37
+
38
+ return out.type(orig_dtype)
39
+
40
+
41
+ class MultiHeadAttention(nn.Module):
42
+ def __init__(self, dim, inner_dim, n_head):
43
+ super().__init__()
44
+ self.n_head = n_head
45
+ self.to_q = nn.Linear(dim, inner_dim, bias=False)
46
+ self.to_k = nn.Linear(dim, inner_dim, bias=False)
47
+ self.to_v = nn.Linear(dim, inner_dim, bias=False)
48
+ self.to_out = nn.Linear(inner_dim, dim, bias=False)
49
+ self.softmax = nn.Softmax(dim=-1)
50
+
51
+ # Scaled dot product attention
52
+ def sdp_attention(self, q, k_t, v, mask=None):
53
+ d_tensor = v.shape[3]
54
+
55
+ op = (q @ k_t) / math.sqrt(d_tensor)
56
+ if mask is not None:
57
+ op = op.masked_fill(mask, -torch.finfo(op.dtype).max)
58
+ score = self.softmax(op)
59
+ out = score @ v
60
+
61
+ # concat and pass to linear layer
62
+ out = rearrange(out, "b h n d -> b n (h d)")
63
+ return self.to_out(out)
64
+
65
+ def forward(self, q, k, v, rot_pos_emb=None, mask=None):
66
+ # dot product with weight matrices
67
+ q, k, v = self.to_q(q), self.to_k(k), self.to_v(v)
68
+
69
+ q = rearrange(q, "b n (h d) -> b h n d", h=self.n_head)
70
+ k = rearrange(k, "b n (h d) -> b h n d", h=self.n_head)
71
+ v = rearrange(v, "b n (h d) -> b h n d", h=self.n_head)
72
+
73
+ # apply RoPE
74
+ if rot_pos_emb is not None:
75
+ q = apply_rotary_pos_emb(q, rot_pos_emb)
76
+ k = apply_rotary_pos_emb(k, rot_pos_emb)
77
+
78
+ k_t = k.transpose(2, 3)
79
+
80
+ return self.sdp_attention(q, k_t, v, mask), k_t, v
81
+
82
+
83
+ class MultiHeadCausalSelfAttentionWithKVCache(MultiHeadAttention):
84
+ def __init__(self, dim, inner_dim, n_head):
85
+ super().__init__(dim, inner_dim, n_head)
86
+
87
+ def forward(self, q, k, v, k_cache, v_cache, rot_pos_emb, mask):
88
+ # dot product with weight matrices
89
+ q, k, v = self.to_q(q), self.to_k(k), self.to_v(v)
90
+
91
+ q = rearrange(q, "b n (h d) -> b h n d", h=self.n_head)
92
+ k = rearrange(k, "b n (h d) -> b h n d", h=self.n_head)
93
+ v = rearrange(v, "b n (h d) -> b h n d", h=self.n_head)
94
+
95
+ # apply RoPE
96
+ q = apply_rotary_pos_emb(q, rot_pos_emb)
97
+ k = apply_rotary_pos_emb(k, rot_pos_emb)
98
+
99
+ k_t = k.transpose(2, 3)
100
+
101
+ # Append new rows to K and V caches.
102
+ k_t = torch.concat((k_cache, k_t), dim=3)
103
+ v = torch.concat((v_cache, v), dim=2)
104
+
105
+ return super().sdp_attention(q, k_t, v, mask=mask), k_t, v
106
+
107
+
108
+ class MultiHeadCrossAttentionWithKVCache(MultiHeadAttention):
109
+ def __init__(self, dim, inner_dim, n_head):
110
+ super().__init__(dim, inner_dim, n_head)
111
+
112
+ def forward(self, q, k_cache, v_cache):
113
+ q = self.to_q(q)
114
+ q = rearrange(q, "b n (h d) -> b h n d", h=self.n_head)
115
+
116
+ return super().sdp_attention(q, k_cache, v_cache)
117
+
118
+
119
+ class FFLinearGelu(nn.Module):
120
+ def __init__(self, dim, ff_mult=4):
121
+ super().__init__()
122
+
123
+ self.ff = nn.Sequential(
124
+ nn.Linear(dim, dim * ff_mult, bias=True),
125
+ nn.GELU(),
126
+ nn.Linear(dim * ff_mult, dim, bias=True),
127
+ )
128
+
129
+ def forward(self, x):
130
+ return self.ff(x)
131
+
132
+
133
+ class FFSwiGLU(nn.Module):
134
+ def __init__(self, dim, ff_mult=4):
135
+ super().__init__()
136
+
137
+ self.ff_proj = nn.Linear(dim, dim * ff_mult, bias=True)
138
+ self.ff_noact = nn.Linear(dim, dim * ff_mult, bias=True)
139
+ self.ff_act = nn.SiLU()
140
+ self.ff_out = nn.Linear(dim * ff_mult, dim, bias=True)
141
+
142
+ def forward(self, x):
143
+ gate = self.ff_act(self.ff_proj(x))
144
+ x_noact = self.ff_noact(x)
145
+ x = x_noact * gate
146
+ return self.ff_out(x)
147
+
148
+
149
+ class EncoderLayer(nn.Module):
150
+ def __init__(self, dim, inner_dim, n_head, ff_swiglu, ff_mult=4):
151
+ super().__init__()
152
+
153
+ self.norm1 = nn.LayerNorm(dim, bias=False)
154
+
155
+ self.attention = MultiHeadAttention(dim, inner_dim=inner_dim, n_head=n_head)
156
+
157
+ self.norm2 = nn.LayerNorm(dim, bias=False)
158
+
159
+ self.ff = FFSwiGLU(dim, ff_mult) if ff_swiglu else FFLinearGelu(dim, ff_mult)
160
+
161
+ def forward(self, x, rot_pos_emb):
162
+ _x = x
163
+ x = self.norm1(x)
164
+ x, _, _ = self.attention(q=x, k=x, v=x, rot_pos_emb=rot_pos_emb)
165
+ x = x + _x
166
+
167
+ _x = x
168
+ x = self.norm2(x)
169
+ x = self.ff(x)
170
+
171
+ x = x + _x
172
+ return x
173
+
174
+
175
+ class Encoder(nn.Module):
176
+ def __init__(self, dim, inner_dim, n_head, n_layers, ff_swiglu):
177
+ super().__init__()
178
+ rot_embed_dim = max(inner_dim / n_head / 2, 32)
179
+ self.rot_pos_emb = RotaryEmbedding(rot_embed_dim)
180
+
181
+ self.layers = nn.ModuleList(
182
+ [EncoderLayer(dim, inner_dim, n_head, ff_swiglu) for _ in range(n_layers)]
183
+ )
184
+ self.post_norm = nn.LayerNorm(dim, bias=False)
185
+
186
+ def forward(self, x):
187
+ pos = torch.arange(x.shape[1], device=x.device)
188
+ rot_pos_emb = self.rot_pos_emb(pos)
189
+
190
+ for layer in self.layers:
191
+ x = layer(x, rot_pos_emb=rot_pos_emb)
192
+ return self.post_norm(x)
193
+
194
+
195
+ class DecoderLayer(nn.Module):
196
+ def __init__(self, dim, inner_dim, n_head, ff_swiglu, ff_mult=4):
197
+ super().__init__()
198
+
199
+ self.norm1 = nn.LayerNorm(dim, bias=False)
200
+
201
+ self.self_attention = MultiHeadCausalSelfAttentionWithKVCache(
202
+ dim, inner_dim=inner_dim, n_head=n_head
203
+ )
204
+
205
+ self.norm2 = nn.LayerNorm(dim, bias=False)
206
+ self.cross_attention = MultiHeadCrossAttentionWithKVCache(
207
+ dim, inner_dim=inner_dim, n_head=n_head
208
+ )
209
+
210
+ self.norm3 = nn.LayerNorm(dim, bias=False)
211
+ self.ff = FFSwiGLU(dim, ff_mult) if ff_swiglu else FFLinearGelu(dim, ff_mult)
212
+
213
+ def forward(self, x, k_cache, v_cache, x_attn_k_cache, x_attn_v_cache, rot_pos_emb):
214
+ dim = x.size()[1]
215
+ causal_mask = torch.ones((dim, dim), dtype=torch.bool).triu(1).to(x.device)
216
+ _x = x
217
+ x = self.norm1(x)
218
+ x, new_k_cache, new_v_cache = self.self_attention(
219
+ q=x,
220
+ k=x,
221
+ v=x,
222
+ k_cache=k_cache,
223
+ v_cache=v_cache,
224
+ rot_pos_emb=rot_pos_emb,
225
+ mask=causal_mask,
226
+ )
227
+ x = x + _x
228
+
229
+ _x = x
230
+ x = self.norm2(x)
231
+ x = self.cross_attention(q=x, k_cache=x_attn_k_cache, v_cache=x_attn_v_cache)
232
+ x = x + _x
233
+
234
+ _x = x
235
+ x = self.norm3(x)
236
+ x = self.ff(x)
237
+ x = x + _x
238
+
239
+ return x, new_k_cache, new_v_cache
240
+
241
+
242
+ class Decoder(nn.Module):
243
+ def __init__(self, dim, inner_dim, n_head, n_layers, dec_voc_size, ff_swiglu):
244
+ super().__init__()
245
+
246
+ self.n_head = n_head
247
+ self.d_head = inner_dim // n_head
248
+
249
+ rot_embed_dim = max(inner_dim / n_head / 2, 32)
250
+ self.rot_pos_emb = RotaryEmbedding(rot_embed_dim)
251
+
252
+ self.layers = nn.ModuleList(
253
+ [DecoderLayer(dim, inner_dim, n_head, ff_swiglu) for _ in range(n_layers)]
254
+ )
255
+ self.final_norm = nn.LayerNorm(dim, bias=False)
256
+ self.token_embedding = nn.Embedding(dec_voc_size, dim)
257
+
258
+ def forward(self, x, *args):
259
+ pos = torch.arange(x.shape[1], device=x.device)
260
+ rot_pos_emb = self.rot_pos_emb(pos)
261
+ x = self.token_embedding(x)
262
+
263
+ k_cache_new = []
264
+ v_cache_new = []
265
+
266
+ n_layer = len(self.layers)
267
+ k_cache, v_cache, x_attn_k_cache, x_attn_v_cache = [
268
+ args[i : i + n_layer] for i in range(0, 4 * n_layer, n_layer)
269
+ ]
270
+ for idx, layer in enumerate(self.layers):
271
+ x, new_k_line, new_v_line = layer(
272
+ x[:, -1:],
273
+ k_cache=k_cache[idx],
274
+ v_cache=v_cache[idx],
275
+ x_attn_k_cache=x_attn_k_cache[idx],
276
+ x_attn_v_cache=x_attn_v_cache[idx],
277
+ rot_pos_emb=rot_pos_emb,
278
+ )
279
+ k_cache_new.append(new_k_line)
280
+ v_cache_new.append(new_v_line)
281
+
282
+ x = self.final_norm(x)
283
+
284
+ return x @ self.token_embedding.weight.t(), *k_cache_new, *v_cache_new
285
+
286
+
287
+ class InitialDecoderLayer(nn.Module):
288
+ def __init__(self, dim, inner_dim, n_head, ff_swiglu, ff_mult=4):
289
+ super().__init__()
290
+
291
+ self.norm1 = nn.LayerNorm(dim, bias=False)
292
+
293
+ self.self_attention = MultiHeadAttention(
294
+ dim, inner_dim=inner_dim, n_head=n_head
295
+ )
296
+
297
+ self.norm2 = nn.LayerNorm(dim, bias=False)
298
+ self.cross_attention = MultiHeadAttention(
299
+ dim, inner_dim=inner_dim, n_head=n_head
300
+ )
301
+
302
+ self.norm3 = nn.LayerNorm(dim, bias=False)
303
+ self.ff = FFSwiGLU(dim, ff_mult) if ff_swiglu else FFLinearGelu(dim, ff_mult)
304
+
305
+ def forward(self, x, context, rot_pos_emb):
306
+ dim = x.size()[1]
307
+ causal_mask = torch.ones((dim, dim), dtype=torch.bool).triu(1).to(x.device)
308
+ _x = x
309
+ x = self.norm1(x)
310
+ x, new_k_cache, new_v_cache = self.self_attention(
311
+ q=x,
312
+ k=x,
313
+ v=x,
314
+ rot_pos_emb=rot_pos_emb,
315
+ mask=causal_mask,
316
+ )
317
+ x = x + _x
318
+
319
+ _x = x
320
+ x = self.norm2(x)
321
+ x, x_attn_k_cache, x_attn_v_cache = self.cross_attention(
322
+ q=x, k=context, v=context
323
+ )
324
+ x = x + _x
325
+
326
+ _x = x
327
+ x = self.norm3(x)
328
+ x = self.ff(x)
329
+ x = x + _x
330
+
331
+ return x, new_k_cache, new_v_cache, x_attn_k_cache, x_attn_v_cache
332
+
333
+
334
+ class DecoderInitial(Decoder):
335
+ def __init__(self, dim, inner_dim, n_head, n_layers, dec_voc_size, ff_swiglu):
336
+ super().__init__(dim, inner_dim, n_head, n_layers, dec_voc_size, ff_swiglu)
337
+ self.layers = nn.ModuleList(
338
+ [
339
+ InitialDecoderLayer(dim, inner_dim, n_head, ff_swiglu)
340
+ for _ in range(n_layers)
341
+ ]
342
+ )
343
+
344
+ def forward(self, x, enc_src):
345
+ pos = torch.arange(x.shape[1], device=x.device)
346
+ rot_pos_emb = self.rot_pos_emb(pos)
347
+ x = self.token_embedding(x)
348
+
349
+ # Shape [n_layers, batch_size, n_head, seq_len, inner_dim]. Cache K transposed.
350
+ n_layer = len(self.layers)
351
+ k_cache = []
352
+ v_cache = []
353
+ x_attn_k_cache = []
354
+ x_attn_v_cache = []
355
+
356
+ for idx, layer in enumerate(self.layers):
357
+ x, new_k_line, new_v_line, new_x_attn_k_line, new_x_attn_v_line = layer(
358
+ x,
359
+ enc_src,
360
+ rot_pos_emb,
361
+ )
362
+
363
+ k_cache.append(new_k_line)
364
+ v_cache.append(new_v_line)
365
+ x_attn_k_cache.append(new_x_attn_k_line)
366
+ x_attn_v_cache.append(new_x_attn_v_line)
367
+
368
+ x = self.final_norm(x)
369
+
370
+ return (
371
+ x @ self.token_embedding.weight.t(),
372
+ *k_cache,
373
+ *v_cache,
374
+ *x_attn_k_cache,
375
+ *x_attn_v_cache,
376
+ )
377
+
378
+
379
+ class AudioPreprocessor(nn.Module):
380
+ def __init__(self, dim):
381
+ super().__init__()
382
+ self.audio_preprocess = nn.Sequential(
383
+ nn.Conv1d(1, dim, 127, 64, bias=False),
384
+ nn.Tanh(),
385
+ nn.GroupNorm(1, dim),
386
+ nn.Conv1d(dim, 2 * dim, 7, 3),
387
+ nn.GELU(),
388
+ nn.Conv1d(2 * dim, dim, 3, 2),
389
+ nn.GELU(),
390
+ Rearrange("... c s -> ... s c"),
391
+ )
392
+
393
+ def forward(self, src):
394
+ assert (
395
+ src.shape[-1] >= 1023
396
+ ), f"src shape[-1] {src.shape[-1]} should be at least 1023"
397
+ src = src.unsqueeze(-2)
398
+ return self.audio_preprocess(src)
399
+
400
+
401
+ class MoonshineModelTorch(nn.Module):
402
+ def __init__(
403
+ self,
404
+ dim,
405
+ inner_dim,
406
+ enc_depth,
407
+ dec_depth,
408
+ n_head=8,
409
+ dec_voc_size=32768,
410
+ enc_ff_swiglu=False,
411
+ dec_ff_swiglu=False,
412
+ ):
413
+ super().__init__()
414
+ self.preprocessor = AudioPreprocessor(dim)
415
+ self.encoder = Encoder(
416
+ dim, inner_dim, n_head, enc_depth, ff_swiglu=enc_ff_swiglu
417
+ )
418
+ self.decoder_initial = DecoderInitial(
419
+ dim, inner_dim, n_head, dec_depth, dec_voc_size, ff_swiglu=dec_ff_swiglu
420
+ )
421
+ self.decoder = Decoder(
422
+ dim, inner_dim, n_head, dec_depth, dec_voc_size, ff_swiglu=dec_ff_swiglu
423
+ )
424
+ self.dec_depth = dec_depth
425
+ self.n_head = n_head
426
+ self.d_head = inner_dim // n_head
427
+
428
+ def generate(self, src):
429
+ start = time.time()
430
+ preprocessed = self.preprocessor(src)
431
+ start = time.time()
432
+ enc = self.encoder(preprocessed)
433
+ start = time.time()
434
+ sot_token = 1
435
+ eot_token = 2
436
+
437
+ seq = torch.as_tensor([[sot_token]]).to(src.device)
438
+
439
+ vals = self.decoder_initial(x=seq, enc_src=enc)
440
+ logits = vals[0]
441
+ k_cache, v_cache, x_attn_k_cache, x_attn_v_cache = [
442
+ vals[i : i + self.dec_depth]
443
+ for i in range(1, 1 + self.dec_depth * 4, self.dec_depth)
444
+ ]
445
+
446
+ start = time.time()
447
+
448
+ sample = logits[:, -1].argmax(dim=-1, keepdim=True)
449
+ seq = torch.cat((seq, sample), dim=-1)
450
+
451
+ seq_len = int(src.shape[-1] * 6 / 16000)
452
+ while sample != eot_token and len(seq.flatten()) <= seq_len:
453
+ vals = self.decoder(
454
+ seq,
455
+ *k_cache,
456
+ *v_cache,
457
+ *x_attn_k_cache,
458
+ *x_attn_v_cache,
459
+ )
460
+ logits = vals[0]
461
+ k_cache = vals[1 : self.dec_depth + 1]
462
+ v_cache = vals[self.dec_depth + 1 :]
463
+ logits = logits[:, -1] # get last token
464
+ sample = logits.argmax(dim=-1, keepdim=True)
465
+ seq = torch.cat((seq, sample), dim=-1)
466
+
467
+ return seq
468
+
469
+ from transformers import PreTrainedModel
470
+ from configuration_moonshine import MoonshineConfig
471
+
472
+ class MoonshineModel(PreTrainedModel):
473
+ config_class = MoonshineConfig
474
+
475
+ def __init__(self, config):
476
+ super().__init__(config)
477
+ self.model = MoonshineModelTorch(
478
+ dim = config.dim,
479
+ inner_dim = config.inner_dim,
480
+ enc_depth = config.enc_depth,
481
+ dec_depth = config.dec_depth,
482
+ n_head = config.n_head,
483
+ dec_voc_size = config.dec_voc_size,
484
+ enc_ff_swiglu = config.enc_ff_swiglu,
485
+ dec_ff_swiglu = config.dec_ff_swiglu,
486
+ )
487
+
488
+ def forward(self, tensor):
489
+ return self.model.generate(tensor)
490
+
491
+ class MoonshineForConditionalGeneration(PreTrainedModel):
492
+ config_class = MoonshineConfig
493
+
494
+ def __init__(self, config):
495
+ super().__init__(config)
496
+ self.model = MoonshineModelTorch(
497
+ dim = config.dim,
498
+ inner_dim = config.inner_dim,
499
+ enc_depth = config.enc_depth,
500
+ dec_depth = config.dec_depth,
501
+ n_head = config.n_head,
502
+ dec_voc_size = config.dec_voc_size,
503
+ enc_ff_swiglu = config.enc_ff_swiglu,
504
+ dec_ff_swiglu = config.dec_ff_swiglu,
505
+ )
506
+
507
+ def forward(self, tensor):
508
+ return self.model.generate(tensor)