Upload model
Browse files- config.json +26 -0
- config.py +43 -0
- language.py +169 -0
- pytorch_model.bin +3 -0
config.json
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"BigBrainLanguageModel"
|
4 |
+
],
|
5 |
+
"attention_probs_dropout_prob": 0.1,
|
6 |
+
"auto_map": {
|
7 |
+
"AutoConfig": "config.BigBrainConfig",
|
8 |
+
"AutoModel": "language.BigBrainLanguageModel"
|
9 |
+
},
|
10 |
+
"hidden_act": "gelu",
|
11 |
+
"hidden_dropout_probability": 0.1,
|
12 |
+
"hidden_size": 768,
|
13 |
+
"initializer_range": 0.02,
|
14 |
+
"intermediate_size": 3072,
|
15 |
+
"layer_norm_eps": 1e-06,
|
16 |
+
"max_position_embeddings": 512,
|
17 |
+
"model_type": "big-brain-lm",
|
18 |
+
"num_attention_heads": 12,
|
19 |
+
"num_hidden_layers": 12,
|
20 |
+
"rope_theta": 10000,
|
21 |
+
"sos_token_id": 0,
|
22 |
+
"torch_dtype": "float32",
|
23 |
+
"transformers_version": "4.31.0",
|
24 |
+
"unk_token_id": 3,
|
25 |
+
"vocab_size": 50265
|
26 |
+
}
|
config.py
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import PretrainedConfig
|
2 |
+
|
3 |
+
|
4 |
+
class BigBrainConfig(PretrainedConfig):
|
5 |
+
model_type = 'big-brain-lm'
|
6 |
+
|
7 |
+
def __init__(
|
8 |
+
self,
|
9 |
+
vocab_size=50265,
|
10 |
+
hidden_size=768,
|
11 |
+
num_hidden_layers=12,
|
12 |
+
num_attention_heads=12,
|
13 |
+
intermediate_size=3072,
|
14 |
+
hidden_act='gelu',
|
15 |
+
hidden_dropout_probability=0.1,
|
16 |
+
attention_probs_dropout_prob=0.1,
|
17 |
+
max_position_embeddings=512,
|
18 |
+
initializer_range=0.02,
|
19 |
+
layer_norm_eps=1e-6,
|
20 |
+
rope_theta=10000,
|
21 |
+
sos_token_id=0,
|
22 |
+
pad_token_id=1,
|
23 |
+
eos_token_id=2,
|
24 |
+
unk_token_id=3,
|
25 |
+
**kwargs
|
26 |
+
):
|
27 |
+
self.vocab_size = vocab_size
|
28 |
+
self.hidden_size = hidden_size
|
29 |
+
self.num_hidden_layers = num_hidden_layers
|
30 |
+
self.num_attention_heads = num_attention_heads
|
31 |
+
self.intermediate_size = intermediate_size
|
32 |
+
self.hidden_act = hidden_act
|
33 |
+
self.hidden_dropout_probability = hidden_dropout_probability
|
34 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
35 |
+
self.max_position_embeddings = max_position_embeddings
|
36 |
+
self.initializer_range = initializer_range
|
37 |
+
self.layer_norm_eps = layer_norm_eps
|
38 |
+
self.rope_theta = rope_theta
|
39 |
+
self.sos_token_id = sos_token_id
|
40 |
+
self.pad_token_id = pad_token_id
|
41 |
+
self.eos_token_id = eos_token_id
|
42 |
+
self.unk_token_id = unk_token_id
|
43 |
+
super().__init__(**kwargs)
|
language.py
ADDED
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
|
3 |
+
import torch
|
4 |
+
import torch.nn as nn
|
5 |
+
from torch.nn import functional as f
|
6 |
+
from transformers import PreTrainedModel
|
7 |
+
from transformers.activations import ACT2FN
|
8 |
+
|
9 |
+
from config import BigBrainConfig
|
10 |
+
|
11 |
+
|
12 |
+
def _make_casual_mask(size: int) -> torch.Tensor:
|
13 |
+
return torch.tril(torch.ones(size, size))
|
14 |
+
|
15 |
+
|
16 |
+
class RootMeanSquareNorm(nn.Module):
|
17 |
+
def __init__(self, hidden_size, eps=1e-6):
|
18 |
+
super().__init__()
|
19 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
20 |
+
self.variance_eps = eps
|
21 |
+
|
22 |
+
def forward(self, x: torch.Tensor):
|
23 |
+
variance = x.pow(2).mean(-1, keepdim=True)
|
24 |
+
x = x * torch.rsqrt(variance + self.variance_eps)
|
25 |
+
return self.weight * x
|
26 |
+
|
27 |
+
|
28 |
+
class MultiLayerPerceptron(nn.Module):
|
29 |
+
def __init__(self, config: BigBrainConfig):
|
30 |
+
super().__init__()
|
31 |
+
self.config = config
|
32 |
+
self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
|
33 |
+
self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
|
34 |
+
self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
|
35 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
36 |
+
|
37 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
38 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
39 |
+
|
40 |
+
|
41 |
+
class RotaryPositionalEmbedding(nn.Module):
|
42 |
+
def __init__(self, dim: int, base: int = 10000):
|
43 |
+
super().__init__()
|
44 |
+
self.dim = dim
|
45 |
+
self.base = base
|
46 |
+
self.cos = None
|
47 |
+
self.sin = None
|
48 |
+
|
49 |
+
def _build_cache(self, x: torch.Tensor):
|
50 |
+
if self.cos is not None and x.shape[0] <= self.cos.shape[0]:
|
51 |
+
return
|
52 |
+
|
53 |
+
seq_len = x.shape[0]
|
54 |
+
theta = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float() / self.dim)).to(x.device)
|
55 |
+
seq_idx = torch.arange(seq_len, device=x.device).float().to(x.device)
|
56 |
+
idx_theta = torch.einsum('a,b->ab', seq_idx, theta)
|
57 |
+
idx_theta = torch.cat([idx_theta, idx_theta], dim=1)
|
58 |
+
|
59 |
+
self.cos = idx_theta.cos()[:, None, None, :]
|
60 |
+
self.sin = idx_theta.sin()[:, None, None, :]
|
61 |
+
|
62 |
+
def _neg_half(self, x: torch.Tensor):
|
63 |
+
d_2 = self.dim // 2
|
64 |
+
return torch.cat([-x[:, :, :, d_2:], x[:, :, :, :d_2]], dim=-1)
|
65 |
+
|
66 |
+
def forward(self, x: torch.Tensor):
|
67 |
+
self._build_cache(x)
|
68 |
+
x_rope, x_pass = x[..., :self.dim], x[..., self.dim:]
|
69 |
+
neg_half_x = self._neg_half(x_rope)
|
70 |
+
x_rope = (x_rope * self.cos[:x.shape[0]]) + (neg_half_x * self.sin[:x.shape[0]])
|
71 |
+
return torch.cat((x_rope, x_pass), dim=-1)
|
72 |
+
|
73 |
+
|
74 |
+
class RotaryMultiHeadAttention(nn.Module):
|
75 |
+
def __init__(self, config: BigBrainConfig):
|
76 |
+
super().__init__()
|
77 |
+
self.config = config
|
78 |
+
self.hidden_size = config.hidden_size
|
79 |
+
self.num_heads = config.num_attention_heads
|
80 |
+
self.head_dim = config.hidden_size // config.num_attention_heads
|
81 |
+
|
82 |
+
if (self.head_dim * config.num_attention_heads) != config.hidden_size:
|
83 |
+
raise ValueError('num_embedd must be evenly divisible by num_heads')
|
84 |
+
|
85 |
+
self.q_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
|
86 |
+
self.k_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
|
87 |
+
self.v_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
|
88 |
+
self.o_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
|
89 |
+
self.rope_e = RotaryPositionalEmbedding(self.head_dim, config.rope_theta)
|
90 |
+
|
91 |
+
def _shape(self, tensor: torch.Tensor, batch_size: int, seq_len: int):
|
92 |
+
return tensor.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
93 |
+
|
94 |
+
def _reshape(self, tensor: torch.Tensor, batch_size: int, seq_len: int):
|
95 |
+
return tensor.transpose(1, 2).contiguous().reshape(batch_size, seq_len, self.hidden_size)
|
96 |
+
|
97 |
+
def forward(self, states: torch.Tensor, mask: torch.Tensor = None) -> torch.Tensor:
|
98 |
+
batch_size, seq_len, _ = states.size()
|
99 |
+
|
100 |
+
q_states = self.rope_e(self._shape(self.q_proj(states), batch_size, seq_len))
|
101 |
+
k_states = self.rope_e(self._shape(self.k_proj(states), batch_size, seq_len))
|
102 |
+
v_states = self._shape(self.v_proj(states), batch_size, seq_len)
|
103 |
+
|
104 |
+
attn_weights = torch.matmul(q_states, k_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
105 |
+
attn_weights = torch.clamp(attn_weights, min=-1024.0, max=1024.0)
|
106 |
+
|
107 |
+
if mask is not None:
|
108 |
+
attn_weights = attn_weights.masked_fill(mask == 0, float('-inf'))
|
109 |
+
|
110 |
+
attn_weights = f.softmax(attn_weights, dim=-1)
|
111 |
+
attn_outputs = torch.matmul(attn_weights, v_states)
|
112 |
+
return self._reshape(attn_outputs, batch_size, seq_len)
|
113 |
+
|
114 |
+
|
115 |
+
class BigBrainDecoderLayer(nn.Module):
|
116 |
+
def __init__(self, config: BigBrainConfig):
|
117 |
+
super().__init__()
|
118 |
+
self.config = config
|
119 |
+
self.self_attn = RotaryMultiHeadAttention(config)
|
120 |
+
self.feed_forward = MultiLayerPerceptron(config)
|
121 |
+
self.input_norm = RootMeanSquareNorm(config.hidden_size, config.layer_norm_eps)
|
122 |
+
self.attn_norm = RootMeanSquareNorm(config.hidden_size, config.layer_norm_eps)
|
123 |
+
self.register_buffer('attn_mask', _make_casual_mask(config.max_position_embeddings))
|
124 |
+
|
125 |
+
def forward(self, x: torch.Tensor):
|
126 |
+
batch_size, seq_len, _ = x.size()
|
127 |
+
mask = self.attn_mask[:seq_len, :seq_len]
|
128 |
+
x = x + self.self_attn(self.input_norm(x), mask)
|
129 |
+
x = x + self.feed_forward(self.attn_norm(x))
|
130 |
+
return x
|
131 |
+
|
132 |
+
|
133 |
+
class BigBrainLanguageModel(PreTrainedModel):
|
134 |
+
config_class = BigBrainConfig
|
135 |
+
base_model_prefix = 'big-brain-lm'
|
136 |
+
|
137 |
+
def __init__(self, config: BigBrainConfig):
|
138 |
+
super().__init__(config)
|
139 |
+
self.config = config
|
140 |
+
self.tok_embed = nn.Embedding(config.vocab_size, config.hidden_size, config.pad_token_id)
|
141 |
+
self.layers = nn.ModuleList([BigBrainDecoderLayer(config) for _ in range(config.num_hidden_layers)])
|
142 |
+
self.norm = RootMeanSquareNorm(config.hidden_size, config.layer_norm_eps)
|
143 |
+
self.linear = nn.Linear(config.hidden_size, config.vocab_size)
|
144 |
+
self.post_init()
|
145 |
+
|
146 |
+
def _init_weights(self, module):
|
147 |
+
std = self.config.initializer_range
|
148 |
+
if isinstance(module, nn.Linear):
|
149 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
150 |
+
if module.bias is not None:
|
151 |
+
module.bias.data.zero_()
|
152 |
+
elif isinstance(module, nn.Embedding):
|
153 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
154 |
+
if module.padding_idx is not None:
|
155 |
+
module.weight.data[module.padding_idx].zero_()
|
156 |
+
|
157 |
+
def forward(self, input_ids: torch.Tensor, target_ids: torch.Tensor = None):
|
158 |
+
hidden_states = self.tok_embed(input_ids)
|
159 |
+
for decoder_layer in self.layers:
|
160 |
+
hidden_states = decoder_layer(hidden_states)
|
161 |
+
hidden_states = self.norm(hidden_states)
|
162 |
+
hidden_states = self.linear(hidden_states)
|
163 |
+
|
164 |
+
if target_ids is None:
|
165 |
+
return hidden_states, None
|
166 |
+
|
167 |
+
b, t, c = hidden_states.size()
|
168 |
+
loss = f.cross_entropy(hidden_states.view(b * t, c), target_ids.view(b * t))
|
169 |
+
return hidden_states, loss
|
pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c547697b1f4cc69295875fd3afc1679df421333ef53026d3f1f50cbc6b1dd5a3
|
3 |
+
size 774713018
|