Upload model
Browse files- config.json +33 -0
- generation_config.json +6 -0
- model.safetensors +3 -0
- modeling_t2.py +656 -0
config.json
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"activation_function": "silu",
|
3 |
+
"architectures": [
|
4 |
+
"TransformerModelForCausalLM"
|
5 |
+
],
|
6 |
+
"auto_map": {
|
7 |
+
"AutoConfig": "modeling_t2.TransformerConfig",
|
8 |
+
"AutoModelForCausalLM": "modeling_t2.TransformerModelForCausalLM"
|
9 |
+
},
|
10 |
+
"bos_token_id": 1,
|
11 |
+
"combined_qkv": true,
|
12 |
+
"eos_token_id": 2,
|
13 |
+
"expanded_lm_head_size": 8192,
|
14 |
+
"hidden_size": 768,
|
15 |
+
"initializer_range": 0.02,
|
16 |
+
"intermediate_size": 3072,
|
17 |
+
"kv_hidden_size": null,
|
18 |
+
"layer_norm_epsilon": 1e-06,
|
19 |
+
"max_position_embeddings": 2048,
|
20 |
+
"model_type": "Transformer",
|
21 |
+
"num_attention_heads": 12,
|
22 |
+
"num_hidden_layers": 10,
|
23 |
+
"rope_scaling": null,
|
24 |
+
"rope_theta": 10000,
|
25 |
+
"stage_0_attention_heads": 6,
|
26 |
+
"stage_0_hidden_layers": 1,
|
27 |
+
"stage_0_hidden_size": 384,
|
28 |
+
"torch_dtype": "bfloat16",
|
29 |
+
"transformers_version": "4.36.2",
|
30 |
+
"use_bias": false,
|
31 |
+
"use_cache": true,
|
32 |
+
"vocab_size": 32000
|
33 |
+
}
|
generation_config.json
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"bos_token_id": 1,
|
4 |
+
"eos_token_id":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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import os
|
3 |
+
import random
|
4 |
+
import warnings
|
5 |
+
from dataclasses import dataclass
|
6 |
+
from typing import Optional, Tuple, Union
|
7 |
+
|
8 |
+
import torch
|
9 |
+
import torch.nn as nn
|
10 |
+
import torch.nn.functional as F
|
11 |
+
import torch.utils.checkpoint
|
12 |
+
from einops import repeat
|
13 |
+
from torch import nn
|
14 |
+
from torch.cuda.amp import autocast
|
15 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
16 |
+
from transformers.activations import ACT2FN
|
17 |
+
from transformers.modeling_outputs import (
|
18 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
19 |
+
CausalLMOutputWithCrossAttentions, QuestionAnsweringModelOutput,
|
20 |
+
SequenceClassifierOutputWithPast, TokenClassifierOutput)
|
21 |
+
from transformers.modeling_utils import PreTrainedModel, SequenceSummary
|
22 |
+
from transformers.utils import (ModelOutput, logging)
|
23 |
+
from transformers.utils.model_parallel_utils import (assert_device_map,
|
24 |
+
get_device_map)
|
25 |
+
from collections import OrderedDict
|
26 |
+
from typing import Any, List, Mapping, Optional
|
27 |
+
|
28 |
+
from transformers import PreTrainedTokenizer, TensorType, is_torch_available
|
29 |
+
from transformers.configuration_utils import PretrainedConfig
|
30 |
+
from transformers.utils import logging
|
31 |
+
|
32 |
+
logger = logging.get_logger(__name__)
|
33 |
+
|
34 |
+
class StageLinear(nn.Module):
|
35 |
+
def __init__(self, in_features=768, out_features=768, bias=True, stage=0, config=None):
|
36 |
+
super().__init__()
|
37 |
+
self.stage = stage
|
38 |
+
if self.stage==0:
|
39 |
+
self.module = nn.Linear(in_features, out_features, bias)
|
40 |
+
else:
|
41 |
+
transformer_config = TransformerConfig()
|
42 |
+
transformer_config.__dict__.update(config.__dict__)
|
43 |
+
transformer_config.__dict__.update({"hidden_size": config.stage_0_hidden_size})
|
44 |
+
transformer_config.__dict__.update({"num_hidden_layers": config.stage_0_hidden_layers})
|
45 |
+
transformer_config.__dict__.update({"num_attention_heads": config.stage_0_attention_heads})
|
46 |
+
transformer_config.__dict__.update({"intermediate_size": config.stage_0_hidden_size * 4})
|
47 |
+
self.in_proj = nn.Linear(in_features, config.stage_0_hidden_size, bias=bias)
|
48 |
+
self.h = nn.ModuleList(
|
49 |
+
[TransformerBlock(transformer_config) for i in range(transformer_config.num_hidden_layers)]
|
50 |
+
)
|
51 |
+
self.ln_f = LlamaRMSNorm(config.stage_0_hidden_size, eps=config.layer_norm_epsilon)
|
52 |
+
self.out_proj = nn.Linear(config.stage_0_hidden_size, out_features, bias=bias)
|
53 |
+
def forward(self, x):
|
54 |
+
if self.stage==0:
|
55 |
+
return self.module(x)
|
56 |
+
|
57 |
+
x = self.in_proj(x)
|
58 |
+
for block in self.h:
|
59 |
+
x_new, attn_outs = block(x)
|
60 |
+
x = x + x_new
|
61 |
+
x = self.out_proj(x)
|
62 |
+
return x
|
63 |
+
|
64 |
+
class TransformerConfig(PretrainedConfig):
|
65 |
+
model_type = "Transformer"
|
66 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
67 |
+
attribute_map = {
|
68 |
+
"hidden_size": "hidden_size",
|
69 |
+
"max_position_embeddings": "max_position_embeddings",
|
70 |
+
"num_attention_heads": "num_attention_heads",
|
71 |
+
"num_hidden_layers": "num_hidden_layers",
|
72 |
+
}
|
73 |
+
|
74 |
+
def __init__(
|
75 |
+
self,
|
76 |
+
vocab_size=32000,
|
77 |
+
max_position_embeddings=2048,
|
78 |
+
expanded_lm_head_size=8192,
|
79 |
+
hidden_size=768,
|
80 |
+
stage_0_hidden_size=256,
|
81 |
+
stage_0_hidden_layers=1,
|
82 |
+
stage_0_attention_heads=8,
|
83 |
+
kv_hidden_size=None, # in case you want to use cross-attention
|
84 |
+
num_hidden_layers=10,
|
85 |
+
num_attention_heads=12,
|
86 |
+
intermediate_size=None,
|
87 |
+
activation_function="silu",
|
88 |
+
layer_norm_epsilon=1e-6,
|
89 |
+
initializer_range=0.02,
|
90 |
+
use_cache=True,
|
91 |
+
bos_token_id=1,
|
92 |
+
eos_token_id=2,
|
93 |
+
combined_qkv=True,
|
94 |
+
use_bias=False,
|
95 |
+
rope_scaling=None,
|
96 |
+
rope_theta=10000,
|
97 |
+
tie_word_embeddings=False,
|
98 |
+
|
99 |
+
|
100 |
+
**kwargs,
|
101 |
+
):
|
102 |
+
self.stage_0_hidden_size = stage_0_hidden_size
|
103 |
+
self.stage_0_hidden_layers = stage_0_hidden_layers
|
104 |
+
self.stage_0_attention_heads = stage_0_attention_heads
|
105 |
+
self.expanded_lm_head_size = expanded_lm_head_size
|
106 |
+
self.tie_word_embeddings = tie_word_embeddings
|
107 |
+
self.rope_theta=rope_theta
|
108 |
+
self.rope_scaling=rope_scaling
|
109 |
+
self.kv_hidden_size = kv_hidden_size
|
110 |
+
self.use_bias = use_bias
|
111 |
+
self.combined_qkv = combined_qkv
|
112 |
+
self.vocab_size = vocab_size
|
113 |
+
self.max_position_embeddings = max_position_embeddings
|
114 |
+
self.hidden_size = hidden_size
|
115 |
+
self.num_hidden_layers = num_hidden_layers
|
116 |
+
self.num_attention_heads = num_attention_heads
|
117 |
+
self.intermediate_size = (
|
118 |
+
intermediate_size if intermediate_size is not None else hidden_size * 4
|
119 |
+
)
|
120 |
+
self.activation_function = activation_function
|
121 |
+
self.layer_norm_epsilon = layer_norm_epsilon
|
122 |
+
self.initializer_range = initializer_range
|
123 |
+
|
124 |
+
self.use_cache = use_cache
|
125 |
+
|
126 |
+
self.bos_token_id = bos_token_id
|
127 |
+
self.eos_token_id = eos_token_id
|
128 |
+
|
129 |
+
super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
|
130 |
+
|
131 |
+
|
132 |
+
from transformers.models.llama.modeling_llama import LlamaRMSNorm, LlamaDynamicNTKScalingRotaryEmbedding, LlamaRotaryEmbedding, LlamaLinearScalingRotaryEmbedding
|
133 |
+
|
134 |
+
def rotate_half(x):
|
135 |
+
"""Rotates half the hidden dims of the input."""
|
136 |
+
x1 = x[..., : x.shape[-1] // 2]
|
137 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
138 |
+
return torch.cat((-x2, x1), dim=-1)
|
139 |
+
|
140 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
|
141 |
+
cos = cos[position_ids].unsqueeze(unsqueeze_dim)
|
142 |
+
sin = sin[position_ids].unsqueeze(unsqueeze_dim)
|
143 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
144 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
145 |
+
return q_embed, k_embed
|
146 |
+
|
147 |
+
class TransformerAttention(nn.Module):
|
148 |
+
def __init__(self, config, stage):
|
149 |
+
super().__init__()
|
150 |
+
self.config = config
|
151 |
+
self.stage = stage
|
152 |
+
self.head_dim = config.hidden_size // config.num_attention_heads
|
153 |
+
assert (
|
154 |
+
self.head_dim * config.num_attention_heads == config.hidden_size
|
155 |
+
), "d_model must be divisible by n_head"
|
156 |
+
self.use_bias = config.use_bias
|
157 |
+
|
158 |
+
if not config.combined_qkv or config.kv_hidden_size is not None:
|
159 |
+
self.query = StageLinear(
|
160 |
+
config.hidden_size, config.hidden_size, bias=self.use_bias, stage=stage, config=config
|
161 |
+
)
|
162 |
+
self.key = StageLinear(
|
163 |
+
config.hidden_size
|
164 |
+
if not config.kv_hidden_size
|
165 |
+
else config.kv_hidden_size,
|
166 |
+
config.hidden_size,
|
167 |
+
bias=self.use_bias,
|
168 |
+
stage=stage, config=config
|
169 |
+
)
|
170 |
+
self.value = StageLinear(
|
171 |
+
config.hidden_size
|
172 |
+
if not config.kv_hidden_size
|
173 |
+
else config.kv_hidden_size,
|
174 |
+
config.hidden_size,
|
175 |
+
bias=self.use_bias, stage=stage, config=config
|
176 |
+
)
|
177 |
+
else:
|
178 |
+
self.qkv = StageLinear(
|
179 |
+
config.hidden_size, config.hidden_size * 3, bias=self.use_bias, stage=stage, config=config
|
180 |
+
)
|
181 |
+
self.out = StageLinear(config.hidden_size, config.hidden_size, bias=self.use_bias, stage=stage, config=config)
|
182 |
+
self._init_rope()
|
183 |
+
|
184 |
+
def _init_rope(self):
|
185 |
+
if self.config.rope_scaling is None:
|
186 |
+
self.rotary_emb = LlamaRotaryEmbedding(
|
187 |
+
self.head_dim,
|
188 |
+
max_position_embeddings=self.config.max_position_embeddings,
|
189 |
+
base=self.config.rope_theta,
|
190 |
+
)
|
191 |
+
else:
|
192 |
+
scaling_type = self.config.rope_scaling["type"]
|
193 |
+
scaling_factor = self.config.rope_scaling["factor"]
|
194 |
+
if scaling_type == "linear":
|
195 |
+
self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
|
196 |
+
self.head_dim,
|
197 |
+
max_position_embeddings=self.config.max_position_embeddings,
|
198 |
+
scaling_factor=scaling_factor,
|
199 |
+
base=self.config.rope_theta,
|
200 |
+
)
|
201 |
+
elif scaling_type == "dynamic":
|
202 |
+
self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
|
203 |
+
self.head_dim,
|
204 |
+
max_position_embeddings=self.max_position_embeddings,
|
205 |
+
scaling_factor=scaling_factor,
|
206 |
+
base=self.config.rope_theta,
|
207 |
+
)
|
208 |
+
else:
|
209 |
+
raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
|
210 |
+
|
211 |
+
def forward(self, x0, x1=None, causal=False, mask=None, position_ids=None, use_cache=True, layer_past=None):
|
212 |
+
batch_size = x0.size(0)
|
213 |
+
|
214 |
+
def split_heads(x):
|
215 |
+
return x.view(
|
216 |
+
batch_size, -1, self.config.num_attention_heads, self.head_dim
|
217 |
+
).transpose(1, 2)
|
218 |
+
|
219 |
+
if not self.config.combined_qkv:
|
220 |
+
q = split_heads(self.query(x0))
|
221 |
+
k = split_heads(self.key(x1) if x1 is not None else self.key(x0))
|
222 |
+
v = split_heads(
|
223 |
+
self.value(x1 if x1 is not None else x0)
|
224 |
+
)
|
225 |
+
else:
|
226 |
+
q, k, v = self.qkv(x0).chunk(3,-1)
|
227 |
+
q = split_heads(q)
|
228 |
+
k = split_heads(k)
|
229 |
+
v = split_heads(v)
|
230 |
+
|
231 |
+
if layer_past is not None:
|
232 |
+
past_key, past_value = layer_past
|
233 |
+
k = torch.cat((past_key, k), dim=-2)
|
234 |
+
v = torch.cat((past_value, v), dim=-2)
|
235 |
+
|
236 |
+
cos, sin = self.rotary_emb(v, seq_len=v.shape[-2])
|
237 |
+
q, k = apply_rotary_pos_emb(q, k, cos, sin, position_ids)
|
238 |
+
|
239 |
+
if use_cache is True:
|
240 |
+
present = (k,v)
|
241 |
+
else:
|
242 |
+
present = None
|
243 |
+
|
244 |
+
attn_output = F.scaled_dot_product_attention(
|
245 |
+
q, k, v, attn_mask=None, dropout_p=0.0, is_causal=causal
|
246 |
+
)
|
247 |
+
attn_output = (
|
248 |
+
attn_output.transpose(1, 2)
|
249 |
+
.contiguous()
|
250 |
+
.view(batch_size, -1, self.config.hidden_size)
|
251 |
+
)
|
252 |
+
return self.out(attn_output), present
|
253 |
+
|
254 |
+
|
255 |
+
class MLP(nn.Module):
|
256 |
+
def __init__(self, config, stage=0):
|
257 |
+
super().__init__()
|
258 |
+
self.config = config
|
259 |
+
self.stage = stage
|
260 |
+
self.gate_proj = StageLinear(
|
261 |
+
config.hidden_size, config.intermediate_size, bias=False, stage=stage, config=config
|
262 |
+
)
|
263 |
+
self.up_proj = StageLinear(
|
264 |
+
config.hidden_size, config.intermediate_size, bias=False, stage=stage, config=config
|
265 |
+
)
|
266 |
+
self.down_proj = StageLinear(
|
267 |
+
config.intermediate_size, config.hidden_size, bias=False, stage=stage, config=config
|
268 |
+
)
|
269 |
+
self.act_fn = ACT2FN[config.activation_function]
|
270 |
+
|
271 |
+
def forward(self, x):
|
272 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
273 |
+
|
274 |
+
class TransformerBlock(nn.Module):
|
275 |
+
def __init__(self, config, stage=0):
|
276 |
+
super().__init__()
|
277 |
+
self.config = config
|
278 |
+
self.stage = stage
|
279 |
+
self.attn = TransformerAttention(config, stage)
|
280 |
+
self.ffn = MLP(config, stage)
|
281 |
+
self.ln1 = LlamaRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
|
282 |
+
self.ln2 = LlamaRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
|
283 |
+
|
284 |
+
def forward(self, x, mask=None, position_ids=None, use_cache=True, layer_past=None):
|
285 |
+
attn_in = self.ln1(x)
|
286 |
+
ffn_in = self.ln2(x)
|
287 |
+
attn_out, attn_outs = self.attn(attn_in, causal=True, mask=mask, position_ids=position_ids, use_cache=use_cache, layer_past=layer_past)
|
288 |
+
ffn_out = self.ffn(ffn_in)
|
289 |
+
x = x + attn_out + ffn_out
|
290 |
+
if not use_cache: attn_outs = None
|
291 |
+
return (x, attn_outs)
|
292 |
+
|
293 |
+
class TransformerPreTrainedModel(PreTrainedModel):
|
294 |
+
config_class = TransformerConfig
|
295 |
+
base_model_prefix = "transformer"
|
296 |
+
is_parallelizable = False
|
297 |
+
supports_gradient_checkpointing = True
|
298 |
+
_no_split_modules = ["TransformerBlock"]
|
299 |
+
_skip_keys_device_placement = "past_key_values"
|
300 |
+
|
301 |
+
def __init__(self, *inputs, **kwargs):
|
302 |
+
super().__init__(*inputs, **kwargs)
|
303 |
+
|
304 |
+
def _init_weights(self, module):
|
305 |
+
"""Initialize the weights."""
|
306 |
+
if isinstance(module, (nn.Linear)):
|
307 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
308 |
+
if module.bias is not None:
|
309 |
+
module.bias.data.zero_()
|
310 |
+
elif isinstance(module, nn.Embedding):
|
311 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
312 |
+
if module.padding_idx is not None:
|
313 |
+
module.weight.data[module.padding_idx].zero_()
|
314 |
+
elif isinstance(module, nn.LayerNorm):
|
315 |
+
module.bias.data.zero_()
|
316 |
+
module.weight.data.fill_(1.0)
|
317 |
+
|
318 |
+
# def _set_gradient_checkpointing(self, module, value=False):
|
319 |
+
# if isinstance(module, TransformerModel):
|
320 |
+
# module.gradient_checkpointing = value
|
321 |
+
|
322 |
+
class TransformerModel(TransformerPreTrainedModel):
|
323 |
+
def __init__(self, config):
|
324 |
+
super().__init__(config)
|
325 |
+
# self.wte = nn.Embedding(config.vocab_size, config.hidden_size)
|
326 |
+
self.wte = nn.Sequential(
|
327 |
+
nn.Embedding(config.vocab_size, config.stage_0_hidden_size),
|
328 |
+
StageLinear(config.stage_0_hidden_size, config.hidden_size, bias=False, stage=0, config=config)
|
329 |
+
)
|
330 |
+
self.h = nn.ModuleList(
|
331 |
+
[TransformerBlock(config, stage=1) for i in range(config.num_hidden_layers)]
|
332 |
+
)
|
333 |
+
self.ln_f = LlamaRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
|
334 |
+
self.model_parallel = False
|
335 |
+
self.device_map = None
|
336 |
+
self.gradient_checkpointing = False
|
337 |
+
self.post_init()
|
338 |
+
|
339 |
+
def get_input_embeddings(self):
|
340 |
+
return self.wte[0]
|
341 |
+
|
342 |
+
def set_input_embeddings(self, new_embeddings):
|
343 |
+
self.wte[0] = new_embeddings
|
344 |
+
|
345 |
+
def forward(
|
346 |
+
self,
|
347 |
+
input_ids: Optional[torch.LongTensor] = None,
|
348 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
349 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
350 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
351 |
+
position_ids: Optional[torch.LongTensor] = None,
|
352 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
353 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
354 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
355 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
356 |
+
use_cache: Optional[bool] = None,
|
357 |
+
output_attentions: Optional[bool] = None,
|
358 |
+
output_hidden_states: Optional[bool] = None,
|
359 |
+
return_dict: Optional[bool] = None,
|
360 |
+
) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
|
361 |
+
# soooo not all of the params are able to be used, since I just copied this framework from modeling_gpt2
|
362 |
+
|
363 |
+
output_attentions = (
|
364 |
+
output_attentions
|
365 |
+
if output_attentions is not None
|
366 |
+
else self.config.output_attentions
|
367 |
+
)
|
368 |
+
output_hidden_states = (
|
369 |
+
output_hidden_states
|
370 |
+
if output_hidden_states is not None
|
371 |
+
else self.config.output_hidden_states
|
372 |
+
)
|
373 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
374 |
+
return_dict = (
|
375 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
376 |
+
)
|
377 |
+
if input_ids is not None and inputs_embeds is not None:
|
378 |
+
raise ValueError(
|
379 |
+
"You cannot specify both input_ids and inputs_embeds at the same time"
|
380 |
+
)
|
381 |
+
elif input_ids is not None:
|
382 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
383 |
+
input_shape = input_ids.size()
|
384 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
385 |
+
batch_size = input_ids.shape[0]
|
386 |
+
elif inputs_embeds is not None:
|
387 |
+
input_shape = inputs_embeds.size()[:-1]
|
388 |
+
batch_size = inputs_embeds.shape[0]
|
389 |
+
else:
|
390 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
391 |
+
|
392 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
393 |
+
|
394 |
+
if token_type_ids is not None:
|
395 |
+
token_type_ids = token_type_ids.view(-1, input_shape[-1])
|
396 |
+
if position_ids is not None:
|
397 |
+
position_ids = position_ids.view(-1, input_shape[-1])
|
398 |
+
|
399 |
+
if past_key_values is None:
|
400 |
+
past_length = 0
|
401 |
+
past_key_values = tuple([None] * len(self.h))
|
402 |
+
else:
|
403 |
+
past_length = past_key_values[0][0].size(-2)
|
404 |
+
if position_ids is None:
|
405 |
+
position_ids = torch.arange(
|
406 |
+
past_length,
|
407 |
+
input_shape[-1] + past_length,
|
408 |
+
dtype=torch.long,
|
409 |
+
device=device,
|
410 |
+
)
|
411 |
+
position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
|
412 |
+
|
413 |
+
if attention_mask is not None:
|
414 |
+
if batch_size <= 0:
|
415 |
+
raise ValueError("batch_size has to be defined and > 0")
|
416 |
+
attention_mask = attention_mask.view(batch_size, -1)
|
417 |
+
attention_mask = attention_mask[:, None, None, :]
|
418 |
+
attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
|
419 |
+
attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
|
420 |
+
|
421 |
+
if self.config.add_cross_attention and encoder_hidden_states is not None:
|
422 |
+
(
|
423 |
+
encoder_batch_size,
|
424 |
+
encoder_sequence_length,
|
425 |
+
_,
|
426 |
+
) = encoder_hidden_states.size()
|
427 |
+
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
|
428 |
+
if encoder_attention_mask is None:
|
429 |
+
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
|
430 |
+
encoder_attention_mask = self.invert_attention_mask(encoder_attention_mask)
|
431 |
+
else:
|
432 |
+
encoder_attention_mask = None
|
433 |
+
|
434 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
435 |
+
|
436 |
+
if inputs_embeds is None:
|
437 |
+
inputs_embeds = self.wte(input_ids)
|
438 |
+
# print("inputs embeds shape", inputs_embeds.shape)
|
439 |
+
|
440 |
+
hidden_states = inputs_embeds
|
441 |
+
|
442 |
+
if token_type_ids is not None:
|
443 |
+
token_type_embeds = self.wte(token_type_ids)
|
444 |
+
hidden_states = hidden_states + token_type_embeds
|
445 |
+
|
446 |
+
# output_shape = (-1,) + input_shape[1:] + (hidden_states.size(-1),)
|
447 |
+
output_shape = (-1,) + (hidden_states.shape[1],) + (hidden_states.size(-1),)
|
448 |
+
# print(output_shape, "output shape")
|
449 |
+
|
450 |
+
if self.gradient_checkpointing and self.training:
|
451 |
+
if use_cache:
|
452 |
+
# logger.warning_once(
|
453 |
+
# "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
454 |
+
# )
|
455 |
+
use_cache = False
|
456 |
+
|
457 |
+
presents = () if use_cache else None
|
458 |
+
all_self_attentions = () if output_attentions else None
|
459 |
+
all_cross_attentions = (
|
460 |
+
() if output_attentions and self.config.add_cross_attention else None
|
461 |
+
)
|
462 |
+
all_hidden_states = () if output_hidden_states else None
|
463 |
+
for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
|
464 |
+
if self.model_parallel:
|
465 |
+
torch.cuda.set_device(hidden_states.device)
|
466 |
+
if layer_past is not None:
|
467 |
+
layer_past = tuple(
|
468 |
+
past_state.to(hidden_states.device)
|
469 |
+
for past_state in layer_past
|
470 |
+
)
|
471 |
+
if attention_mask is not None:
|
472 |
+
attention_mask = attention_mask.to(hidden_states.device)
|
473 |
+
if isinstance(head_mask, torch.Tensor):
|
474 |
+
head_mask = head_mask.to(hidden_states.device)
|
475 |
+
if output_hidden_states:
|
476 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
477 |
+
outputs = block(hidden_states, mask=attention_mask, position_ids=position_ids, use_cache=use_cache, layer_past=layer_past)
|
478 |
+
hidden_states = outputs[0]
|
479 |
+
if use_cache == True:
|
480 |
+
presents = presents + (outputs[1],)
|
481 |
+
|
482 |
+
hidden_states = self.ln_f(hidden_states)
|
483 |
+
hidden_states = hidden_states.view(output_shape)
|
484 |
+
if output_hidden_states:
|
485 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
486 |
+
|
487 |
+
if not return_dict:
|
488 |
+
return tuple(
|
489 |
+
v
|
490 |
+
for v in [hidden_states, None, all_hidden_states, None, None]
|
491 |
+
if v is not None
|
492 |
+
)
|
493 |
+
|
494 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
495 |
+
last_hidden_state=hidden_states,
|
496 |
+
past_key_values=presents,
|
497 |
+
hidden_states=all_hidden_states,
|
498 |
+
attentions=None,
|
499 |
+
cross_attentions=None,
|
500 |
+
)
|
501 |
+
|
502 |
+
class TransformerModelForCausalLM(TransformerPreTrainedModel):
|
503 |
+
_tied_weights_keys = ["lm_head.1.weight"]
|
504 |
+
_tied_weights_keys = []
|
505 |
+
def __init__(self, config):
|
506 |
+
super().__init__(config)
|
507 |
+
self.transformer = TransformerModel(config)
|
508 |
+
# self.lm_head = nn.Linear(
|
509 |
+
# config.hidden_size, config.vocab_size, bias=False
|
510 |
+
# )
|
511 |
+
self.lm_head = nn.Sequential(
|
512 |
+
StageLinear(config.hidden_size, config.stage_0_hidden_size, bias=False, stage=0, config=config),
|
513 |
+
nn.Linear(config.stage_0_hidden_size, config.vocab_size),
|
514 |
+
)
|
515 |
+
self.model_parallel = False
|
516 |
+
self.device_map = None
|
517 |
+
self.post_init()
|
518 |
+
|
519 |
+
def get_output_embeddings(self):
|
520 |
+
return self.lm_head[1]
|
521 |
+
|
522 |
+
def set_output_embeddings(self, new_embeddings):
|
523 |
+
# print("Huggingface is inexplicably trying to tie the lm head no matter how many times i'm saying tie_weights False but I'm not letting it")
|
524 |
+
self.lm_head[1] = new_embeddings
|
525 |
+
|
526 |
+
def prepare_inputs_for_generation(
|
527 |
+
self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs
|
528 |
+
):
|
529 |
+
token_type_ids = kwargs.get("token_type_ids", None)
|
530 |
+
# only last token for inputs_ids if past is defined in kwargs
|
531 |
+
if past_key_values:
|
532 |
+
input_ids = input_ids[:, -1].unsqueeze(-1)
|
533 |
+
if token_type_ids is not None:
|
534 |
+
token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
|
535 |
+
|
536 |
+
attention_mask = kwargs.get("attention_mask", None)
|
537 |
+
position_ids = kwargs.get("position_ids", None)
|
538 |
+
|
539 |
+
if attention_mask is not None and position_ids is None:
|
540 |
+
# create position_ids on the fly for batch generation
|
541 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
542 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
543 |
+
if past_key_values:
|
544 |
+
position_ids = position_ids[:, -1].unsqueeze(-1)
|
545 |
+
else:
|
546 |
+
position_ids = None
|
547 |
+
|
548 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
549 |
+
if inputs_embeds is not None and past_key_values is None:
|
550 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
551 |
+
else:
|
552 |
+
model_inputs = {"input_ids": input_ids}
|
553 |
+
|
554 |
+
model_inputs.update(
|
555 |
+
{
|
556 |
+
"past_key_values": past_key_values,
|
557 |
+
"use_cache": kwargs.get("use_cache"),
|
558 |
+
"position_ids": position_ids,
|
559 |
+
"attention_mask": attention_mask,
|
560 |
+
"token_type_ids": token_type_ids,
|
561 |
+
}
|
562 |
+
)
|
563 |
+
return model_inputs
|
564 |
+
|
565 |
+
def forward(
|
566 |
+
self,
|
567 |
+
input_ids: Optional[torch.LongTensor] = None,
|
568 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
569 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
570 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
571 |
+
position_ids: Optional[torch.LongTensor] = None,
|
572 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
573 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
574 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
575 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
576 |
+
labels: Optional[torch.LongTensor] = None,
|
577 |
+
use_cache: Optional[bool] = None,
|
578 |
+
output_attentions: Optional[bool] = None,
|
579 |
+
output_hidden_states: Optional[bool] = None,
|
580 |
+
return_dict: Optional[bool] = None,
|
581 |
+
) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
|
582 |
+
r"""
|
583 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
584 |
+
Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
|
585 |
+
`labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
|
586 |
+
are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
|
587 |
+
"""
|
588 |
+
return_dict = (
|
589 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
590 |
+
)
|
591 |
+
|
592 |
+
transformer_outputs = self.transformer(
|
593 |
+
input_ids,
|
594 |
+
past_key_values=past_key_values,
|
595 |
+
attention_mask=attention_mask,
|
596 |
+
token_type_ids=token_type_ids,
|
597 |
+
position_ids=position_ids,
|
598 |
+
head_mask=head_mask,
|
599 |
+
inputs_embeds=inputs_embeds,
|
600 |
+
encoder_hidden_states=encoder_hidden_states,
|
601 |
+
encoder_attention_mask=encoder_attention_mask,
|
602 |
+
use_cache=use_cache,
|
603 |
+
output_attentions=output_attentions,
|
604 |
+
output_hidden_states=output_hidden_states,
|
605 |
+
return_dict=return_dict,
|
606 |
+
)
|
607 |
+
hidden_states = transformer_outputs[0]
|
608 |
+
# print("Hidden states shape", hidden_states.shape)
|
609 |
+
if self.model_parallel:
|
610 |
+
torch.cuda.set_device(self.transformer.first_device)
|
611 |
+
hidden_states = hidden_states.to(self.lm_head.weight.device)
|
612 |
+
|
613 |
+
lm_logits = self.lm_head(hidden_states)
|
614 |
+
|
615 |
+
loss = None
|
616 |
+
if labels is not None:
|
617 |
+
# move labels to correct device to enable model parallelism
|
618 |
+
labels = labels.to(lm_logits.device)
|
619 |
+
# Shift so that tokens < n predict n
|
620 |
+
shift_logits = lm_logits[..., :-1, :].contiguous()
|
621 |
+
shift_labels = labels[..., 1:].contiguous()
|
622 |
+
# Flatten the tokens
|
623 |
+
loss_fct = CrossEntropyLoss()
|
624 |
+
loss = loss_fct(
|
625 |
+
shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)
|
626 |
+
)
|
627 |
+
|
628 |
+
if not return_dict:
|
629 |
+
output = (lm_logits,) + transformer_outputs[1:]
|
630 |
+
return ((loss,) + output) if loss is not None else output
|
631 |
+
|
632 |
+
return CausalLMOutputWithCrossAttentions(
|
633 |
+
loss=loss,
|
634 |
+
logits=lm_logits,
|
635 |
+
past_key_values=transformer_outputs.past_key_values,
|
636 |
+
hidden_states=transformer_outputs.hidden_states,
|
637 |
+
attentions=transformer_outputs.attentions,
|
638 |
+
cross_attentions=transformer_outputs.cross_attentions,
|
639 |
+
)
|
640 |
+
|
641 |
+
@staticmethod
|
642 |
+
def _reorder_cache(
|
643 |
+
past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
|
644 |
+
) -> Tuple[Tuple[torch.Tensor]]:
|
645 |
+
"""
|
646 |
+
This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
|
647 |
+
[`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
|
648 |
+
beam_idx at every generation step.
|
649 |
+
"""
|
650 |
+
return tuple(
|
651 |
+
tuple(
|
652 |
+
past_state.index_select(0, beam_idx.to(past_state.device))
|
653 |
+
for past_state in layer_past
|
654 |
+
)
|
655 |
+
for layer_past in past_key_values
|
656 |
+
)
|