jianfbsdc commited on
Commit
0290131
·
verified ·
1 Parent(s): 7f9256c

Upload folder using huggingface_hub

Browse files
configuration_telechat2.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 the Big Science Workshop and HuggingFace Inc. team. 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
+ """ Telechat configuration"""
17
+
18
+ from packaging import version
19
+ from collections import OrderedDict
20
+ from transformers.utils import is_torch_available, logging
21
+ from transformers.configuration_utils import PretrainedConfig
22
+ from typing import TYPE_CHECKING, Any, List, Mapping, Optional
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+ class Telechat2Config(PretrainedConfig):
27
+ """
28
+ Args:
29
+ vocab_size (`int`, *optional*, defaults to 160256): Vocabulary size of the Telechat model.
30
+ hidden_size (`int`, *optional*, defaults to 4096): Dimensionality of the embeddings and hidden states.
31
+ ffn_hidden_size (`int`, *optional*, defaults to 12288): Dimensionality of the feed-forward hidden states.
32
+ n_layer (`int`, *optional*, defaults to 30): Number of hidden layers in the Transformer
33
+ n_head (`int`, *optional*, defaults to 32): Number of attention heads for each attention layer.
34
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-5): The epsilon to use in the layer normalization layers.
35
+ initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
36
+ apply_residual_connection_post_layernorm (`bool`, *optional*, defaults to `False`): If enabled, use the layer norm of the hidden states as the residual in the transformer blocks
37
+ hidden_dropout (`float`, *optional*, defaults to 0.0): Dropout rate of the dropout function on the bias dropout.
38
+ attention_dropout (`float`, *optional*, defaults to 0.0): Dropout rate applied to the attention probs
39
+ use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions.
40
+ training_seqlen (`int`, *optional*, defaults to 8192): Sequence length during last finetuning.
41
+ logn (`bool`, *optional*, defaults to `True`): Whether or not to use logN during extrapolation.
42
+ embed_layernorm (`bool`, *optional*, defaults to `True`): Whether or not to use embedding layernorm.
43
+
44
+ """
45
+
46
+ model_type = "telechat"
47
+ keys_to_ignore_at_inference = ["past_key_values"]
48
+ attribute_map = {
49
+ "num_hidden_layers": "n_layer",
50
+ "num_attention_heads": "n_head",
51
+ }
52
+
53
+ def __init__(
54
+ self,
55
+ vocab_size=160256,
56
+ hidden_size=4096,
57
+ n_layer=30,
58
+ n_head=32,
59
+ layer_norm_epsilon=1e-5,
60
+ initializer_range=0.02,
61
+ use_cache=True,
62
+ bos_token_id=1,
63
+ eos_token_id=2,
64
+ apply_residual_connection_post_layernorm=False,
65
+ hidden_dropout=0.0,
66
+ attention_dropout=0.0,
67
+ ffn_hidden_size=12288,
68
+ training_seqlen = 8192,
69
+ logn = True,
70
+ embed_layernorm = False,
71
+ **kwargs,
72
+ ):
73
+ self.vocab_size = vocab_size
74
+ n_embed = kwargs.pop("n_embed", None)
75
+ self.hidden_size = hidden_size if n_embed is None else n_embed
76
+ self.n_layer = n_layer
77
+ self.n_head = n_head
78
+ self.layer_norm_epsilon = layer_norm_epsilon
79
+ self.initializer_range = initializer_range
80
+ self.use_cache = use_cache
81
+ self.apply_residual_connection_post_layernorm = apply_residual_connection_post_layernorm
82
+ self.hidden_dropout = hidden_dropout
83
+ self.attention_dropout = attention_dropout
84
+ self.bos_token_id = bos_token_id
85
+ self.eos_token_id = eos_token_id
86
+ self.logn = logn
87
+ self.ffn_hidden_size = ffn_hidden_size
88
+ self.training_seqlen = training_seqlen
89
+ self.embed_layernorm = embed_layernorm
90
+ self.num_key_value_heads= kwargs.pop("num_key_value_heads", None)
91
+
92
+
93
+ super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
94
+
generation_utils.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+ from collections import deque
3
+ from queue import Queue
4
+ import copy
5
+
6
+
7
+ class History:
8
+
9
+ def __init__(self, tokenizer, history):
10
+ '''
11
+ init from a list of dict
12
+ '''
13
+ # use deque to meet some special situation
14
+ self.input_history = deque()
15
+ self.tokenizer = tokenizer
16
+ if history:
17
+ self._transfer_from_list(history)
18
+
19
+ def _transfer_from_list(self, history):
20
+ for message in history:
21
+ content = message.get("content")
22
+ # the token result may not be equal to the result model gen
23
+ message.update(self.tokenizer(content))
24
+ self.input_history.append(message)
25
+
26
+ def append(self, message):
27
+ content = message.get("content")
28
+ if "input_ids" not in message or "attention_mask" not in message:
29
+ message.update(self.tokenizer(content))
30
+ self.input_history.append(message)
31
+
32
+ def append_left(self, message):
33
+ content = message.get("content")
34
+ if "input_ids" not in message or "attention_mask" not in message:
35
+ message.update(self.tokenizer(content))
36
+ self.input_history.appendleft(message)
37
+
38
+ def pop(self):
39
+ x = self.input_history.pop()
40
+ return x
41
+
42
+ def pop_left(self):
43
+ x = self.input_history.popleft()
44
+ return x
45
+
46
+ def update(self, message):
47
+ self.input_history.pop()
48
+ self.append(message)
49
+
50
+ def __len__(self):
51
+ return self.input_history.__len__()
52
+
53
+ def __str__(self):
54
+ return self.input_history.__str__()
55
+
56
+ def __copy__(self):
57
+ new_instance = type(self)(self.tokenizer, [])
58
+ new_instance.input_history = copy.copy(self.input_history)
59
+ return new_instance
60
+
61
+ def __deepcopy__(self, memodict={}):
62
+ new_instance = type(self)(self.tokenizer, [])
63
+ new_instance.input_history = copy.deepcopy(self.input_history)
64
+ return new_instance
65
+
66
+
67
+ class TelechatIterTextStreamer:
68
+ """
69
+ With reference to the TextIterStreamers in transformers, we have rewritten this class
70
+ """
71
+
72
+ def __init__(
73
+ self, tokenizer, history: History = None, skip_prompt: bool = False, timeout: Optional[float] = None,
74
+ **decode_kwargs
75
+ ):
76
+
77
+ self.tokenizer = tokenizer
78
+ self.history = history
79
+ self.skip_prompt = skip_prompt
80
+ self.timeout = timeout
81
+ self.decode_kwargs = decode_kwargs
82
+
83
+ self.text_queue = Queue()
84
+ self.cache_time = 0
85
+ self.text_until = ""
86
+ self.token_until = []
87
+ self.stop_signal = None
88
+ self.next_tokens_are_prompt = True
89
+
90
+ self.history.append({"role": "bot", "content": self.text_until})
91
+
92
+ def put(self, value):
93
+ """
94
+ put printable text into queue
95
+ """
96
+ if len(value.shape) > 1 and value.shape[0] > 1:
97
+ raise ValueError("TextStreamer only supports batch size 1")
98
+ elif len(value.shape) > 1:
99
+ value = value[0]
100
+
101
+ if self.skip_prompt and self.next_tokens_are_prompt:
102
+ self.next_tokens_are_prompt = False
103
+ return
104
+
105
+ if value[-1] == self.tokenizer.eos_token_id:
106
+ return
107
+
108
+ # there may be some smart way to decode.
109
+ self.token_until.extend(value.tolist())
110
+ text = self.tokenizer.decode(self.token_until, **self.decode_kwargs)
111
+
112
+
113
+ if self._is_printable(text) or self.cache_time >= 6:
114
+ output_text = text[len(self.text_until):]
115
+ self.text_until = text
116
+
117
+ else:
118
+ self.cache_time+=1
119
+ return
120
+
121
+ self.on_finalized_text(output_text)
122
+
123
+ def end(self):
124
+ """Flushes any remaining cache and prints a newline to stdout."""
125
+ # Flush the cache, if it exists
126
+ text = self.tokenizer.decode(self.token_until, **self.decode_kwargs)
127
+ output_text = text[len(self.text_until):]
128
+ self.text_until = text
129
+ self.on_finalized_text(output_text, stream_end=True)
130
+ self.clear_cache()
131
+
132
+ def clear_cache(self):
133
+ self.cache_time = 0
134
+ self.token_until = []
135
+ self.text_until = ""
136
+ self.history = None
137
+ self.next_tokens_are_prompt = True
138
+
139
+ def on_finalized_text(self, text: str, stream_end: bool = False):
140
+ """Put the text tuple in the queue."""
141
+ self.history.update({"role": "bot", "content": self.text_until, "input_ids": self.token_until,
142
+ "attention_mask": [1] * len(self.token_until)})
143
+ self.text_queue.put((text, self.history), timeout=self.timeout)
144
+ if stream_end:
145
+ self.text_queue.put((self.stop_signal, self.history), timeout=self.timeout)
146
+
147
+ @staticmethod
148
+ def _is_printable(cp):
149
+ """Checks whether tokens can be decoded or not"""
150
+ if "�" in cp:
151
+ return False
152
+ return True
153
+
154
+ def __iter__(self):
155
+ return self
156
+
157
+ def __next__(self):
158
+ value_now, history_until = self.text_queue.get(timeout=self.timeout)
159
+ if value_now == self.stop_signal:
160
+ raise StopIteration()
161
+ else:
162
+ return value_now, history_until
modeling_telechat2.py ADDED
@@ -0,0 +1,863 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 HuggingFace Inc. team and BigScience workshop.
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
+ # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
17
+
18
+ # Copyright (c) 2021 EleutherAI
19
+ # This file is based on code by the authors denoted below and has been modified from its original version.
20
+ #
21
+ # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
22
+ #
23
+ # Licensed under the Apache License, Version 2.0 (the "License");
24
+ # you may not use this file except in compliance with the License.
25
+ # You may obtain a copy of the License at
26
+ #
27
+ # http://www.apache.org/licenses/LICENSE-2.0
28
+ #
29
+ # Unless required by applicable law or agreed to in writing, software
30
+ # distributed under the License is distributed on an "AS IS" BASIS,
31
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
32
+ # See the License for the specific language governing permissions and
33
+ # limitations under the License.
34
+
35
+
36
+ """PyTorch TELECHAT model."""
37
+
38
+ import warnings
39
+ from typing import Optional, Tuple, Union, List, Dict
40
+ from threading import Thread
41
+
42
+ import torch
43
+ import math
44
+ import copy
45
+ from torch import nn
46
+ import torch.utils.checkpoint
47
+ from torch.nn import functional as F
48
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, LayerNorm, MSELoss
49
+ from transformers.modeling_outputs import (
50
+ BaseModelOutputWithPastAndCrossAttentions,
51
+ CausalLMOutputWithCrossAttentions
52
+ )
53
+ from transformers.modeling_utils import PreTrainedModel
54
+ from transformers.utils import logging
55
+ from transformers import GenerationConfig
56
+
57
+ from .configuration_telechat2 import Telechat2Config
58
+
59
+
60
+ logger = logging.get_logger(__name__)
61
+
62
+ _CHECKPOINT_FOR_DOC = "telechat"
63
+ _CONFIG_FOR_DOC = "Telechat2Config"
64
+
65
+ TELECHAT_PRETRAINED_MODEL_ARCHIVE_LIST = []
66
+
67
+ try:
68
+ from einops import rearrange
69
+ except ImportError:
70
+ rearrange = None
71
+
72
+ is_flash_attn_available = False
73
+ try:
74
+ from flash_attn.flash_attn_interface import flash_attn_unpadded_func
75
+ is_flash_attn_available = True
76
+ except ImportError:
77
+ try:
78
+ from flash_attn.flash_attn_interface import flash_attn_varlen_func as flash_attn_unpadded_func
79
+ is_flash_attn_available = True
80
+ except ImportError:
81
+ flash_attn_unpadded_func = None
82
+
83
+
84
+ class RotaryEmbedding(torch.nn.Module):
85
+ # Extracted from: https://github.com/EleutherAI/gpt-neox
86
+ def __init__(self, dim, config, base=1000000, precision=torch.half):
87
+ super().__init__()
88
+ self.config = config
89
+ self.dim = dim
90
+ self.base = base
91
+ self.inv_freq = 1. / (base ** (torch.arange(0, dim, 2).float().half() / dim))
92
+ self.max_seq_len_cached = None
93
+ self.cos_cached = None
94
+ self.sin_cached = None
95
+ self.precision = precision
96
+
97
+ def get_mscale(self, scale=1):
98
+ if scale <= 1:
99
+ return 1.0
100
+ return 0.1 * math.log(scale) + 1.0
101
+
102
+ def get_ntk_alpha(self, true_seq_len):
103
+ context_value = math.log(true_seq_len / self.config.base_seqlen, 2) + 1
104
+ # ntk_alpha = 2 ** context_value - 1
105
+ ntk_alpha = 2 ** math.ceil(context_value) - 1
106
+ ntk_alpha = max(ntk_alpha, 1)
107
+ return ntk_alpha
108
+
109
+ def forward(self, x, seq_dim=0, seq_len=None):
110
+ if seq_len is None:
111
+ seq_len = x.shape[seq_dim]
112
+ seq_len = max(seq_len, self.config.training_seqlen)
113
+ ntk_alpha = self.get_ntk_alpha(seq_len)
114
+ self.mscale = float(self.get_mscale(seq_len / self.config.training_seqlen))
115
+ if True:
116
+ base = self.base * ntk_alpha ** (self.dim / (self.dim - 2))
117
+ self.inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2, device=x.device).float() / self.dim))
118
+ self.max_seq_len_cached = seq_len
119
+ t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
120
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
121
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
122
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
123
+ if x.dtype == torch.bfloat16:
124
+ emb = emb.float()
125
+ # [sx, 1 (b * np), hn]
126
+ self.cos_cached = self.mscale * emb.cos()[:, None, :].half()
127
+ self.sin_cached = self.mscale * emb.sin()[:, None, :].half()
128
+ if x.dtype == torch.bfloat16:
129
+ self.cos_cached = self.cos_cached.bfloat16()
130
+ self.sin_cached = self.sin_cached.bfloat16()
131
+ return self.cos_cached[:seq_len, ...], self.sin_cached[:seq_len, ...]
132
+
133
+
134
+ # rotary pos emb helpers:
135
+ def rotate_half(x):
136
+ x1, x2 = x[..., :x.shape[-1] // 2], x[..., x.shape[-1] // 2:]
137
+ return torch.cat((-x2, x1), dim=x1.ndim - 1) # dim=-1 triggers a bug in earlier torch versions
138
+
139
+
140
+ def apply_rotary_pos_emb_torch(q, k, cos, sin, offset: int = 0): # jitting fails with bf16
141
+ cos, sin = cos[offset:q.shape[0] + offset, ...], sin[offset:q.shape[0] + offset, ...]
142
+ return (q * cos) + (rotate_half(q) * sin), (k * cos) + (rotate_half(k) * sin)
143
+
144
+
145
+ class MixedFusedRMSNorm(nn.Module):
146
+ # Extracted from https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py
147
+ def __init__(self, hidden_size, eps=1e-6):
148
+ super().__init__()
149
+ self.weight = nn.Parameter(torch.ones(hidden_size))
150
+ self.variance_epsilon = eps
151
+
152
+ def forward(self, hidden_states):
153
+ input_dtype = hidden_states.dtype
154
+ hidden_states = hidden_states.to(torch.float32)
155
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
156
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
157
+ return self.weight * hidden_states.to(input_dtype)
158
+
159
+
160
+ class FlashSelfAttention(torch.nn.Module):
161
+ # Extracted from https://github.com/microsoft/Megatron-DeepSpeed/blob/main/megatron/model/transformer.py
162
+ """Implement the scaled dot product attention with softmax.
163
+ Arguments
164
+ ---------
165
+ softmax_scale: The temperature to use for the softmax attention.
166
+ (default: 1/sqrt(d_keys) where d_keys is computed at
167
+ runtime)
168
+ attention_dropout: The dropout rate to apply to the attention
169
+ (default: 0.0)
170
+ """
171
+
172
+ def __init__(self, causal=False, softmax_scale=None, attention_dropout=0.0,
173
+ device=None, dtype=None):
174
+ super().__init__()
175
+ # assert flash_attn_unpadded_func is not None, ('Please install FlashAttention first, '
176
+ # 'e.g., with pip install flash-attn')
177
+ assert rearrange is not None, 'Please install einops first, e.g., with pip install einops'
178
+ self.causal = causal
179
+ self.softmax_scale = softmax_scale
180
+ self.dropout_p = attention_dropout
181
+
182
+ def forward(self, q, k, v):
183
+ """Implements the multihead softmax attention.
184
+ Arguments
185
+ ---------
186
+ q, k, v: The tensor containing the query, key, and value. (B, S, H, D)
187
+ """
188
+ assert all((i.dtype in [torch.float16, torch.bfloat16] for i in (q, k, v)))
189
+ assert all((i.is_cuda for i in (q, k, v)))
190
+
191
+ batch_size, seqlen_q = q.shape[0], q.shape[1]
192
+ seqlen_k = k.shape[1]
193
+
194
+ q, k, v = [rearrange(x, 'b s ... -> (b s) ...') for x in [q, k, v]]
195
+ cu_seqlens_q = torch.arange(0, (batch_size + 1) * seqlen_q, step=seqlen_q, dtype=torch.int32,
196
+ device=q.device)
197
+ # self.training = False
198
+ if self.training:
199
+ # during training q,k,v always have same seqlen
200
+ assert seqlen_k == seqlen_q
201
+
202
+ is_causal = self.causal
203
+ cu_seqlens_k = cu_seqlens_q
204
+ dropout_p = self.dropout_p
205
+ else:
206
+ # turn off FA causal mask after first inference autoregressive iteration
207
+ # only on first autoregressive step q,k,v have same seqlen
208
+ is_causal = seqlen_q == seqlen_k
209
+ cu_seqlens_k = torch.arange(0, (batch_size + 1) * seqlen_k, step=seqlen_k, dtype=torch.int32,
210
+ device=q.device)
211
+ dropout_p = 0
212
+
213
+ output = flash_attn_unpadded_func(
214
+ q, k, v, cu_seqlens_q, cu_seqlens_k, seqlen_q, seqlen_k,
215
+ dropout_p=dropout_p,
216
+ softmax_scale=self.softmax_scale, causal=is_causal
217
+ )
218
+
219
+ output = rearrange(output, '(b s) ... -> b s ...', b=batch_size)
220
+ return output
221
+
222
+
223
+ def _make_causal_mask(
224
+ input_ids_shape: torch.Size, device: torch.device, past_key_values_length: int
225
+ ) -> torch.BoolTensor:
226
+ """
227
+ Make causal mask used for self-attention.
228
+ """
229
+ batch_size, target_length = input_ids_shape
230
+ mask = torch.empty((target_length, target_length + past_key_values_length), dtype=torch.bool, device=device)
231
+ # ONNX doesn't support `torch.Tensor.triu` properly, thus we use this workaround
232
+ seq_ids = torch.arange(target_length, device=device)
233
+ mask[:, past_key_values_length:] = seq_ids[:, None] < seq_ids[None, :]
234
+
235
+ if past_key_values_length > 0:
236
+ mask[:, :past_key_values_length] = False
237
+
238
+ expanded_mask = mask[None, None, :, :].expand(batch_size, 1, target_length, target_length + past_key_values_length)
239
+ return expanded_mask
240
+
241
+
242
+ def _expand_mask(mask: torch.Tensor, tgt_length: int) -> torch.BoolTensor:
243
+ """
244
+ Expands attention_mask from `[batch_size, src_length]` to `[batch_size, 1, tgt_length, src_length]`.
245
+ """
246
+ batch_size, src_length = mask.shape
247
+ tgt_length = tgt_length if tgt_length is not None else src_length
248
+
249
+ expanded_mask = ~(mask[:, None, None, :].to(torch.bool))
250
+ return expanded_mask.expand(batch_size, 1, tgt_length, src_length)
251
+
252
+
253
+ def dropout_add(x: torch.Tensor, residual: torch.Tensor, prob: float, training: bool) -> torch.Tensor:
254
+ """
255
+ Dropout add function
256
+
257
+ Args:
258
+ x (`torch.tensor`, *required*):
259
+ input tensor
260
+ residual (`torch.tensor`, *required*):
261
+ residual tensor
262
+ prob (`float`, *required*):
263
+ dropout probability
264
+ training (`bool`, *required*):
265
+ training mode
266
+ """
267
+ out = F.dropout(x, p=prob, training=training)
268
+ out = residual + out
269
+ return out
270
+
271
+
272
+ def telechat_gelu_forward(x: torch.Tensor) -> torch.Tensor:
273
+ """
274
+ Custom bias GELU function. Adapted from Megatron-DeepSpeed code. Here we use a simple implementation (inference) to
275
+ make the model jitable.
276
+
277
+ Args:
278
+ x (`torch.tensor`, *required*):
279
+ input hidden states
280
+ """
281
+ return x * 0.5 * (1.0 + torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x)))
282
+
283
+
284
+ def telechat_gelu_back(g: torch.Tensor, x: torch.Tensor) -> torch.Tensor:
285
+ """
286
+ gradient of tanh approximation of gelu gradient of actual gelu is: 0.5 * (1. + torch.erf(x * 0.70710678)) +
287
+ 0.3989423 * x * torch.exp(-0.5 * x * x)
288
+
289
+ Args:
290
+ g (`torch.tensor`, *required*):
291
+ gradient output tensor
292
+ x (`torch.tensor`, *required*):
293
+ input tensor
294
+ """
295
+ x = x[0] # x is a tuple of 1 element, needs to unpack it first
296
+ tanh_out = torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x))
297
+ # sqrt(2/pi) * 3 * 0.044715 -> 0.1070322243
298
+ ff = 0.5 * x * ((1 - tanh_out * tanh_out) * (0.79788456 + 0.1070322243 * x * x)) + 0.5 * (1 + tanh_out)
299
+ return ff * g
300
+
301
+
302
+ class GeLUFunction(torch.autograd.Function):
303
+ @staticmethod
304
+ def forward(ctx, input: torch.Tensor) -> torch.Tensor:
305
+ ctx.save_for_backward(input)
306
+ return telechat_gelu_forward(input)
307
+
308
+ @staticmethod
309
+ def backward(ctx, grad_output: torch.Tensor) -> torch.Tensor:
310
+ input = ctx.saved_tensors
311
+ tmp = telechat_gelu_back(grad_output, input)
312
+ return tmp
313
+
314
+
315
+ class TelechatGelu(nn.Module):
316
+ """
317
+ TelechatBiasGelu wrapper function that make use of the simple function on inference mode to make the model
318
+ torchscriptable and use the autograd function in training mode to get the accurate results of the gradients Partly
319
+ copied from Megatron-DeepSpeed code and adapted for our needs
320
+
321
+ See here why autograd functions are not torchscriptable: https://github.com/pytorch/pytorch/issues/22329
322
+ """
323
+
324
+ def __init__(self):
325
+ super().__init__()
326
+
327
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
328
+ if self.training:
329
+ return GeLUFunction.apply(x)
330
+ else:
331
+ return telechat_gelu_forward(x)
332
+
333
+
334
+ class TelechatAttention(nn.Module):
335
+ def __init__(self, config: Telechat2Config, layer_idx):
336
+ super().__init__()
337
+ self.kv_cache = None
338
+ self.layer_idx = layer_idx
339
+
340
+ self.hidden_size = config.hidden_size
341
+ self.num_heads = config.n_head
342
+ self.head_dim = self.hidden_size // self.num_heads
343
+ self.split_size = self.hidden_size
344
+ self.hidden_dropout = config.hidden_dropout
345
+ self.config = config
346
+
347
+ if self.head_dim * self.num_heads != self.hidden_size:
348
+ raise ValueError(
349
+ f"`hidden_size` must be divisible by num_heads (got `hidden_size`: {self.hidden_size} and `num_heads`:"
350
+ f" {self.num_heads})."
351
+ )
352
+
353
+ # Layer-wise attention scaling
354
+ self.inv_norm_factor = 1.0 / math.sqrt(self.head_dim)
355
+ self.beta = 1.0
356
+
357
+ self.num_key_value_heads = config.num_key_value_heads if config.num_key_value_heads else self.num_heads
358
+ self.kv_projection_size = self.head_dim * self.num_key_value_heads
359
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
360
+ self.query = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
361
+ self.key_value = nn.Linear(self.hidden_size, self.kv_projection_size * 2, bias=False)
362
+ self.dense = nn.Linear(self.hidden_size, self.hidden_size)
363
+ self.attention_dropout = nn.Dropout(config.attention_dropout)
364
+ self.rotary_emb = RotaryEmbedding(self.head_dim, config=config)
365
+
366
+ self.core_attention_flash = None
367
+ self.use_flash_attn = False
368
+ if self.config.flash_attn:
369
+ if not is_flash_attn_available:
370
+ logger.warning(
371
+ '`flash_attn` was set to True, but FlashAttention is not supported.',
372
+ ' Please install FlashAttention first,',
373
+ ' e.g., with `pip install flash-attn`.'
374
+ )
375
+ else:
376
+ self.core_attention_flash = FlashSelfAttention(
377
+ causal=True, attention_dropout=config.attention_dropout
378
+ )
379
+ self.use_flash_attn = True
380
+
381
+ self.last_key_layer = None
382
+ # logn_list = [math.log(i, 4096) if i > 4096 else 1 for i in range(1, 32768)]
383
+ # self.logn_tensor = torch.tensor(logn_list)[None, :, None, None].half().cuda()
384
+
385
+ def repeat_kv(self, hidden_states, n_rep):
386
+ slen, batch, num_key_value_heads_per_partition, head_dim = hidden_states.shape
387
+ if n_rep == 1:
388
+ return hidden_states
389
+ hidden_states = hidden_states[:, :, :, None, :].expand(slen, batch, num_key_value_heads_per_partition, n_rep,
390
+ head_dim)
391
+ return hidden_states.reshape(slen, batch, num_key_value_heads_per_partition * n_rep, head_dim)
392
+
393
+ def split_tensor_along_last_dim(self,
394
+ tensor: torch.Tensor,
395
+ num_partitions: int,
396
+ contiguous_split_chunks: bool = False,
397
+ ):
398
+
399
+ # Get the size and dimension.
400
+ last_dim = tensor.dim() - 1
401
+ last_dim_size = tensor.size()[last_dim] // num_partitions
402
+ # Split.
403
+ tensor_list = torch.split(tensor, last_dim_size, dim=last_dim)
404
+ # Note: torch.split does not create contiguous tensors by default.
405
+ if contiguous_split_chunks:
406
+ return tuple(chunk.contiguous() for chunk in tensor_list)
407
+
408
+ return tensor_list
409
+
410
+ def _merge_heads(self, x: torch.Tensor) -> torch.Tensor:
411
+ batch_size_and_num_heads, seq_length, _ = x.shape
412
+ batch_size = batch_size_and_num_heads // self.num_heads
413
+ x = x.view(batch_size, self.num_heads, seq_length, self.head_dim)
414
+ x = x.permute(0, 2, 1, 3)
415
+ return x.reshape(batch_size, seq_length, self.num_heads * self.head_dim)
416
+
417
+ def forward(
418
+ self,
419
+ hidden_states: torch.Tensor,
420
+ residual: torch.Tensor,
421
+ attention_mask: torch.Tensor,
422
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
423
+ use_cache: bool = False,
424
+ output_attentions: bool = False,
425
+ ):
426
+ hidden_states = hidden_states.transpose(1, 0)
427
+ query_layer = self.query(hidden_states)
428
+ new_tensor_shape = query_layer.size()[:-1] + \
429
+ (self.num_heads,
430
+ self.head_dim)
431
+ query_layer = query_layer.view(*new_tensor_shape)
432
+
433
+ mixed_kv_layer = self.key_value(hidden_states)
434
+ new_tensor_shape = mixed_kv_layer.size()[:-1] + \
435
+ (self.num_key_value_heads,
436
+ 2 * self.head_dim)
437
+ mixed_kv_layer = mixed_kv_layer.view(*new_tensor_shape)
438
+ (key_layer, value_layer) = self.split_tensor_along_last_dim(mixed_kv_layer, 2)
439
+
440
+ output_size = (query_layer.size(1),
441
+ query_layer.size(2),
442
+ query_layer.size(0),
443
+ key_layer.size(0),
444
+ key_layer.size(2)
445
+ )
446
+
447
+ query_layer = query_layer.view(output_size[2], output_size[0] * output_size[1], -1)
448
+ key_layer = key_layer.view(output_size[3], output_size[0] * output_size[4], -1)
449
+
450
+ apply_rotary_fn = apply_rotary_pos_emb_torch
451
+
452
+ seq_len = key_layer.shape[0]
453
+ offset = 0
454
+
455
+ if use_cache and layer_past != None:
456
+ past_key, past_value = layer_past
457
+ offset = past_key.shape[0]
458
+ seq_len += offset
459
+
460
+ cos, sin = self.rotary_emb(value_layer, seq_len=seq_len)
461
+
462
+ query_layer, key_layer = apply_rotary_fn(query_layer, key_layer, cos, sin, offset=offset)
463
+ if use_cache:
464
+ if layer_past != None:
465
+ past_key, past_value = layer_past
466
+ key_layer = torch.cat((past_key, key_layer[-1, ...].unsqueeze(0)), dim=0)
467
+ value_layer = torch.cat((past_value, value_layer[-1, ...].unsqueeze(0)), dim=0)
468
+ layer_past = key_layer, value_layer
469
+
470
+ s_value, bz, kv_head, dim = value_layer.shape
471
+ s_key = key_layer.shape[0]
472
+ s_query = query_layer.shape[0]
473
+ q_head = output_size[1]
474
+
475
+ query_layer = query_layer.reshape((s_query, bz, q_head, dim))
476
+ key_layer = key_layer.reshape((s_key, bz, kv_head, dim))
477
+
478
+ key_layer = self.repeat_kv(key_layer, self.num_key_value_groups)
479
+ value_layer = self.repeat_kv(value_layer, self.num_key_value_groups)
480
+
481
+ if self.use_flash_attn:
482
+ q, k, v = [rearrange(x, 's b ... -> b s ...').contiguous() for x in
483
+ (query_layer, key_layer, value_layer)]
484
+ context_layer = self.core_attention_flash(q, k, v)
485
+ context_layer = rearrange(context_layer, 'b s h d -> b s (h d)').contiguous()
486
+ else:
487
+ ##[sq, b, np, hn] -> [sq, b * np, hn]
488
+ query_layer = query_layer.reshape(s_query, bz * self.num_heads, dim)
489
+ # [sk, b, np, hn] -> [sk, b * np, hn]
490
+ key_layer = key_layer.reshape(s_key, bz * self.num_heads, dim)
491
+ matmul_result = self.inv_norm_factor * torch.einsum('bik,bkj->bij', query_layer.transpose(0, 1),
492
+ key_layer.transpose(0, 1).transpose(1, 2))
493
+
494
+ attention_scores = matmul_result.view(bz, self.num_heads, s_query, s_key)
495
+
496
+ input_dtype = attention_scores.dtype
497
+ if input_dtype == torch.float16:
498
+ attention_scores = attention_scores.to(torch.float)
499
+ attn_weights = torch.masked_fill(attention_scores, attention_mask, torch.finfo(attention_scores.dtype).min)
500
+ attention_probs = F.softmax(attn_weights, dim=-1).to(input_dtype) ##dtype = torch.float32
501
+ attention_probs = self.attention_dropout(attention_probs)
502
+ attention_probs_reshaped = attention_probs.view(bz * self.num_heads, s_query, s_key)
503
+
504
+ value_layer = value_layer.reshape(s_key, bz * self.num_heads, dim)
505
+ context_layer = torch.bmm(attention_probs_reshaped, value_layer.transpose(0, 1))
506
+ context_layer = self._merge_heads(context_layer)
507
+ output_tensor = self.dense(context_layer)
508
+
509
+ output_tensor = dropout_add(output_tensor, residual, self.hidden_dropout, self.training)
510
+ present = None
511
+ outputs = (output_tensor, present)
512
+ if output_attentions:
513
+ outputs += (attention_probs,)
514
+
515
+ return output_tensor, layer_past
516
+
517
+
518
+ class TelechatMLP(nn.Module):
519
+ def __init__(self, config: Telechat2Config):
520
+ super().__init__()
521
+ hidden_size = config.hidden_size
522
+ self.gate_proj = nn.Linear(hidden_size, config.ffn_hidden_size, bias=False)
523
+ self.up_proj = nn.Linear(hidden_size, config.ffn_hidden_size, bias=False)
524
+ self.down_proj = nn.Linear(config.ffn_hidden_size, hidden_size, bias=True)
525
+ self.hidden_dropout = config.hidden_dropout
526
+
527
+ def forward(self, hidden_states: torch.Tensor, residual: torch.Tensor) -> torch.Tensor:
528
+ intermediate_output = self.down_proj(F.silu(self.gate_proj(hidden_states)) * self.up_proj(hidden_states))
529
+ output = dropout_add(intermediate_output, residual, self.hidden_dropout, self.training)
530
+ return output
531
+
532
+
533
+ class TelechatBlock(nn.Module):
534
+ def __init__(self, config: Telechat2Config, layer_idx):
535
+ super().__init__()
536
+ hidden_size = config.hidden_size
537
+
538
+ self.input_layernorm = MixedFusedRMSNorm(hidden_size, eps=config.layer_norm_epsilon)
539
+ self.num_heads = config.n_head
540
+ self.layer_idx = layer_idx
541
+ self.self_attention = TelechatAttention(config, layer_idx)
542
+ self.post_attention_layernorm = MixedFusedRMSNorm(hidden_size, eps=config.layer_norm_epsilon)
543
+
544
+ self.mlp = TelechatMLP(config)
545
+
546
+ self.apply_residual_connection_post_layernorm = config.apply_residual_connection_post_layernorm
547
+ self.hidden_dropout = config.hidden_dropout
548
+
549
+ def forward(
550
+ self,
551
+ hidden_states: torch.Tensor,
552
+ attention_mask: torch.Tensor,
553
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
554
+ use_cache: bool = False,
555
+ output_attentions: bool = False,
556
+ ):
557
+ layernorm_output = self.input_layernorm(hidden_states)
558
+ if self.apply_residual_connection_post_layernorm:
559
+ residual = layernorm_output
560
+ else:
561
+ residual = hidden_states
562
+
563
+ attn_outputs = self.self_attention(
564
+ layernorm_output,
565
+ residual,
566
+ layer_past=layer_past,
567
+ attention_mask=attention_mask,
568
+ use_cache=use_cache,
569
+ output_attentions=output_attentions,
570
+ )
571
+
572
+ attention_output = attn_outputs[0]
573
+ outputs = attn_outputs[1:]
574
+ layernorm_output = self.post_attention_layernorm(attention_output)
575
+
576
+ if self.apply_residual_connection_post_layernorm:
577
+ residual = layernorm_output
578
+ else:
579
+ residual = attention_output
580
+ output = self.mlp(layernorm_output, residual)
581
+
582
+ if use_cache:
583
+ outputs = (output,) + outputs
584
+ else:
585
+ outputs = (output,) + outputs[1:]
586
+
587
+ return outputs
588
+
589
+
590
+ class Telechat2PreTrainedModel(PreTrainedModel):
591
+ config_class = Telechat2Config
592
+ base_model_prefix = "transformer"
593
+ supports_gradient_checkpointing = True
594
+ _no_split_modules = ["TelechatBlock"]
595
+ _skip_keys_device_placement = "past_key_values"
596
+
597
+ def __init__(self, *inputs, **kwargs):
598
+ super().__init__(*inputs, **kwargs)
599
+
600
+ def _init_weights(self, module: nn.Module):
601
+ """Initialize the weights."""
602
+ if isinstance(module, nn.Linear):
603
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
604
+ if module.bias is not None:
605
+ module.bias.data.zero_()
606
+
607
+ elif isinstance(module, nn.Embedding):
608
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
609
+ if module.padding_idx is not None:
610
+ module.weight.data[module.padding_idx].zero_()
611
+
612
+ elif isinstance(module, LayerNorm):
613
+ module.bias.data.zero_()
614
+ module.weight.data.fill_(1.0)
615
+
616
+
617
+ class Telechat2Model(Telechat2PreTrainedModel):
618
+ def __init__(self, config: Telechat2Config):
619
+ super().__init__(config)
620
+
621
+ self.embed_dim = config.hidden_size
622
+ self.num_heads = config.n_head
623
+ self.config = config
624
+ self.word_embeddings = nn.Embedding(config.vocab_size, self.embed_dim)
625
+ if self.config.embed_layernorm:
626
+ self.word_embeddings_layernorm = MixedFusedRMSNorm(self.embed_dim, eps=config.layer_norm_epsilon)
627
+
628
+ self.h = nn.ModuleList([TelechatBlock(config, _) for _ in range(config.num_hidden_layers)])
629
+ self.ln_f = MixedFusedRMSNorm(self.embed_dim, eps=config.layer_norm_epsilon)
630
+ self.gradient_checkpointing = True
631
+ self.post_init()
632
+
633
+ def get_input_embeddings(self):
634
+ return self.word_embeddings
635
+
636
+ def _prepare_attn_mask(
637
+ self, attention_mask: torch.Tensor, input_shape: Tuple[int, int], past_key_values_length: int
638
+ ) -> torch.BoolTensor:
639
+ combined_attention_mask = None
640
+ device = attention_mask.device
641
+ _, src_length = input_shape
642
+
643
+ if src_length > 1:
644
+ combined_attention_mask = _make_causal_mask(
645
+ input_shape, device=device, past_key_values_length=past_key_values_length
646
+ )
647
+ expanded_attn_mask = _expand_mask(attention_mask, tgt_length=src_length)
648
+ combined_attention_mask = (
649
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask | combined_attention_mask
650
+ )
651
+
652
+ return combined_attention_mask
653
+
654
+ def set_input_embeddings(self, new_embeddings: torch.Tensor):
655
+ self.word_embeddings = new_embeddings
656
+
657
+ def forward(
658
+ self,
659
+ input_ids: Optional[torch.LongTensor] = None,
660
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
661
+ attention_mask: Optional[torch.Tensor] = None,
662
+ inputs_embeds: Optional[torch.LongTensor] = None,
663
+ use_cache: Optional[bool] = None,
664
+ output_attentions: Optional[bool] = None,
665
+ output_hidden_states: Optional[bool] = None,
666
+ return_dict: Optional[bool] = None,
667
+ **deprecated_arguments,
668
+ ) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPastAndCrossAttentions]:
669
+
670
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
671
+ output_hidden_states = (
672
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
673
+ )
674
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
675
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
676
+
677
+ if input_ids is not None:
678
+ batch_size, seq_length = input_ids.shape
679
+ elif inputs_embeds is not None:
680
+ batch_size, seq_length, _ = inputs_embeds.shape
681
+
682
+ if past_key_values is None:
683
+ past_key_values = tuple([None] * len(self.h))
684
+ # input_ids = torch.load("Megatron-LM-0624-3B/tensors/input_ids.pt").to(input_ids.device)
685
+ if inputs_embeds is None:
686
+ inputs_embeds = self.word_embeddings(input_ids)
687
+ hidden_states = inputs_embeds
688
+ # print(f"[INFO_Telechat]: inputs_embeds={inputs_embeds}")
689
+ if self.config.embed_layernorm:
690
+ hidden_states = self.word_embeddings_layernorm(inputs_embeds)
691
+
692
+ presents = () if use_cache else None
693
+ all_self_attentions = () if output_attentions else None
694
+ all_hidden_states = () if output_hidden_states else None
695
+
696
+ if self.gradient_checkpointing and self.training:
697
+ if use_cache:
698
+ use_cache = False
699
+
700
+ seq_length_with_past = seq_length
701
+ past_key_values_length = 0
702
+ if past_key_values[0] is not None:
703
+ past_key_values_length = past_key_values[0][0].shape[2]
704
+ seq_length_with_past = seq_length_with_past + past_key_values_length
705
+ if attention_mask is None:
706
+ attention_mask = torch.ones((batch_size, seq_length_with_past), device=hidden_states.device)
707
+ else:
708
+ attention_mask = attention_mask.to(hidden_states.device)
709
+ causal_mask = self._prepare_attn_mask(
710
+ attention_mask,
711
+ input_shape=(batch_size, seq_length),
712
+ past_key_values_length=past_key_values_length,
713
+ )
714
+
715
+ # print(f"[INFO_Telechat]: word_embeddings_layernorm={hidden_states}")
716
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
717
+ if output_hidden_states:
718
+ all_hidden_states = all_hidden_states + (hidden_states,)
719
+
720
+ if self.gradient_checkpointing and self.training:
721
+
722
+ def create_custom_forward(module):
723
+ def custom_forward(*inputs):
724
+ # None for past_key_value
725
+ return module(*inputs, use_cache=use_cache, output_attentions=output_attentions)
726
+
727
+ return custom_forward
728
+
729
+ outputs = torch.utils.checkpoint.checkpoint(
730
+ create_custom_forward(block),
731
+ hidden_states,
732
+ causal_mask,
733
+ layer_past,
734
+ )
735
+ else:
736
+ outputs = block(
737
+ hidden_states,
738
+ layer_past=layer_past,
739
+ attention_mask=causal_mask,
740
+ use_cache=use_cache,
741
+ output_attentions=output_attentions,
742
+ )
743
+
744
+ # print(f"[INFO_Telechat]: outputs{i}={outputs}")
745
+ hidden_states = outputs[0]
746
+ if use_cache is True:
747
+ presents = presents + (outputs[1],)
748
+
749
+ if output_attentions:
750
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
751
+ hidden_states = self.ln_f(hidden_states)
752
+ # print(f"[INFO_Telechat]: hidden_states={hidden_states}")
753
+ # ref = torch.load("Megatron-LM-0624-3B/tensors/final_layernorm.pt")
754
+ # print(hidden_states.squeeze()[2048:])
755
+ # print(ref.squeeze())
756
+ # print(torch.max(hidden_states.squeeze()[2048:] - ref.squeeze().to(hidden_states.device)))
757
+ # exit()
758
+ # print(ref.shape,hidden_states.shape)
759
+ # print(hidden_states)
760
+ # exit()
761
+ if output_hidden_states:
762
+ all_hidden_states = all_hidden_states + (hidden_states,)
763
+ if not return_dict:
764
+ return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
765
+ return BaseModelOutputWithPastAndCrossAttentions(
766
+ last_hidden_state=hidden_states,
767
+ past_key_values=presents,
768
+ hidden_states=all_hidden_states,
769
+ attentions=all_self_attentions,
770
+ )
771
+
772
+
773
+ class Telechat2ForCausalLM(Telechat2PreTrainedModel):
774
+ # _tied_weights_keys = ["lm_head.weight"]
775
+ _keys_to_ignore_on_load_missing = [r"lm_head.weight"]
776
+
777
+ def __init__(self, config: Telechat2Config):
778
+ super().__init__(config)
779
+ self.transformer = Telechat2Model(config)
780
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
781
+ self.post_init()
782
+
783
+ def get_output_embeddings(self):
784
+ return self.lm_head
785
+
786
+ def set_output_embeddings(self, new_embeddings: torch.Tensor):
787
+ self.lm_head = new_embeddings
788
+
789
+ def prepare_inputs_for_generation(
790
+ self,
791
+ input_ids: torch.LongTensor,
792
+ past_key_values: Optional[torch.Tensor] = None,
793
+ attention_mask: Optional[torch.Tensor] = None,
794
+ inputs_embeds: Optional[torch.Tensor] = None,
795
+ **kwargs,
796
+ ) -> dict:
797
+ if past_key_values:
798
+ input_ids = input_ids[:, -1].unsqueeze(-1)
799
+ if inputs_embeds is not None and past_key_values is None:
800
+ model_inputs = {"inputs_embeds": inputs_embeds}
801
+ else:
802
+ model_inputs = {"input_ids": input_ids}
803
+
804
+ model_inputs.update(
805
+ {
806
+ "past_key_values": past_key_values,
807
+ "use_cache": kwargs.get("use_cache"),
808
+ "attention_mask": attention_mask,
809
+ }
810
+ )
811
+ return model_inputs
812
+
813
+ def forward(
814
+ self,
815
+ input_ids: Optional[torch.LongTensor] = None,
816
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
817
+ attention_mask: Optional[torch.Tensor] = None,
818
+ inputs_embeds: Optional[torch.Tensor] = None,
819
+ labels: Optional[torch.Tensor] = None,
820
+ use_cache: Optional[bool] = None,
821
+ output_attentions: Optional[bool] = None,
822
+ output_hidden_states: Optional[bool] = None,
823
+ return_dict: Optional[bool] = None,
824
+ **deprecated_arguments,
825
+ ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
826
+
827
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
828
+
829
+ transformer_outputs = self.transformer(
830
+ input_ids,
831
+ past_key_values=past_key_values,
832
+ attention_mask=attention_mask,
833
+ inputs_embeds=inputs_embeds,
834
+ use_cache=use_cache,
835
+ output_attentions=output_attentions,
836
+ output_hidden_states=output_hidden_states,
837
+ return_dict=return_dict,
838
+ )
839
+ hidden_states = transformer_outputs[0]
840
+ lm_logits = self.lm_head(hidden_states)
841
+
842
+ loss = None
843
+ if labels is not None:
844
+ labels = labels.to(lm_logits.device)
845
+ shift_logits = lm_logits[..., :-1, :].contiguous()
846
+ shift_labels = labels[..., 1:].contiguous()
847
+ batch_size, seq_length, vocab_size = shift_logits.shape
848
+ loss_fct = CrossEntropyLoss()
849
+ loss = loss_fct(
850
+ shift_logits.view(batch_size * seq_length, vocab_size), shift_labels.view(batch_size * seq_length)
851
+ )
852
+
853
+ if not return_dict:
854
+ output = (lm_logits,) + transformer_outputs[1:]
855
+ return ((loss,) + output) if loss is not None else output
856
+
857
+ return CausalLMOutputWithCrossAttentions(
858
+ loss=loss,
859
+ logits=lm_logits,
860
+ past_key_values=transformer_outputs.past_key_values,
861
+ hidden_states=transformer_outputs.hidden_states,
862
+ attentions=transformer_outputs.attentions,
863
+ )
tokenization_telechat2.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from shutil import copyfile
3
+ from typing import Any, Dict, List, Optional, Tuple
4
+ import sentencepiece as spm
5
+ from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
6
+ from transformers.utils import logging
7
+
8
+ logger = logging.get_logger(__name__)
9
+
10
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
11
+
12
+ # TODO: when we get download url from huggingface, refresh the map
13
+ PRETRAINED_VOCAB_FILES_MAP = {
14
+ "vocab_file": {},
15
+ "tokenizer_file": {},
16
+ }
17
+
18
+
19
+ class Telechat2Tokenizer(PreTrainedTokenizer):
20
+ vocab_files_names = VOCAB_FILES_NAMES
21
+ pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
22
+ model_input_names = ["input_ids", "attention_mask"]
23
+
24
+ def __init__(
25
+ self,
26
+ vocab_file,
27
+ unk_token="<unk>",
28
+ bos_token="<_start>",
29
+ eos_token="<_end>",
30
+ pad_token="<_pad>",
31
+ sp_model_kwargs: Optional[Dict[str, Any]] = None,
32
+ add_bos_token=True,
33
+ add_eos_token=False,
34
+ clean_up_tokenization_spaces=False,
35
+ **kwargs,
36
+ ):
37
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
38
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
39
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
40
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
41
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
42
+ self.sp_model.Load(vocab_file)
43
+ super().__init__(
44
+ bos_token=bos_token,
45
+ eos_token=eos_token,
46
+ pad_token=pad_token,
47
+ add_bos_token=add_bos_token,
48
+ add_eos_token=add_eos_token,
49
+ sp_model_kwargs=self.sp_model_kwargs,
50
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
51
+ **kwargs,
52
+ )
53
+ self.vocab_file = vocab_file
54
+ self.add_bos_token = add_bos_token
55
+ self.add_eos_token = add_eos_token
56
+
57
+ def __getstate__(self):
58
+ state = self.__dict__.copy()
59
+ state["sp_model"] = None
60
+ return state
61
+
62
+ def __setstate__(self, d):
63
+ self.__dict__ = d
64
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
65
+ self.sp_model.Load(self.vocab_file)
66
+
67
+ @property
68
+ def vocab_size(self):
69
+ """Returns vocab size"""
70
+ return self.sp_model.get_piece_size()
71
+
72
+ def get_vocab(self):
73
+ """Returns vocab as a dict"""
74
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
75
+ vocab.update(self.added_tokens_encoder)
76
+ return vocab
77
+
78
+ @property
79
+ def vocab(self):
80
+ return self.get_vocab()
81
+
82
+ def _tokenize(self, text):
83
+ """Returns a tokenized string."""
84
+ return self.sp_model.encode(text, out_type=str)
85
+
86
+ def _convert_token_to_id(self, token):
87
+ """Converts a token (str) in an id using the vocab."""
88
+ return self.sp_model.piece_to_id(token)
89
+
90
+ def _convert_id_to_token(self, index):
91
+ """Converts an index (integer) in a token (str) using the vocab."""
92
+ token = self.sp_model.IdToPiece(index)
93
+ return token
94
+
95
+ def convert_tokens_to_string(self, tokens):
96
+ """Converts a sequence of tokens (string) in a single string."""
97
+ current_sub_tokens = []
98
+ out_string = ""
99
+ # prev_is_special = False
100
+ for i, token in enumerate(tokens):
101
+ # make sure that special tokens are not decoded using sentencepiece model
102
+ if token in self.all_special_tokens:
103
+ # if not prev_is_special and i != 0:
104
+ # out_string += " "
105
+ out_string += self.sp_model.decode(current_sub_tokens) + token
106
+ # prev_is_special = True
107
+ current_sub_tokens = []
108
+ else:
109
+ current_sub_tokens.append(token)
110
+ # prev_is_special = False
111
+ out_string += self.sp_model.decode(current_sub_tokens)
112
+ return out_string
113
+
114
+ def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
115
+ """
116
+ Save the vocabulary and special tokens file to a directory.
117
+
118
+ Args:
119
+ save_directory (`str`):
120
+ The directory in which to save the vocabulary.
121
+
122
+ Returns:
123
+ `Tuple(str)`: Paths to the files saved.
124
+ """
125
+ if not os.path.isdir(save_directory):
126
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
127
+ return
128
+ out_vocab_file = os.path.join(
129
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
130
+ )
131
+
132
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
133
+ copyfile(self.vocab_file, out_vocab_file)
134
+ elif not os.path.isfile(self.vocab_file):
135
+ with open(out_vocab_file, "wb") as fi:
136
+ content_spiece_model = self.sp_model.serialized_model_proto()
137
+ fi.write(content_spiece_model)
138
+
139
+ return (out_vocab_file,)
140
+
141
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
142
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
143
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
144
+
145
+ output = bos_token_id + token_ids_0 + eos_token_id
146
+
147
+ if token_ids_1 is not None:
148
+ output = output + bos_token_id + token_ids_1 + eos_token_id
149
+
150
+ return output
151
+
152
+ def get_special_tokens_mask(
153
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None,
154
+ already_has_special_tokens: bool = False
155
+ ) -> List[int]:
156
+ """
157
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
158
+ special tokens using the tokenizer `prepare_for_model` method.
159
+
160
+ Args:
161
+ token_ids_0 (`List[int]`):
162
+ List of IDs.
163
+ token_ids_1 (`List[int]`, *optional*):
164
+ Optional second list of IDs for sequence pairs.
165
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
166
+ Whether or not the token list is already formatted with special tokens for the model.
167
+
168
+ Returns:
169
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
170
+ """
171
+ if already_has_special_tokens:
172
+ return super().get_special_tokens_mask(
173
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
174
+ )
175
+
176
+ bos_token_id = [1] if self.add_bos_token else []
177
+ eos_token_id = [1] if self.add_eos_token else []
178
+
179
+ if token_ids_1 is None:
180
+ return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
181
+ return (
182
+ bos_token_id
183
+ + ([0] * len(token_ids_0))
184
+ + eos_token_id
185
+ + bos_token_id
186
+ + ([0] * len(token_ids_1))
187
+ + eos_token_id
188
+ )
189
+
190
+ def create_token_type_ids_from_sequences(
191
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
192
+ ) -> List[int]:
193
+ """
194
+ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
195
+ sequence pair mask has the following format:
196
+
197
+ ```
198
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
199
+ | first sequence | second sequence |
200
+ ```
201
+
202
+ if token_ids_1 is None, only returns the first portion of the mask (0s).
203
+
204
+ Args:
205
+ token_ids_0 (`List[int]`):
206
+ List of ids.
207
+ token_ids_1 (`List[int]`, *optional*):
208
+ Optional second list of IDs for sequence pairs.
209
+
210
+ Returns:
211
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
212
+ """
213
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
214
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
215
+
216
+ output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
217
+
218
+ if token_ids_1 is not None:
219
+ output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
220
+
221
+ return output