guanwenyu1995 commited on
Commit
33d53a0
·
verified ·
1 Parent(s): ef1e3f1

Upload folder using huggingface_hub

Browse files
config.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "openbmb/CPM-2B",
3
+ "architectures": [
4
+ "LlamaForCausalLM"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_llama.LlamaConfig",
8
+ "AutoModel": "modeling_llama.LlamaForCausalLM",
9
+ "AutoModelForCausalLM": "modeling_llama.LlamaForCausalLM"
10
+ },
11
+ "bos_token_id": 1,
12
+ "eos_token_id": [2,73440],
13
+ "pad_token_id": 2,
14
+ "hidden_act": "silu",
15
+ "hidden_size": 2560,
16
+ "initializer_range": 0.1,
17
+ "intermediate_size": 10240,
18
+ "head_dim": 128,
19
+ "max_position_embeddings": 32768,
20
+ "model_type": "llama",
21
+ "num_attention_heads": 32,
22
+ "num_hidden_layers": 32,
23
+ "num_key_value_heads": 2,
24
+ "rms_norm_eps": 1e-06,
25
+ "rope_scaling": {
26
+ "factor": 1.0,
27
+ "rope_type": "longrope",
28
+ "long_factor": [0.9977997200264581, 1.014658295992452, 1.0349680404997148, 1.059429246056193, 1.0888815016813513, 1.1243301355211495, 1.166977103606075, 1.2182568066927284, 1.2798772354275727, 1.3538666751582975, 1.4426259039919596, 1.5489853358570191, 1.6762658237220625, 1.8283407612492941, 2.0096956085876183, 2.225478927469756, 2.481536379650452, 2.784415934557119, 3.1413289096347365, 3.560047844772632, 4.048719380066383, 4.615569542115128, 5.2684819496549835, 6.014438591970396, 6.858830049237097, 7.804668263503327, 8.851768731513417, 9.99600492938444, 11.228766118181639, 12.536757560834843, 13.902257701387796, 15.303885189125953, 16.717837610115794, 18.119465097853947, 19.484965238406907, 20.792956681060105, 22.02571786985731, 23.16995406772833, 24.217054535738416, 25.16289275000465, 26.007284207271347, 26.753240849586767, 27.40615325712662, 27.973003419175363, 28.461674954469114, 28.880393889607006, 29.237306864684626, 29.540186419591297, 29.79624387177199, 30.01202719065413, 30.193382037992453, 30.34545697551969, 30.47273746338473, 30.579096895249787, 30.66785612408345, 30.741845563814174, 30.80346599254902, 30.85474569563567, 30.897392663720595, 30.932841297560394, 30.962293553185553, 30.986754758742034, 31.007064503249293, 31.02392307921529],
29
+ "short_factor": [0.9977997200264581, 1.014658295992452, 1.0349680404997148, 1.059429246056193, 1.0888815016813513, 1.1243301355211495, 1.166977103606075, 1.2182568066927284, 1.2798772354275727, 1.3538666751582975, 1.4426259039919596, 1.5489853358570191, 1.6762658237220625, 1.8283407612492941, 2.0096956085876183, 2.225478927469756, 2.481536379650452, 2.784415934557119, 3.1413289096347365, 3.560047844772632, 4.048719380066383, 4.615569542115128, 5.2684819496549835, 6.014438591970396, 6.858830049237097, 7.804668263503327, 8.851768731513417, 9.99600492938444, 11.228766118181639, 12.536757560834843, 13.902257701387796, 15.303885189125953, 16.717837610115794, 18.119465097853947, 19.484965238406907, 20.792956681060105, 22.02571786985731, 23.16995406772833, 24.217054535738416, 25.16289275000465, 26.007284207271347, 26.753240849586767, 27.40615325712662, 27.973003419175363, 28.461674954469114, 28.880393889607006, 29.237306864684626, 29.540186419591297, 29.79624387177199, 30.01202719065413, 30.193382037992453, 30.34545697551969, 30.47273746338473, 30.579096895249787, 30.66785612408345, 30.741845563814174, 30.80346599254902, 30.85474569563567, 30.897392663720595, 30.932841297560394, 30.962293553185553, 30.986754758742034, 31.007064503249293, 31.02392307921529],
30
+ "original_max_position_embeddings": 32768
31
+ },
32
+ "torch_dtype": "bfloat16",
33
+ "transformers_version": "4.36.0",
34
+ "use_cache": true,
35
+ "vocab_size": 73448
36
+ }
configuration_llama.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """LLaMA model configuration"""
21
+
22
+ from transformers.configuration_utils import PretrainedConfig
23
+ from transformers.modeling_rope_utils import rope_config_validation
24
+
25
+
26
+ class LlamaConfig(PretrainedConfig):
27
+ r"""
28
+ This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA
29
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
30
+ defaults will yield a similar configuration to that of the LLaMA-7B.
31
+ e.g. [meta-llama/Llama-2-7b-hf](https://huggingface.co/meta-llama/Llama-2-7b-hf)
32
+
33
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
34
+ documentation from [`PretrainedConfig`] for more information.
35
+
36
+
37
+ Args:
38
+ vocab_size (`int`, *optional*, defaults to 32000):
39
+ Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
40
+ `inputs_ids` passed when calling [`LlamaModel`]
41
+ hidden_size (`int`, *optional*, defaults to 4096):
42
+ Dimension of the hidden representations.
43
+ intermediate_size (`int`, *optional*, defaults to 11008):
44
+ Dimension of the MLP representations.
45
+ num_hidden_layers (`int`, *optional*, defaults to 32):
46
+ Number of hidden layers in the Transformer decoder.
47
+ num_attention_heads (`int`, *optional*, defaults to 32):
48
+ Number of attention heads for each attention layer in the Transformer decoder.
49
+ num_key_value_heads (`int`, *optional*):
50
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
51
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
52
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
53
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
54
+ by meanpooling all the original heads within that group. For more details, check out [this
55
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
56
+ `num_attention_heads`.
57
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
58
+ The non-linear activation function (function or string) in the decoder.
59
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
60
+ The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens,
61
+ Llama 2 up to 4096, CodeLlama up to 16384.
62
+ initializer_range (`float`, *optional*, defaults to 0.02):
63
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
64
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
65
+ The epsilon used by the rms normalization layers.
66
+ use_cache (`bool`, *optional*, defaults to `True`):
67
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
68
+ relevant if `config.is_decoder=True`.
69
+ pad_token_id (`int`, *optional*):
70
+ Padding token id.
71
+ bos_token_id (`int`, *optional*, defaults to 1):
72
+ Beginning of stream token id.
73
+ eos_token_id (`int`, *optional*, defaults to 2):
74
+ End of stream token id.
75
+ pretraining_tp (`int`, *optional*, defaults to 1):
76
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
77
+ document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to
78
+ understand more about it. This value is necessary to ensure exact reproducibility of the pretraining
79
+ results. Please refer to [this issue](https://github.com/pytorch/pytorch/issues/76232).
80
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
81
+ Whether to tie weight embeddings
82
+ rope_theta (`float`, *optional*, defaults to 10000.0):
83
+ The base period of the RoPE embeddings.
84
+ rope_scaling (`Dict`, *optional*):
85
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
86
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
87
+ accordingly.
88
+ Expected contents:
89
+ `rope_type` (`str`):
90
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
91
+ 'llama3'], with 'default' being the original RoPE implementation.
92
+ `factor` (`float`, *optional*):
93
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
94
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
95
+ original maximum pre-trained length.
96
+ `original_max_position_embeddings` (`int`, *optional*):
97
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
98
+ pretraining.
99
+ `attention_factor` (`float`, *optional*):
100
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
101
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
102
+ `factor` field to infer the suggested value.
103
+ `beta_fast` (`float`, *optional*):
104
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
105
+ ramp function. If unspecified, it defaults to 32.
106
+ `beta_slow` (`float`, *optional*):
107
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
108
+ ramp function. If unspecified, it defaults to 1.
109
+ `short_factor` (`list[float]`, *optional*):
110
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
111
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
112
+ size divided by the number of attention heads divided by 2
113
+ `long_factor` (`list[float]`, *optional*):
114
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
115
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
116
+ size divided by the number of attention heads divided by 2
117
+ `low_freq_factor` (`float`, *optional*):
118
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
119
+ `high_freq_factor` (`float`, *optional*):
120
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
121
+ attention_bias (`bool`, *optional*, defaults to `False`):
122
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
123
+ attention_dropout (`float`, *optional*, defaults to 0.0):
124
+ The dropout ratio for the attention probabilities.
125
+ mlp_bias (`bool`, *optional*, defaults to `False`):
126
+ Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
127
+ head_dim (`int`, *optional*):
128
+ The attention head dimension. If None, it will default to hidden_size // num_attention_heads
129
+
130
+ ```python
131
+ >>> from transformers import LlamaModel, LlamaConfig
132
+
133
+ >>> # Initializing a LLaMA llama-7b style configuration
134
+ >>> configuration = LlamaConfig()
135
+
136
+ >>> # Initializing a model from the llama-7b style configuration
137
+ >>> model = LlamaModel(configuration)
138
+
139
+ >>> # Accessing the model configuration
140
+ >>> configuration = model.config
141
+ ```"""
142
+
143
+ model_type = "llama"
144
+ keys_to_ignore_at_inference = ["past_key_values"]
145
+ # Default tensor parallel plan for base model `LlamaModel`
146
+ base_model_tp_plan = {
147
+ "layers.*.self_attn.q_proj": "colwise",
148
+ "layers.*.self_attn.k_proj": "colwise",
149
+ "layers.*.self_attn.v_proj": "colwise",
150
+ "layers.*.self_attn.o_proj": "rowwise",
151
+ "layers.*.mlp.gate_proj": "colwise",
152
+ "layers.*.mlp.up_proj": "colwise",
153
+ "layers.*.mlp.down_proj": "rowwise",
154
+ }
155
+ base_model_pp_plan = {
156
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
157
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
158
+ "norm": (["hidden_states"], ["hidden_states"]),
159
+ }
160
+
161
+ def __init__(
162
+ self,
163
+ vocab_size=32000,
164
+ hidden_size=4096,
165
+ intermediate_size=11008,
166
+ num_hidden_layers=32,
167
+ num_attention_heads=32,
168
+ num_key_value_heads=None,
169
+ hidden_act="silu",
170
+ max_position_embeddings=2048,
171
+ initializer_range=0.02,
172
+ rms_norm_eps=1e-6,
173
+ use_cache=True,
174
+ pad_token_id=None,
175
+ bos_token_id=1,
176
+ eos_token_id=2,
177
+ pretraining_tp=1,
178
+ tie_word_embeddings=False,
179
+ rope_theta=10000.0,
180
+ rope_scaling=None,
181
+ attention_bias=False,
182
+ attention_dropout=0.0,
183
+ mlp_bias=False,
184
+ head_dim=None,
185
+ **kwargs,
186
+ ):
187
+ self.vocab_size = vocab_size
188
+ self.max_position_embeddings = max_position_embeddings
189
+ self.hidden_size = hidden_size
190
+ self.intermediate_size = intermediate_size
191
+ self.num_hidden_layers = num_hidden_layers
192
+ self.num_attention_heads = num_attention_heads
193
+
194
+ # for backward compatibility
195
+ if num_key_value_heads is None:
196
+ num_key_value_heads = num_attention_heads
197
+
198
+ self.num_key_value_heads = num_key_value_heads
199
+ self.hidden_act = hidden_act
200
+ self.initializer_range = initializer_range
201
+ self.rms_norm_eps = rms_norm_eps
202
+ self.pretraining_tp = pretraining_tp
203
+ self.use_cache = use_cache
204
+ self.rope_theta = rope_theta
205
+ self.rope_scaling = rope_scaling
206
+ self.attention_bias = attention_bias
207
+ self.attention_dropout = attention_dropout
208
+ self.mlp_bias = mlp_bias
209
+ self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
210
+ # Validate the correctness of rotary position embeddings parameters
211
+ # BC: if there is a 'type' field, copy it it to 'rope_type'.
212
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
213
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
214
+ rope_config_validation(self)
215
+
216
+ super().__init__(
217
+ pad_token_id=pad_token_id,
218
+ bos_token_id=bos_token_id,
219
+ eos_token_id=eos_token_id,
220
+ tie_word_embeddings=tie_word_embeddings,
221
+ **kwargs,
222
+ )
223
+
224
+
225
+ __all__ = ["LlamaConfig"]
generation_config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_sample": true,
3
+ "top_p": 0.8,
4
+ "temperature": 0.8,
5
+ "bos_token_id": 1,
6
+ "eos_token_id": [2,73440],
7
+ "pad_token_id": 2
8
+ }
modeling_llama.py ADDED
@@ -0,0 +1,926 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Callable, Optional, Union
21
+
22
+ import torch
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+
26
+ from transformers.activations import ACT2FN
27
+ from transformers.cache_utils import Cache, DynamicCache
28
+ from transformers.generation import GenerationMixin
29
+ from transformers.integrations import use_kernel_forward_from_hub
30
+ from transformers.masking_utils import create_causal_mask
31
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
32
+ from transformers.modeling_layers import GradientCheckpointingLayer
33
+ from transformers.modeling_outputs import (
34
+ BaseModelOutputWithPast,
35
+ CausalLMOutputWithPast,
36
+ QuestionAnsweringModelOutput,
37
+ SequenceClassifierOutputWithPast,
38
+ TokenClassifierOutput,
39
+ )
40
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
41
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
42
+ from transformers.processing_utils import Unpack
43
+ from transformers.utils import LossKwargs, auto_docstring, can_return_tuple, logging
44
+ from .configuration_llama import LlamaConfig
45
+
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+
50
+ def get_quantizer(quant_type="none", bit=4, group_size=128):
51
+ if quant_type == "intsym":
52
+ return SteIntSymQuantizerGPTQ(bit, group_size)
53
+ elif quant_type == "ternary":
54
+ return SteTernaryQuantizer(group_size)
55
+ elif quant_type == "none":
56
+ return NoQuantizer()
57
+ else:
58
+ raise ValueError(f"Unsupported quantization type: {quant_type}")
59
+
60
+ class SteIntSymQuantizerGPTQ(nn.Module):
61
+ def __init__(self, bit=4, group_size=-1):
62
+ super().__init__()
63
+ self.bit = bit
64
+ self.group_size = group_size
65
+
66
+ def forward(self, x):
67
+ org_w_shape = x.shape
68
+
69
+ if self.group_size > 0:
70
+ assert org_w_shape[-1] % self.group_size == 0
71
+ x = x.reshape(-1, self.group_size)
72
+ elif self.group_size == -1:
73
+ assert org_w_shape[-1] % self.group_size == 0
74
+ x = x.reshape(-1, x.shape[-1])
75
+ elif self.group_size == 0:
76
+ x = x.reshape(1, -1)
77
+
78
+ assert x.dim() == 2
79
+
80
+ xmax = x.max(dim=1, keepdim=True)[0]
81
+ xmin = x.min(dim=1, keepdim=True)[0]
82
+ abs_max_val = torch.maximum(torch.abs(xmin), xmax) # 与Quantizer的xmax计算一致
83
+ scales = abs_max_val * 2 / (2 ** self.bit - 1) # 分子分母都对齐
84
+
85
+ max_int = 2 ** (self.bit - 1) - 1
86
+ min_int = - (2 ** (self.bit - 1))
87
+
88
+ assert torch.isnan(scales).sum() == 0
89
+
90
+ x_q = (torch.clamp(torch.round(x / scales), min_int, max_int)) * scales
91
+
92
+ assert torch.isnan(x_q).sum() == 0
93
+
94
+ x = x.reshape(org_w_shape)
95
+ x_q = x_q.reshape(org_w_shape)
96
+
97
+ return x + (x_q - x).detach()
98
+
99
+ class SteTernaryQuantizer(nn.Module):
100
+ def __init__(self, group_size):
101
+ super().__init__()
102
+ self.group_size = group_size
103
+
104
+ def forward(self, x):
105
+ org_w_shape = x.shape
106
+ if self.group_size > 0:
107
+ assert x.shape[-1] % self.group_size == 0
108
+ x = x.reshape(-1, self.group_size)
109
+ elif self.group_size == -1:
110
+ x = x.reshape(-1, x.shape[-1])
111
+
112
+ assert x.dim() == 2
113
+
114
+ scales = 1.0 / (x.abs().mean(dim=1, keepdim=True).clamp_(min=1e-5))
115
+ x_q = (torch.clamp(torch.round(x * scales),-1,1) / scales)
116
+
117
+ assert torch.isnan(x_q).sum() == 0
118
+
119
+ x = x.reshape(org_w_shape)
120
+ x_q = x_q.reshape(org_w_shape)
121
+
122
+ return x + (x_q - x).detach()
123
+
124
+ class NoQuantizer(nn.Module):
125
+ def __init__(self):
126
+ super().__init__()
127
+
128
+ def forward(self, x):
129
+ return x
130
+
131
+ class LinearQuantizer(nn.Linear):
132
+ def __init__(self, in_features, out_features, bias=False, quant_type="ternary", bit=4, group_size=-1):
133
+ super().__init__(in_features, out_features, bias)
134
+ self.quantizer = get_quantizer(quant_type, bit, group_size)
135
+
136
+ def forward(self, x):
137
+ weight_tensor = self.quantizer(self.weight)
138
+ x = torch.nn.functional.linear(x, weight_tensor)
139
+ if self.bias is not None:
140
+ x = x + self.bias
141
+ return x
142
+
143
+ @use_kernel_forward_from_hub("RMSNorm")
144
+ class LlamaRMSNorm(nn.Module):
145
+ def __init__(self, hidden_size, eps=1e-6):
146
+ """
147
+ LlamaRMSNorm is equivalent to T5LayerNorm
148
+ """
149
+ super().__init__()
150
+ self.weight = nn.Parameter(torch.ones(hidden_size))
151
+ self.variance_epsilon = eps
152
+
153
+ def forward(self, hidden_states):
154
+ input_dtype = hidden_states.dtype
155
+ hidden_states = hidden_states.to(torch.float32)
156
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
157
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
158
+ return self.weight * hidden_states.to(input_dtype)
159
+
160
+ def extra_repr(self):
161
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
162
+
163
+
164
+ class LlamaRotaryEmbedding(nn.Module):
165
+ def __init__(self, config: LlamaConfig, device=None):
166
+ super().__init__()
167
+ # BC: "rope_type" was originally "type"
168
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
169
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
170
+ else:
171
+ self.rope_type = "default"
172
+ self.max_seq_len_cached = config.max_position_embeddings
173
+ self.original_max_seq_len = config.max_position_embeddings
174
+
175
+ self.config = config
176
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
177
+
178
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
179
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
180
+ self.original_inv_freq = self.inv_freq
181
+
182
+ @torch.no_grad()
183
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
184
+ def forward(self, x, position_ids):
185
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
186
+ position_ids_expanded = position_ids[:, None, :].float()
187
+
188
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
189
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
190
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
191
+ emb = torch.cat((freqs, freqs), dim=-1)
192
+ cos = emb.cos() * self.attention_scaling
193
+ sin = emb.sin() * self.attention_scaling
194
+
195
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
196
+
197
+
198
+ def rotate_half(x):
199
+ """Rotates half the hidden dims of the input."""
200
+ x1 = x[..., : x.shape[-1] // 2]
201
+ x2 = x[..., x.shape[-1] // 2 :]
202
+ return torch.cat((-x2, x1), dim=-1)
203
+
204
+
205
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
206
+ """Applies Rotary Position Embedding to the query and key tensors.
207
+
208
+ Args:
209
+ q (`torch.Tensor`): The query tensor.
210
+ k (`torch.Tensor`): The key tensor.
211
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
212
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
213
+ position_ids (`torch.Tensor`, *optional*):
214
+ Deprecated and unused.
215
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
216
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
217
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
218
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
219
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
220
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
221
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
222
+ Returns:
223
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
224
+ """
225
+ cos = cos.unsqueeze(unsqueeze_dim)
226
+ sin = sin.unsqueeze(unsqueeze_dim)
227
+ q_embed = (q * cos) + (rotate_half(q) * sin)
228
+ k_embed = (k * cos) + (rotate_half(k) * sin)
229
+ return q_embed, k_embed
230
+
231
+
232
+ class LlamaMLP(nn.Module):
233
+ def __init__(self, config):
234
+ super().__init__()
235
+ self.config = config
236
+ self.hidden_size = config.hidden_size
237
+ self.intermediate_size = config.intermediate_size
238
+ self.gate_proj = LinearQuantizer(self.hidden_size, self.intermediate_size, bias=config.mlp_bias, quant_type="ternary", bit=4, group_size=-1)
239
+ self.up_proj = LinearQuantizer(self.hidden_size, self.intermediate_size, bias=config.mlp_bias, quant_type="ternary", bit=4, group_size=-1)
240
+ self.down_proj = LinearQuantizer(self.intermediate_size, self.hidden_size, bias=config.mlp_bias, quant_type="ternary", bit=4, group_size=-1)
241
+ # self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
242
+ # self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
243
+ # self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
244
+ self.act_fn = ACT2FN[config.hidden_act]
245
+
246
+ def forward(self, x):
247
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
248
+ return down_proj
249
+
250
+
251
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
252
+ """
253
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
254
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
255
+ """
256
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
257
+ if n_rep == 1:
258
+ return hidden_states
259
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
260
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
261
+
262
+
263
+ def eager_attention_forward(
264
+ module: nn.Module,
265
+ query: torch.Tensor,
266
+ key: torch.Tensor,
267
+ value: torch.Tensor,
268
+ attention_mask: Optional[torch.Tensor],
269
+ scaling: float,
270
+ dropout: float = 0.0,
271
+ **kwargs,
272
+ ):
273
+ key_states = repeat_kv(key, module.num_key_value_groups)
274
+ value_states = repeat_kv(value, module.num_key_value_groups)
275
+
276
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
277
+ if attention_mask is not None:
278
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
279
+ attn_weights = attn_weights + causal_mask
280
+
281
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
282
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
283
+ attn_output = torch.matmtes)
284
+ attn_output = attn_output.transpose(1, 2).contiguous()
285
+
286
+ return attn_output, attn_weights
287
+
288
+
289
+ class LlamaAttention(nn.Module):
290
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
291
+
292
+ def __init__(self, config: LlamaConfig, layer_idx: int):
293
+ super().__init__()
294
+ self.config = config
295
+ self.layer_idx = layer_idx
296
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
297
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
298
+ self.scaling = self.head_dim**-0.5
299
+ self.attention_dropout = config.attention_dropout
300
+ self.is_causal = True
301
+
302
+ # self.q_proj = nn.Linear(
303
+ # config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
304
+ # )
305
+ # self.k_proj = nn.Linear(
306
+ # config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
307
+ # )
308
+ # self.v_proj = nn.Linear(
309
+ # config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
310
+ # )
311
+ # self.o_proj = nn.Linear(
312
+ # config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
313
+ # )
314
+ self.q_proj = LinearQuantizer(config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias, quant_type="ternary", bit=4, group_size=-1)
315
+ self.k_proj = LinearQuantizer(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias, quant_type="ternary", bit=4, group_size=-1)
316
+ self.v_proj = LinearQuantizer(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias, quant_type="ternary", bit=4, group_size=-1)
317
+ self.o_proj = LinearQuantizer(config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias, quant_type="ternary", bit=4, group_size=-1)
318
+
319
+ def forward(
320
+ self,
321
+ hidden_states: torch.Tensor,
322
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
323
+ attention_mask: Optional[torch.Tensor],
324
+ past_key_value: Optional[Cache] = None,
325
+ cache_position: Optional[torch.LongTensor] = None,
326
+ **kwargs: Unpack[FlashAttentionKwargs],
327
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
328
+ input_shape = hidden_states.shape[:-1]
329
+ hidden_shape = (*input_shape, -1, self.head_dim)
330
+
331
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
332
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
333
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
334
+
335
+ cos, sin = position_embeddings
336
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
337
+
338
+ if past_key_value is not None:
339
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
340
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
341
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
342
+
343
+ attention_interface: Callable = eager_attention_forward
344
+ if self.config._attn_implementation != "eager":
345
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
346
+
347
+ attn_output, attn_weights = attention_interface(
348
+ self,
349
+ query_states,
350
+ key_states,
351
+ value_states,
352
+ attention_mask,
353
+ dropout=0.0 if not self.training else self.attention_dropout,
354
+ scaling=self.scaling,
355
+ **kwargs,
356
+ )
357
+
358
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
359
+ attn_output = self.o_proj(attn_output)
360
+ return attn_output, attn_weights
361
+
362
+
363
+ class LlamaDecoderLayer(GradientCheckpointingLayer):
364
+ def __init__(self, config: LlamaConfig, layer_idx: int):
365
+ super().__init__()
366
+ self.hidden_size = config.hidden_size
367
+
368
+ self.self_attn = LlamaAttention(config=config, layer_idx=layer_idx)
369
+
370
+ self.mlp = LlamaMLP(config)
371
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
372
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
373
+
374
+ def forward(
375
+ self,
376
+ hidden_states: torch.Tensor,
377
+ attention_mask: Optional[torch.Tensor] = None,
378
+ position_ids: Optional[torch.LongTensor] = None,
379
+ past_key_value: Optional[Cache] = None,
380
+ output_attentions: Optional[bool] = False,
381
+ use_cache: Optional[bool] = False,
382
+ cache_position: Optional[torch.LongTensor] = None,
383
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
384
+ **kwargs: Unpack[FlashAttentionKwargs],
385
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
386
+ residual = hidden_states
387
+ hidden_states = self.input_layernorm(hidden_states)
388
+
389
+ # Self Attention
390
+ hidden_states, self_attn_weights = self.self_attn(
391
+ hidden_states=hidden_states,
392
+ attention_mask=attention_mask,
393
+ position_ids=position_ids,
394
+ past_key_value=past_key_value,
395
+ output_attentions=output_attentions,
396
+ use_cache=use_cache,
397
+ cache_position=cache_position,
398
+ position_embeddings=position_embeddings,
399
+ **kwargs,
400
+ )
401
+ hidden_states = residual + hidden_states
402
+
403
+ # Fully Connected
404
+ residual = hidden_states
405
+ hidden_states = self.post_attention_layernorm(hidden_states)
406
+ hidden_states = self.mlp(hidden_states)
407
+ hidden_states = residual + hidden_states
408
+
409
+ outputs = (hidden_states,)
410
+ if output_attentions:
411
+ outputs += (self_attn_weights,)
412
+
413
+ return outputs
414
+
415
+
416
+ @auto_docstring
417
+ class LlamaPreTrainedModel(PreTrainedModel):
418
+ config_class = LlamaConfig
419
+ base_model_prefix = "model"
420
+ supports_gradient_checkpointing = True
421
+ _no_split_modules = ["LlamaDecoderLayer"]
422
+ _skip_keys_device_placement = ["past_key_values"]
423
+ _supports_flash_attn_3 = True
424
+ _supports_flash_attn_2 = True
425
+ _supports_sdpa = True
426
+ _supports_flex_attn = True
427
+ _supports_cache_class = True
428
+ _supports_quantized_cache = True
429
+ _supports_static_cache = True
430
+ _supports_attention_backend = True
431
+
432
+ def _init_weights(self, module):
433
+ std = self.config.initializer_range
434
+ if isinstance(module, nn.Linear):
435
+ module.weight.data.normal_(mean=0.0, std=std)
436
+ if module.bias is not None:
437
+ module.bias.data.zero_()
438
+ elif isinstance(module, nn.Embedding):
439
+ module.weight.data.normal_(mean=0.0, std=std)
440
+ if module.padding_idx is not None:
441
+ module.weight.data[module.padding_idx].zero_()
442
+ elif isinstance(module, LlamaRMSNorm):
443
+ module.weight.data.fill_(1.0)
444
+
445
+
446
+ @auto_docstring
447
+ class LlamaModel(LlamaPreTrainedModel):
448
+ def __init__(self, config: LlamaConfig):
449
+ super().__init__(config)
450
+ self.padding_idx = config.pad_token_id
451
+ self.vocab_size = config.vocab_size
452
+
453
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
454
+ self.layers = nn.ModuleList(
455
+ [LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
456
+ )
457
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
458
+ self.rotary_emb = LlamaRotaryEmbedding(config=config)
459
+ self.gradient_checkpointing = False
460
+
461
+ # Initialize weights and apply final processing
462
+ self.post_init()
463
+
464
+ def get_input_embeddings(self):
465
+ return self.embed_tokens
466
+
467
+ def set_input_embeddings(self, value):
468
+ self.embed_tokens = value
469
+
470
+ @can_return_tuple
471
+ @auto_docstring
472
+ def forward(
473
+ self,
474
+ input_ids: Optional[torch.LongTensor] = None,
475
+ attention_mask: Optional[torch.Tensor] = None,
476
+ position_ids: Optional[torch.LongTensor] = None,
477
+ past_key_values: Optional[Cache] = None,
478
+ inputs_embeds: Optional[torch.FloatTensor] = None,
479
+ use_cache: Optional[bool] = None,
480
+ output_attentions: Optional[bool] = None,
481
+ output_hidden_states: Optional[bool] = None,
482
+ cache_position: Optional[torch.LongTensor] = None,
483
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
484
+ ) -> BaseModelOutputWithPast:
485
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
486
+ output_hidden_states = (
487
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
488
+ )
489
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
490
+
491
+ if (input_ids is None) ^ (inputs_embeds is not None):
492
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
493
+
494
+ if self.gradient_checkpointing and self.training and use_cache:
495
+ logger.warning_once(
496
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
497
+ )
498
+ use_cache = False
499
+
500
+ # TODO (joao): remove this exception in v4.56 -- it exists for users that try to pass a legacy cache
501
+ if not isinstance(past_key_values, (type(None), Cache)):
502
+ raise ValueError("The `past_key_values` should be either a `Cache` object or `None`.")
503
+
504
+ if inputs_embeds is None:
505
+ inputs_embeds = self.embed_tokens(input_ids)
506
+
507
+ if use_cache and past_key_values is None:
508
+ past_key_values = DynamicCache()
509
+
510
+ if cache_position is None:
511
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
512
+ cache_position = torch.arange(
513
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
514
+ )
515
+
516
+ if position_ids is None:
517
+ position_ids = cache_position.unsqueeze(0)
518
+
519
+ causal_mask = create_causal_mask(
520
+ config=self.config,
521
+ input_embeds=inputs_embeds,
522
+ attention_mask=attention_mask,
523
+ cache_position=cache_position,
524
+ past_key_values=past_key_values,
525
+ position_ids=position_ids,
526
+ )
527
+
528
+ hidden_states = inputs_embeds
529
+
530
+ # create position embeddings to be shared across the decoder layers
531
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
532
+
533
+ # decoder layers
534
+ all_hidden_states = () if output_hidden_states else None
535
+ all_self_attns = () if output_attentions else None
536
+
537
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
538
+ if output_hidden_states:
539
+ all_hidden_states += (hidden_states,)
540
+
541
+ layer_outputs = decoder_layer(
542
+ hidden_states,
543
+ attention_mask=causal_mask,
544
+ position_ids=position_ids,
545
+ past_key_value=past_key_values,
546
+ output_attentions=output_attentions,
547
+ use_cache=use_cache,
548
+ cache_position=cache_position,
549
+ position_embeddings=position_embeddings,
550
+ **flash_attn_kwargs,
551
+ )
552
+
553
+ hidden_states = layer_outputs[0]
554
+
555
+ if output_attentions:
556
+ all_self_attns += (layer_outputs[1],)
557
+
558
+ hidden_states = self.norm(hidden_states)
559
+
560
+ # add hidden states from the last decoder layer
561
+ if output_hidden_states:
562
+ all_hidden_states += (hidden_states,)
563
+
564
+ return BaseModelOutputWithPast(
565
+ last_hidden_state=hidden_states,
566
+ past_key_values=past_key_values if use_cache else None,
567
+ hidden_states=all_hidden_states,
568
+ attentions=all_self_attns,
569
+ )
570
+
571
+
572
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
573
+
574
+
575
+ @auto_docstring
576
+ class LlamaForCausalLM(LlamaPreTrainedModel, GenerationMixin):
577
+ _tied_weights_keys = ["lm_head.weight"]
578
+ _tp_plan = {"lm_head": "colwise_rep"}
579
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
580
+
581
+ def __init__(self, config):
582
+ super().__init__(config)
583
+ self.model = LlamaModel(config)
584
+ self.vocab_size = config.vocab_size
585
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
586
+
587
+ # Initialize weights and apply final processing
588
+ self.post_init()
589
+
590
+ def get_input_embeddings(self):
591
+ return self.model.embed_tokens
592
+
593
+ def set_input_embeddings(self, value):
594
+ self.model.embed_tokens = value
595
+
596
+ def get_output_embeddings(self):
597
+ return self.lm_head
598
+
599
+ def set_output_embeddings(self, new_embeddings):
600
+ self.lm_head = new_embeddings
601
+
602
+ def set_decoder(self, decoder):
603
+ self.model = decoder
604
+
605
+ def get_decoder(self):
606
+ return self.model
607
+
608
+ @can_return_tuple
609
+ @auto_docstring
610
+ def forward(
611
+ self,
612
+ input_ids: Optional[torch.LongTensor] = None,
613
+ attention_mask: Optional[torch.Tensor] = None,
614
+ position_ids: Optional[torch.LongTensor] = None,
615
+ past_key_values: Optional[Cache] = None,
616
+ inputs_embeds: Optional[torch.FloatTensor] = None,
617
+ labels: Optional[torch.LongTensor] = None,
618
+ use_cache: Optional[bool] = None,
619
+ output_attentions: Optional[bool] = None,
620
+ output_hidden_states: Optional[bool] = None,
621
+ cache_position: Optional[torch.LongTensor] = None,
622
+ logits_to_keep: Union[int, torch.Tensor] = 0,
623
+ **kwargs: Unpack[KwargsForCausalLM],
624
+ ) -> CausalLMOutputWithPast:
625
+ r"""
626
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
627
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
628
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
629
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
630
+
631
+ Example:
632
+
633
+ ```python
634
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
635
+
636
+ >>> model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
637
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
638
+
639
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
640
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
641
+
642
+ >>> # Generate
643
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
644
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
645
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
646
+ ```"""
647
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
648
+ output_hidden_states = (
649
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
650
+ )
651
+
652
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
653
+ outputs: BaseModelOutputWithPast = self.model(
654
+ input_ids=input_ids,
655
+ attention_mask=attention_mask,
656
+ position_ids=position_ids,
657
+ past_key_values=past_key_values,
658
+ inputs_embeds=inputs_embeds,
659
+ use_cache=use_cache,
660
+ output_attentions=output_attentions,
661
+ output_hidden_states=output_hidden_states,
662
+ cache_position=cache_position,
663
+ **kwargs,
664
+ )
665
+
666
+ hidden_states = outputs.last_hidden_state
667
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
668
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
669
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
670
+
671
+ loss = None
672
+ if labels is not None:
673
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
674
+
675
+ return CausalLMOutputWithPast(
676
+ loss=loss,
677
+ logits=logits,
678
+ past_key_values=outputs.past_key_values,
679
+ hidden_states=outputs.hidden_states,
680
+ attentions=outputs.attentions,
681
+ )
682
+
683
+
684
+ @auto_docstring(
685
+ custom_intro="""
686
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
687
+
688
+ [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
689
+ (e.g. GPT-2) do.
690
+
691
+ Since it does classification on the last token, it requires to know the position of the last token. If a
692
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
693
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
694
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
695
+ each row of the batch).
696
+ """
697
+ )
698
+ class LlamaForSequenceClassification(LlamaPreTrainedModel):
699
+ def __init__(self, config):
700
+ super().__init__(config)
701
+ self.num_labels = config.num_labels
702
+ self.model = LlamaModel(config)
703
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
704
+
705
+ # Initialize weights and apply final processing
706
+ self.post_init()
707
+
708
+ def get_input_embeddings(self):
709
+ return self.model.embed_tokens
710
+
711
+ def set_input_embeddings(self, value):
712
+ self.model.embed_tokens = value
713
+
714
+ @can_return_tuple
715
+ @auto_docstring
716
+ def forward(
717
+ self,
718
+ input_ids: Optional[torch.LongTensor] = None,
719
+ attention_mask: Optional[torch.Tensor] = None,
720
+ position_ids: Optional[torch.LongTensor] = None,
721
+ past_key_values: Optional[Cache] = None,
722
+ inputs_embeds: Optional[torch.FloatTensor] = None,
723
+ labels: Optional[torch.LongTensor] = None,
724
+ use_cache: Optional[bool] = None,
725
+ output_attentions: Optional[bool] = None,
726
+ output_hidden_states: Optional[bool] = None,
727
+ ) -> SequenceClassifierOutputWithPast:
728
+ r"""
729
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
730
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
731
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
732
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
733
+ """
734
+
735
+ transformer_outputs: BaseModelOutputWithPast = self.model(
736
+ input_ids,
737
+ attention_mask=attention_mask,
738
+ position_ids=position_ids,
739
+ past_key_values=past_key_values,
740
+ inputs_embeds=inputs_embeds,
741
+ use_cache=use_cache,
742
+ output_attentions=output_attentions,
743
+ output_hidden_states=output_hidden_states,
744
+ )
745
+ hidden_states = transformer_outputs.last_hidden_state
746
+ logits = self.score(hidden_states)
747
+
748
+ if input_ids is not None:
749
+ batch_size = input_ids.shape[0]
750
+ else:
751
+ batch_size = inputs_embeds.shape[0]
752
+
753
+ if self.config.pad_token_id is None and batch_size != 1:
754
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
755
+ if self.config.pad_token_id is None:
756
+ last_non_pad_token = -1
757
+ elif input_ids is not None:
758
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
759
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
760
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
761
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
762
+ else:
763
+ last_non_pad_token = -1
764
+ logger.warning_once(
765
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
766
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
767
+ )
768
+
769
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
770
+
771
+ loss = None
772
+ if labels is not None:
773
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
774
+
775
+ return SequenceClassifierOutputWithPast(
776
+ loss=loss,
777
+ logits=pooled_logits,
778
+ past_key_values=transformer_outputs.past_key_values,
779
+ hidden_states=transformer_outputs.hidden_states,
780
+ attentions=transformer_outputs.attentions,
781
+ )
782
+
783
+
784
+ @auto_docstring
785
+ class LlamaForQuestionAnswering(LlamaPreTrainedModel):
786
+ base_model_prefix = "transformer"
787
+
788
+ # Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->Llama
789
+ def __init__(self, config):
790
+ super().__init__(config)
791
+ self.transformer = LlamaModel(config)
792
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
793
+
794
+ # Initialize weights and apply final processing
795
+ self.post_init()
796
+
797
+ def get_input_embeddings(self):
798
+ return self.transformer.embed_tokens
799
+
800
+ def set_input_embeddings(self, value):
801
+ self.transformer.embed_tokens = value
802
+
803
+ @can_return_tuple
804
+ @auto_docstring
805
+ def forward(
806
+ self,
807
+ input_ids: Optional[torch.LongTensor] = None,
808
+ attention_mask: Optional[torch.Tensor] = None,
809
+ position_ids: Optional[torch.LongTensor] = None,
810
+ past_key_values: Optional[Cache] = None,
811
+ inputs_embeds: Optional[torch.FloatTensor] = None,
812
+ start_positions: Optional[torch.LongTensor] = None,
813
+ end_positions: Optional[torch.LongTensor] = None,
814
+ output_attentions: Optional[bool] = None,
815
+ output_hidden_states: Optional[bool] = None,
816
+ **kwargs,
817
+ ) -> QuestionAnsweringModelOutput:
818
+ outputs: BaseModelOutputWithPast = self.transformer(
819
+ input_ids,
820
+ attention_mask=attention_mask,
821
+ position_ids=position_ids,
822
+ past_key_values=past_key_values,
823
+ inputs_embeds=inputs_embeds,
824
+ output_attentions=output_attentions,
825
+ output_hidden_states=output_hidden_states,
826
+ )
827
+
828
+ sequence_output = outputs.last_hidden_state
829
+
830
+ logits = self.qa_outputs(sequence_output)
831
+ start_logits, end_logits = logits.split(1, dim=-1)
832
+ start_logits = start_logits.squeeze(-1).contiguous()
833
+ end_logits = end_logits.squeeze(-1).contiguous()
834
+
835
+ loss = None
836
+ if start_positions is not None and end_positions is not None:
837
+ loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
838
+
839
+ return QuestionAnsweringModelOutput(
840
+ loss=loss,
841
+ start_logits=start_logits,
842
+ end_logits=end_logits,
843
+ hidden_states=outputs.hidden_states,
844
+ attentions=outputs.attentions,
845
+ )
846
+
847
+
848
+ @auto_docstring
849
+ class LlamaForTokenClassification(LlamaPreTrainedModel):
850
+ def __init__(self, config):
851
+ super().__init__(config)
852
+ self.num_labels = config.num_labels
853
+ self.model = LlamaModel(config)
854
+ if getattr(config, "classifier_dropout", None) is not None:
855
+ classifier_dropout = config.classifier_dropout
856
+ elif getattr(config, "hidden_dropout", None) is not None:
857
+ classifier_dropout = config.hidden_dropout
858
+ else:
859
+ classifier_dropout = 0.1
860
+ self.dropout = nn.Dropout(classifier_dropout)
861
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
862
+
863
+ # Initialize weights and apply final processing
864
+ self.post_init()
865
+
866
+ def get_input_embeddings(self):
867
+ return self.model.embed_tokens
868
+
869
+ def set_input_embeddings(self, value):
870
+ self.model.embed_tokens = value
871
+
872
+ @can_return_tuple
873
+ @auto_docstring
874
+ def forward(
875
+ self,
876
+ input_ids: Optional[torch.LongTensor] = None,
877
+ attention_mask: Optional[torch.Tensor] = None,
878
+ position_ids: Optional[torch.LongTensor] = None,
879
+ past_key_values: Optional[Cache] = None,
880
+ inputs_embeds: Optional[torch.FloatTensor] = None,
881
+ labels: Optional[torch.LongTensor] = None,
882
+ use_cache: Optional[bool] = None,
883
+ output_attentions: Optional[bool] = None,
884
+ output_hidden_states: Optional[bool] = None,
885
+ ) -> TokenClassifierOutput:
886
+ r"""
887
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
888
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
889
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
890
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
891
+ """
892
+
893
+ outputs: BaseModelOutputWithPast = self.model(
894
+ input_ids,
895
+ attention_mask=attention_mask,
896
+ position_ids=position_ids,
897
+ past_key_values=past_key_values,
898
+ inputs_embeds=inputs_embeds,
899
+ use_cache=use_cache,
900
+ output_attentions=output_attentions,
901
+ output_hidden_states=output_hidden_states,
902
+ )
903
+ sequence_output = outputs.last_hidden_state
904
+ sequence_output = self.dropout(sequence_output)
905
+ logits = self.score(sequence_output)
906
+
907
+ loss = None
908
+ if labels is not None:
909
+ loss = self.loss_function(logits, labels, self.config)
910
+
911
+ return TokenClassifierOutput(
912
+ loss=loss,
913
+ logits=logits,
914
+ hidden_states=outputs.hidden_states,
915
+ attentions=outputs.attentions,
916
+ )
917
+
918
+
919
+ __all__ = [
920
+ "LlamaForCausalLM",
921
+ "LlamaModel",
922
+ "LlamaPreTrainedModel",
923
+ "LlamaForSequenceClassification",
924
+ "LlamaForQuestionAnswering",
925
+ "LlamaForTokenClassification",
926
+ ]
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1a499ed6e84ed768e739876eda1fe919a677603027a37907f23cab0f4e122f23
3
+ size 867818482
special_tokens_map.json ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ {
4
+ "content": "<|im_end|>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false
9
+ },
10
+ {
11
+ "content": "<|im_start|>",
12
+ "lstrip": false,
13
+ "normalized": false,
14
+ "rstrip": false,
15
+ "single_word": false
16
+ },
17
+ {
18
+ "content": "<|tool_call|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ {
25
+ "content": "<|execute_start|>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ },
31
+ {
32
+ "content": "<|execute_end|>",
33
+ "lstrip": false,
34
+ "normalized": false,
35
+ "rstrip": false,
36
+ "single_word": false
37
+ },
38
+ {
39
+ "content": "<|fim_prefix|>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": false,
43
+ "single_word": false
44
+ },
45
+ {
46
+ "content": "<|fim_middle|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false
51
+ },
52
+ {
53
+ "content": "<|fim_suffix|>",
54
+ "lstrip": false,
55
+ "normalized": false,
56
+ "rstrip": false,
57
+ "single_word": false
58
+ }
59
+ ],
60
+ "bos_token": {
61
+ "content": "<s>",
62
+ "lstrip": false,
63
+ "normalized": false,
64
+ "rstrip": false,
65
+ "single_word": false
66
+ },
67
+ "eos_token": {
68
+ "content": "</s>",
69
+ "lstrip": false,
70
+ "normalized": false,
71
+ "rstrip": false,
72
+ "single_word": false
73
+ },
74
+ "unk_token": {
75
+ "content": "<unk>",
76
+ "lstrip": false,
77
+ "normalized": false,
78
+ "rstrip": false,
79
+ "single_word": false
80
+ }
81
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bb74d51116831c3bf65db812c553f94ab0c88dcf97a5bbb37e3504f6d359c530
3
+ size 1181204
tokenizer_config.json ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": false,
4
+ "added_tokens_decoder": {
5
+ "0": {
6
+ "content": "<unk>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "1": {
14
+ "content": "<s>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "2": {
22
+ "content": "</s>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "73440": {
30
+ "content": "<|im_end|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "73441": {
38
+ "content": "<|im_start|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "73442": {
46
+ "content": "<|tool_call|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "73443": {
54
+ "content": "<|execute_start|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "73444": {
62
+ "content": "<|execute_end|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "73445": {
70
+ "content": "<|fim_prefix|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "73446": {
78
+ "content": "<|fim_middle|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "73447": {
86
+ "content": "<|fim_suffix|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ }
93
+ },
94
+ "additional_special_tokens": [
95
+ "<|im_end|>",
96
+ "<|im_start|>",
97
+ "<|tool_call|>",
98
+ "<|execute_start|>",
99
+ "<|execute_end|>",
100
+ "<|fim_prefix|>",
101
+ "<|fim_middle|>",
102
+ "<|fim_suffix|>"
103
+ ],
104
+ "bos_token": "<s>",
105
+ "clean_up_tokenization_spaces": false,
106
+ "eos_token": "<|im_end|>",
107
+ "legacy": true,
108
+ "model_max_length": 1000000000000000019884624838656,
109
+ "pad_token": null,
110
+ "sp_model_kwargs": {},
111
+ "spaces_between_special_tokens": false,
112
+ "tokenizer_class": "LlamaTokenizer",
113
+ "unk_token": "<unk>",
114
+ "use_default_system_prompt": false,
115
+ "chat_template": "{% for message in messages %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}"
116
+ }