N8Programs commited on
Commit
e8df098
·
verified ·
1 Parent(s): 4e10ccc

Upload ProGen2 base BF16 MLX conversion

Browse files
README.md ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: bsd-3-clause
3
+ library_name: mlx
4
+ pipeline_tag: text-generation
5
+ base_model: hugohrban/progen2-base
6
+ tags:
7
+ - progen
8
+ - progen2
9
+ - protein-language-model
10
+ - mlx
11
+ - mlx-lm
12
+ - safetensors
13
+ - bfloat16
14
+ - icl-many-replication
15
+ ---
16
+
17
+ # ProGen2 Base BF16 MLX Conversion
18
+
19
+ This repository contains a BF16 MLX-LM conversion of
20
+ [`hugohrban/progen2-base`](https://huggingface.co/hugohrban/progen2-base), a
21
+ mirror of the base ProGen2 model by Nijkamp et al.
22
+
23
+ The source checkpoint was downloaded from Hugging Face revision
24
+ `71228cbfca5960f9fab5775f378bba3673af9f00` and converted from FP32 to BF16
25
+ safetensors. The converted tensor file contains 764,803,616 BF16 parameters.
26
+
27
+ This conversion was prepared for the standalone replication artifact for
28
+ *Many Next Token Predictors are In-context Learners*.
29
+
30
+ ## Files
31
+
32
+ - `model.safetensors`: BF16 converted ProGen2-base weights.
33
+ - `progen2_mlx.py`: MLX-LM custom model implementation.
34
+ - `config.json`, tokenizer files, and ProGen custom-code files copied from the
35
+ source model with the MLX model-file entry added.
36
+
37
+ ## Loading with MLX-LM
38
+
39
+ ```python
40
+ from mlx_lm import load
41
+
42
+ model, tokenizer = load("N8Programs/ProGen2-base-bf16")
43
+ ```
44
+
45
+ ## Original Model
46
+
47
+ Please cite and follow the terms of the upstream ProGen2 work and the source
48
+ model repository:
49
+
50
+ - Source model: https://huggingface.co/hugohrban/progen2-base
51
+ - Paper: https://arxiv.org/abs/2206.13517
config.json ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "hugohrban/progen2-base",
3
+ "activation_function": "gelu_new",
4
+ "architectures": [
5
+ "ProGenForCausalLM"
6
+ ],
7
+ "attn_pdrop": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_progen.ProGenConfig",
10
+ "AutoModelForCausalLM": "modeling_progen.ProGenForCausalLM"
11
+ },
12
+ "bos_token_id": 1,
13
+ "embd_pdrop": 0.0,
14
+ "embed_dim": 1536,
15
+ "eos_token_id": 2,
16
+ "gradient_checkpointing": false,
17
+ "initializer_range": 0.02,
18
+ "layer_norm_epsilon": 1e-05,
19
+ "model_type": "progen",
20
+ "n_head": 16,
21
+ "n_inner": null,
22
+ "n_layer": 27,
23
+ "n_positions": 2048,
24
+ "resid_pdrop": 0.0,
25
+ "rotary_dim": 48,
26
+ "scale_attn_weights": true,
27
+ "summary_activation": null,
28
+ "summary_first_dropout": 0.1,
29
+ "summary_proj_to_labels": true,
30
+ "summary_type": "cls_index",
31
+ "summary_use_proj": true,
32
+ "task_specific_params": {
33
+ "text-generation": {
34
+ "do_sample": true,
35
+ "max_length": 50,
36
+ "temperature": 1.0
37
+ }
38
+ },
39
+ "tokenizer_class": "GPT2Tokenizer",
40
+ "torch_dtype": "bfloat16",
41
+ "transformers_version": "4.40.0",
42
+ "use_cache": true,
43
+ "vocab_size": 32,
44
+ "vocab_size_emb": 32,
45
+ "vocab_size_lm_head": 32,
46
+ "model_file": "progen2_mlx.py",
47
+ "dtype": "bfloat16",
48
+ "pad_token_id": 0
49
+ }
configuration_progen.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The EleutherAI and HuggingFace Teams. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ # Modified configuration implementation based on https://github.com/huggingface/transformers/blob/main/src/transformers/models/gptj/configuration_gptj.py
17
+
18
+ from transformers.configuration_utils import PretrainedConfig
19
+ from transformers.utils import logging
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class ProGenConfig(PretrainedConfig):
25
+ model_type = "progen"
26
+
27
+ def __init__(
28
+ self,
29
+ vocab_size_emb=32,
30
+ vocab_size_lm_head=32,
31
+ n_positions=1024,
32
+ embed_dim=1024,
33
+ n_layer=12,
34
+ n_head=16,
35
+ rotary_dim=32,
36
+ n_inner=None,
37
+ activation_function="gelu_new",
38
+ resid_pdrop=0.0,
39
+ embd_pdrop=0.0,
40
+ attn_pdrop=0.0,
41
+ layer_norm_epsilon=1e-5,
42
+ initializer_range=0.02,
43
+ scale_attn_weights=True,
44
+ gradient_checkpointing=False,
45
+ use_cache=True,
46
+ bos_token_id=1,
47
+ eos_token_id=2,
48
+ **kwargs
49
+ ):
50
+ super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
51
+
52
+ self.vocab_size_emb = vocab_size_emb # input vocab size
53
+ self.vocab_size_lm_head = vocab_size_lm_head # output vocab size
54
+ self.n_positions = n_positions # context window size
55
+ self.embed_dim = embed_dim
56
+ self.n_layer = n_layer
57
+ self.n_head = n_head
58
+ self.n_inner = n_inner # inner dimension of the MLP
59
+ self.rotary_dim = rotary_dim
60
+ self.activation_function = activation_function
61
+ self.resid_pdrop = resid_pdrop
62
+ self.embd_pdrop = embd_pdrop
63
+ self.attn_pdrop = attn_pdrop
64
+ self.layer_norm_epsilon = layer_norm_epsilon
65
+ self.initializer_range = initializer_range
66
+ self.gradient_checkpointing = gradient_checkpointing
67
+ self.scale_attn_weights = scale_attn_weights
68
+ self.use_cache = use_cache
69
+
70
+ self.bos_token_id = bos_token_id
71
+ self.eos_token_id = eos_token_id
72
+
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "transformers_version": "4.40.0"
6
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bc2ee1fe37ec29e2371b37ba9f06ab468cce7e30d6d8b3eb0b99a9fee8d23ccb
3
+ size 1529630800
modeling_progen.py ADDED
@@ -0,0 +1,654 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The EleutherAI and HuggingFace Teams. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License atí
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ # Modified forward-pass implementation based on https://github.com/huggingface/transformers/blob/main/src/transformers/models/gptj/modeling_gptj.py
17
+
18
+ from typing import Tuple
19
+
20
+ import numpy as np
21
+
22
+ import torch
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+ from torch.nn import CrossEntropyLoss
26
+ import torch.nn.functional as F
27
+
28
+ from transformers.activations import ACT2FN
29
+ from transformers.modeling_outputs import (
30
+ BaseModelOutputWithPast,
31
+ CausalLMOutputWithPast,
32
+ )
33
+ from transformers.modeling_utils import PreTrainedModel
34
+ from transformers.utils import logging
35
+ from .configuration_progen import ProGenConfig
36
+
37
+
38
+ logger = logging.get_logger(__name__)
39
+
40
+
41
+ def fixed_pos_embedding(x, seq_dim=1, seq_len=None):
42
+ dim = x.shape[-1]
43
+ if seq_len is None:
44
+ seq_len = x.shape[seq_dim]
45
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2) / dim))
46
+ sinusoid_inp = (
47
+ torch.einsum("i , j -> i j", torch.arange(seq_len), inv_freq)
48
+ .to(x.device)
49
+ .float()
50
+ )
51
+ return torch.sin(sinusoid_inp), torch.cos(sinusoid_inp)
52
+
53
+
54
+ def rotate_every_two(x: torch.Tensor):
55
+ x1 = x[:, :, :, ::2]
56
+ x2 = x[:, :, :, 1::2]
57
+ x = torch.stack((-x2, x1), axis=-1)
58
+ return x.flatten(-2)
59
+
60
+ def apply_rotary_pos_emb(x, sincos, offset=0):
61
+ sin, cos = map(
62
+ lambda t: t[None, offset : x.shape[1] + offset, None, :].repeat_interleave(
63
+ 2, 3
64
+ ),
65
+ sincos,
66
+ )
67
+ # einsum notation for lambda t: repeat(t[offset:x.shape[1]+offset,:], "n d -> () n () (d j)", j=2)
68
+ return (x * cos) + (rotate_every_two(x) * sin)
69
+
70
+
71
+ class ProGenAttention(nn.Module):
72
+ def __init__(self, config):
73
+ super().__init__()
74
+
75
+ max_positions = config.n_positions
76
+ self.register_buffer(
77
+ "bias",
78
+ torch.tril(
79
+ torch.ones((max_positions, max_positions), dtype=torch.bool)
80
+ ).view(1, 1, max_positions, max_positions),
81
+ persistent=False
82
+ )
83
+ self.register_buffer("masked_bias", torch.tensor(-1e9), persistent=False) # approx. -inf
84
+
85
+ self.attn_dropout = nn.Dropout(config.attn_pdrop)
86
+ self.resid_dropout = nn.Dropout(config.resid_pdrop)
87
+
88
+ self.embed_dim = config.embed_dim
89
+ self.num_attention_heads = config.n_head
90
+ self.head_dim = self.embed_dim // self.num_attention_heads
91
+ if self.head_dim * self.num_attention_heads != self.embed_dim:
92
+ raise ValueError(
93
+ f"embed_dim must be divisible by num_attention_heads (got `embed_dim`: {self.embed_dim} and `num_attention_heads`: {self.num_attention_heads})."
94
+ )
95
+ self.scale_attn = torch.sqrt(
96
+ torch.tensor(self.head_dim, dtype=torch.float32)
97
+ ).to(torch.get_default_dtype())
98
+ self.qkv_proj = nn.Linear(self.embed_dim, self.embed_dim * 3, bias=False)
99
+
100
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
101
+ self.rotary_dim = None
102
+ if config.rotary_dim is not None:
103
+ self.rotary_dim = config.rotary_dim
104
+
105
+ def _split_heads(self, x: torch.Tensor, n_head, dim_head) -> torch.Tensor:
106
+ x = x.reshape(x.shape[:-2] + (-1,)) # (B, T, 8 * E // 8)
107
+ x = x.reshape(x.shape[:-1] + (n_head, dim_head)) # (B, T, n_heads, dim_head)
108
+ return x
109
+
110
+ def _merge_heads(self, tensor, num_attention_heads, attn_head_size) -> torch.Tensor:
111
+ """
112
+ Merges attn_head_size dim and num_attn_heads dim into n_positions
113
+ """
114
+ if len(tensor.shape) == 5:
115
+ tensor = tensor.permute(0, 1, 3, 2, 4).contiguous()
116
+ elif len(tensor.shape) == 4:
117
+ tensor = tensor.permute(0, 2, 1, 3).contiguous()
118
+ else:
119
+ raise ValueError(
120
+ f"Input tensor rank should be one of [4, 5], but is: {len(tensor.shape)}"
121
+ )
122
+ new_shape = tensor.size()[:-2] + (num_attention_heads * attn_head_size,)
123
+ return tensor.view(new_shape)
124
+
125
+ def _attn(
126
+ self,
127
+ query,
128
+ key,
129
+ value,
130
+ attention_mask=None,
131
+ head_mask=None,
132
+ ):
133
+ # compute causal mask from causal mask buffer
134
+ query_length, key_length = query.size(-2), key.size(-2)
135
+ causal_mask = self.bias[
136
+ :, :, key_length - query_length : key_length, :key_length
137
+ ]
138
+
139
+ # Keep the attention weights computation in fp32 to avoid overflow issues
140
+ query = query.to(torch.float32)
141
+ key = key.to(torch.float32)
142
+
143
+ attn_weights = query @ key.transpose(-1, -2) # (B, n_heads, T, T)
144
+
145
+ attn_weights = attn_weights / self.scale_attn
146
+
147
+ # attend only to previous positions
148
+ attn_weights = torch.where(
149
+ causal_mask, attn_weights, self.masked_bias.to(attn_weights.dtype)
150
+ )
151
+
152
+ if attention_mask is not None:
153
+ attn_weights = attn_weights + attention_mask
154
+
155
+ attn_weights = F.softmax(attn_weights, dim=-1)
156
+ attn_weights = attn_weights.to(value.dtype)
157
+ attn_weights = self.attn_dropout(attn_weights)
158
+
159
+ if head_mask is not None:
160
+ attn_weights = attn_weights * head_mask
161
+
162
+ attn_output = attn_weights @ value # (B, n_heads, T, dim_head)
163
+
164
+ return attn_output, attn_weights
165
+
166
+ def forward(
167
+ self,
168
+ hidden_states,
169
+ attention_mask=None,
170
+ layer_past=None,
171
+ head_mask=None,
172
+ use_cache=False,
173
+ output_attentions=False,
174
+ ):
175
+ qkv = self.qkv_proj(hidden_states) # (B, T, 3 * E)
176
+
177
+ mp_num = 8
178
+ qkv_split = qkv.reshape(qkv.shape[:-1] + (mp_num, -1)) # (B, T, 8, 3 * E // 8)
179
+
180
+ query, value, key = torch.split(qkv_split, self.embed_dim // mp_num, dim=-1) # 3 * (B, T, 8, E // 8)
181
+
182
+ query = self._split_heads(query, self.num_attention_heads, self.head_dim) # (B, T, n_heads, dim_head)
183
+ key = self._split_heads(key, self.num_attention_heads, self.head_dim) # (B, T, n_heads, dim_head)
184
+ value = self._split_heads(value, self.num_attention_heads, self.head_dim) # (B, T, n_heads, dim_head)
185
+ value = value.permute(0, 2, 1, 3)
186
+
187
+ seq_len = key.shape[1]
188
+ offset = 0
189
+
190
+ if layer_past is not None:
191
+ offset = layer_past[0].shape[-2]
192
+ seq_len += offset
193
+
194
+ if self.rotary_dim is not None:
195
+ k_rot = key[:, :, :, : self.rotary_dim]
196
+ k_pass = key[:, :, :, self.rotary_dim :]
197
+
198
+ q_rot = query[:, :, :, : self.rotary_dim]
199
+ q_pass = query[:, :, :, self.rotary_dim :]
200
+
201
+ sincos = fixed_pos_embedding(k_rot, 1, seq_len=seq_len)
202
+ k_rot = apply_rotary_pos_emb(k_rot, sincos, offset=offset)
203
+ q_rot = apply_rotary_pos_emb(q_rot, sincos, offset=offset)
204
+
205
+ key = torch.cat([k_rot, k_pass], dim=-1)
206
+ query = torch.cat([q_rot, q_pass], dim=-1)
207
+ else:
208
+ sincos = fixed_pos_embedding(key, 1, seq_len=seq_len)
209
+ key = apply_rotary_pos_emb(key, sincos, offset=offset)
210
+ query = apply_rotary_pos_emb(query, sincos, offset=offset)
211
+
212
+ key = key.permute(0, 2, 1, 3)
213
+ query = query.permute(0, 2, 1, 3)
214
+
215
+ if layer_past is not None:
216
+ past_key = layer_past[0]
217
+ past_value = layer_past[1]
218
+ key = torch.cat((past_key, key), dim=-2)
219
+ value = torch.cat((past_value, value), dim=-2)
220
+
221
+ if use_cache is True:
222
+ present = (key, value)
223
+ else:
224
+ present = None
225
+
226
+ # compute self-attention: softmax((Q @ K.T) / sqrt(dim_head)) @ V
227
+ attn_output, attn_weights = self._attn(
228
+ query, key, value, attention_mask, head_mask
229
+ )
230
+
231
+ attn_output = self._merge_heads( # (B, T, E)
232
+ attn_output, self.num_attention_heads, self.head_dim
233
+ )
234
+
235
+ attn_output = self.out_proj(attn_output)
236
+ attn_output = self.resid_dropout(attn_output)
237
+
238
+ outputs = (attn_output, present)
239
+ if output_attentions:
240
+ outputs += (attn_weights,)
241
+
242
+ return outputs # a, present, (attentions)
243
+
244
+
245
+ class ProGenMLP(nn.Module):
246
+ def __init__(
247
+ self, intermediate_size, config
248
+ ): # in MLP: intermediate_size= 4 * embed_dim
249
+ super().__init__()
250
+ embed_dim = config.embed_dim
251
+
252
+ self.fc_in = nn.Linear(embed_dim, intermediate_size)
253
+ self.fc_out = nn.Linear(intermediate_size, embed_dim)
254
+
255
+ self.act = ACT2FN[config.activation_function]
256
+ self.dropout = nn.Dropout(config.resid_pdrop)
257
+
258
+ def forward(self, hidden_states):
259
+ hidden_states = self.fc_in(hidden_states)
260
+ hidden_states = self.act(hidden_states)
261
+ hidden_states = self.fc_out(hidden_states)
262
+ hidden_states = self.dropout(hidden_states)
263
+ return hidden_states
264
+
265
+
266
+ class ProGenBlock(nn.Module):
267
+ def __init__(self, config):
268
+ super().__init__()
269
+ inner_dim = config.n_inner if config.n_inner is not None else 4 * config.embed_dim
270
+ self.ln_1 = nn.LayerNorm(config.embed_dim, eps=config.layer_norm_epsilon)
271
+ self.attn = ProGenAttention(config)
272
+ self.mlp = ProGenMLP(inner_dim, config)
273
+
274
+ def forward(
275
+ self,
276
+ hidden_states,
277
+ layer_past=None,
278
+ attention_mask=None,
279
+ head_mask=None,
280
+ use_cache=False,
281
+ output_attentions=False,
282
+ ):
283
+ residual = hidden_states
284
+ hidden_states = self.ln_1(hidden_states)
285
+ attn_outputs = self.attn(
286
+ hidden_states,
287
+ layer_past=layer_past,
288
+ attention_mask=attention_mask,
289
+ head_mask=head_mask,
290
+ use_cache=use_cache,
291
+ output_attentions=output_attentions,
292
+ )
293
+ attn_output = attn_outputs[0] # output_attn: a, present, (attentions)
294
+ outputs = attn_outputs[1:]
295
+
296
+ feed_forward_hidden_states = self.mlp(hidden_states) # (B, T, E)
297
+ hidden_states = attn_output + feed_forward_hidden_states + residual
298
+
299
+ if use_cache:
300
+ outputs = (hidden_states,) + outputs
301
+ else:
302
+ outputs = (hidden_states,) + outputs[1:]
303
+
304
+ return outputs # hidden_states, present, (attentions)
305
+
306
+
307
+ class ProGenPreTrainedModel(PreTrainedModel):
308
+ """
309
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
310
+ models.
311
+ """
312
+
313
+ config_class = ProGenConfig
314
+ base_model_prefix = "transformer"
315
+ is_parallelizable = False
316
+
317
+ def __init__(self, *inputs, **kwargs):
318
+ super().__init__(*inputs, **kwargs)
319
+
320
+ def _init_weights(self, module):
321
+ """Initialize the weights."""
322
+ if isinstance(module, (nn.Linear,)):
323
+ # Slightly different from Mesh Transformer JAX which uses truncated_normal for initialization
324
+ # cf https://github.com/pytorch/pytorch/pull/5617
325
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
326
+ if module.bias is not None:
327
+ module.bias.data.zero_()
328
+ elif isinstance(module, nn.Embedding):
329
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
330
+ if module.padding_idx is not None:
331
+ module.weight.data[module.padding_idx].zero_()
332
+ elif isinstance(module, nn.LayerNorm):
333
+ module.bias.data.zero_()
334
+ module.weight.data.fill_(1.0)
335
+
336
+
337
+ class ProGenModel(ProGenPreTrainedModel):
338
+ def __init__(self, config):
339
+ super().__init__(config)
340
+ self.vocab_size_emb = config.vocab_size_emb
341
+ self.embed_dim = config.embed_dim
342
+ self.wte = nn.Embedding(config.vocab_size_emb, self.embed_dim)
343
+ self.drop = nn.Dropout(config.embd_pdrop)
344
+ self.h = nn.ModuleList([ProGenBlock(config) for _ in range(config.n_layer)])
345
+ self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
346
+ self.rotary_dim = min(
347
+ config.rotary_dim, config.n_positions // config.n_head
348
+ )
349
+ self.init_weights()
350
+
351
+ def forward(
352
+ self,
353
+ input_ids=None,
354
+ past_key_values=None,
355
+ attention_mask=None,
356
+ token_type_ids=None,
357
+ position_ids=None,
358
+ head_mask=None,
359
+ inputs_embeds=None,
360
+ use_cache=None,
361
+ output_attentions=None,
362
+ output_hidden_states=None,
363
+ return_dict=None,
364
+ ):
365
+ output_attentions = (
366
+ output_attentions
367
+ if output_attentions is not None
368
+ else self.config.output_attentions
369
+ )
370
+ output_hidden_states = (
371
+ output_hidden_states
372
+ if output_hidden_states is not None
373
+ else self.config.output_hidden_states
374
+ )
375
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
376
+ return_dict = (
377
+ return_dict if return_dict is not None else self.config.use_return_dict
378
+ )
379
+
380
+ if input_ids is not None and inputs_embeds is not None:
381
+ raise ValueError(
382
+ "You cannot specify both input_ids and inputs_embeds at the same time"
383
+ )
384
+ elif input_ids is not None:
385
+ input_shape = input_ids.size()
386
+ input_ids = input_ids.view(-1, input_shape[-1])
387
+ batch_size = input_ids.shape[0]
388
+ elif inputs_embeds is not None:
389
+ input_shape = inputs_embeds.size()[:-1]
390
+ batch_size = inputs_embeds.shape[0]
391
+ else:
392
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
393
+
394
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
395
+
396
+ if token_type_ids is not None:
397
+ token_type_ids = token_type_ids.view(-1, input_shape[-1])
398
+
399
+ if position_ids is not None:
400
+ position_ids = position_ids.view(-1, input_shape[-1])
401
+
402
+ if past_key_values is None:
403
+ past_length = 0
404
+ past_key_values = tuple([None] * len(self.h))
405
+ else:
406
+ past_length = past_key_values[0][0].size(-2)
407
+
408
+ if position_ids is None:
409
+ position_ids = torch.arange(
410
+ past_length,
411
+ input_shape[-1] + past_length,
412
+ dtype=torch.long,
413
+ device=device,
414
+ )
415
+ position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
416
+
417
+ # Attention mask.
418
+ if attention_mask is not None:
419
+ assert batch_size > 0, "batch_size has to be defined and > 0"
420
+ attention_mask = attention_mask.view(batch_size, -1)
421
+ # We create a 3D attention mask from a 2D tensor mask.
422
+ # Sizes are [batch_size, 1, 1, to_seq_length]
423
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
424
+ # this attention mask is more simple than the triangular masking of causal attention
425
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
426
+ attention_mask = attention_mask[:, None, None, :]
427
+
428
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
429
+ # masked positions, this operation will create a tensor which is 0.0 for
430
+ # positions we want to attend and -10000.0 for masked positions.
431
+ # Since we are adding it to the raw scores before the softmax, this is
432
+ # effectively the same as removing these entirely.
433
+ attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
434
+ attention_mask = (1.0 - attention_mask) * -10000.0
435
+
436
+ # Prepare head mask if needed
437
+ # 1.0 in head_mask indicate we keep the head
438
+ # attention_probs has shape bsz x num_attention_heads x N x N
439
+ # head_mask has shape n_layer x batch x num_attention_heads x N x N
440
+ head_mask = self.get_head_mask(head_mask, self.config.n_layer)
441
+
442
+ if inputs_embeds is None:
443
+ inputs_embeds = self.wte(input_ids)
444
+
445
+ hidden_states = inputs_embeds
446
+
447
+ if token_type_ids is not None:
448
+ token_type_embeds = self.wte(token_type_ids)
449
+ hidden_states = hidden_states + token_type_embeds
450
+
451
+ hidden_states = self.drop(hidden_states)
452
+
453
+ output_shape = input_shape + (hidden_states.size(-1),)
454
+
455
+ presents = () if use_cache else None
456
+ all_self_attentions = () if output_attentions else None
457
+ all_hidden_states = () if output_hidden_states else None
458
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
459
+ if output_hidden_states:
460
+ all_hidden_states = all_hidden_states + (hidden_states,)
461
+
462
+ if getattr(self.config, "gradient_checkpointing", False) and self.training:
463
+ if use_cache:
464
+ logger.warning(
465
+ "`use_cache=True` is incompatible with `config.gradient_checkpointing=True`. Setting "
466
+ "`use_cache=False`..."
467
+ )
468
+ use_cache = False
469
+
470
+ def create_custom_forward(module):
471
+ def custom_forward(*inputs):
472
+ # None for past_key_value
473
+ return module(*inputs, use_cache, output_attentions)
474
+
475
+ return custom_forward
476
+
477
+ outputs = torch.utils.checkpoint.checkpoint(
478
+ create_custom_forward(block),
479
+ hidden_states,
480
+ None,
481
+ attention_mask,
482
+ head_mask[i],
483
+ )
484
+ else:
485
+ outputs = block(
486
+ hidden_states,
487
+ layer_past=layer_past,
488
+ attention_mask=attention_mask,
489
+ head_mask=head_mask[i],
490
+ use_cache=use_cache,
491
+ output_attentions=output_attentions,
492
+ )
493
+
494
+ hidden_states = outputs[0]
495
+ if use_cache is True:
496
+ presents = presents + (outputs[1],)
497
+
498
+ if output_attentions:
499
+ all_self_attentions = all_self_attentions + (
500
+ outputs[2 if use_cache else 1],
501
+ )
502
+
503
+ hidden_states = self.ln_f(hidden_states)
504
+
505
+ hidden_states = hidden_states.view(*output_shape)
506
+ # Add last hidden state
507
+ if output_hidden_states:
508
+ all_hidden_states = all_hidden_states + (hidden_states,)
509
+
510
+ if not return_dict:
511
+ return tuple(
512
+ v
513
+ for v in [
514
+ hidden_states,
515
+ presents,
516
+ all_hidden_states,
517
+ all_self_attentions,
518
+ ]
519
+ if v is not None
520
+ )
521
+
522
+ return BaseModelOutputWithPast(
523
+ last_hidden_state=hidden_states,
524
+ past_key_values=presents,
525
+ hidden_states=all_hidden_states,
526
+ attentions=all_self_attentions,
527
+ )
528
+
529
+
530
+ class ProGenForCausalLM(ProGenPreTrainedModel):
531
+ _keys_to_ignore_on_load_missing = [
532
+ r"h\.\d+\.attn\.masked_bias",
533
+ r"h\.\d+\.attn\.bias",
534
+ r"lm_head\.weight",
535
+ ]
536
+
537
+ def __init__(self, config):
538
+ super().__init__(config)
539
+ self.transformer = ProGenModel(config)
540
+ self.lm_head = nn.Linear(config.embed_dim, config.vocab_size_lm_head)
541
+ self.init_weights()
542
+
543
+ def prepare_inputs_for_generation(self, input_ids, past=None, **kwargs):
544
+ token_type_ids = kwargs.get("token_type_ids", None)
545
+ # only last token for inputs_ids if past is defined in kwargs
546
+ if past:
547
+ input_ids = input_ids[:, -1].unsqueeze(-1)
548
+ if token_type_ids is not None:
549
+ token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
550
+
551
+ attention_mask = kwargs.get("attention_mask", None)
552
+ position_ids = kwargs.get("position_ids", None)
553
+
554
+ if attention_mask is not None and position_ids is None:
555
+ # create position_ids on the fly for batch generation
556
+ position_ids = attention_mask.long().cumsum(-1) - 1
557
+ position_ids.masked_fill_(attention_mask == 0, 1)
558
+ if past:
559
+ position_ids = position_ids[:, -1].unsqueeze(-1)
560
+ else:
561
+ position_ids = None
562
+ return {
563
+ "input_ids": input_ids,
564
+ "past_key_values": past,
565
+ "use_cache": kwargs.get("use_cache"),
566
+ "position_ids": position_ids,
567
+ "attention_mask": attention_mask,
568
+ "token_type_ids": token_type_ids,
569
+ }
570
+
571
+ def forward(
572
+ self,
573
+ input_ids=None,
574
+ past_key_values=None,
575
+ attention_mask=None,
576
+ token_type_ids=None,
577
+ position_ids=None,
578
+ head_mask=None,
579
+ inputs_embeds=None,
580
+ labels=None,
581
+ use_cache=None,
582
+ output_attentions=None,
583
+ output_hidden_states=None,
584
+ return_dict=None,
585
+ ):
586
+ r"""
587
+ labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
588
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
589
+ ``labels = input_ids`` Indices are selected in ``[-100, 0, ..., config.vocab_size]`` All labels set to
590
+ ``-100`` are ignored (masked), the loss is only computed for labels in ``[0, ..., config.vocab_size]``
591
+ """
592
+ return_dict = (
593
+ return_dict if return_dict is not None else self.config.use_return_dict
594
+ )
595
+
596
+ transformer_outputs = self.transformer(
597
+ input_ids,
598
+ past_key_values=past_key_values,
599
+ attention_mask=attention_mask,
600
+ token_type_ids=token_type_ids,
601
+ position_ids=position_ids,
602
+ head_mask=head_mask,
603
+ inputs_embeds=inputs_embeds,
604
+ use_cache=use_cache,
605
+ output_attentions=output_attentions,
606
+ output_hidden_states=output_hidden_states,
607
+ return_dict=return_dict,
608
+ )
609
+ hidden_states = transformer_outputs[0]
610
+
611
+ # make sure sampling in fp16 works correctly and
612
+ # compute loss in fp32 to match with mesh-tf version
613
+ # https://github.com/EleutherAI/gpt-neo/blob/89ce74164da2fb16179106f54e2269b5da8db333/models/gpt2/gpt2.py#L179
614
+ lm_logits = self.lm_head(hidden_states).to(torch.float32)
615
+
616
+ loss = None
617
+ if labels is not None:
618
+ # Shift so that tokens < n predict n
619
+ shift_logits = lm_logits[..., :-1, :].contiguous()
620
+ shift_labels = labels[..., 1:].contiguous()
621
+ loss_fct = CrossEntropyLoss()
622
+ loss = loss_fct(
623
+ shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)
624
+ )
625
+ loss = loss.to(hidden_states.dtype)
626
+
627
+ if not return_dict:
628
+ output = (lm_logits,) + transformer_outputs[1:]
629
+ return ((loss,) + output) if loss is not None else output
630
+
631
+ return CausalLMOutputWithPast(
632
+ loss=loss,
633
+ logits=lm_logits,
634
+ past_key_values=transformer_outputs.past_key_values,
635
+ hidden_states=transformer_outputs.hidden_states,
636
+ attentions=transformer_outputs.attentions,
637
+ )
638
+
639
+ @staticmethod
640
+ def _reorder_cache(
641
+ past: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
642
+ ) -> Tuple[Tuple[torch.Tensor]]:
643
+ """
644
+ This function is used to re-order the :obj:`past_key_values` cache if
645
+ :meth:`~transformers.PretrainedModel.beam_search` or :meth:`~transformers.PretrainedModel.beam_sample` is
646
+ called. This is required to match :obj:`past_key_values` with the correct beam_idx at every generation step.
647
+ """
648
+ return tuple(
649
+ tuple(
650
+ past_state.index_select(0, beam_idx.to(past_state.device))
651
+ for past_state in layer_past
652
+ )
653
+ for layer_past in past
654
+ )
progen2_mlx.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2026
2
+ """MLX-LM architecture for ProGen2 causal protein LMs."""
3
+
4
+ from dataclasses import dataclass
5
+ from typing import Any, Optional
6
+
7
+ import mlx.core as mx
8
+ import mlx.nn as nn
9
+
10
+ from mlx_lm.models.base import (
11
+ BaseModelArgs,
12
+ create_attention_mask,
13
+ scaled_dot_product_attention,
14
+ )
15
+
16
+
17
+ @dataclass
18
+ class ModelArgs(BaseModelArgs):
19
+ model_type: str
20
+ vocab_size_emb: int
21
+ vocab_size_lm_head: int
22
+ n_positions: int
23
+ embed_dim: int
24
+ n_layer: int
25
+ n_head: int
26
+ rotary_dim: int = 64
27
+ n_inner: Optional[int] = None
28
+ activation_function: str = "gelu_new"
29
+ layer_norm_epsilon: float = 1e-5
30
+ bos_token_id: int = 1
31
+ eos_token_id: int = 2
32
+ pad_token_id: int = 0
33
+
34
+
35
+ def gelu_new(x: mx.array) -> mx.array:
36
+ return 0.5 * x * (
37
+ 1.0
38
+ + mx.tanh(0.7978845608028654 * (x + 0.044715 * mx.power(x, 3)))
39
+ )
40
+
41
+
42
+ def rotate_every_two(x: mx.array) -> mx.array:
43
+ x1 = x[..., ::2]
44
+ x2 = x[..., 1::2]
45
+ stacked = mx.stack((-x2, x1), axis=-1)
46
+ return stacked.reshape(*x.shape)
47
+
48
+
49
+ class PartialRotaryEmbedding(nn.Module):
50
+ def __init__(self, rotary_dim: int):
51
+ super().__init__()
52
+ self.rotary_dim = rotary_dim
53
+ inv_freq = 1.0 / (
54
+ 10000
55
+ ** (mx.arange(0, rotary_dim, 2, dtype=mx.float32) / rotary_dim)
56
+ )
57
+ self.inv_freq = inv_freq
58
+
59
+ def __call__(self, x: mx.array, offset: int | mx.array = 0) -> mx.array:
60
+ seq_len = x.shape[-2]
61
+ offset = mx.array(offset, dtype=mx.float32)
62
+ positions = mx.arange(seq_len, dtype=mx.float32)
63
+
64
+ if offset.ndim == 0:
65
+ positions = positions + offset
66
+ freqs = positions[:, None] * self.inv_freq[None, :]
67
+ emb = mx.repeat(freqs, 2, axis=-1)
68
+ cos = mx.cos(emb).astype(x.dtype).reshape(
69
+ 1,
70
+ 1,
71
+ seq_len,
72
+ self.rotary_dim,
73
+ )
74
+ sin = mx.sin(emb).astype(x.dtype).reshape(
75
+ 1,
76
+ 1,
77
+ seq_len,
78
+ self.rotary_dim,
79
+ )
80
+ else:
81
+ positions = positions[None, :] + offset[:, None]
82
+ freqs = positions[:, :, None] * self.inv_freq[None, None, :]
83
+ emb = mx.repeat(freqs, 2, axis=-1)
84
+ cos = mx.cos(emb).astype(x.dtype).reshape(
85
+ x.shape[0],
86
+ 1,
87
+ seq_len,
88
+ self.rotary_dim,
89
+ )
90
+ sin = mx.sin(emb).astype(x.dtype).reshape(
91
+ x.shape[0],
92
+ 1,
93
+ seq_len,
94
+ self.rotary_dim,
95
+ )
96
+
97
+ return (x * cos) + (rotate_every_two(x) * sin)
98
+
99
+
100
+ class ProGenAttention(nn.Module):
101
+ def __init__(self, args: ModelArgs):
102
+ super().__init__()
103
+ if args.embed_dim % args.n_head != 0:
104
+ raise ValueError("embed_dim must be divisible by n_head")
105
+ self.embed_dim = args.embed_dim
106
+ self.num_heads = args.n_head
107
+ self.head_dim = args.embed_dim // args.n_head
108
+ self.mp_num = 8
109
+ self.mp_part = args.embed_dim // self.mp_num
110
+ self.scale = self.head_dim**-0.5
111
+ self.rotary_dim = args.rotary_dim
112
+
113
+ self.qkv_proj = nn.Linear(args.embed_dim, args.embed_dim * 3, bias=False)
114
+ self.out_proj = nn.Linear(args.embed_dim, args.embed_dim, bias=False)
115
+ self.rotary = PartialRotaryEmbedding(self.rotary_dim)
116
+
117
+ def _split_heads_from_mp(self, x: mx.array) -> mx.array:
118
+ batch_size, seq_len = x.shape[:2]
119
+ x = x.reshape(batch_size, seq_len, self.embed_dim)
120
+ return x.reshape(
121
+ batch_size,
122
+ seq_len,
123
+ self.num_heads,
124
+ self.head_dim,
125
+ ).transpose(0, 2, 1, 3)
126
+
127
+ def _apply_partial_rotary(self, x: mx.array, offset: int | mx.array) -> mx.array:
128
+ x_rot = x[..., : self.rotary_dim]
129
+ x_pass = x[..., self.rotary_dim :]
130
+ return mx.concatenate([self.rotary(x_rot, offset=offset), x_pass], axis=-1)
131
+
132
+ def __call__(
133
+ self,
134
+ hidden_states: mx.array,
135
+ mask: Optional[Any] = None,
136
+ cache: Optional[Any] = None,
137
+ ) -> mx.array:
138
+ batch_size, seq_len, _ = hidden_states.shape
139
+ qkv = self.qkv_proj(hidden_states)
140
+ qkv = qkv.reshape(batch_size, seq_len, self.mp_num, -1)
141
+
142
+ query, value, key = mx.split(qkv, 3, axis=-1)
143
+ query = self._split_heads_from_mp(query)
144
+ key = self._split_heads_from_mp(key)
145
+ value = self._split_heads_from_mp(value)
146
+
147
+ offset = 0 if cache is None else cache.offset
148
+ query = self._apply_partial_rotary(query, offset=offset)
149
+ key = self._apply_partial_rotary(key, offset=offset)
150
+
151
+ if cache is not None:
152
+ key, value = cache.update_and_fetch(key, value)
153
+
154
+ attn_output = scaled_dot_product_attention(
155
+ query,
156
+ key,
157
+ value,
158
+ cache=cache,
159
+ scale=self.scale,
160
+ mask=mask,
161
+ )
162
+ attn_output = attn_output.transpose(0, 2, 1, 3).reshape(
163
+ batch_size,
164
+ seq_len,
165
+ self.embed_dim,
166
+ )
167
+ return self.out_proj(attn_output)
168
+
169
+
170
+ class ProGenMLP(nn.Module):
171
+ def __init__(self, args: ModelArgs):
172
+ super().__init__()
173
+ inner_dim = args.n_inner if args.n_inner is not None else 4 * args.embed_dim
174
+ self.fc_in = nn.Linear(args.embed_dim, inner_dim, bias=True)
175
+ self.fc_out = nn.Linear(inner_dim, args.embed_dim, bias=True)
176
+
177
+ def __call__(self, hidden_states: mx.array) -> mx.array:
178
+ return self.fc_out(gelu_new(self.fc_in(hidden_states)))
179
+
180
+
181
+ class ProGenBlock(nn.Module):
182
+ def __init__(self, args: ModelArgs):
183
+ super().__init__()
184
+ self.ln_1 = nn.LayerNorm(
185
+ args.embed_dim,
186
+ eps=args.layer_norm_epsilon,
187
+ affine=True,
188
+ bias=True,
189
+ )
190
+ self.attn = ProGenAttention(args)
191
+ self.mlp = ProGenMLP(args)
192
+
193
+ def __call__(
194
+ self,
195
+ hidden_states: mx.array,
196
+ mask: Optional[Any] = None,
197
+ cache: Optional[Any] = None,
198
+ ) -> mx.array:
199
+ residual = hidden_states
200
+ normed = self.ln_1(hidden_states)
201
+ attn_output = self.attn(normed, mask=mask, cache=cache)
202
+ mlp_output = self.mlp(normed)
203
+ return residual + attn_output + mlp_output
204
+
205
+
206
+ class ProGenModel(nn.Module):
207
+ def __init__(self, args: ModelArgs):
208
+ super().__init__()
209
+ self.wte = nn.Embedding(args.vocab_size_emb, args.embed_dim)
210
+ self.h = [ProGenBlock(args) for _ in range(args.n_layer)]
211
+ self.ln_f = nn.LayerNorm(
212
+ args.embed_dim,
213
+ eps=args.layer_norm_epsilon,
214
+ affine=True,
215
+ bias=True,
216
+ )
217
+
218
+ def __call__(self, inputs: mx.array, cache=None) -> mx.array:
219
+ hidden_states = self.wte(inputs)
220
+ if cache is None:
221
+ cache = [None] * len(self.h)
222
+ mask = create_attention_mask(hidden_states, cache[0])
223
+ for block, c in zip(self.h, cache):
224
+ hidden_states = block(hidden_states, mask=mask, cache=c)
225
+ return self.ln_f(hidden_states)
226
+
227
+
228
+ class Model(nn.Module):
229
+ def __init__(self, args: ModelArgs):
230
+ super().__init__()
231
+ self.args = args
232
+ self.model_type = args.model_type
233
+ self.transformer = ProGenModel(args)
234
+ self.lm_head = nn.Linear(args.embed_dim, args.vocab_size_lm_head, bias=True)
235
+
236
+ def __call__(self, inputs: mx.array, cache=None) -> mx.array:
237
+ return self.lm_head(self.transformer(inputs, cache=cache))
238
+
239
+ def sanitize(self, weights):
240
+ weights = dict(weights)
241
+ inv_freq = 1.0 / (
242
+ 10000
243
+ ** (
244
+ mx.arange(0, self.args.rotary_dim, 2, dtype=mx.float32)
245
+ / self.args.rotary_dim
246
+ )
247
+ )
248
+ for layer_idx in range(self.args.n_layer):
249
+ weights[f"transformer.h.{layer_idx}.attn.rotary.inv_freq"] = inv_freq
250
+ return weights
251
+
252
+ @property
253
+ def layers(self):
254
+ return self.transformer.h
special_tokens_map.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<|bos|>",
3
+ "eos_token": "<|eos|>",
4
+ "pad_token": "<|pad|>",
5
+ "unk_token": "<|eos|>"
6
+ }
tokenizer.json ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": "1.0",
3
+ "truncation": null,
4
+ "padding": null,
5
+ "added_tokens": [
6
+ {
7
+ "id": 0,
8
+ "special": true,
9
+ "content": "<|pad|>",
10
+ "single_word": false,
11
+ "lstrip": false,
12
+ "rstrip": false,
13
+ "normalized": false
14
+ },
15
+ {
16
+ "id": 1,
17
+ "special": true,
18
+ "content": "<|bos|>",
19
+ "single_word": false,
20
+ "lstrip": false,
21
+ "rstrip": false,
22
+ "normalized": false
23
+ },
24
+ {
25
+ "id": 2,
26
+ "special": true,
27
+ "content": "<|eos|>",
28
+ "single_word": false,
29
+ "lstrip": false,
30
+ "rstrip": false,
31
+ "normalized": false
32
+ }
33
+ ],
34
+ "normalizer": null,
35
+ "pre_tokenizer": {
36
+ "type": "ByteLevel",
37
+ "add_prefix_space": false,
38
+ "trim_offsets": true
39
+ },
40
+ "post_processor": {
41
+ "type": "ByteLevel",
42
+ "add_prefix_space": true,
43
+ "trim_offsets": true
44
+ },
45
+ "decoder": {
46
+ "type": "ByteLevel",
47
+ "add_prefix_space": true,
48
+ "trim_offsets": true
49
+ },
50
+ "model": {
51
+ "type": "BPE",
52
+ "dropout": null,
53
+ "unk_token": null,
54
+ "continuing_subword_prefix": null,
55
+ "end_of_word_suffix": null,
56
+ "fuse_unk": false,
57
+ "vocab": {
58
+ "<|pad|>": 0,
59
+ "<|bos|>": 1,
60
+ "<|eos|>": 2,
61
+ "1": 3,
62
+ "2": 4,
63
+ "A": 5,
64
+ "B": 6,
65
+ "C": 7,
66
+ "D": 8,
67
+ "E": 9,
68
+ "F": 10,
69
+ "G": 11,
70
+ "H": 12,
71
+ "I": 13,
72
+ "K": 14,
73
+ "L": 15,
74
+ "M": 16,
75
+ "N": 17,
76
+ "O": 18,
77
+ "P": 19,
78
+ "Q": 20,
79
+ "R": 21,
80
+ "S": 22,
81
+ "T": 23,
82
+ "U": 24,
83
+ "V": 25,
84
+ "W": 26,
85
+ "X": 27,
86
+ "Y": 28,
87
+ "Z": 29
88
+ },
89
+ "merges": []
90
+ }
91
+ }
tokenizer_config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<|bos|>",
3
+ "eos_token": "<|eos|>",
4
+ "pad_token": "<|pad|>",
5
+ "unk_token": "<|eos|>",
6
+ "model_max_length": 2048,
7
+ "add_prefix_space": false
8
+ }