Upload 4 files
Browse files- configuration_baichuan.py +66 -0
- handler.py +27 -0
- modeling_baichuan.py +834 -0
- tokenization_baichuan.py +6 -5
configuration_baichuan.py
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
5 |
+
# and OPT implementations in this library. It has been modified from its
|
6 |
+
# original forms to accommodate minor architectural differences compared
|
7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
8 |
+
#
|
9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
10 |
+
# you may not use this file except in compliance with the License.
|
11 |
+
# You may obtain a copy of the License at
|
12 |
+
#
|
13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
14 |
+
#
|
15 |
+
# Unless required by applicable law or agreed to in writing, software
|
16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
18 |
+
# See the License for the specific language governing permissions and
|
19 |
+
# limitations under the License.
|
20 |
+
|
21 |
+
from transformers.configuration_utils import PretrainedConfig
|
22 |
+
from transformers.utils import logging
|
23 |
+
|
24 |
+
|
25 |
+
logger = logging.get_logger(__name__)
|
26 |
+
|
27 |
+
|
28 |
+
class BaiChuanConfig(PretrainedConfig):
|
29 |
+
model_type = "baichuan"
|
30 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
31 |
+
|
32 |
+
def __init__(
|
33 |
+
self,
|
34 |
+
vocab_size=64000,
|
35 |
+
hidden_size=4096,
|
36 |
+
intermediate_size=11008,
|
37 |
+
num_hidden_layers=32,
|
38 |
+
num_attention_heads=32,
|
39 |
+
hidden_act="silu",
|
40 |
+
max_position_embeddings=4096,
|
41 |
+
initializer_range=0.02,
|
42 |
+
rms_norm_eps=1e-6,
|
43 |
+
use_cache=True,
|
44 |
+
pad_token_id=0,
|
45 |
+
bos_token_id=1,
|
46 |
+
eos_token_id=2,
|
47 |
+
tie_word_embeddings=False,
|
48 |
+
**kwargs,
|
49 |
+
):
|
50 |
+
self.vocab_size = vocab_size
|
51 |
+
self.max_position_embeddings = max_position_embeddings
|
52 |
+
self.hidden_size = hidden_size
|
53 |
+
self.intermediate_size = intermediate_size
|
54 |
+
self.num_hidden_layers = num_hidden_layers
|
55 |
+
self.num_attention_heads = num_attention_heads
|
56 |
+
self.hidden_act = hidden_act
|
57 |
+
self.initializer_range = initializer_range
|
58 |
+
self.rms_norm_eps = rms_norm_eps
|
59 |
+
self.use_cache = use_cache
|
60 |
+
super().__init__(
|
61 |
+
pad_token_id=pad_token_id,
|
62 |
+
bos_token_id=bos_token_id,
|
63 |
+
eos_token_id=eos_token_id,
|
64 |
+
tie_word_embeddings=tie_word_embeddings,
|
65 |
+
**kwargs,
|
66 |
+
)
|
handler.py
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from typing import Dict, List, Any
|
3 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
4 |
+
|
5 |
+
# get dtype
|
6 |
+
dtype = torch.bfloat16 if torch.cuda.get_device_capability()[0] == 8 else torch.float16
|
7 |
+
|
8 |
+
|
9 |
+
class EndpointHandler:
|
10 |
+
def __init__(self, path=""):
|
11 |
+
# load the model
|
12 |
+
tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
|
13 |
+
model = AutoModelForCausalLM.from_pretrained(path, device_map="auto", torch_dtype=dtype, trust_remote_code=True)
|
14 |
+
# create inference pipeline
|
15 |
+
self.pipeline = pipeline("text-generation", model=model, tokenizer=tokenizer)
|
16 |
+
|
17 |
+
def __call__(self, data: Any) -> List[List[Dict[str, float]]]:
|
18 |
+
inputs = data.pop("inputs", data)
|
19 |
+
parameters = data.pop("parameters", None)
|
20 |
+
|
21 |
+
# pass inputs with all kwargs in data
|
22 |
+
if parameters is not None:
|
23 |
+
prediction = self.pipeline(inputs, **parameters)
|
24 |
+
else:
|
25 |
+
prediction = self.pipeline(inputs)
|
26 |
+
# postprocess the prediction
|
27 |
+
return prediction
|
modeling_baichuan.py
ADDED
@@ -0,0 +1,834 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
5 |
+
# and OPT implementations in this library. It has been modified from its
|
6 |
+
# original forms to accommodate minor architectural differences compared
|
7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
8 |
+
#
|
9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
10 |
+
# you may not use this file except in compliance with the License.
|
11 |
+
# You may obtain a copy of the License at
|
12 |
+
#
|
13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
14 |
+
#
|
15 |
+
# Unless required by applicable law or agreed to in writing, software
|
16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
18 |
+
# See the License for the specific language governing permissions and
|
19 |
+
# limitations under the License.
|
20 |
+
from .configuration_baichuan import BaiChuanConfig
|
21 |
+
|
22 |
+
import copy
|
23 |
+
import warnings
|
24 |
+
import math
|
25 |
+
from typing import *
|
26 |
+
import re
|
27 |
+
import torch
|
28 |
+
import torch.utils.checkpoint
|
29 |
+
from torch import nn
|
30 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
31 |
+
from transformers import PreTrainedModel, add_start_docstrings
|
32 |
+
from transformers.activations import ACT2FN
|
33 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, \
|
34 |
+
SequenceClassifierOutputWithPast
|
35 |
+
from transformers.utils import logging, add_start_docstrings_to_model_forward, replace_return_docstrings
|
36 |
+
from transformers.generation.logits_process import LogitsProcessor
|
37 |
+
from transformers.generation.utils import LogitsProcessorList, StoppingCriteriaList, GenerationConfig, ModelOutput
|
38 |
+
|
39 |
+
logger = logging.get_logger(__name__)
|
40 |
+
|
41 |
+
# copied from https://huggingface.co/THUDM/chatglm-6b-int4/blob/main/modeling_chatglm.py
|
42 |
+
class InvalidScoreLogitsProcessor(LogitsProcessor):
|
43 |
+
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
|
44 |
+
if torch.isnan(scores).any() or torch.isinf(scores).any():
|
45 |
+
scores.zero_()
|
46 |
+
scores[..., 5] = 5e4
|
47 |
+
return scores
|
48 |
+
|
49 |
+
def generate_prompt(input_text):
|
50 |
+
return "Human: \n" + input_text + "\n\nAssistant:\n"
|
51 |
+
|
52 |
+
|
53 |
+
# Copied from transformers.models.bart.modeling_bart._make_causal_mask
|
54 |
+
def _make_causal_mask(
|
55 |
+
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
|
56 |
+
):
|
57 |
+
"""
|
58 |
+
Make causal mask used for bi-directional self-attention.
|
59 |
+
"""
|
60 |
+
bsz, tgt_len = input_ids_shape
|
61 |
+
mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
|
62 |
+
mask_cond = torch.arange(mask.size(-1), device=device)
|
63 |
+
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
64 |
+
mask = mask.to(dtype)
|
65 |
+
|
66 |
+
if past_key_values_length > 0:
|
67 |
+
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
|
68 |
+
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
|
69 |
+
|
70 |
+
|
71 |
+
# Copied from transformers.models.bart.modeling_bart._expand_mask
|
72 |
+
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
73 |
+
"""
|
74 |
+
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
75 |
+
"""
|
76 |
+
bsz, src_len = mask.size()
|
77 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
78 |
+
|
79 |
+
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
80 |
+
|
81 |
+
inverted_mask = 1.0 - expanded_mask
|
82 |
+
|
83 |
+
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
84 |
+
|
85 |
+
|
86 |
+
class RMSNorm(nn.Module):
|
87 |
+
def __init__(self, hidden_size, eps=1e-6):
|
88 |
+
"""
|
89 |
+
RMSNorm is equivalent to T5LayerNorm
|
90 |
+
"""
|
91 |
+
super().__init__()
|
92 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
93 |
+
self.variance_epsilon = eps
|
94 |
+
|
95 |
+
def forward(self, hidden_states):
|
96 |
+
variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
|
97 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
98 |
+
|
99 |
+
# convert into half-precision if necessary
|
100 |
+
if self.weight.dtype in [torch.float16, torch.bfloat16]:
|
101 |
+
hidden_states = hidden_states.to(self.weight.dtype)
|
102 |
+
|
103 |
+
return self.weight * hidden_states
|
104 |
+
|
105 |
+
|
106 |
+
class RotaryEmbedding(torch.nn.Module):
|
107 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
108 |
+
super().__init__()
|
109 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
|
110 |
+
self.register_buffer("inv_freq", inv_freq)
|
111 |
+
|
112 |
+
# Build here to make `torch.jit.trace` work.
|
113 |
+
self.max_seq_len_cached = max_position_embeddings
|
114 |
+
t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
|
115 |
+
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
116 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
117 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
118 |
+
self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
|
119 |
+
self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
|
120 |
+
|
121 |
+
def forward(self, x, seq_len=None):
|
122 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
123 |
+
# This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
|
124 |
+
if seq_len > self.max_seq_len_cached:
|
125 |
+
self.max_seq_len_cached = seq_len
|
126 |
+
t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
|
127 |
+
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
128 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
129 |
+
emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
|
130 |
+
self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
|
131 |
+
self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
|
132 |
+
return (
|
133 |
+
self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
|
134 |
+
self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
|
135 |
+
)
|
136 |
+
|
137 |
+
|
138 |
+
def rotate_half(x):
|
139 |
+
"""Rotates half the hidden dims of the input."""
|
140 |
+
x1 = x[..., : x.shape[-1] // 2]
|
141 |
+
x2 = x[..., x.shape[-1] // 2:]
|
142 |
+
return torch.cat((-x2, x1), dim=-1)
|
143 |
+
|
144 |
+
|
145 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
|
146 |
+
# The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
|
147 |
+
cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
|
148 |
+
sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
|
149 |
+
cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
|
150 |
+
sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
|
151 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
152 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
153 |
+
return q_embed, k_embed
|
154 |
+
|
155 |
+
|
156 |
+
class MLP(nn.Module):
|
157 |
+
def __init__(
|
158 |
+
self,
|
159 |
+
hidden_size: int,
|
160 |
+
intermediate_size: int,
|
161 |
+
hidden_act: str,
|
162 |
+
):
|
163 |
+
super().__init__()
|
164 |
+
self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
165 |
+
self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
|
166 |
+
self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
167 |
+
self.act_fn = ACT2FN[hidden_act]
|
168 |
+
|
169 |
+
def forward(self, x):
|
170 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
171 |
+
|
172 |
+
|
173 |
+
class Attention(nn.Module):
|
174 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
175 |
+
|
176 |
+
def __init__(self, config: BaiChuanConfig):
|
177 |
+
super().__init__()
|
178 |
+
self.config = config
|
179 |
+
self.hidden_size = config.hidden_size
|
180 |
+
self.num_heads = config.num_attention_heads
|
181 |
+
self.head_dim = self.hidden_size // self.num_heads
|
182 |
+
self.max_position_embeddings = config.max_position_embeddings
|
183 |
+
|
184 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
185 |
+
raise ValueError(
|
186 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
187 |
+
f" and `num_heads`: {self.num_heads})."
|
188 |
+
)
|
189 |
+
# self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
|
190 |
+
# self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
|
191 |
+
# self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
|
192 |
+
self.W_pack = nn.Linear(self.hidden_size, 3 * self.hidden_size, bias=False)
|
193 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
194 |
+
self.rotary_emb = RotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
|
195 |
+
|
196 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
197 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
198 |
+
|
199 |
+
def forward(
|
200 |
+
self,
|
201 |
+
hidden_states: torch.Tensor,
|
202 |
+
attention_mask: Optional[torch.Tensor] = None,
|
203 |
+
position_ids: Optional[torch.LongTensor] = None,
|
204 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
205 |
+
output_attentions: bool = False,
|
206 |
+
use_cache: bool = False,
|
207 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
208 |
+
bsz, q_len, _ = hidden_states.size()
|
209 |
+
|
210 |
+
proj = self.W_pack(hidden_states)
|
211 |
+
proj = proj.unflatten(-1, (3, self.hidden_size)).unsqueeze(0).transpose(0, -2).squeeze(-2)
|
212 |
+
query_states = proj[0].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1,
|
213 |
+
2) # batch_size x source_len x hidden_size
|
214 |
+
key_states = proj[1].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1,
|
215 |
+
2) # batch_size x target_len x head_size
|
216 |
+
value_states = proj[2].view(bsz, q_len, self.num_heads, self.head_dim).transpose(1,
|
217 |
+
2) # batch_size x source_len x hidden_size
|
218 |
+
|
219 |
+
# query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
220 |
+
# key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
221 |
+
# value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
222 |
+
|
223 |
+
kv_seq_len = key_states.shape[-2]
|
224 |
+
if past_key_value is not None:
|
225 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
226 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
227 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
228 |
+
# [bsz, nh, t, hd]
|
229 |
+
|
230 |
+
if past_key_value is not None:
|
231 |
+
# reuse k, v, self_attention
|
232 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
233 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
234 |
+
|
235 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
236 |
+
|
237 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
238 |
+
|
239 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
240 |
+
raise ValueError(
|
241 |
+
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
242 |
+
f" {attn_weights.size()}"
|
243 |
+
)
|
244 |
+
|
245 |
+
if attention_mask is not None:
|
246 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
247 |
+
raise ValueError(
|
248 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
249 |
+
)
|
250 |
+
attn_weights = attn_weights + attention_mask
|
251 |
+
attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min))
|
252 |
+
|
253 |
+
# upcast attention to fp32
|
254 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
255 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
256 |
+
|
257 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
258 |
+
raise ValueError(
|
259 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
260 |
+
f" {attn_output.size()}"
|
261 |
+
)
|
262 |
+
|
263 |
+
attn_output = attn_output.transpose(1, 2)
|
264 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
265 |
+
|
266 |
+
attn_output = self.o_proj(attn_output)
|
267 |
+
|
268 |
+
if not output_attentions:
|
269 |
+
attn_weights = None
|
270 |
+
|
271 |
+
return attn_output, attn_weights, past_key_value
|
272 |
+
|
273 |
+
|
274 |
+
class DecoderLayer(nn.Module):
|
275 |
+
def __init__(self, config: BaiChuanConfig):
|
276 |
+
super().__init__()
|
277 |
+
self.hidden_size = config.hidden_size
|
278 |
+
self.self_attn = Attention(config=config)
|
279 |
+
self.mlp = MLP(
|
280 |
+
hidden_size=self.hidden_size,
|
281 |
+
intermediate_size=config.intermediate_size,
|
282 |
+
hidden_act=config.hidden_act,
|
283 |
+
)
|
284 |
+
self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
285 |
+
self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
286 |
+
|
287 |
+
def forward(
|
288 |
+
self,
|
289 |
+
hidden_states: torch.Tensor,
|
290 |
+
attention_mask: Optional[torch.Tensor] = None,
|
291 |
+
position_ids: Optional[torch.LongTensor] = None,
|
292 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
293 |
+
output_attentions: Optional[bool] = False,
|
294 |
+
use_cache: Optional[bool] = False,
|
295 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
296 |
+
"""
|
297 |
+
Args:
|
298 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
299 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
300 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
301 |
+
output_attentions (`bool`, *optional*):
|
302 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
303 |
+
returned tensors for more detail.
|
304 |
+
use_cache (`bool`, *optional*):
|
305 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
306 |
+
(see `past_key_values`).
|
307 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
308 |
+
"""
|
309 |
+
|
310 |
+
residual = hidden_states
|
311 |
+
|
312 |
+
hidden_states = self.input_layernorm(hidden_states)
|
313 |
+
|
314 |
+
# Self Attention
|
315 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
316 |
+
hidden_states=hidden_states,
|
317 |
+
attention_mask=attention_mask,
|
318 |
+
position_ids=position_ids,
|
319 |
+
past_key_value=past_key_value,
|
320 |
+
output_attentions=output_attentions,
|
321 |
+
use_cache=use_cache,
|
322 |
+
)
|
323 |
+
hidden_states = residual + hidden_states
|
324 |
+
|
325 |
+
# Fully Connected
|
326 |
+
residual = hidden_states
|
327 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
328 |
+
hidden_states = self.mlp(hidden_states)
|
329 |
+
hidden_states = residual + hidden_states
|
330 |
+
|
331 |
+
outputs = (hidden_states,)
|
332 |
+
|
333 |
+
if output_attentions:
|
334 |
+
outputs += (self_attn_weights,)
|
335 |
+
|
336 |
+
if use_cache:
|
337 |
+
outputs += (present_key_value,)
|
338 |
+
|
339 |
+
return outputs
|
340 |
+
|
341 |
+
|
342 |
+
class PreTrainedModel(PreTrainedModel):
|
343 |
+
config_class = BaiChuanConfig
|
344 |
+
base_model_prefix = "model"
|
345 |
+
supports_gradient_checkpointing = True
|
346 |
+
_no_split_modules = ["DecoderLayer"]
|
347 |
+
_keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
|
348 |
+
|
349 |
+
def _init_weights(self, module):
|
350 |
+
std = self.config.initializer_range
|
351 |
+
if isinstance(module, nn.Linear):
|
352 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
353 |
+
if module.bias is not None:
|
354 |
+
module.bias.data.zero_()
|
355 |
+
elif isinstance(module, nn.Embedding):
|
356 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
357 |
+
if module.padding_idx is not None:
|
358 |
+
module.weight.data[module.padding_idx].zero_()
|
359 |
+
|
360 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
361 |
+
if isinstance(module, Model):
|
362 |
+
module.gradient_checkpointing = value
|
363 |
+
|
364 |
+
|
365 |
+
class Model(PreTrainedModel):
|
366 |
+
"""
|
367 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DecoderLayer`]
|
368 |
+
|
369 |
+
Args:
|
370 |
+
config: BaiChuanConfig
|
371 |
+
"""
|
372 |
+
|
373 |
+
def __init__(self, config: BaiChuanConfig):
|
374 |
+
super().__init__(config)
|
375 |
+
self.padding_idx = config.pad_token_id
|
376 |
+
self.vocab_size = config.vocab_size
|
377 |
+
|
378 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
379 |
+
self.layers = nn.ModuleList([DecoderLayer(config) for _ in range(config.num_hidden_layers)])
|
380 |
+
self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
381 |
+
|
382 |
+
self.gradient_checkpointing = False
|
383 |
+
# Initialize weights and apply final processing
|
384 |
+
self.post_init()
|
385 |
+
|
386 |
+
def get_input_embeddings(self):
|
387 |
+
return self.embed_tokens
|
388 |
+
|
389 |
+
def set_input_embeddings(self, value):
|
390 |
+
self.embed_tokens = value
|
391 |
+
|
392 |
+
# Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
|
393 |
+
def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
|
394 |
+
# create causal mask
|
395 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
396 |
+
combined_attention_mask = None
|
397 |
+
if input_shape[-1] > 1:
|
398 |
+
combined_attention_mask = _make_causal_mask(
|
399 |
+
input_shape,
|
400 |
+
inputs_embeds.dtype,
|
401 |
+
device=inputs_embeds.device,
|
402 |
+
past_key_values_length=past_key_values_length,
|
403 |
+
)
|
404 |
+
|
405 |
+
if attention_mask is not None:
|
406 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
407 |
+
expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
|
408 |
+
inputs_embeds.device
|
409 |
+
)
|
410 |
+
combined_attention_mask = (
|
411 |
+
expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
|
412 |
+
)
|
413 |
+
|
414 |
+
return combined_attention_mask
|
415 |
+
|
416 |
+
def forward(
|
417 |
+
self,
|
418 |
+
input_ids: torch.LongTensor = None,
|
419 |
+
attention_mask: Optional[torch.Tensor] = None,
|
420 |
+
position_ids: Optional[torch.LongTensor] = None,
|
421 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
422 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
423 |
+
use_cache: Optional[bool] = None,
|
424 |
+
output_attentions: Optional[bool] = None,
|
425 |
+
output_hidden_states: Optional[bool] = None,
|
426 |
+
return_dict: Optional[bool] = None,
|
427 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
428 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
429 |
+
output_hidden_states = (
|
430 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
431 |
+
)
|
432 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
433 |
+
|
434 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
435 |
+
|
436 |
+
# retrieve input_ids and inputs_embeds
|
437 |
+
if input_ids is not None and inputs_embeds is not None:
|
438 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
439 |
+
elif input_ids is not None:
|
440 |
+
batch_size, seq_length = input_ids.shape
|
441 |
+
elif inputs_embeds is not None:
|
442 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
443 |
+
else:
|
444 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
445 |
+
|
446 |
+
seq_length_with_past = seq_length
|
447 |
+
past_key_values_length = 0
|
448 |
+
|
449 |
+
if past_key_values is not None:
|
450 |
+
past_key_values_length = past_key_values[0][0].shape[2]
|
451 |
+
seq_length_with_past = seq_length_with_past + past_key_values_length
|
452 |
+
|
453 |
+
if position_ids is None:
|
454 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
455 |
+
position_ids = torch.arange(
|
456 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
457 |
+
)
|
458 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
459 |
+
else:
|
460 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
461 |
+
|
462 |
+
if inputs_embeds is None:
|
463 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
464 |
+
# embed positions
|
465 |
+
if attention_mask is None:
|
466 |
+
attention_mask = torch.ones(
|
467 |
+
(batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
|
468 |
+
)
|
469 |
+
attention_mask = self._prepare_decoder_attention_mask(
|
470 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
471 |
+
)
|
472 |
+
|
473 |
+
hidden_states = inputs_embeds
|
474 |
+
|
475 |
+
if self.gradient_checkpointing and self.training:
|
476 |
+
if use_cache:
|
477 |
+
logger.warning_once(
|
478 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
479 |
+
)
|
480 |
+
use_cache = False
|
481 |
+
|
482 |
+
# decoder layers
|
483 |
+
all_hidden_states = () if output_hidden_states else None
|
484 |
+
all_self_attns = () if output_attentions else None
|
485 |
+
next_decoder_cache = () if use_cache else None
|
486 |
+
|
487 |
+
for idx, decoder_layer in enumerate(self.layers):
|
488 |
+
if output_hidden_states:
|
489 |
+
all_hidden_states += (hidden_states,)
|
490 |
+
|
491 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
492 |
+
|
493 |
+
if self.gradient_checkpointing and self.training:
|
494 |
+
|
495 |
+
def create_custom_forward(module):
|
496 |
+
def custom_forward(*inputs):
|
497 |
+
# None for past_key_value
|
498 |
+
return module(*inputs, output_attentions, None)
|
499 |
+
|
500 |
+
return custom_forward
|
501 |
+
|
502 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
503 |
+
create_custom_forward(decoder_layer),
|
504 |
+
hidden_states,
|
505 |
+
attention_mask,
|
506 |
+
position_ids,
|
507 |
+
None,
|
508 |
+
)
|
509 |
+
else:
|
510 |
+
layer_outputs = decoder_layer(
|
511 |
+
hidden_states,
|
512 |
+
attention_mask=attention_mask,
|
513 |
+
position_ids=position_ids,
|
514 |
+
past_key_value=past_key_value,
|
515 |
+
output_attentions=output_attentions,
|
516 |
+
use_cache=use_cache,
|
517 |
+
)
|
518 |
+
|
519 |
+
hidden_states = layer_outputs[0]
|
520 |
+
|
521 |
+
if use_cache:
|
522 |
+
next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
|
523 |
+
|
524 |
+
if output_attentions:
|
525 |
+
all_self_attns += (layer_outputs[1],)
|
526 |
+
|
527 |
+
hidden_states = self.norm(hidden_states)
|
528 |
+
|
529 |
+
# add hidden states from the last decoder layer
|
530 |
+
if output_hidden_states:
|
531 |
+
all_hidden_states += (hidden_states,)
|
532 |
+
|
533 |
+
next_cache = next_decoder_cache if use_cache else None
|
534 |
+
if not return_dict:
|
535 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
536 |
+
return BaseModelOutputWithPast(
|
537 |
+
last_hidden_state=hidden_states,
|
538 |
+
past_key_values=next_cache,
|
539 |
+
hidden_states=all_hidden_states,
|
540 |
+
attentions=all_self_attns,
|
541 |
+
)
|
542 |
+
|
543 |
+
|
544 |
+
class BaiChuanForCausalLM(PreTrainedModel):
|
545 |
+
def __init__(self, config):
|
546 |
+
super().__init__(config)
|
547 |
+
self.model = Model(config)
|
548 |
+
|
549 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
550 |
+
|
551 |
+
# Initialize weights and apply final processing
|
552 |
+
self.post_init()
|
553 |
+
|
554 |
+
def get_input_embeddings(self):
|
555 |
+
return self.model.embed_tokens
|
556 |
+
|
557 |
+
def set_input_embeddings(self, value):
|
558 |
+
self.model.embed_tokens = value
|
559 |
+
|
560 |
+
def get_output_embeddings(self):
|
561 |
+
return self.lm_head
|
562 |
+
|
563 |
+
def set_output_embeddings(self, new_embeddings):
|
564 |
+
self.lm_head = new_embeddings
|
565 |
+
|
566 |
+
def set_decoder(self, decoder):
|
567 |
+
self.model = decoder
|
568 |
+
|
569 |
+
def get_decoder(self):
|
570 |
+
return self.model
|
571 |
+
|
572 |
+
def forward(
|
573 |
+
self,
|
574 |
+
input_ids: torch.LongTensor = None,
|
575 |
+
attention_mask: Optional[torch.Tensor] = None,
|
576 |
+
position_ids: Optional[torch.LongTensor] = None,
|
577 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
578 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
579 |
+
labels: Optional[torch.LongTensor] = None,
|
580 |
+
use_cache: Optional[bool] = None,
|
581 |
+
output_attentions: Optional[bool] = None,
|
582 |
+
output_hidden_states: Optional[bool] = None,
|
583 |
+
return_dict: Optional[bool] = None,
|
584 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
585 |
+
r"""
|
586 |
+
Args:
|
587 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
588 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
589 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
590 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
591 |
+
|
592 |
+
Returns:
|
593 |
+
|
594 |
+
Example:
|
595 |
+
|
596 |
+
```python
|
597 |
+
>>> from transformers import AutoTokenizer, ModelForCausalLM
|
598 |
+
|
599 |
+
>>> model = ModelForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
|
600 |
+
>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
|
601 |
+
|
602 |
+
>>> prompt = "Hey, are you consciours? Can you talk to me?"
|
603 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
604 |
+
|
605 |
+
>>> # Generate
|
606 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
607 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
608 |
+
"Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."
|
609 |
+
```"""
|
610 |
+
|
611 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
612 |
+
output_hidden_states = (
|
613 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
614 |
+
)
|
615 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
616 |
+
|
617 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
618 |
+
outputs = self.model(
|
619 |
+
input_ids=input_ids,
|
620 |
+
attention_mask=attention_mask,
|
621 |
+
position_ids=position_ids,
|
622 |
+
past_key_values=past_key_values,
|
623 |
+
inputs_embeds=inputs_embeds,
|
624 |
+
use_cache=use_cache,
|
625 |
+
output_attentions=output_attentions,
|
626 |
+
output_hidden_states=output_hidden_states,
|
627 |
+
return_dict=return_dict,
|
628 |
+
)
|
629 |
+
|
630 |
+
hidden_states = outputs[0]
|
631 |
+
logits = self.lm_head(hidden_states)
|
632 |
+
|
633 |
+
loss = None
|
634 |
+
if labels is not None:
|
635 |
+
# Shift so that tokens < n predict n
|
636 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
637 |
+
shift_labels = labels[..., 1:].contiguous()
|
638 |
+
# Flatten the tokens
|
639 |
+
loss_fct = CrossEntropyLoss()
|
640 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
641 |
+
shift_labels = shift_labels.view(-1)
|
642 |
+
# Enable model parallelism
|
643 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
644 |
+
loss = loss_fct(shift_logits, shift_labels)
|
645 |
+
|
646 |
+
if not return_dict:
|
647 |
+
output = (logits,) + outputs[1:]
|
648 |
+
return (loss,) + output if loss is not None else output
|
649 |
+
|
650 |
+
return CausalLMOutputWithPast(
|
651 |
+
loss=loss,
|
652 |
+
logits=logits,
|
653 |
+
past_key_values=outputs.past_key_values,
|
654 |
+
hidden_states=outputs.hidden_states,
|
655 |
+
attentions=outputs.attentions,
|
656 |
+
)
|
657 |
+
|
658 |
+
def prepare_inputs_for_generation(
|
659 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
660 |
+
):
|
661 |
+
if past_key_values:
|
662 |
+
input_ids = input_ids[:, -1:]
|
663 |
+
|
664 |
+
position_ids = kwargs.get("position_ids", None)
|
665 |
+
if attention_mask is not None and position_ids is None:
|
666 |
+
# create position_ids on the fly for batch generation
|
667 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
668 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
669 |
+
if past_key_values:
|
670 |
+
position_ids = position_ids[:, -1].unsqueeze(-1)
|
671 |
+
|
672 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
673 |
+
if inputs_embeds is not None and past_key_values is None:
|
674 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
675 |
+
else:
|
676 |
+
model_inputs = {"input_ids": input_ids}
|
677 |
+
|
678 |
+
model_inputs.update(
|
679 |
+
{
|
680 |
+
"position_ids": position_ids,
|
681 |
+
"past_key_values": past_key_values,
|
682 |
+
"use_cache": kwargs.get("use_cache"),
|
683 |
+
"attention_mask": attention_mask,
|
684 |
+
}
|
685 |
+
)
|
686 |
+
return model_inputs
|
687 |
+
|
688 |
+
@staticmethod
|
689 |
+
def _reorder_cache(past_key_values, beam_idx):
|
690 |
+
reordered_past = ()
|
691 |
+
for layer_past in past_key_values:
|
692 |
+
reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
|
693 |
+
return reordered_past
|
694 |
+
|
695 |
+
def process_response(self, response):
|
696 |
+
response = response.strip()
|
697 |
+
response = response.replace("[[训练时间]]", "2023年")
|
698 |
+
punkts = [
|
699 |
+
[",", ","],
|
700 |
+
["!", "!"],
|
701 |
+
[":", ":"],
|
702 |
+
[";", ";"],
|
703 |
+
["\?", "?"],
|
704 |
+
]
|
705 |
+
for item in punkts:
|
706 |
+
response = re.sub(r"([\u4e00-\u9fff])%s" % item[0], r"\1%s" % item[1], response)
|
707 |
+
response = re.sub(r"%s([\u4e00-\u9fff])" % item[0], r"%s\1" % item[1], response)
|
708 |
+
return response
|
709 |
+
|
710 |
+
# copied from https://huggingface.co/THUDM/chatglm-6b-int4/blob/main/modeling_chatglm.py
|
711 |
+
@torch.no_grad()
|
712 |
+
def stream_chat(self, tokenizer, query: str, history: List = None,
|
713 |
+
gen_kwargs: dict = None, logits_processor=None):
|
714 |
+
if history is None:
|
715 |
+
history = []
|
716 |
+
if logits_processor is None:
|
717 |
+
logits_processor = LogitsProcessorList()
|
718 |
+
logits_processor.append(InvalidScoreLogitsProcessor())
|
719 |
+
|
720 |
+
if not history:
|
721 |
+
prompt = generate_prompt(query)
|
722 |
+
else:
|
723 |
+
history.append(generate_prompt(query))
|
724 |
+
prompt = "".join(history)
|
725 |
+
|
726 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
727 |
+
inputs = inputs.to(self.model.device)
|
728 |
+
for outputs in self.stream_generate(**inputs, **gen_kwargs):
|
729 |
+
outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):]
|
730 |
+
response = tokenizer.decode(outputs, skip_special_tokens=True).split("Assistant:")[-1].strip()
|
731 |
+
response = self.process_response(response)
|
732 |
+
yield response
|
733 |
+
|
734 |
+
@torch.no_grad()
|
735 |
+
def stream_generate(
|
736 |
+
self,
|
737 |
+
input_ids,
|
738 |
+
generation_config: Optional[GenerationConfig] = None,
|
739 |
+
logits_processor: Optional[LogitsProcessorList] = None,
|
740 |
+
stopping_criteria: Optional[StoppingCriteriaList] = None,
|
741 |
+
prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
|
742 |
+
**kwargs,
|
743 |
+
):
|
744 |
+
batch_size, input_ids_seq_length = input_ids.shape[0], input_ids.shape[-1]
|
745 |
+
|
746 |
+
if generation_config is None:
|
747 |
+
generation_config = self.generation_config
|
748 |
+
generation_config = copy.deepcopy(generation_config)
|
749 |
+
model_kwargs = generation_config.update(**kwargs)
|
750 |
+
bos_token_id, eos_token_id = generation_config.bos_token_id, generation_config.eos_token_id
|
751 |
+
|
752 |
+
if isinstance(eos_token_id, int):
|
753 |
+
eos_token_id = [eos_token_id]
|
754 |
+
|
755 |
+
has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
|
756 |
+
if has_default_max_length and generation_config.max_new_tokens is None:
|
757 |
+
warnings.warn(
|
758 |
+
f"Using `max_length`'s default ({generation_config.max_length}) to control the generation length. "
|
759 |
+
"This behaviour is deprecated and will be removed from the config in v5 of Transformers -- we"
|
760 |
+
" recommend using `max_new_tokens` to control the maximum length of the generation.",
|
761 |
+
UserWarning,
|
762 |
+
)
|
763 |
+
elif generation_config.max_new_tokens is not None:
|
764 |
+
generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length
|
765 |
+
if not has_default_max_length:
|
766 |
+
logger.warn(
|
767 |
+
f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
|
768 |
+
f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
|
769 |
+
"Please refer to the documentation for more information. "
|
770 |
+
"(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)",
|
771 |
+
UserWarning,
|
772 |
+
)
|
773 |
+
|
774 |
+
if input_ids_seq_length >= generation_config.max_length:
|
775 |
+
input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
|
776 |
+
logger.warning(
|
777 |
+
f"Input length of {input_ids_string} is {input_ids_seq_length}, but `max_length` is set to"
|
778 |
+
f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider"
|
779 |
+
" increasing `max_new_tokens`."
|
780 |
+
)
|
781 |
+
|
782 |
+
# 2. Set generation parameters if not already defined
|
783 |
+
logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
|
784 |
+
stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
|
785 |
+
|
786 |
+
logits_processor = self._get_logits_processor(
|
787 |
+
generation_config=generation_config,
|
788 |
+
input_ids_seq_length=input_ids_seq_length,
|
789 |
+
encoder_input_ids=input_ids,
|
790 |
+
prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
|
791 |
+
logits_processor=logits_processor,
|
792 |
+
)
|
793 |
+
|
794 |
+
stopping_criteria = self._get_stopping_criteria(
|
795 |
+
generation_config=generation_config, stopping_criteria=stopping_criteria
|
796 |
+
)
|
797 |
+
logits_warper = self._get_logits_warper(generation_config)
|
798 |
+
|
799 |
+
unfinished_sequences = input_ids.new(input_ids.shape[0]).fill_(1)
|
800 |
+
scores = None
|
801 |
+
while True:
|
802 |
+
model_inputs = self.prepare_inputs_for_generation(input_ids, **model_kwargs)
|
803 |
+
# forward pass to get next token
|
804 |
+
outputs = self(
|
805 |
+
**model_inputs,
|
806 |
+
return_dict=True,
|
807 |
+
output_attentions=False,
|
808 |
+
output_hidden_states=False,
|
809 |
+
)
|
810 |
+
|
811 |
+
next_token_logits = outputs.logits[:, -1, :]
|
812 |
+
|
813 |
+
# pre-process distribution
|
814 |
+
next_token_scores = logits_processor(input_ids, next_token_logits)
|
815 |
+
next_token_scores = logits_warper(input_ids, next_token_scores)
|
816 |
+
|
817 |
+
# sample
|
818 |
+
probs = nn.functional.softmax(next_token_scores, dim=-1)
|
819 |
+
if generation_config.do_sample:
|
820 |
+
next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
|
821 |
+
else:
|
822 |
+
next_tokens = torch.argmax(probs, dim=-1)
|
823 |
+
|
824 |
+
# update generated ids, model inputs, and length for next step
|
825 |
+
input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
|
826 |
+
model_kwargs = self._update_model_kwargs_for_generation(
|
827 |
+
outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
|
828 |
+
)
|
829 |
+
unfinished_sequences = unfinished_sequences.mul((sum(next_tokens != i for i in eos_token_id)).long())
|
830 |
+
|
831 |
+
# stop when each sentence is finished, or if we exceed the maximum length
|
832 |
+
if unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores):
|
833 |
+
break
|
834 |
+
yield input_ids
|
tokenization_baichuan.py
CHANGED
@@ -71,6 +71,11 @@ class BaiChuanTokenizer(PreTrainedTokenizer):
|
|
71 |
eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
|
72 |
unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
|
73 |
pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
|
|
|
|
|
|
|
|
|
|
|
74 |
super().__init__(
|
75 |
bos_token=bos_token,
|
76 |
eos_token=eos_token,
|
@@ -82,11 +87,7 @@ class BaiChuanTokenizer(PreTrainedTokenizer):
|
|
82 |
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
83 |
**kwargs,
|
84 |
)
|
85 |
-
|
86 |
-
self.add_bos_token = add_bos_token
|
87 |
-
self.add_eos_token = add_eos_token
|
88 |
-
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
89 |
-
self.sp_model.Load(vocab_file)
|
90 |
|
91 |
def __getstate__(self):
|
92 |
state = self.__dict__.copy()
|
|
|
71 |
eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
|
72 |
unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
|
73 |
pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
|
74 |
+
self.vocab_file = vocab_file
|
75 |
+
self.add_bos_token = add_bos_token
|
76 |
+
self.add_eos_token = add_eos_token
|
77 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
78 |
+
self.sp_model.Load(vocab_file)
|
79 |
super().__init__(
|
80 |
bos_token=bos_token,
|
81 |
eos_token=eos_token,
|
|
|
87 |
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
88 |
**kwargs,
|
89 |
)
|
90 |
+
|
|
|
|
|
|
|
|
|
91 |
|
92 |
def __getstate__(self):
|
93 |
state = self.__dict__.copy()
|